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
use crate::block::Block;
use crate::converters::{ConversionFormat, Converter};
use crate::error::{BlocksError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// Represents a document containing multiple blocks
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Document {
    /// Unique identifier for the document
    pub id: Uuid,
    /// Title of the document
    pub title: String,
    /// List of blocks in the document
    pub blocks: Vec<Block>,
    /// Document metadata
    pub metadata: HashMap<String, String>,
    /// Creation timestamp
    pub created_at: u64,
    /// Last modification timestamp
    pub updated_at: u64,
}

impl Document {
    /// Creates a new empty document
    ///
    /// # Example
    ///
    /// ```rust
    /// use blocks::Document;
    ///
    /// let doc = Document::new();
    /// assert!(doc.blocks.is_empty());
    /// ```
    pub fn new() -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        Self {
            id: Uuid::new_v4(),
            title: String::new(),
            blocks: Vec::new(),
            metadata: HashMap::new(),
            created_at: now,
            updated_at: now,
        }
    }

    /// Creates a new document with a title
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the document
    ///
    /// # Example
    ///
    /// ```rust
    /// use blocks::Document;
    ///
    /// let doc = Document::with_title("My Document".to_string());
    /// assert_eq!(doc.title, "My Document");
    /// ```
    pub fn with_title(title: String) -> Self {
        let mut doc = Self::new();
        doc.title = title;
        doc
    }

    /// Adds a block to the document
    ///
    /// # Arguments
    ///
    /// * `block` - The block to add
    ///
    /// # Example
    ///
    /// ```rust
    /// use blocks::{Document, Block, BlockType};
    ///
    /// let mut doc = Document::new();
    /// let block = Block::new(BlockType::Text, "Hello".to_string());
    /// doc.add_block(block);
    /// assert_eq!(doc.blocks.len(), 1);
    /// ```
    pub fn add_block(&mut self, block: Block) {
        self.blocks.push(block);
        self.update_timestamp();
    }

    /// Inserts a block at a specific position
    ///
    /// # Arguments
    ///
    /// * `index` - The position to insert at
    /// * `block` - The block to insert
    ///
    /// # Returns
    ///
    /// `Result<(), BlocksError>` - Ok if successful, Err if index is out of bounds
    pub fn insert_block(&mut self, index: usize, block: Block) -> Result<()> {
        if index > self.blocks.len() {
            return Err(BlocksError::ValidationError {
                message: format!(
                    "Index {} is out of bounds for {} blocks",
                    index,
                    self.blocks.len()
                ),
            });
        }
        self.blocks.insert(index, block);
        self.update_timestamp();
        Ok(())
    }

    /// Removes a block by its ID
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the block to remove
    ///
    /// # Returns
    ///
    /// `Result<Block, BlocksError>` - The removed block if found
    pub fn remove_block(&mut self, id: Uuid) -> Result<Block> {
        let index = self.blocks.iter().position(|b| b.id == id).ok_or_else(|| {
            BlocksError::ValidationError {
                message: format!("Block with ID {id} not found"),
            }
        })?;

        let block = self.blocks.remove(index);
        self.update_timestamp();
        Ok(block)
    }

    /// Removes a block by index
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the block to remove
    ///
    /// # Returns
    ///
    /// `Result<Block, BlocksError>` - The removed block if found
    pub fn remove_block_at(&mut self, index: usize) -> Result<Block> {
        if index >= self.blocks.len() {
            return Err(BlocksError::ValidationError {
                message: format!(
                    "Index {} is out of bounds for {} blocks",
                    index,
                    self.blocks.len()
                ),
            });
        }

        let block = self.blocks.remove(index);
        self.update_timestamp();
        Ok(block)
    }

    /// Gets a block by its ID
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the block to find
    ///
    /// # Returns
    ///
    /// `Option<&Block>` - The block if found
    pub fn get_block(&self, id: Uuid) -> Option<&Block> {
        self.blocks.iter().find(|b| b.id == id)
    }

    /// Gets a mutable reference to a block by its ID
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the block to find
    ///
    /// # Returns
    ///
    /// `Option<&mut Block>` - The mutable block if found
    pub fn get_block_mut(&mut self, id: Uuid) -> Option<&mut Block> {
        self.blocks.iter_mut().find(|b| b.id == id)
    }

    /// Gets a block by index
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the block
    ///
    /// # Returns
    ///
    /// `Option<&Block>` - The block if found
    pub fn get_block_at(&self, index: usize) -> Option<&Block> {
        self.blocks.get(index)
    }

    /// Gets a mutable reference to a block by index
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the block
    ///
    /// # Returns
    ///
    /// `Option<&mut Block>` - The mutable block if found
    pub fn get_block_at_mut(&mut self, index: usize) -> Option<&mut Block> {
        self.blocks.get_mut(index)
    }

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

    /// Returns true if the document has no blocks
    pub fn is_empty(&self) -> bool {
        self.blocks.is_empty()
    }

    /// Validates all blocks in the document
    pub fn validate(&self) -> Result<()> {
        for (index, block) in self.blocks.iter().enumerate() {
            block.validate().map_err(|e| BlocksError::ValidationError {
                message: format!("Block {index} validation failed: {e}"),
            })?;
        }
        Ok(())
    }

    /// Converts the document to a specific format
    ///
    /// # Arguments
    ///
    /// * `format` - The format to convert to
    ///
    /// # Returns
    ///
    /// `Result<String, BlocksError>` - The converted document
    ///
    /// # Example
    ///
    /// ```rust
    /// use blocks::{Document, Block, BlockType, ConversionFormat};
    ///
    /// let mut doc = Document::new();
    /// doc.add_block(Block::new(BlockType::Text, "Hello".to_string()));
    /// let markdown = doc.to_format(ConversionFormat::Markdown).unwrap();
    /// assert!(markdown.contains("Hello"));
    /// ```
    pub fn to_format(&self, format: ConversionFormat) -> Result<String> {
        let converter = Converter::new(format);
        converter.convert(self)
    }

    /// Adds metadata to the document
    pub fn add_metadata(&mut self, key: String, value: String) {
        self.metadata.insert(key, value);
        self.update_timestamp();
    }

    /// Gets metadata from the document
    pub fn get_metadata(&self, key: &str) -> Option<&String> {
        self.metadata.get(key)
    }

    /// Updates the document title
    pub fn set_title(&mut self, title: String) {
        self.title = title;
        self.update_timestamp();
    }

    /// Updates the timestamp
    pub fn update_timestamp(&mut self) {
        self.updated_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
    }

    /// Clears all blocks from the document
    pub fn clear(&mut self) {
        self.blocks.clear();
        self.update_timestamp();
    }
}

impl Default for Document {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for Document {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Document: {} ({} blocks)", self.title, self.blocks.len())
    }
}

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

    #[test]
    fn test_document_creation() {
        let doc = Document::new();
        assert!(doc.blocks.is_empty());
        assert!(doc.title.is_empty());
        assert!(doc.metadata.is_empty());
    }

    #[test]
    fn test_document_with_title() {
        let doc = Document::with_title("Test Document".to_string());
        assert_eq!(doc.title, "Test Document");
    }

    #[test]
    fn test_add_block() {
        let mut doc = Document::new();
        let block = Block::new(BlockType::Text, "Hello".to_string());
        doc.add_block(block);
        assert_eq!(doc.blocks.len(), 1);
    }

    #[test]
    fn test_insert_block() {
        let mut doc = Document::new();
        let block1 = Block::new(BlockType::Text, "First".to_string());
        let block2 = Block::new(BlockType::Text, "Second".to_string());

        doc.add_block(block1);
        assert!(doc.insert_block(0, block2).is_ok());
        assert_eq!(doc.blocks.len(), 2);
        assert_eq!(doc.blocks[0].content, "Second");
    }

    #[test]
    fn test_insert_block_out_of_bounds() {
        let mut doc = Document::new();
        let block = Block::new(BlockType::Text, "Test".to_string());

        assert!(doc.insert_block(1, block).is_err());
    }

    #[test]
    fn test_remove_block() {
        let mut doc = Document::new();
        let block = Block::new(BlockType::Text, "Test".to_string());
        let id = block.id;
        doc.add_block(block);

        let removed = doc.remove_block(id).unwrap();
        assert_eq!(removed.id, id);
        assert!(doc.blocks.is_empty());
    }

    #[test]
    fn test_remove_block_not_found() {
        let mut doc = Document::new();
        let id = Uuid::new_v4();

        assert!(doc.remove_block(id).is_err());
    }

    #[test]
    fn test_remove_block_at() {
        let mut doc = Document::new();
        let block = Block::new(BlockType::Text, "Test".to_string());
        doc.add_block(block);

        let removed = doc.remove_block_at(0).unwrap();
        assert_eq!(removed.content, "Test");
        assert!(doc.blocks.is_empty());
    }

    #[test]
    fn test_get_block() {
        let mut doc = Document::new();
        let block = Block::new(BlockType::Text, "Test".to_string());
        let id = block.id;
        doc.add_block(block);

        let found = doc.get_block(id).unwrap();
        assert_eq!(found.id, id);
    }

    #[test]
    fn test_get_block_at() {
        let mut doc = Document::new();
        let block = Block::new(BlockType::Text, "Test".to_string());
        doc.add_block(block);

        let found = doc.get_block_at(0).unwrap();
        assert_eq!(found.content, "Test");
    }

    #[test]
    fn test_len_and_is_empty() {
        let mut doc = Document::new();
        assert_eq!(doc.len(), 0);
        assert!(doc.is_empty());

        doc.add_block(Block::new(BlockType::Text, "Test".to_string()));
        assert_eq!(doc.len(), 1);
        assert!(!doc.is_empty());
    }

    #[test]
    fn test_clear() {
        let mut doc = Document::new();
        doc.add_block(Block::new(BlockType::Text, "Test".to_string()));
        assert!(!doc.is_empty());

        doc.clear();
        assert!(doc.is_empty());
    }

    #[test]
    fn test_metadata() {
        let mut doc = Document::new();
        doc.add_metadata("author".to_string(), "John Doe".to_string());

        assert_eq!(doc.get_metadata("author"), Some(&"John Doe".to_string()));
        assert_eq!(doc.get_metadata("nonexistent"), None);
    }

    #[test]
    fn test_set_title() {
        let mut doc = Document::new();
        doc.set_title("New Title".to_string());
        assert_eq!(doc.title, "New Title");
    }

    #[test]
    fn test_display() {
        let mut doc = Document::with_title("Test Doc".to_string());
        doc.add_block(Block::new(BlockType::Text, "Test".to_string()));

        let display = format!("{doc}");
        assert!(display.contains("Test Doc"));
        assert!(display.contains("1 blocks"));
    }

    #[test]
    fn test_serialization() {
        let mut doc = Document::with_title("Test".to_string());
        doc.add_block(Block::new(BlockType::Text, "Content".to_string()));

        let json = serde_json::to_string(&doc).unwrap();
        let deserialized: Document = serde_json::from_str(&json).unwrap();
        assert_eq!(doc, deserialized);
    }
}