asciidoc-parser 0.15.2

Parser for AsciiDoc format
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
//! Virtual DOM representation of parsed AsciiDoc documents.
//!
//! This module provides a lightweight HTML-like representation of AsciiDoc
//! documents for testing purposes. It maps AsciiDoc block structures to their
//! HTML equivalents, enabling XPath-like queries for test assertions.

use std::sync::LazyLock;

use regex::Regex;

use crate::{
    Document, HasSpan,
    blocks::{
        Block, Break, ColumnStyle, CompoundDelimitedBlock, Frame, Grid, HorizontalAlignment,
        IsBlock, ListBlock, ListItem, ListItemMarker, ListType, MediaBlock, Preamble,
        RawDelimitedBlock, SectionBlock, SimpleBlock, SimpleBlockStyle, Stripes, TableBlock,
        TableCellContent, TableColumn, TableRow, VerticalAlignment,
    },
};

/// Decodes common HTML entities to their character equivalents.
///
/// This simulates what a browser would do when parsing HTML and accessing
/// text content via JavaScript's `textContent` or XPath's `text()`.
fn decode_html_entities(s: &str) -> String {
    let s = decode_numeric_entities(s);
    s.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&amp;", "&")
        .replace("&quot;", "\"")
        .replace("&apos;", "'")
}

/// Decodes numeric character references (`&#8230;` and `&#x2026;`) to their
/// character equivalents, mirroring what a browser does when reading `text()`.
/// Asciidoctor emits typographic replacements (ellipsis, dashes, zero-width
/// spaces) as numeric references, so the test DOM must decode them to compare
/// against the expected characters.
fn decode_numeric_entities(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut rest = s;

    while let Some(amp) = rest.find("&#") {
        result.push_str(&rest[..amp]);
        let after = &rest[amp + 2..];

        let (digits, radix) = match after.strip_prefix(['x', 'X']) {
            Some(hex) => (hex, 16),
            None => (after, 10),
        };

        let end = digits.find(';');
        let parsed = end
            .map(|e| &digits[..e])
            .and_then(|d| u32::from_str_radix(d, radix).ok())
            .and_then(char::from_u32);

        match (end, parsed) {
            (Some(e), Some(ch)) => {
                result.push(ch);
                rest = &digits[e + 1..];
            }
            _ => {
                // Not a well-formed numeric reference; keep the literal `&#`.
                result.push_str("&#");
                rest = after;
            }
        }
    }

    result.push_str(rest);
    result
}

/// Parses simple HTML inline markup from text and returns a mix of text and
/// element nodes.
///
/// This handles common inline HTML elements like <strong>, <em>, <code>, etc.
/// It does not handle nested elements or attributes - just simple tags with
/// text content.
fn parse_html_content(text: &str) -> Vec<VirtualNode> {
    let mut result = Vec::new();
    let mut last_pos = 0;
    let mut i = 0;

    while i < text.len() {
        if text[i..].starts_with('<') {
            // Try to parse an HTML element.
            if let Some((element, new_pos)) = try_parse_element(text, i) {
                // Add any text before this element.
                if i > last_pos {
                    let text_content = &text[last_pos..i];
                    if !text_content.is_empty() {
                        result.push(VirtualNode::new("text").with_text(text_content));
                    }
                }

                // Add the element.
                result.push(element);

                // Move forward.
                i = new_pos;
                last_pos = new_pos;
                continue;
            }
        }
        i += 1;
    }

    // Add any remaining text.
    if last_pos < text.len() {
        let remaining = &text[last_pos..];
        if !remaining.is_empty() {
            result.push(VirtualNode::new("text").with_text(remaining));
        }
    }

    // If we never created any nodes, create a text node.
    if result.is_empty() && !text.is_empty() {
        result.push(VirtualNode::new("text").with_text(text));
    }

    result
}

/// Attempts to parse an HTML element starting at position `pos`.
/// Returns the element and the position after the closing tag if successful.
fn try_parse_element(text: &str, pos: usize) -> Option<(VirtualNode, usize)> {
    if !text[pos..].starts_with('<') {
        return None;
    }

    // Find the end of the opening tag.
    let tag_end = text[pos + 1..].find('>')?;
    let tag_content = &text[pos + 1..pos + 1 + tag_end];
    let tag_name = extract_tag_name(tag_content)?;

    // Check for self-closing tag.
    if tag_content.ends_with('/') {
        return None; // Ignore self-closing tags.
    }

    // Find the closing tag.
    let after_opening = pos + 1 + tag_end + 1;
    let closing_tag = format!("</{tag_name}>");
    let close_pos = text[after_opening..].find(&closing_tag)?;

    // Extract content between tags.
    let content = &text[after_opening..after_opening + close_pos];
    let after_closing = after_opening + close_pos + closing_tag.len();

    // Create the element.
    let element = if content.contains('<') {
        // Nested HTML - recursively parse.
        VirtualNode::new(tag_name).with_children(parse_html_content(content))
    } else {
        // Plain text content.
        VirtualNode::new(tag_name).with_text(content)
    };

    // Capture the opening tag's attributes (id, class, href, etc.) so that
    // attribute predicates like `[@href="#x"]` can match inline elements.
    let element = apply_tag_attributes(element, tag_content);

    Some((element, after_closing))
}

/// Matches `name="value"` attribute pairs in an opening tag. Renderer output
/// always uses double quotes, so single-quoted values are not handled.
static HTML_ATTR: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(r#"([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*"([^"]*)""#).unwrap()
});

/// Parses the attributes from an opening tag's content and applies them to
/// `node`, routing `id` and `class` to their dedicated fields and everything
/// else into the generic attribute map.
fn apply_tag_attributes(mut node: VirtualNode, tag_content: &str) -> VirtualNode {
    // Skip the tag name; only the remainder can contain attributes.
    let attrs = tag_content
        .trim()
        .split_once(char::is_whitespace)
        .map(|(_, rest)| rest)
        .unwrap_or("");

    for caps in HTML_ATTR.captures_iter(attrs) {
        let name = &caps[1];
        let value = caps[2].to_string();

        match name {
            "id" => node.id = Some(value),
            "class" => {
                for class in value.split_whitespace() {
                    node.classes.push(class.to_string());
                }
            }
            _ => {
                node.attributes.insert(name.to_string(), value);
            }
        }
    }

    node
}

/// Extracts the tag name from an opening tag string (without the < and >).
fn extract_tag_name(tag_content: &str) -> Option<String> {
    let tag_content = tag_content.trim();
    if tag_content.is_empty() || tag_content.starts_with('/') {
        return None;
    }

    // Extract tag name (before any whitespace or attributes).
    let tag_name = tag_content
        .split_whitespace()
        .next()
        .unwrap_or(tag_content)
        .trim_end_matches('/');

    if tag_name.is_empty() {
        None
    } else {
        Some(tag_name.to_string())
    }
}

/// A virtual DOM node representing an HTML-like element.
///
/// This structure is built from a parsed `Document` and maps AsciiDoc blocks
/// to their HTML equivalents for testing purposes.
#[derive(Debug, Clone, PartialEq)]
pub struct VirtualNode {
    /// HTML tag name (e.g., "ul", "li", "p", "div").
    pub tag: String,

    /// CSS classes applied to this element.
    pub classes: Vec<String>,

    /// Element ID attribute, if any.
    pub id: Option<String>,

    /// Text content of this element (for leaf nodes).
    pub text: Option<String>,

    /// Other HTML attributes (e.g., "start", "type", etc.).
    pub attributes: std::collections::HashMap<String, String>,

    /// Child elements.
    pub children: Vec<VirtualNode>,
}

#[allow(dead_code)] // TEMPORARY while building
impl VirtualNode {
    /// Creates a new virtual node with the specified tag.
    pub fn new(tag: impl Into<String>) -> Self {
        Self {
            tag: tag.into(),
            classes: Vec::new(),
            id: None,
            text: None,
            attributes: std::collections::HashMap::new(),
            children: Vec::new(),
        }
    }

    /// Adds a CSS class to this node.
    pub fn with_class(mut self, class: impl Into<String>) -> Self {
        self.classes.push(class.into());
        self
    }

    /// Adds multiple CSS classes to this node.
    pub fn with_classes(mut self, classes: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.classes.extend(classes.into_iter().map(Into::into));
        self
    }

    /// Sets the ID of this node.
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Sets an arbitrary HTML attribute on this node.
    pub fn with_attribute(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(name.into(), value.into());
        self
    }

    /// Sets the text content of this node.
    ///
    /// Decodes HTML entities to match what a browser's text content would show.
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(decode_html_entities(&text.into()));
        self
    }

    /// Sets the text content and parses any HTML inline elements.
    ///
    /// This will parse HTML tags like <strong>, <em>, <code>, etc. and create
    /// child nodes for them.
    pub fn with_html_content(mut self, text: impl Into<String>) -> Self {
        let content = text.into();

        // Check if there's any HTML to parse.
        if content.contains('<') {
            self.children = parse_html_content(&content);
        } else {
            // No HTML - just set as plain text.
            self.text = Some(decode_html_entities(&content));
        }

        self
    }

    /// Adds a child node.
    pub fn with_child(mut self, child: VirtualNode) -> Self {
        self.children.push(child);
        self
    }

    /// Adds multiple child nodes.
    pub fn with_children(mut self, children: impl IntoIterator<Item = VirtualNode>) -> Self {
        self.children.extend(children);
        self
    }
}

/// Trait for converting AsciiDoc structures to virtual DOM nodes.
pub trait ToVirtualDom {
    /// Converts this structure to a virtual DOM node.
    fn to_virtual_dom(&self) -> VirtualNode;
}

impl ToVirtualDom for Document<'_> {
    fn to_virtual_dom(&self) -> VirtualNode {
        let mut node = VirtualNode::new("div").with_class("document");

        // Add document ID if present.
        if let Some(id) = self.id() {
            node = node.with_id(id);
        }

        // The document title renders as an `<h1>` when it is shown (the
        // effective `showtitle`/`notitle` state).
        if self.show_doctitle()
            && let Some(title) = self.doctitle()
        {
            node.children.push(VirtualNode::new("h1").with_text(title));
        }

        // Add child blocks, including block titles as separate siblings.
        for block in self.nested_blocks() {
            add_block_with_title(&mut node, block);
        }

        node
    }
}

/// Adds a block to the parent node, including its title as a separate sibling
/// element if present.
///
/// NOTE: Some block types (like lists) handle their titles internally, so we
/// skip adding a separate title element for those.
fn add_block_with_title<'a>(parent: &mut VirtualNode, block: &'a Block<'a>) {
    // Check if this block type handles its own title internally. Lists render
    // their title inside the list wrapper; tables render it as a <caption>.
    let handles_title_internally = matches!(block, Block::List(_) | Block::Table(_));

    // Add title as a separate sibling element if the block doesn't handle it
    // internally.
    if !handles_title_internally && let Some(title) = block.title() {
        // Add title as a separate div element with class="title".
        let title_node = VirtualNode::new("div").with_class("title").with_text(title);
        parent.children.push(title_node);
    }

    // Check if this is a paragraph that needs to be wrapped in div.paragraph.
    // Asciidoctor wraps top-level paragraphs in <div
    // class="paragraph"><p>...</p></div>.
    if let Block::Simple(simple) = block
        && simple.declared_style().is_none()
        && simple.style() == SimpleBlockStyle::Paragraph
    {
        let mut p_node = block.to_virtual_dom();
        let mut wrapper = VirtualNode::new("div").with_class("paragraph");

        // Roles and ID belong on the wrapper div, not the inner <p>.
        wrapper.classes.append(&mut p_node.classes);
        if p_node.id.is_some() {
            wrapper.id = p_node.id.take();
        }

        wrapper.children.push(p_node);
        parent.children.push(wrapper);
    } else {
        // Add the block itself (which will handle its own title if applicable).
        parent.children.push(block.to_virtual_dom());
    }
}

impl ToVirtualDom for Block<'_> {
    fn to_virtual_dom(&self) -> VirtualNode {
        match self {
            Block::Simple(simple) => {
                // Comment blocks should not be rendered.
                if simple.declared_style() == Some("comment") {
                    return VirtualNode::new("comment");
                }

                let mut node = simple_block_to_node(simple);

                // For literal and verse blocks, add a <pre> element containing the content.
                if simple.style() == SimpleBlockStyle::Literal
                    || simple.declared_style() == Some("literal")
                    || simple.declared_style() == Some("verse")
                {
                    let pre_node =
                        VirtualNode::new("pre").with_text(simple.content().rendered().to_string());
                    node = node.with_child(pre_node);
                }
                node
            }

            Block::List(list) => list_block_to_node(list),
            Block::ListItem(item) => list_item_to_node(item),

            Block::Section(section) => {
                let mut node = section_to_node(section);
                // Add section title as heading element.
                // Section levels are 1-5, which map to h2-h6.
                let heading_level = (section.level() + 1).min(6);
                let heading_tag = format!("h{}", heading_level);

                let mut title_node =
                    VirtualNode::new(heading_tag).with_text(section.section_title());

                // Add the section ID to the heading element if present.
                if let Some(id) = section.id() {
                    title_node = title_node.with_id(id);
                }

                node.children.insert(0, title_node);
                node
            }

            Block::Media(media) => media_to_node(media),
            Block::RawDelimited(raw) => raw_delimited_to_node(raw),
            Block::CompoundDelimited(compound) => compound_delimited_to_node(compound),
            Block::Table(table) => table_to_node(table),
            Block::Preamble(preamble) => preamble_to_node(preamble),
            Block::Break(break_) => break_to_node(break_),
            Block::DocumentAttribute(_) => {
                // Document attributes don't render in HTML.
                VirtualNode::new("comment")
            }
        }
    }
}

fn simple_block_to_node<'a>(block: &'a SimpleBlock<'a>) -> VirtualNode {
    let declared_style = block.declared_style();
    let block_style = block.style();

    // Determine tag and classes based on both declared style and block style.
    let (tag, wrapper_classes) =
        if block_style == SimpleBlockStyle::Literal || declared_style == Some("literal") {
            ("div", vec!["literalblock"])
        } else {
            match declared_style {
                Some("paragraph") | None => ("p", vec![]),
                Some("verse") => ("div", vec!["verseblock"]),
                Some("quote") => ("div", vec!["quoteblock"]),
                Some("sidebar") => ("div", vec!["sidebarblock"]),
                Some("example") => ("div", vec!["exampleblock"]),
                Some("open") => ("div", vec!["openblock"]),
                Some("pass") => ("div", vec!["passblock"]),
                _ => ("p", vec![]),
            }
        };

    let mut node = VirtualNode::new(tag);

    for class in wrapper_classes {
        node = node.with_class(class);
    }

    for role in block.roles() {
        node = node.with_class(role);
    }

    if let Some(id) = block.id() {
        node = node.with_id(id);
    }

    // Extract text content for paragraphs (only for <p> tags).
    if tag == "p" {
        node = node.with_html_content(block.content().rendered().to_string());
    }

    node
}

fn list_block_to_node<'a>(list: &'a ListBlock<'a>) -> VirtualNode {
    // Horizontal description lists render as tables instead of dl elements.
    let is_horizontal =
        list.type_() == ListType::Description && list.declared_style() == Some("horizontal");

    let (list_tag, base_class) = match list.type_() {
        ListType::Unordered => ("ul", "ulist"),
        ListType::Ordered => ("ol", "olist"),
        ListType::Description => {
            if is_horizontal {
                ("table", "hdlist")
            } else {
                ("dl", "dlist")
            }
        }
    };

    let mut list_element = VirtualNode::new(list_tag);

    // For ordered lists, add style class to the list element based on marker
    // length, but only if no explicit style is declared.
    if list.type_() == ListType::Ordered
        && list.declared_style().is_none()
        && let Some(style) = list.marker_style()
    {
        list_element = list_element.with_class(style);
    }

    // For ordered lists whose explicit numbering does not start at 1, emit the
    // implicit `start` attribute (matching Asciidoctor).
    if list.type_() == ListType::Ordered
        && let Some(Block::ListItem(first)) = list.nested_blocks().next()
        && let Some(ordinal) = first.list_item_marker().ordinal_value()
        && ordinal != 1
    {
        list_element = list_element.with_attribute("start", ordinal.to_string());
    }

    // Add all named attributes from the attrlist to the list element.
    if let Some(attrlist) = list.attrlist() {
        for attr in attrlist.attributes() {
            if let Some(attr_name) = attr.name() {
                list_element = list_element.with_attribute(attr_name, attr.value());
            }
        }
    }

    // Add options as boolean attributes on the list element.
    for option in list.options() {
        list_element = list_element.with_attribute(option, "");
    }

    // Add style class to the list element if present.
    // Skip for horizontal dlists since they use a different rendering.
    if !is_horizontal && let Some(style) = list.declared_style() {
        list_element = list_element.with_class(style);
    }

    for item in list.nested_blocks() {
        // For description lists, we need to create two peer nodes: dt and dd
        // (or tr/td for horizontal lists).
        if list.type_() == ListType::Description {
            if let Block::ListItem(list_item) = item {
                // Create dt node for the term.
                if let ListItemMarker::DefinedTerm { term, .. } = list_item.list_item_marker() {
                    if is_horizontal {
                        // Horizontal description lists render as table rows.
                        let mut tr_node = VirtualNode::new("tr");

                        let td_term = VirtualNode::new("td")
                            .with_class("hdlist1")
                            .with_html_content(term.rendered().to_string());
                        tr_node.children.push(td_term);

                        let mut td_def = VirtualNode::new("td").with_class("hdlist2");
                        let nested = list_item.nested_blocks().collect::<Vec<_>>();
                        for child in &nested {
                            td_def.children.push(child.to_virtual_dom());
                        }
                        tr_node.children.push(td_def);

                        list_element.children.push(tr_node);
                    } else {
                        let mut dt_node = VirtualNode::new("dt");

                        for role in list_item.roles() {
                            dt_node = dt_node.with_class(role);
                        }

                        if let Some(id) = list_item.id() {
                            dt_node = dt_node.with_id(id);
                        }

                        // Set the term text.
                        dt_node = dt_node.with_html_content(term.rendered().to_string());
                        list_element.children.push(dt_node);

                        // Create dd node for the definition, but only if the item has content.
                        // Multiple consecutive terms can share a single definition.
                        let nested = list_item.nested_blocks().collect::<Vec<_>>();

                        if !nested.is_empty() {
                            let mut dd_node = VirtualNode::new("dd");

                            let has_multiple_blocks = nested.len() > 1;

                            // Check if the first block was attached via list
                            // continuation (+). When content is from continuation,
                            // paragraphs should be wrapped in div.paragraph.
                            let first_block_from_continuation =
                                nested.first().is_some_and(|first_block| {
                                    let item_span = list_item.span();
                                    let marker_span = list_item.list_item_marker().span();

                                    let marker_end_offset =
                                        marker_span.byte_offset() + marker_span.data().len();

                                    let first_block_offset = first_block.span().byte_offset();

                                    let item_start = item_span.byte_offset();

                                    if first_block_offset > marker_end_offset
                                        && marker_end_offset >= item_start
                                    {
                                        let start = marker_end_offset - item_start;
                                        let end = first_block_offset - item_start;

                                        if end <= item_span.data().len() {
                                            let between = &item_span.data()[start..end];
                                            between.lines().any(|line| line.trim() == "+")
                                        } else {
                                            false
                                        }
                                    } else {
                                        false
                                    }
                                });

                            for (index, child) in nested.iter().enumerate() {
                                let child_vdom = child.to_virtual_dom();

                                // Wrap paragraphs in div.paragraph when they
                                // appear after other blocks or when the first
                                // block was attached via continuation.
                                let should_wrap = child_vdom.tag == "p"
                                    && child_vdom.classes.is_empty()
                                    && ((has_multiple_blocks && index > 0)
                                        || (index == 0 && first_block_from_continuation));

                                if should_wrap {
                                    let wrapper = VirtualNode::new("div")
                                        .with_class("paragraph")
                                        .with_child(child_vdom);
                                    dd_node.children.push(wrapper);
                                } else {
                                    dd_node.children.push(child_vdom);
                                }
                            }

                            list_element.children.push(dd_node);
                        }
                    }
                }
            }
        } else {
            list_element.children.push(item.to_virtual_dom());
        }
    }

    // Wrap the list in a div container (matching Asciidoctor's HTML structure).
    let mut wrapper = VirtualNode::new("div").with_class(base_class);

    // For ordered lists, add style class to the wrapper based on marker length,
    // but only if no explicit style is declared.
    if list.type_() == ListType::Ordered
        && list.declared_style().is_none()
        && let Some(style) = list.marker_style()
    {
        wrapper = wrapper.with_class(style);
    }

    // Add style class to the wrapper if present (explicit style overrides marker
    // style). Skip for horizontal dlists since wrapper already has hdlist class.
    if !is_horizontal && let Some(style) = list.declared_style() {
        wrapper = wrapper.with_class(style);
    }

    for role in list.roles() {
        wrapper = wrapper.with_class(role);
    }

    if let Some(id) = list.id() {
        wrapper = wrapper.with_id(id);
    }

    // Add block title if present (inside the wrapper, before the list element).
    if let Some(title) = list.title() {
        let title_node = VirtualNode::new("div").with_class("title").with_text(title);
        wrapper.children.push(title_node);
    }

    wrapper.children.push(list_element);
    wrapper
}

fn list_item_to_node<'a>(item: &'a ListItem<'a>) -> VirtualNode {
    let mut node = VirtualNode::new("li");

    for role in item.roles() {
        node = node.with_class(role);
    }

    if let Some(id) = item.id() {
        node = node.with_id(id);
    }

    let nested = item.nested_blocks().collect::<Vec<_>>();
    let has_multiple_blocks = nested.len() > 1;

    for (index, child) in nested.iter().enumerate() {
        let child_vdom = child.to_virtual_dom();

        // Wrap paragraphs in div.paragraph when they appear after other blocks in the
        // list item. This matches Asciidoctor's HTML output for list
        // continuations. The first paragraph block is never wrapped, only
        // subsequent ones.
        if has_multiple_blocks
            && index > 0
            && child_vdom.tag == "p"
            && child_vdom.classes.is_empty()
        {
            let wrapper = VirtualNode::new("div")
                .with_class("paragraph")
                .with_child(child_vdom);
            node.children.push(wrapper);
        } else {
            node.children.push(child_vdom);
        }
    }

    node
}

fn section_to_node<'a>(section: &'a SectionBlock<'a>) -> VirtualNode {
    let class = format!("sect{}", section.level());
    let mut node = VirtualNode::new("div").with_class(class);

    for role in section.roles() {
        node = node.with_class(role);
    }

    if let Some(id) = section.id() {
        node = node.with_id(id);
    }

    // TODO: Section title heading is added in the Block::Section match arm
    // using section.level() to determine the heading level (h2-h6) and
    // section.section_title() to get the rendered title text.

    // Add nested blocks, handling block titles as separate siblings.
    for child in section.nested_blocks() {
        add_block_with_title(&mut node, child);
    }

    node
}

fn media_to_node<'a>(media: &'a MediaBlock<'a>) -> VirtualNode {
    // Media blocks render as <div class="imageblock"> or similar.
    let context = media.raw_context();
    let class = format!("{}block", context.as_ref());

    let mut node = VirtualNode::new("div").with_class(class);

    for role in media.roles() {
        node = node.with_class(role);
    }

    if let Some(id) = media.id() {
        node = node.with_id(id);
    }

    // TODO: Media blocks typically contain an <img> or similar element.
    // We'll add this when we need more detailed media representation.

    node
}

fn raw_delimited_to_node<'a>(raw: &'a RawDelimitedBlock<'a>) -> VirtualNode {
    let context = raw.raw_context();

    let (tag, classes): (&str, Vec<String>) = match context.as_ref() {
        "listing" => ("div", vec!["listingblock".to_string()]),
        "literal" => ("div", vec!["literalblock".to_string()]),
        "comment" => ("comment", vec![]),
        _ => ("div", vec![format!("{}block", context.as_ref())]),
    };

    let mut node = VirtualNode::new(tag);
    for class in classes {
        node = node.with_class(class);
    }

    for role in raw.roles() {
        node = node.with_class(role);
    }

    if let Some(id) = raw.id() {
        node = node.with_id(id);
    }

    // Add block title if present.
    if let Some(title) = raw.title() {
        let title_node = VirtualNode::new("div").with_class("title").with_text(title);
        node.children.push(title_node);
    }

    if tag != "comment" {
        // Check if this is a source block by looking for style="source" in attrlist.
        let is_source_block = raw
            .attrlist()
            .and_then(|attrlist| attrlist.attributes().next())
            .map(|attr| attr.value() == "source")
            .unwrap_or(false);

        if is_source_block {
            // For source blocks, create pre > code structure.
            let mut code = VirtualNode::new("code");

            // Add data-lang attribute if language is specified (second positional
            // attribute).
            if let Some(attrlist) = raw.attrlist() {
                let mut attrs = attrlist.attributes();
                // Skip first attribute (style="source").
                attrs.next();
                // Second attribute is the language.
                if let Some(lang_attr) = attrs.next() {
                    code = code.with_attribute("data-lang", lang_attr.value());
                }
            }

            // Add the block's rendered content to the code element.
            if let Some(content) = raw.rendered_content() {
                code = code.with_text(content);
            }

            let pre = VirtualNode::new("pre").with_child(code);
            node.children.push(pre);
        } else {
            let mut pre = VirtualNode::new("pre");
            if let Some(content) = raw.rendered_content() {
                pre = pre.with_text(content);
            }
            node.children.push(pre);
        }
    }

    node
}

fn compound_delimited_to_node<'a>(compound: &'a CompoundDelimitedBlock<'a>) -> VirtualNode {
    let context = compound.raw_context();
    let class = format!("{}block", context.as_ref());

    let mut node = VirtualNode::new("div").with_class(class);

    for role in compound.roles() {
        node = node.with_class(role);
    }

    if let Some(id) = compound.id() {
        node = node.with_id(id);
    }

    for child in compound.nested_blocks() {
        node.children.push(child.to_virtual_dom());
    }

    node
}

fn table_to_node<'a>(table: &'a TableBlock<'a>) -> VirtualNode {
    // The table-level classes mirror Asciidoctor's HTML backend: always
    // `tableblock`, then the frame and grid classes, then a width class.
    let mut classes = vec![
        "tableblock".to_string(),
        frame_class(table.frame()).to_string(),
        grid_class(table.grid()).to_string(),
    ];

    // A table whose columns are sized to their content renders `fit-content`; a
    // full-width (default) table renders `stretch`; a table with an explicit
    // width renders neither (the width travels in the `width` attribute).
    let autowidth = table.columns().iter().any(TableColumn::is_autowidth);
    if autowidth {
        classes.push("fit-content".to_string());
    } else if table.width().is_none() {
        classes.push("stretch".to_string());
    }

    if let Some(stripes) = stripes_class(table.stripes()) {
        classes.push(stripes.to_string());
    }

    // The `float` attribute renders as a bare direction class (e.g. `left`).
    if let Some(float) = table
        .attrlist()
        .and_then(|a| a.named_attribute("float"))
        .map(|a| a.value())
    {
        classes.push(float.to_string());
    }

    let mut node = VirtualNode::new("table").with_classes(classes);

    if let Some(id) = table.id() {
        node = node.with_id(id);
    }

    for role in table.roles() {
        node = node.with_class(role);
    }

    // An explicit table width is carried in the `width` attribute as a
    // percentage, matching `table[width="50%"]`-style assertions.
    if let Some(width) = table.width() {
        node = node.with_attribute("width", format!("{width}%"));
    }

    if let Some(title) = table.title() {
        // A titled table renders a <caption class="title">. When the processor
        // assigned an automatic caption (e.g. "Table 1. "), it is prepended to
        // the title text.
        let caption_text = match table.caption() {
            Some(caption) => format!("{caption}{title}"),
            None => title.to_string(),
        };

        node.children.push(
            VirtualNode::new("caption")
                .with_class("title")
                .with_text(caption_text),
        );
    }

    // A table with no rows at all (e.g. every row was dropped for exceeding the
    // column count) renders as a bare `<table>` with no colgroup or sections.
    if table.header_row().is_none() && table.body_rows().is_empty() && table.footer_row().is_none()
    {
        return node;
    }

    let mut colgroup = VirtualNode::new("colgroup");
    for (column, pcwidth) in table.columns().iter().zip(column_pcwidths(table.columns())) {
        // Every column exposes its computed percentage width in `colpcwidth`,
        // mirroring the model attribute Asciidoctor assigns to each column.
        let mut col = VirtualNode::new("col").with_attribute("colpcwidth", pcwidth.clone());

        if column.is_autowidth() {
            // An autowidth column is sized to its content: it carries the
            // `autowidth-option` marker (present with an empty value) and no HTML
            // `width` attribute.
            col = col.with_attribute("autowidth-option", "");
        } else {
            // A proportional column emits its percentage as the HTML `width`.
            col = col.with_attribute("width", format!("{pcwidth}%"));
        }

        colgroup.children.push(col);
    }
    node.children.push(colgroup);

    if let Some(header) = table.header_row() {
        let mut thead = VirtualNode::new("thead");
        thead.children.push(table_row_to_node(header, true, false));
        node.children.push(thead);
    }

    if !table.body_rows().is_empty() {
        let mut tbody = VirtualNode::new("tbody");
        for row in table.body_rows() {
            tbody.children.push(table_row_to_node(row, false, true));
        }
        node.children.push(tbody);
    }

    // The footer renders after the body, so the section order is
    // thead, tbody, tfoot.
    if let Some(footer) = table.footer_row() {
        let mut tfoot = VirtualNode::new("tfoot");
        tfoot.children.push(table_row_to_node(footer, false, true));
        node.children.push(tfoot);
    }

    node
}

/// Renders one table row. `header_row` marks the row as the table's header (its
/// cells become `<th>` and their content is not wrapped in a paragraph);
/// otherwise cells are `<td>` and body content is wrapped in a
/// `<p class="tableblock">` (`wrap_in_paragraph`).
fn table_row_to_node(row: &TableRow<'_>, header_row: bool, wrap_in_paragraph: bool) -> VirtualNode {
    let mut tr = VirtualNode::new("tr");

    for cell in row.cells() {
        // A cell carrying the header style renders as a `<th>` even outside the
        // header row; otherwise header rows use `<th>` and body/footer rows use
        // `<td>`.
        let cell_tag = if header_row || cell.style() == ColumnStyle::Header {
            "th"
        } else {
            "td"
        };

        let mut cell_node = VirtualNode::new(cell_tag).with_classes([
            "tableblock".to_string(),
            halign_class(cell.h_align()).to_string(),
            valign_class(cell.v_align()).to_string(),
        ]);

        if cell.colspan() > 1 {
            cell_node = cell_node.with_attribute("colspan", cell.colspan().to_string());
        }
        if cell.rowspan() > 1 {
            cell_node = cell_node.with_attribute("rowspan", cell.rowspan().to_string());
        }

        match cell.content() {
            TableCellContent::Simple(content) => {
                let rendered = content.rendered().to_string();

                match cell.style() {
                    // A literal cell renders its content verbatim inside a
                    // `<div class="literal"><pre>…</pre></div>`.
                    ColumnStyle::Literal => {
                        cell_node.children.push(
                            VirtualNode::new("div")
                                .with_class("literal")
                                .with_child(VirtualNode::new("pre").with_html_content(rendered)),
                        );
                    }

                    _ if !wrap_in_paragraph => {
                        // Header-row cells place their content directly in the
                        // cell, wrapped only by any style element.
                        match style_wrapper(cell.style()) {
                            Some(tag) => cell_node
                                .children
                                .push(VirtualNode::new(tag).with_html_content(rendered)),
                            None => cell_node = cell_node.with_html_content(rendered),
                        }
                    }

                    // An empty body cell renders as an empty `<td>` with no
                    // paragraph.
                    _ if rendered.is_empty() => {}

                    style => match style_wrapper(style) {
                        // A text-styled cell wraps its content in a
                        // `<p class="tableblock">` with an inner style element
                        // (`<strong>`, `<em>`, `<code>`).
                        Some(tag) => {
                            cell_node.children.push(
                                VirtualNode::new("p")
                                    .with_class("tableblock")
                                    .with_child(VirtualNode::new(tag).with_html_content(rendered)),
                            );
                        }

                        // A plain cell renders each blank-line-separated
                        // paragraph as its own `<p class="tableblock">`, matching
                        // Asciidoctor (the parser stores them as one cell with
                        // embedded blank lines).
                        None => {
                            for para in
                                split_cell_paragraphs(content.original().data(), content.rendered())
                            {
                                cell_node.children.push(
                                    VirtualNode::new("p")
                                        .with_class("tableblock")
                                        .with_html_content(para),
                                );
                            }
                        }
                    },
                }
            }

            // An AsciiDoc-styled cell holds a nested document, which renders into
            // a `<div class="content">` wrapper inside the cell. The blocks
            // render as they would at the top level of a document (e.g.
            // paragraphs wrapped in `<div class="paragraph">`), so the cell
            // reuses `add_block_with_title`.
            TableCellContent::AsciiDoc(cell) => {
                let mut content = VirtualNode::new("div").with_class("content");

                // The nested document's title renders as an `<h1>` when shown.
                if let Some(title) = cell.title() {
                    content
                        .children
                        .push(VirtualNode::new("h1").with_text(title));
                }

                if cell.is_inline() {
                    // An `inline` doctype renders block content as bare inline
                    // content, without the `<div class="paragraph"><p>` wrapper.
                    for block in cell.blocks() {
                        match block.rendered_content() {
                            Some(rendered) => {
                                content.children.extend(parse_html_content(rendered));
                            }
                            None => add_block_with_title(&mut content, block),
                        }
                    }
                } else {
                    for block in cell.blocks() {
                        add_block_with_title(&mut content, block);
                    }
                }

                cell_node.children.push(content);
            }
        }

        tr.children.push(cell_node);
    }

    tr
}

/// Computes the `colpcwidth` (percentage width) that Asciidoctor assigns to
/// every column, mirroring `Table#assign_column_widths`.
///
/// Each autowidth column takes an equal share of the space the fixed columns
/// leave free (`(100 - fixed_total) / autowidth_count`); every column's
/// percentage is then truncated to four decimal places and the rounding balance
/// is donated to the final column so the widths sum to exactly 100. The value
/// is returned for every column (including autowidth columns, which carry the
/// percentage in the model even though the HTML backend omits their `width`
/// attribute).
fn column_pcwidths(columns: &[TableColumn]) -> Vec<String> {
    let n = columns.len();
    if n == 0 {
        return vec![];
    }

    let fixed_total: usize = columns
        .iter()
        .filter(|c| !c.is_autowidth())
        .map(TableColumn::width)
        .sum();

    // Resolve the effective per-column width and the base they are a percentage
    // of. With autowidth columns present the base is the full 100% and each
    // autowidth column takes an equal share of the remaining space (collapsing
    // to zero when the fixed columns already exceed 100%); otherwise each
    // column's own proportional width is taken over the sum of all widths.
    let (effective, base): (Vec<f64>, f64) = if columns.iter().any(TableColumn::is_autowidth) {
        let autowidth_count = columns.iter().filter(|c| c.is_autowidth()).count();
        let (share, base) = if fixed_total > 100 {
            (0.0, fixed_total as f64)
        } else {
            (
                truncate4((100.0 - fixed_total as f64) / autowidth_count as f64),
                100.0,
            )
        };
        let effective = columns
            .iter()
            .map(|c| {
                if c.is_autowidth() {
                    share
                } else {
                    c.width() as f64
                }
            })
            .collect();
        (effective, base)
    } else {
        let base = if fixed_total == 0 {
            n as f64
        } else {
            fixed_total as f64
        };
        (columns.iter().map(|c| c.width() as f64).collect(), base)
    };

    let mut pct: Vec<f64> = effective
        .iter()
        .map(|w| truncate4(w * 100.0 / base))
        .collect();

    // Donate the rounding balance to the final column.
    let total: f64 = pct.iter().sum();
    if (total - 100.0).abs() > 1e-9 {
        let last = n - 1;
        pct[last] = round4(100.0 - total + pct[last]);
    }

    pct.iter().map(|w| format_pcwidth(*w)).collect()
}

/// Splits a plain (non-styled) table cell's content into paragraphs, returning
/// the rendered text of each.
///
/// A paragraph break is a blank line in the **source**, not the rendered text.
/// This matters for an attribute reference such as `{blank}`: a line containing
/// only `{blank}` renders as an empty line but is not blank in the source, so
/// it must not split the paragraph (matching Asciidoctor). Inline substitution
/// is line-preserving, so the source and rendered line counts line up; each
/// non-blank source line contributes its rendered counterpart to the current
/// paragraph. If the two ever diverge in length, fall back to splitting the
/// rendered text on blank lines.
fn split_cell_paragraphs(source: &str, rendered: &str) -> Vec<String> {
    let source_lines: Vec<&str> = source.split('\n').collect();
    let rendered_lines: Vec<&str> = rendered.split('\n').collect();

    if source_lines.len() != rendered_lines.len() {
        return rendered
            .split("\n\n")
            .map(|p| p.trim().to_string())
            .filter(|p| !p.is_empty())
            .collect();
    }

    let mut paragraphs: Vec<String> = vec![];
    let mut current: Vec<&str> = vec![];
    for (src, rendered) in source_lines.iter().zip(rendered_lines.iter()) {
        if src.trim().is_empty() {
            if !current.is_empty() {
                paragraphs.push(current.join("\n").trim().to_string());
                current.clear();
            }
        } else {
            current.push(rendered);
        }
    }
    if !current.is_empty() {
        paragraphs.push(current.join("\n").trim().to_string());
    }

    paragraphs.retain(|p| !p.is_empty());
    paragraphs
}

fn truncate4(x: f64) -> f64 {
    (x * 10000.0).trunc() / 10000.0
}

fn round4(x: f64) -> f64 {
    (x * 10000.0).round() / 10000.0
}

/// Formats a percentage width the way Asciidoctor serializes it: whole numbers
/// have no decimal part, and fractional values keep up to four significant
/// decimal places with trailing zeros trimmed (e.g. `50`, `17.647`, `33.3334`).
fn format_pcwidth(x: f64) -> String {
    let s = format!("{x:.4}");
    let trimmed = s.trim_end_matches('0').trim_end_matches('.');
    trimmed.to_string()
}

/// The inline element a text-styled cell wraps its content in, if any.
fn style_wrapper(style: ColumnStyle) -> Option<&'static str> {
    match style {
        ColumnStyle::Strong => Some("strong"),
        ColumnStyle::Emphasis => Some("em"),
        ColumnStyle::Monospace => Some("code"),
        _ => None,
    }
}

fn frame_class(frame: Frame) -> &'static str {
    match frame {
        Frame::All => "frame-all",
        Frame::Ends => "frame-ends",
        Frame::Sides => "frame-sides",
        Frame::None => "frame-none",
    }
}

fn grid_class(grid: Grid) -> &'static str {
    match grid {
        Grid::All => "grid-all",
        Grid::Rows => "grid-rows",
        Grid::Cols => "grid-cols",
        Grid::None => "grid-none",
    }
}

fn stripes_class(stripes: Stripes) -> Option<&'static str> {
    match stripes {
        Stripes::None => None,
        Stripes::Even => Some("stripes-even"),
        Stripes::Odd => Some("stripes-odd"),
        Stripes::All => Some("stripes-all"),
        Stripes::Hover => Some("stripes-hover"),
    }
}

fn halign_class(align: HorizontalAlignment) -> &'static str {
    match align {
        HorizontalAlignment::Left => "halign-left",
        HorizontalAlignment::Center => "halign-center",
        HorizontalAlignment::Right => "halign-right",
    }
}

fn valign_class(align: VerticalAlignment) -> &'static str {
    match align {
        VerticalAlignment::Top => "valign-top",
        VerticalAlignment::Middle => "valign-middle",
        VerticalAlignment::Bottom => "valign-bottom",
    }
}

fn preamble_to_node<'a>(preamble: &'a Preamble<'a>) -> VirtualNode {
    let mut node = VirtualNode::new("div").with_id("preamble");

    for child in preamble.nested_blocks() {
        node.children.push(child.to_virtual_dom());
    }

    node
}

fn break_to_node<'a>(break_: &'a Break<'a>) -> VirtualNode {
    let context = break_.raw_context();

    match context.as_ref() {
        "thematic_break" => VirtualNode::new("hr"),
        "page_break" => VirtualNode::new("div").with_class("page-break"),
        _ => VirtualNode::new("hr"),
    }
}

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

    #[test]
    fn empty_document() {
        let doc = Parser::default().parse("");
        let vdom = doc.to_virtual_dom();

        assert_eq!(vdom.tag, "div");
        assert_eq!(vdom.classes, vec!["document"]);
        assert_eq!(vdom.children.len(), 0);
    }

    #[test]
    fn single_paragraph() {
        let doc = Parser::default().parse("Hello, world!");
        let vdom = doc.to_virtual_dom();

        assert_eq!(vdom.tag, "div");
        assert_eq!(vdom.classes, vec!["document"]);
        assert_eq!(vdom.children.len(), 1);

        // Top-level paragraphs are wrapped in div.paragraph.
        let wrapper = &vdom.children[0];
        assert_eq!(wrapper.tag, "div");
        assert!(wrapper.classes.contains(&"paragraph".to_string()));
        assert_eq!(wrapper.children.len(), 1);

        let para = &wrapper.children[0];
        assert_eq!(para.tag, "p");
        assert_eq!(para.text.as_deref(), Some("Hello, world!"));
    }

    #[test]
    fn unordered_list() {
        let doc = Parser::default().parse("* item 1\n* item 2\n* item 3");
        let vdom = doc.to_virtual_dom();

        assert_eq!(vdom.children.len(), 1);

        let wrapper = &vdom.children[0];
        assert_eq!(wrapper.tag, "div");
        assert!(wrapper.classes.contains(&"ulist".to_string()));
        assert_eq!(wrapper.children.len(), 1);

        let ul = &wrapper.children[0];
        assert_eq!(ul.tag, "ul");
        assert_eq!(ul.children.len(), 3);

        for li in &ul.children {
            assert_eq!(li.tag, "li");
        }
    }

    #[test]
    fn section_with_paragraph() {
        let doc = Parser::default().parse("== Section Title\n\nSome text.");
        let vdom = doc.to_virtual_dom();

        assert_eq!(vdom.children.len(), 1);

        let section = &vdom.children[0];
        assert_eq!(section.tag, "div");
        assert!(section.classes.contains(&"sect1".to_string()));

        // Section contains heading and paragraph wrapper.
        assert_eq!(section.children.len(), 2);
        assert_eq!(section.children[0].tag, "h2");

        // Paragraph is wrapped in div.paragraph.
        let para_wrapper = &section.children[1];
        assert_eq!(para_wrapper.tag, "div");
        assert!(para_wrapper.classes.contains(&"paragraph".to_string()));
        assert_eq!(para_wrapper.children.len(), 1);
        assert_eq!(para_wrapper.children[0].tag, "p");
    }

    #[test]
    fn ordered_list_has_arabic_class() {
        let doc = Parser::default().parse(". item 1\n. item 2\n. item 3");
        let vdom = doc.to_virtual_dom();

        assert_eq!(vdom.children.len(), 1);

        let wrapper = &vdom.children[0];
        assert_eq!(wrapper.tag, "div");
        assert!(wrapper.classes.contains(&"olist".to_string()));
        // Wrapper should also have "arabic" class for ordered lists.
        assert!(wrapper.classes.contains(&"arabic".to_string()));
        assert_eq!(wrapper.children.len(), 1);

        let ol = &wrapper.children[0];
        assert_eq!(ol.tag, "ol");
        // The <ol> element should also have "arabic" class.
        assert!(ol.classes.contains(&"arabic".to_string()));
        assert_eq!(ol.children.len(), 3);

        for li in &ol.children {
            assert_eq!(li.tag, "li");
        }
    }

    #[test]
    fn inline_html_markup_in_paragraph() {
        let doc = Parser::default().parse("I am *strong* and _emphasized_ and `code`.");
        let vdom = doc.to_virtual_dom();

        assert_eq!(vdom.children.len(), 1);

        // Top-level paragraphs are wrapped in div.paragraph.
        let wrapper = &vdom.children[0];
        assert_eq!(wrapper.tag, "div");
        assert!(wrapper.classes.contains(&"paragraph".to_string()));
        assert_eq!(wrapper.children.len(), 1);

        let para = &wrapper.children[0];
        assert_eq!(para.tag, "p");

        // Should have parsed HTML into child nodes.
        assert!(
            !para.children.is_empty(),
            "Should have child nodes from parsed HTML"
        );

        // Verify strong element.
        let strong = para.children.iter().find(|c| c.tag == "strong");
        assert!(strong.is_some(), "Should have a <strong> element");
        assert_eq!(strong.unwrap().text.as_deref(), Some("strong"));

        // Verify em element.
        let em = para.children.iter().find(|c| c.tag == "em");
        assert!(em.is_some(), "Should have an <em> element");
        assert_eq!(em.unwrap().text.as_deref(), Some("emphasized"));

        // Verify code element.
        let code = para.children.iter().find(|c| c.tag == "code");
        assert!(code.is_some(), "Should have a <code> element");
        assert_eq!(code.unwrap().text.as_deref(), Some("code"));
    }

    #[test]
    fn titled_table_renders_captioned_title() {
        let doc = Parser::default().parse(".A table with a title\n|===\n|a |b\n|===");
        let vdom = doc.to_virtual_dom();

        let table = &vdom.children[0];
        assert_eq!(table.tag, "table");

        let caption = &table.children[0];
        assert_eq!(caption.tag, "caption");
        assert!(caption.classes.contains(&"title".to_string()));
        assert_eq!(
            caption.text.as_deref(),
            Some("Table 1. A table with a title")
        );
    }

    #[test]
    fn description_list_uses_dt_and_dd_tags() {
        let doc = Parser::default().parse("term1:: definition1\nterm2:: definition2");
        let vdom = doc.to_virtual_dom();

        assert_eq!(vdom.children.len(), 1);

        let wrapper = &vdom.children[0];
        assert_eq!(wrapper.tag, "div");
        assert!(wrapper.classes.contains(&"dlist".to_string()));
        assert_eq!(wrapper.children.len(), 1);

        let dl = &wrapper.children[0];
        assert_eq!(dl.tag, "dl");
        // Should have 4 children: dt, dd, dt, dd.
        assert_eq!(dl.children.len(), 4);

        // Check first term/definition pair.
        assert_eq!(dl.children[0].tag, "dt");
        assert_eq!(dl.children[0].text.as_deref(), Some("term1"));
        assert_eq!(dl.children[1].tag, "dd");
        assert_eq!(dl.children[1].children.len(), 1);
        assert_eq!(dl.children[1].children[0].tag, "p");
        assert_eq!(
            dl.children[1].children[0].text.as_deref(),
            Some("definition1")
        );

        // Check second term/definition pair.
        assert_eq!(dl.children[2].tag, "dt");
        assert_eq!(dl.children[2].text.as_deref(), Some("term2"));
        assert_eq!(dl.children[3].tag, "dd");
        assert_eq!(dl.children[3].children.len(), 1);
        assert_eq!(dl.children[3].children[0].tag, "p");
        assert_eq!(
            dl.children[3].children[0].text.as_deref(),
            Some("definition2")
        );
    }
}