blocks 0.1.0

A high-performance Rust library for block-based content editing with JSON, Markdown, and HTML support
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/// Diff and Merge module for comparing and merging documents
///
/// Provides functionality to compare documents and merge changes.
use crate::block::Block;
use crate::document::Document;
use crate::error::{BlocksError, Result};
use uuid::Uuid;

/// Represents a change between two documents
#[derive(Debug, Clone, PartialEq)]
pub enum Change {
    /// Block was added
    Added { block: Block, index: usize },
    /// Block was removed
    Removed { block: Block, index: usize },
    /// Block was modified
    Modified {
        old_block: Block,
        new_block: Block,
        index: usize,
    },
    /// Block was moved
    Moved {
        block_id: Uuid,
        old_index: usize,
        new_index: usize,
    },
    /// Title was changed
    TitleChanged {
        old_title: String,
        new_title: String,
    },
    /// Metadata was changed
    MetadataChanged {
        key: String,
        old_value: Option<String>,
        new_value: Option<String>,
    },
}

impl Change {
    /// Returns a description of the change
    pub fn description(&self) -> String {
        match self {
            Self::Added { index, .. } => format!("Added block at index {}", index),
            Self::Removed { index, .. } => format!("Removed block at index {}", index),
            Self::Modified { index, .. } => format!("Modified block at index {}", index),
            Self::Moved {
                old_index,
                new_index,
                ..
            } => format!("Moved block from {} to {}", old_index, new_index),
            Self::TitleChanged {
                old_title,
                new_title,
            } => format!("Title changed from '{}' to '{}'", old_title, new_title),
            Self::MetadataChanged { key, .. } => format!("Metadata '{}' changed", key),
        }
    }

    /// Returns true if this is a content change
    pub fn is_content_change(&self) -> bool {
        matches!(
            self,
            Self::Added { .. } | Self::Removed { .. } | Self::Modified { .. }
        )
    }
}

/// Result of comparing two documents
#[derive(Debug, Clone)]
pub struct DiffResult {
    /// List of changes between documents
    pub changes: Vec<Change>,
    /// ID of the original document
    pub original_id: Uuid,
    /// ID of the modified document
    pub modified_id: Uuid,
}

impl DiffResult {
    /// Returns true if there are no changes
    pub fn is_empty(&self) -> bool {
        self.changes.is_empty()
    }

    /// Returns the number of changes
    pub fn len(&self) -> usize {
        self.changes.len()
    }

    /// Returns only content changes (added, removed, modified)
    pub fn content_changes(&self) -> Vec<&Change> {
        self.changes
            .iter()
            .filter(|c| c.is_content_change())
            .collect()
    }

    /// Returns a summary of changes
    pub fn summary(&self) -> String {
        let added = self
            .changes
            .iter()
            .filter(|c| matches!(c, Change::Added { .. }))
            .count();
        let removed = self
            .changes
            .iter()
            .filter(|c| matches!(c, Change::Removed { .. }))
            .count();
        let modified = self
            .changes
            .iter()
            .filter(|c| matches!(c, Change::Modified { .. }))
            .count();

        format!(
            "{} added, {} removed, {} modified",
            added, removed, modified
        )
    }
}

/// Document differ for comparing documents
pub struct DocumentDiffer;

impl DocumentDiffer {
    /// Compares two documents and returns the differences
    ///
    /// # Arguments
    ///
    /// * `original` - The original document
    /// * `modified` - The modified document
    ///
    /// # Returns
    ///
    /// `DiffResult` containing all changes
    pub fn diff(original: &Document, modified: &Document) -> DiffResult {
        let mut changes = Vec::new();

        // Check title change
        if original.title != modified.title {
            changes.push(Change::TitleChanged {
                old_title: original.title.clone(),
                new_title: modified.title.clone(),
            });
        }

        // Check metadata changes
        for (key, value) in &modified.metadata {
            let old_value = original.metadata.get(key);
            if old_value != Some(value) {
                changes.push(Change::MetadataChanged {
                    key: key.clone(),
                    old_value: old_value.cloned(),
                    new_value: Some(value.clone()),
                });
            }
        }

        // Check for removed metadata
        for (key, value) in &original.metadata {
            if !modified.metadata.contains_key(key) {
                changes.push(Change::MetadataChanged {
                    key: key.clone(),
                    old_value: Some(value.clone()),
                    new_value: None,
                });
            }
        }

        // Build index of blocks by ID
        let original_blocks: std::collections::HashMap<Uuid, (usize, &Block)> = original
            .blocks
            .iter()
            .enumerate()
            .map(|(i, b)| (b.id, (i, b)))
            .collect();

        let modified_blocks: std::collections::HashMap<Uuid, (usize, &Block)> = modified
            .blocks
            .iter()
            .enumerate()
            .map(|(i, b)| (b.id, (i, b)))
            .collect();

        // Find added and modified blocks
        for (i, block) in modified.blocks.iter().enumerate() {
            if let Some((old_idx, old_block)) = original_blocks.get(&block.id) {
                // Block exists - check if modified
                if old_block.content != block.content || old_block.block_type != block.block_type {
                    changes.push(Change::Modified {
                        old_block: (*old_block).clone(),
                        new_block: block.clone(),
                        index: i,
                    });
                } else if *old_idx != i {
                    // Block was moved
                    changes.push(Change::Moved {
                        block_id: block.id,
                        old_index: *old_idx,
                        new_index: i,
                    });
                }
            } else {
                // Block was added
                changes.push(Change::Added {
                    block: block.clone(),
                    index: i,
                });
            }
        }

        // Find removed blocks
        for (i, block) in original.blocks.iter().enumerate() {
            if !modified_blocks.contains_key(&block.id) {
                changes.push(Change::Removed {
                    block: block.clone(),
                    index: i,
                });
            }
        }

        DiffResult {
            changes,
            original_id: original.id,
            modified_id: modified.id,
        }
    }
}

/// Merge strategy for resolving conflicts
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MergeStrategy {
    /// Keep changes from the first document
    KeepFirst,
    /// Keep changes from the second document
    KeepSecond,
    /// Keep both versions (for blocks, creates duplicates)
    KeepBoth,
    /// Fail on conflict
    FailOnConflict,
}

/// Document merger for combining documents
pub struct DocumentMerger {
    strategy: MergeStrategy,
}

impl DocumentMerger {
    /// Creates a new merger with the specified strategy
    pub fn new(strategy: MergeStrategy) -> Self {
        Self { strategy }
    }

    /// Merges two documents into one
    ///
    /// # Arguments
    ///
    /// * `base` - The base document
    /// * `other` - The document to merge in
    ///
    /// # Returns
    ///
    /// `Result<Document>` - The merged document
    pub fn merge(&self, base: &Document, other: &Document) -> Result<Document> {
        let mut result = base.clone();

        // Merge title
        if base.title != other.title {
            result.title = match self.strategy {
                MergeStrategy::KeepFirst => base.title.clone(),
                MergeStrategy::KeepSecond => other.title.clone(),
                MergeStrategy::KeepBoth => format!("{} / {}", base.title, other.title),
                MergeStrategy::FailOnConflict => {
                    return Err(BlocksError::ValidationError {
                        message: "Title conflict".to_string(),
                    });
                }
            };
        }

        // Merge metadata
        for (key, value) in &other.metadata {
            if let Some(existing) = result.metadata.get(key) {
                if existing != value {
                    match self.strategy {
                        MergeStrategy::KeepFirst => {}
                        MergeStrategy::KeepSecond => {
                            result.metadata.insert(key.clone(), value.clone());
                        }
                        MergeStrategy::KeepBoth => {
                            result
                                .metadata
                                .insert(key.clone(), format!("{} / {}", existing, value));
                        }
                        MergeStrategy::FailOnConflict => {
                            return Err(BlocksError::ValidationError {
                                message: format!("Metadata conflict for key: {}", key),
                            });
                        }
                    }
                }
            } else {
                result.metadata.insert(key.clone(), value.clone());
            }
        }

        // Merge blocks
        let base_ids: std::collections::HashSet<Uuid> = base.blocks.iter().map(|b| b.id).collect();

        for block in &other.blocks {
            if !base_ids.contains(&block.id) {
                // New block - add it
                result.blocks.push(block.clone());
            } else {
                // Existing block - check for conflicts
                if let Some(existing) = result.blocks.iter_mut().find(|b| b.id == block.id) {
                    if existing.content != block.content || existing.block_type != block.block_type
                    {
                        match self.strategy {
                            MergeStrategy::KeepFirst => {}
                            MergeStrategy::KeepSecond => {
                                *existing = block.clone();
                            }
                            MergeStrategy::KeepBoth => {
                                // Add both versions
                                result.blocks.push(block.clone());
                            }
                            MergeStrategy::FailOnConflict => {
                                return Err(BlocksError::ValidationError {
                                    message: format!("Block conflict for id: {}", block.id),
                                });
                            }
                        }
                    }
                }
            }
        }

        result.update_timestamp();
        Ok(result)
    }

    /// Three-way merge with common ancestor
    pub fn merge_three_way(
        &self,
        base: &Document,
        ours: &Document,
        theirs: &Document,
    ) -> Result<Document> {
        // First merge base with ours
        let intermediate = self.merge(base, ours)?;
        // Then merge result with theirs
        self.merge(&intermediate, theirs)
    }
}

impl Default for DocumentMerger {
    fn default() -> Self {
        Self::new(MergeStrategy::KeepSecond)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::BlockType;

    fn create_test_doc(title: &str) -> Document {
        let mut doc = Document::with_title(title.to_string());
        doc.add_block(Block::new(BlockType::Text, "Block 1".to_string()));
        doc.add_block(Block::new(BlockType::Text, "Block 2".to_string()));
        doc
    }

    #[test]
    fn test_diff_identical_documents() {
        let doc = create_test_doc("Test");
        let diff = DocumentDiffer::diff(&doc, &doc);
        assert!(diff.is_empty());
    }

    #[test]
    fn test_diff_title_change() {
        let original = create_test_doc("Original");
        let mut modified = original.clone();
        modified.title = "Modified".to_string();

        let diff = DocumentDiffer::diff(&original, &modified);

        assert_eq!(diff.len(), 1);
        assert!(matches!(&diff.changes[0], Change::TitleChanged { .. }));
    }

    #[test]
    fn test_diff_added_block() {
        let original = create_test_doc("Test");
        let mut modified = original.clone();
        modified.add_block(Block::new(BlockType::Text, "Block 3".to_string()));

        let diff = DocumentDiffer::diff(&original, &modified);

        let added: Vec<_> = diff
            .changes
            .iter()
            .filter(|c| matches!(c, Change::Added { .. }))
            .collect();
        assert_eq!(added.len(), 1);
    }

    #[test]
    fn test_diff_removed_block() {
        let original = create_test_doc("Test");
        let mut modified = original.clone();
        modified.blocks.pop();

        let diff = DocumentDiffer::diff(&original, &modified);

        let removed: Vec<_> = diff
            .changes
            .iter()
            .filter(|c| matches!(c, Change::Removed { .. }))
            .collect();
        assert_eq!(removed.len(), 1);
    }

    #[test]
    fn test_diff_modified_block() {
        let original = create_test_doc("Test");
        let mut modified = original.clone();
        modified.blocks[0].content = "Modified content".to_string();

        let diff = DocumentDiffer::diff(&original, &modified);

        let mods: Vec<_> = diff
            .changes
            .iter()
            .filter(|c| matches!(c, Change::Modified { .. }))
            .collect();
        assert_eq!(mods.len(), 1);
    }

    #[test]
    fn test_diff_summary() {
        let original = create_test_doc("Test");
        let mut modified = original.clone();
        modified.add_block(Block::new(BlockType::Text, "New".to_string()));
        modified.blocks[0].content = "Changed".to_string();

        let diff = DocumentDiffer::diff(&original, &modified);
        let summary = diff.summary();

        assert!(summary.contains("added"));
        assert!(summary.contains("modified"));
    }

    #[test]
    fn test_merge_keep_second() {
        let base = create_test_doc("Base");
        let mut other = base.clone();
        other.title = "Other".to_string();

        let merger = DocumentMerger::new(MergeStrategy::KeepSecond);
        let result = merger.merge(&base, &other).unwrap();

        assert_eq!(result.title, "Other");
    }

    #[test]
    fn test_merge_keep_first() {
        let base = create_test_doc("Base");
        let mut other = base.clone();
        other.title = "Other".to_string();

        let merger = DocumentMerger::new(MergeStrategy::KeepFirst);
        let result = merger.merge(&base, &other).unwrap();

        assert_eq!(result.title, "Base");
    }

    #[test]
    fn test_merge_keep_both() {
        let base = create_test_doc("Base");
        let mut other = base.clone();
        other.title = "Other".to_string();

        let merger = DocumentMerger::new(MergeStrategy::KeepBoth);
        let result = merger.merge(&base, &other).unwrap();

        assert!(result.title.contains("Base"));
        assert!(result.title.contains("Other"));
    }

    #[test]
    fn test_merge_fail_on_conflict() {
        let base = create_test_doc("Base");
        let mut other = base.clone();
        other.title = "Other".to_string();

        let merger = DocumentMerger::new(MergeStrategy::FailOnConflict);
        let result = merger.merge(&base, &other);

        assert!(result.is_err());
    }

    #[test]
    fn test_merge_adds_new_blocks() {
        let base = create_test_doc("Base");
        let mut other = Document::with_title("Other".to_string());
        other.add_block(Block::new(BlockType::Text, "New Block".to_string()));

        let merger = DocumentMerger::new(MergeStrategy::KeepSecond);
        let result = merger.merge(&base, &other).unwrap();

        assert!(result.blocks.len() > base.blocks.len());
    }

    #[test]
    fn test_change_description() {
        let change = Change::Added {
            block: Block::new(BlockType::Text, "test".to_string()),
            index: 0,
        };
        assert!(change.description().contains("Added"));
    }

    #[test]
    fn test_content_changes_filter() {
        let original = create_test_doc("Test");
        let mut modified = original.clone();
        modified.title = "Changed Title".to_string();
        modified.add_block(Block::new(BlockType::Text, "New".to_string()));

        let diff = DocumentDiffer::diff(&original, &modified);
        let content_changes = diff.content_changes();

        assert_eq!(content_changes.len(), 1); // Only the added block
    }
}