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
/// Middleware and Pipeline module for block processing
///
/// Provides composable middleware chains for processing blocks and documents.
use crate::block::Block;
use crate::document::Document;
use crate::error::{BlocksError, Result};
use std::sync::Arc;

/// Type alias for middleware function
pub type MiddlewareFn = Arc<dyn Fn(&mut Block) -> Result<()> + Send + Sync>;

/// Type alias for document middleware function
pub type DocumentMiddlewareFn = Arc<dyn Fn(&mut Document) -> Result<()> + Send + Sync>;

/// Pipeline for processing blocks through multiple middleware stages
///
/// # Example
///
/// ```rust
/// use blocks::pipeline::BlockPipeline;
///
/// let pipeline = BlockPipeline::new()
///     .add_middleware(|block| {
///         block.content = block.content.trim().to_string();
///         Ok(())
///     })
///     .add_middleware(|block| {
///         block.content = block.content.to_uppercase();
///         Ok(())
///     });
/// ```
pub struct BlockPipeline {
    middlewares: Vec<MiddlewareFn>,
    name: String,
}

impl BlockPipeline {
    /// Creates a new empty pipeline
    pub fn new() -> Self {
        Self {
            middlewares: Vec::new(),
            name: "default".to_string(),
        }
    }

    /// Creates a new pipeline with a name
    pub fn with_name(name: impl Into<String>) -> Self {
        Self {
            middlewares: Vec::new(),
            name: name.into(),
        }
    }

    /// Adds a middleware function to the pipeline
    pub fn add_middleware<F>(mut self, middleware: F) -> Self
    where
        F: Fn(&mut Block) -> Result<()> + Send + Sync + 'static,
    {
        self.middlewares.push(Arc::new(middleware));
        self
    }

    /// Processes a block through all middleware in the pipeline
    pub fn process(&self, block: &mut Block) -> Result<()> {
        for middleware in &self.middlewares {
            middleware(block)?;
        }
        Ok(())
    }

    /// Processes multiple blocks through the pipeline
    pub fn process_all(&self, blocks: &mut [Block]) -> Result<()> {
        for block in blocks {
            self.process(block)?;
        }
        Ok(())
    }

    /// Returns the pipeline name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the number of middleware in the pipeline
    pub fn len(&self) -> usize {
        self.middlewares.len()
    }

    /// Returns true if the pipeline is empty
    pub fn is_empty(&self) -> bool {
        self.middlewares.is_empty()
    }
}

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

/// Pipeline for processing documents through multiple middleware stages
pub struct DocumentPipeline {
    middlewares: Vec<DocumentMiddlewareFn>,
    block_pipeline: Option<BlockPipeline>,
    name: String,
}

impl DocumentPipeline {
    /// Creates a new empty document pipeline
    pub fn new() -> Self {
        Self {
            middlewares: Vec::new(),
            block_pipeline: None,
            name: "default".to_string(),
        }
    }

    /// Creates a new pipeline with a name
    pub fn with_name(name: impl Into<String>) -> Self {
        Self {
            middlewares: Vec::new(),
            block_pipeline: None,
            name: name.into(),
        }
    }

    /// Adds a middleware function to the pipeline
    pub fn add_middleware<F>(mut self, middleware: F) -> Self
    where
        F: Fn(&mut Document) -> Result<()> + Send + Sync + 'static,
    {
        self.middlewares.push(Arc::new(middleware));
        self
    }

    /// Sets a block pipeline to process each block
    pub fn with_block_pipeline(mut self, pipeline: BlockPipeline) -> Self {
        self.block_pipeline = Some(pipeline);
        self
    }

    /// Processes a document through all middleware in the pipeline
    pub fn process(&self, doc: &mut Document) -> Result<()> {
        // First, process document-level middleware
        for middleware in &self.middlewares {
            middleware(doc)?;
        }

        // Then, if there's a block pipeline, process each block
        if let Some(ref block_pipeline) = self.block_pipeline {
            for block in &mut doc.blocks {
                block_pipeline.process(block)?;
            }
        }

        Ok(())
    }

    /// Returns the pipeline name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the number of middleware in the pipeline
    pub fn len(&self) -> usize {
        self.middlewares.len()
    }

    /// Returns true if the pipeline is empty
    pub fn is_empty(&self) -> bool {
        self.middlewares.is_empty() && self.block_pipeline.is_none()
    }
}

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

/// Common middleware functions for blocks
pub mod block_middlewares {
    use super::*;
    use crate::BlockType;

    /// Trims whitespace from block content
    pub fn trim_content() -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        |block| {
            block.content = block.content.trim().to_string();
            Ok(())
        }
    }

    /// Converts content to uppercase
    pub fn uppercase() -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        |block| {
            block.content = block.content.to_uppercase();
            Ok(())
        }
    }

    /// Converts content to lowercase
    pub fn lowercase() -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        |block| {
            block.content = block.content.to_lowercase();
            Ok(())
        }
    }

    /// Adds a prefix to text blocks
    pub fn add_prefix(prefix: String) -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        move |block| {
            if matches!(block.block_type, BlockType::Text) {
                block.content = format!("{}{}", prefix, block.content);
            }
            Ok(())
        }
    }

    /// Adds a suffix to text blocks
    pub fn add_suffix(suffix: String) -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        move |block| {
            if matches!(block.block_type, BlockType::Text) {
                block.content = format!("{}{}", block.content, suffix);
            }
            Ok(())
        }
    }

    /// Validates block content is not empty
    pub fn require_content() -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        |block| {
            if block.content.trim().is_empty() {
                return Err(BlocksError::EmptyContent {
                    block_type: block.type_name().to_string(),
                });
            }
            Ok(())
        }
    }

    /// Limits content length
    pub fn max_length(max: usize) -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        move |block| {
            if block.content.len() > max {
                block.content = block.content.chars().take(max).collect();
            }
            Ok(())
        }
    }

    /// Replaces text in content
    pub fn replace_text(
        from: String,
        to: String,
    ) -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        move |block| {
            block.content = block.content.replace(&from, &to);
            Ok(())
        }
    }

    /// Adds metadata to block
    pub fn add_metadata(
        key: String,
        value: String,
    ) -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        move |block| {
            block.metadata.insert(key.clone(), value.clone());
            Ok(())
        }
    }

    /// Adds timestamp metadata
    pub fn timestamp_metadata() -> impl Fn(&mut Block) -> Result<()> + Send + Sync + 'static {
        |block| {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs();
            block
                .metadata
                .insert("processed_at".to_string(), now.to_string());
            Ok(())
        }
    }
}

/// Common middleware functions for documents
pub mod document_middlewares {
    use super::*;

    /// Sets document title if empty
    pub fn default_title(
        title: String,
    ) -> impl Fn(&mut Document) -> Result<()> + Send + Sync + 'static {
        move |doc| {
            if doc.title.is_empty() {
                doc.title = title.clone();
            }
            Ok(())
        }
    }

    /// Adds metadata to document
    pub fn add_metadata(
        key: String,
        value: String,
    ) -> impl Fn(&mut Document) -> Result<()> + Send + Sync + 'static {
        move |doc| {
            doc.metadata.insert(key.clone(), value.clone());
            Ok(())
        }
    }

    /// Validates document has at least one block
    pub fn require_blocks() -> impl Fn(&mut Document) -> Result<()> + Send + Sync + 'static {
        |doc| {
            if doc.blocks.is_empty() {
                return Err(BlocksError::ValidationError {
                    message: "Document must have at least one block".to_string(),
                });
            }
            Ok(())
        }
    }

    /// Removes empty blocks from document
    pub fn remove_empty_blocks() -> impl Fn(&mut Document) -> Result<()> + Send + Sync + 'static {
        |doc| {
            doc.blocks.retain(|block| !block.content.trim().is_empty());
            Ok(())
        }
    }

    /// Limits number of blocks
    pub fn max_blocks(max: usize) -> impl Fn(&mut Document) -> Result<()> + Send + Sync + 'static {
        move |doc| {
            if doc.blocks.len() > max {
                doc.blocks.truncate(max);
            }
            Ok(())
        }
    }

    /// Adds processing timestamp
    pub fn timestamp_metadata() -> impl Fn(&mut Document) -> Result<()> + Send + Sync + 'static {
        |doc| {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs();
            doc.metadata
                .insert("processed_at".to_string(), now.to_string());
            Ok(())
        }
    }

    /// Sorts blocks by type
    pub fn sort_by_type() -> impl Fn(&mut Document) -> Result<()> + Send + Sync + 'static {
        |doc| {
            doc.blocks.sort_by(|a, b| a.type_name().cmp(b.type_name()));
            Ok(())
        }
    }
}

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

    #[test]
    fn test_block_pipeline_creation() {
        let pipeline = BlockPipeline::new();
        assert!(pipeline.is_empty());
        assert_eq!(pipeline.len(), 0);
    }

    #[test]
    fn test_block_pipeline_with_middleware() {
        let pipeline = BlockPipeline::new()
            .add_middleware(|block| {
                block.content = block.content.trim().to_string();
                Ok(())
            })
            .add_middleware(|block| {
                block.content = block.content.to_uppercase();
                Ok(())
            });

        assert_eq!(pipeline.len(), 2);
    }

    #[test]
    fn test_block_pipeline_processing() {
        let pipeline = BlockPipeline::new()
            .add_middleware(block_middlewares::trim_content())
            .add_middleware(block_middlewares::uppercase());

        let mut block = Block::new(BlockType::Text, "  hello world  ".to_string());
        pipeline.process(&mut block).unwrap();

        assert_eq!(block.content, "HELLO WORLD");
    }

    #[test]
    fn test_document_pipeline_creation() {
        let pipeline = DocumentPipeline::new();
        assert!(pipeline.is_empty());
    }

    #[test]
    fn test_document_pipeline_processing() {
        let block_pipeline = BlockPipeline::new().add_middleware(block_middlewares::trim_content());

        let doc_pipeline = DocumentPipeline::new()
            .add_middleware(document_middlewares::default_title("Untitled".to_string()))
            .with_block_pipeline(block_pipeline);

        let mut doc = Document::new();
        doc.add_block(Block::new(BlockType::Text, "  content  ".to_string()));

        doc_pipeline.process(&mut doc).unwrap();

        assert_eq!(doc.title, "Untitled");
        assert_eq!(doc.blocks[0].content, "content");
    }

    #[test]
    fn test_block_middlewares() {
        let mut block = Block::new(BlockType::Text, "Hello".to_string());

        // Test prefix
        let add_prefix = block_middlewares::add_prefix("[PREFIX] ".to_string());
        add_prefix(&mut block).unwrap();
        assert!(block.content.starts_with("[PREFIX]"));

        // Test max length
        let mut long_block = Block::new(BlockType::Text, "a".repeat(1000));
        let max_length = block_middlewares::max_length(100);
        max_length(&mut long_block).unwrap();
        assert_eq!(long_block.content.len(), 100);
    }

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

        // Remove empty blocks
        let remove_empty = document_middlewares::remove_empty_blocks();
        remove_empty(&mut doc).unwrap();

        assert_eq!(doc.blocks.len(), 1);
        assert_eq!(doc.blocks[0].content, "content");
    }

    #[test]
    fn test_pipeline_with_name() {
        let pipeline = BlockPipeline::with_name("my-pipeline");
        assert_eq!(pipeline.name(), "my-pipeline");
    }

    #[test]
    fn test_process_all_blocks() {
        let pipeline = BlockPipeline::new().add_middleware(block_middlewares::uppercase());

        let mut blocks = vec![
            Block::new(BlockType::Text, "hello".to_string()),
            Block::new(BlockType::Text, "world".to_string()),
        ];

        pipeline.process_all(&mut blocks).unwrap();

        assert_eq!(blocks[0].content, "HELLO");
        assert_eq!(blocks[1].content, "WORLD");
    }

    #[test]
    fn test_require_content_middleware() {
        let require = block_middlewares::require_content();

        let mut valid = Block::new(BlockType::Text, "content".to_string());
        assert!(require(&mut valid).is_ok());

        let mut empty = Block::new(BlockType::Text, "   ".to_string());
        assert!(require(&mut empty).is_err());
    }

    #[test]
    fn test_metadata_middleware() {
        let add_meta = block_middlewares::add_metadata("key".to_string(), "value".to_string());

        let mut block = Block::new(BlockType::Text, "test".to_string());
        add_meta(&mut block).unwrap();

        assert_eq!(block.metadata.get("key"), Some(&"value".to_string()));
    }
}