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