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
/// Statistics and analysis module for documents
///
/// Provides comprehensive statistics and analysis of documents and blocks.
use crate::block::{Block, BlockType};
use crate::document::Document;
use std::collections::HashMap;

/// Statistics for a single block
#[derive(Debug, Clone, Default)]
pub struct BlockStats {
    /// Number of characters in content
    pub char_count: usize,
    /// Number of words in content
    pub word_count: usize,
    /// Number of lines in content
    pub line_count: usize,
    /// Number of sentences in content
    pub sentence_count: usize,
    /// Number of metadata entries
    pub metadata_count: usize,
    /// Estimated reading time in seconds
    pub reading_time_secs: f64,
}

impl BlockStats {
    /// Calculates statistics for a block
    pub fn from_block(block: &Block) -> Self {
        let content = &block.content;

        let char_count = content.chars().count();
        let word_count = content.split_whitespace().count();
        let line_count = content.lines().count().max(1);
        let sentence_count = content
            .chars()
            .filter(|c| *c == '.' || *c == '!' || *c == '?')
            .count()
            .max(1);
        let metadata_count = block.metadata.len();

        // Average reading speed: 200-250 words per minute
        let reading_time_secs = (word_count as f64 / 225.0) * 60.0;

        Self {
            char_count,
            word_count,
            line_count,
            sentence_count,
            metadata_count,
            reading_time_secs,
        }
    }
}

/// Statistics for a document
#[derive(Debug, Clone, Default)]
pub struct DocumentStats {
    /// Total number of blocks
    pub block_count: usize,
    /// Total number of characters
    pub total_chars: usize,
    /// Total number of words
    pub total_words: usize,
    /// Total number of lines
    pub total_lines: usize,
    /// Total number of sentences
    pub total_sentences: usize,
    /// Blocks by type
    pub blocks_by_type: HashMap<String, usize>,
    /// Average words per block
    pub avg_words_per_block: f64,
    /// Average chars per block
    pub avg_chars_per_block: f64,
    /// Estimated total reading time in minutes
    pub reading_time_mins: f64,
    /// Document complexity score (0-100)
    pub complexity_score: f64,
    /// Title length
    pub title_length: usize,
    /// Metadata count
    pub metadata_count: usize,
}

impl DocumentStats {
    /// Calculates statistics for a document
    pub fn from_document(doc: &Document) -> Self {
        let mut stats = Self {
            block_count: doc.blocks.len(),
            title_length: doc.title.len(),
            metadata_count: doc.metadata.len(),
            ..Self::default()
        };

        for block in &doc.blocks {
            let block_stats = BlockStats::from_block(block);

            stats.total_chars += block_stats.char_count;
            stats.total_words += block_stats.word_count;
            stats.total_lines += block_stats.line_count;
            stats.total_sentences += block_stats.sentence_count;

            let type_name = block.type_name().to_string();
            *stats.blocks_by_type.entry(type_name).or_insert(0) += 1;
        }

        if stats.block_count > 0 {
            stats.avg_words_per_block = stats.total_words as f64 / stats.block_count as f64;
            stats.avg_chars_per_block = stats.total_chars as f64 / stats.block_count as f64;
        }

        // Reading time: 225 words per minute
        stats.reading_time_mins = stats.total_words as f64 / 225.0;

        // Complexity score based on various factors
        stats.complexity_score = Self::calculate_complexity(doc, &stats);

        stats
    }

    /// Calculates a complexity score for the document
    fn calculate_complexity(_doc: &Document, stats: &DocumentStats) -> f64 {
        let mut score = 0.0;

        // Factor 1: Block type diversity (0-25 points)
        let type_count = stats.blocks_by_type.len();
        score += (type_count as f64 * 5.0).min(25.0);

        // Factor 2: Average sentence length (0-25 points)
        if stats.total_sentences > 0 {
            let avg_words_per_sentence = stats.total_words as f64 / stats.total_sentences as f64;
            score += (avg_words_per_sentence * 1.5).min(25.0);
        }

        // Factor 3: Code blocks (0-25 points)
        let code_blocks = stats.blocks_by_type.get("code").unwrap_or(&0);
        score += (*code_blocks as f64 * 5.0).min(25.0);

        // Factor 4: Document size (0-25 points)
        score += (stats.block_count as f64 * 0.5).min(25.0);

        score.min(100.0)
    }

    /// Returns a human-readable summary
    pub fn summary(&self) -> String {
        format!(
            "Document with {} blocks, {} words, ~{:.1} min read time",
            self.block_count, self.total_words, self.reading_time_mins
        )
    }

    /// Returns the most common block type
    pub fn most_common_block_type(&self) -> Option<&str> {
        self.blocks_by_type
            .iter()
            .max_by_key(|(_, count)| *count)
            .map(|(name, _)| name.as_str())
    }
}

/// Analyzer for documents
pub struct DocumentAnalyzer;

impl DocumentAnalyzer {
    /// Analyzes a document and returns statistics
    pub fn analyze(doc: &Document) -> DocumentStats {
        DocumentStats::from_document(doc)
    }

    /// Analyzes a single block
    pub fn analyze_block(block: &Block) -> BlockStats {
        BlockStats::from_block(block)
    }

    /// Finds potential issues in a document
    pub fn find_issues(doc: &Document) -> Vec<DocumentIssue> {
        let mut issues = Vec::new();

        // Check for empty title
        if doc.title.trim().is_empty() {
            issues.push(DocumentIssue::new(
                IssueSeverity::Warning,
                "Document has no title",
            ));
        }

        // Check for empty document
        if doc.blocks.is_empty() {
            issues.push(DocumentIssue::new(
                IssueSeverity::Error,
                "Document has no blocks",
            ));
        }

        // Check individual blocks
        for (i, block) in doc.blocks.iter().enumerate() {
            // Empty content
            if block.content.trim().is_empty() {
                issues.push(DocumentIssue::new(
                    IssueSeverity::Warning,
                    &format!("Block {} has empty content", i + 1),
                ));
            }

            // Very long content
            if block.content.len() > 10000 {
                issues.push(DocumentIssue::new(
                    IssueSeverity::Info,
                    &format!(
                        "Block {} has very long content ({} chars)",
                        i + 1,
                        block.content.len()
                    ),
                ));
            }

            // Header validation
            if let BlockType::Header { level } = &block.block_type {
                if *level > 6 {
                    issues.push(DocumentIssue::new(
                        IssueSeverity::Error,
                        &format!("Block {} has invalid header level: {}", i + 1, level),
                    ));
                }
            }
        }

        // Check for missing h1
        let has_h1 = doc
            .blocks
            .iter()
            .any(|b| matches!(b.block_type, BlockType::Header { level: 1 }));
        if !has_h1 && !doc.blocks.is_empty() {
            issues.push(DocumentIssue::new(
                IssueSeverity::Info,
                "Document has no H1 header",
            ));
        }

        issues
    }

    /// Calculates readability score (Flesch Reading Ease)
    pub fn readability_score(doc: &Document) -> f64 {
        let stats = DocumentStats::from_document(doc);

        if stats.total_words == 0 || stats.total_sentences == 0 {
            return 0.0;
        }

        // Count syllables (simplified estimation)
        let total_syllables: usize = doc
            .blocks
            .iter()
            .map(|b| Self::count_syllables(&b.content))
            .sum();

        let words = stats.total_words as f64;
        let sentences = stats.total_sentences as f64;
        let syllables = total_syllables as f64;

        // Flesch Reading Ease formula
        let score = 206.835 - 1.015 * (words / sentences) - 84.6 * (syllables / words);

        score.clamp(0.0, 100.0)
    }

    /// Estimates syllable count (simplified)
    fn count_syllables(text: &str) -> usize {
        let vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
        let mut count = 0;
        let mut prev_was_vowel = false;

        for c in text.to_lowercase().chars() {
            let is_vowel = vowels.contains(&c);
            if is_vowel && !prev_was_vowel {
                count += 1;
            }
            prev_was_vowel = is_vowel;
        }

        count.max(1)
    }

    /// Gets reading level description
    pub fn reading_level(score: f64) -> &'static str {
        match score as i32 {
            90..=100 => "Very Easy (5th grade)",
            80..=89 => "Easy (6th grade)",
            70..=79 => "Fairly Easy (7th grade)",
            60..=69 => "Standard (8th-9th grade)",
            50..=59 => "Fairly Difficult (10th-12th grade)",
            30..=49 => "Difficult (College)",
            0..=29 => "Very Difficult (Graduate)",
            _ => "Unknown",
        }
    }
}

/// Issue severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
    /// Informational - not a problem
    Info,
    /// Warning - potential issue
    Warning,
    /// Error - needs attention
    Error,
}

/// Represents an issue found in a document
#[derive(Debug, Clone)]
pub struct DocumentIssue {
    /// Severity of the issue
    pub severity: IssueSeverity,
    /// Description of the issue
    pub message: String,
}

impl DocumentIssue {
    /// Creates a new issue
    pub fn new(severity: IssueSeverity, message: &str) -> Self {
        Self {
            severity,
            message: message.to_string(),
        }
    }
}

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

    fn create_test_doc() -> Document {
        let mut doc = Document::with_title("Test Document".to_string());
        doc.add_block(Block::new(
            BlockType::Header { level: 1 },
            "Introduction".to_string(),
        ));
        doc.add_block(Block::new(
            BlockType::Text,
            "This is a sample paragraph with multiple words.".to_string(),
        ));
        doc.add_block(Block::new(
            BlockType::Code {
                language: Some("rust".to_string()),
            },
            "fn main() {}".to_string(),
        ));
        doc
    }

    #[test]
    fn test_block_stats() {
        let block = Block::new(BlockType::Text, "Hello world. How are you?".to_string());
        let stats = BlockStats::from_block(&block);

        assert_eq!(stats.word_count, 5);
        assert!(stats.char_count > 0);
        assert!(stats.sentence_count >= 1);
    }

    #[test]
    fn test_document_stats() {
        let doc = create_test_doc();
        let stats = DocumentStats::from_document(&doc);

        assert_eq!(stats.block_count, 3);
        assert!(stats.total_words > 0);
        assert_eq!(stats.blocks_by_type.get("header"), Some(&1));
        assert_eq!(stats.blocks_by_type.get("text"), Some(&1));
        assert_eq!(stats.blocks_by_type.get("code"), Some(&1));
    }

    #[test]
    fn test_document_stats_summary() {
        let doc = create_test_doc();
        let stats = DocumentStats::from_document(&doc);
        let summary = stats.summary();

        assert!(summary.contains("3 blocks"));
        assert!(summary.contains("words"));
    }

    #[test]
    fn test_most_common_block_type() {
        let mut doc = Document::new();
        doc.add_block(Block::new(BlockType::Text, "text 1".to_string()));
        doc.add_block(Block::new(BlockType::Text, "text 2".to_string()));
        doc.add_block(Block::new(
            BlockType::Header { level: 1 },
            "header".to_string(),
        ));

        let stats = DocumentStats::from_document(&doc);
        assert_eq!(stats.most_common_block_type(), Some("text"));
    }

    #[test]
    fn test_find_issues_empty_title() {
        let doc = Document::new();
        let issues = DocumentAnalyzer::find_issues(&doc);

        assert!(issues.iter().any(|i| i.message.contains("no title")));
    }

    #[test]
    fn test_find_issues_empty_blocks() {
        let doc = Document::with_title("Test".to_string());
        let issues = DocumentAnalyzer::find_issues(&doc);

        assert!(issues.iter().any(|i| i.message.contains("no blocks")));
    }

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

        let issues = DocumentAnalyzer::find_issues(&doc);

        assert!(issues.iter().any(|i| i.message.contains("empty content")));
    }

    #[test]
    fn test_readability_score() {
        let mut doc = Document::with_title("Test".to_string());
        doc.add_block(Block::new(
            BlockType::Text,
            "The cat sat on the mat. The dog ran in the park.".to_string(),
        ));

        let score = DocumentAnalyzer::readability_score(&doc);
        assert!(score > 0.0);
        assert!(score <= 100.0);
    }

    #[test]
    fn test_reading_level() {
        assert_eq!(
            DocumentAnalyzer::reading_level(95.0),
            "Very Easy (5th grade)"
        );
        assert_eq!(
            DocumentAnalyzer::reading_level(65.0),
            "Standard (8th-9th grade)"
        );
        assert_eq!(
            DocumentAnalyzer::reading_level(25.0),
            "Very Difficult (Graduate)"
        );
    }

    #[test]
    fn test_complexity_score() {
        let doc = create_test_doc();
        let stats = DocumentStats::from_document(&doc);

        assert!(stats.complexity_score >= 0.0);
        assert!(stats.complexity_score <= 100.0);
    }

    #[test]
    fn test_syllable_counting() {
        assert!(DocumentAnalyzer::count_syllables("hello") >= 2);
        assert!(DocumentAnalyzer::count_syllables("beautiful") >= 3);
    }

    #[test]
    fn test_empty_document_stats() {
        let doc = Document::new();
        let stats = DocumentStats::from_document(&doc);

        assert_eq!(stats.block_count, 0);
        assert_eq!(stats.total_words, 0);
        assert_eq!(stats.reading_time_mins, 0.0);
    }
}