@manuscripts/track-changes-plugin 0.0.4 → 0.3.0

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