@manuscripts/track-changes-plugin 1.7.2 → 1.7.3-LEAN-2832-v3

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 (118) hide show
  1. package/dist/cjs/ChangeSet.js +155 -0
  2. package/dist/cjs/actions.js +23 -0
  3. package/dist/cjs/change-steps/diffChangeSteps.js +63 -0
  4. package/dist/cjs/change-steps/matchInserted.js +70 -0
  5. package/dist/cjs/change-steps/processChangeSteps.js +141 -0
  6. package/dist/cjs/changes/applyChanges.js +81 -0
  7. package/dist/cjs/changes/findChanges.js +72 -0
  8. package/dist/cjs/changes/fixInconsistentChanges.js +21 -0
  9. package/dist/cjs/changes/updateChangeAttrs.js +65 -0
  10. package/dist/cjs/commands.js +47 -0
  11. package/dist/cjs/compute/nodeHelpers.js +77 -0
  12. package/dist/cjs/compute/setFragmentAsInserted.js +53 -0
  13. package/dist/cjs/compute/splitSliceIntoMergedParts.js +57 -0
  14. package/dist/cjs/index.js +41 -0
  15. package/dist/cjs/mutate/deleteAndMergeSplitNodes.js +105 -0
  16. package/dist/cjs/mutate/deleteNode.js +51 -0
  17. package/dist/cjs/mutate/deleteText.js +29 -0
  18. package/dist/cjs/mutate/mergeNode.js +21 -0
  19. package/dist/cjs/mutate/mergeTrackedMarks.js +25 -0
  20. package/dist/cjs/plugin.js +118 -0
  21. package/dist/cjs/steps/trackReplaceAroundStep.js +72 -0
  22. package/dist/cjs/steps/trackReplaceStep.js +79 -0
  23. package/dist/cjs/steps/trackTransaction.js +88 -0
  24. package/dist/cjs/types/change.js +15 -0
  25. package/dist/cjs/types/pm.js +2 -0
  26. package/dist/cjs/types/step.js +2 -0
  27. package/dist/cjs/types/track.js +9 -0
  28. package/dist/cjs/utils/logger.js +43 -0
  29. package/dist/cjs/utils/track-utils.js +28 -0
  30. package/dist/cjs/utils/uuidv4.js +10 -0
  31. package/dist/es/ChangeSet.js +151 -0
  32. package/dist/es/actions.js +17 -0
  33. package/dist/es/change-steps/diffChangeSteps.js +59 -0
  34. package/dist/es/change-steps/matchInserted.js +66 -0
  35. package/dist/es/change-steps/processChangeSteps.js +114 -0
  36. package/dist/es/changes/applyChanges.js +77 -0
  37. package/dist/es/changes/findChanges.js +68 -0
  38. package/dist/es/changes/fixInconsistentChanges.js +17 -0
  39. package/dist/es/changes/updateChangeAttrs.js +60 -0
  40. package/dist/es/commands.js +39 -0
  41. package/dist/es/compute/nodeHelpers.js +67 -0
  42. package/dist/es/compute/setFragmentAsInserted.js +49 -0
  43. package/dist/es/compute/splitSliceIntoMergedParts.js +53 -0
  44. package/dist/es/index.js +7 -0
  45. package/dist/es/mutate/deleteAndMergeSplitNodes.js +78 -0
  46. package/dist/es/mutate/deleteNode.js +46 -0
  47. package/dist/es/mutate/deleteText.js +25 -0
  48. package/dist/es/mutate/mergeNode.js +17 -0
  49. package/dist/es/mutate/mergeTrackedMarks.js +21 -0
  50. package/dist/es/plugin.js +114 -0
  51. package/dist/es/steps/trackReplaceAroundStep.js +45 -0
  52. package/dist/es/steps/trackReplaceStep.js +52 -0
  53. package/dist/es/steps/trackTransaction.js +84 -0
  54. package/dist/es/types/change.js +12 -0
  55. package/dist/es/types/pm.js +1 -0
  56. package/dist/es/types/step.js +1 -0
  57. package/dist/es/types/track.js +6 -0
  58. package/dist/es/utils/logger.js +36 -0
  59. package/dist/es/utils/track-utils.js +22 -0
  60. package/dist/es/utils/uuidv4.js +6 -0
  61. package/dist/types/ChangeSet.d.ts +28 -0
  62. package/dist/{actions.d.ts → types/actions.d.ts} +27 -60
  63. package/dist/{change-steps → types/change-steps}/diffChangeSteps.d.ts +2 -2
  64. package/dist/types/change-steps/matchInserted.d.ts +3 -0
  65. package/dist/types/change-steps/processChangeSteps.d.ts +6 -0
  66. package/dist/types/changes/applyChanges.d.ts +5 -0
  67. package/dist/types/changes/findChanges.d.ts +3 -0
  68. package/dist/types/changes/fixInconsistentChanges.d.ts +4 -0
  69. package/dist/types/changes/updateChangeAttrs.d.ts +6 -0
  70. package/dist/types/commands.d.ts +8 -0
  71. package/dist/{compute → types/compute}/nodeHelpers.d.ts +13 -28
  72. package/dist/types/compute/setFragmentAsInserted.d.ts +3 -0
  73. package/dist/types/compute/splitSliceIntoMergedParts.d.ts +13 -0
  74. package/dist/types/index.d.ts +7 -0
  75. package/dist/types/mutate/deleteAndMergeSplitNodes.d.ts +13 -0
  76. package/dist/types/mutate/deleteNode.d.ts +5 -0
  77. package/dist/types/mutate/deleteText.d.ts +4 -0
  78. package/dist/types/mutate/mergeNode.d.ts +3 -0
  79. package/dist/types/mutate/mergeTrackedMarks.d.ts +3 -0
  80. package/dist/types/plugin.d.ts +4 -0
  81. package/dist/{steps → types/steps}/trackReplaceAroundStep.d.ts +5 -5
  82. package/dist/types/steps/trackReplaceStep.d.ts +6 -0
  83. package/dist/types/steps/trackTransaction.d.ts +2 -0
  84. package/dist/types/types/change.d.ts +61 -0
  85. package/dist/types/types/pm.d.ts +12 -0
  86. package/dist/types/{step.d.ts → types/step.d.ts} +38 -53
  87. package/dist/types/types/track.d.ts +30 -0
  88. package/dist/types/utils/logger.d.ts +8 -0
  89. package/dist/{utils → types/utils}/track-utils.d.ts +4 -4
  90. package/dist/types/utils/uuidv4.d.ts +1 -0
  91. package/package.json +18 -39
  92. package/LICENSE +0 -201
  93. package/dist/ChangeSet.d.ts +0 -71
  94. package/dist/change-steps/matchInserted.d.ts +0 -13
  95. package/dist/change-steps/processChangeSteps.d.ts +0 -21
  96. package/dist/changes/applyChanges.d.ts +0 -28
  97. package/dist/changes/findChanges.d.ts +0 -27
  98. package/dist/changes/fixInconsistentChanges.d.ts +0 -29
  99. package/dist/changes/updateChangeAttrs.d.ts +0 -21
  100. package/dist/commands.d.ts +0 -47
  101. package/dist/compute/setFragmentAsInserted.d.ts +0 -18
  102. package/dist/compute/splitSliceIntoMergedParts.d.ts +0 -41
  103. package/dist/index.cjs +0 -2026
  104. package/dist/index.d.ts +0 -22
  105. package/dist/index.js +0 -2013
  106. package/dist/mutate/deleteAndMergeSplitNodes.d.ts +0 -53
  107. package/dist/mutate/deleteNode.d.ts +0 -36
  108. package/dist/mutate/deleteText.d.ts +0 -33
  109. package/dist/mutate/mergeNode.d.ts +0 -25
  110. package/dist/mutate/mergeTrackedMarks.d.ts +0 -29
  111. package/dist/plugin.d.ts +0 -25
  112. package/dist/steps/trackReplaceStep.d.ts +0 -21
  113. package/dist/steps/trackTransaction.d.ts +0 -17
  114. package/dist/types/change.d.ts +0 -76
  115. package/dist/types/pm.d.ts +0 -27
  116. package/dist/types/track.d.ts +0 -45
  117. package/dist/utils/logger.d.ts +0 -27
  118. package/dist/utils/uuidv4.d.ts +0 -16
package/dist/index.js DELETED
@@ -1,2013 +0,0 @@
1
- import { NodeSelection, PluginKey, Plugin } from 'prosemirror-state';
2
- import debug from 'debug';
3
- import { liftTarget, canJoin, Mapping, ReplaceStep, ReplaceAroundStep } from 'prosemirror-transform';
4
- import { Fragment, Slice } from 'prosemirror-model';
5
-
6
- var TrackChangesAction;
7
- (function (TrackChangesAction) {
8
- TrackChangesAction["skipTrack"] = "track-changes-skip-tracking";
9
- TrackChangesAction["setUserID"] = "track-changes-set-user-id";
10
- TrackChangesAction["setPluginStatus"] = "track-changes-set-track-status";
11
- TrackChangesAction["setChangeStatuses"] = "track-changes-set-change-statuses";
12
- TrackChangesAction["refreshChanges"] = "track-changes-refresh-changes";
13
- TrackChangesAction["applyAndRemoveChanges"] = "track-changes-apply-remove-changes";
14
- TrackChangesAction["updateMetaNode"] = "track-changes-update-meta-node";
15
- })(TrackChangesAction || (TrackChangesAction = {}));
16
- /**
17
- * Gets the value of a meta field, action payload, of a defined track-changes action.
18
- * @param tr
19
- * @param action
20
- */
21
- function getAction(tr, action) {
22
- return tr.getMeta(action);
23
- }
24
- /**
25
- * Use this function to set meta keys to transactions that are consumed by the track-changes-plugin.
26
- * For example, you can skip tracking of a transaction with setAction(tr, TrackChangesAction.skipTrack, true)
27
- * @param tr
28
- * @param action
29
- * @param payload
30
- */
31
- function setAction(tr, action, payload) {
32
- return tr.setMeta(action, payload);
33
- }
34
- /**
35
- * Skip tracking for a transaction, use this with caution to avoid race-conditions or just to otherwise
36
- * omitting applying of track attributes or marks.
37
- * @param tr
38
- * @returns
39
- */
40
- const skipTracking = (tr) => setAction(tr, TrackChangesAction.skipTrack, true);
41
-
42
- /******************************************************************************
43
- Copyright (c) Microsoft Corporation.
44
-
45
- Permission to use, copy, modify, and/or distribute this software for any
46
- purpose with or without fee is hereby granted.
47
-
48
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
49
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
50
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
51
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
52
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
53
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
54
- PERFORMANCE OF THIS SOFTWARE.
55
- ***************************************************************************** */
56
-
57
- function __classPrivateFieldGet(receiver, state, kind, f) {
58
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
59
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
60
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
61
- }
62
-
63
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
64
- if (kind === "m") throw new TypeError("Private method is not writable");
65
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
66
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
67
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
68
- }
69
-
70
- /*!
71
- * © 2021 Atypon Systems LLC
72
- *
73
- * Licensed under the Apache License, Version 2.0 (the "License");
74
- * you may not use this file except in compliance with the License.
75
- * You may obtain a copy of the License at
76
- *
77
- * http://www.apache.org/licenses/LICENSE-2.0
78
- *
79
- * Unless required by applicable law or agreed to in writing, software
80
- * distributed under the License is distributed on an "AS IS" BASIS,
81
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
82
- * See the License for the specific language governing permissions and
83
- * limitations under the License.
84
- */
85
- var CHANGE_OPERATION;
86
- (function (CHANGE_OPERATION) {
87
- CHANGE_OPERATION["insert"] = "insert";
88
- CHANGE_OPERATION["delete"] = "delete";
89
- CHANGE_OPERATION["set_node_attributes"] = "set_attrs";
90
- // wrap_with_node = 'wrap_with_node',
91
- // unwrap_from_node = 'unwrap_from_node',
92
- // add_mark = 'add_mark',
93
- // remove_mark = 'remove_mark',
94
- })(CHANGE_OPERATION || (CHANGE_OPERATION = {}));
95
- var CHANGE_STATUS;
96
- (function (CHANGE_STATUS) {
97
- CHANGE_STATUS["accepted"] = "accepted";
98
- CHANGE_STATUS["rejected"] = "rejected";
99
- CHANGE_STATUS["pending"] = "pending";
100
- })(CHANGE_STATUS || (CHANGE_STATUS = {}));
101
-
102
- /*!
103
- * © 2021 Atypon Systems LLC
104
- *
105
- * Licensed under the Apache License, Version 2.0 (the "License");
106
- * you may not use this file except in compliance with the License.
107
- * You may obtain a copy of the License at
108
- *
109
- * http://www.apache.org/licenses/LICENSE-2.0
110
- *
111
- * Unless required by applicable law or agreed to in writing, software
112
- * distributed under the License is distributed on an "AS IS" BASIS,
113
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
- * See the License for the specific language governing permissions and
115
- * limitations under the License.
116
- */
117
- const logger = debug('track');
118
- const log = {
119
- info(str, obj) {
120
- if (obj) {
121
- logger(str, obj);
122
- }
123
- else {
124
- logger(str);
125
- }
126
- },
127
- warn(str, obj) {
128
- if (obj) {
129
- logger(`%c WARNING ${str}`, 'color: #f3f32c', obj);
130
- }
131
- else {
132
- logger(`%c WARNING ${str}`, 'color: #f3f32c');
133
- }
134
- },
135
- error(str, obj) {
136
- if (obj) {
137
- logger(`%c ERROR ${str}`, 'color: #ff4242', obj);
138
- }
139
- else {
140
- logger(`%c ERROR ${str}`, 'color: #ff4242');
141
- }
142
- },
143
- };
144
- /**
145
- * Sets debug logging enabled/disabled.
146
- * @param enabled
147
- */
148
- const enableDebug = (enabled) => {
149
- if (enabled) {
150
- debug.enable('track');
151
- }
152
- else {
153
- debug.disable();
154
- }
155
- };
156
-
157
- var _ChangeSet_instances, _ChangeSet_changes, _ChangeSet_isSameNodeChange, _ChangeSet_isNotPendingOrDeleted;
158
- /**
159
- * ChangeSet is a data structure to contain the tracked changes with some utility methods and computed
160
- * values to allow easier operability.
161
- */
162
- class ChangeSet {
163
- constructor(changes = []) {
164
- _ChangeSet_instances.add(this);
165
- _ChangeSet_changes.set(this, void 0);
166
- __classPrivateFieldSet(this, _ChangeSet_changes, changes, "f");
167
- }
168
- /**
169
- * List of all the valid TrackedChanges. This prevents for example changes with duplicate ids being shown
170
- * in the UI, causing errors.
171
- */
172
- get changes() {
173
- const iteratedIds = new Set();
174
- return __classPrivateFieldGet(this, _ChangeSet_changes, "f").filter((c) => {
175
- const valid = !iteratedIds.has(c.dataTracked.id) && ChangeSet.isValidDataTracked(c.dataTracked);
176
- iteratedIds.add(c.dataTracked.id);
177
- return valid;
178
- });
179
- }
180
- get invalidChanges() {
181
- return __classPrivateFieldGet(this, _ChangeSet_changes, "f").filter((c) => !this.changes.find((cc) => c.id === cc.id));
182
- }
183
- /**
184
- * List of 1-level nested changes where the top-most node change contains all the changes within its start
185
- * and end position. This is useful for showing the changes as groups in the UI.
186
- */
187
- get changeTree() {
188
- const rootNodes = [];
189
- let currentNodeChange;
190
- this.changes.forEach((c) => {
191
- if (currentNodeChange && c.from >= currentNodeChange.to) {
192
- rootNodes.push(currentNodeChange);
193
- currentNodeChange = undefined;
194
- }
195
- if (currentNodeChange &&
196
- c.from < currentNodeChange.to &&
197
- !(__classPrivateFieldGet(this, _ChangeSet_instances, "m", _ChangeSet_isSameNodeChange).call(this, currentNodeChange, c) &&
198
- __classPrivateFieldGet(this, _ChangeSet_instances, "m", _ChangeSet_isNotPendingOrDeleted).call(this, currentNodeChange))) {
199
- currentNodeChange.children.push(c);
200
- }
201
- else if (c.type === 'node-change') {
202
- currentNodeChange = { ...c, children: [] };
203
- }
204
- else {
205
- rootNodes.push(c);
206
- }
207
- });
208
- if (currentNodeChange) {
209
- rootNodes.push(currentNodeChange);
210
- }
211
- return rootNodes;
212
- }
213
- get pending() {
214
- return this.changeTree.filter((c) => c.dataTracked.status === CHANGE_STATUS.pending);
215
- }
216
- get accepted() {
217
- return this.changeTree.filter((c) => c.dataTracked.status === CHANGE_STATUS.accepted);
218
- }
219
- get rejected() {
220
- return this.changeTree.filter((c) => c.dataTracked.status === CHANGE_STATUS.rejected);
221
- }
222
- get textChanges() {
223
- return this.changes.filter((c) => c.type === 'text-change');
224
- }
225
- get nodeChanges() {
226
- return this.changes.filter((c) => c.type === 'node-change');
227
- }
228
- get nodeAttrChanges() {
229
- return this.changes.filter((c) => c.type === 'node-attr-change');
230
- }
231
- get bothNodeChanges() {
232
- return this.changes.filter((c) => c.type === 'node-change' || c.type === 'node-attr-change');
233
- }
234
- get isEmpty() {
235
- return __classPrivateFieldGet(this, _ChangeSet_changes, "f").length === 0;
236
- }
237
- /**
238
- * Used to determine whether `fixInconsistentChanges` has to be executed to replace eg duplicate ids or
239
- * changes that are missing attributes.
240
- */
241
- get hasInconsistentData() {
242
- return this.hasDuplicateIds || this.hasIncompleteAttrs;
243
- }
244
- get hasDuplicateIds() {
245
- const iterated = new Set();
246
- return __classPrivateFieldGet(this, _ChangeSet_changes, "f").some((c) => {
247
- if (iterated.has(c.id)) {
248
- return true;
249
- }
250
- iterated.add(c.id);
251
- });
252
- }
253
- get hasIncompleteAttrs() {
254
- return __classPrivateFieldGet(this, _ChangeSet_changes, "f").some((c) => !ChangeSet.isValidDataTracked(c.dataTracked));
255
- }
256
- get(id) {
257
- return __classPrivateFieldGet(this, _ChangeSet_changes, "f").find((c) => c.id === id);
258
- }
259
- getIn(ids) {
260
- return ids
261
- .map((id) => __classPrivateFieldGet(this, _ChangeSet_changes, "f").find((c) => c.id === id))
262
- .filter((c) => c !== undefined);
263
- }
264
- getNotIn(ids) {
265
- return __classPrivateFieldGet(this, _ChangeSet_changes, "f").filter((c) => ids.includes(c.id));
266
- }
267
- /**
268
- * Flattens a changeTree into a list of IDs
269
- * @param changes
270
- */
271
- static flattenTreeToIds(changes) {
272
- return changes.flatMap((c) => this.isNodeChange(c) ? [c.id, ...c.children.map((c) => c.id)] : c.id);
273
- }
274
- /**
275
- * Determines whether a change should be deleted when applying it to the document.
276
- * @param change
277
- */
278
- static shouldDeleteChange(change) {
279
- const { status, operation } = change.dataTracked;
280
- return ((operation === CHANGE_OPERATION.insert && status === CHANGE_STATUS.rejected) ||
281
- (operation === CHANGE_OPERATION.delete && status === CHANGE_STATUS.accepted));
282
- }
283
- /**
284
- * Checks whether change attributes contain all TrackedAttrs keys with non-undefined values
285
- * @param dataTracked
286
- */
287
- static isValidDataTracked(dataTracked = {}) {
288
- if ('dataTracked' in dataTracked) {
289
- log.warn('passed "dataTracked" as property to isValidTrackedAttrs()', dataTracked);
290
- }
291
- const trackedKeys = [
292
- 'id',
293
- 'authorID',
294
- 'operation',
295
- 'status',
296
- 'createdAt',
297
- 'updatedAt',
298
- ];
299
- // reviewedByID is set optional since either ProseMirror or Yjs doesn't like persisting null values inside attributes objects
300
- // So it can be either omitted completely or at least be null or string
301
- const optionalKeys = ['reviewedByID'];
302
- const entries = Object.entries(dataTracked).filter(([key, val]) => trackedKeys.includes(key));
303
- const optionalEntries = Object.entries(dataTracked).filter(([key, val]) => optionalKeys.includes(key));
304
- return (entries.length === trackedKeys.length &&
305
- entries.every(([key, val]) => trackedKeys.includes(key) && val !== undefined) &&
306
- optionalEntries.every(([key, val]) => optionalKeys.includes(key) && val !== undefined) &&
307
- (dataTracked.id || '').length > 0 // Changes created with undefined id have '' as placeholder
308
- );
309
- }
310
- static isTextChange(change) {
311
- return change.type === 'text-change';
312
- }
313
- static isNodeChange(change) {
314
- return change.type === 'node-change';
315
- }
316
- static isNodeAttrChange(change) {
317
- return change.type === 'node-attr-change';
318
- }
319
- }
320
- _ChangeSet_changes = new WeakMap(), _ChangeSet_instances = new WeakSet(), _ChangeSet_isSameNodeChange = function _ChangeSet_isSameNodeChange(currentChange, nextChange) {
321
- return currentChange.from === nextChange.from && currentChange.to === nextChange.to;
322
- }, _ChangeSet_isNotPendingOrDeleted = function _ChangeSet_isNotPendingOrDeleted(change) {
323
- return (change.dataTracked.operation !== CHANGE_OPERATION.delete &&
324
- change.dataTracked.status !== CHANGE_STATUS.pending);
325
- };
326
-
327
- /*!
328
- * © 2021 Atypon Systems LLC
329
- *
330
- * Licensed under the Apache License, Version 2.0 (the "License");
331
- * you may not use this file except in compliance with the License.
332
- * You may obtain a copy of the License at
333
- *
334
- * http://www.apache.org/licenses/LICENSE-2.0
335
- *
336
- * Unless required by applicable law or agreed to in writing, software
337
- * distributed under the License is distributed on an "AS IS" BASIS,
338
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
339
- * See the License for the specific language governing permissions and
340
- * limitations under the License.
341
- */
342
- function uuidv4() {
343
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
344
- const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
345
- return v.toString(16);
346
- });
347
- }
348
-
349
- function addTrackIdIfDoesntExist(attrs) {
350
- if (!attrs.id) {
351
- return {
352
- id: uuidv4(),
353
- ...attrs,
354
- };
355
- }
356
- return attrs;
357
- }
358
- function getTextNodeTrackedMarkData(node, schema) {
359
- if (!node || !node.isText) {
360
- return undefined;
361
- }
362
- const marksTrackedData = [];
363
- node.marks.forEach((mark) => {
364
- if (mark.type === schema.marks.tracked_insert || mark.type === schema.marks.tracked_delete) {
365
- const operation = mark.type === schema.marks.tracked_insert
366
- ? CHANGE_OPERATION.insert
367
- : CHANGE_OPERATION.delete;
368
- marksTrackedData.push({ ...mark.attrs.dataTracked, operation });
369
- }
370
- });
371
- if (marksTrackedData.length > 1) {
372
- log.warn('inline node with more than 1 of tracked marks', marksTrackedData);
373
- }
374
- return marksTrackedData[0] || undefined;
375
- }
376
- function getBlockInlineTrackedData(node) {
377
- const { dataTracked } = node.attrs;
378
- if (dataTracked && !Array.isArray(dataTracked)) {
379
- return [dataTracked];
380
- }
381
- return dataTracked;
382
- }
383
- function getNodeTrackedData(node, schema) {
384
- let tracked;
385
- if (node && !node.isText) {
386
- tracked = getBlockInlineTrackedData(node);
387
- }
388
- else if (node === null || node === void 0 ? void 0 : node.isText) {
389
- tracked = getTextNodeTrackedMarkData(node, schema);
390
- }
391
- if (tracked && !Array.isArray(tracked)) {
392
- tracked = [tracked];
393
- }
394
- return tracked;
395
- }
396
- function equalMarks(n1, n2) {
397
- return (n1.marks.length === n2.marks.length &&
398
- n1.marks.every((mark) => n1.marks.find((m) => m.type === mark.type)));
399
- }
400
- function shouldMergeTrackedAttributes(left, right) {
401
- if (!left || !right) {
402
- log.warn('passed undefined dataTracked attributes to shouldMergeTrackedAttributes', {
403
- left,
404
- right,
405
- });
406
- return false;
407
- }
408
- return (left.status === right.status &&
409
- left.operation === right.operation &&
410
- left.authorID === right.authorID);
411
- }
412
- function getMergeableMarkTrackedAttrs(node, attrs, schema) {
413
- const nodeAttrs = getTextNodeTrackedMarkData(node, schema);
414
- return nodeAttrs && shouldMergeTrackedAttributes(nodeAttrs, attrs) ? nodeAttrs : null;
415
- }
416
-
417
- /*!
418
- * © 2021 Atypon Systems LLC
419
- *
420
- * Licensed under the Apache License, Version 2.0 (the "License");
421
- * you may not use this file except in compliance with the License.
422
- * You may obtain a copy of the License at
423
- *
424
- * http://www.apache.org/licenses/LICENSE-2.0
425
- *
426
- * Unless required by applicable law or agreed to in writing, software
427
- * distributed under the License is distributed on an "AS IS" BASIS,
428
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
429
- * See the License for the specific language governing permissions and
430
- * limitations under the License.
431
- */
432
- /**
433
- * Deletes node but tries to leave its content intact by trying to unwrap it first
434
- *
435
- * Incase unwrapping doesn't work deletes the whole node.
436
- * @param node
437
- * @param pos
438
- * @param tr
439
- * @returns
440
- */
441
- function deleteNode(node, pos, tr) {
442
- var _a;
443
- const startPos = tr.doc.resolve(pos + 1);
444
- const range = startPos.blockRange(tr.doc.resolve(startPos.pos - 2 + node.nodeSize));
445
- const targetDepth = range && liftTarget(range);
446
- // Check with typeof since with prosemirror-transform pre 1.6.0 targetDepth is undefined
447
- if (range && typeof targetDepth === 'number') {
448
- return tr.lift(range, targetDepth);
449
- }
450
- const resPos = tr.doc.resolve(pos);
451
- // Block nodes can be deleted by just removing their start token which should then merge the text
452
- // content to above node's content (if there is one)
453
- // this will work just for the node after the first child
454
- const canMergeToNodeAbove = resPos.parent !== tr.doc && resPos.nodeBefore && node.isBlock && ((_a = node.firstChild) === null || _a === void 0 ? void 0 : _a.isText);
455
- if (canMergeToNodeAbove) {
456
- return tr.replaceWith(pos - 1, pos + 1, Fragment.empty);
457
- }
458
- else {
459
- // NOTE: there's an edge case where moving content is not possible but because the immediate
460
- // child, say some wrapper blockNode, is also deleted the content could be retained. TODO I guess.
461
- return tr.delete(pos, pos + node.nodeSize);
462
- }
463
- }
464
- /**
465
- * Deletes inserted block or inline node, otherwise adds `dataTracked` object with CHANGE_STATUS 'deleted'
466
- * @param node
467
- * @param pos
468
- * @param newTr
469
- * @param deleteAttrs
470
- */
471
- function deleteOrSetNodeDeleted(node, pos, newTr, deleteAttrs) {
472
- const dataTracked = getBlockInlineTrackedData(node);
473
- const inserted = dataTracked === null || dataTracked === void 0 ? void 0 : dataTracked.find((d) => d.operation === CHANGE_OPERATION.insert);
474
- const deleted = dataTracked === null || dataTracked === void 0 ? void 0 : dataTracked.find((d) => d.operation === CHANGE_OPERATION.delete);
475
- const updated = dataTracked === null || dataTracked === void 0 ? void 0 : dataTracked.find((d) => d.operation === CHANGE_OPERATION.set_node_attributes);
476
- if (inserted && inserted.authorID === deleteAttrs.authorID) {
477
- return deleteNode(node, pos, newTr);
478
- }
479
- const newDeleted = deleted
480
- ? { ...deleted, updatedAt: deleteAttrs.updatedAt }
481
- : addTrackIdIfDoesntExist(deleteAttrs);
482
- newTr.setNodeMarkup(pos, undefined, {
483
- ...node.attrs,
484
- dataTracked: updated ? [newDeleted, updated] : [newDeleted],
485
- }, node.marks);
486
- }
487
-
488
- /*!
489
- * © 2021 Atypon Systems LLC
490
- *
491
- * Licensed under the Apache License, Version 2.0 (the "License");
492
- * you may not use this file except in compliance with the License.
493
- * You may obtain a copy of the License at
494
- *
495
- * http://www.apache.org/licenses/LICENSE-2.0
496
- *
497
- * Unless required by applicable law or agreed to in writing, software
498
- * distributed under the License is distributed on an "AS IS" BASIS,
499
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
500
- * See the License for the specific language governing permissions and
501
- * limitations under the License.
502
- */
503
- /**
504
- * Deletes node but tries to leave its content intact by moving/wrapping it to a node before or after
505
- * @param node
506
- * @param pos
507
- * @param tr
508
- * @returns
509
- */
510
- function mergeNode(node, pos, tr) {
511
- var _a;
512
- if (canJoin(tr.doc, pos)) {
513
- return tr.join(pos);
514
- }
515
- else if (!tr.doc.resolve(pos).nodeBefore) {
516
- // for this case will just delete that node in `deleteNode.ts` as the join will not work
517
- return undefined;
518
- }
519
- // TODO is this the same thing as join to above?
520
- const resPos = tr.doc.resolve(pos);
521
- const canMergeToNodeAbove = (resPos.parent !== tr.doc || resPos.nodeBefore) && ((_a = node.firstChild) === null || _a === void 0 ? void 0 : _a.isText);
522
- if (canMergeToNodeAbove) {
523
- return tr.replaceWith(pos - 1, pos + 1, Fragment.empty);
524
- }
525
- return undefined;
526
- }
527
-
528
- function updateChangeAttrs(tr, change, trackedAttrs, schema) {
529
- const node = tr.doc.nodeAt(change.from);
530
- if (!node) {
531
- log.error('updateChangeAttrs: no node at the from of change ', change);
532
- return tr;
533
- }
534
- const { operation } = trackedAttrs;
535
- const oldTrackData = change.type === 'text-change' ? getTextNodeTrackedMarkData(node, schema) : getBlockInlineTrackedData(node);
536
- if (!operation) {
537
- log.warn('updateChangeAttrs: unable to determine operation of change ', change);
538
- }
539
- else if (!oldTrackData) {
540
- log.warn('updateChangeAttrs: no old dataTracked for change ', change);
541
- }
542
- if (change.type === 'text-change') {
543
- const oldMark = node.marks.find((m) => m.type === schema.marks.tracked_insert || m.type === schema.marks.tracked_delete);
544
- if (!oldMark) {
545
- log.warn('updateChangeAttrs: no track marks for a text-change ', change);
546
- return tr;
547
- }
548
- // TODO add operation based on mark type if it's undefined?
549
- tr.addMark(change.from, change.to, oldMark.type.create({ ...oldMark.attrs, dataTracked: { ...oldTrackData, ...trackedAttrs } }));
550
- }
551
- else if ((change.type === 'node-change' || change.type === 'node-attr-change') && !operation) {
552
- // Very weird edge-case if this happens
553
- tr.setNodeMarkup(change.from, undefined, { ...node.attrs, dataTracked: null }, node.marks);
554
- }
555
- else if (change.type === 'node-change' || change.type === 'node-attr-change') {
556
- const trackedDataSource = getBlockInlineTrackedData(node) || [];
557
- const targetDataTracked = trackedDataSource.find((t) => change.id === t.id);
558
- const newDataTracked = trackedDataSource.map((oldTrack) => {
559
- if (targetDataTracked) {
560
- if (oldTrack.id === targetDataTracked.id) {
561
- return { ...oldTrack, ...trackedAttrs };
562
- }
563
- return oldTrack;
564
- }
565
- if (oldTrack.operation === operation) {
566
- return { ...oldTrack, ...trackedAttrs };
567
- }
568
- return oldTrack;
569
- });
570
- tr.setNodeMarkup(change.from, undefined, { ...node.attrs, dataTracked: newDataTracked.length === 0 ? null : newDataTracked }, node.marks);
571
- }
572
- return tr;
573
- }
574
- function updateChangeChildrenAttributes(changes, tr, mapping) {
575
- changes.forEach((c) => {
576
- if (c.type === 'node-change' && !ChangeSet.shouldDeleteChange(c)) {
577
- const from = mapping.map(c.from);
578
- const node = tr.doc.nodeAt(from);
579
- if (!node) {
580
- return;
581
- }
582
- const attrs = { ...node.attrs, dataTracked: null };
583
- tr.setNodeMarkup(from, undefined, attrs, node.marks);
584
- }
585
- });
586
- }
587
-
588
- function getUpdatedDataTracked(dataTracked, changeId) {
589
- if (!dataTracked) {
590
- return null;
591
- }
592
- const newDataTracked = dataTracked.filter((c) => c.id !== changeId);
593
- return newDataTracked.length ? newDataTracked : null;
594
- }
595
- /**
596
- * Applies the accepted/rejected changes in the current document and sets them untracked
597
- *
598
- * @param tr
599
- * @param schema
600
- * @param changes
601
- * @param deleteMap
602
- */
603
- function applyAcceptedRejectedChanges(tr, schema, changes, deleteMap = new Mapping()) {
604
- const attrsChangesLog = new Map(); // map of node ids and applied change updatedAt timestamp
605
- function addAttrLog(nodeId, changeId) {
606
- const arr = attrsChangesLog.get(nodeId) || attrsChangesLog.set(nodeId, []).get(nodeId);
607
- arr.push(changeId);
608
- }
609
- changes.forEach((change) => {
610
- // Map change.from and skip those which dont need to be applied
611
- // or were already deleted by an applied block delete
612
- const { pos: from, deleted } = deleteMap.mapResult(change.from), node = tr.doc.nodeAt(from), noChangeNeeded = deleted || !ChangeSet.shouldDeleteChange(change);
613
- if (!node) {
614
- !deleted && log.warn('no node found to update for change', change);
615
- return;
616
- }
617
- if (change.dataTracked.status === CHANGE_STATUS.pending) {
618
- if (ChangeSet.isNodeAttrChange(change)) {
619
- /*
620
- Apply pending changes for attributes as well because applying accepted/rejected changes may override
621
- pending because we store the most recent change directly on the node attributes. But in case of pending attributes
622
- we don't need to remove dataTracked record. We need, however, to make sure we don't restore dataTracked records for
623
- the previously applied changes. To check for already applied changes we log them into "attrsChangesLog" Map.
624
- */
625
- const { dataTracked, ...attrs } = change.newAttrs;
626
- const changeLog = attrsChangesLog.get(node.attrs.id);
627
- const newDataTracked = changeLog && changeLog.length ? dataTracked.filter((c) => !changeLog.includes(c.id)) : dataTracked;
628
- tr.setNodeMarkup(from, undefined, { ...attrs, dataTracked: newDataTracked.length ? newDataTracked : null }, node.marks);
629
- // default is "null" for dataTracked in attrs in pm schema, so codebase generally relies on it being null when empty
630
- }
631
- return;
632
- }
633
- if (ChangeSet.isTextChange(change) && noChangeNeeded) {
634
- tr.removeMark(from, deleteMap.map(change.to), schema.marks.tracked_insert);
635
- tr.removeMark(from, deleteMap.map(change.to), schema.marks.tracked_delete);
636
- }
637
- else if (ChangeSet.isTextChange(change)) {
638
- tr.delete(from, deleteMap.map(change.to));
639
- deleteMap.appendMap(tr.steps[tr.steps.length - 1].getMap());
640
- }
641
- else if (ChangeSet.isNodeChange(change) && noChangeNeeded) {
642
- const attrs = { ...node.attrs, dataTracked: null };
643
- tr.setNodeMarkup(from, undefined, attrs, node.marks);
644
- updateChangeChildrenAttributes(change.children, tr, deleteMap);
645
- }
646
- else if (ChangeSet.isNodeChange(change)) {
647
- // Try first moving the node children to either nodeAbove, nodeBelow or its parent.
648
- // Then try unwrapping it with lift or just hacky-joining by replacing the border between
649
- // it and its parent with Fragment.empty. If none of these apply, delete the content between the change.
650
- const merged = mergeNode(node, from, tr);
651
- if (merged === undefined) {
652
- deleteNode(node, from, tr);
653
- }
654
- deleteMap.appendMap(tr.steps[tr.steps.length - 1].getMap());
655
- }
656
- else if (ChangeSet.isNodeAttrChange(change) && change.dataTracked.status === CHANGE_STATUS.accepted) {
657
- tr.setNodeMarkup(from, undefined, { ...change.newAttrs, dataTracked: getUpdatedDataTracked(node.attrs.dataTracked, change.id) }, node.marks);
658
- addAttrLog(node.attrs.id, change.dataTracked.id);
659
- }
660
- else if (ChangeSet.isNodeAttrChange(change) && change.dataTracked.status === CHANGE_STATUS.rejected) {
661
- tr.setNodeMarkup(from, undefined, { ...change.oldAttrs, dataTracked: getUpdatedDataTracked(node.attrs.dataTracked, change.id) }, node.marks);
662
- addAttrLog(node.attrs.id, change.dataTracked.id);
663
- }
664
- });
665
- return deleteMap;
666
- }
667
-
668
- /**
669
- * Finds all changes (basically text marks or node attributes) from document
670
- *
671
- * This could be possibly made more efficient by only iterating the sections of doc where changes have
672
- * been applied. This could attempted with eg findDiffStart but it might be less robust than just using
673
- * doc.descendants
674
- * @param state
675
- * @returns
676
- */
677
- function findChanges(state) {
678
- const changes = [];
679
- // Store the last iterated change to join adjacent text changes
680
- let current;
681
- state.doc.descendants((node, pos) => {
682
- const tracked = getNodeTrackedData(node, state.schema) || [];
683
- for (let i = 0; i < tracked.length; i += 1) {
684
- const dataTracked = tracked[i];
685
- const id = dataTracked.id || '';
686
- // Join adjacent text changes that have been broken up due to different marks
687
- // eg <ins><b>bold</b>norm<i>italic</i></ins> -> treated as one continuous change
688
- // Note the !equalMarks to leave changes separate incase the marks are equal to let fixInconsistentChanges to fix them
689
- if (current &&
690
- current.change.id === id &&
691
- current.node.isText &&
692
- node.isText &&
693
- !equalMarks(node, current.node)) {
694
- current.change.to = pos + node.nodeSize;
695
- // Important to update the node as the text changes might contain multiple parts where some marks equal each other
696
- current.node = node;
697
- continue;
698
- }
699
- current && changes.push(current.change);
700
- let change;
701
- if (node.isText) {
702
- change = {
703
- id,
704
- type: 'text-change',
705
- from: pos,
706
- to: pos + node.nodeSize,
707
- dataTracked,
708
- text: node.text,
709
- };
710
- }
711
- else if (dataTracked.operation === CHANGE_OPERATION.set_node_attributes) {
712
- change = {
713
- id,
714
- type: 'node-attr-change',
715
- from: pos,
716
- to: pos + node.nodeSize,
717
- dataTracked,
718
- nodeType: node.type.name,
719
- newAttrs: node.attrs,
720
- oldAttrs: dataTracked.oldAttrs,
721
- };
722
- }
723
- else {
724
- change = {
725
- id,
726
- type: 'node-change',
727
- from: pos,
728
- to: pos + node.nodeSize,
729
- dataTracked,
730
- nodeType: node.type.name,
731
- children: [],
732
- };
733
- }
734
- current = {
735
- change,
736
- node,
737
- };
738
- }
739
- if (tracked.length === 0 && current) {
740
- changes.push(current.change);
741
- current = undefined;
742
- }
743
- });
744
- current && changes.push(current.change);
745
- return new ChangeSet(changes);
746
- }
747
-
748
- /**
749
- * Iterates over a ChangeSet to check all changes have their required attributes
750
- *
751
- * This inconsistency might happen due to a bug in the track changes implementation or by a user somehow applying an empty insert/delete mark that doesn't contain proper data. Also this checks the track IDs for duplicates.
752
- * @param changeSet
753
- * @param currentUser
754
- * @param newTr
755
- * @param schema
756
- * @return docWasChanged, a boolean
757
- */
758
- function fixInconsistentChanges(changeSet, currentUserID, newTr, schema) {
759
- const iteratedIds = new Set();
760
- let changed = false;
761
- changeSet.invalidChanges.forEach((c) => {
762
- const { id, authorID, operation, reviewedByID, status, createdAt, updatedAt } = c.dataTracked;
763
- const newAttrs = {
764
- ...((!id || iteratedIds.has(id) || id.length === 0) && { id: uuidv4() }),
765
- ...(!authorID && { authorID: currentUserID }),
766
- // Dont add a default operation -> rather have updateChangeAttrs delete the track data
767
- // ...(!operation && { operation: CHANGE_OPERATION.insert }),
768
- ...(!reviewedByID && { reviewedByID: null }),
769
- ...(!status && { status: CHANGE_STATUS.pending }),
770
- ...(!createdAt && { createdAt: Date.now() }),
771
- ...(!updatedAt && { updatedAt: Date.now() }),
772
- };
773
- if (Object.keys(newAttrs).length > 0) {
774
- updateChangeAttrs(newTr, c, { ...c.dataTracked, ...newAttrs }, schema);
775
- changed = true;
776
- }
777
- iteratedIds.add(newAttrs.id || id);
778
- });
779
- return changed;
780
- }
781
-
782
- /*!
783
- * © 2021 Atypon Systems LLC
784
- *
785
- * Licensed under the Apache License, Version 2.0 (the "License");
786
- * you may not use this file except in compliance with the License.
787
- * You may obtain a copy of the License at
788
- *
789
- * http://www.apache.org/licenses/LICENSE-2.0
790
- *
791
- * Unless required by applicable law or agreed to in writing, software
792
- * distributed under the License is distributed on an "AS IS" BASIS,
793
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
794
- * See the License for the specific language governing permissions and
795
- * limitations under the License.
796
- */
797
- /**
798
- * Recurses node children and returns the merged first/last node's content and the unmerged children
799
- *
800
- * For example when merging two blockquotes:
801
- * <bq><p>old|</p></bq>...| + [<bq><p>] inserted</p><p>2nd p</p></bq> -> <bq><p>old inserted</p><p>2nd p</p></bq>
802
- * The extracted merged and unmerged content from the insertSlice are:
803
- * {
804
- * mergedNodeContent: <text> inserted</text>
805
- * unmergedContent: [<p>2nd p</p>]
806
- * }
807
- * @param node
808
- * @param currentDepth
809
- * @param depth
810
- * @param first
811
- * @returns
812
- */
813
- function getMergedNode(node, currentDepth, depth, first) {
814
- if (currentDepth === depth) {
815
- return {
816
- mergedNodeContent: node.content,
817
- unmergedContent: undefined,
818
- };
819
- }
820
- const result = [];
821
- let merged = Fragment.empty;
822
- node.content.forEach((n, _, i) => {
823
- if ((first && i === 0) || (!first && i === node.childCount - 1)) {
824
- const { mergedNodeContent, unmergedContent } = getMergedNode(n, currentDepth + 1, depth, first);
825
- merged = mergedNodeContent;
826
- if (unmergedContent) {
827
- result.push(...unmergedContent.content);
828
- }
829
- }
830
- else {
831
- result.push(n);
832
- }
833
- });
834
- return {
835
- mergedNodeContent: merged,
836
- unmergedContent: result.length > 0 ? Fragment.fromArray(result) : undefined,
837
- };
838
- }
839
- /**
840
- * Filters merged nodes from an open insertSlice to manually merge them to prevent unwanted deletions
841
- *
842
- * So instead of joining the slice by its open sides, possibly deleting previous nodes, we can push the
843
- * changed content manually inside the merged nodes.
844
- * Eg. instead of doing `|<p>asdf</p><p>|bye</p>` automatically, we extract the merged nodes first:
845
- * {
846
- * updatedSliceNodes: [<p>asdf</p>],
847
- * firstMergedNode: <p>bye</p>,
848
- * lastMergedNode: undefined,
849
- * }
850
- * @param insertSlice inserted slice
851
- */
852
- function splitSliceIntoMergedParts(insertSlice, mergeEqualSides = false) {
853
- const { openStart, openEnd, content: { firstChild, lastChild, content: nodes }, } = insertSlice;
854
- let updatedSliceNodes = nodes;
855
- const mergeSides = openStart !== openEnd || mergeEqualSides;
856
- const firstMergedNode = openStart > 0 && mergeSides && firstChild
857
- ? getMergedNode(firstChild, 1, openStart, true)
858
- : undefined;
859
- const lastMergedNode = openEnd > 0 && mergeSides && lastChild ? getMergedNode(lastChild, 1, openEnd, false) : undefined;
860
- if (firstMergedNode) {
861
- updatedSliceNodes = updatedSliceNodes.slice(1);
862
- if (firstMergedNode.unmergedContent) {
863
- updatedSliceNodes = [...firstMergedNode.unmergedContent.content, ...updatedSliceNodes];
864
- }
865
- }
866
- if (lastMergedNode) {
867
- updatedSliceNodes = updatedSliceNodes.slice(0, -1);
868
- if (lastMergedNode.unmergedContent) {
869
- updatedSliceNodes = [...updatedSliceNodes, ...lastMergedNode.unmergedContent.content];
870
- }
871
- }
872
- return {
873
- updatedSliceNodes,
874
- firstMergedNode,
875
- lastMergedNode,
876
- };
877
- }
878
-
879
- /*!
880
- * © 2021 Atypon Systems LLC
881
- *
882
- * Licensed under the Apache License, Version 2.0 (the "License");
883
- * you may not use this file except in compliance with the License.
884
- * You may obtain a copy of the License at
885
- *
886
- * http://www.apache.org/licenses/LICENSE-2.0
887
- *
888
- * Unless required by applicable law or agreed to in writing, software
889
- * distributed under the License is distributed on an "AS IS" BASIS,
890
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
891
- * See the License for the specific language governing permissions and
892
- * limitations under the License.
893
- */
894
- function markInlineNodeChange(node, newTrackAttrs, schema) {
895
- const filtered = node.marks.filter((m) => m.type !== schema.marks.tracked_insert && m.type !== schema.marks.tracked_delete);
896
- const mark = newTrackAttrs.operation === CHANGE_OPERATION.insert
897
- ? schema.marks.tracked_insert
898
- : schema.marks.tracked_delete;
899
- const createdMark = mark.create({
900
- dataTracked: addTrackIdIfDoesntExist(newTrackAttrs),
901
- });
902
- return node.mark(filtered.concat(createdMark));
903
- }
904
- /**
905
- * Iterates over fragment's content and joins pasted text with old track marks
906
- *
907
- * This is not strictly necessary but it's kinda bad UX if the inserted text is split into parts
908
- * even when it's authored by the same user.
909
- * @param content
910
- * @param newTrackAttrs
911
- * @param schema
912
- * @returns
913
- */
914
- function loopContentAndMergeText(content, newTrackAttrs, schema) {
915
- var _a;
916
- const updatedChildren = [];
917
- for (let i = 0; i < content.childCount; i += 1) {
918
- const recursed = recurseNodeContent(content.child(i), newTrackAttrs, schema);
919
- const prev = i > 0 ? updatedChildren[i - 1] : null;
920
- if ((prev === null || prev === void 0 ? void 0 : prev.isText) &&
921
- recursed.isText &&
922
- equalMarks(prev, recursed) &&
923
- ((_a = getTextNodeTrackedMarkData(prev, schema)) === null || _a === void 0 ? void 0 : _a.operation) === CHANGE_OPERATION.insert) {
924
- updatedChildren.splice(i - 1, 1, schema.text('' + prev.text + recursed.text, prev.marks));
925
- }
926
- else {
927
- updatedChildren.push(recursed);
928
- }
929
- }
930
- return updatedChildren;
931
- }
932
- function recurseNodeContent(node, newTrackAttrs, schema) {
933
- if (node.isText) {
934
- return markInlineNodeChange(node, newTrackAttrs, schema);
935
- }
936
- else if (node.isBlock || node.isInline) {
937
- const updatedChildren = loopContentAndMergeText(node.content, newTrackAttrs, schema);
938
- return node.type.create({
939
- ...node.attrs,
940
- dataTracked: [addTrackIdIfDoesntExist(newTrackAttrs)],
941
- }, Fragment.fromArray(updatedChildren), node.marks);
942
- }
943
- else {
944
- log.error(`unhandled node type: "${node.type.name}"`, node);
945
- return node;
946
- }
947
- }
948
- function setFragmentAsInserted(inserted, insertAttrs, schema) {
949
- // Recurse the content in the inserted slice and either mark it tracked_insert or set node attrs
950
- const updatedInserted = loopContentAndMergeText(inserted, insertAttrs, schema);
951
- return updatedInserted.length === 0 ? Fragment.empty : Fragment.fromArray(updatedInserted);
952
- }
953
-
954
- /*!
955
- * © 2021 Atypon Systems LLC
956
- *
957
- * Licensed under the Apache License, Version 2.0 (the "License");
958
- * you may not use this file except in compliance with the License.
959
- * You may obtain a copy of the License at
960
- *
961
- * http://www.apache.org/licenses/LICENSE-2.0
962
- *
963
- * Unless required by applicable law or agreed to in writing, software
964
- * distributed under the License is distributed on an "AS IS" BASIS,
965
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
966
- * See the License for the specific language governing permissions and
967
- * limitations under the License.
968
- */
969
- function createNewInsertAttrs(attrs) {
970
- return {
971
- ...attrs,
972
- operation: CHANGE_OPERATION.insert,
973
- };
974
- }
975
- function createNewDeleteAttrs(attrs) {
976
- return {
977
- ...attrs,
978
- operation: CHANGE_OPERATION.delete,
979
- };
980
- }
981
- function createNewUpdateAttrs(attrs, oldAttrs) {
982
- // Omit dataTracked
983
- const { dataTracked, ...restAttrs } = oldAttrs;
984
- return {
985
- ...attrs,
986
- operation: CHANGE_OPERATION.set_node_attributes,
987
- oldAttrs: JSON.parse(JSON.stringify(restAttrs)),
988
- };
989
- }
990
-
991
- /*!
992
- * © 2021 Atypon Systems LLC
993
- *
994
- * Licensed under the Apache License, Version 2.0 (the "License");
995
- * you may not use this file except in compliance with the License.
996
- * You may obtain a copy of the License at
997
- *
998
- * http://www.apache.org/licenses/LICENSE-2.0
999
- *
1000
- * Unless required by applicable law or agreed to in writing, software
1001
- * distributed under the License is distributed on an "AS IS" BASIS,
1002
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1003
- * See the License for the specific language governing permissions and
1004
- * limitations under the License.
1005
- */
1006
- /**
1007
- * Applies deletion to the doc without actually deleting nodes that have not been inserted
1008
- *
1009
- * The hairiest part of this whole library which does a fair bit of magic to split the inserted slice
1010
- * into pieces that can be inserted without deleting nodes in the doc. Basically we first split the
1011
- * inserted slice into merged pieces _if_ the slice was open on either end. Then, we iterate over the deleted
1012
- * range and see if the node in question was completely wrapped in the range (therefore fully deleted)
1013
- * or only partially deleted by the slice. In that case, we merge the content from the inserted slice
1014
- * and keep the original nodes if they do not contain insert attributes.
1015
- *
1016
- * It is definitely a messy function but so far this seems to have been the best approach to prevent
1017
- * deletion of nodes with open slices. Other option would be to allow the deletions to take place but that
1018
- * requires then inserting the deleted nodes back to the doc if their deletion should be prevented, which does
1019
- * not seem trivial either.
1020
- *
1021
- * @param from start of the deleted range
1022
- * @param to end of the deleted range
1023
- * @param gap retained content in a ReplaceAroundStep, not deleted
1024
- * @param startDoc doc before the deletion
1025
- * @param newTr the new track transaction
1026
- * @param schema ProseMirror schema
1027
- * @param deleteAttrs attributes for the dataTracked object
1028
- * @param insertSlice the inserted slice from ReplaceStep
1029
- * @returns mapping adjusted by the applied operations & modified insert slice
1030
- */
1031
- function deleteAndMergeSplitNodes(from, to, gap, startDoc, newTr, schema, trackAttrs, insertSlice) {
1032
- const steps = [];
1033
- // No deletion applied, return default values
1034
- if (from === to) {
1035
- return {
1036
- newSliceContent: insertSlice.content,
1037
- sliceWasSplit: false,
1038
- steps,
1039
- };
1040
- }
1041
- const { openStart, openEnd } = insertSlice;
1042
- const { updatedSliceNodes, firstMergedNode, lastMergedNode } = splitSliceIntoMergedParts(insertSlice, gap !== undefined);
1043
- let mergingStartSide = true;
1044
- startDoc.nodesBetween(from, to, (node, pos) => {
1045
- const nodeEnd = pos + node.nodeSize;
1046
- // So this insane boolean checks for ReplaceAroundStep gaps and whether the node should be skipped
1047
- // since the content inside gap should stay unchanged.
1048
- // All other nodes except text nodes consist of one start and end token (or just a single token for atoms).
1049
- // For them we can just check whether the start token is within the gap eg pos is 10 when gap (8, 18) to
1050
- // determine whether it should be skipped.
1051
- // For text nodes though, since they are continous, they might only partially be enclosed in the gap
1052
- // eg. pos 10 when gap is (8, 18) BUT if their nodeEnd goes past the gap's end eg nodeEnd 20 they actually
1053
- // are altered and should not be skipped.
1054
- // @TODO ATM 20.7.2022 there doesn't seem to be tests that capture this.
1055
- const wasWithinGap = gap &&
1056
- ((!node.isText && pos >= gap.start) ||
1057
- (node.isText && pos >= gap.start && nodeEnd <= gap.end));
1058
- // nodeEnd > offsetFrom -> delete touches this node
1059
- // eg (del 6 10) <p 5>|<t 6>cdf</t 9></p 10>| -> <p> nodeEnd 10 > from 6
1060
- if (nodeEnd > from && !wasWithinGap) {
1061
- // |<p>asdf</p>| -> node deleted completely
1062
- const nodeCompletelyDeleted = pos >= from && nodeEnd <= to;
1063
- // The end token deleted eg:
1064
- // <p 1>asdf|</p 7><p 7>bye</p 12>| + [<p>]hello</p> -> <p>asdfhello</p>
1065
- // (del 6 12) + (ins [<p>]hello</p> openStart 1 openEnd 0)
1066
- // (<p> nodeEnd 7) > (from 6) && (nodeEnd 7) <= (to 12)
1067
- //
1068
- // How about
1069
- // <p 1>asdf|</p 7><p 7>|bye</p 12> + [<p>]hello</p><p>good[</p>] -> <p>asdfhello</p><p>goodbye</p>
1070
- //
1071
- // What about:
1072
- // <p 1>asdf|</p 7><p 7 op="inserted">|bye</p 12> + empty -> <p>asdfbye</p>
1073
- const endTokenDeleted = nodeEnd <= to;
1074
- // The start token deleted eg:
1075
- // |<p1 0>hey</p 6><p2 6>|asdf</p 12> + <p3>hello [</p>] -> <p3>hello asdf</p2>
1076
- // (del 0 7) + (ins <p>hello [</p>] openStart 0 openEnd 1)
1077
- // (<p1> pos 0) >= (from 0) && (nodeEnd 6) - 1 > (to 7) == false???
1078
- // (<p2> pos 6) >= (from 0) && (nodeEnd 12) - 1 > (to 7) == true
1079
- //
1080
- const startTokenDeleted = pos >= from; // && nodeEnd - 1 > offsetTo
1081
- if (node.isText ||
1082
- (!endTokenDeleted && startTokenDeleted) ||
1083
- (endTokenDeleted && !startTokenDeleted)) {
1084
- // Since we don't know which side to merge with wholly deleted TextNodes, we use this boolean to remember
1085
- // whether we have entered the endSide of the mergeable blockNodes. Also applies for partial TextNodes
1086
- // (which we could determine without this).
1087
- if (!endTokenDeleted && startTokenDeleted) {
1088
- mergingStartSide = false;
1089
- }
1090
- // Depth is often 1 when merging paragraphs or 2 for fully open blockquotes.
1091
- // Incase of merging text within a ReplaceAroundStep the depth might be 1
1092
- const depth = newTr.doc.resolve(pos).depth;
1093
- const mergeContent = mergingStartSide
1094
- ? firstMergedNode === null || firstMergedNode === void 0 ? void 0 : firstMergedNode.mergedNodeContent
1095
- : lastMergedNode === null || lastMergedNode === void 0 ? void 0 : lastMergedNode.mergedNodeContent;
1096
- // Insert inside a merged node only if the slice was open (openStart > 0) and there exists mergedNodeContent.
1097
- // Then we only have to ensure the depth is at the right level, so say a fully open blockquote insert will
1098
- // be merged at the lowest, paragraph level, instead of blockquote level.
1099
- const mergeStartNode = endTokenDeleted && openStart > 0 && depth === openStart && mergeContent !== undefined;
1100
- // Same as above, merge nodes manually if there exists an open slice with mergeable content.
1101
- // Compared to deleting an end token however, the merged block node is set as deleted. This is due to
1102
- // ProseMirror node semantics as start tokens are considered to contain the actual node itself.
1103
- const mergeEndNode = startTokenDeleted && openEnd > 0 && depth === openEnd && mergeContent !== undefined;
1104
- if (mergeStartNode || mergeEndNode) {
1105
- // Just as a fun fact that I found out while debugging this. Inserting text at paragraph position wraps
1106
- // it into a new paragraph(!). So that's why you always offset your positions to insert it _inside_
1107
- // the paragraph.
1108
- steps.push({
1109
- type: 'merge-fragment',
1110
- pos,
1111
- mergePos: mergeStartNode ? nodeEnd - openStart : pos + openEnd,
1112
- from,
1113
- to,
1114
- node,
1115
- fragment: setFragmentAsInserted(mergeContent, createNewInsertAttrs(trackAttrs), schema),
1116
- });
1117
- // Okay this is a bit ridiculous but it's used to adjust the insert pos when track changes prevents deletions
1118
- // of merged nodes & content, as just using mapped toA in that case isn't the same.
1119
- // The calculation is a bit mysterious, I admit.
1120
- // TODO delete/fix this?
1121
- // 'should prevent replacing of blockquotes and break the slice into parts instead' test needs this
1122
- // if (node.isText) {
1123
- // mergedInsertPos = offsetPos - openEnd
1124
- // }
1125
- }
1126
- else if (node.isText) {
1127
- // Text deletion is handled even when the deletion doesn't completely wrap the text node
1128
- // (which is basically the case most of the time)
1129
- steps.push({
1130
- type: 'delete-text',
1131
- pos,
1132
- from: Math.max(pos, from),
1133
- to: Math.min(nodeEnd, to),
1134
- node,
1135
- });
1136
- }
1137
- else ;
1138
- }
1139
- else if (nodeCompletelyDeleted) {
1140
- steps.push({
1141
- type: 'delete-node',
1142
- pos,
1143
- nodeEnd,
1144
- node,
1145
- });
1146
- }
1147
- }
1148
- });
1149
- return {
1150
- sliceWasSplit: !!(firstMergedNode || lastMergedNode),
1151
- newSliceContent: updatedSliceNodes
1152
- ? Fragment.fromArray(updatedSliceNodes)
1153
- : insertSlice.content,
1154
- steps,
1155
- };
1156
- }
1157
-
1158
- /*!
1159
- * © 2021 Atypon Systems LLC
1160
- *
1161
- * Licensed under the Apache License, Version 2.0 (the "License");
1162
- * you may not use this file except in compliance with the License.
1163
- * You may obtain a copy of the License at
1164
- *
1165
- * http://www.apache.org/licenses/LICENSE-2.0
1166
- *
1167
- * Unless required by applicable law or agreed to in writing, software
1168
- * distributed under the License is distributed on an "AS IS" BASIS,
1169
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1170
- * See the License for the specific language governing permissions and
1171
- * limitations under the License.
1172
- */
1173
- function trackReplaceAroundStep(step, oldState, tr, newTr, attrs) {
1174
- log.info('###### ReplaceAroundStep ######');
1175
- // @ts-ignore
1176
- const { from, to, gapFrom, gapTo, insert, slice, structure, } = step;
1177
- // Invert the transaction step to prevent it from actually deleting or inserting anything
1178
- const newStep = step.invert(oldState.doc);
1179
- const stepResult = newTr.maybeStep(newStep);
1180
- if (stepResult.failed) {
1181
- log.error(`inverting ReplaceAroundStep failed: "${stepResult.failed}"`, newStep);
1182
- return [];
1183
- }
1184
- const gap = oldState.doc.slice(gapFrom, gapTo);
1185
- log.info('RETAINED GAP CONTENT', gap);
1186
- // First apply the deleted range and update the insert slice to not include content that was deleted,
1187
- // eg partial nodes in an open-ended slice
1188
- const { sliceWasSplit, newSliceContent, steps: deleteSteps, } = deleteAndMergeSplitNodes(from, to, { start: gapFrom, end: gapTo }, newTr.doc, newTr, oldState.schema, attrs, slice);
1189
- const steps = deleteSteps;
1190
- log.info('TR: new steps after applying delete', [...newTr.steps]);
1191
- log.info('DELETE STEPS: ', deleteSteps);
1192
- // We only want to insert when there something inside the gap (actually would this be always true?)
1193
- // or insert slice wasn't just start/end tokens (which we already merged inside deleteAndMergeSplitBlockNodes)
1194
- // ^^answering above comment we could have meta node like(bibliography_item, contributor) will not have content at all,
1195
- // and that case gap will be 0, for that will use updateMetaNode to indicate that we are going just to update that node
1196
- if (gap.size > 0 ||
1197
- (!structure && newSliceContent.size > 0) ||
1198
- tr.getMeta(TrackChangesAction.updateMetaNode)) {
1199
- log.info('newSliceContent', newSliceContent);
1200
- // Since deleteAndMergeSplitBlockNodes modified the slice to not to contain any merged nodes,
1201
- // the sides should be equal. TODO can they be other than 0?
1202
- const openStart = slice.openStart !== slice.openEnd || newSliceContent.size === 0 ? 0 : slice.openStart;
1203
- const openEnd = slice.openStart !== slice.openEnd || newSliceContent.size === 0 ? 0 : slice.openEnd;
1204
- let insertedSlice = new Slice(setFragmentAsInserted(newSliceContent, createNewInsertAttrs(attrs), oldState.schema), openStart, openEnd);
1205
- if (gap.size > 0 || tr.getMeta(TrackChangesAction.updateMetaNode)) {
1206
- log.info('insertedSlice before inserted gap', insertedSlice);
1207
- insertedSlice = insertedSlice.insertAt(insertedSlice.size === 0 ? 0 : insert, gap.content);
1208
- log.info('insertedSlice after inserted gap', insertedSlice);
1209
- }
1210
- deleteSteps.push({
1211
- type: 'insert-slice',
1212
- from: gapFrom,
1213
- to: gapTo,
1214
- slice: insertedSlice,
1215
- sliceWasSplit,
1216
- });
1217
- }
1218
- return steps;
1219
- }
1220
-
1221
- /*!
1222
- * © 2021 Atypon Systems LLC
1223
- *
1224
- * Licensed under the Apache License, Version 2.0 (the "License");
1225
- * you may not use this file except in compliance with the License.
1226
- * You may obtain a copy of the License at
1227
- *
1228
- * http://www.apache.org/licenses/LICENSE-2.0
1229
- *
1230
- * Unless required by applicable law or agreed to in writing, software
1231
- * distributed under the License is distributed on an "AS IS" BASIS,
1232
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1233
- * See the License for the specific language governing permissions and
1234
- * limitations under the License.
1235
- */
1236
- function trackReplaceStep(step, oldState, newTr, attrs, stepResult, currentStepDoc) {
1237
- log.info('###### ReplaceStep ######');
1238
- let selectionPos = 0;
1239
- const changeSteps = [];
1240
- // Invert the transaction step to prevent it from actually deleting or inserting anything
1241
- step.getMap().forEach((fromA, toA, fromB, toB) => {
1242
- var _a, _b;
1243
- log.info(`changed ranges: ${fromA} ${toA} ${fromB} ${toB}`);
1244
- const { slice } = step;
1245
- log.info('TR: steps before applying delete', [...newTr.steps]);
1246
- // First apply the deleted range and update the insert slice to not include content that was deleted,
1247
- // eg partial nodes in an open-ended slice
1248
- if (stepResult.failed) {
1249
- log.error(`invert ReplaceStep failed: "${stepResult.failed}"`);
1250
- return;
1251
- }
1252
- const { sliceWasSplit, newSliceContent, steps: deleteSteps, } = deleteAndMergeSplitNodes(fromA, toA, undefined, currentStepDoc, newTr, oldState.schema, attrs, slice);
1253
- changeSteps.push(...deleteSteps);
1254
- log.info('TR: steps after applying delete', [...newTr.steps]);
1255
- log.info('DELETE STEPS: ', changeSteps);
1256
- // console.log('CHANGE STEPS AT THIS POINT:')
1257
- // console.log(JSON.parse(JSON.stringify(changeSteps)))
1258
- function sameThingBackSpaced() {
1259
- /*
1260
- When deleting text with backspace and getting to the point of when a space and a character before a deleted piece of text is deleted
1261
- the prosemirror would interpret it as moving the <del> node (this is a tracked deletion) one characted behind.
1262
- It normally results in [delete, delete, insert] set of ChangSteps where the 1st delete is for the delete done by
1263
- the backspace key, the second delete and the insert are a misinterpretation of the moved text. So these last 2 steps have to be caught
1264
- and removed as they are not meaningful.
1265
- */
1266
- if (changeSteps.length == 2 && newSliceContent.size > 0) {
1267
- const correspondingDeletion = changeSteps.find(
1268
- // @ts-ignore
1269
- (step) => step.node.text === newSliceContent.content[0].text // @TODO - get more precise proof of match. E.g.: position approximation
1270
- );
1271
- return correspondingDeletion;
1272
- }
1273
- return undefined;
1274
- }
1275
- const backSpacedText = sameThingBackSpaced();
1276
- if (backSpacedText) {
1277
- changeSteps.splice(changeSteps.indexOf(backSpacedText));
1278
- }
1279
- const textWasDeleted = !!changeSteps.length;
1280
- if (!backSpacedText && newSliceContent.size > 0) {
1281
- log.info('newSliceContent', newSliceContent);
1282
- // Since deleteAndMergeSplitBlockNodes modified the slice to not to contain any merged nodes,
1283
- // the sides should be equal. TODO can they be other than 0?
1284
- const openStart = slice.openStart !== slice.openEnd ? 0 : slice.openStart;
1285
- const openEnd = slice.openStart !== slice.openEnd ? 0 : slice.openEnd;
1286
- changeSteps.push({
1287
- type: 'insert-slice',
1288
- from: textWasDeleted ? fromB : toA,
1289
- to: textWasDeleted ? toB - 1 : toA,
1290
- sliceWasSplit,
1291
- slice: new Slice(setFragmentAsInserted(newSliceContent, createNewInsertAttrs(attrs), oldState.schema), openStart, openEnd),
1292
- });
1293
- }
1294
- else {
1295
- // Incase only deletion was applied, check whether tracked marks around deleted content can be merged
1296
- // mergeTrackedMarks(adjustedInsertPos, newTr.doc, newTr, oldState.schema)
1297
- // When DEL is used, the selection is set to the end of the deleted content
1298
- // TODO: 'window.event' is deprecated, find a better way to detect the key used for deletion
1299
- // @ts-ignore
1300
- selectionPos = ((_a = window.event) === null || _a === void 0 ? void 0 : _a.code) === 'Delete' || ((_b = window.event) === null || _b === void 0 ? void 0 : _b.inputType) === 'deleteContentForward' ? toA : fromA;
1301
- }
1302
- });
1303
- return [changeSteps, selectionPos];
1304
- }
1305
-
1306
- /*!
1307
- * © 2021 Atypon Systems LLC
1308
- *
1309
- * Licensed under the Apache License, Version 2.0 (the "License");
1310
- * you may not use this file except in compliance with the License.
1311
- * You may obtain a copy of the License at
1312
- *
1313
- * http://www.apache.org/licenses/LICENSE-2.0
1314
- *
1315
- * Unless required by applicable law or agreed to in writing, software
1316
- * distributed under the License is distributed on an "AS IS" BASIS,
1317
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1318
- * See the License for the specific language governing permissions and
1319
- * limitations under the License.
1320
- */
1321
- /**
1322
- * Deletes inserted text directly, otherwise wraps it with tracked_delete mark
1323
- *
1324
- * This would work for general inline nodes too, but since node marks don't work properly
1325
- * with Yjs, attributes are used instead.
1326
- * @param node
1327
- * @param pos
1328
- * @param newTr
1329
- * @param schema
1330
- * @param deleteAttrs
1331
- * @param from
1332
- * @param to
1333
- * @returns position at the end of the possibly deleted text
1334
- */
1335
- function deleteTextIfInserted(node, pos, newTr, schema, deleteAttrs, from, to) {
1336
- const start = from ? Math.max(pos, from) : pos;
1337
- const nodeEnd = pos + node.nodeSize;
1338
- const end = to ? Math.min(nodeEnd, to) : nodeEnd;
1339
- if (node.marks.find((m) => m.type === schema.marks.tracked_insert)) {
1340
- // Math.max(pos, from) is for picking always the start of the node,
1341
- // not the start of the change (which might span multiple nodes).
1342
- // Pos can be less than from as nodesBetween iterates through all nodes starting from the top block node
1343
- newTr.replaceWith(start, end, Fragment.empty);
1344
- return start;
1345
- }
1346
- else {
1347
- const leftNode = newTr.doc.resolve(start).nodeBefore;
1348
- const leftMarks = getMergeableMarkTrackedAttrs(leftNode, deleteAttrs, schema);
1349
- const rightNode = newTr.doc.resolve(end).nodeAfter;
1350
- const rightMarks = getMergeableMarkTrackedAttrs(rightNode, deleteAttrs, schema);
1351
- const fromStartOfMark = start - (leftNode && leftMarks ? leftNode.nodeSize : 0);
1352
- const toEndOfMark = end + (rightNode && rightMarks ? rightNode.nodeSize : 0);
1353
- const createdAt = Math.min((leftMarks === null || leftMarks === void 0 ? void 0 : leftMarks.createdAt) || Number.MAX_VALUE, (rightMarks === null || rightMarks === void 0 ? void 0 : rightMarks.createdAt) || Number.MAX_VALUE, deleteAttrs.createdAt);
1354
- const dataTracked = addTrackIdIfDoesntExist({
1355
- ...leftMarks,
1356
- ...rightMarks,
1357
- ...deleteAttrs,
1358
- createdAt,
1359
- });
1360
- newTr.addMark(fromStartOfMark, toEndOfMark, schema.marks.tracked_delete.create({
1361
- dataTracked,
1362
- }));
1363
- return toEndOfMark;
1364
- }
1365
- }
1366
-
1367
- /**
1368
- * Merges tracked marks between text nodes at a position
1369
- *
1370
- * Will work for any nodes that use tracked_insert or tracked_delete marks which may not be preferrable
1371
- * if used for block nodes (since we possibly want to show the individual changed nodes).
1372
- * Merging is done based on the userID, operation type and status.
1373
- * @param pos
1374
- * @param doc
1375
- * @param newTr
1376
- * @param schema
1377
- */
1378
- function mergeTrackedMarks(pos, doc, newTr, schema) {
1379
- const resolved = doc.resolve(pos);
1380
- const { nodeAfter, nodeBefore } = resolved;
1381
- const leftMark = nodeBefore === null || nodeBefore === void 0 ? void 0 : nodeBefore.marks.filter((m) => m.type === schema.marks.tracked_insert || m.type === schema.marks.tracked_delete)[0];
1382
- const rightMark = nodeAfter === null || nodeAfter === void 0 ? void 0 : nodeAfter.marks.filter((m) => m.type === schema.marks.tracked_insert || m.type === schema.marks.tracked_delete)[0];
1383
- if (!nodeAfter || !nodeBefore || !leftMark || !rightMark || leftMark.type !== rightMark.type) {
1384
- return;
1385
- }
1386
- const leftDataTracked = leftMark.attrs.dataTracked;
1387
- const rightDataTracked = rightMark.attrs.dataTracked;
1388
- if (!shouldMergeTrackedAttributes(leftDataTracked, rightDataTracked)) {
1389
- return;
1390
- }
1391
- const isLeftOlder = (leftDataTracked.createdAt || 0) < (rightDataTracked.createdAt || 0);
1392
- const ancestorAttrs = isLeftOlder ? leftDataTracked : rightDataTracked;
1393
- const dataTracked = {
1394
- ...ancestorAttrs,
1395
- updatedAt: Date.now(),
1396
- };
1397
- const fromStartOfMark = pos - nodeBefore.nodeSize;
1398
- const toEndOfMark = pos + nodeAfter.nodeSize;
1399
- newTr.addMark(fromStartOfMark, toEndOfMark, leftMark.type.create({ ...leftMark.attrs, dataTracked }));
1400
- }
1401
-
1402
- function processChangeSteps(changes, startPos, newTr, emptyAttrs, schema) {
1403
- const mapping = new Mapping();
1404
- const deleteAttrs = createNewDeleteAttrs(emptyAttrs);
1405
- let selectionPos = startPos;
1406
- // @TODO add custom handler / condition?
1407
- changes.forEach((c) => {
1408
- let step = newTr.steps[newTr.steps.length - 1];
1409
- log.info('process change: ', c);
1410
- // const handled = customStepHandler(changes, newTr, emptyAttrs) // ChangeStep[] | undefined
1411
- if (c.type === 'delete-node') {
1412
- deleteOrSetNodeDeleted(c.node, mapping.map(c.pos), newTr, deleteAttrs);
1413
- const newestStep = newTr.steps[newTr.steps.length - 1];
1414
- if (step !== newestStep) {
1415
- mapping.appendMap(newestStep.getMap());
1416
- step = newestStep;
1417
- }
1418
- mergeTrackedMarks(mapping.map(c.pos), newTr.doc, newTr, schema);
1419
- }
1420
- else if (c.type === 'delete-text') {
1421
- const node = newTr.doc.nodeAt(mapping.map(c.pos));
1422
- if (!node) {
1423
- log.error(`processChangeSteps: no text node found for text-change`, c);
1424
- return;
1425
- }
1426
- const where = deleteTextIfInserted(node, mapping.map(c.pos), newTr, schema, deleteAttrs, mapping.map(c.from), mapping.map(c.to));
1427
- mergeTrackedMarks(where, newTr.doc, newTr, schema);
1428
- }
1429
- else if (c.type === 'merge-fragment') {
1430
- let insertPos = mapping.map(c.mergePos);
1431
- // The default insert position for block nodes is either the start of the merged content or the end.
1432
- // Incase text was merged, this must be updated as the start or end of the node doesn't map to the
1433
- // actual position of the merge. Currently the inserted content is inserted at the start or end
1434
- // of the merged content, TODO reverse the start/end when end/start token?
1435
- if (c.node.isText) {
1436
- // When merging text we must delete text in the same go as well, as the from/to boundary goes through
1437
- // the text node.
1438
- insertPos = deleteTextIfInserted(c.node, mapping.map(c.pos), newTr, schema, deleteAttrs, mapping.map(c.from), mapping.map(c.to));
1439
- const newestStep = newTr.steps[newTr.steps.length - 1];
1440
- if (step !== newestStep) {
1441
- mapping.appendMap(newestStep.getMap());
1442
- step = newestStep;
1443
- }
1444
- }
1445
- if (c.fragment.size > 0) {
1446
- newTr.insert(insertPos, c.fragment);
1447
- }
1448
- }
1449
- else if (c.type === 'insert-slice') {
1450
- const newStep = new ReplaceStep(mapping.map(c.from), mapping.map(c.to), c.slice, false);
1451
- const stepResult = newTr.maybeStep(newStep);
1452
- if (stepResult.failed) {
1453
- log.error(`processChangeSteps: insert-slice ReplaceStep failed "${stepResult.failed}"`, newStep);
1454
- return;
1455
- }
1456
- mergeTrackedMarks(mapping.map(c.from), newTr.doc, newTr, schema);
1457
- const to = mapping.map(c.to) + c.slice.size;
1458
- mergeTrackedMarks(mapping.map(c.to) + (to < newTr.doc.nodeSize ? c.slice.size : 0), newTr.doc, newTr, schema);
1459
- selectionPos = mapping.map(c.to) + c.slice.size;
1460
- }
1461
- else if (c.type === 'update-node-attrs') {
1462
- const oldDataTracked = getBlockInlineTrackedData(c.node) || [];
1463
- const oldUpdate = oldDataTracked.reverse().find((d) => {
1464
- // reversing to start from the most recent change
1465
- if (d.operation === CHANGE_OPERATION.set_node_attributes &&
1466
- (d.status === CHANGE_STATUS.pending || d.status === CHANGE_STATUS.rejected)) {
1467
- return true;
1468
- }
1469
- return false;
1470
- });
1471
- // if the selected last change is with status "rejected" we need to use oldAttrs from it because
1472
- // node's actual attributes represent the "rejected" values
1473
- const lastChangeRejected = oldUpdate && oldUpdate.status === CHANGE_STATUS.rejected;
1474
- const sourceAttrs = (oldUpdate === null || oldUpdate === void 0 ? void 0 : oldUpdate.oldAttrs) || c.node.attrs;
1475
- const { dataTracked, ...restAttrs } = sourceAttrs;
1476
- const oldAttrs = lastChangeRejected ? oldUpdate.oldAttrs : restAttrs;
1477
- const newDataTracked = [
1478
- ...oldDataTracked.filter((d) => !oldUpdate || d.id !== oldUpdate.id || lastChangeRejected),
1479
- ];
1480
- const newUpdate = oldUpdate && oldUpdate.status !== CHANGE_STATUS.rejected
1481
- ? {
1482
- ...oldUpdate,
1483
- updatedAt: emptyAttrs.updatedAt,
1484
- }
1485
- : addTrackIdIfDoesntExist(createNewUpdateAttrs(emptyAttrs, lastChangeRejected ? oldAttrs : c.node.attrs));
1486
- // Dont add update changes if there exists already an insert change for this node
1487
- if ((JSON.stringify(oldAttrs) !== JSON.stringify(c.newAttrs) ||
1488
- c.node.type === c.node.type.schema.nodes.citation) &&
1489
- !oldDataTracked.find((d) => d.operation === CHANGE_OPERATION.insert && d.status === CHANGE_STATUS.pending)) {
1490
- newDataTracked.push(newUpdate);
1491
- }
1492
- newTr.setNodeMarkup(mapping.map(c.pos), undefined, {
1493
- ...c.newAttrs,
1494
- dataTracked: newDataTracked.length > 0 ? newDataTracked : null,
1495
- }, c.node.marks);
1496
- }
1497
- const newestStep = newTr.steps[newTr.steps.length - 1];
1498
- if (step !== newestStep) {
1499
- mapping.appendMap(newestStep.getMap());
1500
- }
1501
- });
1502
- return [mapping, selectionPos];
1503
- }
1504
-
1505
- /**
1506
- * Matches deleted-text recursively to inserted text
1507
- *
1508
- * This is needed as text containing various marks is split into multiple parts even though it's
1509
- * continously deleted. Therefore, we need to find the next part if there is any and keep going until
1510
- * we've reached the end of the deleted text or inserted content.
1511
- * @param adjDeleted
1512
- * @param insNode
1513
- * @param offset
1514
- * @param matchedDeleted
1515
- * @param deleted
1516
- * @returns
1517
- */
1518
- function matchText(adjDeleted, insNode, offset, matchedDeleted, deleted) {
1519
- const { pos, from, to, node: delNode } = adjDeleted;
1520
- let j = offset, d = from - pos, maxSteps = to - Math.max(pos, from);
1521
- // Match text inside the inserted text node to the deleted text node
1522
- for (; maxSteps !== j && insNode.text[j] !== undefined && insNode.text[j] === delNode.text[d]; j += 1, d += 1) {
1523
- matchedDeleted += 1;
1524
- }
1525
- // this is needed incase diffing tr.doc
1526
- // deleted.push({
1527
- // pos: pos,
1528
- // type: 'update-node-attrs',
1529
- // // Should check the attrs for equality in fixInconsistentChanges? to remove dataTracked completely
1530
- // oldAttrs: adjDeleted.node.attrs || {},
1531
- // newAttrs: child.attrs || {},
1532
- // })
1533
- deleted = deleted.filter((d) => d !== adjDeleted);
1534
- if (maxSteps !== j) {
1535
- deleted.push({
1536
- pos,
1537
- from: from + j - offset,
1538
- to,
1539
- type: 'delete-text',
1540
- node: delNode,
1541
- });
1542
- return [matchedDeleted, deleted];
1543
- }
1544
- const nextTextDelete = deleted.find((d) => d.type === 'delete-text' && d.pos === to);
1545
- if (nextTextDelete) {
1546
- return matchText(nextTextDelete, insNode, j, matchedDeleted, deleted);
1547
- }
1548
- return [matchedDeleted, deleted];
1549
- }
1550
- /**
1551
- * Matches deleted to inserted content and returns the first pos they differ and the updated
1552
- * ChangeStep list.
1553
- *
1554
- * Based on https://github.com/ProseMirror/prosemirror-model/blob/master/src/diff.ts
1555
- * @param matchedDeleted
1556
- * @param deleted
1557
- * @param inserted
1558
- * @returns
1559
- */
1560
- function matchInserted(matchedDeleted, deleted, inserted) {
1561
- var _a;
1562
- let matched = [matchedDeleted, deleted];
1563
- for (let i = 0;; i += 1) {
1564
- if (inserted.childCount === i) {
1565
- return matched;
1566
- }
1567
- const insNode = inserted.child(i);
1568
- // @ts-ignore
1569
- const adjDeleted = matched[1].find((d) => (d.type === 'delete-text' && Math.max(d.pos, d.from) === matched[0]) ||
1570
- (d.type === 'delete-node' && d.pos === matched[0]));
1571
- if (insNode.type !== ((_a = adjDeleted === null || adjDeleted === void 0 ? void 0 : adjDeleted.node) === null || _a === void 0 ? void 0 : _a.type)) {
1572
- return matched;
1573
- }
1574
- else if (insNode.isText && (adjDeleted === null || adjDeleted === void 0 ? void 0 : adjDeleted.node)) {
1575
- matched = matchText(adjDeleted, insNode, 0, matched[0], matched[1]);
1576
- continue;
1577
- }
1578
- else if (insNode.content.size > 0 || (adjDeleted === null || adjDeleted === void 0 ? void 0 : adjDeleted.node.content.size) > 0) {
1579
- // Move the inDeleted inside the block/inline node's boundary
1580
- matched = matchInserted(matched[0] + 1, matched[1].filter((d) => d !== adjDeleted), insNode.content);
1581
- }
1582
- else {
1583
- matched = [matched[0] + insNode.nodeSize, matched[1].filter((d) => d !== adjDeleted)];
1584
- }
1585
- // Omit dataTracked
1586
- const { dataTracked, ...newAttrs } = insNode.attrs || {};
1587
- matched[1].push({
1588
- pos: adjDeleted.pos,
1589
- type: 'update-node-attrs',
1590
- node: adjDeleted.node,
1591
- newAttrs,
1592
- });
1593
- }
1594
- }
1595
-
1596
- /*!
1597
- * © 2021 Atypon Systems LLC
1598
- *
1599
- * Licensed under the Apache License, Version 2.0 (the "License");
1600
- * you may not use this file except in compliance with the License.
1601
- * You may obtain a copy of the License at
1602
- *
1603
- * http://www.apache.org/licenses/LICENSE-2.0
1604
- *
1605
- * Unless required by applicable law or agreed to in writing, software
1606
- * distributed under the License is distributed on an "AS IS" BASIS,
1607
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1608
- * See the License for the specific language governing permissions and
1609
- * limitations under the License.
1610
- */
1611
- /**
1612
- * Cuts a fragment similar to Fragment.cut but also removes the parent node.
1613
- *
1614
- * @param matched
1615
- * @param deleted
1616
- * @param content
1617
- * @returns
1618
- */
1619
- function cutFragment(matched, deleted, content) {
1620
- const newContent = [];
1621
- for (let i = 0; matched <= deleted && i < content.childCount; i += 1) {
1622
- const child = content.child(i);
1623
- if (!child.isText && child.content.size > 0) {
1624
- const cut = cutFragment(matched + 1, deleted, child.content);
1625
- matched = cut[0];
1626
- newContent.push(...cut[1].content);
1627
- }
1628
- else if (child.isText && matched + child.nodeSize > deleted) {
1629
- if (deleted - matched > 0) {
1630
- newContent.push(child.cut(deleted - matched));
1631
- }
1632
- else {
1633
- newContent.push(child);
1634
- }
1635
- matched = deleted + 1;
1636
- }
1637
- else {
1638
- matched += child.nodeSize;
1639
- }
1640
- }
1641
- return [matched, Fragment.fromArray(newContent)];
1642
- }
1643
- function diffChangeSteps(deleted, inserted) {
1644
- const updated = [];
1645
- let updatedDeleted = [...deleted];
1646
- inserted.forEach((ins) => {
1647
- log.info('DIFF ins ', ins);
1648
- //
1649
- // @TODO this is a temporary workaround to prevent duplicated diffing between splitSliceIntoMergedParts and
1650
- // matchInserted.
1651
- //
1652
- // As originally authored splitSliceIntoMergedParts splits open slices into their merged parts
1653
- // leaving out the need to insert the possibly deleted nodes into the doc. However, as matchInserted now
1654
- // traverses the deleted range checking it against the inserted slice this behaves quite in a same way
1655
- // where the opened block nodes are traversed but left unmodified. With an openStart > 0 though the
1656
- // node-attr-updates would additionally have to be filtered out in the processChangeSteps.
1657
- //
1658
- // The old logic is still left as it's as refactoring is painful and would probably break something and just
1659
- // in general, take a lot of time. Therefore, this sliceWasSplit boolean is used to just skip diffing.
1660
- if (ins.sliceWasSplit) {
1661
- updated.push(ins);
1662
- return;
1663
- }
1664
- // Start diffing from the start of the deleted range
1665
- const deleteStart = updatedDeleted.reduce((acc, cur) => {
1666
- if (cur.type === 'delete-node') {
1667
- return Math.min(acc, cur.pos);
1668
- }
1669
- else if (cur.type === 'delete-text') {
1670
- return Math.min(acc, cur.from);
1671
- }
1672
- return acc;
1673
- }, Number.MAX_SAFE_INTEGER);
1674
- const [matchedDeleted, updatedDel] = matchInserted(deleteStart, updatedDeleted, ins.slice.content);
1675
- if (matchedDeleted === deleteStart) {
1676
- updated.push(ins);
1677
- return;
1678
- }
1679
- updatedDeleted = updatedDel;
1680
- const [_, newInserted] = cutFragment(0, matchedDeleted - deleteStart, ins.slice.content);
1681
- if (newInserted.size > 0) {
1682
- updated.push({
1683
- ...ins,
1684
- slice: new Slice(newInserted, ins.slice.openStart, ins.slice.openEnd),
1685
- });
1686
- }
1687
- });
1688
- log.info('FINISH DIFF: ', [...updatedDeleted, ...updated]);
1689
- return [...updatedDeleted, ...updated];
1690
- }
1691
-
1692
- /**
1693
- * Retrieves a static property from Selection class instead of having to use direct imports
1694
- *
1695
- * This skips the direct dependency to prosemirror-state where multiple versions might cause conflicts
1696
- * as the created instances might belong to different prosemirror-state import than one used in the editor.
1697
- * @param sel
1698
- * @returns
1699
- */
1700
- const getSelectionStaticConstructor = (sel) => Object.getPrototypeOf(sel).constructor;
1701
- const isHighlightMarkerNode = (node) => node && node.type === node.type.schema.nodes.highlight_marker;
1702
- /**
1703
- * Inverts transactions to wrap their contents/operations with track data instead
1704
- *
1705
- * The main function of track changes that holds the most complex parts of this whole library.
1706
- * Takes in as arguments the data from appendTransaction to reapply it with the track marks/attributes.
1707
- * We could prevent the initial transaction from being applied all together but since invert works just
1708
- * as well and we can use the intermediate doc for checking which nodes are changed, it's not prevented.
1709
- *
1710
- *
1711
- * @param tr Original transaction
1712
- * @param oldState State before transaction
1713
- * @param newTr Transaction created from the new editor state
1714
- * @param authorID User id
1715
- * @returns newTr that inverts the initial tr and applies track attributes/marks
1716
- */
1717
- function trackTransaction(tr, oldState, newTr, authorID) {
1718
- var _a, _b, _c, _d;
1719
- const emptyAttrs = {
1720
- authorID,
1721
- reviewedByID: null,
1722
- createdAt: tr.time,
1723
- updatedAt: tr.time,
1724
- status: CHANGE_STATUS.pending,
1725
- };
1726
- // Must use constructor.name instead of instanceof as aliasing prosemirror-state is a lot more
1727
- // difficult than prosemirror-transform
1728
- const wasNodeSelection = tr.selection instanceof NodeSelection;
1729
- let iters = 0;
1730
- log.info('ORIGINAL transaction', tr);
1731
- for (let i = tr.steps.length - 1; i >= 0; i--) {
1732
- const step = tr.steps[i];
1733
- log.info('transaction step', step);
1734
- iters += 1;
1735
- if (iters > 20) {
1736
- console.error('@manuscripts/track-changes-plugin: Possible infinite loop in iterating tr.steps, tracking skipped!\n' +
1737
- 'This is probably an error with the library, please report back to maintainers with a reproduction if possible', newTr);
1738
- continue;
1739
- }
1740
- else if (!(step instanceof ReplaceStep) && step.constructor.name === 'ReplaceStep') {
1741
- console.error('@manuscripts/track-changes-plugin: Multiple prosemirror-transform packages imported, alias/dedupe them ' +
1742
- 'or instanceof checks fail as well as creating new steps');
1743
- continue;
1744
- }
1745
- else if (step instanceof ReplaceStep) {
1746
- const { slice } = step;
1747
- if (((_b = (_a = slice === null || slice === void 0 ? void 0 : slice.content) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.length) === 1 &&
1748
- isHighlightMarkerNode(slice.content.content[0])) {
1749
- // don't track highlight marker nodes
1750
- continue;
1751
- }
1752
- const newStep = step.invert(tr.docs[i]);
1753
- const stepResult = newTr.maybeStep(newStep);
1754
- let [steps, startPos] = trackReplaceStep(step, oldState, newTr, emptyAttrs, stepResult, tr.docs[i]);
1755
- if (steps.length === 1) {
1756
- const step = steps[0]; // eslint-disable-line @typescript-eslint/no-explicit-any
1757
- if (isHighlightMarkerNode((step === null || step === void 0 ? void 0 : step.node) || ((_d = (_c = step === null || step === void 0 ? void 0 : step.slice) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.content[0]))) {
1758
- // don't track deleted highlight marker nodes
1759
- continue;
1760
- }
1761
- }
1762
- log.info('CHANGES: ', steps);
1763
- // deleted and merged really...
1764
- const deleted = steps.filter((s) => s.type !== 'insert-slice');
1765
- const inserted = steps.filter((s) => s.type === 'insert-slice');
1766
- steps = diffChangeSteps(deleted, inserted);
1767
- log.info('DIFFED STEPS: ', steps);
1768
- const [mapping, selectionPos] = processChangeSteps(steps, startPos || tr.selection.head, // Incase startPos is it's default value 0, use the old selection head
1769
- newTr, emptyAttrs, oldState.schema);
1770
- if (!wasNodeSelection) {
1771
- const sel = getSelectionStaticConstructor(tr.selection);
1772
- // Use Selection.near to fix selections that point to a block node instead of inline content
1773
- // eg when inserting a complete new paragraph. -1 finds the first valid position moving backwards
1774
- // inside the content
1775
- const near = sel.near(newTr.doc.resolve(selectionPos), -1);
1776
- newTr.setSelection(near);
1777
- }
1778
- }
1779
- else if (step instanceof ReplaceAroundStep) {
1780
- let steps = trackReplaceAroundStep(step, oldState, tr, newTr, emptyAttrs);
1781
- const deleted = steps.filter((s) => s.type !== 'insert-slice');
1782
- const inserted = steps.filter((s) => s.type === 'insert-slice');
1783
- log.info('INSERT STEPS: ', inserted);
1784
- steps = diffChangeSteps(deleted, inserted);
1785
- log.info('DIFFED STEPS: ', steps);
1786
- processChangeSteps(steps, tr.selection.from, newTr, emptyAttrs, oldState.schema);
1787
- }
1788
- // } else if (step instanceof AddMarkStep) {
1789
- // } else if (step instanceof RemoveMarkStep) {
1790
- // TODO: here we could check whether adjacent inserts & deletes cancel each other out.
1791
- // However, this should not be done by diffing and only matching node or char by char instead since
1792
- // it's A easier and B more intuitive to user.
1793
- // The old meta keys are not copied to the new transaction since this will cause race-conditions
1794
- // when a single meta-field is expected to having been processed / removed. Generic input meta keys,
1795
- // inputType and uiEvent, are re-added since some plugins might depend on them and process the transaction
1796
- // after track-changes plugin.
1797
- tr.getMeta('inputType') && newTr.setMeta('inputType', tr.getMeta('inputType'));
1798
- tr.getMeta('uiEvent') && newTr.setMeta('uiEvent', tr.getMeta('uiEvent'));
1799
- }
1800
- // This is kinda hacky solution at the moment to maintain NodeSelections over transactions
1801
- // These are required by at least cross-references and links to activate their selector pop-ups
1802
- if (wasNodeSelection) {
1803
- console.log('%c Getting into node select! ', 'background: #222; color: #bada55');
1804
- // And -1 here is necessary to keep the selection pointing at the start of the node
1805
- // (or something, breaks with cross-references otherwise)
1806
- const mappedPos = newTr.mapping.map(tr.selection.from, -1);
1807
- const sel = getSelectionStaticConstructor(tr.selection);
1808
- newTr.setSelection(sel.create(newTr.doc, mappedPos));
1809
- }
1810
- log.info('NEW transaction', newTr);
1811
- return newTr;
1812
- }
1813
-
1814
- var TrackChangesStatus;
1815
- (function (TrackChangesStatus) {
1816
- TrackChangesStatus["enabled"] = "enabled";
1817
- TrackChangesStatus["viewSnapshots"] = "view-snapshots";
1818
- TrackChangesStatus["disabled"] = "disabled";
1819
- })(TrackChangesStatus || (TrackChangesStatus = {}));
1820
-
1821
- /*!
1822
- * © 2021 Atypon Systems LLC
1823
- *
1824
- * Licensed under the Apache License, Version 2.0 (the "License");
1825
- * you may not use this file except in compliance with the License.
1826
- * You may obtain a copy of the License at
1827
- *
1828
- * http://www.apache.org/licenses/LICENSE-2.0
1829
- *
1830
- * Unless required by applicable law or agreed to in writing, software
1831
- * distributed under the License is distributed on an "AS IS" BASIS,
1832
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1833
- * See the License for the specific language governing permissions and
1834
- * limitations under the License.
1835
- */
1836
- const trackChangesPluginKey = new PluginKey('track-changes');
1837
- /**
1838
- * The ProseMirror plugin needed to enable track-changes.
1839
- *
1840
- * Accepts an empty options object as an argument but note that this uses 'anonymous:Anonymous' as the default userID.
1841
- * @param opts
1842
- */
1843
- const trackChangesPlugin = (opts = { userID: 'anonymous:Anonymous' }) => {
1844
- const { userID, debug, skipTrsWithMetas = [] } = opts;
1845
- let editorView;
1846
- if (debug) {
1847
- enableDebug(true);
1848
- }
1849
- return new Plugin({
1850
- key: trackChangesPluginKey,
1851
- props: {
1852
- editable(state) {
1853
- var _a;
1854
- return ((_a = trackChangesPluginKey.getState(state)) === null || _a === void 0 ? void 0 : _a.status) !== TrackChangesStatus.viewSnapshots;
1855
- },
1856
- },
1857
- state: {
1858
- init(_config, state) {
1859
- return {
1860
- status: TrackChangesStatus.enabled,
1861
- userID,
1862
- changeSet: findChanges(state),
1863
- };
1864
- },
1865
- apply(tr, pluginState, _oldState, newState) {
1866
- const setUserID = getAction(tr, TrackChangesAction.setUserID);
1867
- const setStatus = getAction(tr, TrackChangesAction.setPluginStatus);
1868
- if (setUserID) {
1869
- return { ...pluginState, userID: setUserID };
1870
- }
1871
- else if (setStatus) {
1872
- return {
1873
- ...pluginState,
1874
- status: setStatus,
1875
- changeSet: setStatus === TrackChangesStatus.disabled ? new ChangeSet() : findChanges(newState),
1876
- };
1877
- }
1878
- else if (pluginState.status === TrackChangesStatus.disabled) {
1879
- return { ...pluginState, changeSet: new ChangeSet() };
1880
- }
1881
- let { changeSet, ...rest } = pluginState;
1882
- if (getAction(tr, TrackChangesAction.refreshChanges)) {
1883
- changeSet = findChanges(newState);
1884
- }
1885
- return {
1886
- changeSet,
1887
- ...rest,
1888
- };
1889
- },
1890
- },
1891
- view(p) {
1892
- editorView = p;
1893
- return {
1894
- update: undefined,
1895
- destroy: undefined,
1896
- };
1897
- },
1898
- appendTransaction(trs, oldState, newState) {
1899
- const pluginState = trackChangesPluginKey.getState(newState);
1900
- if (!pluginState || pluginState.status === TrackChangesStatus.disabled || !(editorView === null || editorView === void 0 ? void 0 : editorView.editable)) {
1901
- return null;
1902
- }
1903
- const { userID, changeSet } = pluginState;
1904
- let createdTr = newState.tr, docChanged = false;
1905
- log.info('TRS', trs);
1906
- trs.forEach((tr) => {
1907
- const wasAppended = tr.getMeta('appendedTransaction');
1908
- const skipMetaUsed = skipTrsWithMetas.some((m) => tr.getMeta(m) || (wasAppended === null || wasAppended === void 0 ? void 0 : wasAppended.getMeta(m)));
1909
- const skipTrackUsed = getAction(tr, TrackChangesAction.skipTrack) || (wasAppended && getAction(wasAppended, TrackChangesAction.skipTrack));
1910
- if (tr.docChanged && !skipMetaUsed && !skipTrackUsed && !tr.getMeta('history$') && !(wasAppended && tr.getMeta('origin') === 'paragraphs')) {
1911
- createdTr = trackTransaction(tr, oldState, createdTr, userID);
1912
- }
1913
- docChanged = docChanged || tr.docChanged;
1914
- const setChangeStatuses = getAction(tr, TrackChangesAction.setChangeStatuses);
1915
- if (setChangeStatuses) {
1916
- const { status, ids } = setChangeStatuses;
1917
- ids.forEach((changeId) => {
1918
- const change = changeSet === null || changeSet === void 0 ? void 0 : changeSet.get(changeId);
1919
- if (change) {
1920
- createdTr = updateChangeAttrs(createdTr, change, { ...change.dataTracked, status, reviewedByID: userID }, oldState.schema);
1921
- }
1922
- });
1923
- }
1924
- else if (getAction(tr, TrackChangesAction.applyAndRemoveChanges)) {
1925
- const mapping = applyAcceptedRejectedChanges(createdTr, oldState.schema, changeSet.bothNodeChanges);
1926
- applyAcceptedRejectedChanges(createdTr, oldState.schema, changeSet.textChanges, mapping);
1927
- setAction(createdTr, TrackChangesAction.refreshChanges, true);
1928
- }
1929
- });
1930
- const changed = pluginState.changeSet.hasInconsistentData && fixInconsistentChanges(pluginState.changeSet, userID, createdTr, oldState.schema);
1931
- if (changed) {
1932
- log.warn('had to fix inconsistent changes in', createdTr);
1933
- }
1934
- if (docChanged || createdTr.docChanged || changed) {
1935
- createdTr.setMeta('origin', trackChangesPluginKey);
1936
- return setAction(createdTr, TrackChangesAction.refreshChanges, true);
1937
- }
1938
- return null;
1939
- },
1940
- });
1941
- };
1942
-
1943
- /**
1944
- * Sets track-changes plugin's status to any of: 'enabled' 'disabled' 'viewSnapshots'. Passing undefined will
1945
- * set 'enabled' status to 'disabled' and 'disabled' | 'viewSnapshots' status to 'enabled'.
1946
- *
1947
- * In disabled view, the plugin is completely inactive and changes are not updated anymore.
1948
- * In viewSnasphots state, editor is set uneditable by editable prop that allows only selection changes
1949
- * to the document.
1950
- * @param status
1951
- */
1952
- const setTrackingStatus = (status) => (state, dispatch) => {
1953
- var _a;
1954
- const currentStatus = (_a = trackChangesPluginKey.getState(state)) === null || _a === void 0 ? void 0 : _a.status;
1955
- if (currentStatus) {
1956
- let newStatus = status;
1957
- if (newStatus === undefined) {
1958
- newStatus =
1959
- currentStatus === TrackChangesStatus.enabled
1960
- ? TrackChangesStatus.disabled
1961
- : TrackChangesStatus.enabled;
1962
- }
1963
- dispatch && dispatch(setAction(state.tr, TrackChangesAction.setPluginStatus, newStatus));
1964
- return true;
1965
- }
1966
- return false;
1967
- };
1968
- /**
1969
- * Appends a transaction to set change attributes/marks' statuses to any of: 'pending' 'accepted' 'rejected'.
1970
- * @param status
1971
- * @param ids
1972
- */
1973
- const setChangeStatuses = (status, ids) => (state, dispatch) => {
1974
- dispatch &&
1975
- dispatch(setAction(state.tr, TrackChangesAction.setChangeStatuses, {
1976
- status,
1977
- ids,
1978
- }));
1979
- return true;
1980
- };
1981
- /**
1982
- * Sets track-changes plugin's userID.
1983
- * @param userID
1984
- */
1985
- const setUserID = (userID) => (state, dispatch) => {
1986
- dispatch && dispatch(setAction(state.tr, TrackChangesAction.setUserID, userID));
1987
- return true;
1988
- };
1989
- /**
1990
- * Appends a transaction that applies all 'accepted' and 'rejected' changes to the document.
1991
- */
1992
- const applyAndRemoveChanges = () => (state, dispatch) => {
1993
- dispatch && dispatch(setAction(state.tr, TrackChangesAction.applyAndRemoveChanges, true));
1994
- return true;
1995
- };
1996
- /**
1997
- * Runs `findChanges` to iterate over the document to collect changes into a new ChangeSet.
1998
- */
1999
- const refreshChanges = () => (state, dispatch) => {
2000
- dispatch && dispatch(setAction(state.tr, TrackChangesAction.refreshChanges, true));
2001
- return true;
2002
- };
2003
-
2004
- var commands = /*#__PURE__*/Object.freeze({
2005
- __proto__: null,
2006
- setTrackingStatus: setTrackingStatus,
2007
- setChangeStatuses: setChangeStatuses,
2008
- setUserID: setUserID,
2009
- applyAndRemoveChanges: applyAndRemoveChanges,
2010
- refreshChanges: refreshChanges
2011
- });
2012
-
2013
- export { CHANGE_OPERATION, CHANGE_STATUS, ChangeSet, TrackChangesStatus, enableDebug, skipTracking, trackChangesPlugin, trackChangesPluginKey, commands as trackCommands };