automorph 0.2.0

Derive macros for bidirectional Automerge-Rust struct synchronization
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Collaborative text type for character-level merging.
//!
//! Unlike regular `String` which uses last-writer-wins semantics, `Text` supports
//! collaborative editing where concurrent insertions and deletions merge correctly.
//!
//! # Example
//!
//! ```rust
//! use automorph::{Automorph, crdt::Text};
//! use automerge::{AutoCommit, ROOT};
//!
//! #[derive(Automorph, Debug, PartialEq)]
//! struct Document {
//!     title: String,
//!     content: Text,
//! }
//!
//! // Create document with initial content
//! let mut doc = Document {
//!     title: "Untitled".to_string(),
//!     content: Text::new("Hello world"),
//! };
//!
//! // Save to Automerge document
//! let mut automerge_doc = AutoCommit::new();
//! doc.save(&mut automerge_doc, &ROOT, "doc").unwrap();
//!
//! // Load it back
//! let loaded = Document::load(&automerge_doc, &ROOT, "doc").unwrap();
//! assert_eq!(loaded.content.as_str(), "Hello world");
//! ```
//!
//! # CRDT Semantics
//!
//! Text uses Automerge's native text type, which is based on the RGA (Replicated Growable Array)
//! CRDT. Key properties:
//!
//! - Concurrent insertions at the same position are ordered deterministically
//! - Concurrent insertion and deletion of the same character: insertion wins
//! - Character positions are stable across concurrent edits
//!
//! # Limitations
//!
//! - No rich text support (use Automerge marks directly for that)
//! - Position-based API may be confusing during concurrent edits (positions shift)
//! - For complex text editing, consider using Automerge's text API directly

use std::fmt;
use std::ops::Deref;

use automerge::{ChangeHash, ObjId, ObjType, Prop, ReadDoc, Value, transaction::Transactable};

use crate::{Automorph, Error, PrimitiveChanged, Result, ScalarCursor};

/// A collaborative text type that supports character-level merging.
///
/// This wraps Automerge's native text type, enabling concurrent edits
/// to merge at the character level rather than using last-writer-wins.
///
/// # Important
///
/// For collaborative benefits, use the mutation methods:
/// - [`insert()`](Self::insert) - Insert text at a position
/// - [`delete()`](Self::delete) - Delete characters at a position
/// - [`splice()`](Self::splice) - Replace a range with new text
///
/// Setting the entire text with [`set()`](Self::set) replaces all content
/// and may lose concurrent edits.
#[derive(Clone, PartialEq, Eq, Hash, Default)]
pub struct Text {
    /// The current text content
    content: String,
    /// Pending operations to apply on save
    pending_ops: Vec<TextOp>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum TextOp {
    /// Insert text at position
    Insert { pos: usize, text: String },
    /// Delete count characters starting at position
    Delete { pos: usize, count: usize },
    /// Replace entire content
    Replace { text: String },
}

impl Text {
    /// Creates a new Text with the given content.
    #[must_use]
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            pending_ops: Vec::new(),
        }
    }

    /// Creates an empty Text.
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Returns the current text content as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        // Apply pending ops to get current view
        // Note: This is a simplified view; actual positions may differ after save
        &self.content
    }

    /// Returns the length of the text in bytes.
    #[must_use]
    pub fn len(&self) -> usize {
        self.content.len()
    }

    /// Returns true if the text is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.content.is_empty()
    }

    /// Inserts text at the given byte position.
    ///
    /// # Panics
    ///
    /// Panics if `pos` is not on a character boundary.
    pub fn insert(&mut self, pos: usize, text: impl Into<String>) {
        let text = text.into();
        if !text.is_empty() {
            // Update local content for immediate feedback
            self.content.insert_str(pos, &text);
            self.pending_ops.push(TextOp::Insert { pos, text });
        }
    }

    /// Appends text to the end.
    pub fn push_str(&mut self, text: impl Into<String>) {
        let pos = self.content.len();
        self.insert(pos, text);
    }

    /// Deletes `count` bytes starting at `pos`.
    ///
    /// # Panics
    ///
    /// Panics if `pos` or `pos + count` is not on a character boundary.
    pub fn delete(&mut self, pos: usize, count: usize) {
        if count > 0 && pos < self.content.len() {
            let actual_count = count.min(self.content.len() - pos);
            // Update local content
            self.content.drain(pos..pos + actual_count);
            self.pending_ops.push(TextOp::Delete {
                pos,
                count: actual_count,
            });
        }
    }

    /// Replaces the range `pos..pos+delete_count` with `text`.
    pub fn splice(&mut self, pos: usize, delete_count: usize, text: impl Into<String>) {
        self.delete(pos, delete_count);
        self.insert(pos, text);
    }

    /// Sets the entire text content.
    ///
    /// **Warning**: This replaces all content and may lose concurrent edits.
    /// Prefer [`insert()`](Self::insert), [`delete()`](Self::delete), or
    /// [`splice()`](Self::splice) for collaborative editing.
    pub fn set(&mut self, content: impl Into<String>) {
        let text = content.into();
        self.content = text.clone();
        self.pending_ops.clear();
        self.pending_ops.push(TextOp::Replace { text });
    }

    /// Returns true if there are pending changes to save.
    #[must_use]
    pub fn has_pending_changes(&self) -> bool {
        !self.pending_ops.is_empty()
    }

    /// Clears all pending operations without saving.
    pub fn clear_pending(&mut self) {
        self.pending_ops.clear();
    }
}

impl fmt::Debug for Text {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Text")
            .field("content", &self.content)
            .field("pending_ops", &self.pending_ops.len())
            .finish()
    }
}

impl fmt::Display for Text {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.content)
    }
}

impl Deref for Text {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.content
    }
}

impl From<String> for Text {
    fn from(s: String) -> Self {
        Self::new(s)
    }
}

impl From<&str> for Text {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

impl From<Text> for String {
    fn from(text: Text) -> Self {
        text.content
    }
}

impl AsRef<str> for Text {
    fn as_ref(&self) -> &str {
        &self.content
    }
}

impl Automorph for Text {
    type Changes = PrimitiveChanged;
    type Cursor = ScalarCursor;

    fn save<D: Transactable + ReadDoc>(
        &self,
        doc: &mut D,
        obj: impl AsRef<ObjId>,
        prop: impl Into<Prop>,
    ) -> Result<()> {
        let prop: Prop = prop.into();
        let obj = obj.as_ref();

        // Check if we need to handle pending ops or just ensure text exists
        let text_id = match doc.get(obj, prop.clone())? {
            Some((Value::Object(ObjType::Text), id)) => {
                // Text object exists
                id
            }
            _ => {
                // Create new text object
                doc.put_object(obj, prop.clone(), ObjType::Text)?
            }
        };

        // If there are pending operations, apply them
        if !self.pending_ops.is_empty() {
            for op in &self.pending_ops {
                match op {
                    TextOp::Insert { pos, text } => {
                        // Splice inserts text at position
                        doc.splice_text(&text_id, *pos, 0, text)?;
                    }
                    TextOp::Delete { pos, count } => {
                        // Splice with delete count and empty string
                        doc.splice_text(&text_id, *pos, *count as isize, "")?;
                    }
                    TextOp::Replace { text } => {
                        // Delete all existing content and insert new
                        let current_len = doc.text(&text_id)?.len();
                        if current_len > 0 {
                            doc.splice_text(&text_id, 0, current_len as isize, "")?;
                        }
                        if !text.is_empty() {
                            doc.splice_text(&text_id, 0, 0, text)?;
                        }
                    }
                }
            }
        } else {
            // No pending ops - ensure content matches
            let current = doc.text(&text_id)?;
            if current != self.content {
                // Replace content
                let current_len = current.len();
                if current_len > 0 {
                    doc.splice_text(&text_id, 0, current_len as isize, "")?;
                }
                if !self.content.is_empty() {
                    doc.splice_text(&text_id, 0, 0, &self.content)?;
                }
            }
        }

        Ok(())
    }

    fn load<D: ReadDoc>(doc: &D, obj: impl AsRef<ObjId>, prop: impl Into<Prop>) -> Result<Self> {
        let prop: Prop = prop.into();
        let obj = obj.as_ref();

        match doc.get(obj, prop)? {
            Some((Value::Object(ObjType::Text), text_id)) => {
                let content = doc.text(&text_id)?;
                Ok(Self {
                    content,
                    pending_ops: Vec::new(),
                })
            }
            // Also accept regular strings for compatibility
            Some((Value::Scalar(s), _)) => {
                if let Some(str_val) = s.to_str() {
                    Ok(Self::new(str_val))
                } else {
                    Err(Error::type_mismatch("Text", Some(format!("{:?}", s))))
                }
            }
            Some((v, _)) => Err(Error::type_mismatch("Text", Some(format!("{:?}", v)))),
            None => Err(Error::missing_value()),
        }
    }

    fn load_at<D: ReadDoc>(
        doc: &D,
        obj: impl AsRef<ObjId>,
        prop: impl Into<Prop>,
        heads: &[ChangeHash],
    ) -> Result<Self> {
        let prop: Prop = prop.into();
        let obj = obj.as_ref();

        match doc.get_at(obj, prop, heads)? {
            Some((Value::Object(ObjType::Text), text_id)) => {
                let content = doc.text_at(&text_id, heads)?;
                Ok(Self {
                    content,
                    pending_ops: Vec::new(),
                })
            }
            // Also accept regular strings for compatibility
            Some((Value::Scalar(s), _)) => {
                if let Some(str_val) = s.to_str() {
                    Ok(Self::new(str_val))
                } else {
                    Err(Error::type_mismatch("Text", Some(format!("{:?}", s))))
                }
            }
            Some((v, _)) => Err(Error::type_mismatch("Text", Some(format!("{:?}", v)))),
            None => Err(Error::missing_value()),
        }
    }

    fn diff<D: ReadDoc>(
        &self,
        doc: &D,
        obj: impl AsRef<ObjId>,
        prop: impl Into<Prop>,
    ) -> Result<Self::Changes> {
        let loaded = Self::load(doc, obj, prop)?;
        Ok(PrimitiveChanged::new(self.content != loaded.content))
    }

    fn diff_at<D: ReadDoc>(
        &self,
        doc: &D,
        obj: impl AsRef<ObjId>,
        prop: impl Into<Prop>,
        heads: &[ChangeHash],
    ) -> Result<Self::Changes> {
        let loaded = Self::load_at(doc, obj, prop, heads)?;
        Ok(PrimitiveChanged::new(self.content != loaded.content))
    }

    fn update<D: ReadDoc>(
        &mut self,
        doc: &D,
        obj: impl AsRef<ObjId>,
        prop: impl Into<Prop>,
    ) -> Result<Self::Changes> {
        let loaded = Self::load(doc, obj, prop)?;
        let changed = self.content != loaded.content;
        self.content = loaded.content;
        self.pending_ops.clear();
        Ok(PrimitiveChanged::new(changed))
    }

    fn update_at<D: ReadDoc>(
        &mut self,
        doc: &D,
        obj: impl AsRef<ObjId>,
        prop: impl Into<Prop>,
        heads: &[ChangeHash],
    ) -> Result<Self::Changes> {
        let loaded = Self::load_at(doc, obj, prop, heads)?;
        let changed = self.content != loaded.content;
        self.content = loaded.content;
        self.pending_ops.clear();
        Ok(PrimitiveChanged::new(changed))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use automerge::{ActorId, AutoCommit, ROOT};

    #[test]
    fn test_text_basic_operations() {
        let mut text = Text::new("hello");
        assert_eq!(text.as_str(), "hello");

        text.insert(5, " world");
        assert_eq!(text.as_str(), "hello world");

        text.delete(5, 6);
        assert_eq!(text.as_str(), "hello");
    }

    #[test]
    fn test_text_roundtrip() {
        let mut doc = AutoCommit::new();

        let text = Text::new("Hello, World!");
        text.save(&mut doc, &ROOT, "greeting").unwrap();

        let loaded = Text::load(&doc, &ROOT, "greeting").unwrap();
        assert_eq!(loaded.as_str(), "Hello, World!");
    }

    #[test]
    fn test_text_incremental_edits() {
        let mut doc = AutoCommit::new();

        // Initial save
        let text = Text::new("hello");
        text.save(&mut doc, &ROOT, "text").unwrap();

        // Load, edit, save
        let mut text = Text::load(&doc, &ROOT, "text").unwrap();
        text.insert(5, " world");
        text.save(&mut doc, &ROOT, "text").unwrap();

        // Verify
        let loaded = Text::load(&doc, &ROOT, "text").unwrap();
        assert_eq!(loaded.as_str(), "hello world");
    }

    #[test]
    fn test_text_concurrent_inserts() {
        // Create initial document
        let mut doc1 = AutoCommit::new();
        let text = Text::new("hello");
        text.save(&mut doc1, &ROOT, "text").unwrap();

        // Fork for concurrent editing
        let mut doc2 = doc1.fork().with_actor(ActorId::random());

        // User 1 inserts " world" at end
        let mut text1 = Text::load(&doc1, &ROOT, "text").unwrap();
        text1.insert(5, " world");
        text1.save(&mut doc1, &ROOT, "text").unwrap();

        // User 2 inserts " there" at end (concurrently, sees original "hello")
        let mut text2 = Text::load(&doc2, &ROOT, "text").unwrap();
        text2.insert(5, " there");
        text2.save(&mut doc2, &ROOT, "text").unwrap();

        // Merge
        doc1.merge(&mut doc2).unwrap();

        // Both insertions should be present
        let merged = Text::load(&doc1, &ROOT, "text").unwrap();
        let merged_str = merged.as_str();

        // Both " world" and " there" should be in the result
        assert!(
            merged_str.contains("world"),
            "Should contain 'world': {}",
            merged_str
        );
        assert!(
            merged_str.contains("there"),
            "Should contain 'there': {}",
            merged_str
        );
    }

    #[test]
    fn test_text_splice() {
        let mut text = Text::new("hello world");
        text.splice(6, 5, "there");
        assert_eq!(text.as_str(), "hello there");
    }

    #[test]
    fn test_text_push_str() {
        let mut text = Text::new("hello");
        text.push_str(" world");
        assert_eq!(text.as_str(), "hello world");
    }

    #[test]
    fn test_text_set_replaces_all() {
        let mut doc = AutoCommit::new();

        let text = Text::new("original content");
        text.save(&mut doc, &ROOT, "text").unwrap();

        let mut text = Text::load(&doc, &ROOT, "text").unwrap();
        text.set("completely new content");
        text.save(&mut doc, &ROOT, "text").unwrap();

        let loaded = Text::load(&doc, &ROOT, "text").unwrap();
        assert_eq!(loaded.as_str(), "completely new content");
    }
}