loro 1.12.0

Loro is a high-performance CRDTs framework. Make your app collaborative efforlessly.
Documentation
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
use loro::cursor::PosType;
use loro::{ExpandType, LoroDoc, StyleConfig, StyleConfigMap, TextDelta};

// Convert a Unicode scalar index into a byte offset.
fn byte_pos(s: &str, char_index: usize) -> usize {
    s.char_indices()
        .nth(char_index)
        .map(|(idx, _)| idx)
        .unwrap_or_else(|| s.len())
}

// Convert a Unicode scalar index into a UTF-16 code unit offset.
fn utf16_pos(s: &str, char_index: usize) -> usize {
    s.chars().take(char_index).map(|c| c.len_utf16()).sum()
}

#[test]
fn test_slice_delta() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    text.insert(0, "Hello world!").unwrap();
    text.mark(0..5, "bold", true).unwrap();

    // Test slice_delta
    let delta = text.slice_delta(0, 12, PosType::Unicode).unwrap();
    println!("{:?}", delta);

    assert_eq!(delta.len(), 2);

    match &delta[0] {
        TextDelta::Insert { insert, attributes } => {
            assert_eq!(insert, "Hello");
            let attrs = attributes.as_ref().unwrap();
            assert!(attrs.contains_key("bold"));
            assert_eq!(attrs.get("bold").unwrap(), &true.into());
        }
        _ => panic!("Expected Insert, got {:?}", delta[0]),
    }

    match &delta[1] {
        TextDelta::Insert { insert, attributes } => {
            assert_eq!(insert, " world!");
            assert!(attributes.is_none());
        }
        _ => panic!("Expected Insert, got {:?}", delta[1]),
    }

    // Test slice_delta with partial range
    let delta = text.slice_delta(2, 8, PosType::Unicode).unwrap();
    // "llo wo"
    // "llo" (bold), " wo" (no bold)
    assert_eq!(delta.len(), 2);
    match &delta[0] {
        TextDelta::Insert { insert, attributes } => {
            assert_eq!(insert, "llo");
            let attrs = attributes.as_ref().unwrap();
            assert!(attrs.contains_key("bold"));
        }
        _ => panic!("Expected Insert, got {:?}", delta[0]),
    }
    match &delta[1] {
        TextDelta::Insert { insert, attributes } => {
            assert_eq!(insert, " wo");
            assert!(attributes.is_none());
        }
        _ => panic!("Expected Insert, got {:?}", delta[1]),
    }
}

#[test]
fn test_slice_delta_overlapping() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    text.insert(0, "0123456789").unwrap();
    // "01234" bold
    text.mark(0..5, "bold", true).unwrap();
    // "23456" italic
    text.mark(2..7, "italic", true).unwrap();

    // Slice "1234567" (index 1 to 8)
    // 1: bold
    // 234: bold, italic
    // 56: italic
    // 7: none

    let delta = text.slice_delta(1, 8, PosType::Unicode).unwrap();
    assert_eq!(delta.len(), 4);

    // "1"
    if let TextDelta::Insert { insert, attributes } = &delta[0] {
        assert_eq!(insert, "1");
        let attrs = attributes.as_ref().unwrap();
        assert!(attrs.contains_key("bold"));
        assert!(!attrs.contains_key("italic"));
    } else {
        panic!("Expected segment 1")
    }

    // "234"
    if let TextDelta::Insert { insert, attributes } = &delta[1] {
        assert_eq!(insert, "234");
        let attrs = attributes.as_ref().unwrap();
        assert!(attrs.contains_key("bold"));
        assert!(attrs.contains_key("italic"));
    } else {
        panic!("Expected segment 234")
    }

    // "56"
    if let TextDelta::Insert { insert, attributes } = &delta[2] {
        assert_eq!(insert, "56");
        let attrs = attributes.as_ref().unwrap();
        assert!(!attrs.contains_key("bold"));
        assert!(attrs.contains_key("italic"));
    } else {
        panic!("Expected segment 56")
    }

    // "7"
    if let TextDelta::Insert { insert, attributes } = &delta[3] {
        assert_eq!(insert, "7");
        assert!(attributes.is_none());
    } else {
        panic!("Expected segment 7")
    }
}

#[test]
fn test_slice_delta_unicode() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    // "你好" len 2
    // "World" len 5
    text.insert(0, "你好World").unwrap();
    text.mark(0..2, "bold", true).unwrap(); // Mark "你好"

    // Slice "好W" (index 1 to 3)
    let delta = text.slice_delta(1, 3, PosType::Unicode).unwrap();
    assert_eq!(delta.len(), 2);

    // "好"
    if let TextDelta::Insert { insert, attributes } = &delta[0] {
        assert_eq!(insert, "");
        assert!(attributes.as_ref().unwrap().contains_key("bold"));
    } else {
        panic!("Expected segment '好'")
    }

    // "W"
    if let TextDelta::Insert { insert, attributes } = &delta[1] {
        assert_eq!(insert, "W");
        assert!(attributes.is_none());
    } else {
        panic!("Expected segment 'W'")
    }
}

#[test]
fn test_slice_delta_with_deletion() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    text.insert(0, "01234").unwrap();
    text.mark(0..5, "bold", true).unwrap();
    text.delete(2, 2).unwrap(); // delete "23"
                                // Now "014" (all bold)

    let delta = text.slice_delta(0, 3, PosType::Unicode).unwrap();
    assert_eq!(delta.len(), 1);

    if let TextDelta::Insert { insert, attributes } = &delta[0] {
        assert_eq!(insert, "014");
        assert!(attributes.as_ref().unwrap().contains_key("bold"));
    } else {
        panic!("Expected combined segment after deletion")
    }
}

#[test]
fn test_slice_delta_unicode_boundaries() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    // "😀" is 1 char (scalar) in Rust chars().
    text.insert(0, "A😀B").unwrap();

    // Mark "😀" (index 1 to 2)
    text.mark(1..2, "bold", true).unwrap();

    let delta = text.slice_delta(0, 3, PosType::Unicode).unwrap();
    assert_eq!(delta.len(), 3);

    // "A"
    if let TextDelta::Insert { insert, attributes } = &delta[0] {
        assert_eq!(insert, "A");
        assert!(attributes.is_none());
    } else {
        panic!("Expected 'A'")
    }

    // "😀"
    if let TextDelta::Insert { insert, attributes } = &delta[1] {
        assert_eq!(insert, "😀");
        assert!(attributes.as_ref().unwrap().contains_key("bold"));
    } else {
        panic!("Expected Emoji")
    }

    // "B"
    if let TextDelta::Insert { insert, attributes } = &delta[2] {
        assert_eq!(insert, "B");
        assert!(attributes.is_none());
    } else {
        panic!("Expected 'B'")
    }
}

#[test]
fn test_slice_delta_discontinuous_styles() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    text.insert(0, "AB").unwrap();
    text.mark(0..1, "bold", true).unwrap(); // A bold
    text.mark(1..2, "bold", true).unwrap(); // B bold
                                            // Even though they are applied separately, they might merge if they are adjacent and same.
                                            // Let's see if Loro merges adjacent identical styles.
                                            // Usually they should merge into one span if attributes are equal.

    let delta = text.slice_delta(0, 2, PosType::Unicode).unwrap();
    // Depends on implementation. Loro text delta usually merges adjacent same attributes.
    // If so, len is 1.
    if delta.len() == 1 {
        if let TextDelta::Insert { insert, attributes } = &delta[0] {
            assert_eq!(
                insert, "AB",
                "Expected merged segment 'AB', got '{}'",
                insert
            );
            assert!(attributes.as_ref().unwrap().contains_key("bold"));
        } else {
            panic!("Expected merged segment")
        }
    } else {
        // If not merged
        assert_eq!(
            delta.len(),
            2,
            "Expected 1 or 2 segments, got {}",
            delta.len()
        );
        if let TextDelta::Insert { insert, attributes } = &delta[0] {
            assert_eq!(insert, "A");
            assert!(attributes.as_ref().unwrap().contains_key("bold"));
        }
        if let TextDelta::Insert { insert, attributes } = &delta[1] {
            assert_eq!(insert, "B");
            assert!(attributes.as_ref().unwrap().contains_key("bold"));
        }
    }
}

#[test]
fn test_slice_delta_out_of_bounds() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    text.insert(0, "A").unwrap();
    // Slicing beyond end should error
    assert!(text.slice_delta(0, 2, PosType::Unicode).is_err());
}

#[test]
fn test_slice_delta_empty() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    text.insert(0, "A").unwrap();
    let delta = text.slice_delta(0, 0, PosType::Unicode).unwrap();
    assert!(delta.is_empty());
}

#[test]
fn test_slice_delta_utf16_positions() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    let content = "A😀BC💡";
    text.insert(0, content).unwrap();
    let char_len = content.chars().count();
    text.mark(0..2, "bold", true).unwrap(); // A and 😀
    text.mark(4..char_len, "bold", true).unwrap(); // 💡 outside of slice
    text.mark(1..3, "underline", true).unwrap(); // 😀 and B

    let start = utf16_pos(content, 1); // start at 😀 which takes 2 UTF-16 units
    let end = utf16_pos(content, 4); // end right before 💡
    let delta = text.slice_delta(start, end, PosType::Utf16).unwrap();
    assert_eq!(delta.len(), 3);

    if let TextDelta::Insert { insert, attributes } = &delta[0] {
        assert_eq!(insert, "😀");
        let attrs = attributes.as_ref().expect("attributes expected for emoji");
        assert_eq!(attrs.get("bold").unwrap(), &true.into());
        assert_eq!(attrs.get("underline").unwrap(), &true.into());
        assert_eq!(attrs.len(), 2);
    } else {
        panic!("Expected emoji segment");
    }

    if let TextDelta::Insert { insert, attributes } = &delta[1] {
        assert_eq!(insert, "B");
        let attrs = attributes.as_ref().expect("underline expected on 'B'");
        assert!(attrs.get("bold").is_none());
        assert_eq!(attrs.get("underline").unwrap(), &true.into());
    } else {
        panic!("Expected 'B' segment");
    }

    if let TextDelta::Insert { insert, attributes } = &delta[2] {
        assert_eq!(insert, "C");
        assert!(attributes.is_none(), "C should not carry attributes");
    } else {
        panic!("Expected 'C' segment");
    }
}

#[test]
fn utf16_insert_delete_and_slice() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    text.insert(0, "A😀C").unwrap();

    text.insert_utf16(1, "B").unwrap();
    assert_eq!(text.to_string(), "AB😀C");

    let current = text.to_string();
    let emoji_start = utf16_pos(&current, 2);
    text.delete_utf16(emoji_start, 2).unwrap();
    assert_eq!(text.to_string(), "ABC");

    let tail = text.slice_utf16(1, text.len_utf16()).unwrap();
    assert_eq!(tail, "BC");
}

#[test]
fn mark_and_unmark_utf16_ranges() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    let content = "A😀BC";
    text.insert(0, content).unwrap();

    let start = utf16_pos(content, 1);
    let end = utf16_pos(content, 3);
    text.mark_utf16(start..end, "bold", true).unwrap();

    let delta = text
        .slice_delta(0, text.len_unicode(), PosType::Unicode)
        .unwrap();
    assert_eq!(delta.len(), 3);

    if let TextDelta::Insert { insert, attributes } = &delta[0] {
        assert_eq!(insert, "A");
        assert!(attributes.is_none());
    } else {
        panic!("Expected leading segment");
    }

    if let TextDelta::Insert { insert, attributes } = &delta[1] {
        assert_eq!(insert, "😀B");
        let attrs = attributes.as_ref().expect("bold attribute expected");
        assert_eq!(attrs.get("bold"), Some(&true.into()));
    } else {
        panic!("Expected middle segment");
    }

    if let TextDelta::Insert { insert, attributes } = &delta[2] {
        assert_eq!(insert, "C");
        assert!(attributes.is_none());
    } else {
        panic!("Expected trailing segment");
    }

    text.unmark_utf16(start..end, "bold").unwrap();
    let delta = text
        .slice_delta(0, text.len_unicode(), PosType::Unicode)
        .unwrap();
    let mut combined = String::new();
    for segment in &delta {
        if let TextDelta::Insert { insert, attributes } = segment {
            combined.push_str(insert);
            if let Some(attrs) = attributes {
                if let Some(v) = attrs.get("bold") {
                    assert_ne!(
                        v,
                        &true.into(),
                        "expected formatting cleared, got {:?}",
                        attrs
                    );
                }
            }
        } else {
            panic!("Expected insert segment");
        }
    }
    assert_eq!(combined, content);
}

#[test]
fn convert_pos_across_coord_systems() {
    let doc = LoroDoc::new();
    let text = doc.get_text("text");
    let content = "A😀BC";
    text.insert(0, content).unwrap();

    // Unicode -> UTF-16
    assert_eq!(
        text.convert_pos(0, PosType::Unicode, PosType::Utf16),
        Some(0)
    );
    assert_eq!(
        text.convert_pos(1, PosType::Unicode, PosType::Utf16),
        Some(1)
    ); // after 'A'
    assert_eq!(
        text.convert_pos(2, PosType::Unicode, PosType::Utf16),
        Some(3)
    ); // after emoji (2 code units)

    // UTF-16 -> Unicode
    assert_eq!(
        text.convert_pos(3, PosType::Utf16, PosType::Unicode),
        Some(2)
    );

    // Unicode -> Bytes
    let utf8_len_before_emoji = "A".as_bytes().len();
    assert_eq!(
        text.convert_pos(1, PosType::Unicode, PosType::Bytes),
        Some(utf8_len_before_emoji)
    );

    // Out of bounds yields None
    assert_eq!(text.convert_pos(10, PosType::Unicode, PosType::Utf16), None);
}

#[test]
fn test_slice_delta_bytes_with_mixed_attributes() {
    let doc = LoroDoc::new();
    let mut styles = StyleConfigMap::default_rich_text_config();
    styles.insert(
        "script".into(),
        StyleConfig {
            expand: ExpandType::After,
        },
    );
    doc.config_text_style(styles);
    let text = doc.get_text("text");
    let content = "Rä😀汉字Z";
    text.insert(0, content).unwrap();
    let char_len = content.chars().count();
    text.mark(0..3, "bold", true).unwrap(); // R, ä, 😀
    text.mark(4..char_len, "bold", true).unwrap(); // 字 and beyond
    text.mark(2..4, "script", true).unwrap(); // 😀 and 汉

    let start = byte_pos(content, 1); // begin at 'ä' which is multi-byte
    let end = byte_pos(content, 5); // stop before the trailing 'Z'
    let delta = text.slice_delta(start, end, PosType::Bytes).unwrap();
    assert_eq!(delta.len(), 4);

    if let TextDelta::Insert { insert, attributes } = &delta[0] {
        assert_eq!(insert, "ä");
        let attrs = attributes.as_ref().expect("bold expected on 'ä'");
        assert_eq!(attrs.get("bold").unwrap(), &true.into());
        assert_eq!(attrs.len(), 1);
    } else {
        panic!("Expected 'ä' segment");
    }

    if let TextDelta::Insert { insert, attributes } = &delta[1] {
        assert_eq!(insert, "😀");
        let attrs = attributes.as_ref().expect("attributes expected on emoji");
        assert_eq!(attrs.get("bold").unwrap(), &true.into());
        assert_eq!(attrs.get("script").unwrap(), &true.into());
    } else {
        panic!("Expected emoji segment");
    }

    if let TextDelta::Insert { insert, attributes } = &delta[2] {
        assert_eq!(insert, "");
        let attrs = attributes.as_ref().expect("script expected on 汉");
        assert!(attrs.get("bold").is_none());
        assert_eq!(attrs.get("script").unwrap(), &true.into());
        assert_eq!(attrs.len(), 1);
    } else {
        panic!("Expected '汉' segment");
    }

    if let TextDelta::Insert { insert, attributes } = &delta[3] {
        assert_eq!(insert, "");
        let attrs = attributes.as_ref().expect("bold expected on 字");
        assert_eq!(attrs.get("bold").unwrap(), &true.into());
        assert!(attrs.get("script").is_none());
    } else {
        panic!("Expected '字' segment");
    }
}