piki-gui 0.2.0

FLTK-based GUI for Piki personal wiki application
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
// Markdown Converter
// Converts between StructuredDocument and Markdown text format
// Markdown is used purely as a storage/serialization format

use super::markdown_ast::{ASTNode, Document as ASTDocument, NodeType};
use super::markdown_parser::parse_markdown;
use super::structured_document::*;

const MAX_LINE_WIDTH: usize = 80;
const BR_TOKEN: &str = "<<__FLIKI_BR__>>";
const NEWLINE_TOKEN: &str = "<<__FLIKI_NL__>>";

/// Convert markdown text to a StructuredDocument
pub fn markdown_to_document(markdown: &str) -> StructuredDocument {
    let ast_doc = parse_markdown(markdown);
    ast_to_structured(&ast_doc)
}

/// Convert a StructuredDocument to markdown text
pub fn document_to_markdown(doc: &StructuredDocument) -> String {
    let mut output = String::new();

    let mut is_first_block = true;
    let mut prev_list_ordered: Option<bool> = None;

    for block in doc.blocks() {
        let current_list_ordered = match &block.block_type {
            BlockType::ListItem { ordered, .. } => Some(*ordered),
            _ => None,
        };

        if !is_first_block {
            match (prev_list_ordered, current_list_ordered) {
                (Some(prev), Some(curr)) if prev == curr => output.push('\n'),
                _ => output.push_str("\n\n"),
            }
        }

        let block_markdown = match &block.block_type {
            BlockType::Paragraph => {
                wrap_text_with_indent(&inline_content_to_markdown(&block.content), "", "")
            }
            BlockType::Heading { level } => {
                let mut heading = "#".repeat(*level as usize);
                heading.push(' ');
                heading.push_str(&inline_content_to_markdown(&block.content));
                heading
            }
            BlockType::CodeBlock { language } => {
                let mut code = String::from("```");
                if let Some(lang) = language {
                    code.push_str(lang);
                }
                code.push('\n');
                code.push_str(&block.to_plain_text());
                code.push_str("\n```");
                code
            }
            BlockType::BlockQuote => {
                wrap_text_with_indent(&inline_content_to_markdown(&block.content), "> ", "> ")
            }
            BlockType::ListItem {
                ordered,
                number,
                checkbox,
            } => {
                let inline = inline_content_to_markdown(&block.content);
                let (initial_indent, subsequent_indent) =
                    list_item_indents(*ordered, *number, *checkbox);
                wrap_text_with_indent(&inline, &initial_indent, &subsequent_indent)
            }
        };

        output.push_str(&block_markdown);

        is_first_block = false;
        prev_list_ordered = current_list_ordered;
    }

    output
}

/// Convert inline content to markdown
fn inline_content_to_markdown(content: &[InlineContent]) -> String {
    let mut output = String::new();

    for (idx, item) in content.iter().enumerate() {
        match item {
            InlineContent::Text(run) => {
                let text = &run.text;

                // Handle code specially (overrides other styles)
                let styled = if run.style.code {
                    format!("`{}`", text)
                } else {
                    // Build up style wrappers from outermost to innermost
                    let mut result = text.clone();

                    // Strikethrough (outermost)
                    if run.style.strikethrough {
                        result = format!("~~{}~~", result);
                    }

                    // Bold and/or italic
                    if run.style.bold && run.style.italic {
                        result = format!("***{}***", result);
                    } else if run.style.bold {
                        result = format!("**{}**", result);
                    } else if run.style.italic {
                        result = format!("*{}*", result);
                    }

                    // Underline (HTML tag)
                    if run.style.underline {
                        result = format!("<u>{}</u>", result);
                    }

                    // Highlight (HTML tag, outermost)
                    if run.style.highlight {
                        result = format!("<mark>{}</mark>", result);
                    }

                    result
                };
                output.push_str(&styled);
            }
            InlineContent::Link { link, content } => {
                output.push('[');
                output.push_str(&inline_content_to_markdown(content));
                output.push_str("](");
                output.push_str(&link.destination);
                if let Some(title) = &link.title {
                    output.push_str(" \"");
                    output.push_str(title);
                    output.push('"');
                }
                output.push(')');
            }
            InlineContent::HardBreak => {
                let trailing_hard_break = content[idx..]
                    .iter()
                    .all(|c| matches!(c, InlineContent::HardBreak));
                let next_is_hard_break = content
                    .get(idx + 1)
                    .map(|c| matches!(c, InlineContent::HardBreak))
                    .unwrap_or(false);
                let prev_is_hard_break =
                    idx > 0 && matches!(content.get(idx - 1), Some(InlineContent::HardBreak));
                let part_of_hard_break_run = prev_is_hard_break || next_is_hard_break;

                if trailing_hard_break || part_of_hard_break_run {
                    output.push_str("<br>");
                    if trailing_hard_break && !next_is_hard_break {
                        output.push('\n');
                    }
                } else {
                    output.push_str("  \n");
                }
            }
        }
    }

    output
}

fn wrap_text_with_indent(text: &str, initial_indent: &str, subsequent_indent: &str) -> String {
    if text.is_empty() {
        return initial_indent.to_string();
    }

    if text.trim().is_empty() {
        return initial_indent.to_string();
    }

    if initial_indent.len() + text.len() <= MAX_LINE_WIDTH {
        if initial_indent.is_empty() {
            return text.to_string();
        }
        let mut line = initial_indent.to_string();
        line.push_str(text);
        return line;
    }

    let mut normalized = text.replace("<br>", &format!(" {} ", BR_TOKEN));
    normalized = normalized.replace('\n', &format!(" {} ", NEWLINE_TOKEN));

    let mut lines: Vec<String> = Vec::new();
    let mut current_line = String::new();
    let mut is_first_line = true;

    for token in normalized.split_whitespace() {
        if token == BR_TOKEN {
            if !current_line.is_empty() {
                current_line.push_str("<br>");
                lines.push(std::mem::take(&mut current_line));
            } else if let Some(last) = lines.last_mut() {
                last.push_str("<br>");
            } else {
                lines.push("<br>".to_string());
            }
            is_first_line = false;
            continue;
        }

        if token == NEWLINE_TOKEN {
            lines.push(std::mem::take(&mut current_line));
            is_first_line = false;
            continue;
        }

        let word = token;
        loop {
            let indent_len = if is_first_line && current_line.is_empty() {
                initial_indent.len()
            } else {
                subsequent_indent.len()
            };
            let needed_len = if current_line.is_empty() {
                indent_len + word.len()
            } else {
                indent_len + current_line.len() + 1 + word.len()
            };

            if !current_line.is_empty() && needed_len > MAX_LINE_WIDTH {
                lines.push(std::mem::take(&mut current_line));
                is_first_line = false;
                continue;
            }

            if current_line.is_empty() && indent_len + word.len() > MAX_LINE_WIDTH {
                current_line.push_str(word);
            } else {
                if !current_line.is_empty() {
                    current_line.push(' ');
                }
                current_line.push_str(word);
            }

            break;
        }
    }

    if !current_line.is_empty() {
        lines.push(current_line);
    }

    if lines.is_empty() {
        return initial_indent.to_string();
    }

    let mut result = String::new();
    for (idx, line) in lines.into_iter().enumerate() {
        if idx > 0 {
            result.push('\n');
        }
        let indent = if idx == 0 {
            initial_indent
        } else {
            subsequent_indent
        };
        result.push_str(indent);
        result.push_str(&line);
    }

    result
}

fn list_item_indents(
    ordered: bool,
    number: Option<u64>,
    checkbox: Option<bool>,
) -> (String, String) {
    if let Some(checked) = checkbox {
        let marker = if checked { "[x] " } else { "[ ] " };
        let initial = format!("- {}", marker);
        let subsequent = " ".repeat(initial.len());
        return (initial, subsequent);
    }

    if ordered {
        let value = number.unwrap_or(1);
        let initial = format!("{}. ", value);
        let subsequent = " ".repeat(initial.len());
        return (initial, subsequent);
    }

    let initial = "- ".to_string();
    let subsequent = "  ".to_string();
    (initial, subsequent)
}

/// Convert AST to StructuredDocument
fn ast_to_structured(ast_doc: &ASTDocument) -> StructuredDocument {
    let mut doc = StructuredDocument::new();

    for child in &ast_doc.root.children {
        ast_node_to_blocks(child, &mut doc);
    }

    // Ensure at least one block exists
    if doc.is_empty() {
        doc.add_block(Block::paragraph(0));
    }

    doc
}

/// Convert an AST node to one or more blocks (handles List which contains multiple ListItems)
fn ast_node_to_blocks(node: &ASTNode, doc: &mut StructuredDocument) {
    match &node.node_type {
        NodeType::List { ordered, start } => {
            // Process each list item as a separate block
            for (idx, child) in node.children.iter().enumerate() {
                if let NodeType::ListItem { checkbox } = &child.node_type {
                    let number = if *ordered {
                        Some(start + idx as u64)
                    } else {
                        None
                    };

                    let mut block = Block::new(
                        0,
                        BlockType::ListItem {
                            ordered: *ordered,
                            number,
                            checkbox: *checkbox,
                        },
                    );
                    block.content = ast_node_to_inline_content(child);
                    doc.add_block(block);
                }
            }
        }
        _ => {
            // Handle other block types
            if let Some(block) = ast_node_to_block(node, doc) {
                doc.add_block(block);
            }
        }
    }
}

/// Convert an AST node to a Block
fn ast_node_to_block(node: &ASTNode, _doc: &mut StructuredDocument) -> Option<Block> {
    let id = 0; // Will be assigned by document

    match &node.node_type {
        NodeType::Paragraph => {
            let mut block = Block::paragraph(id);
            block.content = ast_node_to_inline_content(node);
            Some(block)
        }
        NodeType::Heading { level } => {
            let mut block = Block::heading(id, *level);
            block.content = ast_node_to_inline_content(node);
            Some(block)
        }
        NodeType::CodeBlock { language, .. } => {
            let mut block = Block::new(
                id,
                BlockType::CodeBlock {
                    language: language.clone(),
                },
            );
            let text = node.flatten_text();
            block.content = vec![InlineContent::Text(TextRun::plain(text))];
            Some(block)
        }
        NodeType::BlockQuote => {
            let mut block = Block::new(id, BlockType::BlockQuote);
            block.content = ast_node_to_inline_content(node);
            Some(block)
        }
        NodeType::ListItem { checkbox } => {
            // Determine if parent is ordered or unordered
            // For now, assume unordered
            let mut block = Block::new(
                id,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: *checkbox,
                },
            );
            block.content = ast_node_to_inline_content(node);
            Some(block)
        }
        _ => None,
    }
}

/// Convert AST node children to inline content
fn ast_node_to_inline_content(node: &ASTNode) -> Vec<InlineContent> {
    let mut content = Vec::new();

    for child in &node.children {
        match &child.node_type {
            NodeType::Text {
                content: text,
                style,
            } => {
                let text_style = TextStyle {
                    bold: style.bold,
                    italic: style.italic,
                    code: style.code,
                    strikethrough: style.strikethrough,
                    underline: style.underline,
                    highlight: style.highlight,
                };
                if let Some(InlineContent::Text(existing)) = content.last_mut()
                    && existing.style == text_style
                {
                    existing.text.push_str(text);
                    continue;
                }
                content.push(InlineContent::Text(TextRun::new(text, text_style)));
            }
            NodeType::WikiLink { destination: _ } => {}
            NodeType::Code { content: text } => {
                content.push(InlineContent::Text(TextRun::new(text, TextStyle::code())));
            }
            NodeType::Link { destination, title } => {
                let link = Link {
                    destination: destination.clone(),
                    title: title.clone(),
                };
                let link_content = ast_node_to_inline_content(child);
                content.push(InlineContent::Link {
                    link,
                    content: link_content,
                });
            }
            NodeType::SoftBreak => {
                if let Some(InlineContent::Text(existing)) = content.last_mut() {
                    existing.text.push(' ');
                } else {
                    content.push(InlineContent::Text(TextRun::plain(" ")));
                }
            }
            NodeType::HardBreak => {
                content.push(InlineContent::HardBreak);
            }
            _ => {
                // Recursively process container nodes
                if child.node_type.can_have_children() {
                    content.extend(ast_node_to_inline_content(child));
                }
            }
        }
    }

    for idx in 1..content.len() {
        if matches!(content[idx - 1], InlineContent::HardBreak)
            && let InlineContent::Text(run) = &mut content[idx]
            && run.text.starts_with(' ')
        {
            run.text.remove(0);
        }
    }

    content
}

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

    #[test]
    fn test_markdown_to_document_paragraph() {
        let md = "Hello world";
        let doc = markdown_to_document(md);
        assert_eq!(doc.block_count(), 1);
        assert_eq!(doc.to_plain_text(), "Hello world");
    }

    #[test]
    fn test_markdown_to_document_heading() {
        let md = "# Heading 1\n\nSome text";
        let doc = markdown_to_document(md);
        assert_eq!(doc.block_count(), 2);

        if let BlockType::Heading { level } = doc.blocks()[0].block_type {
            assert_eq!(level, 1);
        } else {
            panic!("Expected heading");
        }
    }

    #[test]
    fn test_document_to_markdown_paragraph() {
        let mut doc = StructuredDocument::new();
        doc.add_block(Block::paragraph(0).with_plain_text("Hello world"));

        let md = document_to_markdown(&doc);
        assert_eq!(md, "Hello world");
    }

    #[test]
    fn test_document_to_markdown_heading() {
        let mut doc = StructuredDocument::new();
        doc.add_block(Block::heading(0, 1).with_plain_text("Title"));

        let md = document_to_markdown(&doc);
        assert_eq!(md, "# Title");
    }

    #[test]
    fn test_document_to_markdown_list() {
        let mut doc = StructuredDocument::new();
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: None,
                },
            )
            .with_plain_text("Item 1"),
        );
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: None,
                },
            )
            .with_plain_text("Item 2"),
        );

        let md = document_to_markdown(&doc);
        assert_eq!(md, "- Item 1\n- Item 2");
    }

    #[test]
    fn test_document_to_markdown_ordered_list_spacing() {
        let mut doc = StructuredDocument::new();
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: true,
                    number: Some(1),
                    checkbox: None,
                },
            )
            .with_plain_text("First"),
        );
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: true,
                    number: Some(2),
                    checkbox: None,
                },
            )
            .with_plain_text("Second"),
        );

        let md = document_to_markdown(&doc);
        assert_eq!(md, "1. First\n2. Second");
    }

    #[test]
    fn test_document_to_markdown_checklist_spacing() {
        let mut doc = StructuredDocument::new();
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: Some(false),
                },
            )
            .with_plain_text("Todo"),
        );
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: Some(true),
                },
            )
            .with_plain_text("Done"),
        );

        let md = document_to_markdown(&doc);
        assert_eq!(md, "- [ ] Todo\n- [x] Done");
    }

    #[test]
    fn test_document_to_markdown_list_spacing_between_types() {
        let mut doc = StructuredDocument::new();
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: None,
                },
            )
            .with_plain_text("Bullet item"),
        );
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: true,
                    number: Some(1),
                    checkbox: None,
                },
            )
            .with_plain_text("Numbered item"),
        );
        doc.add_block(Block::paragraph(0).with_plain_text("After list"));

        let md = document_to_markdown(&doc);
        assert_eq!(md, "- Bullet item\n\n1. Numbered item\n\nAfter list");
    }

    #[test]
    fn test_round_trip() {
        let original = "# Heading\n\nSome **bold** text.";
        let doc = markdown_to_document(original);
        let md = document_to_markdown(&doc);

        // Re-parse to verify structure is preserved
        let doc2 = markdown_to_document(&md);
        assert_eq!(doc.block_count(), doc2.block_count());
    }

    #[test]
    fn test_document_to_markdown_checklist() {
        let mut doc = StructuredDocument::new();
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: Some(false),
                },
            )
            .with_plain_text("Todo"),
        );
        doc.add_block(Block::paragraph(0).with_plain_text(""));
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: Some(true),
                },
            )
            .with_plain_text("Done"),
        );

        let md = document_to_markdown(&doc);
        assert_eq!(md, "- [ ] Todo\n\n\n\n- [x] Done");
    }

    #[test]
    fn test_markdown_export_wraps_paragraph_without_modifying_structure() {
        let mut doc = StructuredDocument::new();
        let long_text = (0..6)
            .map(|_| "Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .collect::<Vec<_>>()
            .join(" ");
        doc.add_block(Block::paragraph(0).with_plain_text(long_text));

        let markdown = document_to_markdown(&doc);
        let lines: Vec<&str> = markdown.lines().collect();
        assert!(
            lines.len() > 1,
            "expected wrapped output for long paragraph, got: {}",
            markdown
        );

        for line in &lines {
            assert!(
                line.len() <= MAX_LINE_WIDTH,
                "line exceeded {} characters: {}",
                MAX_LINE_WIDTH,
                line
            );
        }

        let round_tripped = markdown_to_document(&markdown);
        assert_eq!(round_tripped.blocks(), doc.blocks());
    }

    #[test]
    fn test_markdown_export_wraps_list_items_with_round_trip() {
        let mut doc = StructuredDocument::new();
        let long_text = (0..6)
            .map(|_| "Aliquam fermentum sapien nec quam feugiat, vitae placerat mauris luctus.")
            .collect::<Vec<_>>()
            .join(" ");
        doc.add_block(
            Block::new(
                0,
                BlockType::ListItem {
                    ordered: false,
                    number: None,
                    checkbox: None,
                },
            )
            .with_plain_text(long_text),
        );

        let markdown = document_to_markdown(&doc);
        let lines: Vec<&str> = markdown.lines().collect();
        assert!(
            lines.len() > 1,
            "expected wrapped output for long list item, got: {}",
            markdown
        );
        assert!(
            lines.iter().skip(1).all(|line| line.starts_with("  ")),
            "expected subsequent lines to be indented with spaces: {:?}",
            lines
        );
        for line in &lines {
            assert!(
                line.len() <= MAX_LINE_WIDTH,
                "line exceeded {} characters: {}",
                MAX_LINE_WIDTH,
                line
            );
        }

        let round_tripped = markdown_to_document(&markdown);
        assert_eq!(round_tripped.blocks(), doc.blocks());
    }

    #[test]
    fn test_markdown_export_wraps_blockquotes_with_round_trip() {
        let mut doc = StructuredDocument::new();
        let long_text = (0..5)
            .map(|_| "Praesent a orci sed lorem cursus tempor id ut lectus.")
            .collect::<Vec<_>>()
            .join(" ");
        doc.add_block(Block::new(0, BlockType::BlockQuote).with_plain_text(long_text));

        let markdown = document_to_markdown(&doc);
        let lines: Vec<&str> = markdown.lines().collect();
        assert!(
            lines.len() > 1,
            "expected wrapped output for blockquote, got: {}",
            markdown
        );
        assert!(
            lines.iter().all(|line| line.starts_with("> ")),
            "expected each blockquote line to start with '> ': {:?}",
            lines
        );
        for line in &lines {
            assert!(
                line.len() <= MAX_LINE_WIDTH,
                "line exceeded {} characters: {}",
                MAX_LINE_WIDTH,
                line
            );
        }

        let round_tripped = markdown_to_document(&markdown);
        assert_eq!(round_tripped.blocks(), doc.blocks());
    }

    #[test]
    fn test_markdown_export_wraps_blockquote_with_html_breaks() {
        let mut doc = StructuredDocument::new();
        let mut block = Block::new(0, BlockType::BlockQuote);
        block
            .content
            .push(InlineContent::Text(TextRun::plain("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur elementum augue ut erat laoreet, at tristique leo laoreet.")));
        block.content.push(InlineContent::HardBreak);
        block.content.push(InlineContent::HardBreak);
        block
            .content
            .push(InlineContent::Text(TextRun::plain("Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Integer euismod, justo in consequat fermentum, est mi sodales justo, at aliquam est mauris a lectus.")));
        doc.add_block(block);

        let markdown = document_to_markdown(&doc);
        let lines: Vec<&str> = markdown.lines().collect();
        assert!(
            lines.len() > 2,
            "expected wrapped blockquote with multiple lines, got: {}",
            markdown
        );
        assert!(
            lines.iter().all(|line| line.starts_with("> ")),
            "expected blockquote lines to keep '> ' prefix: {:?}",
            lines
        );
        assert!(
            lines.iter().all(|line| line.len() <= MAX_LINE_WIDTH),
            "line exceeded {} characters: {:?}",
            MAX_LINE_WIDTH,
            lines
        );
        assert!(
            markdown.contains("<br>"),
            "expected HTML breaks to be preserved: {}",
            markdown
        );

        let round_tripped = markdown_to_document(&markdown);
        assert_eq!(round_tripped.blocks(), doc.blocks());
    }

    #[test]
    fn test_markdown_to_document_checklist() {
        let md = "- [ ] Todo\n\n- [x] Done";
        let doc = markdown_to_document(md);
        assert_eq!(doc.block_count(), 2);
        match doc.blocks()[0].block_type {
            BlockType::ListItem {
                ordered: false,
                number: None,
                checkbox: Some(state),
            } => assert!(!state),
            _ => panic!("expected checklist"),
        }
        match doc.blocks()[1].block_type {
            BlockType::ListItem {
                ordered: false,
                number: None,
                checkbox: Some(state),
            } => assert!(state),
            _ => panic!("expected checklist"),
        }
    }

    #[test]
    fn test_markdown_to_document_wikilink() {
        let md = "A [[WikiPage]] link";
        let doc = markdown_to_document(md);
        assert_eq!(doc.block_count(), 1);
        let block = &doc.blocks()[0];
        // Expect at least one InlineContent::Link
        let has_link = block
            .content
            .iter()
            .any(|c| matches!(c, InlineContent::Link { .. }));
        assert!(has_link);
    }

    #[test]
    fn test_double_hard_break_round_trip() {
        let mut doc = StructuredDocument::new();
        let mut block = Block::paragraph(0);
        block
            .content
            .push(InlineContent::Text(TextRun::plain("Line 1")));
        block.content.push(InlineContent::HardBreak);
        block.content.push(InlineContent::HardBreak);
        block
            .content
            .push(InlineContent::Text(TextRun::plain("Line 2")));
        doc.add_block(block);

        let markdown = document_to_markdown(&doc);
        assert_eq!(markdown, "Line 1<br><br>Line 2");

        let round_tripped = markdown_to_document(&markdown);
        assert_eq!(
            round_tripped.block_count(),
            1,
            "blocks after round trip: {:?}",
            round_tripped.blocks()
        );
        let block = &round_tripped.blocks()[0];
        assert_eq!(block.content, doc.blocks()[0].content);
    }

    #[test]
    fn test_double_hard_break_round_trip_in_list_item() {
        let mut doc = StructuredDocument::new();
        let mut block = Block::new(
            0,
            BlockType::ListItem {
                ordered: false,
                number: None,
                checkbox: None,
            },
        );
        block
            .content
            .push(InlineContent::Text(TextRun::plain("First line")));
        block.content.push(InlineContent::HardBreak);
        block.content.push(InlineContent::HardBreak);
        block
            .content
            .push(InlineContent::Text(TextRun::plain("Second line")));
        doc.add_block(block);

        let markdown = document_to_markdown(&doc);
        assert_eq!(markdown, "- First line<br><br>Second line");

        let round_tripped = markdown_to_document(&markdown);
        assert_eq!(
            round_tripped.block_count(),
            1,
            "blocks after round trip: {:?}",
            round_tripped.blocks()
        );
        match &round_tripped.blocks()[0].block_type {
            BlockType::ListItem { .. } => {}
            other => panic!("expected list item, got {:?}", other),
        }
        assert_eq!(round_tripped.blocks()[0].content, doc.blocks()[0].content);
    }

    #[test]
    fn test_trailing_double_hard_break_round_trip() {
        let mut doc = StructuredDocument::new();
        let mut block = Block::paragraph(0);
        block
            .content
            .push(InlineContent::Text(TextRun::plain("Line 1")));
        block.content.push(InlineContent::HardBreak);
        block.content.push(InlineContent::HardBreak);
        doc.add_block(block);

        let markdown = document_to_markdown(&doc);
        assert_eq!(markdown, "Line 1<br><br>\n");

        let round_tripped = markdown_to_document(&markdown);
        assert_eq!(round_tripped.block_count(), 1);
        assert_eq!(round_tripped.blocks()[0].content, doc.blocks()[0].content);
    }
}