cdx-core 0.7.1

Core library for reading, writing, and validating Codex Document Format (.cdx) files
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Content validation.

use std::collections::HashSet;
use std::fmt;

use super::{Block, Content, Text};
use crate::extensions::ExtensionBlock;

/// Content structure validation error.
///
/// Reports issues with block hierarchy, unique IDs, heading levels,
/// parent-child constraints, and similar structural rules within
/// document content.
///
/// See also [`crate::validation::SchemaValidationError`] for JSON schema
/// validation of manifest and metadata files.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    /// Path to the invalid element (e.g., `blocks[0].children[1]`).
    pub path: String,

    /// Description of the validation failure.
    pub message: String,
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.path.is_empty() {
            write!(f, "{}", self.message)
        } else {
            write!(f, "{}: {}", self.path, self.message)
        }
    }
}

impl std::error::Error for ValidationError {}

/// Validate content structure and rules.
///
/// This validates:
/// - Block structure (correct children types)
/// - Unique block IDs
/// - Required fields
/// - Heading levels (1-6)
/// - List items only in lists
/// - Table rows only in tables
/// - Table cells only in rows
///
/// # Errors
///
/// Returns a vector of validation errors if any are found.
#[must_use]
pub fn validate_content(content: &Content) -> Vec<ValidationError> {
    let mut errors = Vec::new();
    let mut seen_ids = HashSet::new();

    for (i, block) in content.blocks.iter().enumerate() {
        let path = format!("blocks[{i}]");
        validate_block(block, &path, &mut errors, &mut seen_ids, None);
    }

    errors
}

/// Parent context for validating child blocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParentContext {
    List,
    Table,
    TableRow,
    DefinitionList,
    Figure,
}

/// Context passed through validation.
struct ValidationContext<'a> {
    errors: &'a mut Vec<ValidationError>,
    seen_ids: &'a mut HashSet<String>,
}

impl ValidationContext<'_> {
    fn add_error(&mut self, path: &str, message: impl Into<String>) {
        self.errors.push(ValidationError {
            path: path.to_string(),
            message: message.into(),
        });
    }
}

fn validate_block(
    block: &Block,
    path: &str,
    errors: &mut Vec<ValidationError>,
    seen_ids: &mut HashSet<String>,
    parent: Option<ParentContext>,
) {
    let mut ctx = ValidationContext { errors, seen_ids };

    // Check ID uniqueness
    if let Some(id) = block.id() {
        if !ctx.seen_ids.insert(id.to_string()) {
            ctx.add_error(path, format!("duplicate block ID: {id}"));
        }
    }

    match block {
        Block::Paragraph { children, .. } => validate_text_children(children, path, ctx.errors),
        Block::Heading {
            level, children, ..
        } => {
            validate_heading(*level, children, path, ctx.errors);
        }
        Block::List { children, .. } => validate_list(children, path, &mut ctx),
        Block::ListItem { children, .. } => validate_list_item(children, path, parent, &mut ctx),
        Block::Blockquote { children, .. } => validate_container(children, path, &mut ctx),
        Block::CodeBlock { children, .. } => validate_code_block(children, path, ctx.errors),
        Block::HorizontalRule { .. } | Block::Break { .. } | Block::Signature(_) => {}
        Block::Image(img) => validate_image(img, path, ctx.errors),
        Block::Table { children, .. } => validate_table(children, path, &mut ctx),
        Block::TableRow { children, .. } => validate_table_row(children, path, parent, &mut ctx),
        Block::TableCell(cell) => validate_table_cell(cell, path, parent, ctx.errors),
        Block::Math(math) => validate_math(math, path, ctx.errors),
        Block::Extension(ext) => validate_extension(ext, path, &mut ctx),
        // New block types
        Block::DefinitionList(dl) => validate_definition_list(&dl.children, path, &mut ctx),
        Block::DefinitionItem { children, .. } => {
            validate_definition_item(children, path, parent, &mut ctx);
        }
        Block::DefinitionTerm { children, .. } => {
            validate_text_children(children, path, ctx.errors);
        }
        Block::DefinitionDescription { children, .. } => {
            validate_container(children, path, &mut ctx);
        }
        Block::Measurement(m) => validate_measurement(m, path, ctx.errors),
        Block::Svg(svg) => validate_svg(svg, path, ctx.errors),
        Block::Barcode(bc) => validate_barcode(bc, path, ctx.errors),
        Block::Figure(fig) => validate_figure(fig, path, &mut ctx),
        Block::FigCaption(fc) => validate_figcaption(&fc.children, path, parent, ctx.errors),
        Block::Admonition(adm) => validate_container(&adm.children, path, &mut ctx),
    }
}

fn validate_heading(level: u8, children: &[Text], path: &str, errors: &mut Vec<ValidationError>) {
    if !(1..=6).contains(&level) {
        errors.push(ValidationError {
            path: path.to_string(),
            message: format!("heading level must be 1-6, got {level}"),
        });
    }
    validate_text_children(children, path, errors);
}

fn validate_list(children: &[Block], path: &str, ctx: &mut ValidationContext<'_>) {
    for (i, child) in children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        if !matches!(child, Block::ListItem { .. }) {
            ctx.add_error(
                &child_path,
                format!("list children must be listItem, got {}", child.block_type()),
            );
        }
        validate_block(
            child,
            &child_path,
            ctx.errors,
            ctx.seen_ids,
            Some(ParentContext::List),
        );
    }
}

fn validate_list_item(
    children: &[Block],
    path: &str,
    parent: Option<ParentContext>,
    ctx: &mut ValidationContext<'_>,
) {
    if parent != Some(ParentContext::List) {
        ctx.add_error(path, "listItem must be a child of list");
    }
    for (i, child) in children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        validate_block(child, &child_path, ctx.errors, ctx.seen_ids, None);
    }
}

fn validate_container(children: &[Block], path: &str, ctx: &mut ValidationContext<'_>) {
    for (i, child) in children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        validate_block(child, &child_path, ctx.errors, ctx.seen_ids, None);
    }
}

fn validate_code_block(children: &[Text], path: &str, errors: &mut Vec<ValidationError>) {
    if children.len() != 1 {
        errors.push(ValidationError {
            path: path.to_string(),
            message: format!(
                "codeBlock should have exactly 1 text node, got {}",
                children.len()
            ),
        });
    }
    for child in children {
        if !child.marks.is_empty() {
            errors.push(ValidationError {
                path: path.to_string(),
                message: "codeBlock text should not have marks".to_string(),
            });
        }
    }
}

fn validate_image(img: &super::block::ImageBlock, path: &str, errors: &mut Vec<ValidationError>) {
    if img.src.is_empty() {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "image src is required".to_string(),
        });
    }
    if img.alt.is_empty() {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "image alt is required".to_string(),
        });
    }
}

fn validate_table(children: &[Block], path: &str, ctx: &mut ValidationContext<'_>) {
    for (i, child) in children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        if !matches!(child, Block::TableRow { .. }) {
            ctx.add_error(
                &child_path,
                format!(
                    "table children must be tableRow, got {}",
                    child.block_type()
                ),
            );
        }
        validate_block(
            child,
            &child_path,
            ctx.errors,
            ctx.seen_ids,
            Some(ParentContext::Table),
        );
    }
}

fn validate_table_row(
    children: &[Block],
    path: &str,
    parent: Option<ParentContext>,
    ctx: &mut ValidationContext<'_>,
) {
    if parent != Some(ParentContext::Table) {
        ctx.add_error(path, "tableRow must be a child of table");
    }
    for (i, child) in children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        if !matches!(child, Block::TableCell(_)) {
            ctx.add_error(
                &child_path,
                format!(
                    "tableRow children must be tableCell, got {}",
                    child.block_type()
                ),
            );
        }
        validate_block(
            child,
            &child_path,
            ctx.errors,
            ctx.seen_ids,
            Some(ParentContext::TableRow),
        );
    }
}

fn validate_table_cell(
    cell: &super::block::TableCellBlock,
    path: &str,
    parent: Option<ParentContext>,
    errors: &mut Vec<ValidationError>,
) {
    if parent != Some(ParentContext::TableRow) {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "tableCell must be a child of tableRow".to_string(),
        });
    }
    if cell.colspan == 0 {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "tableCell colspan must be at least 1".to_string(),
        });
    }
    if cell.rowspan == 0 {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "tableCell rowspan must be at least 1".to_string(),
        });
    }
    validate_text_children(&cell.children, path, errors);
}

fn validate_math(math: &super::block::MathBlock, path: &str, errors: &mut Vec<ValidationError>) {
    if math.value.is_empty() {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "math value is required".to_string(),
        });
    }
}

fn validate_extension(ext: &ExtensionBlock, path: &str, ctx: &mut ValidationContext<'_>) {
    // Validate extension namespace and type
    if ext.namespace.is_empty() {
        ctx.add_error(path, "extension namespace is required");
    }
    if ext.block_type.is_empty() {
        ctx.add_error(path, "extension block type is required");
    }

    // Validate children recursively
    for (i, child) in ext.children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        validate_block(child, &child_path, ctx.errors, ctx.seen_ids, None);
    }

    // Validate fallback content if present
    if let Some(fallback) = &ext.fallback {
        let fallback_path = format!("{path}.fallback");
        validate_block(fallback, &fallback_path, ctx.errors, ctx.seen_ids, None);
    }
}

fn validate_text_children(children: &[Text], path: &str, errors: &mut Vec<ValidationError>) {
    for (i, text) in children.iter().enumerate() {
        if text.value.is_empty() {
            errors.push(ValidationError {
                path: format!("{path}.children[{i}]"),
                message: "text value cannot be empty".to_string(),
            });
        }
    }
}

fn validate_definition_list(children: &[Block], path: &str, ctx: &mut ValidationContext<'_>) {
    for (i, child) in children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        if !matches!(child, Block::DefinitionItem { .. }) {
            ctx.add_error(
                &child_path,
                format!(
                    "definitionList children must be definitionItem, got {}",
                    child.block_type()
                ),
            );
        }
        validate_block(
            child,
            &child_path,
            ctx.errors,
            ctx.seen_ids,
            Some(ParentContext::DefinitionList),
        );
    }
}

fn validate_definition_item(
    children: &[Block],
    path: &str,
    parent: Option<ParentContext>,
    ctx: &mut ValidationContext<'_>,
) {
    if parent != Some(ParentContext::DefinitionList) {
        ctx.add_error(path, "definitionItem must be a child of definitionList");
    }
    for (i, child) in children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        validate_block(child, &child_path, ctx.errors, ctx.seen_ids, None);
    }
}

fn validate_measurement(
    m: &super::block::MeasurementBlock,
    path: &str,
    errors: &mut Vec<ValidationError>,
) {
    if m.display.is_empty() {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "measurement display is required".to_string(),
        });
    }
}

fn validate_svg(svg: &super::block::SvgBlock, path: &str, errors: &mut Vec<ValidationError>) {
    // SVG must have exactly one of src or content
    match (&svg.src, &svg.content) {
        (Some(_), Some(_)) => {
            errors.push(ValidationError {
                path: path.to_string(),
                message: "svg must have either src or content, not both".to_string(),
            });
        }
        (None, None) => {
            errors.push(ValidationError {
                path: path.to_string(),
                message: "svg must have either src or content".to_string(),
            });
        }
        _ => {}
    }
}

fn validate_barcode(
    bc: &super::block::BarcodeBlock,
    path: &str,
    errors: &mut Vec<ValidationError>,
) {
    if bc.data.is_empty() {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "barcode data is required".to_string(),
        });
    }
    // Check for generic/placeholder alt text
    let alt_lower = bc.alt.to_lowercase();
    if bc.alt.is_empty() || alt_lower == "barcode" || alt_lower == "qr code" || alt_lower == "image"
    {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "barcode alt must be meaningful (not just 'barcode' or 'image')".to_string(),
        });
    }
}

fn validate_figure(fig: &super::block::FigureBlock, path: &str, ctx: &mut ValidationContext<'_>) {
    for (i, child) in fig.children.iter().enumerate() {
        let child_path = format!("{path}.children[{i}]");
        validate_block(
            child,
            &child_path,
            ctx.errors,
            ctx.seen_ids,
            Some(ParentContext::Figure),
        );
    }

    // Validate subfigures if present
    if let Some(ref subfigures) = fig.subfigures {
        for (i, subfig) in subfigures.iter().enumerate() {
            let subfig_path = format!("{path}.subfigures[{i}]");

            // Check subfigure ID uniqueness
            if let Some(ref id) = subfig.id {
                if !ctx.seen_ids.insert(id.clone()) {
                    ctx.add_error(&subfig_path, format!("duplicate block ID: {id}"));
                }
            }

            // Validate subfigure children
            for (j, child) in subfig.children.iter().enumerate() {
                let child_path = format!("{subfig_path}.children[{j}]");
                validate_block(child, &child_path, ctx.errors, ctx.seen_ids, None);
            }
        }
    }
}

fn validate_figcaption(
    children: &[Text],
    path: &str,
    parent: Option<ParentContext>,
    errors: &mut Vec<ValidationError>,
) {
    if parent != Some(ParentContext::Figure) {
        errors.push(ValidationError {
            path: path.to_string(),
            message: "figcaption should be a child of figure".to_string(),
        });
    }
    validate_text_children(children, path, errors);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::content::{BlockAttributes, Mark, Text};

    #[test]
    fn test_valid_content() {
        let content = Content::new(vec![
            Block::heading(1, vec![Text::plain("Title")]),
            Block::paragraph(vec![Text::plain("Body")]),
        ]);
        let errors = validate_content(&content);
        assert!(errors.is_empty());
    }

    #[test]
    fn test_duplicate_ids() {
        let content = Content::new(vec![
            Block::Paragraph {
                id: Some("dup".to_string()),
                children: vec![Text::plain("First")],
                attributes: BlockAttributes::default(),
            },
            Block::Paragraph {
                id: Some("dup".to_string()),
                children: vec![Text::plain("Second")],
                attributes: BlockAttributes::default(),
            },
        ]);
        let errors = validate_content(&content);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("duplicate"));
    }

    #[test]
    fn test_invalid_heading_level() {
        let content = Content::new(vec![Block::Heading {
            id: None,
            level: 7,
            children: vec![Text::plain("Too deep")],
            attributes: BlockAttributes::default(),
        }]);
        let errors = validate_content(&content);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("level"));
    }

    #[test]
    fn test_list_item_outside_list() {
        let content = Content::new(vec![Block::list_item(vec![Block::paragraph(vec![
            Text::plain("Orphan"),
        ])])]);
        let errors = validate_content(&content);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("child of list"));
    }

    #[test]
    fn test_list_with_wrong_children() {
        let content = Content::new(vec![Block::List {
            id: None,
            ordered: false,
            start: None,
            children: vec![Block::paragraph(vec![Text::plain("Wrong")])],
            attributes: BlockAttributes::default(),
        }]);
        let errors = validate_content(&content);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("listItem"));
    }

    #[test]
    fn test_code_block_with_marks() {
        let content = Content::new(vec![Block::CodeBlock {
            id: None,
            language: Some("rust".to_string()),
            highlighting: None,
            tokens: None,
            children: vec![Text::with_marks("code", vec![Mark::Bold])],
            attributes: BlockAttributes::default(),
        }]);
        let errors = validate_content(&content);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("marks"));
    }

    #[test]
    fn test_empty_image() {
        let content = Content::new(vec![Block::Image(super::super::block::ImageBlock {
            id: None,
            src: String::new(),
            alt: String::new(),
            title: None,
            width: None,
            height: None,
        })]);
        let errors = validate_content(&content);
        assert_eq!(errors.len(), 2);
    }

    #[test]
    fn test_valid_table() {
        let content = Content::new(vec![Block::table(vec![Block::table_row(
            vec![Block::table_cell(vec![Text::plain("Cell")])],
            false,
        )])]);
        let errors = validate_content(&content);
        assert!(errors.is_empty());
    }

    #[test]
    fn test_table_row_outside_table() {
        let content = Content::new(vec![Block::table_row(
            vec![Block::table_cell(vec![Text::plain("Orphan")])],
            false,
        )]);
        let errors = validate_content(&content);
        assert!(errors.iter().any(|e| e.message.contains("child of table")));
    }

    // Tests for new block type validation

    #[test]
    fn test_valid_definition_list() {
        let content = Content::new(vec![Block::definition_list(vec![Block::definition_item(
            vec![
                Block::definition_term(vec![Text::plain("Term")]),
                Block::definition_description(vec![Block::paragraph(vec![Text::plain("Desc")])]),
            ],
        )])]);
        let errors = validate_content(&content);
        assert!(errors.is_empty());
    }

    #[test]
    fn test_definition_item_outside_list() {
        let content = Content::new(vec![Block::definition_item(vec![Block::definition_term(
            vec![Text::plain("Orphan term")],
        )])]);
        let errors = validate_content(&content);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("child of definitionList")));
    }

    #[test]
    fn test_definition_list_with_wrong_children() {
        let content = Content::new(vec![Block::DefinitionList(
            super::super::block::DefinitionListBlock::new(vec![Block::paragraph(vec![
                Text::plain("Wrong"),
            ])]),
        )]);
        let errors = validate_content(&content);
        assert!(errors.iter().any(|e| e.message.contains("definitionItem")));
    }

    #[test]
    fn test_svg_with_both_src_and_content() {
        let content = Content::new(vec![Block::Svg(super::super::block::SvgBlock {
            id: None,
            src: Some("file.svg".to_string()),
            content: Some("<svg>...</svg>".to_string()),
            width: None,
            height: None,
            alt: None,
        })]);
        let errors = validate_content(&content);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("either src or content, not both")));
    }

    #[test]
    fn test_svg_with_neither_src_nor_content() {
        let content = Content::new(vec![Block::Svg(super::super::block::SvgBlock {
            id: None,
            src: None,
            content: None,
            width: None,
            height: None,
            alt: None,
        })]);
        let errors = validate_content(&content);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("either src or content")));
    }

    #[test]
    fn test_barcode_with_generic_alt() {
        use super::super::block::{BarcodeBlock, BarcodeFormat};

        let content = Content::new(vec![Block::Barcode(BarcodeBlock::new(
            BarcodeFormat::Qr,
            "https://example.com",
            "barcode", // Generic alt text should fail
        ))]);
        let errors = validate_content(&content);
        assert!(errors.iter().any(|e| e.message.contains("meaningful")));
    }

    #[test]
    fn test_barcode_with_good_alt() {
        use super::super::block::{BarcodeBlock, BarcodeFormat};

        let content = Content::new(vec![Block::Barcode(BarcodeBlock::new(
            BarcodeFormat::Qr,
            "https://example.com",
            "Link to example.com homepage",
        ))]);
        let errors = validate_content(&content);
        assert!(errors.is_empty());
    }

    #[test]
    fn test_valid_figure() {
        let content = Content::new(vec![Block::figure(vec![
            Block::image("photo.png", "A photo"),
            Block::figcaption(vec![Text::plain("Figure 1")]),
        ])]);
        let errors = validate_content(&content);
        assert!(errors.is_empty());
    }

    #[test]
    fn test_figcaption_outside_figure() {
        let content = Content::new(vec![Block::figcaption(vec![Text::plain("Orphan caption")])]);
        let errors = validate_content(&content);
        assert!(errors.iter().any(|e| e.message.contains("child of figure")));
    }

    #[test]
    fn test_subfigure_with_invalid_block() {
        use super::super::block::{FigureBlock, Subfigure};

        let fig = FigureBlock {
            id: None,
            numbering: None,
            subfigures: Some(vec![Subfigure {
                id: Some("sub-a".to_string()),
                label: Some("(a)".to_string()),
                children: vec![Block::Image(super::super::block::ImageBlock {
                    id: None,
                    src: String::new(), // invalid: empty src
                    alt: String::new(), // invalid: empty alt
                    title: None,
                    width: None,
                    height: None,
                })],
            }]),
            children: vec![Block::image("main.png", "Main image")],
            attributes: BlockAttributes::default(),
        };

        let content = Content::new(vec![Block::Figure(fig)]);
        let errors = validate_content(&content);
        assert!(
            !errors.is_empty(),
            "subfigure with invalid block should produce errors"
        );
        // Should have errors for empty src and empty alt
        assert!(errors.iter().any(|e| e.message.contains("src")));
        assert!(errors.iter().any(|e| e.message.contains("alt")));
    }

    #[test]
    fn test_subfigure_duplicate_id() {
        use super::super::block::{FigureBlock, Subfigure};

        let fig = FigureBlock {
            id: Some("fig-1".to_string()),
            numbering: None,
            subfigures: Some(vec![Subfigure {
                id: Some("fig-1".to_string()), // duplicate of parent
                label: None,
                children: vec![Block::paragraph(vec![Text::plain("subfig")])],
            }]),
            children: vec![Block::paragraph(vec![Text::plain("content")])],
            attributes: BlockAttributes::default(),
        };

        let content = Content::new(vec![Block::Figure(fig)]);
        let errors = validate_content(&content);
        assert!(errors.iter().any(|e| e.message.contains("duplicate")));
    }

    #[test]
    fn test_heading_level_clamped_on_deser() {
        let json = r#"{"type":"heading","level":0,"children":[{"value":"Zero"}]}"#;
        let block: Block = serde_json::from_str(json).unwrap();
        if let Block::Heading { level, .. } = block {
            assert_eq!(level, 1, "level 0 should be clamped to 1");
        } else {
            panic!("Expected Heading");
        }

        let json = r#"{"type":"heading","level":99,"children":[{"value":"High"}]}"#;
        let block: Block = serde_json::from_str(json).unwrap();
        if let Block::Heading { level, .. } = block {
            assert_eq!(level, 6, "level 99 should be clamped to 6");
        } else {
            panic!("Expected Heading");
        }
    }

    #[test]
    fn test_measurement_empty_display() {
        let content = Content::new(vec![Block::Measurement(
            super::super::block::MeasurementBlock {
                id: None,
                value: 42.0,
                uncertainty: None,
                uncertainty_notation: None,
                exponent: None,
                display: String::new(), // Empty display should fail
                unit: None,
            },
        )]);
        let errors = validate_content(&content);
        assert!(errors.iter().any(|e| e.message.contains("display")));
    }
}