-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathreplaceAroundStep.test.js
More file actions
800 lines (685 loc) · 27.2 KB
/
replaceAroundStep.test.js
File metadata and controls
800 lines (685 loc) · 27.2 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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import { EditorState, TextSelection } from 'prosemirror-state';
import { Mapping, ReplaceAroundStep, ReplaceStep } from 'prosemirror-transform';
import { Fragment, Slice } from 'prosemirror-model';
import { trackedTransaction, documentHelpers } from './index.js';
import { replaceAroundStep } from './replaceAroundStep.js';
import { TrackDeleteMarkName, TrackInsertMarkName } from '../constants.js';
import { TrackChangesBasePluginKey } from '../plugins/trackChangesBasePlugin.js';
import { initTestEditor } from '@tests/helpers/helpers.js';
import { findTextPos, findFirstParagraphRange } from './testUtils.js';
describe('replaceAroundStep handler', () => {
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 createState = (doc) =>
EditorState.create({
schema,
doc,
plugins: basePlugins,
});
/**
* Create a ReplaceAroundStep that simulates ProseMirror's structural backspace.
* A ReplaceAroundStep replaces from..gapFrom and gapTo..to with a slice,
* preserving the content between gapFrom..gapTo (the "gap").
*
* For backspace at a list/paragraph boundary, ProseMirror creates a step that
* lifts content out of its wrapper. We simulate this by wrapping the text
* in a listItem-like structure and creating a step that unwraps it.
*/
const createBackspaceReplaceAroundTr = (state, doc) => {
// Create a ReplaceAroundStep that covers the paragraph node.
// This simulates what ProseMirror generates when backspacing at a
// paragraph boundary to lift content out of its wrapper.
//
// We find the first paragraph and create a step that would "unwrap" it
// by replacing the paragraph's opening and closing tokens while preserving
// the content between them.
const { paraStart, paraEnd } = findFirstParagraphRange(doc);
// Build a transaction with a ReplaceAroundStep.
// The step unwraps the paragraph: replaces the paragraph node but keeps its inline content.
// from=paraStart, to=paraEnd, gapFrom=paraStart+1, gapTo=paraEnd-1
// This means: replace [paraStart..paraStart+1] (open tag) and [paraEnd-1..paraEnd] (close tag)
// with a new paragraph wrapper, keeping the content (the "gap") intact.
const tr = state.tr;
const step = new ReplaceAroundStep(
paraStart,
paraEnd,
paraStart + 1,
paraEnd - 1,
new Slice(Fragment.from(schema.nodes.paragraph.create()), 0, 0),
1,
true,
);
if (!tr.maybeStep(step).failed) {
return tr;
}
// Fallback: just create a simple structural step to test the handler
return null;
};
/**
* Helper to invoke replaceAroundStep handler directly.
* Sets up tr with a real step applied so tr.docs[0] is populated.
*/
const invokeHandler = ({ state, inputType = 'deleteContentBackward' }) => {
const doc = state.doc;
const trackDeleteMarkType = state.schema.marks[TrackDeleteMarkName];
// We need to supply a tr that has tr.docs populated (i.e., a step was applied to it).
// Apply a dummy ReplaceStep to the tr to populate tr.docs[0].
const tr = state.tr;
// Find cursor position and the char we'd delete
const cursorPos = state.selection.from;
let lastLiveCharPos = null;
// Walk the paragraph to find the live char (same logic as findPreviousLiveCharPos)
const $cursor = doc.resolve(cursorPos);
let paraDepth = $cursor.depth;
while (paraDepth > 0 && $cursor.node(paraDepth).type.name !== 'paragraph') {
paraDepth--;
}
if (paraDepth > 0) {
const paraStart = $cursor.before(paraDepth) + 1;
doc.nodesBetween(paraStart, cursorPos, (node, pos) => {
if (!node.isText) return;
const hasDeleteMark = node.marks.some((m) => m.type === trackDeleteMarkType);
if (hasDeleteMark) return;
const nodeEnd = pos + node.nodeSize;
const relevantEnd = Math.min(nodeEnd, cursorPos);
if (relevantEnd > pos) lastLiveCharPos = relevantEnd - 1;
});
}
// Apply a ReplaceStep to tr so tr.docs gets populated
if (lastLiveCharPos !== null) {
tr.step(new ReplaceStep(lastLiveCharPos, lastLiveCharPos + 1, Slice.empty));
}
tr.setMeta('inputType', inputType);
const newTr = state.tr;
const map = new Mapping();
const fakeStep = {};
replaceAroundStep({
state,
tr,
step: fakeStep,
newTr,
map,
doc,
user,
date,
originalStep: fakeStep,
originalStepIndex: 0,
});
return newTr;
};
describe('isNodeMarkupChange detection', () => {
it('allows setNodeMarkup-style steps through (structure=true, insert=1, gap=±1)', () => {
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create(
{ paragraphProperties: { styleId: 'Normal' } },
schema.nodes.run.create({}, [schema.text('Hello')]),
),
);
const state = createState(doc);
const { paraStart, paraEnd } = findFirstParagraphRange(state.doc);
const newParagraph = schema.nodes.paragraph.create({ paragraphProperties: { styleId: 'Heading1' } });
const step = new ReplaceAroundStep(
paraStart,
paraEnd,
paraStart + 1,
paraEnd - 1,
new Slice(Fragment.from(newParagraph), 0, 0),
1,
true,
);
const tr = state.tr;
tr.setMeta('inputType', 'insertParagraph'); // non-backspace — would normally be blocked
const newTr = state.tr;
const map = new Mapping();
replaceAroundStep({
state,
tr,
step,
newTr,
map,
doc: state.doc,
user,
date,
originalStep: step,
originalStepIndex: 0,
});
// The step should be applied directly (not blocked)
expect(newTr.steps.length).toBe(1);
expect(newTr.steps[0]).toBe(step);
});
it('blocks lift-style steps (structure=true, insert=0, gap=±1)', () => {
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Hello')])),
);
const state = createState(doc);
const { paraStart, paraEnd } = findFirstParagraphRange(state.doc);
// lift-style step: insert=0, structure=true, gap=±1
const step = new ReplaceAroundStep(paraStart, paraEnd, paraStart + 1, paraEnd - 1, Slice.empty, 0, true);
const tr = state.tr;
tr.setMeta('inputType', 'insertParagraph');
const newTr = state.tr;
const map = new Mapping();
replaceAroundStep({
state,
tr,
step,
newTr,
map,
doc: state.doc,
user,
date,
originalStep: step,
originalStepIndex: 0,
});
// Should be blocked — not a node markup change
expect(newTr.steps.length).toBe(0);
});
it('appends step mapping after applying node markup change', () => {
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create(
{ paragraphProperties: { styleId: 'Normal' } },
schema.nodes.run.create({}, [schema.text('Hello')]),
),
);
const state = createState(doc);
const { paraStart, paraEnd } = findFirstParagraphRange(state.doc);
const newParagraph = schema.nodes.paragraph.create({ paragraphProperties: { styleId: 'Heading1' } });
const step = new ReplaceAroundStep(
paraStart,
paraEnd,
paraStart + 1,
paraEnd - 1,
new Slice(Fragment.from(newParagraph), 0, 0),
1,
true,
);
const tr = state.tr;
const newTr = state.tr;
const map = new Mapping();
replaceAroundStep({
state,
tr,
step,
newTr,
map,
doc: state.doc,
user,
date,
originalStep: step,
originalStepIndex: 0,
});
// map should have been updated
expect(map.maps.length).toBe(1);
});
});
describe('non-backspace blocking', () => {
it('blocks non-backspace ReplaceAroundStep (no steps added to newTr)', () => {
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Hello')])),
);
const state = createState(doc);
const cursorPos = findTextPos(state.doc, 'Hello') + 5;
const stateWithSelection = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const newTr = invokeHandler({ state: stateWithSelection, inputType: 'insertParagraph' });
// No steps should be added — the structural change is blocked
expect(newTr.steps.length).toBe(0);
});
it('blocks ReplaceAroundStep without inputType meta', () => {
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Hello')])),
);
const state = createState(doc);
const tr = state.tr;
// No inputType meta set
const newTr = state.tr;
const map = new Mapping();
replaceAroundStep({
state,
tr,
step: {},
newTr,
map,
doc: state.doc,
user,
date,
originalStep: {},
originalStepIndex: 0,
});
expect(newTr.steps.length).toBe(0);
});
});
describe('backspace character deletion', () => {
it('converts backspace ReplaceAroundStep to tracked single-char deletion', () => {
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Hello')])),
);
let state = createState(doc);
// Position cursor after 'o' (end of "Hello")
const cursorPos = findTextPos(state.doc, 'Hello') + 5;
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const newTr = invokeHandler({ state });
// Should have added steps (the tracked deletion)
expect(newTr.steps.length).toBeGreaterThan(0);
// The last character 'o' should be marked as deleted
let hasDeleteMark = false;
newTr.doc.descendants((node) => {
if (node.isText && node.marks.some((m) => m.type.name === TrackDeleteMarkName)) {
hasDeleteMark = true;
}
});
expect(hasDeleteMark).toBe(true);
});
it('sets selectionPos on track meta for cursor positioning', () => {
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Hello')])),
);
let state = createState(doc);
const cursorPos = findTextPos(state.doc, 'Hello') + 5;
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const newTr = invokeHandler({ state });
const trackMeta = newTr.getMeta(TrackChangesBasePluginKey);
expect(trackMeta).toBeDefined();
expect(trackMeta.selectionPos).toBeDefined();
// selectionPos should be the position of the deleted character (before cursor)
expect(trackMeta.selectionPos).toBeLessThan(cursorPos);
});
it('blocks structural step when cursor is at start of non-empty list item (regression)', () => {
// Cursor at position 0 of a non-empty list item. findPreviousLiveCharPos
// returns null (no live char before caret), but the item still has live
// content after the cursor. The structural lift must be blocked.
const listItemType = schema.nodes.listItem || schema.nodes.list_item;
const bulletListType = schema.nodes.bulletList || schema.nodes.bullet_list;
if (!listItemType || !bulletListType) return; // skip if schema lacks list nodes
const doc = schema.nodes.doc.create({}, [
bulletListType.create({}, [
listItemType.create({}, [
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Hello')])),
]),
]),
]);
let state = createState(doc);
// Cursor at the very start of "Hello"
const cursorPos = findTextPos(state.doc, 'Hello');
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const tr = state.tr;
tr.setMeta('inputType', 'deleteContentBackward');
// Build a ReplaceAroundStep that unwraps the paragraph (simulates PM structural backspace)
let paraStart = null;
let paraEnd = null;
state.doc.descendants((node, pos) => {
if (paraStart === null && node.type.name === 'paragraph') {
paraStart = pos;
paraEnd = pos + node.nodeSize;
}
});
const step = new ReplaceAroundStep(
paraStart,
paraEnd,
paraStart + 1,
paraEnd - 1,
new Slice(Fragment.from(schema.nodes.paragraph.create()), 0, 0),
1,
true,
);
const newTr = state.tr;
const map = new Mapping();
replaceAroundStep({
state,
tr,
step,
newTr,
map,
doc: state.doc,
user,
date,
originalStep: step,
originalStepIndex: 0,
});
// The structural step must be blocked — the list item has live content.
expect(newTr.steps.length).toBe(0);
expect(map.maps.length).toBe(0);
});
it('attempts structural change when no live character exists before cursor (SD-2187)', () => {
// All content is tracked-deleted — no character to delete, but the
// handler should attempt the structural change (e.g. lifting out of
// list) so the user can remove the empty bullet. Previously this
// returned early and blocked the backspace entirely.
const deleteMark = schema.marks[TrackDeleteMarkName].create({
id: 'del-existing',
author: user.name,
authorEmail: user.email,
date,
});
// Build a doc with a paragraph inside a list item so the structural
// step (unwrap list item) can actually apply.
const listItemType = schema.nodes.listItem || schema.nodes.list_item;
const bulletListType = schema.nodes.bulletList || schema.nodes.bullet_list;
let doc;
if (listItemType && bulletListType) {
doc = schema.nodes.doc.create({}, [
bulletListType.create({}, [
listItemType.create({}, [
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Deleted', [deleteMark])])),
]),
]),
]);
} else {
// Fallback: simple paragraph (structural step may fail, but handler
// should not throw or block).
doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Deleted', [deleteMark])])),
);
}
let state = createState(doc);
const cursorPos = findTextPos(state.doc, 'Deleted') + 7;
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
// Invoke with a real ReplaceAroundStep instead of fakeStep
const tr = state.tr;
tr.setMeta('inputType', 'deleteContentBackward');
// Create a ReplaceAroundStep that unwraps the paragraph
let paraStart = null;
let paraEnd = null;
state.doc.descendants((node, pos) => {
if (paraStart === null && node.type.name === 'paragraph') {
paraStart = pos;
paraEnd = pos + node.nodeSize;
}
});
const step = new ReplaceAroundStep(
paraStart,
paraEnd,
paraStart + 1,
paraEnd - 1,
new Slice(Fragment.from(schema.nodes.paragraph.create()), 0, 0),
1,
true,
);
const newTr = state.tr;
const map = new Mapping();
replaceAroundStep({
state,
tr,
step,
newTr,
map,
doc: state.doc,
user,
date,
originalStep: step,
originalStepIndex: 0,
});
// The handler must apply the structural step — the list item is fully
// track-deleted so there is nothing live to preserve.
expect(newTr.steps.length).toBeGreaterThan(0);
});
it('blocks structural step when first paragraph is deleted but list item has live content in a later paragraph', () => {
// Multi-paragraph list item: first paragraph fully deleted, second has
// live text. Backspace at the start of the first paragraph should NOT
// allow the structural lift — the list item scope still has live content.
const listItemType = schema.nodes.listItem || schema.nodes.list_item;
const bulletListType = schema.nodes.bulletList || schema.nodes.bullet_list;
if (!listItemType || !bulletListType) return;
const deleteMark = schema.marks[TrackDeleteMarkName].create({
id: 'del-existing',
author: user.name,
authorEmail: user.email,
date,
});
let doc;
try {
doc = schema.nodes.doc.create({}, [
bulletListType.create({}, [
listItemType.create({}, [
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Gone', [deleteMark])])),
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Still here')])),
]),
]),
]);
} catch {
// Schema may not allow multiple paragraphs in a list item — skip.
return;
}
let state = createState(doc);
// Cursor at the start of the first (deleted) paragraph
const cursorPos = findTextPos(state.doc, 'Gone');
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const tr = state.tr;
tr.setMeta('inputType', 'deleteContentBackward');
let paraStart = null;
let paraEnd = null;
state.doc.descendants((node, pos) => {
if (paraStart === null && node.type.name === 'paragraph') {
paraStart = pos;
paraEnd = pos + node.nodeSize;
}
});
const step = new ReplaceAroundStep(
paraStart,
paraEnd,
paraStart + 1,
paraEnd - 1,
new Slice(Fragment.from(schema.nodes.paragraph.create()), 0, 0),
1,
true,
);
const newTr = state.tr;
const map = new Mapping();
replaceAroundStep({
state,
tr,
step,
newTr,
map,
doc: state.doc,
user,
date,
originalStep: step,
originalStepIndex: 0,
});
// Structural step must be blocked — listItem still has live content.
expect(newTr.steps.length).toBe(0);
expect(map.maps.length).toBe(0);
});
});
describe('findPreviousLiveCharPos (tested through handler)', () => {
it('skips tracked-deleted text and deletes the last live character', () => {
// "Hel" (live) + "lo" (deleted by another author) — cursor at end
// Should delete 'l' (the last live char), not 'o'
const deleteMark = schema.marks[TrackDeleteMarkName].create({
id: 'del-existing',
author: 'Other Author',
authorEmail: 'other@example.com',
date: '2023-01-01T00:00:00.000Z',
});
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create(
{},
schema.nodes.run.create({}, [schema.text('Hel'), schema.text('lo', [deleteMark])]),
),
);
let state = createState(doc);
// Cursor after 'lo' (end of all text)
const hPos = findTextPos(state.doc, 'Hel');
const cursorPos = hPos + 5; // After "Hello" = Hel + lo
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const newTr = invokeHandler({ state });
// Should have tracked deletion
expect(newTr.steps.length).toBeGreaterThan(0);
// 'l' from "Hel" should be the newly deleted character
let newlyDeletedText = '';
newTr.doc.descendants((node) => {
if (!node.isText) return;
const mark = node.marks.find((m) => m.type.name === TrackDeleteMarkName);
if (mark && mark.attrs.id !== 'del-existing') {
newlyDeletedText += node.text;
}
});
expect(newlyDeletedText).toBe('l');
});
});
describe('mark merging', () => {
it('merges adjacent trackDelete marks with same author/date but different IDs', () => {
// Simulate the scenario: "." was deleted previously (id A), now "l" is deleted (id B)
// They are in separate run nodes with a gap between them.
// After handler runs, both should have the same ID.
const existingDeleteMark = schema.marks[TrackDeleteMarkName].create({
id: 'existing-period-id',
author: user.name,
authorEmail: user.email,
date,
});
// "Material" (live) in one run, "." (deleted, id=existing) in another run
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, [
schema.nodes.run.create({}, [schema.text('Material')]),
schema.nodes.run.create({}, [schema.text('.', [existingDeleteMark])]),
]),
);
let state = createState(doc);
// Cursor after 'l' in "Material" (position to delete 'l')
const textPos = findTextPos(state.doc, 'Material');
const cursorPos = textPos + 8; // After "Material"
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const newTr = invokeHandler({ state });
const trackMeta = newTr.getMeta(TrackChangesBasePluginKey);
// The handler should have created a deletion mark
expect(trackMeta?.deletionMark).toBeDefined();
// Check that the existing "." deletion was re-marked with the new ID
const newId = trackMeta.deletionMark.attrs.id;
let periodMarkId = null;
newTr.doc.descendants((node) => {
if (!node.isText || node.text !== '.') return;
const delMark = node.marks.find((m) => m.type.name === TrackDeleteMarkName);
if (delMark) periodMarkId = delMark.attrs.id;
});
// Both the 'l' deletion and the '.' deletion should now share the same ID
expect(periodMarkId).toBe(newId);
});
it('does not merge marks from different authors', () => {
const otherAuthorMark = schema.marks[TrackDeleteMarkName].create({
id: 'other-author-del',
author: 'Other Author',
authorEmail: 'other@example.com',
date,
});
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, [
schema.nodes.run.create({}, [schema.text('Material')]),
schema.nodes.run.create({}, [schema.text('.', [otherAuthorMark])]),
]),
);
let state = createState(doc);
const textPos = findTextPos(state.doc, 'Material');
const cursorPos = textPos + 8;
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const newTr = invokeHandler({ state });
// The "." should keep the other author's ID (not merged)
let periodMarkId = null;
newTr.doc.descendants((node) => {
if (!node.isText || node.text !== '.') return;
const delMark = node.marks.find((m) => m.type.name === TrackDeleteMarkName);
if (delMark) periodMarkId = delMark.attrs.id;
});
expect(periodMarkId).toBe('other-author-del');
});
it('does not merge non-contiguous marks separated by live text', () => {
// "Material" (live) + "." (deleted, same author) + "end" (live) + "!" (deleted, same author)
// Only "." should be merged with the new deletion; "!" should keep its own ID
// because "end" (live text) breaks contiguity.
const deleteMark1 = schema.marks[TrackDeleteMarkName].create({
id: 'period-del',
author: user.name,
authorEmail: user.email,
date,
});
const deleteMark2 = schema.marks[TrackDeleteMarkName].create({
id: 'excl-del',
author: user.name,
authorEmail: user.email,
date,
});
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, [
schema.nodes.run.create({}, [schema.text('Material')]),
schema.nodes.run.create({}, [schema.text('.', [deleteMark1])]),
schema.nodes.run.create({}, [schema.text('end')]),
schema.nodes.run.create({}, [schema.text('!', [deleteMark2])]),
]),
);
let state = createState(doc);
const textPos = findTextPos(state.doc, 'Material');
const cursorPos = textPos + 8;
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
const newTr = invokeHandler({ state });
const trackMeta = newTr.getMeta(TrackChangesBasePluginKey);
const newId = trackMeta?.deletionMark?.attrs?.id;
// "." should be merged (same ID as new deletion)
let periodMarkId = null;
let exclMarkId = null;
newTr.doc.descendants((node) => {
if (!node.isText) return;
const delMark = node.marks.find((m) => m.type.name === TrackDeleteMarkName);
if (!delMark) return;
if (node.text === '.') periodMarkId = delMark.attrs.id;
if (node.text === '!') exclMarkId = delMark.attrs.id;
});
expect(periodMarkId).toBe(newId); // Adjacent — merged
expect(exclMarkId).toBe('excl-del'); // Non-contiguous — NOT merged
});
});
describe('selectionPos in trackedTransaction', () => {
it('selectionPos is honored even when tr.selectionSet is false', () => {
// This tests the critical fix in trackedTransaction.js:
// ReplaceAroundStep transactions may not set selection on the original tr,
// but our handler sets selectionPos on the meta. trackedTransaction must
// check selectionPos BEFORE checking tr.selectionSet.
const doc = schema.nodes.doc.create(
{},
schema.nodes.paragraph.create({}, schema.nodes.run.create({}, [schema.text('Hello')])),
);
let state = createState(doc);
const cursorPos = findTextPos(state.doc, 'Hello') + 5;
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, cursorPos)));
// Create a transaction with a ReplaceStep but do NOT set selection on tr,
// simulating the ReplaceAroundStep behavior where tr.selectionSet is false.
const deletePos = cursorPos - 1;
const tr = state.tr;
tr.step(new ReplaceStep(deletePos, cursorPos, Slice.empty));
tr.setMeta('inputType', 'deleteContentBackward');
// Critically: do NOT call tr.setSelection — this is what happens with ReplaceAroundStep
// Set selectionPos meta to simulate what replaceAroundStep handler does
tr.setMeta(TrackChangesBasePluginKey, { selectionPos: deletePos });
// Now run through trackedTransaction
const tracked = trackedTransaction({ tr, state, user });
const finalState = state.apply(tracked);
// The selection should be at or near deletePos, not at the original cursor position
expect(finalState.selection.from).toBeLessThanOrEqual(cursorPos);
});
});
});