-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathtrackChangesHelpers.test.js
More file actions
735 lines (617 loc) · 26.4 KB
/
trackChangesHelpers.test.js
File metadata and controls
735 lines (617 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import { EditorState, TextSelection } from 'prosemirror-state';
import { AddMarkStep, RemoveMarkStep } from 'prosemirror-transform';
import { Node as ProseMirrorNode } from 'prosemirror-model';
import { undo } from 'prosemirror-history';
import { ySyncPluginKey } from 'y-prosemirror';
import { TrackInsertMarkName, TrackDeleteMarkName, TrackFormatMarkName } from '../constants.js';
import {
markInsertion,
markDeletion,
addMarkStep,
removeMarkStep,
trackedTransaction,
parseFormatList,
getTrackChanges,
findTrackedMarkBetween,
markWrapping,
replaceAroundStep,
documentHelpers,
} from './index.js';
import { TrackChangesBasePluginKey } from '../plugins/trackChangesBasePlugin.js';
import { CommentsPluginKey } from '../../comment/comments-plugin.js';
import { handleTrackChangeNode } from '@converter/v2/importer/trackChangesImporter.js';
import { defaultNodeListHandler } from '@converter/v2/importer/docxImporter.js';
import { parseXmlToJson } from '@converter/v2/docxHelper.js';
import { initTestEditor } from '@tests/helpers/helpers.js';
import { findTextPos } from './testUtils.js';
describe('trackChangesHelpers', () => {
let editor;
let schema;
let basePlugins;
const user = { name: 'Track Tester', email: 'track@example.com' };
const date = '2024-01-01T00:00:00.000Z';
beforeEach(() => {
({ editor } = initTestEditor({ mode: 'text', content: '<p></p>' }));
schema = editor.schema;
basePlugins = editor.state.plugins;
});
afterEach(() => {
vi.restoreAllMocks();
editor?.destroy();
editor = null;
});
const createDocWithText = (text, marks = []) => {
const paragraph = schema.nodes.paragraph.create({}, schema.nodes.run.create({}, schema.text(text, marks)));
return schema.nodes.doc.create({}, paragraph);
};
const createState = (doc) =>
EditorState.create({
schema,
doc,
plugins: basePlugins,
});
it('findMarkPosition returns full mark span', () => {
const mark = schema.marks[TrackInsertMarkName].create({
id: 'ins-1',
author: user.name,
authorEmail: user.email,
date,
});
const doc = createDocWithText('abc', [mark]);
const result = documentHelpers.findMarkPosition(doc, 2, TrackInsertMarkName);
expect(result).toEqual(
expect.objectContaining({
from: 2,
to: 5,
attrs: expect.objectContaining({ id: 'ins-1' }),
}),
);
});
it('document helper utilities validate input and traversal', () => {
const doc = createDocWithText('abc');
expect(() => documentHelpers.flatten(null)).toThrow('Invalid "node" parameter');
expect(() => documentHelpers.findChildren(doc, null)).toThrow('Invalid "predicate" parameter');
const flattened = documentHelpers.flatten(doc, false);
expect(flattened.length).toBeGreaterThan(0);
const inlineNodes = documentHelpers.findInlineNodes(doc, true);
expect(inlineNodes.every(({ node }) => node.isInline)).toBe(true);
});
it('parseFormatList gracefully handles malformed input', () => {
expect(parseFormatList('')).toEqual([]);
expect(parseFormatList('{ not json')).toEqual([]);
expect(parseFormatList('"string"')).toEqual([]);
const payload = [
{ type: 'bold', attrs: {} },
{ type: 'italic', attrs: {} },
];
expect(parseFormatList(JSON.stringify(payload))).toEqual(payload);
});
it('findTrackedMarkBetween locates marks using attributes', () => {
const mark = schema.marks[TrackInsertMarkName].create({
id: 'match-me',
author: user.name,
authorEmail: user.email,
date,
});
const doc = createDocWithText('abc', [mark]);
const state = createState(doc);
const tr = state.tr;
const found = findTrackedMarkBetween({
tr,
from: 2,
to: 4,
markName: TrackInsertMarkName,
attrs: { authorEmail: user.email },
});
expect(found).toEqual(
expect.objectContaining({
from: 2,
to: 5,
mark: expect.objectContaining({ attrs: expect.objectContaining({ id: 'match-me' }) }),
}),
);
});
it('markInsertion reuses or creates tracked marks', () => {
const state = createState(createDocWithText('Hello'));
const tr = state.tr.insertText('X', 1);
const mark = markInsertion({ tr, from: 1, to: 2, user, date });
expect(mark.attrs).toEqual(
expect.objectContaining({
author: user.name,
authorEmail: user.email,
date,
}),
);
const nextState = state.apply(tr);
const inlineNodes = documentHelpers.findInlineNodes(nextState.doc);
const tracked = inlineNodes.find(({ node }) => node.marks.some((m) => m.type.name === TrackInsertMarkName));
expect(tracked).toBeTruthy();
});
it('markInsertion uses provided id for replace operations', () => {
const state = createState(createDocWithText('Hello'));
const tr = state.tr.insertText('X', 1);
const customId = 'shared-replacement-id';
const mark = markInsertion({ tr, from: 1, to: 2, user, date, id: customId });
expect(mark.attrs.id).toBe(customId);
});
it('markDeletion applies trackDelete marks and collects nodes', () => {
const state = createState(createDocWithText('World'));
const tr = state.tr;
const result = markDeletion({ tr, from: 1, to: 6, user, date });
expect(result.deletionMark.attrs.authorEmail).toBe(user.email);
expect(result.nodes.length).toBeGreaterThan(0);
const applied = state.apply(tr);
const inlineNodes = documentHelpers.findInlineNodes(applied.doc);
const hasDelete = inlineNodes.some(({ node }) => node.marks.some((m) => m.type.name === TrackDeleteMarkName));
expect(hasDelete).toBe(true);
});
it('markDeletion reassigns existing deletions and removes own insertions for replacements', () => {
const ownInsertMark = schema.marks[TrackInsertMarkName].create({
id: 'ins-own',
author: user.name,
authorEmail: user.email,
date,
});
const oldDeleteMark = schema.marks[TrackDeleteMarkName].create({
id: 'del-old',
author: 'Other User',
authorEmail: 'other@example.com',
date,
});
const run = schema.nodes.run.create({}, [
schema.text('Keep '),
schema.text('OwnInsert', [ownInsertMark]),
schema.text(' OldDelete', [oldDeleteMark]),
schema.text(' Plain'),
]);
const doc = schema.nodes.doc.create({}, schema.nodes.paragraph.create({}, run));
const state = createState(doc);
const tr = state.tr;
const ownInsertPos = findTextPos(state.doc, 'OwnInsert');
const plainPos = findTextPos(state.doc, ' Plain');
expect(ownInsertPos).toBeTypeOf('number');
expect(plainPos).toBeTypeOf('number');
const replacementId = 'replacement-id';
const result = markDeletion({
tr,
from: ownInsertPos,
to: plainPos + ' Plain'.length,
user,
date,
id: replacementId,
});
const finalState = state.apply(tr);
expect(result.deletionMark.attrs.id).toBe(replacementId);
expect(result.nodes.some((node) => node.text?.includes('OldDelete'))).toBe(true);
expect(result.nodes.some((node) => node.text?.includes('Plain'))).toBe(true);
expect(result.deletionMap.maps.length).toBeGreaterThan(0);
expect(finalState.doc.textContent).not.toContain('OwnInsert');
let reassignedDeletedText = '';
let hasOldDeletionId = false;
finalState.doc.descendants((node) => {
if (!node.isText) return;
node.marks.forEach((mark) => {
if (mark.type.name !== TrackDeleteMarkName) return;
if (mark.attrs.id === replacementId) {
reassignedDeletedText += node.text;
}
if (mark.attrs.id === 'del-old') {
hasOldDeletionId = true;
}
});
});
expect(reassignedDeletedText).toContain('OldDelete');
expect(reassignedDeletedText).toContain('Plain');
expect(hasOldDeletionId).toBe(false);
});
it('markDeletion preserves existing deletions on plain delete actions', () => {
const oldDeleteMark = schema.marks[TrackDeleteMarkName].create({
id: 'del-old',
author: 'Other User',
authorEmail: 'other@example.com',
date,
});
const run = schema.nodes.run.create({}, [
schema.text('Keep '),
schema.text('OldDelete', [oldDeleteMark]),
schema.text(' Plain'),
]);
const doc = schema.nodes.doc.create({}, schema.nodes.paragraph.create({}, run));
const state = createState(doc);
const tr = state.tr;
const oldDeletePos = findTextPos(state.doc, 'OldDelete');
const plainPos = findTextPos(state.doc, ' Plain');
expect(oldDeletePos).toBeTypeOf('number');
expect(plainPos).toBeTypeOf('number');
markDeletion({
tr,
from: oldDeletePos,
to: plainPos + ' Plain'.length,
user,
date,
});
const finalState = state.apply(tr);
let hasOldDeleteId = false;
let plainHasDeleteMark = false;
let plainHasOldDeleteId = false;
finalState.doc.descendants((node) => {
if (!node.isText) return;
const deleteMarks = node.marks.filter((mark) => mark.type.name === TrackDeleteMarkName);
if (!deleteMarks.length) return;
if (deleteMarks.some((mark) => mark.attrs.id === 'del-old')) {
hasOldDeleteId = true;
}
if (node.text.includes('Plain')) {
plainHasDeleteMark = true;
plainHasOldDeleteId = deleteMarks.some((mark) => mark.attrs.id === 'del-old');
}
});
expect(hasOldDeleteId).toBe(true);
expect(plainHasDeleteMark).toBe(true);
expect(plainHasOldDeleteId).toBe(false);
});
it('removes Word-imported insertions without authorEmail when deleted', () => {
const insertXml = `<w:ins w:id="1" w:author="Word Author" w:date="2024-09-02T15:56:00Z">
<w:r>
<w:t>Inserted</w:t>
</w:r>
</w:ins>`;
const nodes = parseXmlToJson(insertXml).elements;
const result = handleTrackChangeNode({ docx: {}, nodes, nodeListHandler: defaultNodeListHandler() });
expect(result.nodes.length).toBe(1);
const insertedMark = result.nodes?.[0]?.content?.[0]?.marks?.find((mark) => mark.type === TrackInsertMarkName);
expect(insertedMark).toBeDefined();
expect(insertedMark.attrs?.authorEmail).toBeUndefined();
const runNodes = result.nodes.map((node) => ProseMirrorNode.fromJSON(schema, node));
const paragraph = schema.nodes.paragraph.create({}, runNodes);
const doc = schema.nodes.doc.create({}, paragraph);
const state = createState(doc);
const textEntry = documentHelpers.findInlineNodes(state.doc).find(({ node }) => node.isText);
expect(textEntry).toBeDefined();
const deleteTr = state.tr.delete(textEntry.pos, textEntry.pos + textEntry.node.nodeSize);
deleteTr.setMeta('inputType', 'deleteContentBackward');
const trackedDelete = trackedTransaction({ tr: deleteTr, state, user });
const finalState = state.apply(trackedDelete);
expect(finalState.doc.textContent).toBe('');
});
it('addMarkStep adds format mark metadata for styling changes', () => {
const state = createState(createDocWithText('Format me'));
const boldMark = schema.marks.bold.create();
const step = new AddMarkStep(1, 9, boldMark);
const newTr = state.tr;
addMarkStep({
state,
step,
newTr,
doc: state.doc,
user,
date,
});
expect(newTr.steps.length).toBeGreaterThan(0);
const meta = newTr.getMeta(TrackChangesBasePluginKey);
expect(meta).toBeTruthy();
expect(meta.step).toBe(step);
expect(meta.formatMark?.type.name).toBe(TrackFormatMarkName);
expect(newTr.getMeta(CommentsPluginKey)).toEqual({ type: 'force' });
});
it('addMarkStep tracks textStyle attr changes on imported-like marks', () => {
const importedTextStyle = schema.marks.textStyle.create({
styleId: 'Emphasis',
fontFamily: 'Calibri, sans-serif',
fontSize: '11pt',
color: '#112233',
});
const doc = createDocWithText('Format me', [importedTextStyle]);
const state = createState(doc);
const changedTextStyle = schema.marks.textStyle.create({
styleId: 'Emphasis',
fontFamily: 'Calibri, sans-serif',
fontSize: '11pt',
color: '#FF0000',
});
const step = new AddMarkStep(1, 9, changedTextStyle);
const newTr = state.tr;
addMarkStep({
state,
step,
newTr,
doc: state.doc,
user,
date,
});
const meta = newTr.getMeta(TrackChangesBasePluginKey);
expect(meta?.formatMark?.type.name).toBe(TrackFormatMarkName);
expect(meta?.formatMark?.attrs?.before).toEqual([{ type: 'textStyle', attrs: importedTextStyle.attrs }]);
expect(meta?.formatMark?.attrs?.after).toEqual([{ type: 'textStyle', attrs: changedTextStyle.attrs }]);
});
it('addMarkStep tracks highlight mark changes', () => {
const state = createState(createDocWithText('Highlight me'));
const highlightMark = schema.marks.highlight.create({ color: '#E4668C' });
const step = new AddMarkStep(1, 12, highlightMark);
const newTr = state.tr;
addMarkStep({
state,
step,
newTr,
doc: state.doc,
user,
date,
});
const meta = newTr.getMeta(TrackChangesBasePluginKey);
expect(meta?.formatMark?.type.name).toBe(TrackFormatMarkName);
expect(meta?.formatMark?.attrs?.after).toEqual([{ type: 'highlight', attrs: { color: '#E4668C' } }]);
});
it('addMarkStep does not include unrelated marks in before (SD-2077)', () => {
const highlight = schema.marks.highlight.create({ color: '#FFFF00' });
const doc = createDocWithText('Hello', [highlight]);
const state = createState(doc);
const boldMark = schema.marks.bold.create();
const step = new AddMarkStep(1, 6, boldMark);
const newTr = state.tr;
addMarkStep({
state,
step,
newTr,
doc: state.doc,
user,
date,
});
const meta = newTr.getMeta(TrackChangesBasePluginKey);
expect(meta?.formatMark?.type.name).toBe(TrackFormatMarkName);
expect(meta?.formatMark?.attrs?.before).toEqual([]);
expect(meta?.formatMark?.attrs?.after).toEqual([{ type: 'bold', attrs: boldMark.attrs }]);
});
it('addMarkStep only captures same-type mark in before when replacing (SD-2077)', () => {
const highlight = schema.marks.highlight.create({ color: '#FFFF00' });
const textStyle = schema.marks.textStyle.create({ color: '#112233', fontSize: '11pt' });
const doc = createDocWithText('Hello', [highlight, textStyle]);
const state = createState(doc);
const changedTextStyle = schema.marks.textStyle.create({ color: '#FF0000', fontSize: '11pt' });
const step = new AddMarkStep(1, 6, changedTextStyle);
const newTr = state.tr;
addMarkStep({
state,
step,
newTr,
doc: state.doc,
user,
date,
});
const meta = newTr.getMeta(TrackChangesBasePluginKey);
expect(meta?.formatMark?.type.name).toBe(TrackFormatMarkName);
expect(meta?.formatMark?.attrs?.before).toEqual([{ type: 'textStyle', attrs: textStyle.attrs }]);
expect(meta?.formatMark?.attrs?.after).toEqual([{ type: 'textStyle', attrs: changedTextStyle.attrs }]);
});
it('removeMarkStep records previous formatting when mark removed', () => {
const bold = schema.marks.bold.create();
const doc = createDocWithText('Styled', [bold]);
const state = createState(doc);
const step = new RemoveMarkStep(1, 7, bold);
const newTr = state.tr;
removeMarkStep({
state,
step,
newTr,
doc: state.doc,
user,
date,
});
expect(newTr.steps.length).toBeGreaterThan(0);
const meta = newTr.getMeta(TrackChangesBasePluginKey);
expect(meta?.formatMark?.type.name).toBe(TrackFormatMarkName);
});
it('removeMarkStep tracks removed highlight mark', () => {
const highlight = schema.marks.highlight.create({ color: '#E4668C' });
const doc = createDocWithText('Styled', [highlight]);
const state = createState(doc);
const step = new RemoveMarkStep(1, 7, highlight);
const newTr = state.tr;
removeMarkStep({
state,
step,
newTr,
doc: state.doc,
user,
date,
});
const meta = newTr.getMeta(TrackChangesBasePluginKey);
expect(meta?.formatMark?.type.name).toBe(TrackFormatMarkName);
expect(meta?.formatMark?.attrs?.before).toEqual([{ type: 'highlight', attrs: { color: '#E4668C' } }]);
});
it('getTrackChanges enumerates marks with optional filtering', () => {
const insertMark = schema.marks[TrackInsertMarkName].create({
id: 'track-1',
author: user.name,
authorEmail: user.email,
date,
});
const doc = createDocWithText('abc', [insertMark]);
const state = createState(doc);
const allChanges = getTrackChanges(state);
expect(allChanges.length).toBeGreaterThan(0);
const filtered = getTrackChanges(state, 'track-1');
expect(filtered.length).toBe(allChanges.length);
});
it('trackedTransaction annotates insertions and deletions', () => {
const initialState = createState(createDocWithText('abc'));
// insertion
let tr = initialState.tr.insertText('Z', 2);
tr.setMeta('inputType', 'insertText');
const trackedInsert = trackedTransaction({ tr, state: initialState, user });
const insertState = initialState.apply(trackedInsert);
const insertMeta = trackedInsert.getMeta(TrackChangesBasePluginKey);
expect(insertMeta?.insertedMark?.type.name).toBe(TrackInsertMarkName);
const hasInsertMark = documentHelpers
.findInlineNodes(insertState.doc)
.some(({ node }) => node.marks.some((mark) => mark.type.name === TrackInsertMarkName));
expect(hasInsertMark).toBe(true);
// deletion
const deleteState = createState(createDocWithText('abc'));
let deleteTr = deleteState.tr.delete(2, 3);
deleteTr.setMeta('inputType', 'deleteContentBackward');
const trackedDelete = trackedTransaction({ tr: deleteTr, state: deleteState, user });
const finalState = deleteState.apply(trackedDelete);
const deleteMeta = trackedDelete.getMeta(TrackChangesBasePluginKey);
expect(deleteMeta?.deletionMark?.type.name).toBe(TrackDeleteMarkName);
const hasDeleteMark = documentHelpers
.findInlineNodes(finalState.doc)
.some(({ node }) => node.marks.some((mark) => mark.type.name === TrackDeleteMarkName));
expect(hasDeleteMark).toBe(true);
});
it('trackedTransaction returns original transaction when metadata disallows tracking', () => {
const state = createState(createDocWithText('abc'));
const tr = state.tr.insertText('!', 1);
tr.setMeta('custom', true);
const result = trackedTransaction({ tr, state, user });
expect(result).toBe(tr);
});
it('trackedTransaction skips Yjs-origin transactions', () => {
const state = createState(createDocWithText('abc'));
const tr = state.tr.insertText('!', 1);
tr.setMeta('inputType', 'insertText');
tr.setMeta(ySyncPluginKey, { isChangeOrigin: true });
const result = trackedTransaction({ tr, state, user });
expect(result).toBe(tr);
});
it('trackedTransaction preserves addToHistory meta when inputType is programmatic', () => {
// Create initial state with history plugin (editor already has it from basePlugins)
let state = createState(createDocWithText('initial'));
// Step 1: Make a normal change that SHOULD be in history
let tr1 = state.tr.insertText('normal', 9);
tr1.setMeta('inputType', 'insertText');
const tracked1 = trackedTransaction({ tr: tr1, state, user });
state = state.apply(tracked1);
expect(state.doc.textContent).toBe('initialnormal');
// Step 2: Make a programmatic change that should NOT be in history
// This simulates the customer use case
let tr2 = state.tr.insertText('programmatic', 15);
tr2.setMeta('addToHistory', false);
tr2.setMeta('inputType', 'programmatic');
const tracked2 = trackedTransaction({ tr: tr2, state, user });
// Verify meta properties are preserved
expect(tracked2.getMeta('addToHistory')).toBe(false);
expect(tracked2.getMeta('inputType')).toBe('programmatic');
// Verify track changes were created
const meta = tracked2.getMeta(TrackChangesBasePluginKey);
expect(meta?.insertedMark?.type.name).toBe(TrackInsertMarkName);
// Apply the tracked transaction
state = state.apply(tracked2);
// Verify both changes are in the document
expect(state.doc.textContent).toBe('initialnormalprogrammatic');
// Step 3: Undo - this should only undo the "normal" change, NOT the "programmatic" one
let undoState = state;
undo(undoState, (tr) => {
undoState = undoState.apply(tr);
});
// CRITICAL TEST: The programmatic change should still be there after undo
// because it was marked with addToHistory: false
const finalText = undoState.doc.textContent;
expect(finalText).toBe('initialprogrammatic');
expect(finalText).not.toContain('normal'); // The normal change was undone
// Verify the track changes mark is still present
const hasInsertMark = documentHelpers
.findInlineNodes(undoState.doc)
.some(({ node }) => node.marks.some((mark) => mark.type.name === TrackInsertMarkName));
expect(hasInsertMark).toBe(true);
});
it('no-op helpers exist for future implementations', () => {
expect(markWrapping()).toBeUndefined();
});
it('trackedTransaction keeps selection in sync', () => {
const state = createState(createDocWithText('abc'));
const tr = state.tr.setSelection(TextSelection.create(state.doc, 2));
tr.insertText('Q');
tr.setMeta('inputType', 'insertText');
const tracked = trackedTransaction({ tr, state, user });
const updatedState = state.apply(tracked);
expect(updatedState.selection.from).toBeGreaterThan(1);
});
describe('Replace operations and ID sharing', () => {
it('replace operation creates insertion and deletion marks with the same ID', () => {
const state = createState(createDocWithText('old text'));
// Simulate selecting "old" and typing "new" (a replace operation)
const tr = state.tr.replaceWith(2, 5, schema.text('new'));
tr.setMeta('inputType', 'insertText');
const tracked = trackedTransaction({ tr, state, user });
const meta = tracked.getMeta(TrackChangesBasePluginKey);
// CRITICAL: Both marks should have the same ID for replace operations
expect(meta.insertedMark).toBeDefined();
expect(meta.deletionMark).toBeDefined();
expect(meta.insertedMark.attrs.id).toBe(meta.deletionMark.attrs.id);
const finalState = state.apply(tracked);
const inlineNodes = documentHelpers.findInlineNodes(finalState.doc);
const insertedNodes = inlineNodes.filter(({ node }) =>
node.marks.some((mark) => mark.type.name === TrackInsertMarkName),
);
const deletedNodes = inlineNodes.filter(({ node }) =>
node.marks.some((mark) => mark.type.name === TrackDeleteMarkName),
);
expect(insertedNodes.length).toBeGreaterThan(0);
expect(deletedNodes.length).toBeGreaterThan(0);
const insertId = insertedNodes[0].node.marks.find((m) => m.type.name === TrackInsertMarkName).attrs.id;
const deleteId = deletedNodes[0].node.marks.find((m) => m.type.name === TrackDeleteMarkName).attrs.id;
expect(insertId).toBe(deleteId);
});
it('deletion-only operation creates unique ID (no insertion)', () => {
const state = createState(createDocWithText('delete me'));
// Pure deletion without replacement
const tr = state.tr.delete(2, 11);
tr.setMeta('inputType', 'deleteContentBackward');
const tracked = trackedTransaction({ tr, state, user });
const meta = tracked.getMeta(TrackChangesBasePluginKey);
expect(meta.deletionMark).toBeDefined();
expect(meta.insertedMark).toBeUndefined();
});
it('insertion-only operation creates unique ID (no deletion)', () => {
const state = createState(createDocWithText('existing'));
// Pure insertion without deletion
const tr = state.tr.insertText(' new text', 9);
tr.setMeta('inputType', 'insertText');
const tracked = trackedTransaction({ tr, state, user });
const meta = tracked.getMeta(TrackChangesBasePluginKey);
expect(meta.insertedMark).toBeDefined();
expect(meta.deletionMark).toBeUndefined();
});
it('multiple sequential replace operations create different IDs', () => {
const state1 = createState(createDocWithText('first'));
const tr1 = state1.tr.replaceWith(2, 7, schema.text('1st'));
tr1.setMeta('inputType', 'insertText');
const tracked1 = trackedTransaction({ tr: tr1, state: state1, user });
const meta1 = tracked1.getMeta(TrackChangesBasePluginKey);
const state2 = createState(createDocWithText('second'));
const tr2 = state2.tr.replaceWith(2, 8, schema.text('2nd'));
tr2.setMeta('inputType', 'insertText');
const tracked2 = trackedTransaction({ tr: tr2, state: state2, user });
const meta2 = tracked2.getMeta(TrackChangesBasePluginKey);
expect(meta1.insertedMark.attrs.id).not.toBe(meta2.insertedMark.attrs.id);
});
it('replace operation maintains author and date consistency', () => {
const state = createState(createDocWithText('test'));
const tr = state.tr.replaceWith(2, 6, schema.text('TEST'));
tr.setMeta('inputType', 'insertText');
const tracked = trackedTransaction({ tr, state, user });
const meta = tracked.getMeta(TrackChangesBasePluginKey);
expect(meta.insertedMark.attrs.author).toBe(user.name);
expect(meta.deletionMark.attrs.author).toBe(user.name);
expect(meta.insertedMark.attrs.authorEmail).toBe(user.email);
expect(meta.deletionMark.attrs.authorEmail).toBe(user.email);
expect(meta.insertedMark.attrs.date).toBe(meta.deletionMark.attrs.date);
});
it('getTrackChanges returns both marks with same ID for replace', () => {
const state = createState(createDocWithText('original'));
const tr = state.tr.replaceWith(1, 10, schema.text('modified'));
tr.setMeta('inputType', 'insertText');
const tracked = trackedTransaction({ tr, state, user });
const finalState = state.apply(tracked);
const changes = getTrackChanges(finalState);
const insertions = changes.filter((c) => c.mark.type.name === TrackInsertMarkName);
const deletions = changes.filter((c) => c.mark.type.name === TrackDeleteMarkName);
expect(insertions.length).toBeGreaterThan(0);
expect(deletions.length).toBeGreaterThan(0);
const insertId = insertions[0].mark.attrs.id;
const deleteId = deletions[0].mark.attrs.id;
expect(insertId).toBe(deleteId);
});
});
});