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
use crate::error::{BlocksError, Result};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Represents different types of blocks supported by the editor
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BlockType {
    /// Plain text block
    Text,
    /// Header block with level (1-6)
    Header { level: u8 },
    /// List block (ordered or unordered)
    List { list_type: ListType },
    /// Code block with optional language
    Code { language: Option<String> },
    /// Quote block
    Quote,
    /// Link block with URL and optional title
    Link { url: String, title: Option<String> },
    /// Image block with URL, alt text, and optional caption
    Image {
        url: String,
        alt: String,
        caption: Option<String>,
    },
    // TinyMCE-like advanced blocks
    /// Table block with headers and rows
    Table {
        headers: Vec<String>,
        rows: Vec<Vec<String>>,
        has_header: bool,
    },
    /// Horizontal divider
    Divider,
    /// Embedded content (video, iframe, etc.)
    Embed {
        embed_type: EmbedType,
        url: String,
        width: Option<u32>,
        height: Option<u32>,
    },
    /// Button with styling
    Button {
        text: String,
        url: String,
        style: ButtonStyle,
    },
    /// Callout/alert boxes
    Callout {
        callout_type: CalloutType,
        title: Option<String>,
    },
    /// Multi-column layout
    Columns {
        column_count: u8,
        content: Vec<Vec<String>>,
    },
    /// Collapsible details
    Details { summary: String, is_open: bool },
}

/// Types of lists supported
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ListType {
    /// Ordered list (1, 2, 3...)
    Ordered,
    /// Unordered list (bullets)
    Unordered,
}

/// Types of embedded content
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EmbedType {
    /// YouTube video
    YouTube,
    /// Vimeo video
    Vimeo,
    /// General iframe
    Iframe,
    /// Audio file
    Audio,
    /// Video file
    Video,
}

/// Button styling options
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ButtonStyle {
    /// Primary button (filled)
    Primary,
    /// Secondary button (outlined)
    Secondary,
    /// Danger button (red)
    Danger,
    /// Success button (green)
    Success,
    /// Warning button (yellow)
    Warning,
    /// Info button (blue)
    Info,
}

/// Callout/alert types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CalloutType {
    /// Information callout
    Info,
    /// Warning callout
    Warning,
    /// Error callout
    Error,
    /// Success callout
    Success,
    /// Note callout
    Note,
    /// Tip callout
    Tip,
}

/// Represents a single block in the editor
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Block {
    /// Unique identifier for the block
    pub id: Uuid,
    /// Type of the block
    pub block_type: BlockType,
    /// Content of the block
    pub content: String,
    /// Metadata for the block
    pub metadata: std::collections::HashMap<String, String>,
    /// Creation timestamp
    pub created_at: u64,
    /// Last modification timestamp
    pub updated_at: u64,
}

impl Block {
    /// Creates a new block with the given type and content
    ///
    /// # Arguments
    ///
    /// * `block_type` - The type of block to create
    /// * `content` - The content of the block
    ///
    /// # Returns
    ///
    /// A new `Block` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use blocks::{Block, BlockType};
    ///
    /// let block = Block::new(BlockType::Text, "Hello World".to_string());
    /// assert_eq!(block.content, "Hello World");
    /// ```
    pub fn new(block_type: BlockType, content: String) -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        Self {
            id: Uuid::new_v4(),
            block_type,
            content,
            metadata: std::collections::HashMap::new(),
            created_at: now,
            updated_at: now,
        }
    }

    /// Creates a new block with a specific ID (useful for testing)
    pub fn with_id(id: Uuid, block_type: BlockType, content: String) -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        Self {
            id,
            block_type,
            content,
            metadata: std::collections::HashMap::new(),
            created_at: now,
            updated_at: now,
        }
    }

    /// Creates a new block with metadata
    pub fn new_with_metadata(
        block_type: BlockType,
        content: String,
        metadata: std::collections::HashMap<String, String>,
    ) -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        Self {
            id: Uuid::new_v4(),
            block_type,
            content,
            metadata,
            created_at: now,
            updated_at: now,
        }
    }

    /// Updates the content of the block
    pub fn update_content(&mut self, content: String) {
        self.content = content;
        self.update_timestamp();
    }

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

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

    /// Validates the block according to its type
    pub fn validate(&self) -> Result<()> {
        match &self.block_type {
            BlockType::Header { level } => {
                if *level < 1 || *level > 6 {
                    return Err(BlocksError::InvalidHeaderLevel { level: *level });
                }
                if self.content.trim().is_empty() {
                    return Err(BlocksError::EmptyContent {
                        block_type: "Header".to_string(),
                    });
                }
            }
            BlockType::Link { url, .. } => {
                if url.trim().is_empty() {
                    return Err(BlocksError::InvalidUrl { url: url.clone() });
                }
                // Basic URL validation
                if !url.starts_with("http://")
                    && !url.starts_with("https://")
                    && !url.starts_with("/")
                {
                    return Err(BlocksError::InvalidUrl { url: url.clone() });
                }
            }
            BlockType::Image { url, alt, .. } => {
                if url.trim().is_empty() {
                    return Err(BlocksError::InvalidImage {
                        reason: "URL cannot be empty".to_string(),
                    });
                }
                if alt.trim().is_empty() {
                    return Err(BlocksError::InvalidImage {
                        reason: "Alt text cannot be empty".to_string(),
                    });
                }
            }
            BlockType::Table { headers, rows, .. } => {
                if headers.is_empty() && !rows.is_empty() {
                    return Err(BlocksError::InvalidTable {
                        reason: "Table must have headers or be empty".to_string(),
                    });
                }
                // Validate all rows have same number of columns as headers
                if !headers.is_empty() {
                    for (i, row) in rows.iter().enumerate() {
                        if row.len() != headers.len() {
                            return Err(BlocksError::InvalidTable {
                                reason: format!(
                                    "Row {} has {} columns but headers have {}",
                                    i,
                                    row.len(),
                                    headers.len()
                                ),
                            });
                        }
                    }
                }
            }
            BlockType::Embed { url, .. } => {
                if url.trim().is_empty() {
                    return Err(BlocksError::InvalidUrl { url: url.clone() });
                }
            }
            BlockType::Button { url, text, .. } => {
                if url.trim().is_empty() {
                    return Err(BlocksError::InvalidUrl { url: url.clone() });
                }
                if text.trim().is_empty() {
                    return Err(BlocksError::EmptyContent {
                        block_type: "Button".to_string(),
                    });
                }
            }
            BlockType::Columns {
                column_count,
                content,
            } => {
                if *column_count == 0 || *column_count > 12 {
                    return Err(BlocksError::InvalidColumns {
                        reason: "Column count must be between 1 and 12".to_string(),
                    });
                }
                if content.len() != *column_count as usize {
                    return Err(BlocksError::InvalidColumns {
                        reason: format!(
                            "Expected {} columns but got {}",
                            column_count,
                            content.len()
                        ),
                    });
                }
            }
            BlockType::Details { summary, .. } => {
                if summary.trim().is_empty() {
                    return Err(BlocksError::EmptyContent {
                        block_type: "Details".to_string(),
                    });
                }
            }
            BlockType::Code { .. } => {
                // Code blocks can have empty content
            }
            BlockType::Text
            | BlockType::Quote
            | BlockType::List { .. }
            | BlockType::Divider
            | BlockType::Callout { .. } => {
                // These can have empty content in some cases
            }
        }
        Ok(())
    }

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

    /// Returns the block type as a string
    pub fn type_name(&self) -> &'static str {
        match self.block_type {
            BlockType::Text => "text",
            BlockType::Header { .. } => "header",
            BlockType::List { .. } => "list",
            BlockType::Code { .. } => "code",
            BlockType::Quote => "quote",
            BlockType::Link { .. } => "link",
            BlockType::Image { .. } => "image",
            BlockType::Table { .. } => "table",
            BlockType::Divider => "divider",
            BlockType::Embed { .. } => "embed",
            BlockType::Button { .. } => "button",
            BlockType::Callout { .. } => "callout",
            BlockType::Columns { .. } => "columns",
            BlockType::Details { .. } => "details",
        }
    }
}

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

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

    #[test]
    fn test_block_creation() {
        let block = Block::new(BlockType::Text, "Hello World".to_string());
        assert_eq!(block.content, "Hello World");
        assert_eq!(block.block_type, BlockType::Text);
        assert!(block.metadata.is_empty());
    }

    #[test]
    fn test_block_with_id() {
        let id = Uuid::new_v4();
        let block = Block::with_id(id, BlockType::Text, "Test".to_string());
        assert_eq!(block.id, id);
    }

    #[test]
    fn test_update_content() {
        let mut block = Block::new(BlockType::Text, "Original".to_string());
        let original_updated = block.updated_at;

        // Small delay to ensure timestamp changes
        std::thread::sleep(std::time::Duration::from_millis(10));

        block.update_content("Updated".to_string());
        assert_eq!(block.content, "Updated");
        assert!(block.updated_at >= original_updated);
    }

    #[test]
    fn test_metadata() {
        let mut block = Block::new(BlockType::Text, "Test".to_string());
        block.add_metadata("author".to_string(), "John Doe".to_string());

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

    #[test]
    fn test_header_validation() {
        let block = Block::new(BlockType::Header { level: 1 }, "Valid Header".to_string());
        assert!(block.validate().is_ok());

        let invalid_level = Block::new(BlockType::Header { level: 10 }, "Invalid".to_string());
        assert!(invalid_level.validate().is_err());

        let empty_header = Block::new(BlockType::Header { level: 1 }, "".to_string());
        assert!(empty_header.validate().is_err());
    }

    #[test]
    fn test_link_validation() {
        let valid_link = Block::new(
            BlockType::Link {
                url: "https://example.com".to_string(),
                title: None,
            },
            "Link text".to_string(),
        );
        assert!(valid_link.validate().is_ok());

        let invalid_link = Block::new(
            BlockType::Link {
                url: "".to_string(),
                title: None,
            },
            "Link text".to_string(),
        );
        assert!(invalid_link.validate().is_err());
    }

    #[test]
    fn test_image_validation() {
        let valid_image = Block::new(
            BlockType::Image {
                url: "https://example.com/image.jpg".to_string(),
                alt: "Test image".to_string(),
                caption: None,
            },
            "".to_string(),
        );
        assert!(valid_image.validate().is_ok());

        let invalid_image = Block::new(
            BlockType::Image {
                url: "https://example.com/image.jpg".to_string(),
                alt: "".to_string(),
                caption: None,
            },
            "".to_string(),
        );
        assert!(invalid_image.validate().is_err());
    }

    #[test]
    fn test_type_name() {
        assert_eq!(
            Block::new(BlockType::Text, "".to_string()).type_name(),
            "text"
        );
        assert_eq!(
            Block::new(BlockType::Header { level: 1 }, "".to_string()).type_name(),
            "header"
        );
        assert_eq!(
            Block::new(BlockType::Quote, "".to_string()).type_name(),
            "quote"
        );
    }

    #[test]
    fn test_display() {
        let block = Block::new(BlockType::Text, "Hello World".to_string());
        assert_eq!(format!("{block}"), "text: Hello World");
    }

    #[test]
    fn test_serialization() {
        let block = Block::new(BlockType::Header { level: 2 }, "Test Header".to_string());
        let json = serde_json::to_string(&block).unwrap();
        let deserialized: Block = serde_json::from_str(&json).unwrap();
        assert_eq!(block, deserialized);
    }
}