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
/// Builder pattern implementation for convenient block and document creation
///
/// Provides fluent API for creating blocks and documents with less boilerplate.
use crate::block::{Block, BlockType, ButtonStyle, CalloutType, EmbedType, ListType};
use crate::document::Document;
use crate::error::Result;
use std::collections::HashMap;

/// Builder for creating `Block` instances with fluent API
///
/// # Example
///
/// ```rust
/// use blocks::builders::BlockBuilder;
///
/// let block = BlockBuilder::text("Hello World")
///     .with_metadata("author", "John Doe")
///     .build();
/// ```
pub struct BlockBuilder {
    block_type: BlockType,
    content: String,
    metadata: HashMap<String, String>,
}

impl BlockBuilder {
    /// Creates a new text block builder
    pub fn text(content: impl Into<String>) -> Self {
        Self {
            block_type: BlockType::Text,
            content: content.into(),
            metadata: HashMap::new(),
        }
    }

    /// Creates a new header block builder
    pub fn header(level: u8, content: impl Into<String>) -> Result<Self> {
        if !(1..=6).contains(&level) {
            return Err(crate::error::BlocksError::InvalidHeaderLevel { level });
        }

        Ok(Self {
            block_type: BlockType::Header { level },
            content: content.into(),
            metadata: HashMap::new(),
        })
    }

    /// Creates a new code block builder
    pub fn code(content: impl Into<String>, language: Option<String>) -> Self {
        Self {
            block_type: BlockType::Code { language },
            content: content.into(),
            metadata: HashMap::new(),
        }
    }

    /// Creates a new quote block builder
    pub fn quote(content: impl Into<String>) -> Self {
        Self {
            block_type: BlockType::Quote,
            content: content.into(),
            metadata: HashMap::new(),
        }
    }

    /// Creates a new list block builder
    pub fn list(content: impl Into<String>, list_type: ListType) -> Self {
        Self {
            block_type: BlockType::List { list_type },
            content: content.into(),
            metadata: HashMap::new(),
        }
    }

    /// Creates a new unordered list block builder
    pub fn unordered_list(content: impl Into<String>) -> Self {
        Self::list(content, ListType::Unordered)
    }

    /// Creates a new ordered list block builder
    pub fn ordered_list(content: impl Into<String>) -> Self {
        Self::list(content, ListType::Ordered)
    }

    /// Creates a new link block builder
    pub fn link(
        text: impl Into<String>,
        url: impl Into<String>,
        title: Option<String>,
    ) -> Result<Self> {
        let url = url.into();

        // Validate URL
        crate::sanitizer::ContentSanitizer::new().validate_url(&url)?;

        Ok(Self {
            block_type: BlockType::Link { url, title },
            content: text.into(),
            metadata: HashMap::new(),
        })
    }

    /// Creates a new image block builder
    pub fn image(
        url: impl Into<String>,
        alt: impl Into<String>,
        caption: Option<String>,
    ) -> Result<Self> {
        let url = url.into();

        // Validate URL
        crate::sanitizer::ContentSanitizer::new().validate_url(&url)?;

        Ok(Self {
            block_type: BlockType::Image {
                url,
                alt: alt.into(),
                caption,
            },
            content: String::new(),
            metadata: HashMap::new(),
        })
    }

    /// Creates a new button block builder
    pub fn button(
        text: impl Into<String>,
        url: impl Into<String>,
        style: ButtonStyle,
    ) -> Result<Self> {
        let url = url.into();

        // Validate URL
        crate::sanitizer::ContentSanitizer::new().validate_url(&url)?;

        Ok(Self {
            block_type: BlockType::Button {
                text: text.into(),
                url,
                style,
            },
            content: String::new(),
            metadata: HashMap::new(),
        })
    }

    /// Creates a new callout block builder
    pub fn callout(
        callout_type: CalloutType,
        title: Option<String>,
        content: impl Into<String>,
    ) -> Self {
        Self {
            block_type: BlockType::Callout {
                callout_type,
                title,
            },
            content: content.into(),
            metadata: HashMap::new(),
        }
    }

    /// Creates a new divider block builder
    pub fn divider() -> Self {
        Self {
            block_type: BlockType::Divider,
            content: String::new(),
            metadata: HashMap::new(),
        }
    }

    /// Creates a new table block builder
    pub fn table(headers: Vec<String>, rows: Vec<Vec<String>>, has_header: bool) -> Self {
        Self {
            block_type: BlockType::Table {
                headers,
                rows,
                has_header,
            },
            content: String::new(),
            metadata: HashMap::new(),
        }
    }

    /// Creates a new embed block builder
    pub fn embed(
        embed_type: EmbedType,
        url: impl Into<String>,
        width: Option<u32>,
        height: Option<u32>,
    ) -> Result<Self> {
        let url = url.into();

        // Validate URL
        crate::sanitizer::ContentSanitizer::new().validate_url(&url)?;

        Ok(Self {
            block_type: BlockType::Embed {
                embed_type,
                url,
                width,
                height,
            },
            content: String::new(),
            metadata: HashMap::new(),
        })
    }

    /// Creates a new details (collapsible) block builder
    pub fn details(summary: impl Into<String>, content: impl Into<String>, is_open: bool) -> Self {
        Self {
            block_type: BlockType::Details {
                summary: summary.into(),
                is_open,
            },
            content: content.into(),
            metadata: HashMap::new(),
        }
    }

    /// Adds metadata to the block
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Adds multiple metadata entries
    pub fn with_metadata_map(mut self, metadata: HashMap<String, String>) -> Self {
        self.metadata.extend(metadata);
        self
    }

    /// Builds the block
    pub fn build(self) -> Block {
        Block::new_with_metadata(self.block_type, self.content, self.metadata)
    }
}

/// Builder for creating `Document` instances with fluent API
///
/// # Example
///
/// ```rust
/// use blocks::builders::{DocumentBuilder, BlockBuilder};
///
/// let doc = DocumentBuilder::new("My Document")
///     .with_block(BlockBuilder::text("Hello").build())
///     .with_metadata("version", "1.0")
///     .build();
/// ```
pub struct DocumentBuilder {
    title: String,
    blocks: Vec<Block>,
    metadata: HashMap<String, String>,
}

impl DocumentBuilder {
    /// Creates a new document builder
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            blocks: Vec::new(),
            metadata: HashMap::new(),
        }
    }

    /// Creates a new empty document builder
    pub fn empty() -> Self {
        Self {
            title: String::new(),
            blocks: Vec::new(),
            metadata: HashMap::new(),
        }
    }

    /// Adds a block to the document
    pub fn with_block(mut self, block: Block) -> Self {
        self.blocks.push(block);
        self
    }

    /// Adds multiple blocks to the document
    pub fn with_blocks(mut self, blocks: Vec<Block>) -> Self {
        self.blocks.extend(blocks);
        self
    }

    /// Adds metadata to the document
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Adds multiple metadata entries
    pub fn with_metadata_map(mut self, metadata: HashMap<String, String>) -> Self {
        self.metadata.extend(metadata);
        self
    }

    /// Sets the document title
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Builds the document
    pub fn build(self) -> Document {
        let mut doc = if self.title.is_empty() {
            Document::new()
        } else {
            Document::with_title(self.title)
        };

        for block in self.blocks {
            doc.add_block(block);
        }

        doc.metadata.extend(self.metadata);
        doc
    }
}

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

    #[test]
    fn test_text_block_builder() {
        let block = BlockBuilder::text("Hello World").build();
        assert_eq!(block.content, "Hello World");
        assert_eq!(block.block_type, BlockType::Text);
    }

    #[test]
    fn test_header_block_builder() {
        let block = BlockBuilder::header(1, "Title").unwrap().build();
        assert_eq!(block.content, "Title");
        match block.block_type {
            BlockType::Header { level } => assert_eq!(level, 1),
            _ => panic!("Expected Header block"),
        }
    }

    #[test]
    fn test_invalid_header_level() {
        assert!(BlockBuilder::header(7, "Title").is_err());
        assert!(BlockBuilder::header(0, "Title").is_err());
    }

    #[test]
    fn test_code_block_builder() {
        let block = BlockBuilder::code("print('hello')", Some("python".to_string())).build();
        assert_eq!(block.content, "print('hello')");
        match block.block_type {
            BlockType::Code { language } => assert_eq!(language, Some("python".to_string())),
            _ => panic!("Expected Code block"),
        }
    }

    #[test]
    fn test_list_block_builder() {
        let block = BlockBuilder::unordered_list("item1\nitem2\nitem3").build();
        assert!(block.content.contains("item1"));
        match block.block_type {
            BlockType::List { list_type } => assert_eq!(list_type, ListType::Unordered),
            _ => panic!("Expected List block"),
        }
    }

    #[test]
    fn test_block_with_metadata() {
        let block = BlockBuilder::text("Hello")
            .with_metadata("author", "John")
            .with_metadata("version", "1.0")
            .build();

        assert_eq!(block.metadata.get("author"), Some(&"John".to_string()));
        assert_eq!(block.metadata.get("version"), Some(&"1.0".to_string()));
    }

    #[test]
    fn test_document_builder() {
        let doc = DocumentBuilder::new("My Doc")
            .with_block(BlockBuilder::text("Hello").build())
            .with_block(BlockBuilder::text("World").build())
            .build();

        assert_eq!(doc.title, "My Doc");
        assert_eq!(doc.blocks.len(), 2);
    }

    #[test]
    fn test_document_builder_with_metadata() {
        let doc = DocumentBuilder::new("My Doc")
            .with_metadata("author", "Alice")
            .with_metadata("version", "2.0")
            .build();

        assert_eq!(doc.metadata.get("author"), Some(&"Alice".to_string()));
        assert_eq!(doc.metadata.get("version"), Some(&"2.0".to_string()));
    }

    #[test]
    fn test_quote_block_builder() {
        let block = BlockBuilder::quote("A great quote").build();
        assert_eq!(block.content, "A great quote");
        assert_eq!(block.block_type, BlockType::Quote);
    }

    #[test]
    fn test_divider_block_builder() {
        let block = BlockBuilder::divider().build();
        assert_eq!(block.block_type, BlockType::Divider);
    }

    #[test]
    fn test_link_block_builder() {
        let block = BlockBuilder::link("Click here", "https://example.com", None)
            .unwrap()
            .build();
        assert_eq!(block.content, "Click here");
        match block.block_type {
            BlockType::Link { url, title } => {
                assert_eq!(url, "https://example.com");
                assert_eq!(title, None);
            }
            _ => panic!("Expected Link block"),
        }
    }

    #[test]
    fn test_button_block_builder() {
        let block = BlockBuilder::button("Click", "https://example.com", ButtonStyle::Primary)
            .unwrap()
            .build();
        assert_eq!(block.content, "");
        match block.block_type {
            BlockType::Button { text, url, style } => {
                assert_eq!(text, "Click");
                assert_eq!(url, "https://example.com");
                assert_eq!(style, ButtonStyle::Primary);
            }
            _ => panic!("Expected Button block"),
        }
    }
}