1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod audit_tests {
5
    use super::*;
6

            
7
7
    fn cursor(byte: u32) -> TextCursor {
8
7
        TextCursor {
9
7
            cluster_id: GraphemeClusterId {
10
7
                source_run: 0,
11
7
                start_byte_in_run: byte,
12
7
            },
13
7
            affinity: CursorAffinity::Leading,
14
7
        }
15
7
    }
16

            
17
3
    fn state(byte: u32) -> MultiCursorState {
18
3
        MultiCursorState::new_with_cursor(cursor(byte), DomNodeId::ROOT, 0)
19
3
    }
20

            
21
    #[test]
22
1
    fn primary_tracked_by_id_not_vec_position() {
23
1
        let mut mc = state(100);
24
        // Add a cursor at an EARLIER position; after merge_overlapping's sort it
25
        // becomes the vector's FIRST element, but it is the primary (last added).
26
1
        let b = mc.add_cursor(cursor(0));
27
1
        assert_eq!(mc.len(), 2);
28
        // The primary must be the just-added cursor at byte 0, not the
29
        // position-last cursor at byte 100.
30
1
        assert_eq!(mc.get_primary().unwrap().id, b);
31
1
        assert_eq!(mc.get_primary_cursor().unwrap(), cursor(0));
32
1
    }
33

            
34
    #[test]
35
1
    fn merge_preserves_primary() {
36
1
        let mut mc = state(5);
37
1
        let _b = mc.add_cursor(cursor(5)); // same position -> merges to one
38
1
        assert_eq!(mc.len(), 1);
39
        // primary_id must resolve to the surviving selection.
40
1
        let primary = mc.get_primary().unwrap();
41
1
        assert_eq!(primary.id, mc.selections[0].id);
42
1
    }
43

            
44
    #[test]
45
1
    fn removing_primary_repoints_it() {
46
1
        let mut mc = state(0);
47
1
        let b = mc.add_cursor(cursor(10)); // primary = b
48
1
        assert_eq!(mc.get_primary().unwrap().id, b);
49
1
        assert!(mc.remove_selection(b));
50
        // primary must now be a still-existing selection, not a dangling id.
51
1
        let p = mc.get_primary().unwrap();
52
1
        assert!(mc.selections.iter().any(|s| s.id == p.id));
53
1
    }
54
}
55

            
56
#[cfg(test)]
57
mod autotest_generated {
58
    use super::*;
59
    use crate::{geom::LogicalSize, styled_dom::NodeHierarchyItemId};
60

            
61
    // ---------------------------------------------------------------------
62
    // Fixtures
63
    // ---------------------------------------------------------------------
64

            
65
    /// Cursor in run 0 at `byte`, Leading affinity.
66
    fn c(byte: u32) -> TextCursor {
67
        TextCursor {
68
            cluster_id: GraphemeClusterId {
69
                source_run: 0,
70
                start_byte_in_run: byte,
71
            },
72
            affinity: CursorAffinity::Leading,
73
        }
74
    }
75

            
76
    /// Cursor with explicit run + affinity (for ordering / boundary probes).
77
    fn c_full(run: u32, byte: u32, affinity: CursorAffinity) -> TextCursor {
78
        TextCursor {
79
            cluster_id: GraphemeClusterId {
80
                source_run: run,
81
                start_byte_in_run: byte,
82
            },
83
            affinity,
84
        }
85
    }
86

            
87
    fn rng(a: u32, b: u32) -> SelectionRange {
88
        SelectionRange {
89
            start: c(a),
90
            end: c(b),
91
        }
92
    }
93

            
94
    fn dom_node(index: usize) -> DomNodeId {
95
        DomNodeId {
96
            dom: DomId::ROOT_ID,
97
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(index))),
98
        }
99
    }
100

            
101
    fn state(byte: u32) -> MultiCursorState {
102
        MultiCursorState::new_with_cursor(c(byte), DomNodeId::ROOT, 0)
103
    }
104

            
105
    /// A `MultiCursorState` with zero selections — "should not normally happen",
106
    /// so every getter must survive it.
107
    fn empty_state() -> MultiCursorState {
108
        MultiCursorState {
109
            selections: Vec::new(),
110
            primary_id: SelectionId::new(),
111
            node_id: DomNodeId::ROOT,
112
            contenteditable_key: 0,
113
        }
114
    }
115

            
116
    fn ident(id: SelectionId, sel: Selection) -> IdentifiedSelection {
117
        IdentifiedSelection {
118
            id,
119
            selection: sel,
120
            owner: SelectionOwner::LOCAL,
121
        }
122
    }
123

            
124
    // ---------------------------------------------------------------------
125
    // Invariant checkers (documented in `MultiCursorState`'s `## Invariants`)
126
    // ---------------------------------------------------------------------
127

            
128
    /// `selections` is sorted by position and non-overlapping.
129
    fn assert_sorted_nonoverlapping(mc: &MultiCursorState) {
130
        for w in mc.selections.windows(2) {
131
            let prev_end = selection_end_pos(&w[0].selection);
132
            let next_start = selection_start_pos(&w[1].selection);
133
            assert!(
134
                next_start > prev_end,
135
                "selections must be sorted and non-overlapping after merge: {:?} then {:?}",
136
                w[0],
137
                w[1]
138
            );
139
        }
140
    }
141

            
142
    /// `primary_id` must always name a selection that actually exists (or the
143
    /// state must be empty). A dangling `primary_id` makes `get_primary()` lie.
144
    fn assert_primary_resolves(mc: &MultiCursorState) {
145
        if mc.is_empty() {
146
            assert!(mc.get_primary().is_none());
147
            assert!(mc.get_primary_cursor().is_none());
148
        } else {
149
            let p = mc
150
                .get_primary()
151
                .expect("non-empty state must have a primary");
152
            assert!(
153
                mc.selections.iter().any(|s| s.id == p.id),
154
                "get_primary() returned a selection not in the vec"
155
            );
156
            assert_eq!(
157
                mc.primary_id, p.id,
158
                "primary_id must name an existing selection (not fall back to last)"
159
            );
160
        }
161
    }
162

            
163
    /// All selection IDs must be distinct.
164
    fn assert_ids_unique(mc: &MultiCursorState) {
165
        for (i, a) in mc.selections.iter().enumerate() {
166
            for b in mc.selections.iter().skip(i + 1) {
167
                assert_ne!(a.id, b.id, "duplicate SelectionId in state");
168
            }
169
        }
170
    }
171

            
172
    // =====================================================================
173
    // SelectionId::new  (constructor)
174
    // =====================================================================
175

            
176
    #[test]
177
    fn selection_id_new_is_unique_and_strictly_increasing() {
178
        let mut prev = SelectionId::new();
179
        assert!(prev.inner > 0, "counter starts at 1, never the 0 sentinel");
180
        for _ in 0..1000 {
181
            let next = SelectionId::new();
182
            // Other tests share the global atomic, so ids may skip — but within
183
            // one thread they must be strictly increasing and never repeat.
184
            assert!(
185
                next.inner > prev.inner,
186
                "SelectionId counter must be strictly monotonic"
187
            );
188
            assert_ne!(next, prev);
189
            prev = next;
190
        }
191
    }
192

            
193
    #[test]
194
    fn selection_id_default_mints_a_fresh_id() {
195
        // Documented: Default does NOT return a zero/sentinel value.
196
        let a = SelectionId::default();
197
        let b = SelectionId::default();
198
        let d = SelectionId::new();
199
        assert_ne!(a, b);
200
        assert_ne!(b, d);
201
        assert!(a.inner > 0 && b.inner > 0);
202
    }
203

            
204
    // =====================================================================
205
    // SelectionState::add
206
    // =====================================================================
207

            
208
    #[test]
209
    fn selection_state_add_dedups_identical_cursors() {
210
        let mut st = SelectionState {
211
            selections: Vec::<Selection>::new().into(),
212
            node_id: DomNodeId::ROOT,
213
        };
214
        for _ in 0..100 {
215
            st.add(Selection::Cursor(c(42)));
216
        }
217
        assert_eq!(st.selections.as_ref().len(), 1);
218
        assert_eq!(st.selections.as_ref()[0], Selection::Cursor(c(42)));
219
    }
220

            
221
    #[test]
222
    fn selection_state_add_sorts_descending_input_ascending() {
223
        let mut st = SelectionState {
224
            selections: Vec::<Selection>::new().into(),
225
            node_id: DomNodeId::ROOT,
226
        };
227
        for byte in [90u32, 10, 50, 0, 70] {
228
            st.add(Selection::Cursor(c(byte)));
229
        }
230
        let got: Vec<Selection> = st.selections.as_ref().to_vec();
231
        assert_eq!(got.len(), 5);
232
        let want: Vec<Selection> = [0u32, 10, 50, 70, 90]
233
            .iter()
234
            .map(|b| Selection::Cursor(c(*b)))
235
            .collect();
236
        assert_eq!(got, want);
237
    }
238

            
239
    #[test]
240
    fn selection_state_add_boundary_and_reversed_ranges_do_not_panic() {
241
        let mut st = SelectionState {
242
            selections: Vec::<Selection>::new().into(),
243
            node_id: DomNodeId::ROOT,
244
        };
245
        // u32::MAX bytes, max run index, both affinities, and a *reversed* range
246
        // (start logically after end — explicitly allowed by SelectionRange docs).
247
        st.add(Selection::Cursor(c_full(
248
            u32::MAX,
249
            u32::MAX,
250
            CursorAffinity::Trailing,
251
        )));
252
        st.add(Selection::Cursor(c_full(0, 0, CursorAffinity::Leading)));
253
        st.add(Selection::Range(SelectionRange {
254
            start: c_full(u32::MAX, u32::MAX, CursorAffinity::Trailing),
255
            end: c_full(0, 0, CursorAffinity::Leading),
256
        }));
257
        st.add(Selection::Range(rng(0, u32::MAX)));
258
        // add() only sorts + dedups; it does not normalize or merge, so all 4 stay.
259
        assert_eq!(st.selections.as_ref().len(), 4);
260
        // ... and the result is sorted.
261
        let got: Vec<Selection> = st.selections.as_ref().to_vec();
262
        let mut sorted = got.clone();
263
        sorted.sort_unstable();
264
        assert_eq!(got, sorted);
265
    }
266

            
267
    #[test]
268
    fn selection_state_add_cursor_and_range_at_same_pos_are_distinct() {
269
        let mut st = SelectionState {
270
            selections: Vec::<Selection>::new().into(),
271
            node_id: DomNodeId::ROOT,
272
        };
273
        st.add(Selection::Range(rng(5, 5)));
274
        st.add(Selection::Cursor(c(5)));
275
        // A zero-width Range and a Cursor are different `Selection` variants,
276
        // so dedup() cannot collapse them.
277
        assert_eq!(st.selections.as_ref().len(), 2);
278
        // Cursor variant sorts before Range variant.
279
        assert_eq!(st.selections.as_ref()[0], Selection::Cursor(c(5)));
280
    }
281

            
282
    // =====================================================================
283
    // MultiCursorState::new_with_cursor  (constructor)
284
    // =====================================================================
285

            
286
    #[test]
287
    fn new_with_cursor_invariants_hold() {
288
        let node = dom_node(7);
289
        let mc = MultiCursorState::new_with_cursor(c(3), node, 0xDEAD_BEEF);
290
        assert_eq!(mc.len(), 1);
291
        assert!(!mc.is_empty());
292
        assert_eq!(mc.selections.len(), mc.len());
293
        assert_eq!(mc.primary_id, mc.selections[0].id);
294
        assert_eq!(mc.node_id, node);
295
        assert_eq!(mc.contenteditable_key, 0xDEAD_BEEF);
296
        assert_eq!(mc.get_primary_cursor(), Some(c(3)));
297
        assert_eq!(mc.to_selections(), vec![Selection::Cursor(c(3))]);
298
        assert_primary_resolves(&mc);
299
    }
300

            
301
    #[test]
302
    fn new_with_cursor_extreme_args_do_not_panic() {
303
        let mc = MultiCursorState::new_with_cursor(
304
            c_full(u32::MAX, u32::MAX, CursorAffinity::Trailing),
305
            dom_node(usize::MAX / 4),
306
            u64::MAX,
307
        );
308
        assert_eq!(mc.len(), 1);
309
        assert_eq!(mc.contenteditable_key, u64::MAX);
310
        assert_eq!(
311
            mc.get_primary_cursor(),
312
            Some(c_full(u32::MAX, u32::MAX, CursorAffinity::Trailing))
313
        );
314
        assert_primary_resolves(&mc);
315
    }
316

            
317
    #[test]
318
    fn two_states_get_distinct_ids() {
319
        let a = state(0);
320
        let b = state(0);
321
        assert_ne!(a.primary_id, b.primary_id);
322
    }
323

            
324
    // =====================================================================
325
    // add_cursor / add_selection
326
    // =====================================================================
327

            
328
    #[test]
329
    fn add_cursor_at_same_position_merges_to_one() {
330
        let mut mc = state(5);
331
        let b = mc.add_cursor(c(5));
332
        assert_eq!(mc.len(), 1);
333
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(5)));
334
        assert_eq!(mc.selections[0].id, b, "merge keeps the newer id");
335
        assert_primary_resolves(&mc);
336
        assert_ids_unique(&mc);
337
    }
338

            
339
    #[test]
340
    fn add_cursor_distinct_positions_stay_separate_and_sorted() {
341
        let mut mc = state(30);
342
        let _ = mc.add_cursor(c(10));
343
        let last = mc.add_cursor(c(20));
344
        assert_eq!(mc.len(), 3);
345
        // Sorted by position, NOT by insertion order.
346
        assert_eq!(
347
            mc.to_selections(),
348
            vec![
349
                Selection::Cursor(c(10)),
350
                Selection::Cursor(c(20)),
351
                Selection::Cursor(c(30)),
352
            ]
353
        );
354
        // Primary is the most recently added (byte 20), which is the *middle*
355
        // element — proving primary is tracked by id, not vec position.
356
        assert_eq!(mc.get_primary().unwrap().id, last);
357
        assert_eq!(mc.get_primary_cursor(), Some(c(20)));
358
        assert_sorted_nonoverlapping(&mc);
359
        assert_primary_resolves(&mc);
360
        assert_ids_unique(&mc);
361
    }
362

            
363
    #[test]
364
    fn add_cursor_same_byte_different_affinity_does_not_merge() {
365
        // Leading < Trailing, so cur_start(Trailing) > last_end(Leading) and the
366
        // merge condition (`cur_start <= last_end`) is false. Two carets survive
367
        // at the same byte offset.
368
        let mut mc = MultiCursorState::new_with_cursor(
369
            c_full(0, 4, CursorAffinity::Leading),
370
            DomNodeId::ROOT,
371
            0,
372
        );
373
        let _ = mc.add_cursor(c_full(0, 4, CursorAffinity::Trailing));
374
        assert_eq!(mc.len(), 2);
375
        assert_sorted_nonoverlapping(&mc);
376
        assert_primary_resolves(&mc);
377
    }
378

            
379
    #[test]
380
    fn add_selection_overlapping_ranges_merge_into_union() {
381
        let mut mc = empty_state();
382
        let _ = mc.add_selection(rng(0, 10));
383
        let _ = mc.add_selection(rng(5, 20));
384
        assert_eq!(mc.len(), 1);
385
        assert_eq!(mc.selections[0].selection, Selection::Range(rng(0, 20)));
386
        assert_primary_resolves(&mc);
387
    }
388

            
389
    #[test]
390
    fn add_selection_touching_ranges_merge() {
391
        // Adjacent (end == start) counts as overlapping: `cur_start <= last_end`.
392
        let mut mc = empty_state();
393
        let _ = mc.add_selection(rng(0, 10));
394
        let _ = mc.add_selection(rng(10, 20));
395
        assert_eq!(mc.len(), 1);
396
        assert_eq!(mc.selections[0].selection, Selection::Range(rng(0, 20)));
397
    }
398

            
399
    #[test]
400
    fn add_selection_disjoint_ranges_stay_separate() {
401
        let mut mc = empty_state();
402
        let _ = mc.add_selection(rng(0, 10));
403
        let _ = mc.add_selection(rng(11, 20));
404
        assert_eq!(mc.len(), 2);
405
        assert_sorted_nonoverlapping(&mc);
406
        assert_primary_resolves(&mc);
407
    }
408

            
409
    #[test]
410
    fn add_selection_reversed_range_is_normalized_for_merging() {
411
        // Backwards selection: start (20) is logically after end (5).
412
        let mut mc = empty_state();
413
        let _ = mc.add_selection(SelectionRange {
414
            start: c(20),
415
            end: c(5),
416
        });
417
        // A cursor *inside* the backwards range must merge with it.
418
        let _ = mc.add_cursor(c(10));
419
        assert_eq!(mc.len(), 1);
420
        // The merged result is normalized to a forwards range.
421
        assert_eq!(mc.selections[0].selection, Selection::Range(rng(5, 20)));
422
        assert_primary_resolves(&mc);
423
    }
424

            
425
    #[test]
426
    fn add_selection_at_u32_max_boundary_does_not_overflow() {
427
        let mut mc = empty_state();
428
        let _ = mc.add_selection(rng(u32::MAX - 1, u32::MAX));
429
        let _ = mc.add_cursor(c(u32::MAX));
430
        assert_eq!(mc.len(), 1);
431
        assert_eq!(
432
            mc.selections[0].selection,
433
            Selection::Range(rng(u32::MAX - 1, u32::MAX))
434
        );
435
        assert_primary_resolves(&mc);
436
    }
437

            
438
    #[test]
439
    fn add_cursor_stress_500_distinct_positions() {
440
        let mut mc = state(0);
441
        for i in 1..=500u32 {
442
            let _ = mc.add_cursor(c(i * 2));
443
        }
444
        assert_eq!(mc.len(), 501);
445
        assert_sorted_nonoverlapping(&mc);
446
        assert_primary_resolves(&mc);
447
        assert_ids_unique(&mc);
448
    }
449

            
450
    #[test]
451
    fn add_cursor_stress_same_position_never_grows() {
452
        let mut mc = state(9);
453
        for _ in 0..300 {
454
            let _ = mc.add_cursor(c(9));
455
        }
456
        assert_eq!(mc.len(), 1, "identical cursors must always collapse");
457
        assert_primary_resolves(&mc);
458
    }
459

            
460
    // =====================================================================
461
    // remove_selection
462
    // =====================================================================
463

            
464
    #[test]
465
    fn remove_selection_unknown_id_returns_false_and_changes_nothing() {
466
        let mut mc = state(1);
467
        let before = mc.clone();
468
        let ghost = SelectionId::new(); // never inserted anywhere
469
        assert!(!mc.remove_selection(ghost));
470
        assert_eq!(mc, before);
471
    }
472

            
473
    #[test]
474
    fn remove_selection_twice_second_call_returns_false() {
475
        let mut mc = state(0);
476
        let b = mc.add_cursor(c(10));
477
        assert!(mc.remove_selection(b));
478
        assert!(!mc.remove_selection(b));
479
        assert_eq!(mc.len(), 1);
480
        assert_primary_resolves(&mc);
481
    }
482

            
483
    #[test]
484
    fn remove_all_selections_leaves_a_safe_empty_state() {
485
        let mut mc = state(0);
486
        let b = mc.add_cursor(c(10));
487
        let a = mc.selections.iter().find(|s| s.id != b).unwrap().id;
488
        assert!(mc.remove_selection(a));
489
        assert!(mc.remove_selection(b));
490
        assert!(mc.is_empty());
491
        assert_eq!(mc.len(), 0);
492
        assert!(mc.get_primary().is_none());
493
        assert!(mc.get_primary_cursor().is_none());
494
        assert!(mc.to_selections().is_empty());
495
        // Further mutation of the empty state must not panic.
496
        mc.merge_overlapping();
497
        mc.move_all_cursors(true, |cur| *cur);
498
        assert!(mc.is_empty());
499
    }
500

            
501
    #[test]
502
    fn remove_primary_from_three_repoints_to_a_survivor() {
503
        let mut mc = state(0);
504
        let _ = mc.add_cursor(c(10));
505
        let p = mc.add_cursor(c(20)); // primary
506
        assert_eq!(mc.get_primary().unwrap().id, p);
507
        assert!(mc.remove_selection(p));
508
        assert_eq!(mc.len(), 2);
509
        assert_primary_resolves(&mc);
510
    }
511

            
512
    // =====================================================================
513
    // get_primary / get_primary_mut / get_primary_cursor / to_selections / len
514
    // =====================================================================
515

            
516
    #[test]
517
    fn empty_state_getters_return_none_without_panicking() {
518
        let mut mc = empty_state();
519
        assert!(mc.is_empty());
520
        assert_eq!(mc.len(), 0);
521
        assert!(mc.get_primary().is_none());
522
        assert!(mc.get_primary_mut().is_none());
523
        assert!(mc.get_primary_cursor().is_none());
524
        assert!(mc.to_selections().is_empty());
525
        mc.merge_overlapping(); // early-returns on len <= 1
526
        mc.ensure_primary_valid(); // private: must not panic on empty vec
527
        assert!(mc.is_empty());
528
    }
529

            
530
    #[test]
531
    fn get_primary_falls_back_to_last_when_primary_id_is_dangling() {
532
        let mut mc = state(0);
533
        let _ = mc.add_cursor(c(10));
534
        mc.primary_id = SelectionId::new(); // dangling: names nothing in the vec
535
        let p = mc.get_primary().expect("must fall back, not return None");
536
        assert_eq!(p.id, mc.selections.last().unwrap().id);
537
        assert_eq!(mc.get_primary_cursor(), Some(c(10)));
538
    }
539

            
540
    #[test]
541
    fn ensure_primary_valid_adopts_last_id_when_dangling() {
542
        let mut mc = state(0);
543
        let _ = mc.add_cursor(c(10));
544
        let dangling = SelectionId::new();
545
        mc.primary_id = dangling;
546
        mc.ensure_primary_valid();
547
        assert_ne!(mc.primary_id, dangling);
548
        assert_eq!(mc.primary_id, mc.selections.last().unwrap().id);
549
        // Idempotent: a second call on a now-valid id is a no-op.
550
        let fixed = mc.primary_id;
551
        mc.ensure_primary_valid();
552
        assert_eq!(mc.primary_id, fixed);
553
    }
554

            
555
    #[test]
556
    fn ensure_primary_valid_on_empty_leaves_id_untouched() {
557
        let mut mc = empty_state();
558
        let before = mc.primary_id;
559
        mc.ensure_primary_valid();
560
        assert_eq!(
561
            mc.primary_id, before,
562
            "nothing to adopt — id must not change"
563
        );
564
        assert!(mc.get_primary().is_none());
565
    }
566

            
567
    #[test]
568
    fn get_primary_cursor_of_a_range_is_its_end_field() {
569
        let mut mc = empty_state();
570
        mc.set_single_range(rng(3, 9));
571
        assert_eq!(mc.get_primary_cursor(), Some(c(9)));
572

            
573
        // Backwards range: the raw `end` field is returned (the *focus*), even
574
        // though it is the lower position. This is deliberate — the caret sits
575
        // at the focus, not at the max boundary.
576
        let mut back = empty_state();
577
        back.set_single_range(SelectionRange {
578
            start: c(9),
579
            end: c(3),
580
        });
581
        assert_eq!(back.get_primary_cursor(), Some(c(3)));
582
    }
583

            
584
    #[test]
585
    fn get_primary_mut_mutation_is_visible_through_get_primary() {
586
        let mut mc = state(0);
587
        let p = mc.add_cursor(c(50));
588
        {
589
            let prim = mc.get_primary_mut().expect("primary exists");
590
            assert_eq!(prim.id, p);
591
            prim.selection = Selection::Range(rng(50, 60));
592
        }
593
        assert_eq!(
594
            mc.get_primary().unwrap().selection,
595
            Selection::Range(rng(50, 60))
596
        );
597
        assert_eq!(mc.get_primary_cursor(), Some(c(60)));
598
    }
599

            
600
    #[test]
601
    fn get_primary_mut_falls_back_to_last_when_dangling() {
602
        let mut mc = state(0);
603
        let _ = mc.add_cursor(c(10));
604
        mc.primary_id = SelectionId::new();
605
        let last_id = mc.selections.last().unwrap().id;
606
        let prim = mc.get_primary_mut().expect("fallback to last");
607
        assert_eq!(prim.id, last_id);
608
    }
609

            
610
    #[test]
611
    fn to_selections_matches_the_internal_order_and_len() {
612
        let mut mc = state(30);
613
        let _ = mc.add_cursor(c(10));
614
        let _ = mc.add_selection(rng(15, 20));
615
        let sels = mc.to_selections();
616
        assert_eq!(sels.len(), mc.len());
617
        let inner: Vec<Selection> = mc.selections.iter().map(|s| s.selection).collect();
618
        assert_eq!(sels, inner);
619
    }
620

            
621
    #[test]
622
    fn len_and_is_empty_always_agree() {
623
        let mut mc = empty_state();
624
        assert!(mc.is_empty() && mc.is_empty());
625
        let _ = mc.add_cursor(c(1));
626
        assert!(!mc.is_empty() && mc.len() == 1);
627
        for i in 2..20u32 {
628
            let _ = mc.add_cursor(c(i * 3));
629
        }
630
        assert_eq!(mc.len(), mc.selections.len());
631
        assert_eq!(mc.is_empty(), mc.is_empty());
632
        assert!(!mc.is_empty());
633
    }
634

            
635
    // =====================================================================
636
    // update_from_edit_result
637
    // =====================================================================
638

            
639
    #[test]
640
    fn update_from_edit_result_with_empty_slice_clears_everything() {
641
        let mut mc = state(0);
642
        let _ = mc.add_cursor(c(10));
643
        mc.update_from_edit_result(&[]);
644
        assert!(mc.is_empty());
645
        assert!(mc.get_primary().is_none());
646
        assert!(mc.get_primary_cursor().is_none());
647
    }
648

            
649
    #[test]
650
    fn update_from_edit_result_preserves_ids_by_index_and_mints_extras() {
651
        let mut mc = state(0);
652
        let _ = mc.add_cursor(c(10));
653
        let old: Vec<SelectionId> = mc.selections.iter().map(|s| s.id).collect();
654
        assert_eq!(old.len(), 2);
655

            
656
        mc.update_from_edit_result(&[
657
            Selection::Cursor(c(1)),
658
            Selection::Cursor(c(2)),
659
            Selection::Cursor(c(3)),
660
            Selection::Range(rng(4, 8)),
661
        ]);
662
        assert_eq!(mc.len(), 4);
663
        assert_eq!(mc.selections[0].id, old[0], "id preserved by index");
664
        assert_eq!(mc.selections[1].id, old[1], "id preserved by index");
665
        assert_ids_unique(&mc);
666
        assert_primary_resolves(&mc);
667
        assert_eq!(mc.selections[3].selection, Selection::Range(rng(4, 8)));
668
    }
669

            
670
    #[test]
671
    fn update_from_edit_result_shrinking_keeps_primary_resolvable() {
672
        let mut mc = state(0);
673
        let _ = mc.add_cursor(c(10));
674
        let _ = mc.add_cursor(c(20)); // primary = the byte-20 cursor
675
        mc.update_from_edit_result(&[Selection::Cursor(c(99))]);
676
        assert_eq!(mc.len(), 1);
677
        // The primary's id is gone (only index 0's id survived), so
678
        // ensure_primary_valid must have re-pointed it at the survivor.
679
        assert_primary_resolves(&mc);
680
        assert_eq!(mc.get_primary_cursor(), Some(c(99)));
681
    }
682

            
683
    #[test]
684
    fn update_from_edit_result_does_not_merge_overlaps() {
685
        // Documented: "Don't merge here — edit_text already returns correct positions"
686
        let mut mc = state(0);
687
        mc.update_from_edit_result(&[Selection::Range(rng(0, 10)), Selection::Range(rng(5, 15))]);
688
        assert_eq!(mc.len(), 2, "update must NOT merge");
689
        // ... but an explicit merge afterwards collapses them.
690
        mc.merge_overlapping();
691
        assert_eq!(mc.len(), 1);
692
        assert_eq!(mc.selections[0].selection, Selection::Range(rng(0, 15)));
693
        assert_primary_resolves(&mc);
694
    }
695

            
696
    #[test]
697
    fn update_from_edit_result_with_1000_selections() {
698
        let mut mc = state(0);
699
        let big: Vec<Selection> = (0..1000u32).map(|i| Selection::Cursor(c(i * 4))).collect();
700
        mc.update_from_edit_result(&big);
701
        assert_eq!(mc.len(), 1000);
702
        assert_ids_unique(&mc);
703
        assert_primary_resolves(&mc);
704
        assert_eq!(mc.to_selections(), big);
705
    }
706

            
707
    // =====================================================================
708
    // set_single_cursor / set_single_range
709
    // =====================================================================
710

            
711
    #[test]
712
    fn set_single_cursor_collapses_all_selections() {
713
        let mut mc = state(0);
714
        let _ = mc.add_cursor(c(10));
715
        let _ = mc.add_selection(rng(20, 30));
716
        mc.set_single_cursor(c(7));
717
        assert_eq!(mc.len(), 1);
718
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(7)));
719
        assert_primary_resolves(&mc);
720
        assert_eq!(mc.get_primary_cursor(), Some(c(7)));
721
    }
722

            
723
    #[test]
724
    fn set_single_range_collapses_all_selections() {
725
        let mut mc = state(0);
726
        let _ = mc.add_cursor(c(10));
727
        mc.set_single_range(rng(u32::MAX - 2, u32::MAX));
728
        assert_eq!(mc.len(), 1);
729
        assert_eq!(
730
            mc.selections[0].selection,
731
            Selection::Range(rng(u32::MAX - 2, u32::MAX))
732
        );
733
        assert_primary_resolves(&mc);
734
    }
735

            
736
    #[test]
737
    fn set_single_cursor_on_empty_state_mints_a_fresh_id() {
738
        let mut mc = empty_state();
739
        let stale = mc.primary_id;
740
        mc.set_single_cursor(c(1));
741
        assert_eq!(mc.len(), 1);
742
        assert_ne!(
743
            mc.primary_id, stale,
744
            "no last element -> a new id is minted"
745
        );
746
        assert_primary_resolves(&mc);
747
    }
748

            
749
    #[test]
750
    fn set_single_range_on_empty_state_mints_a_fresh_id() {
751
        let mut mc = empty_state();
752
        mc.set_single_range(rng(0, 0));
753
        assert_eq!(mc.len(), 1);
754
        assert_eq!(mc.selections[0].selection, Selection::Range(rng(0, 0)));
755
        assert_primary_resolves(&mc);
756
    }
757

            
758
    #[test]
759
    fn set_single_cursor_is_idempotent() {
760
        let mut mc = state(0);
761
        mc.set_single_cursor(c(5));
762
        let first = mc.clone();
763
        mc.set_single_cursor(c(5));
764
        assert_eq!(mc, first, "re-setting the same cursor must reuse the id");
765
    }
766

            
767
    // =====================================================================
768
    // merge_overlapping
769
    // =====================================================================
770

            
771
    #[test]
772
    fn merge_overlapping_on_empty_and_single_is_a_noop() {
773
        let mut e = empty_state();
774
        e.merge_overlapping();
775
        assert!(e.is_empty());
776

            
777
        let mut one = state(3);
778
        let before = one.clone();
779
        one.merge_overlapping();
780
        assert_eq!(one, before);
781
    }
782

            
783
    #[test]
784
    fn merge_overlapping_collapses_a_whole_chain() {
785
        let mut mc = empty_state();
786
        let ids: Vec<SelectionId> = (0..4).map(|_| SelectionId::new()).collect();
787
        mc.selections = vec![
788
            ident(ids[0], Selection::Range(rng(25, 40))),
789
            ident(ids[1], Selection::Range(rng(0, 10))),
790
            ident(ids[2], Selection::Range(rng(12, 30))),
791
            ident(ids[3], Selection::Range(rng(5, 15))),
792
        ];
793
        mc.primary_id = ids[3];
794
        mc.merge_overlapping();
795
        // 0..10 ∪ 5..15 ∪ 12..30 ∪ 25..40 = one contiguous 0..40
796
        assert_eq!(mc.len(), 1);
797
        assert_eq!(mc.selections[0].selection, Selection::Range(rng(0, 40)));
798
        assert_sorted_nonoverlapping(&mc);
799
        assert_primary_resolves(&mc);
800
    }
801

            
802
    #[test]
803
    fn merge_overlapping_keeps_disjoint_selections_and_sorts_them() {
804
        let mut mc = empty_state();
805
        let ids: Vec<SelectionId> = (0..3).map(|_| SelectionId::new()).collect();
806
        mc.selections = vec![
807
            ident(ids[0], Selection::Cursor(c(100))),
808
            ident(ids[1], Selection::Range(rng(0, 5))),
809
            ident(ids[2], Selection::Cursor(c(50))),
810
        ];
811
        mc.primary_id = ids[0];
812
        mc.merge_overlapping();
813
        assert_eq!(mc.len(), 3);
814
        assert_eq!(
815
            mc.to_selections(),
816
            vec![
817
                Selection::Range(rng(0, 5)),
818
                Selection::Cursor(c(50)),
819
                Selection::Cursor(c(100)),
820
            ]
821
        );
822
        assert_sorted_nonoverlapping(&mc);
823
        // The primary (byte 100) survived the sort untouched.
824
        assert_eq!(mc.primary_id, ids[0]);
825
        assert_eq!(mc.get_primary_cursor(), Some(c(100)));
826
    }
827

            
828
    #[test]
829
    fn merge_overlapping_zero_width_merge_yields_a_cursor_not_a_range() {
830
        let mut mc = empty_state();
831
        let ids: Vec<SelectionId> = (0..2).map(|_| SelectionId::new()).collect();
832
        mc.selections = vec![
833
            ident(ids[0], Selection::Cursor(c(8))),
834
            ident(ids[1], Selection::Range(rng(8, 8))),
835
        ];
836
        mc.primary_id = ids[1];
837
        mc.merge_overlapping();
838
        assert_eq!(mc.len(), 1);
839
        // new_start == new_end -> collapses back to a Cursor.
840
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(8)));
841
        assert_primary_resolves(&mc);
842
    }
843

            
844
    #[test]
845
    fn merge_overlapping_is_idempotent() {
846
        let mut mc = empty_state();
847
        let ids: Vec<SelectionId> = (0..5).map(|_| SelectionId::new()).collect();
848
        mc.selections = vec![
849
            ident(ids[0], Selection::Range(rng(0, 10))),
850
            ident(ids[1], Selection::Cursor(c(5))),
851
            ident(ids[2], Selection::Range(rng(30, 20))), // reversed
852
            ident(ids[3], Selection::Cursor(c(100))),
853
            ident(ids[4], Selection::Range(rng(99, 101))),
854
        ];
855
        mc.primary_id = ids[2];
856
        mc.merge_overlapping();
857
        let once = mc.clone();
858
        mc.merge_overlapping();
859
        assert_eq!(mc, once, "merge_overlapping must be a fixed point");
860
        assert_sorted_nonoverlapping(&mc);
861
        assert_primary_resolves(&mc);
862
    }
863

            
864
    #[test]
865
    fn merge_overlapping_adversarial_200_selections_keeps_invariants() {
866
        let mut mc = empty_state();
867
        let mut seed: u32 = 0x1234_5678;
868
        let mut next = || {
869
            seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
870
            seed
871
        };
872
        let mut sels = Vec::new();
873
        for i in 0..200u32 {
874
            let a = next() % 1000;
875
            let b = next() % 1000;
876
            let sel = match i % 4 {
877
                0 => Selection::Cursor(c(a)),
878
                1 => Selection::Range(SelectionRange {
879
                    start: c(a),
880
                    end: c(b),
881
                }), // may be reversed
882
                2 => Selection::Range(rng(a.min(b), a.max(b))),
883
                _ => Selection::Cursor(c_full(
884
                    0,
885
                    a,
886
                    if b % 2 == 0 {
887
                        CursorAffinity::Leading
888
                    } else {
889
                        CursorAffinity::Trailing
890
                    },
891
                )),
892
            };
893
            sels.push(ident(SelectionId::new(), sel));
894
        }
895
        // Throw in the absolute boundaries too.
896
        sels.push(ident(SelectionId::new(), Selection::Cursor(c(0))));
897
        sels.push(ident(SelectionId::new(), Selection::Cursor(c(u32::MAX))));
898
        sels.push(ident(
899
            SelectionId::new(),
900
            Selection::Range(rng(u32::MAX - 1, u32::MAX)),
901
        ));
902
        mc.primary_id = sels[7].id;
903
        mc.selections = sels;
904

            
905
        mc.merge_overlapping();
906

            
907
        assert!(!mc.is_empty());
908
        assert!(mc.len() <= 203);
909
        assert_sorted_nonoverlapping(&mc);
910
        assert_primary_resolves(&mc);
911
        assert_ids_unique(&mc);
912
    }
913

            
914
    #[test]
915
    fn merge_overlapping_primary_inside_a_chain_still_resolves() {
916
        // Three cursors that all collapse into one, plus a far-away cursor.
917
        // The primary is the *first* link of the merge chain.
918
        let mut mc = empty_state();
919
        let ids: Vec<SelectionId> = (0..4).map(|_| SelectionId::new()).collect();
920
        mc.selections = vec![
921
            ident(ids[0], Selection::Cursor(c(0))),
922
            ident(ids[1], Selection::Cursor(c(0))),
923
            ident(ids[2], Selection::Cursor(c(0))),
924
            ident(ids[3], Selection::Cursor(c(100))),
925
        ];
926
        mc.primary_id = ids[0];
927
        mc.merge_overlapping();
928

            
929
        assert_eq!(mc.len(), 2);
930
        // Whatever the merge does with ids, `primary_id` must never dangle.
931
        assert!(
932
            mc.selections.iter().any(|s| s.id == mc.primary_id),
933
            "primary_id must name a surviving selection"
934
        );
935
        assert!(mc.get_primary().is_some());
936
    }
937

            
938
    #[test]
939
    fn merge_overlapping_primary_should_follow_its_merge_chain() {
940
        // Same setup as above. `merge_overlapping` records `new_primary = sel.id`
941
        // when the chain's head is the primary, but the head's id is then
942
        // overwritten by the *next* merge, so `new_primary` points at an id that
943
        // no longer exists. ensure_primary_valid() then silently adopts the
944
        // vector's LAST element — the unrelated cursor at byte 100.
945
        //
946
        // Expected: the primary follows the merged selection it was part of (byte 0).
947
        let mut mc = empty_state();
948
        let ids: Vec<SelectionId> = (0..4).map(|_| SelectionId::new()).collect();
949
        mc.selections = vec![
950
            ident(ids[0], Selection::Cursor(c(0))),
951
            ident(ids[1], Selection::Cursor(c(0))),
952
            ident(ids[2], Selection::Cursor(c(0))),
953
            ident(ids[3], Selection::Cursor(c(100))),
954
        ];
955
        mc.primary_id = ids[0];
956
        mc.merge_overlapping();
957
        assert_eq!(
958
            mc.get_primary_cursor(),
959
            Some(c(0)),
960
            "primary jumped to an unrelated selection after the merge"
961
        );
962
    }
963

            
964
    // =====================================================================
965
    // move_all_cursors
966
    // =====================================================================
967

            
968
    #[test]
969
    fn move_all_cursors_identity_leaves_positions_unchanged() {
970
        let mut mc = state(0);
971
        let _ = mc.add_cursor(c(10));
972
        let _ = mc.add_cursor(c(20));
973
        let before = mc.to_selections();
974
        mc.move_all_cursors(false, |cur| *cur);
975
        assert_eq!(mc.to_selections(), before);
976
        assert_eq!(mc.len(), 3);
977
        assert_primary_resolves(&mc);
978
    }
979

            
980
    #[test]
981
    fn move_all_cursors_extend_with_no_movement_keeps_a_cursor() {
982
        // `*c != new_cursor` is false -> the selection must stay a Cursor,
983
        // not degenerate into a zero-width Range.
984
        let mut mc = state(4);
985
        mc.move_all_cursors(true, |cur| *cur);
986
        assert_eq!(mc.len(), 1);
987
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(4)));
988
    }
989

            
990
    #[test]
991
    fn move_all_cursors_extend_turns_a_cursor_into_a_range() {
992
        let mut mc = state(10);
993
        mc.move_all_cursors(true, |cur| c(cur.cluster_id.start_byte_in_run + 5));
994
        assert_eq!(mc.len(), 1);
995
        assert_eq!(mc.selections[0].selection, Selection::Range(rng(10, 15)));
996
        // The anchor stayed at 10, only the focus moved.
997
        assert_eq!(mc.get_primary_cursor(), Some(c(15)));
998
    }
999

            
    #[test]
    fn move_all_cursors_bare_forward_arrow_collapses_range_to_max_boundary() {
        let mut mc = empty_state();
        mc.set_single_range(rng(3, 9));
        mc.move_all_cursors(false, |cur| c(cur.cluster_id.start_byte_in_run + 1));
        assert_eq!(mc.len(), 1);
        // Collapses to the boundary WITHOUT stepping past it (not byte 10).
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(9)));
    }
    #[test]
    fn move_all_cursors_bare_backward_arrow_collapses_range_to_min_boundary() {
        let mut mc = empty_state();
        mc.set_single_range(rng(3, 9));
        mc.move_all_cursors(false, |cur| {
            c(cur.cluster_id.start_byte_in_run.saturating_sub(1))
        });
        assert_eq!(mc.len(), 1);
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(3)));
    }
    #[test]
    fn move_all_cursors_collapses_a_backwards_range_by_direction_not_field_order() {
        // Backwards range (focus at 3, anchor at 9): a forward arrow must still
        // collapse to the max boundary (9), not to the `end` field (3).
        let mut mc = empty_state();
        mc.set_single_range(SelectionRange {
            start: c(9),
            end: c(3),
        });
        mc.move_all_cursors(false, |cur| c(cur.cluster_id.start_byte_in_run + 1));
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(9)));
        let mut back = empty_state();
        back.set_single_range(SelectionRange {
            start: c(9),
            end: c(3),
        });
        back.move_all_cursors(false, |cur| {
            c(cur.cluster_id.start_byte_in_run.saturating_sub(1))
        });
        assert_eq!(back.selections[0].selection, Selection::Cursor(c(3)));
    }
    #[test]
    fn move_all_cursors_without_boundary_collapse_performs_the_step_from_the_focus() {
        // Home over an active range: the caret goes where the step points, not
        // to the range's near edge. `move_fn` here is "go to byte 0".
        let mut mc = empty_state();
        mc.set_single_range(rng(3, 9));
        mc.move_all_cursors_with(false, false, |_| c(0));
        assert_eq!(mc.len(), 1);
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(0)));
        // The same step with the arrow-key rule still answers the boundary.
        let mut arrow = empty_state();
        arrow.set_single_range(rng(3, 9));
        arrow.move_all_cursors_with(false, true, |_| c(0));
        assert_eq!(arrow.selections[0].selection, Selection::Cursor(c(3)));
        // End over the same range: byte 20 is past `hi`, which the boundary
        // rule would have clamped to 9.
        let mut end = empty_state();
        end.set_single_range(rng(3, 9));
        end.move_all_cursors_with(false, false, |_| c(20));
        assert_eq!(end.selections[0].selection, Selection::Cursor(c(20)));
        // A bare cursor is unaffected by the flag either way.
        for collapse in [false, true] {
            let mut bare = state(5);
            bare.move_all_cursors_with(false, collapse, |_| c(0));
            assert_eq!(bare.selections[0].selection, Selection::Cursor(c(0)));
        }
    }
    #[test]
    fn move_all_cursors_extend_back_onto_the_anchor_collapses_to_a_cursor() {
        let mut mc = empty_state();
        mc.set_single_range(rng(3, 4));
        // Shrink the focus back onto the anchor: r.start == new_end.
        mc.move_all_cursors(true, |_| c(3));
        assert_eq!(mc.len(), 1);
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(3)));
    }
    #[test]
    fn move_all_cursors_constant_move_fn_merges_everything_into_one() {
        let mut mc = state(0);
        for i in 1..5u32 {
            let _ = mc.add_cursor(c(i * 10));
        }
        assert_eq!(mc.len(), 5);
        mc.move_all_cursors(false, |_| c(7));
        assert_eq!(mc.len(), 1, "colliding cursors must be merged afterwards");
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(7)));
        assert_primary_resolves(&mc);
        assert_sorted_nonoverlapping(&mc);
    }
    #[test]
    fn move_all_cursors_saturating_at_u32_max_does_not_overflow() {
        let mut mc = empty_state();
        let ids: Vec<SelectionId> = (0..2).map(|_| SelectionId::new()).collect();
        mc.selections = vec![
            ident(ids[0], Selection::Cursor(c(u32::MAX - 1))),
            ident(ids[1], Selection::Cursor(c(u32::MAX))),
        ];
        mc.primary_id = ids[1];
        mc.move_all_cursors(false, |cur| {
            c(cur.cluster_id.start_byte_in_run.saturating_add(1))
        });
        // Both saturate to u32::MAX and merge.
        assert_eq!(mc.len(), 1);
        assert_eq!(mc.selections[0].selection, Selection::Cursor(c(u32::MAX)));
        assert_primary_resolves(&mc);
    }
    #[test]
    fn move_all_cursors_on_empty_state_does_not_panic() {
        let mut mc = empty_state();
        mc.move_all_cursors(false, |cur| *cur);
        mc.move_all_cursors(true, |_| c(u32::MAX));
        assert!(mc.is_empty());
    }
    #[test]
    fn move_all_cursors_stress_keeps_invariants() {
        let mut mc = state(0);
        for i in 1..100u32 {
            let _ = mc.add_cursor(c(i * 5));
        }
        for _ in 0..10 {
            mc.move_all_cursors(false, |cur| {
                // Fold every cursor into a small window -> heavy merging.
                c(cur.cluster_id.start_byte_in_run % 7)
            });
            assert_sorted_nonoverlapping(&mc);
            assert_primary_resolves(&mc);
            assert_ids_unique(&mc);
        }
        assert!(mc.len() <= 7);
    }
    // =====================================================================
    // remap_node_ids
    // =====================================================================
    #[test]
    fn remap_node_ids_for_a_different_dom_is_a_noop() {
        let mut mc = MultiCursorState::new_with_cursor(c(1), dom_node(5), 0);
        mc.node_id.dom = DomId { inner: 7 };
        let before = mc.clone();
        let mut map = BTreeMap::new();
        map.insert(NodeId::new(5), NodeId::new(9));
        mc.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(mc, before, "a foreign DomId must not touch this state");
    }
    #[test]
    fn remap_node_ids_rewrites_a_surviving_node() {
        let mut mc = MultiCursorState::new_with_cursor(c(1), dom_node(5), 0);
        let mut map = BTreeMap::new();
        map.insert(NodeId::new(5), NodeId::new(9));
        mc.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(mc.node_id.node.into_crate_internal(), Some(NodeId::new(9)));
        assert_eq!(mc.len(), 1, "selections survive a successful remap");
        assert_primary_resolves(&mc);
    }
    #[test]
    fn remap_node_ids_clears_selections_when_the_node_was_removed() {
        let mut mc = MultiCursorState::new_with_cursor(c(1), dom_node(5), 0);
        let _ = mc.add_cursor(c(20));
        let map: BTreeMap<NodeId, NodeId> = BTreeMap::new(); // node 5 is gone
        mc.remap_node_ids(DomId::ROOT_ID, &map);
        assert!(mc.is_empty(), "a removed node must drop its selections");
        assert!(mc.get_primary().is_none());
        // node_id itself is left alone (only selections are cleared).
        assert_eq!(mc.node_id.node.into_crate_internal(), Some(NodeId::new(5)));
    }
    #[test]
    fn remap_node_ids_with_a_none_node_is_a_noop() {
        // DomNodeId::ROOT carries NodeHierarchyItemId::NONE -> into_crate_internal()
        // is None, so neither branch runs and the selections must survive.
        let mut mc = state(3);
        let map: BTreeMap<NodeId, NodeId> = BTreeMap::new();
        mc.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(mc.len(), 1);
        assert_eq!(mc.node_id.node, NodeHierarchyItemId::NONE);
        assert_primary_resolves(&mc);
    }
    #[test]
    fn remap_node_ids_handles_large_node_indices() {
        let big = 1_000_000usize;
        let mut mc = MultiCursorState::new_with_cursor(c(1), dom_node(big), 0);
        let mut map = BTreeMap::new();
        map.insert(NodeId::new(big), NodeId::new(big * 2));
        mc.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(
            mc.node_id.node.into_crate_internal(),
            Some(NodeId::new(big * 2))
        );
    }
    #[test]
    fn remap_node_ids_twice_is_stable() {
        let mut mc = MultiCursorState::new_with_cursor(c(1), dom_node(5), 0);
        let mut map = BTreeMap::new();
        map.insert(NodeId::new(5), NodeId::new(9));
        map.insert(NodeId::new(9), NodeId::new(9)); // identity for the new id
        mc.remap_node_ids(DomId::ROOT_ID, &map);
        mc.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(mc.node_id.node.into_crate_internal(), Some(NodeId::new(9)));
        assert_eq!(mc.len(), 1);
    }
    // =====================================================================
    // selection_start_pos / selection_end_pos  (private helpers)
    // =====================================================================
    #[test]
    fn selection_pos_helpers_normalize_reversed_ranges() {
        let forward = Selection::Range(rng(3, 9));
        assert_eq!(selection_start_pos(&forward), c(3));
        assert_eq!(selection_end_pos(&forward), c(9));
        let backward = Selection::Range(SelectionRange {
            start: c(9),
            end: c(3),
        });
        assert_eq!(selection_start_pos(&backward), c(3));
        assert_eq!(selection_end_pos(&backward), c(9));
        let cursor = Selection::Cursor(c(5));
        assert_eq!(selection_start_pos(&cursor), c(5));
        assert_eq!(selection_end_pos(&cursor), c(5));
    }
    #[test]
    fn selection_pos_helpers_start_never_exceeds_end() {
        let mut seed: u32 = 0xACE1_BEEF;
        let mut next = || {
            seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            seed
        };
        let extremes = [0u32, 1, u32::MAX - 1, u32::MAX];
        let mut cases: Vec<Selection> = Vec::new();
        for a in extremes {
            for b in extremes {
                cases.push(Selection::Range(SelectionRange {
                    start: c_full(a, b, CursorAffinity::Trailing),
                    end: c_full(b, a, CursorAffinity::Leading),
                }));
                cases.push(Selection::Cursor(c_full(a, b, CursorAffinity::Leading)));
            }
        }
        for _ in 0..200 {
            cases.push(Selection::Range(SelectionRange {
                start: c(next()),
                end: c(next()),
            }));
        }
        for sel in &cases {
            assert!(
                selection_start_pos(sel) <= selection_end_pos(sel),
                "start must never sort after end: {sel:?}"
            );
        }
    }
    #[test]
    fn selection_pos_helpers_respect_affinity_ordering() {
        // Same byte, different affinity: Leading < Trailing.
        let sel = Selection::Range(SelectionRange {
            start: c_full(0, 4, CursorAffinity::Trailing),
            end: c_full(0, 4, CursorAffinity::Leading),
        });
        assert_eq!(
            selection_start_pos(&sel),
            c_full(0, 4, CursorAffinity::Leading)
        );
        assert_eq!(
            selection_end_pos(&sel),
            c_full(0, 4, CursorAffinity::Trailing)
        );
    }
    // =====================================================================
    // TextSelection
    // =====================================================================
    fn rect(x: f32, y: f32, w: f32, h: f32) -> LogicalRect {
        LogicalRect::new(LogicalPosition::new(x, y), LogicalSize::new(w, h))
    }
    #[test]
    fn new_collapsed_invariants_hold() {
        let node = NodeId::new(3);
        let sel = TextSelection::new_collapsed(
            DomId::ROOT_ID,
            node,
            c(7),
            rect(1.0, 2.0, 3.0, 4.0),
            LogicalPosition::new(5.0, 6.0),
        );
        assert!(sel.is_collapsed());
        assert!(sel.is_forward);
        assert_eq!(sel.dom_id, DomId::ROOT_ID);
        assert_eq!(sel.anchor.ifc_root_node_id, node);
        assert_eq!(sel.focus.ifc_root_node_id, node);
        assert_eq!(sel.anchor.cursor, c(7));
        assert_eq!(sel.focus.cursor, c(7));
        assert_eq!(sel.affected_nodes.len(), 1);
        // The collapsed node maps to a zero-width range at the cursor.
        assert_eq!(
            sel.get_range_for_node(&node),
            Some(&SelectionRange {
                start: c(7),
                end: c(7),
            })
        );
    }
    #[test]
    fn new_collapsed_with_non_finite_geometry_does_not_panic() {
        let node = NodeId::new(0);
        let sel = TextSelection::new_collapsed(
            DomId::ROOT_ID,
            node,
            c_full(u32::MAX, u32::MAX, CursorAffinity::Trailing),
            rect(f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX),
            LogicalPosition::new(f32::NAN, f32::NEG_INFINITY),
        );
        // Geometry is carried verbatim; only the cursors decide collapsedness.
        assert!(sel.is_collapsed());
        assert!(sel.get_range_for_node(&node).is_some());
        assert!(sel.anchor.char_bounds.origin.x.is_nan());
    }
    #[test]
    fn get_range_for_node_returns_none_for_an_unaffected_node() {
        let sel = TextSelection::new_collapsed(
            DomId::ROOT_ID,
            NodeId::new(3),
            c(0),
            rect(0.0, 0.0, 0.0, 0.0),
            LogicalPosition::new(0.0, 0.0),
        );
        assert!(sel.get_range_for_node(&NodeId::new(4)).is_none());
        assert!(sel.get_range_for_node(&NodeId::new(0)).is_none());
        assert!(sel.get_range_for_node(&NodeId::new(usize::MAX)).is_none());
    }
    #[test]
    fn get_range_for_node_on_an_empty_map_returns_none() {
        let node = NodeId::new(3);
        let mut sel = TextSelection::new_collapsed(
            DomId::ROOT_ID,
            node,
            c(0),
            rect(0.0, 0.0, 0.0, 0.0),
            LogicalPosition::new(0.0, 0.0),
        );
        sel.affected_nodes.clear();
        assert!(sel.get_range_for_node(&node).is_none());
        assert!(
            sel.is_collapsed(),
            "collapsedness does not depend on the map"
        );
    }
    #[test]
    fn ranges_for_node_returns_every_range_the_node_carries() {
        // A Ctrl+D session puts all of its occurrences on ONE node, so the
        // carrier has to be a list — the map used to hold a single range and
        // every occurrence but one was unexpressible.
        let node = NodeId::new(3);
        let mut sel = TextSelection::new_collapsed(
            DomId::ROOT_ID,
            node,
            c(0),
            rect(0.0, 0.0, 0.0, 0.0),
            LogicalPosition::new(0.0, 0.0),
        );
        let first = SelectionRange {
            start: c(0),
            end: c(2),
        };
        let second = SelectionRange {
            start: c(5),
            end: c(7),
        };
        sel.affected_nodes.insert(node, vec![first, second]);
        assert_eq!(sel.ranges_for_node(&node), &[first, second]);
        assert_eq!(
            sel.get_range_for_node(&node),
            Some(&first),
            "the single-range accessor answers with the FIRST range"
        );
        assert!(sel.ranges_for_node(&NodeId::new(4)).is_empty());
        sel.affected_nodes.insert(node, Vec::new());
        assert!(sel.ranges_for_node(&node).is_empty());
        assert!(
            sel.get_range_for_node(&node).is_none(),
            "an empty list is not a range"
        );
    }
    #[test]
    fn is_collapsed_is_false_when_the_focus_cursor_moves() {
        let node = NodeId::new(3);
        let mut sel = TextSelection::new_collapsed(
            DomId::ROOT_ID,
            node,
            c(7),
            rect(0.0, 0.0, 1.0, 1.0),
            LogicalPosition::new(0.0, 0.0),
        );
        assert!(sel.is_collapsed());
        sel.focus.cursor = c(8);
        assert!(!sel.is_collapsed());
    }
    #[test]
    fn is_collapsed_is_false_when_the_focus_crosses_into_another_ifc() {
        let mut sel = TextSelection::new_collapsed(
            DomId::ROOT_ID,
            NodeId::new(3),
            c(7),
            rect(0.0, 0.0, 1.0, 1.0),
            LogicalPosition::new(0.0, 0.0),
        );
        sel.focus.ifc_root_node_id = NodeId::new(4); // same cursor, different node
        assert!(
            !sel.is_collapsed(),
            "same cursor offset in a different IFC is not a collapsed selection"
        );
    }
    #[test]
    fn is_collapsed_only_looks_at_cursors_not_at_mouse_position() {
        let node = NodeId::new(1);
        let mut sel = TextSelection::new_collapsed(
            DomId::ROOT_ID,
            node,
            c(2),
            rect(0.0, 0.0, 1.0, 1.0),
            LogicalPosition::new(0.0, 0.0),
        );
        sel.focus.mouse_position = LogicalPosition::new(999.0, -999.0);
        assert!(sel.is_collapsed());
    }
}
#[cfg(test)]
mod owner_tests {
    use alloc::{vec, vec::Vec};
    use crate::{
        dom::{DomId, DomNodeId, NodeId},
        selection::{
            CursorAffinity, GraphemeClusterId, MultiCursorState, Selection, SelectionOwner,
            SelectionRange, TextCursor,
        },
        styled_dom::NodeHierarchyItemId,
    };
44
    fn cursor(byte: u32) -> TextCursor {
44
        TextCursor {
44
            cluster_id: GraphemeClusterId {
44
                source_run: 0,
44
                start_byte_in_run: byte,
44
            },
44
            affinity: CursorAffinity::Leading,
44
        }
44
    }
12
    fn node() -> DomNodeId {
12
        DomNodeId {
12
            dom: DomId::ROOT_ID,
12
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(1))),
12
        }
12
    }
12
    fn state() -> MultiCursorState {
12
        MultiCursorState::new_with_cursor(cursor(0), node(), 0)
12
    }
    // ------------------------------------------------------------------
    // U3: a selection is `(owner, id)`; the engine acts on LOCAL only
    // ------------------------------------------------------------------
6
    fn with_peer(mut mc: MultiCursorState, peer: SelectionOwner, at: u32) -> MultiCursorState {
6
        assert!(mc.set_owner_selections(peer, &[Selection::Cursor(cursor(at))]));
6
        mc
6
    }
    #[test]
1
    fn typing_never_lands_on_a_peers_caret() {
        // THE DEFECT: `to_selections` handed every owner's caret to
        // `edit_text`, which inserts at each one - so a local keystroke was
        // typed at the peer's caret too. And `update_from_edit_result` then
        // rebuilt the list as LOCAL, absorbing the peer after one keystroke.
1
        let bob = SelectionOwner::new(2, 2);
1
        let mut mc = with_peer(state(), bob, 7);
1
        let edit_set = mc.to_selections();
1
        assert_eq!(edit_set, vec![Selection::Cursor(cursor(0))], "local only");
2
        let bob_id = mc.selections.iter().find(|s| s.owner == bob).unwrap().id;
1
        let local_id = mc.primary_id;
        // The edit moved the local caret to 1; Bob is not in the result.
1
        mc.update_from_edit_result(&[Selection::Cursor(cursor(1))]);
1
        assert_eq!(mc.len(), 2, "Bob is still in the session");
2
        let bob_after = mc.selections.iter().find(|s| s.owner == bob).unwrap();
1
        assert_eq!(bob_after.id, bob_id, "and keeps his id");
1
        assert_eq!(
            bob_after.selection,
1
            Selection::Cursor(cursor(7)),
            "and his place"
        );
1
        assert_eq!(mc.get_primary().map(|p| p.id), Some(local_id));
1
        assert_eq!(mc.get_primary_cursor(), Some(cursor(1)));
1
    }
    #[test]
1
    fn a_plain_click_keeps_the_peers_in_view() {
1
        let alice = SelectionOwner::new(1, 1);
1
        let mut mc = with_peer(state(), alice, 3);
1
        let _ = mc.add_cursor(cursor(5)); // local multi-cursor
1
        assert_eq!(mc.local_len(), 2);
1
        mc.set_single_cursor(cursor(9));
1
        assert_eq!(mc.local_len(), 1, "the local set collapsed");
1
        assert!(
1
            mc.owners().contains(&alice),
            "the click did not erase Alice"
        );
1
        assert!(mc.get_primary().unwrap().owner.is_local());
1
        mc.set_single_range(SelectionRange {
1
            start: cursor(1),
1
            end: cursor(4),
1
        });
1
        assert_eq!(mc.local_len(), 1);
1
        assert!(mc.owners().contains(&alice));
1
    }
    #[test]
1
    fn the_primary_is_never_a_peer() {
        // The list is owner-sorted, so a `last()` fallback WAS the peer
        // whenever one existed: removing the local primary would have made
        // Bob "the selection" - for the IME, the platform selection, copy.
1
        let bob = SelectionOwner::new(2, 2);
1
        let mut mc = with_peer(state(), bob, 7);
1
        let local_id = mc.primary_id;
1
        assert!(mc.remove_selection(local_id));
1
        assert!(mc.get_primary().is_none(), "no local selection: no primary");
1
        assert!(mc.get_primary_cursor().is_none());
1
        assert_eq!(mc.local_len(), 0);
1
        assert_eq!(mc.len(), 1, "Bob is still painted");
        // With a second local caret, the primary falls back onto IT.
1
        let mut mc = with_peer(state(), bob, 7);
1
        let second = mc.add_cursor(cursor(4));
1
        let first_local = mc
1
            .local_selections()
1
            .map(|s| s.id)
1
            .find(|id| *id != second)
1
            .unwrap();
1
        assert!(mc.remove_selection(second));
1
        assert_eq!(mc.get_primary().map(|p| p.id), Some(first_local));
1
        assert!(mc.get_primary().unwrap().owner.is_local());
1
    }
    #[test]
1
    fn arrow_keys_move_only_the_local_carets() {
1
        let alice = SelectionOwner::new(1, 1);
1
        let mut mc = with_peer(state(), alice, 3);
1
        mc.move_all_cursors(false, |c| cursor(c.cluster_id.start_byte_in_run + 1));
1
        assert_eq!(mc.get_primary_cursor(), Some(cursor(1)));
2
        let alice_sel = mc.selections.iter().find(|s| s.owner == alice).unwrap();
1
        assert_eq!(
            alice_sel.selection,
1
            Selection::Cursor(cursor(3)),
            "Alice did not move"
        );
1
    }
    #[test]
1
    fn local_len_counts_the_carets_typed_into() {
1
        let alice = SelectionOwner::new(1, 1);
1
        let mut mc = with_peer(state(), alice, 3);
1
        let _ = mc.add_cursor(cursor(5));
1
        assert_eq!(mc.len(), 3, "painted");
1
        assert_eq!(mc.local_len(), 2, "typed into");
1
    }
    #[test]
1
    fn the_engines_own_selections_are_local() {
1
        let mc = state();
1
        assert!(mc.selections[0].owner.is_local());
1
        assert_eq!(SelectionOwner::LOCAL, SelectionOwner::default());
1
        assert_eq!(mc.owners(), vec![SelectionOwner::LOCAL]);
1
    }
    /// THE POINT OF THE WHOLE FIELD. Two participants' cursors at the same
    /// place must stay two cursors: merging them would silently delete someone
    /// from the session - their caret absorbed into another person's and
    /// repainted in that person's colour.
    #[test]
1
    fn two_owners_at_the_same_position_do_not_merge() {
1
        let mut mc = state();
1
        let alice = SelectionOwner::new(1, 1);
1
        let bob = SelectionOwner::new(2, 2);
1
        assert!(mc.set_owner_selections(alice, &[Selection::Cursor(cursor(0))]));
1
        assert!(mc.set_owner_selections(bob, &[Selection::Cursor(cursor(0))]));
1
        mc.merge_overlapping();
1
        assert_eq!(mc.selections.len(), 3, "local + two peers, all at offset 0");
1
        assert_eq!(mc.owners().len(), 3);
1
    }
    /// ...but one owner's own overlapping selections still collapse, which is
    /// what `merge_overlapping` is for.
    #[test]
1
    fn one_owners_overlapping_selections_still_merge() {
1
        let mut mc = state();
1
        let alice = SelectionOwner::new(1, 1);
1
        mc.set_owner_selections(
1
            alice,
1
            &[
1
                Selection::Range(SelectionRange {
1
                    start: cursor(0),
1
                    end: cursor(5),
1
                }),
1
                Selection::Range(SelectionRange {
1
                    start: cursor(3),
1
                    end: cursor(9),
1
                }),
1
            ],
        );
1
        mc.merge_overlapping();
2
        let alice_count = mc.selections.iter().filter(|s| s.owner == alice).count();
1
        assert_eq!(alice_count, 1, "one owner's overlaps must still collapse");
1
    }
    /// A remote participant's state is a SNAPSHOT: replacing is what stops a
    /// missed message leaving a stale caret behind forever.
    #[test]
1
    fn injecting_replaces_that_owner_and_leaves_the_others_alone() {
1
        let mut mc = state();
1
        let alice = SelectionOwner::new(1, 1);
1
        let bob = SelectionOwner::new(2, 2);
1
        mc.set_owner_selections(
1
            alice,
1
            &[Selection::Cursor(cursor(0)), Selection::Cursor(cursor(4))],
        );
1
        mc.set_owner_selections(bob, &[Selection::Cursor(cursor(8))]);
4
        assert_eq!(mc.selections.iter().filter(|s| s.owner == alice).count(), 2);
1
        mc.set_owner_selections(alice, &[Selection::Cursor(cursor(2))]);
1
        assert_eq!(
3
            mc.selections.iter().filter(|s| s.owner == alice).count(),
            1,
            "a snapshot replaces, it does not accumulate"
        );
3
        assert_eq!(mc.selections.iter().filter(|s| s.owner == bob).count(), 1);
1
        assert!(mc.selections.iter().any(|s| s.owner.is_local()));
1
    }
    #[test]
1
    fn a_participant_who_leaves_takes_only_their_own_carets() {
1
        let mut mc = state();
1
        let alice = SelectionOwner::new(1, 1);
1
        let bob = SelectionOwner::new(2, 2);
1
        mc.set_owner_selections(alice, &[Selection::Cursor(cursor(0))]);
1
        mc.set_owner_selections(bob, &[Selection::Cursor(cursor(4))]);
1
        assert_eq!(mc.remove_owner(alice), 1);
1
        assert!(!mc.owners().contains(&alice));
1
        assert!(mc.owners().contains(&bob));
1
        assert!(mc.selections.iter().any(|s| s.owner.is_local()));
1
    }
    /// THE LOCAL CARET IS THE ENGINE'S. Letting an app overwrite or delete it
    /// through the remote door would make every text-editing invariant the
    /// engine maintains someone else's problem - and removing it would leave
    /// the document with no caret at all.
    #[test]
1
    fn the_local_owner_cannot_be_injected_or_removed() {
1
        let mut mc = state();
1
        assert!(!mc.set_owner_selections(SelectionOwner::LOCAL, &[Selection::Cursor(cursor(9))]));
1
        assert_eq!(mc.remove_owner(SelectionOwner::LOCAL), 0);
1
        assert_eq!(mc.selections.len(), 1);
1
        assert!(mc.selections[0].owner.is_local());
1
    }
}
/// U3-a: a peer's caret moves with the text it is anchored in.
#[cfg(test)]
mod peer_shift_tests {
    use super::*;
    use crate::styled_dom::NodeHierarchyItemId;
30
    fn cursor(byte: u32) -> TextCursor {
30
        TextCursor {
30
            cluster_id: GraphemeClusterId {
30
                source_run: 0,
30
                start_byte_in_run: byte,
30
            },
30
            affinity: CursorAffinity::Leading,
30
        }
30
    }
8
    fn node() -> DomNodeId {
8
        DomNodeId {
8
            dom: DomId::ROOT_ID,
8
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(1))),
8
        }
8
    }
8
    fn with_peer_at(at: Selection) -> (MultiCursorState, SelectionOwner) {
8
        let bob = SelectionOwner::new(2, 2);
8
        let mut mc = MultiCursorState::new_with_cursor(cursor(0), node(), 0);
8
        assert!(mc.set_owner_selections(bob, &[at]));
8
        (mc, bob)
8
    }
10
    fn peer(mc: &MultiCursorState, who: SelectionOwner) -> Selection {
10
        mc.selections
10
            .iter()
20
            .find(|s| s.owner == who)
10
            .unwrap()
            .selection
10
    }
17
    fn change(start: u32, end: u32, inserted: u32) -> RunTextChange {
17
        RunTextChange {
17
            run: 0,
17
            start,
17
            end,
17
            inserted,
17
        }
17
    }
    #[test]
1
    fn the_diff_between_two_texts_is_the_replaced_middle() {
1
        assert_eq!(
1
            RunTextChange::between(0, "hello", "hexllo"),
1
            Some(change(2, 2, 1))
        );
1
        assert_eq!(
1
            RunTextChange::between(0, "abc", "ac"),
1
            Some(change(1, 2, 0))
        );
1
        assert_eq!(
1
            RunTextChange::between(0, "abcd", "aXYd"),
1
            Some(change(1, 3, 2))
        );
1
        assert_eq!(RunTextChange::between(0, "same", "same"), None);
1
        assert_eq!(RunTextChange::between(0, "", "new"), Some(change(0, 0, 3)));
1
        assert_eq!(RunTextChange::between(0, "gone", ""), Some(change(0, 4, 0)));
1
    }
    /// Inserting a repeated character: the prefix wins, the change lands
    /// AFTER the existing copy, and the arithmetic stays consistent (no
    /// overlap between prefix and suffix).
    #[test]
1
    fn a_repeated_character_is_placed_after_its_twin() {
1
        assert_eq!(
1
            RunTextChange::between(0, "aa", "aaa"),
1
            Some(change(2, 2, 1))
        );
1
        assert_eq!(
1
            RunTextChange::between(0, "aaa", "aa"),
1
            Some(change(2, 3, 0))
        );
1
    }
    /// A change never starts or ends inside a multi-byte character.
    #[test]
1
    fn the_diff_respects_char_boundaries() {
        // 'é' (C3 A9) -> 'è' (C3 A8): the first byte is shared, but the
        // change must cover the whole character.
1
        assert_eq!(
1
            RunTextChange::between(0, "\u{e9}", "\u{e8}"),
1
            Some(change(0, 2, 2))
        );
1
    }
    /// U3-a-i: a merge of two runs, a split of one, and a delete spanning
    /// runs all move a peer caret to the same text it was at.
    #[test]
1
    fn a_run_remap_carries_carets_across_merges_splits_and_spanning_deletes() {
        use crate::selection::{RunRemap, RunTextDiff};
1
        let at = |run: u32, byte: u32| TextCursor {
20
            cluster_id: GraphemeClusterId {
20
                source_run: run,
20
                start_byte_in_run: byte,
20
            },
20
            affinity: CursorAffinity::Leading,
20
        };
        // ["ab", "cd", "ef"] -> ["abcd", "ef"]: runs 0..2 merged.
1
        let merge = RunRemap {
1
            first: 0,
1
            old_lens: vec![2, 2],
1
            new_lens: vec![4],
1
            middle: None,
1
            prev_len: None,
1
        };
1
        assert_eq!(
1
            merge.map_cursor(at(1, 1)),
1
            at(0, 3),
            "'d' is byte 3 of the merged run"
        );
1
        assert_eq!(
1
            merge.map_cursor(at(2, 1)),
1
            at(1, 1),
            "the run after moves down by one"
        );
        // ["abcd", "ef"] -> ["ab", "cd", "ef"]: run 0 split.
1
        let split = RunRemap {
1
            first: 0,
1
            old_lens: vec![4],
1
            new_lens: vec![2, 2],
1
            middle: None,
1
            prev_len: None,
1
        };
1
        assert_eq!(split.map_cursor(at(0, 3)), at(1, 1));
1
        assert_eq!(
1
            split.map_cursor(at(0, 2)),
1
            at(0, 2),
            "a boundary caret stays at the end of the first piece"
        );
1
        assert_eq!(split.map_cursor(at(1, 0)), at(2, 0));
        // ["hello", "world"] -> ["heorld"]: "llo" + "w" deleted across the seam.
1
        let spanning = RunRemap {
1
            first: 0,
1
            old_lens: vec![5, 5],
1
            new_lens: vec![6],
1
            middle: RunTextChange::between(0, "helloworld", "heorld"),
1
            prev_len: None,
1
        };
1
        assert_eq!(
1
            spanning.map_cursor(at(1, 3)),
1
            at(0, 4),
            "the 'l' of \"world\" is byte 4 of \"heorld\""
        );
1
        assert_eq!(
1
            spanning.map_cursor(at(0, 4)),
1
            at(0, 2),
            "inside the deleted span collapses to its start"
        );
        // The whole middle vanished: land at the end of the run before it.
1
        let gone = RunRemap {
1
            first: 1,
1
            old_lens: vec![3],
1
            new_lens: vec![],
1
            middle: RunTextChange::between(0, "xyz", ""),
1
            prev_len: Some(5),
1
        };
1
        assert_eq!(gone.map_cursor(at(1, 2)), at(0, 5));
1
        assert_eq!(gone.map_cursor(at(2, 1)), at(1, 1));
        // Through the multi-cursor: Bob's caret and Carol's range both move.
1
        let (mut mc, bob) = with_peer_at(Selection::Cursor(at(1, 1)));
1
        mc.shift_peers_across_diff(&RunTextDiff {
1
            remap: Some(merge.clone()),
1
            changes: Vec::new(),
1
        });
1
        assert_eq!(peer(&mc, bob), Selection::Cursor(at(0, 3)));
1
    }
    #[test]
1
    fn a_change_before_the_caret_shifts_it_and_one_after_does_not() {
        // "hello world", Bob at 6 (before "world").
1
        let (mut mc, bob) = with_peer_at(Selection::Cursor(cursor(6)));
1
        mc.shift_peers_across(&[change(0, 0, 3)]); // insert 3 at the start
1
        assert_eq!(peer(&mc, bob), Selection::Cursor(cursor(9)));
1
        mc.shift_peers_across(&[change(2, 4, 0)]); // delete 2 before him
1
        assert_eq!(peer(&mc, bob), Selection::Cursor(cursor(7)));
1
        mc.shift_peers_across(&[change(9, 9, 5)]); // insert after him
1
        assert_eq!(peer(&mc, bob), Selection::Cursor(cursor(7)));
1
    }
    /// A caret AT a pure insert's position is attached to the character that
    /// follows, so it moves with it.
    #[test]
1
    fn an_insert_at_the_caret_pushes_it_after_the_new_text() {
1
        let (mut mc, bob) = with_peer_at(Selection::Cursor(cursor(4)));
1
        mc.shift_peers_across(&[change(4, 4, 2)]);
1
        assert_eq!(peer(&mc, bob), Selection::Cursor(cursor(6)));
1
    }
    #[test]
1
    fn a_change_spanning_the_caret_collapses_it_to_the_change_start() {
1
        let (mut mc, bob) = with_peer_at(Selection::Cursor(cursor(5)));
1
        mc.shift_peers_across(&[change(3, 8, 1)]); // replace 3..8 by one byte
1
        assert_eq!(peer(&mc, bob), Selection::Cursor(cursor(3)));
1
    }
    #[test]
1
    fn a_peer_range_moves_both_ends_and_may_collapse() {
1
        let range = Selection::Range(SelectionRange {
1
            start: cursor(4),
1
            end: cursor(8),
1
        });
1
        let (mut mc, bob) = with_peer_at(range);
1
        mc.shift_peers_across(&[change(0, 0, 2)]);
1
        assert_eq!(
1
            peer(&mc, bob),
1
            Selection::Range(SelectionRange {
1
                start: cursor(6),
1
                end: cursor(10),
1
            })
        );
        // A replace that swallows the whole range collapses it.
1
        mc.shift_peers_across(&[change(5, 12, 0)]);
1
        assert_eq!(
1
            peer(&mc, bob),
1
            Selection::Range(SelectionRange {
1
                start: cursor(5),
1
                end: cursor(5),
1
            })
        );
1
    }
    /// The local selection is placed by the edit result, never by this.
    #[test]
1
    fn local_selections_are_not_shifted() {
1
        let (mut mc, _bob) = with_peer_at(Selection::Cursor(cursor(6)));
1
        mc.shift_peers_across(&[change(0, 0, 3)]);
1
        assert_eq!(mc.get_primary_cursor(), Some(cursor(0)));
1
    }
    /// U3-b: a change the app's generation brought moves the LOCAL caret too.
    #[test]
1
    fn shift_all_moves_the_local_caret_as_well() {
1
        let (mut mc, bob) = with_peer_at(Selection::Cursor(cursor(6)));
1
        mc.set_single_cursor(cursor(3));
1
        mc.shift_all_across(&[change(0, 0, 2)]);
1
        assert_eq!(mc.get_primary_cursor(), Some(cursor(5)));
1
        assert_eq!(peer(&mc, bob), Selection::Cursor(cursor(8)));
1
    }
    /// A change on ANOTHER run leaves a caret alone.
    #[test]
1
    fn only_the_changed_run_is_affected() {
1
        let (mut mc, bob) = with_peer_at(Selection::Cursor(cursor(6)));
1
        mc.shift_peers_across(&[RunTextChange {
1
            run: 1,
1
            start: 0,
1
            end: 0,
1
            inserted: 3,
1
        }]);
1
        assert_eq!(peer(&mc, bob), Selection::Cursor(cursor(6)));
1
    }
}