@manuscripts/track-changes-plugin 0.0.1

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.
@@ -0,0 +1,1539 @@
1
+ import { 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["updateChanges"] = "track-changes-update-changes";
13
+ TrackChangesAction["refreshChanges"] = "track-changes-refresh-changes";
14
+ TrackChangesAction["applyAndRemoveChanges"] = "track-changes-apply-remove-changes";
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
+ /******************************************************************************
36
+ Copyright (c) Microsoft Corporation.
37
+
38
+ Permission to use, copy, modify, and/or distribute this software for any
39
+ purpose with or without fee is hereby granted.
40
+
41
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
42
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
43
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
44
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
45
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
46
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
47
+ PERFORMANCE OF THIS SOFTWARE.
48
+ ***************************************************************************** */
49
+
50
+ function __classPrivateFieldGet(receiver, state, kind, f) {
51
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
52
+ 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");
53
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
54
+ }
55
+
56
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
57
+ if (kind === "m") throw new TypeError("Private method is not writable");
58
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
59
+ 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");
60
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
61
+ }
62
+
63
+ /*!
64
+ * © 2021 Atypon Systems LLC
65
+ *
66
+ * Licensed under the Apache License, Version 2.0 (the "License");
67
+ * you may not use this file except in compliance with the License.
68
+ * You may obtain a copy of the License at
69
+ *
70
+ * http://www.apache.org/licenses/LICENSE-2.0
71
+ *
72
+ * Unless required by applicable law or agreed to in writing, software
73
+ * distributed under the License is distributed on an "AS IS" BASIS,
74
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
75
+ * See the License for the specific language governing permissions and
76
+ * limitations under the License.
77
+ */
78
+ var CHANGE_OPERATION;
79
+ (function (CHANGE_OPERATION) {
80
+ CHANGE_OPERATION["insert"] = "insert";
81
+ CHANGE_OPERATION["delete"] = "delete";
82
+ CHANGE_OPERATION["set_node_attributes"] = "set_node_attributes";
83
+ CHANGE_OPERATION["wrap_with_node"] = "wrap_with_node";
84
+ CHANGE_OPERATION["unwrap_from_node"] = "unwrap_from_node";
85
+ CHANGE_OPERATION["add_mark"] = "add_mark";
86
+ CHANGE_OPERATION["remove_mark"] = "remove_mark";
87
+ })(CHANGE_OPERATION || (CHANGE_OPERATION = {}));
88
+ var CHANGE_STATUS;
89
+ (function (CHANGE_STATUS) {
90
+ CHANGE_STATUS["accepted"] = "accepted";
91
+ CHANGE_STATUS["rejected"] = "rejected";
92
+ CHANGE_STATUS["pending"] = "pending";
93
+ })(CHANGE_STATUS || (CHANGE_STATUS = {}));
94
+
95
+ /*!
96
+ * © 2021 Atypon Systems LLC
97
+ *
98
+ * Licensed under the Apache License, Version 2.0 (the "License");
99
+ * you may not use this file except in compliance with the License.
100
+ * You may obtain a copy of the License at
101
+ *
102
+ * http://www.apache.org/licenses/LICENSE-2.0
103
+ *
104
+ * Unless required by applicable law or agreed to in writing, software
105
+ * distributed under the License is distributed on an "AS IS" BASIS,
106
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
107
+ * See the License for the specific language governing permissions and
108
+ * limitations under the License.
109
+ */
110
+ const logger = debug('track');
111
+ const log = {
112
+ info(str, obj) {
113
+ if (obj) {
114
+ logger(str, obj);
115
+ }
116
+ else {
117
+ logger(str);
118
+ }
119
+ },
120
+ warn(str, obj) {
121
+ if (obj) {
122
+ logger(`%c WARNING ${str}`, 'color: #f3f32c', obj);
123
+ }
124
+ else {
125
+ logger(`%c WARNING ${str}`, 'color: #f3f32c');
126
+ }
127
+ },
128
+ error(str, obj) {
129
+ if (obj) {
130
+ logger(`%c ERROR ${str}`, 'color: #ff4242', obj);
131
+ }
132
+ else {
133
+ logger(`%c ERROR ${str}`, 'color: #ff4242');
134
+ }
135
+ },
136
+ };
137
+ /**
138
+ * Sets debug logging enabled/disabled.
139
+ * @param enabled
140
+ */
141
+ const enableDebug = (enabled) => {
142
+ if (enabled) {
143
+ debug.enable('track');
144
+ }
145
+ else {
146
+ debug.disable();
147
+ }
148
+ };
149
+
150
+ var _ChangeSet_changes;
151
+ /**
152
+ * ChangeSet is a data structure to contain the tracked changes with some utility methods and computed
153
+ * values to allow easier operability.
154
+ */
155
+ class ChangeSet {
156
+ constructor(changes = []) {
157
+ _ChangeSet_changes.set(this, void 0);
158
+ __classPrivateFieldSet(this, _ChangeSet_changes, changes, "f");
159
+ }
160
+ /**
161
+ * List of all the valid TrackedChanges. This prevents for example changes with duplicate ids being shown
162
+ * in the UI, causing errors.
163
+ */
164
+ get changes() {
165
+ const iteratedIds = new Set();
166
+ return __classPrivateFieldGet(this, _ChangeSet_changes, "f").filter((c) => {
167
+ const valid = !iteratedIds.has(c.attrs.id) && ChangeSet.isValidTrackedAttrs(c.attrs);
168
+ iteratedIds.add(c.attrs.id);
169
+ return valid;
170
+ });
171
+ }
172
+ get invalidChanges() {
173
+ return __classPrivateFieldGet(this, _ChangeSet_changes, "f").filter((c) => !this.changes.find((cc) => c.id === cc.id));
174
+ }
175
+ /**
176
+ * List of 1-level nested changes where the top-most node change contains all the changes within its start
177
+ * and end position. This is useful for showing the changes as groups in the UI.
178
+ */
179
+ get changeTree() {
180
+ const rootNodes = [];
181
+ let currentNodeChange;
182
+ this.changes.forEach((c) => {
183
+ if (currentNodeChange && c.from >= currentNodeChange.to) {
184
+ rootNodes.push(currentNodeChange);
185
+ currentNodeChange = undefined;
186
+ }
187
+ if (c.type === 'node-change' && currentNodeChange && c.from < currentNodeChange.to) {
188
+ currentNodeChange.children.push(c);
189
+ }
190
+ else if (c.type === 'node-change') {
191
+ currentNodeChange = { ...c, children: [] };
192
+ }
193
+ else if (c.type === 'text-change' && currentNodeChange && c.from < currentNodeChange.to) {
194
+ currentNodeChange.children.push(c);
195
+ }
196
+ else if (c.type === 'text-change') {
197
+ rootNodes.push(c);
198
+ }
199
+ });
200
+ if (currentNodeChange) {
201
+ rootNodes.push(currentNodeChange);
202
+ }
203
+ return rootNodes;
204
+ }
205
+ get pending() {
206
+ return this.changeTree.filter((c) => c.attrs.status === CHANGE_STATUS.pending);
207
+ }
208
+ get accepted() {
209
+ return this.changeTree.filter((c) => c.attrs.status === CHANGE_STATUS.accepted);
210
+ }
211
+ get rejected() {
212
+ return this.changeTree.filter((c) => c.attrs.status === CHANGE_STATUS.rejected);
213
+ }
214
+ get textChanges() {
215
+ return this.changes.filter((c) => c.type === 'text-change');
216
+ }
217
+ get nodeChanges() {
218
+ return this.changes.filter((c) => c.type === 'node-change');
219
+ }
220
+ get isEmpty() {
221
+ return __classPrivateFieldGet(this, _ChangeSet_changes, "f").length === 0;
222
+ }
223
+ /**
224
+ * Used to determine whether `fixInconsistentChanges` has to be executed to replace eg duplicate ids or
225
+ * changes that are missing attributes.
226
+ */
227
+ get hasInconsistentData() {
228
+ return this.hasDuplicateIds || this.hasIncompleteAttrs;
229
+ }
230
+ get hasDuplicateIds() {
231
+ const iterated = new Set();
232
+ return __classPrivateFieldGet(this, _ChangeSet_changes, "f").some((c) => {
233
+ if (iterated.has(c.id)) {
234
+ return true;
235
+ }
236
+ iterated.add(c.id);
237
+ });
238
+ }
239
+ get hasIncompleteAttrs() {
240
+ return __classPrivateFieldGet(this, _ChangeSet_changes, "f").some((c) => !ChangeSet.isValidTrackedAttrs(c.attrs));
241
+ }
242
+ get(id) {
243
+ return __classPrivateFieldGet(this, _ChangeSet_changes, "f").find((c) => c.id === id);
244
+ }
245
+ getIn(ids) {
246
+ return ids
247
+ .map((id) => __classPrivateFieldGet(this, _ChangeSet_changes, "f").find((c) => c.id === id))
248
+ .filter((c) => c !== undefined);
249
+ }
250
+ getNotIn(ids) {
251
+ return __classPrivateFieldGet(this, _ChangeSet_changes, "f").filter((c) => ids.includes(c.id));
252
+ }
253
+ /**
254
+ * Flattens a changeTree into a list of IDs
255
+ * @param changes
256
+ */
257
+ static flattenTreeToIds(changes) {
258
+ return changes.flatMap((c) => this.isNodeChange(c) ? [c.id, ...c.children.map((c) => c.id)] : c.id);
259
+ }
260
+ /**
261
+ * Determines whether a change should not be deleted when applying it to the document.
262
+ * @param change
263
+ */
264
+ static shouldNotDelete(change) {
265
+ const { status, operation } = change.attrs;
266
+ return ((operation === CHANGE_OPERATION.insert && status === CHANGE_STATUS.accepted) ||
267
+ (operation === CHANGE_OPERATION.delete && status === CHANGE_STATUS.rejected));
268
+ }
269
+ /**
270
+ * Determines whether a change should be deleted when applying it to the document.
271
+ * @param change
272
+ */
273
+ static shouldDeleteChange(change) {
274
+ const { status, operation } = change.attrs;
275
+ return ((operation === CHANGE_OPERATION.insert && status === CHANGE_STATUS.rejected) ||
276
+ (operation === CHANGE_OPERATION.delete && status === CHANGE_STATUS.accepted));
277
+ }
278
+ /**
279
+ * Checks whether change attributes contain all TrackedAttrs keys with non-undefined values
280
+ * @param attrs
281
+ */
282
+ static isValidTrackedAttrs(attrs = {}) {
283
+ if ('attrs' in attrs) {
284
+ log.warn('passed "attrs" as property to isValidTrackedAttrs(attrs)', attrs);
285
+ }
286
+ const trackedKeys = ['id', 'userID', 'operation', 'status', 'createdAt'];
287
+ const entries = Object.entries(attrs);
288
+ return (entries.length === trackedKeys.length &&
289
+ entries.every(([key, val]) => trackedKeys.includes(key) && val !== undefined) &&
290
+ (attrs.id || '').length > 0 // Changes created with undefined id have '' as placeholder
291
+ );
292
+ }
293
+ static isTextChange(change) {
294
+ return change.type === 'text-change';
295
+ }
296
+ static isNodeChange(change) {
297
+ return change.type === 'node-change';
298
+ }
299
+ }
300
+ _ChangeSet_changes = new WeakMap();
301
+
302
+ /*!
303
+ * © 2021 Atypon Systems LLC
304
+ *
305
+ * Licensed under the Apache License, Version 2.0 (the "License");
306
+ * you may not use this file except in compliance with the License.
307
+ * You may obtain a copy of the License at
308
+ *
309
+ * http://www.apache.org/licenses/LICENSE-2.0
310
+ *
311
+ * Unless required by applicable law or agreed to in writing, software
312
+ * distributed under the License is distributed on an "AS IS" BASIS,
313
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
314
+ * See the License for the specific language governing permissions and
315
+ * limitations under the License.
316
+ */
317
+ /**
318
+ * Deletes node but tries to leave its content intact by trying to unwrap it first
319
+ *
320
+ * Incase unwrapping doesn't work deletes the whole node.
321
+ * @param node
322
+ * @param pos
323
+ * @param tr
324
+ * @returns
325
+ */
326
+ function deleteNode(node, pos, tr) {
327
+ var _a;
328
+ const startPos = tr.doc.resolve(pos + 1);
329
+ const range = startPos.blockRange(tr.doc.resolve(startPos.pos - 2 + node.nodeSize));
330
+ const targetDepth = range ? Number(liftTarget(range)) : NaN;
331
+ if (range && !Number.isNaN(targetDepth)) {
332
+ return tr.lift(range, targetDepth);
333
+ }
334
+ const resPos = tr.doc.resolve(pos);
335
+ const canMergeToNodeAbove = (resPos.parent !== tr.doc || resPos.nodeBefore) && ((_a = node.firstChild) === null || _a === void 0 ? void 0 : _a.isText);
336
+ if (canMergeToNodeAbove) {
337
+ return tr.replaceWith(pos - 1, pos + 1, Fragment.empty);
338
+ }
339
+ else {
340
+ // NOTE: there's an edge case where moving content is not possible but because the immediate
341
+ // child, say some wrapper blockNode, is also deleted the content could be retained. TODO I guess.
342
+ return tr.delete(pos, pos + node.nodeSize);
343
+ }
344
+ }
345
+
346
+ /*!
347
+ * © 2021 Atypon Systems LLC
348
+ *
349
+ * Licensed under the Apache License, Version 2.0 (the "License");
350
+ * you may not use this file except in compliance with the License.
351
+ * You may obtain a copy of the License at
352
+ *
353
+ * http://www.apache.org/licenses/LICENSE-2.0
354
+ *
355
+ * Unless required by applicable law or agreed to in writing, software
356
+ * distributed under the License is distributed on an "AS IS" BASIS,
357
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
358
+ * See the License for the specific language governing permissions and
359
+ * limitations under the License.
360
+ */
361
+ /**
362
+ * Deletes node but tries to leave its content intact by moving/wrapping it to a node before or after
363
+ * @param node
364
+ * @param pos
365
+ * @param tr
366
+ * @returns
367
+ */
368
+ function mergeNode(node, pos, tr) {
369
+ var _a;
370
+ if (canJoin(tr.doc, pos)) {
371
+ return tr.join(pos);
372
+ }
373
+ else if (canJoin(tr.doc, pos + node.nodeSize)) {
374
+ return tr.join(pos + node.nodeSize);
375
+ }
376
+ // TODO is this the same thing as join?
377
+ const resPos = tr.doc.resolve(pos);
378
+ const canMergeToNodeAbove = (resPos.parent !== tr.doc || resPos.nodeBefore) && ((_a = node.firstChild) === null || _a === void 0 ? void 0 : _a.isText);
379
+ if (canMergeToNodeAbove) {
380
+ return tr.replaceWith(pos - 1, pos + 1, Fragment.empty);
381
+ }
382
+ return undefined;
383
+ }
384
+
385
+ /*!
386
+ * © 2021 Atypon Systems LLC
387
+ *
388
+ * Licensed under the Apache License, Version 2.0 (the "License");
389
+ * you may not use this file except in compliance with the License.
390
+ * You may obtain a copy of the License at
391
+ *
392
+ * http://www.apache.org/licenses/LICENSE-2.0
393
+ *
394
+ * Unless required by applicable law or agreed to in writing, software
395
+ * distributed under the License is distributed on an "AS IS" BASIS,
396
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
397
+ * See the License for the specific language governing permissions and
398
+ * limitations under the License.
399
+ */
400
+ function uuidv4() {
401
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
402
+ const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
403
+ return v.toString(16);
404
+ });
405
+ }
406
+
407
+ function addTrackIdIfDoesntExist(attrs) {
408
+ if (!attrs.id) {
409
+ return {
410
+ id: uuidv4(),
411
+ ...attrs,
412
+ };
413
+ }
414
+ return attrs;
415
+ }
416
+ function getInlineNodeTrackedMarkData(node, schema) {
417
+ if (!node || !node.isInline) {
418
+ return undefined;
419
+ }
420
+ const marksTrackedData = [];
421
+ node.marks.forEach((mark) => {
422
+ if (mark.type === schema.marks.tracked_insert || mark.type === schema.marks.tracked_delete) {
423
+ const operation = mark.type === schema.marks.tracked_insert
424
+ ? CHANGE_OPERATION.insert
425
+ : CHANGE_OPERATION.delete;
426
+ marksTrackedData.push({ ...mark.attrs.dataTracked, operation });
427
+ }
428
+ });
429
+ if (marksTrackedData.length > 1) {
430
+ log.warn('inline node with more than 1 of tracked marks', marksTrackedData);
431
+ }
432
+ return marksTrackedData[0] || undefined;
433
+ }
434
+ function getNodeTrackedData(node, schema) {
435
+ return !node
436
+ ? undefined
437
+ : node.isText
438
+ ? getInlineNodeTrackedMarkData(node, schema)
439
+ : node.attrs.dataTracked;
440
+ }
441
+ function equalMarks(n1, n2) {
442
+ return (n1.marks.length === n2.marks.length &&
443
+ n1.marks.every((mark) => n1.marks.find((m) => m.type === mark.type)));
444
+ }
445
+ function shouldMergeTrackedAttributes(left, right) {
446
+ if (!left || !right) {
447
+ log.warn('passed undefined dataTracked attributes to shouldMergeTrackedAttributes', {
448
+ left,
449
+ right,
450
+ });
451
+ return false;
452
+ }
453
+ return (left.status === right.status &&
454
+ left.operation === right.operation &&
455
+ left.userID === right.userID);
456
+ }
457
+ function getMergeableMarkTrackedAttrs(node, attrs, schema) {
458
+ const nodeAttrs = getInlineNodeTrackedMarkData(node, schema);
459
+ return nodeAttrs && shouldMergeTrackedAttributes(nodeAttrs, attrs) ? nodeAttrs : null;
460
+ }
461
+
462
+ function updateChangeAttrs(tr, change, trackedAttrs, schema) {
463
+ const node = tr.doc.nodeAt(change.from);
464
+ if (!node) {
465
+ throw Error('No node at the from of change' + change);
466
+ }
467
+ const dataTracked = { ...getNodeTrackedData(node, schema), ...trackedAttrs };
468
+ const oldMark = node.marks.find((m) => m.type === schema.marks.tracked_insert || m.type === schema.marks.tracked_delete);
469
+ if (change.type === 'text-change' && oldMark) {
470
+ tr.addMark(change.from, change.to, oldMark.type.create({ ...oldMark.attrs, dataTracked }));
471
+ }
472
+ else if (change.type === 'node-change') {
473
+ tr.setNodeMarkup(change.from, undefined, { ...node.attrs, dataTracked }, node.marks);
474
+ }
475
+ return tr;
476
+ }
477
+ function updateChangeChildrenAttributes(changes, tr, mapping) {
478
+ changes.forEach((c) => {
479
+ if (c.type === 'node-change' && ChangeSet.shouldNotDelete(c)) {
480
+ const from = mapping.map(c.from);
481
+ const node = tr.doc.nodeAt(from);
482
+ if (!node) {
483
+ return;
484
+ }
485
+ const attrs = { ...node.attrs, dataTracked: null };
486
+ tr.setNodeMarkup(from, undefined, attrs, node.marks);
487
+ }
488
+ });
489
+ }
490
+
491
+ /**
492
+ * Applies the accepted/rejected changes in the current document and sets them untracked
493
+ *
494
+ * @param tr
495
+ * @param schema
496
+ * @param changes
497
+ * @param deleteMap
498
+ */
499
+ function applyAcceptedRejectedChanges(tr, schema, changes, deleteMap = new Mapping()) {
500
+ changes.forEach((change) => {
501
+ if (change.attrs.status === CHANGE_STATUS.pending) {
502
+ return;
503
+ }
504
+ const from = deleteMap.map(change.from), node = tr.doc.nodeAt(from), noChangeNeeded = ChangeSet.shouldNotDelete(change);
505
+ if (!node) {
506
+ log.warn('no node found to update for change', change);
507
+ return;
508
+ }
509
+ if (ChangeSet.isTextChange(change) && noChangeNeeded) {
510
+ tr.removeMark(from, deleteMap.map(change.to), schema.marks.tracked_insert);
511
+ tr.removeMark(from, deleteMap.map(change.to), schema.marks.tracked_delete);
512
+ }
513
+ else if (ChangeSet.isTextChange(change)) {
514
+ tr.delete(from, deleteMap.map(change.to));
515
+ deleteMap.appendMap(tr.steps[tr.steps.length - 1].getMap());
516
+ }
517
+ else if (ChangeSet.isNodeChange(change) && noChangeNeeded) {
518
+ const attrs = { ...node.attrs, dataTracked: null };
519
+ tr.setNodeMarkup(from, undefined, attrs, node.marks);
520
+ updateChangeChildrenAttributes(change.children, tr, deleteMap);
521
+ }
522
+ else if (ChangeSet.isNodeChange(change)) {
523
+ // Try first moving the node children to either nodeAbove, nodeBelow or its parent.
524
+ // Then try unwrapping it with lift or just hacky-joining by replacing the border between
525
+ // it and its parent with Fragment.empty. If none of these apply, delete the content between the change.
526
+ const merged = mergeNode(node, from, tr);
527
+ if (merged === undefined) {
528
+ deleteNode(node, from, tr);
529
+ }
530
+ deleteMap.appendMap(tr.steps[tr.steps.length - 1].getMap());
531
+ }
532
+ });
533
+ return deleteMap;
534
+ }
535
+
536
+ /**
537
+ * Finds all changes (basically text marks or node attributes) from document
538
+ *
539
+ * This could be possibly made more efficient by only iterating the sections of doc
540
+ * where changes have been applied. This could attempted with eg findDiffStart
541
+ * but it might be less robust than just using doc.descendants
542
+ * @param state
543
+ * @returns
544
+ */
545
+ function findChanges(state) {
546
+ const changes = [];
547
+ // Store the last iterated change to join adjacent text changes
548
+ let current;
549
+ state.doc.descendants((node, pos) => {
550
+ const attrs = getNodeTrackedData(node, state.schema);
551
+ if (attrs) {
552
+ const id = (attrs === null || attrs === void 0 ? void 0 : attrs.id) || '';
553
+ // Join adjacent text changes that have been broken up due to different marks
554
+ // eg <ins><b>bold</b>norm<i>italic</i></ins> -> treated as one continuous change
555
+ // Note the !equalMarks to leave changes separate incase the marks are equal to let fixInconsistentChanges to fix them
556
+ if (current &&
557
+ current.change.id === id &&
558
+ current.node.isText &&
559
+ node.isText &&
560
+ !equalMarks(node, current.node)) {
561
+ current.change.to = pos + node.nodeSize;
562
+ // Important to update the node as the text changes might contain multiple parts where some marks equal each other
563
+ current.node = node;
564
+ }
565
+ else if (node.isText) {
566
+ current && changes.push(current.change);
567
+ current = {
568
+ change: {
569
+ id,
570
+ type: 'text-change',
571
+ from: pos,
572
+ to: pos + node.nodeSize,
573
+ attrs,
574
+ },
575
+ node,
576
+ };
577
+ }
578
+ else {
579
+ current && changes.push(current.change);
580
+ current = {
581
+ change: {
582
+ id,
583
+ type: 'node-change',
584
+ from: pos,
585
+ to: pos + node.nodeSize,
586
+ nodeType: node.type.name,
587
+ children: [],
588
+ attrs,
589
+ },
590
+ node,
591
+ };
592
+ }
593
+ }
594
+ else if (current) {
595
+ changes.push(current.change);
596
+ current = undefined;
597
+ }
598
+ });
599
+ current && changes.push(current.change);
600
+ return new ChangeSet(changes);
601
+ }
602
+
603
+ /**
604
+ * Iterates over a ChangeSet to check all changes have their required attributes
605
+ *
606
+ * 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.
607
+ * @param changeSet
608
+ * @param currentUser
609
+ * @param newTr
610
+ * @param schema
611
+ * @return docWasChanged, a boolean
612
+ */
613
+ function fixInconsistentChanges(changeSet, trackUserID, newTr, schema) {
614
+ const iteratedIds = new Set();
615
+ let changed = false;
616
+ changeSet.invalidChanges.forEach((c) => {
617
+ const { id, userID, operation, status, createdAt } = c.attrs;
618
+ const newAttrs = {
619
+ ...((!id || iteratedIds.has(id) || id.length === 0) && { id: uuidv4() }),
620
+ ...(!userID && { userID: trackUserID }),
621
+ ...(!operation && { operation: CHANGE_OPERATION.insert }),
622
+ ...(!status && { status: CHANGE_STATUS.pending }),
623
+ ...(!createdAt && { createdAt: Date.now() }),
624
+ };
625
+ if (Object.keys(newAttrs).length > 0) {
626
+ updateChangeAttrs(newTr, c, { ...c.attrs, ...newAttrs }, schema);
627
+ changed = true;
628
+ }
629
+ iteratedIds.add(newAttrs.id || id);
630
+ });
631
+ return changed;
632
+ }
633
+
634
+ /*!
635
+ * © 2021 Atypon Systems LLC
636
+ *
637
+ * Licensed under the Apache License, Version 2.0 (the "License");
638
+ * you may not use this file except in compliance with the License.
639
+ * You may obtain a copy of the License at
640
+ *
641
+ * http://www.apache.org/licenses/LICENSE-2.0
642
+ *
643
+ * Unless required by applicable law or agreed to in writing, software
644
+ * distributed under the License is distributed on an "AS IS" BASIS,
645
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
646
+ * See the License for the specific language governing permissions and
647
+ * limitations under the License.
648
+ */
649
+ function markInlineNodeChange(node, newTrackAttrs, schema) {
650
+ const filtered = node.marks.filter((m) => m.type !== schema.marks.tracked_insert && m.type !== schema.marks.tracked_delete);
651
+ const mark = newTrackAttrs.operation === CHANGE_OPERATION.insert
652
+ ? schema.marks.tracked_insert
653
+ : schema.marks.tracked_delete;
654
+ const createdMark = mark.create({
655
+ dataTracked: addTrackIdIfDoesntExist(newTrackAttrs),
656
+ });
657
+ return node.mark(filtered.concat(createdMark));
658
+ }
659
+ function recurseNodeContent(node, newTrackAttrs, schema) {
660
+ if (node.isText) {
661
+ return markInlineNodeChange(node, newTrackAttrs, schema);
662
+ }
663
+ else if (node.isBlock || node.isInline) {
664
+ const updatedChildren = [];
665
+ node.content.forEach((child) => {
666
+ updatedChildren.push(recurseNodeContent(child, newTrackAttrs, schema));
667
+ });
668
+ return node.type.create({
669
+ ...node.attrs,
670
+ dataTracked: addTrackIdIfDoesntExist(newTrackAttrs),
671
+ }, Fragment.fromArray(updatedChildren), node.marks);
672
+ }
673
+ else {
674
+ log.error(`unhandled node type: "${node.type.name}"`, node);
675
+ return node;
676
+ }
677
+ }
678
+ function setFragmentAsInserted(inserted, insertAttrs, schema) {
679
+ // Recurse the content in the inserted slice and either mark it tracked_insert or set node attrs
680
+ const updatedInserted = [];
681
+ inserted.forEach((n) => {
682
+ updatedInserted.push(recurseNodeContent(n, insertAttrs, schema));
683
+ });
684
+ return updatedInserted.length === 0 ? inserted : Fragment.fromArray(updatedInserted);
685
+ }
686
+
687
+ /*!
688
+ * © 2021 Atypon Systems LLC
689
+ *
690
+ * Licensed under the Apache License, Version 2.0 (the "License");
691
+ * you may not use this file except in compliance with the License.
692
+ * You may obtain a copy of the License at
693
+ *
694
+ * http://www.apache.org/licenses/LICENSE-2.0
695
+ *
696
+ * Unless required by applicable law or agreed to in writing, software
697
+ * distributed under the License is distributed on an "AS IS" BASIS,
698
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
699
+ * See the License for the specific language governing permissions and
700
+ * limitations under the License.
701
+ */
702
+ function createNewInsertAttrs(attrs) {
703
+ return {
704
+ ...attrs,
705
+ operation: CHANGE_OPERATION.insert,
706
+ };
707
+ }
708
+ function createNewDeleteAttrs(attrs) {
709
+ return {
710
+ ...attrs,
711
+ operation: CHANGE_OPERATION.delete,
712
+ };
713
+ }
714
+
715
+ /*!
716
+ * © 2021 Atypon Systems LLC
717
+ *
718
+ * Licensed under the Apache License, Version 2.0 (the "License");
719
+ * you may not use this file except in compliance with the License.
720
+ * You may obtain a copy of the License at
721
+ *
722
+ * http://www.apache.org/licenses/LICENSE-2.0
723
+ *
724
+ * Unless required by applicable law or agreed to in writing, software
725
+ * distributed under the License is distributed on an "AS IS" BASIS,
726
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
727
+ * See the License for the specific language governing permissions and
728
+ * limitations under the License.
729
+ */
730
+ /**
731
+ * Recurses node children and returns the merged first/last node's content and the unmerged children
732
+ *
733
+ * For example when merging two blockquotes:
734
+ * <bq><p>old|</p></bq>...| + [<bq><p>] inserted</p><p>2nd p</p></bq> -> <bq><p>old inserted</p><p>2nd p</p></bq>
735
+ * The extracted merged and unmerged content from the insertSlice are:
736
+ * {
737
+ * mergedNodeContent: <text> inserted</text>
738
+ * unmergedContent: [<p>2nd p</p>]
739
+ * }
740
+ * @param node
741
+ * @param currentDepth
742
+ * @param depth
743
+ * @param first
744
+ * @returns
745
+ */
746
+ function getMergedNode(node, currentDepth, depth, first) {
747
+ if (currentDepth === depth) {
748
+ return {
749
+ mergedNodeContent: node.content,
750
+ unmergedContent: undefined,
751
+ };
752
+ }
753
+ const result = [];
754
+ let merged = Fragment.empty;
755
+ node.content.forEach((n, _, i) => {
756
+ if ((first && i === 0) || (!first && i === node.childCount - 1)) {
757
+ const { mergedNodeContent, unmergedContent } = getMergedNode(n, currentDepth + 1, depth, first);
758
+ merged = mergedNodeContent;
759
+ if (unmergedContent) {
760
+ result.push(...unmergedContent.content);
761
+ }
762
+ }
763
+ else {
764
+ result.push(n);
765
+ }
766
+ });
767
+ return {
768
+ mergedNodeContent: merged,
769
+ unmergedContent: result.length > 0 ? Fragment.fromArray(result) : undefined,
770
+ };
771
+ }
772
+ /**
773
+ * Filters merged nodes from an open insertSlice to manually merge them to prevent unwanted deletions
774
+ *
775
+ * So instead of joining the slice by its open sides, possibly deleting previous nodes, we can push the
776
+ * changed content manually inside the merged nodes.
777
+ * Eg. instead of doing `|<p>asdf</p><p>|bye</p>` automatically, we extract the merged nodes first:
778
+ * {
779
+ * updatedSliceNodes: [<p>asdf</p>],
780
+ * firstMergedNode: <p>bye</p>,
781
+ * lastMergedNode: undefined,
782
+ * }
783
+ * @param insertSlice inserted slice
784
+ */
785
+ function splitSliceIntoMergedParts(insertSlice, mergeEqualSides = false) {
786
+ const { openStart, openEnd, content: { firstChild, lastChild, content: nodes }, } = insertSlice;
787
+ let updatedSliceNodes = nodes;
788
+ const mergeSides = openStart !== openEnd || mergeEqualSides;
789
+ const firstMergedNode = openStart > 0 && mergeSides && firstChild
790
+ ? getMergedNode(firstChild, 1, openStart, true)
791
+ : undefined;
792
+ const lastMergedNode = openEnd > 0 && mergeSides && lastChild ? getMergedNode(lastChild, 1, openEnd, false) : undefined;
793
+ if (firstMergedNode) {
794
+ updatedSliceNodes = updatedSliceNodes.slice(1);
795
+ if (firstMergedNode.unmergedContent) {
796
+ updatedSliceNodes = [...firstMergedNode.unmergedContent.content, ...updatedSliceNodes];
797
+ }
798
+ }
799
+ if (lastMergedNode) {
800
+ updatedSliceNodes = updatedSliceNodes.slice(0, -1);
801
+ if (lastMergedNode.unmergedContent) {
802
+ updatedSliceNodes = [...updatedSliceNodes, ...lastMergedNode.unmergedContent.content];
803
+ }
804
+ }
805
+ return {
806
+ updatedSliceNodes,
807
+ firstMergedNode,
808
+ lastMergedNode,
809
+ };
810
+ }
811
+ /**
812
+ * Deletes inserted text directly, otherwise wraps it with tracked_delete mark
813
+ *
814
+ * This would work for general inline nodes too, but since node marks don't work properly
815
+ * with Yjs, attributes are used instead.
816
+ * @param node
817
+ * @param pos
818
+ * @param newTr
819
+ * @param schema
820
+ * @param deleteAttrs
821
+ * @param from
822
+ * @param to
823
+ */
824
+ function deleteTextIfInserted(node, pos, newTr, schema, deleteAttrs, from, to) {
825
+ const start = from ? Math.max(pos, from) : pos;
826
+ const nodeEnd = pos + node.nodeSize;
827
+ const end = to ? Math.min(nodeEnd, to) : nodeEnd;
828
+ if (node.marks.find((m) => m.type === schema.marks.tracked_insert)) {
829
+ // Math.max(pos, from) is for picking always the start of the node,
830
+ // not the start of the change (which might span multiple nodes).
831
+ // Pos can be less than from as nodesBetween iterates through all nodes starting from the top block node
832
+ newTr.replaceWith(start, end, Fragment.empty);
833
+ return start;
834
+ }
835
+ else {
836
+ const leftNode = newTr.doc.resolve(start).nodeBefore;
837
+ const leftMarks = getMergeableMarkTrackedAttrs(leftNode, deleteAttrs, schema);
838
+ const rightNode = newTr.doc.resolve(end).nodeAfter;
839
+ const rightMarks = getMergeableMarkTrackedAttrs(rightNode, deleteAttrs, schema);
840
+ const fromStartOfMark = start - (leftNode && leftMarks ? leftNode.nodeSize : 0);
841
+ const toEndOfMark = end + (rightNode && rightMarks ? rightNode.nodeSize : 0);
842
+ const dataTracked = addTrackIdIfDoesntExist({
843
+ ...leftMarks,
844
+ ...rightMarks,
845
+ ...deleteAttrs,
846
+ });
847
+ newTr.addMark(fromStartOfMark, toEndOfMark, schema.marks.tracked_delete.create({
848
+ dataTracked,
849
+ }));
850
+ return toEndOfMark;
851
+ }
852
+ }
853
+ /**
854
+ * Deletes inserted block or inline node, otherwise adds `dataTracked` object with CHANGE_STATUS 'deleted'
855
+ * @param node
856
+ * @param pos
857
+ * @param newTr
858
+ * @param deleteAttrs
859
+ */
860
+ function deleteOrSetNodeDeleted(node, pos, newTr, deleteAttrs) {
861
+ const dataTracked = node.attrs.dataTracked;
862
+ const wasInsertedBySameUser = (dataTracked === null || dataTracked === void 0 ? void 0 : dataTracked.operation) === CHANGE_OPERATION.insert && dataTracked.userID === deleteAttrs.userID;
863
+ if (wasInsertedBySameUser) {
864
+ deleteNode(node, pos, newTr);
865
+ }
866
+ else {
867
+ const attrs = {
868
+ ...node.attrs,
869
+ dataTracked: addTrackIdIfDoesntExist(deleteAttrs),
870
+ };
871
+ newTr.setNodeMarkup(pos, undefined, attrs, node.marks);
872
+ }
873
+ }
874
+ /**
875
+ * Applies deletion to the doc without actually deleting nodes that have not been inserted
876
+ *
877
+ * The hairiest part of this whole library which does a fair bit of magic to split the inserted slice
878
+ * into pieces that can be inserted without deleting nodes in the doc. Basically we first split the
879
+ * inserted slice into merged pieces _if_ the slice was open on either end. Then, we iterate over the deleted
880
+ * range and see if the node in question was completely wrapped in the range (therefore fully deleted)
881
+ * or only partially deleted by the slice. In that case, we merge the content from the inserted slice
882
+ * and keep the original nodes if they do not contain insert attributes.
883
+ *
884
+ * It is definitely a messy function but so far this seems to have been the best approach to prevent
885
+ * deletion of nodes with open slices. Other option would be to allow the deletions to take place but that
886
+ * requires then inserting the deleted nodes back to the doc if their deletion should be prevented, which does
887
+ * not seem trivial either.
888
+ *
889
+ * @param from start of the deleted range
890
+ * @param to end of the deleted range
891
+ * @param gap retained content in a ReplaceAroundStep, not deleted
892
+ * @param startDoc doc before the deletion
893
+ * @param newTr the new track transaction
894
+ * @param schema ProseMirror schema
895
+ * @param deleteAttrs attributes for the dataTracked object
896
+ * @param insertSlice the inserted slice from ReplaceStep
897
+ * @returns mapping adjusted by the applied operations & modified insert slice
898
+ */
899
+ function deleteAndMergeSplitNodes(from, to, gap, startDoc, newTr, schema, trackAttrs, insertSlice) {
900
+ const deleteMap = new Mapping();
901
+ const mergedInsertPos = undefined;
902
+ // No deletion applied, return default values
903
+ if (from === to) {
904
+ return {
905
+ deleteMap,
906
+ mergedInsertPos,
907
+ newSliceContent: insertSlice.content,
908
+ };
909
+ }
910
+ const { openStart, openEnd } = insertSlice;
911
+ const { updatedSliceNodes, firstMergedNode, lastMergedNode } = splitSliceIntoMergedParts(insertSlice, gap !== undefined);
912
+ const deleteAttrs = createNewDeleteAttrs(trackAttrs);
913
+ let mergingStartSide = true;
914
+ startDoc.nodesBetween(from, to, (node, pos) => {
915
+ const { pos: offsetPos, deleted: nodeWasDeleted } = deleteMap.mapResult(pos, 1);
916
+ const offsetFrom = deleteMap.map(from, -1);
917
+ const offsetTo = deleteMap.map(to, 1);
918
+ const wasWithinGap = gap && offsetPos >= deleteMap.map(gap.start, -1);
919
+ const nodeEnd = offsetPos + node.nodeSize;
920
+ let step = newTr.steps[newTr.steps.length - 1];
921
+ // debugger
922
+ // nodeEnd > offsetFrom -> delete touches this node
923
+ // eg (del 6 10) <p 5>|<t 6>cdf</t 9></p 10>| -> <p> nodeEnd 10 > from 6
924
+ //
925
+ // !nodeWasDeleted -> Check node wasn't already deleted by a previous deleteNode
926
+ // This is quite tricky to wrap your head around and I've forgotten the nitty-gritty details already.
927
+ // But from what I remember what it safeguards against is, when you've already deleted a node
928
+ // say an inserted blockquote that had all its children deleted, nodesBetween still iterates over those
929
+ // nodes and therefore we have to make this check to ensure they still exist in the doc.
930
+ if (nodeEnd > offsetFrom && !nodeWasDeleted && !wasWithinGap) {
931
+ // |<p>asdf</p>| -> node deleted completely
932
+ const nodeCompletelyDeleted = offsetPos >= offsetFrom && nodeEnd <= offsetTo;
933
+ // The end token deleted eg:
934
+ // <p 1>asdf|</p 7><p 7>bye</p 12>| + [<p>]hello</p> -> <p>asdfhello</p>
935
+ // (del 6 12) + (ins [<p>]hello</p> openStart 1 openEnd 0)
936
+ // (<p> nodeEnd 7) > (from 6) && (nodeEnd 7) <= (to 12)
937
+ //
938
+ // How about
939
+ // <p 1>asdf|</p 7><p 7>|bye</p 12> + [<p>]hello</p><p>good[</p>] -> <p>asdfhello</p><p>goodbye</p>
940
+ //
941
+ // What about:
942
+ // <p 1>asdf|</p 7><p 7 op="inserted">|bye</p 12> + empty -> <p>asdfbye</p>
943
+ const endTokenDeleted = nodeEnd <= offsetTo;
944
+ // The start token deleted eg:
945
+ // |<p1 0>hey</p 6><p2 6>|asdf</p 12> + <p3>hello [</p>] -> <p3>hello asdf</p2>
946
+ // (del 0 7) + (ins <p>hello [</p>] openStart 0 openEnd 1)
947
+ // (<p1> pos 0) >= (from 0) && (nodeEnd 6) - 1 > (to 7) == false???
948
+ // (<p2> pos 6) >= (from 0) && (nodeEnd 12) - 1 > (to 7) == true
949
+ //
950
+ const startTokenDeleted = offsetPos >= offsetFrom; // && nodeEnd - 1 > offsetTo
951
+ if (node.isText ||
952
+ (!endTokenDeleted && startTokenDeleted) ||
953
+ (endTokenDeleted && !startTokenDeleted)) {
954
+ // Since we don't know which side to merge with wholly deleted TextNodes, we use this boolean to remember
955
+ // whether we have entered the endSide of the mergeable blockNodes. Also applies for partial TextNodes
956
+ // (which we could determine without this).
957
+ if (!endTokenDeleted && startTokenDeleted) {
958
+ mergingStartSide = false;
959
+ }
960
+ // Depth is often 1 when merging paragraphs or 2 for fully open blockquotes.
961
+ // Incase of merging text within a ReplaceAroundStep the depth might be 1
962
+ const depth = newTr.doc.resolve(offsetPos).depth;
963
+ const mergeContent = mergingStartSide
964
+ ? firstMergedNode === null || firstMergedNode === void 0 ? void 0 : firstMergedNode.mergedNodeContent
965
+ : lastMergedNode === null || lastMergedNode === void 0 ? void 0 : lastMergedNode.mergedNodeContent;
966
+ // Insert inside a merged node only if the slice was open (openStart > 0) and there exists mergedNodeContent.
967
+ // Then we only have to ensure the depth is at the right level, so say a fully open blockquote insert will
968
+ // be merged at the lowest, paragraph level, instead of blockquote level.
969
+ const mergeStartNode = endTokenDeleted && openStart > 0 && depth === openStart && mergeContent !== undefined;
970
+ // Same as above, merge nodes manually if there exists an open slice with mergeable content.
971
+ // Compared to deleting an end token however, the merged block node is set as deleted. This is due to
972
+ // ProseMirror node semantics as start tokens are considered to contain the actual node itself.
973
+ const mergeEndNode = startTokenDeleted && openEnd > 0 && depth === openEnd && mergeContent !== undefined;
974
+ if (mergeStartNode || mergeEndNode) {
975
+ // The default insert position for block nodes is either the start of the merged content or the end.
976
+ // Incase text was merged, this must be updated as the start or end of the node doesn't map to the
977
+ // actual position of the merge. Currently the inserted content is inserted at the start or end
978
+ // of the merged content, TODO reverse the start/end when end/start token?
979
+ let insertPos = mergeStartNode ? nodeEnd - openStart : offsetPos + openEnd;
980
+ if (node.isText) {
981
+ // When merging text we must delete text in the same go as well, as the from/to boundary goes through
982
+ // the text node.
983
+ insertPos = deleteTextIfInserted(node, offsetPos, newTr, schema, deleteAttrs, offsetFrom, offsetTo);
984
+ deleteMap.appendMap(newTr.steps[newTr.steps.length - 1].getMap());
985
+ step = newTr.steps[newTr.steps.length - 1];
986
+ }
987
+ // Just as a fun fact that I found out while debugging this. Inserting text at paragraph position wraps
988
+ // it into a new paragraph(!). So that's why you always offset your positions to insert it _inside_
989
+ // the paragraph.
990
+ if (mergeContent.size !== 0) {
991
+ newTr.insert(insertPos, setFragmentAsInserted(mergeContent, createNewInsertAttrs(trackAttrs), schema));
992
+ }
993
+ // Okay this is a bit ridiculous but it's used to adjust the insert pos when track changes prevents deletions
994
+ // of merged nodes & content, as just using mapped toA in that case isn't the same.
995
+ // The calculation is a bit mysterious, I admit.
996
+ // TODO delete/fix this?
997
+ // 'should prevent replacing of blockquotes and break the slice into parts instead' test needs this
998
+ // if (node.isText) {
999
+ // mergedInsertPos = offsetPos - openEnd
1000
+ // }
1001
+ }
1002
+ else if (node.isText) {
1003
+ // Text deletion is handled even when the deletion doesn't completely wrap the text node
1004
+ // (which is basically the case most of the time)
1005
+ deleteTextIfInserted(node, offsetPos, newTr, schema, deleteAttrs, offsetFrom, offsetTo);
1006
+ }
1007
+ else ;
1008
+ }
1009
+ else if (nodeCompletelyDeleted) {
1010
+ deleteOrSetNodeDeleted(node, offsetPos, newTr, deleteAttrs);
1011
+ }
1012
+ }
1013
+ const newestStep = newTr.steps[newTr.steps.length - 1];
1014
+ if (step !== newestStep) {
1015
+ deleteMap.appendMap(newestStep.getMap());
1016
+ }
1017
+ });
1018
+ return {
1019
+ deleteMap,
1020
+ mergedInsertPos,
1021
+ newSliceContent: updatedSliceNodes
1022
+ ? Fragment.fromArray(updatedSliceNodes)
1023
+ : insertSlice.content,
1024
+ };
1025
+ }
1026
+
1027
+ /**
1028
+ * Merges tracked marks between text nodes at a position
1029
+ *
1030
+ * Will work for any nodes that use tracked_insert or tracked_delete marks which may not be preferrable
1031
+ * if used for block nodes (since we possibly want to show the individual changed nodes).
1032
+ * Merging is done based on the userID, operation type and status.
1033
+ * @param pos
1034
+ * @param doc
1035
+ * @param newTr
1036
+ * @param schema
1037
+ */
1038
+ function mergeTrackedMarks(pos, doc, newTr, schema) {
1039
+ const resolved = doc.resolve(pos);
1040
+ const { nodeAfter, nodeBefore } = resolved;
1041
+ 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];
1042
+ 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];
1043
+ if (!nodeAfter || !nodeBefore || !leftMark || !rightMark || leftMark.type !== rightMark.type) {
1044
+ return;
1045
+ }
1046
+ const leftAttrs = leftMark.attrs;
1047
+ const rightAttrs = rightMark.attrs;
1048
+ if (!shouldMergeTrackedAttributes(leftAttrs.dataTracked, rightAttrs.dataTracked)) {
1049
+ return;
1050
+ }
1051
+ const newAttrs = {
1052
+ ...leftAttrs,
1053
+ createdAt: Math.max(leftAttrs.createdAt || 0, rightAttrs.createdAt || 0) || Date.now(),
1054
+ };
1055
+ const fromStartOfMark = pos - nodeBefore.nodeSize;
1056
+ const toEndOfMark = pos + nodeAfter.nodeSize;
1057
+ newTr.addMark(fromStartOfMark, toEndOfMark, leftMark.type.create(newAttrs));
1058
+ }
1059
+
1060
+ /*!
1061
+ * © 2021 Atypon Systems LLC
1062
+ *
1063
+ * Licensed under the Apache License, Version 2.0 (the "License");
1064
+ * you may not use this file except in compliance with the License.
1065
+ * You may obtain a copy of the License at
1066
+ *
1067
+ * http://www.apache.org/licenses/LICENSE-2.0
1068
+ *
1069
+ * Unless required by applicable law or agreed to in writing, software
1070
+ * distributed under the License is distributed on an "AS IS" BASIS,
1071
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1072
+ * See the License for the specific language governing permissions and
1073
+ * limitations under the License.
1074
+ */
1075
+ function trackReplaceAroundStep(step, oldState, newTr, attrs) {
1076
+ log.info('###### ReplaceAroundStep ######');
1077
+ // @ts-ignore
1078
+ const { from, to, gapFrom, gapTo, insert, slice, structure, } = step;
1079
+ if (from === gapFrom && to === gapTo) {
1080
+ log.info('WRAPPED IN SOMETHING');
1081
+ }
1082
+ else if (!slice.size || slice.content.content.length === 2) {
1083
+ log.info('UNWRAPPED FROM SOMETHING');
1084
+ }
1085
+ else if (slice.size === 2 && gapFrom - from === 1 && to - gapTo === 1) {
1086
+ log.info('REPLACED WRAPPING');
1087
+ }
1088
+ else {
1089
+ log.info('????');
1090
+ }
1091
+ if (gapFrom - from > to - gapTo) {
1092
+ log.info('DELETED BEFORE GAP FROM');
1093
+ }
1094
+ else if (gapFrom - from < to - gapTo) {
1095
+ log.info('DELETED AFTER GAP TO');
1096
+ }
1097
+ else {
1098
+ log.info('EQUAL REPLACE BETWEEN GAPS');
1099
+ }
1100
+ // Invert the transaction step to prevent it from actually deleting or inserting anything
1101
+ const newStep = step.invert(oldState.doc);
1102
+ const stepResult = newTr.maybeStep(newStep);
1103
+ if (stepResult.failed) {
1104
+ log.error(`inverting ReplaceAroundStep failed: "${stepResult.failed}"`, newStep);
1105
+ return;
1106
+ }
1107
+ const gap = oldState.doc.slice(gapFrom, gapTo);
1108
+ log.info('RETAINED GAP CONTENT', gap);
1109
+ // First apply the deleted range and update the insert slice to not include content that was deleted,
1110
+ // eg partial nodes in an open-ended slice
1111
+ const { deleteMap, newSliceContent } = deleteAndMergeSplitNodes(from, to, { start: gapFrom, end: gapTo }, newTr.doc, newTr, oldState.schema, attrs, slice);
1112
+ log.info('TR: new steps after applying delete', [...newTr.steps]);
1113
+ // We only want to insert when there something inside the gap (actually would this be always true?)
1114
+ // or insert slice wasn't just start/end tokens (which we already merged inside deleteAndMergeSplitBlockNodes)
1115
+ if (gap.size > 0 || (!structure && newSliceContent.size > 0)) {
1116
+ log.info('newSliceContent', newSliceContent);
1117
+ // Since deleteAndMergeSplitBlockNodes modified the slice to not to contain any merged nodes,
1118
+ // the sides should be equal. TODO can they be other than 0?
1119
+ const openStart = slice.openStart !== slice.openEnd || newSliceContent.size === 0 ? 0 : slice.openStart;
1120
+ const openEnd = slice.openStart !== slice.openEnd || newSliceContent.size === 0 ? 0 : slice.openEnd;
1121
+ let insertedSlice = new Slice(setFragmentAsInserted(newSliceContent, createNewInsertAttrs(attrs), oldState.schema), openStart, openEnd);
1122
+ if (gap.size > 0) {
1123
+ log.info('insertedSlice before inserted gap', insertedSlice);
1124
+ insertedSlice = insertedSlice.insertAt(insertedSlice.size === 0 ? 0 : insert, gap.content);
1125
+ log.info('insertedSlice after inserted gap', insertedSlice);
1126
+ }
1127
+ const newStep = new ReplaceStep(deleteMap.map(gapFrom), deleteMap.map(gapTo), insertedSlice, false);
1128
+ const stepResult = newTr.maybeStep(newStep);
1129
+ if (stepResult.failed) {
1130
+ log.error(`insert ReplaceStep failed: "${stepResult.failed}"`, newStep);
1131
+ return;
1132
+ }
1133
+ log.info('new steps after applying insert', [...newTr.steps]);
1134
+ mergeTrackedMarks(deleteMap.map(gapFrom), newTr.doc, newTr, oldState.schema);
1135
+ mergeTrackedMarks(deleteMap.map(gapTo), newTr.doc, newTr, oldState.schema);
1136
+ }
1137
+ else {
1138
+ // Incase only deletion was applied, check whether tracked marks around deleted content can be merged
1139
+ mergeTrackedMarks(deleteMap.map(gapFrom), newTr.doc, newTr, oldState.schema);
1140
+ mergeTrackedMarks(deleteMap.map(gapTo), newTr.doc, newTr, oldState.schema);
1141
+ }
1142
+ }
1143
+
1144
+ /*!
1145
+ * © 2021 Atypon Systems LLC
1146
+ *
1147
+ * Licensed under the Apache License, Version 2.0 (the "License");
1148
+ * you may not use this file except in compliance with the License.
1149
+ * You may obtain a copy of the License at
1150
+ *
1151
+ * http://www.apache.org/licenses/LICENSE-2.0
1152
+ *
1153
+ * Unless required by applicable law or agreed to in writing, software
1154
+ * distributed under the License is distributed on an "AS IS" BASIS,
1155
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1156
+ * See the License for the specific language governing permissions and
1157
+ * limitations under the License.
1158
+ */
1159
+ function trackReplaceStep(step, oldState, newTr, attrs) {
1160
+ log.info('###### ReplaceStep ######');
1161
+ let selectionPos = 0;
1162
+ step.getMap().forEach((fromA, toA, fromB, toB) => {
1163
+ log.info(`changed ranges: ${fromA} ${toA} ${fromB} ${toB}`);
1164
+ const { slice } = step;
1165
+ // Invert the transaction step to prevent it from actually deleting or inserting anything
1166
+ const newStep = step.invert(oldState.doc);
1167
+ const stepResult = newTr.maybeStep(newStep);
1168
+ if (stepResult.failed) {
1169
+ log.error(`invert ReplaceStep failed: "${stepResult.failed}"`, newStep);
1170
+ return;
1171
+ }
1172
+ // First apply the deleted range and update the insert slice to not include content that was deleted,
1173
+ // eg partial nodes in an open-ended slice
1174
+ const { deleteMap, mergedInsertPos, newSliceContent } = deleteAndMergeSplitNodes(fromA, toA, undefined, oldState.doc, newTr, oldState.schema, attrs, slice);
1175
+ log.info('TR: new steps after applying delete', [...newTr.steps]);
1176
+ const adjustedInsertPos = mergedInsertPos !== null && mergedInsertPos !== void 0 ? mergedInsertPos : deleteMap.map(toA);
1177
+ if (newSliceContent.size > 0) {
1178
+ log.info('newSliceContent', newSliceContent);
1179
+ // Since deleteAndMergeSplitBlockNodes modified the slice to not to contain any merged nodes,
1180
+ // the sides should be equal. TODO can they be other than 0?
1181
+ const openStart = slice.openStart !== slice.openEnd ? 0 : slice.openStart;
1182
+ const openEnd = slice.openStart !== slice.openEnd ? 0 : slice.openEnd;
1183
+ const insertedSlice = new Slice(setFragmentAsInserted(newSliceContent, createNewInsertAttrs(attrs), oldState.schema), openStart, openEnd);
1184
+ const newStep = new ReplaceStep(adjustedInsertPos, adjustedInsertPos, insertedSlice);
1185
+ const stepResult = newTr.maybeStep(newStep);
1186
+ if (stepResult.failed) {
1187
+ log.error(`insert ReplaceStep failed: "${stepResult.failed}"`, newStep);
1188
+ return;
1189
+ }
1190
+ log.info('new steps after applying insert', [...newTr.steps]);
1191
+ mergeTrackedMarks(adjustedInsertPos, newTr.doc, newTr, oldState.schema);
1192
+ mergeTrackedMarks(adjustedInsertPos + insertedSlice.size, newTr.doc, newTr, oldState.schema);
1193
+ selectionPos = adjustedInsertPos + insertedSlice.size;
1194
+ }
1195
+ else {
1196
+ // Incase only deletion was applied, check whether tracked marks around deleted content can be merged
1197
+ mergeTrackedMarks(adjustedInsertPos, newTr.doc, newTr, oldState.schema);
1198
+ selectionPos = fromA;
1199
+ }
1200
+ });
1201
+ return selectionPos;
1202
+ }
1203
+
1204
+ /**
1205
+ * Retrieves a static property from Selection class instead of having to use direct imports
1206
+ *
1207
+ * This skips the direct dependency to prosemirror-state where multiple versions might cause conflicts
1208
+ * as the created instances might belong to different prosemirror-state import than one used in the editor.
1209
+ * @param sel
1210
+ * @param doc
1211
+ * @param from
1212
+ * @returns
1213
+ */
1214
+ const getSelectionStaticCreate = (sel, doc, from) => Object.getPrototypeOf(sel).constructor.create(doc, from);
1215
+ /**
1216
+ * Inverts transactions to wrap their contents/operations with track data instead
1217
+ *
1218
+ * The main function of track changes that holds the most complex parts of this whole library.
1219
+ * Takes in as arguments the data from appendTransaction to reapply it with the track marks/attributes.
1220
+ * We could prevent the initial transaction from being applied all together but since invert works just
1221
+ * as well and we can use the intermediate doc for checking which nodes are changed, it's not prevented.
1222
+ *
1223
+ *
1224
+ * @param tr Original transaction
1225
+ * @param oldState State before transaction
1226
+ * @param newTr Transaction created from the new editor state
1227
+ * @param userID User id
1228
+ * @returns newTr that inverts the initial tr and applies track attributes/marks
1229
+ */
1230
+ function trackTransaction(tr, oldState, newTr, userID) {
1231
+ var _a;
1232
+ const emptyAttrs = {
1233
+ userID,
1234
+ createdAt: tr.time,
1235
+ status: CHANGE_STATUS.pending,
1236
+ };
1237
+ // Must use constructor.name instead of instanceof as aliasing prosemirror-state is a lot more
1238
+ // difficult than prosemirror-transform
1239
+ const wasNodeSelection = tr.selection.constructor.name === 'NodeSelection';
1240
+ let iters = 0;
1241
+ log.info('ORIGINAL transaction', tr);
1242
+ tr.steps.forEach((step) => {
1243
+ log.info('transaction step', step);
1244
+ iters += 1;
1245
+ if (iters > 20) {
1246
+ console.error('@manuscripts/track-changes-plugin: Possible infinite loop in iterating tr.steps, tracking skipped!\n' +
1247
+ 'This is probably an error with the library, please report back to maintainers with a reproduction if possible', newTr);
1248
+ return;
1249
+ }
1250
+ else if (!(step instanceof ReplaceStep) && step.constructor.name === 'ReplaceStep') {
1251
+ console.error('@manuscripts/track-changes-plugin: Multiple prosemirror-transform packages imported, alias/dedupe them ' +
1252
+ 'or instanceof checks fail as well as creating new steps');
1253
+ return;
1254
+ }
1255
+ else if (step instanceof ReplaceStep) {
1256
+ const selectionPos = trackReplaceStep(step, oldState, newTr, emptyAttrs);
1257
+ if (!wasNodeSelection) {
1258
+ newTr.setSelection(getSelectionStaticCreate(tr.selection, newTr.doc, selectionPos));
1259
+ }
1260
+ }
1261
+ else if (step instanceof ReplaceAroundStep) {
1262
+ trackReplaceAroundStep(step, oldState, newTr, emptyAttrs);
1263
+ // } else if (step instanceof AddMarkStep) {
1264
+ // } else if (step instanceof RemoveMarkStep) {
1265
+ }
1266
+ // TODO: here we could check whether adjacent inserts & deletes cancel each other out.
1267
+ // However, this should not be done by diffing and only matching node or char by char instead since
1268
+ // it's A easier and B more intuitive to user.
1269
+ const { meta } = tr;
1270
+ // This is quite non-optimal in some sense but to ensure no information is lost
1271
+ // we have to re-add all the old meta keys, such as inputType or uiEvent.
1272
+ // This should prevent bugs incase other plugins/widgets rely upon them existing (and they
1273
+ // are not able to process the transactions before track-changes).
1274
+ // TODO: will this cause race-condition if a meta causes another appendTransaction to fire
1275
+ Object.keys(meta).forEach((key) => newTr.setMeta(key, tr.getMeta(key)));
1276
+ });
1277
+ // This is kinda hacky solution at the moment to maintain NodeSelections over transactions
1278
+ // These are required by at least cross-references that need it to activate the selector pop-up
1279
+ if (wasNodeSelection) {
1280
+ const mappedPos = newTr.mapping.map(tr.selection.from);
1281
+ const resPos = newTr.doc.resolve(mappedPos);
1282
+ const nodePos = mappedPos - (((_a = resPos.nodeBefore) === null || _a === void 0 ? void 0 : _a.nodeSize) || 0);
1283
+ newTr.setSelection(getSelectionStaticCreate(tr.selection, newTr.doc, nodePos));
1284
+ }
1285
+ log.info('NEW transaction', newTr);
1286
+ return newTr;
1287
+ }
1288
+
1289
+ var TrackChangesStatus;
1290
+ (function (TrackChangesStatus) {
1291
+ TrackChangesStatus["enabled"] = "enabled";
1292
+ TrackChangesStatus["viewSnapshots"] = "view-snapshots";
1293
+ TrackChangesStatus["disabled"] = "disabled";
1294
+ })(TrackChangesStatus || (TrackChangesStatus = {}));
1295
+
1296
+ /*!
1297
+ * © 2021 Atypon Systems LLC
1298
+ *
1299
+ * Licensed under the Apache License, Version 2.0 (the "License");
1300
+ * you may not use this file except in compliance with the License.
1301
+ * You may obtain a copy of the License at
1302
+ *
1303
+ * http://www.apache.org/licenses/LICENSE-2.0
1304
+ *
1305
+ * Unless required by applicable law or agreed to in writing, software
1306
+ * distributed under the License is distributed on an "AS IS" BASIS,
1307
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1308
+ * See the License for the specific language governing permissions and
1309
+ * limitations under the License.
1310
+ */
1311
+ const trackChangesPluginKey = new PluginKey('track-changes');
1312
+ // TODO remove
1313
+ const infiniteLoopCounter = {
1314
+ start: 0,
1315
+ iters: 0,
1316
+ };
1317
+ /**
1318
+ * The ProseMirror plugin needed to enable track-changes.
1319
+ *
1320
+ * Accepts an empty options object as an argument but note that this uses 'anonymous:Anonymous' as the default userID.
1321
+ * @param opts
1322
+ */
1323
+ const trackChangesPlugin = (opts = { userID: 'anonymous:Anonymous' }) => {
1324
+ const { userID, debug, skipTrsWithMetas = [] } = opts;
1325
+ let editorView;
1326
+ if (debug) {
1327
+ enableDebug(true);
1328
+ }
1329
+ return new Plugin({
1330
+ key: trackChangesPluginKey,
1331
+ props: {
1332
+ editable(state) {
1333
+ return this.getState(state).status !== TrackChangesStatus.viewSnapshots;
1334
+ },
1335
+ },
1336
+ state: {
1337
+ init(_config, state) {
1338
+ return {
1339
+ status: TrackChangesStatus.enabled,
1340
+ userID,
1341
+ changeSet: findChanges(state),
1342
+ };
1343
+ },
1344
+ apply(tr, pluginState, _oldState, newState) {
1345
+ const setUserID = getAction(tr, TrackChangesAction.setUserID);
1346
+ const setStatus = getAction(tr, TrackChangesAction.setPluginStatus);
1347
+ if (setUserID) {
1348
+ return { ...pluginState, userID: setUserID };
1349
+ }
1350
+ else if (setStatus) {
1351
+ return {
1352
+ ...pluginState,
1353
+ status: setStatus,
1354
+ changeSet: findChanges(newState),
1355
+ };
1356
+ }
1357
+ else if (pluginState.status === TrackChangesStatus.disabled) {
1358
+ return { ...pluginState, changeSet: new ChangeSet() };
1359
+ }
1360
+ let { changeSet, ...rest } = pluginState;
1361
+ const updatedChangeIds = getAction(tr, TrackChangesAction.updateChanges);
1362
+ if (updatedChangeIds || getAction(tr, TrackChangesAction.refreshChanges)) {
1363
+ changeSet = findChanges(newState);
1364
+ }
1365
+ return {
1366
+ changeSet,
1367
+ ...rest,
1368
+ };
1369
+ },
1370
+ },
1371
+ view(p) {
1372
+ editorView = p;
1373
+ return {
1374
+ update: undefined,
1375
+ destroy: undefined,
1376
+ };
1377
+ },
1378
+ appendTransaction(trs, oldState, newState) {
1379
+ const pluginState = trackChangesPluginKey.getState(newState);
1380
+ if (!pluginState ||
1381
+ pluginState.status === TrackChangesStatus.disabled ||
1382
+ !(editorView === null || editorView === void 0 ? void 0 : editorView.editable)) {
1383
+ return null;
1384
+ }
1385
+ if (infiniteLoopCounter.start < Date.now() - 10000) {
1386
+ infiniteLoopCounter.start = Date.now();
1387
+ infiniteLoopCounter.iters = 0;
1388
+ }
1389
+ if (infiniteLoopCounter.iters >= 100) {
1390
+ console.error('Detected probable infinite loop in track changes!');
1391
+ return null;
1392
+ }
1393
+ const { userID, changeSet } = pluginState;
1394
+ let createdTr = newState.tr, docChanged = false;
1395
+ log.info('TRS', trs);
1396
+ trs.forEach((tr) => {
1397
+ const wasAppended = tr.getMeta('appendedTransaction');
1398
+ const skipMetaUsed = skipTrsWithMetas.some((m) => tr.getMeta(m) || (wasAppended === null || wasAppended === void 0 ? void 0 : wasAppended.getMeta(m)));
1399
+ const skipTrackUsed = getAction(tr, TrackChangesAction.skipTrack) ||
1400
+ (wasAppended && getAction(wasAppended, TrackChangesAction.skipTrack));
1401
+ if (tr.docChanged && !skipMetaUsed && !skipTrackUsed && !tr.getMeta('history$')) {
1402
+ createdTr = trackTransaction(tr, oldState, createdTr, userID);
1403
+ createdTr.setMeta('origin', trackChangesPluginKey);
1404
+ infiniteLoopCounter.iters += 1;
1405
+ }
1406
+ docChanged = docChanged || tr.docChanged;
1407
+ const setChangeStatuses = getAction(tr, TrackChangesAction.setChangeStatuses);
1408
+ if (setChangeStatuses) {
1409
+ const { status, ids } = setChangeStatuses;
1410
+ ids.forEach((changeId) => {
1411
+ const change = changeSet === null || changeSet === void 0 ? void 0 : changeSet.get(changeId);
1412
+ if (change) {
1413
+ createdTr = updateChangeAttrs(createdTr, change, { status }, oldState.schema);
1414
+ setAction(createdTr, TrackChangesAction.updateChanges, [change.id]);
1415
+ }
1416
+ });
1417
+ }
1418
+ else if (getAction(tr, TrackChangesAction.applyAndRemoveChanges)) {
1419
+ const mapping = applyAcceptedRejectedChanges(createdTr, oldState.schema, changeSet.nodeChanges);
1420
+ applyAcceptedRejectedChanges(createdTr, oldState.schema, changeSet.textChanges, mapping);
1421
+ setAction(createdTr, TrackChangesAction.refreshChanges, true);
1422
+ }
1423
+ });
1424
+ const changed = pluginState.changeSet.hasInconsistentData &&
1425
+ fixInconsistentChanges(pluginState.changeSet, userID, createdTr, oldState.schema);
1426
+ if (changed) {
1427
+ log.warn('had to fix inconsistent changes in', createdTr);
1428
+ }
1429
+ if (docChanged || createdTr.docChanged || changed) {
1430
+ return setAction(createdTr, TrackChangesAction.refreshChanges, true);
1431
+ }
1432
+ return null;
1433
+ },
1434
+ });
1435
+ };
1436
+
1437
+ /*!
1438
+ * © 2021 Atypon Systems LLC
1439
+ *
1440
+ * Licensed under the Apache License, Version 2.0 (the "License");
1441
+ * you may not use this file except in compliance with the License.
1442
+ * You may obtain a copy of the License at
1443
+ *
1444
+ * http://www.apache.org/licenses/LICENSE-2.0
1445
+ *
1446
+ * Unless required by applicable law or agreed to in writing, software
1447
+ * distributed under the License is distributed on an "AS IS" BASIS,
1448
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1449
+ * See the License for the specific language governing permissions and
1450
+ * limitations under the License.
1451
+ */
1452
+ /**
1453
+ * Sets track-changes plugin's status to any of: 'enabled' 'disabled' 'viewSnapshots'. Passing undefined will
1454
+ * set 'enabled' status to 'disabled' and 'disabled' | 'viewSnapshots' status to 'enabled'.
1455
+ *
1456
+ * In disabled view, the plugin is completely inactive and changes are not updated anymore.
1457
+ * In viewSnasphots state, editor is set uneditable by editable prop that allows only selection changes
1458
+ * to the document.
1459
+ * @param status
1460
+ */
1461
+ const setTrackingStatus = (status) => (state, dispatch) => {
1462
+ var _a;
1463
+ const currentStatus = (_a = trackChangesPluginKey.getState(state)) === null || _a === void 0 ? void 0 : _a.status;
1464
+ if (currentStatus) {
1465
+ let newStatus = status;
1466
+ if (newStatus === undefined) {
1467
+ newStatus =
1468
+ currentStatus === TrackChangesStatus.enabled
1469
+ ? TrackChangesStatus.disabled
1470
+ : TrackChangesStatus.enabled;
1471
+ }
1472
+ dispatch && dispatch(setAction(state.tr, TrackChangesAction.setPluginStatus, newStatus));
1473
+ return true;
1474
+ }
1475
+ return false;
1476
+ };
1477
+ /**
1478
+ * Appends a transaction to set change attributes/marks' statuses to any of: 'pending' 'accepted' 'rejected'.
1479
+ * @param status
1480
+ * @param ids
1481
+ */
1482
+ const setChangeStatuses = (status, ids) => (state, dispatch) => {
1483
+ dispatch &&
1484
+ dispatch(setAction(state.tr, TrackChangesAction.setChangeStatuses, {
1485
+ status,
1486
+ ids,
1487
+ }));
1488
+ return true;
1489
+ };
1490
+ /**
1491
+ * Sets track-changes plugin's userID.
1492
+ * @param userID
1493
+ */
1494
+ const setUserID = (userID) => (state, dispatch) => {
1495
+ dispatch && dispatch(setAction(state.tr, TrackChangesAction.setUserID, userID));
1496
+ return true;
1497
+ };
1498
+ /**
1499
+ * Appends a transaction that applies all 'accepted' and 'rejected' changes to the document.
1500
+ */
1501
+ const applyAndRemoveChanges = () => (state, dispatch) => {
1502
+ dispatch && dispatch(setAction(state.tr, TrackChangesAction.applyAndRemoveChanges, true));
1503
+ return true;
1504
+ };
1505
+ /**
1506
+ * Runs `findChanges` to iterate over the document to collect changes into a new ChangeSet.
1507
+ */
1508
+ const refreshChanges = () => (state, dispatch) => {
1509
+ dispatch && dispatch(setAction(state.tr, TrackChangesAction.updateChanges, []));
1510
+ return true;
1511
+ };
1512
+ /**
1513
+ * Adds track attributes for a block node. For testing puroses
1514
+ */
1515
+ const setParagraphTestAttribute = (val = 'changed') => (state, dispatch) => {
1516
+ var _a;
1517
+ const cursor = state.selection.head;
1518
+ const blockNodePos = state.doc.resolve(cursor).start(1) - 1;
1519
+ if (((_a = state.doc.resolve(blockNodePos).nodeAfter) === null || _a === void 0 ? void 0 : _a.type) === state.schema.nodes.paragraph &&
1520
+ dispatch) {
1521
+ dispatch(state.tr.setNodeMarkup(blockNodePos, undefined, {
1522
+ testAttribute: val,
1523
+ }));
1524
+ return true;
1525
+ }
1526
+ return false;
1527
+ };
1528
+
1529
+ var commands = /*#__PURE__*/Object.freeze({
1530
+ __proto__: null,
1531
+ setTrackingStatus: setTrackingStatus,
1532
+ setChangeStatuses: setChangeStatuses,
1533
+ setUserID: setUserID,
1534
+ applyAndRemoveChanges: applyAndRemoveChanges,
1535
+ refreshChanges: refreshChanges,
1536
+ setParagraphTestAttribute: setParagraphTestAttribute
1537
+ });
1538
+
1539
+ export { CHANGE_OPERATION, CHANGE_STATUS, ChangeSet, TrackChangesAction, TrackChangesStatus, enableDebug, getAction, setAction, trackChangesPlugin, trackChangesPluginKey, commands as trackCommands };