alix 0.8.0

A learning tool built for understanding, not just remembering.
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
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
use serde::{Deserialize, Serialize};

use crate::{
    card::Card,
    inline::DisplayProjector,
    parser::{BLANK, HIDDEN},
};

// Struct variants (not newtype) because serde's internal tagging can't tag
// newtype variants; wire shape is `{"kind": ..., "text": ...}` (docs/API.md).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ContentUnit {
    Sentence {
        text: String,
        runs: Vec<crate::inline::InlineRun>,
    },
    Code {
        lines: Vec<String>,
    },
    /// A frozen mermaid fence, rendered: occupies the fence's own slot in
    /// the stream. `src` is an absolute file path in the library projection;
    /// the HTTP layer rewrites it to a `/img/<key>` URL. `width`/`height`
    /// are LOGICAL pixels (the raster is 2x); `alt` carries the fence
    /// source, the accessible representation while nothing is masked.
    Diagram {
        src: String,
        width: u32,
        height: u32,
        alt: String,
        /// Overlay regions in RASTER pixel space (the PNG's own pixels, the
        /// space `naturalWidth` placement uses); absent on an unmasked
        /// diagram, so the committed 6a wire shape stands.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        regions: Vec<crate::review::RegionView>,
        /// The post-answer accessible text: asked labels revealed, sibling
        /// and cover labels still masked. Absent when nothing is masked.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        revealed_alt: Option<String>,
    },
    Checklist {
        items: Vec<ChecklistItem>,
    },
    /// A bare pipe table (one no mapping claimed), aligned per the GFM
    /// delimiter-row colons. Rows are padded or truncated to the header
    /// width for display; only the mapped-card table enforces widths.
    Table {
        aligns: Vec<CellAlign>,
        header: Vec<Vec<crate::inline::InlineRun>>,
        rows: Vec<Vec<Vec<crate::inline::InlineRun>>>,
    },
    /// A bare blockquote run: quoted content, never a note. It carries its own
    /// units so a quotation can hold prose, code, or a list, and it is one
    /// block rather than a sequence of gradeable lines.
    Quote {
        units: Vec<ContentUnit>,
    },
}

/// One step of an answer as a client walks it: a line the learner must
/// produce, or a block that reveals whole and is never typed, a quotation run
/// or a table. A block step carries its own units so a client never parses
/// quote or pipe syntax, and spans are half-open into the DISPLAYED back.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum AnswerStep {
    Line {
        back_from: usize,
        back_to: usize,
    },
    Quote {
        back_from: usize,
        back_to: usize,
        units: Vec<ContentUnit>,
    },
    /// A pipe table: one block, revealed whole and never typed, carrying the
    /// aligned table as its single unit.
    Table {
        back_from: usize,
        back_to: usize,
        units: Vec<ContentUnit>,
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CellAlign {
    None,
    Left,
    Center,
    Right,
}

fn cell_align(delimiter_cell: &str) -> CellAlign {
    let left = delimiter_cell.starts_with(':');
    let right = delimiter_cell.ends_with(':');
    match (left, right) {
        (true, true) => CellAlign::Center,
        (true, false) => CellAlign::Left,
        (false, true) => CellAlign::Right,
        (false, false) => CellAlign::None,
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChecklistItem {
    pub checked: bool,
    pub text: String,
    pub runs: Vec<crate::inline::InlineRun>,
}

pub fn checklist_items(lines: &[&str]) -> Option<Vec<ChecklistItem>> {
    let mut projector = DisplayProjector::default();
    checklist_items_with(lines, &mut projector)
}

fn checklist_items_with(
    lines: &[&str],
    projector: &mut DisplayProjector,
) -> Option<Vec<ChecklistItem>> {
    let mut items = Vec::new();
    for line in lines {
        if line.trim().is_empty() {
            continue;
        }
        let (checked, raw) = crate::parser::checklist::parse_line(line)?;
        let raw = raw.trim();
        items.push(ChecklistItem {
            checked,
            text: crate::inline::strip_inline(raw),
            runs: projector.project(raw),
        });
    }
    (!items.is_empty()).then_some(items)
}

pub fn note_views(card: &Card) -> Vec<crate::review::NoteView> {
    let mut projector = DisplayProjector::default();
    note_views_with(card, &mut projector)
}

pub(crate) fn note_views_with(
    card: &Card,
    projector: &mut DisplayProjector,
) -> Vec<crate::review::NoteView> {
    card.notes
        .iter()
        .map(|note| crate::review::NoteView {
            badge: note.badge,
            units: text_units_with(&note.body, projector, true, &card.resolved_diagrams),
        })
        .collect()
}

pub(crate) fn answer_units_with(
    lines: &[String],
    projector: &mut DisplayProjector,
    diagrams: &[crate::card::ResolvedDiagram],
) -> Vec<ContentUnit> {
    text_units_with(&lines.join("\n"), projector, false, diagrams)
}

/// The fence's own slot gets the rendered diagram when (and only when) a
/// resolved stamp fingerprints to the fence's interior; everything else
/// stays a Code unit, so an unfrozen or stale fence falls back to source
/// in place, never somewhere else.
fn fence_unit(
    info: &str,
    lines: Vec<String>,
    diagrams: &[crate::card::ResolvedDiagram],
    projector: &mut DisplayProjector,
) -> ContentUnit {
    if info.eq_ignore_ascii_case("math") && lines.iter().any(|line| !line.trim().is_empty()) {
        let source = lines.join("\n");
        return ContentUnit::Sentence {
            runs: projector.project_display_math(&source),
            text: source,
        };
    }
    if info.eq_ignore_ascii_case("mermaid") && !lines.is_empty() {
        let source = lines.join("\n");
        let print = crate::diagram::fingerprint(&source);
        if let Some(resolved) = diagrams.iter().find(|d| d.fingerprint == print) {
            return ContentUnit::Diagram {
                src: resolved.png.display().to_string(),
                width: resolved.geometry.logical_width,
                height: resolved.geometry.logical_height,
                alt: source,
                regions: Vec::new(),
                revealed_alt: None,
            };
        }
    }
    ContentUnit::Code { lines }
}

/// One flag per answer line: true when the line belongs to a block that
/// reveals whole and is never graded, a quotation or a table. Built from the
/// units, so nothing decides twice what one block is. A cloze card's back
/// lines are its hidden spans, so a span that IS `>` is exact text the
/// learner must reproduce, never authored quotation syntax.
pub(crate) fn card_block_flags(
    card: &crate::card::Card,
    space: crate::card::AnswerSpace,
) -> Vec<bool> {
    let lines = card.answer_lines(space);
    let mut flags = vec![false; lines.len()];
    if card.is_blank_card() {
        return flags;
    }
    let mut projector = DisplayProjector::default();
    for spanned in text_units_spanned(
        &lines.join("\n"),
        &mut projector,
        false,
        &card.resolved_diagrams,
    ) {
        if matches!(
            spanned.unit,
            ContentUnit::Quote { .. } | ContentUnit::Table { .. }
        ) {
            for flag in flags.iter_mut().take(spanned.to).skip(spanned.from) {
                *flag = true;
            }
        }
    }
    flags
}

/// The answer lines a check may grade: the learner's own claims, with
/// supporting blocks dropped.
pub(crate) fn gradeable_answer_lines(
    card: &crate::card::Card,
    space: crate::card::AnswerSpace,
) -> Vec<String> {
    let blocked = card_block_flags(card, space);
    card.answer_lines(space)
        .iter()
        .zip(&blocked)
        .filter(|(_, in_block)| !**in_block)
        .map(|(line, _)| line.clone())
        .collect()
}

/// The answer as a learner READS it: every line kept, a quotation's marker
/// dropped. For a surface that shows the whole answer as one string rather
/// than grading its parts, where dropping a block would show a truncated
/// answer.
pub(crate) fn readable_answer_lines(
    card: &crate::card::Card,
    space: crate::card::AnswerSpace,
) -> Vec<String> {
    let blocked = card_block_flags(card, space);
    card.answer_lines(space)
        .iter()
        .zip(&blocked)
        .map(|(line, in_block)| {
            if *in_block {
                quote_body(line).unwrap_or(line).to_string()
            } else {
                line.clone()
            }
        })
        .collect()
}

/// The steps a client walks a card's answer in, over the lines it is SHOWN.
/// The units decide the grouping, so the displayed stream, the reveal count,
/// and the typed target can never disagree about what is one block.
pub(crate) fn card_answer_steps(
    card: &crate::card::Card,
    projector: &mut DisplayProjector,
    space: crate::card::AnswerSpace,
) -> Vec<AnswerStep> {
    let lines = card.answer_lines(space);
    let line = |index: usize| AnswerStep::Line {
        back_from: index,
        back_to: index + 1,
    };
    if card.is_blank_card() {
        return (0..lines.len()).map(line).collect();
    }
    let spanned = text_units_spanned(&lines.join("\n"), projector, false, &card.resolved_diagrams);
    let mut blocks = spanned.into_iter().filter_map(|spanned| {
        let (back_from, back_to) = (spanned.from, spanned.to);
        match spanned.unit {
            ContentUnit::Quote { units } => Some(AnswerStep::Quote {
                back_from,
                back_to,
                units,
            }),
            unit @ ContentUnit::Table { .. } => Some(AnswerStep::Table {
                back_from,
                back_to,
                units: vec![unit],
            }),
            _ => None,
        }
    });
    let mut next_block = blocks.next();
    let mut steps = Vec::new();
    let mut index = 0;
    while index < lines.len() {
        match block_span(next_block.as_ref()) {
            Some((from, to)) if from == index => {
                steps.extend(next_block.take());
                next_block = blocks.next();
                index = to;
            }
            _ => {
                steps.push(line(index));
                index += 1;
            }
        }
    }
    steps
}

fn block_span(step: Option<&AnswerStep>) -> Option<(usize, usize)> {
    match step? {
        AnswerStep::Quote {
            back_from, back_to, ..
        }
        | AnswerStep::Table {
            back_from, back_to, ..
        } => Some((*back_from, *back_to)),
        AnswerStep::Line { .. } => None,
    }
}

/// A quote line's body. Only a bare `>` reaches an answer: a badge opens a
/// note, which the parser routes away from content.
pub(crate) fn quote_body(line: &str) -> Option<&str> {
    let rest = line.strip_prefix('>')?;
    Some(rest.strip_prefix(' ').unwrap_or(rest))
}

/// A unit with the half-open range of input lines it was built from.
/// Spans are recorded only so [`card_answer_steps`] can group an answer the
/// same way the units render it; they are never serialized.
struct SpannedUnit {
    unit: ContentUnit,
    from: usize,
    to: usize,
}

fn text_units_with(
    text: &str,
    projector: &mut DisplayProjector,
    split_prose_sentences: bool,
    diagrams: &[crate::card::ResolvedDiagram],
) -> Vec<ContentUnit> {
    text_units_spanned(text, projector, split_prose_sentences, diagrams)
        .into_iter()
        .map(|spanned| spanned.unit)
        .collect()
}

/// With `split_prose_sentences` set, one prose run can yield several units,
/// and they share that run's span; the answer path, the only caller that
/// reads spans, passes false.
fn text_units_spanned(
    text: &str,
    projector: &mut DisplayProjector,
    split_prose_sentences: bool,
    diagrams: &[crate::card::ResolvedDiagram],
) -> Vec<SpannedUnit> {
    let mut units: Vec<ContentUnit> = Vec::new();
    let mut spans: Vec<(usize, usize)> = Vec::new();
    let mut code_fence: Option<(char, usize, String)> = None;
    let mut code: Vec<String> = Vec::new();
    let mut code_from = 0;
    let mut math_block: Option<Vec<String>> = None;
    let mut math_from = 0;
    let mut prose = String::new();
    let mut prose_from = 0;
    let mut checklist = Vec::new();
    let mut checklist_from = 0;

    let lines: Vec<&str> = text.lines().collect();
    let mut index = 0;
    while index < lines.len() {
        let logical = lines[index];
        let start = index;
        index += 1;
        // Whichever block opened first owns the other's marker until it
        // closes, which is the parser's own precedence: a `$$` inside a fence
        // is code, and a fence marker inside a `$$` block is math source.
        if let Some((marker, run)) = fence_marker(logical)
            && (code_fence.is_some() || math_block.is_none())
        {
            match &code_fence {
                Some((open_marker, open_run, info))
                    if crate::parser::closes_fence(
                        logical.trim_start(),
                        *open_marker,
                        *open_run,
                    ) =>
                {
                    // An empty fence keeps its unit slot: clients consume one
                    // fence-shaped unit per closed raw fence.
                    let block = std::mem::take(&mut code);
                    units.push(fence_unit(info, block, diagrams, projector));
                    spans.push((code_from, index));
                    code_fence = None;
                }
                None => {
                    flush_checklist(
                        &mut checklist,
                        &mut units,
                        &mut spans,
                        checklist_from,
                        start,
                    );
                    flush_prose(
                        &mut prose,
                        &mut units,
                        &mut spans,
                        prose_from,
                        start,
                        projector,
                        split_prose_sentences,
                    );
                    let info = fence_info(logical, marker);
                    code_fence = Some((marker, run, info.to_string()));
                    code_from = start;
                    code.clear();
                }
                Some(_) => {
                    code.push(logical.to_string());
                }
            }
            continue;
        }
        if code_fence.is_some() {
            code.push(logical.to_string());
            continue;
        }
        if let Some(body) = math_block.as_mut() {
            if logical.trim() == "$$" {
                let source = std::mem::take(body).join("\n");
                math_block = None;
                if !source.trim().is_empty() {
                    units.push(ContentUnit::Sentence {
                        runs: projector.project_display_math(&source),
                        text: source,
                    });
                    spans.push((math_from, index));
                }
            } else {
                body.push(logical.to_string());
            }
            continue;
        }
        if logical.trim() == "$$" {
            flush_checklist(
                &mut checklist,
                &mut units,
                &mut spans,
                checklist_from,
                start,
            );
            flush_prose(
                &mut prose,
                &mut units,
                &mut spans,
                prose_from,
                start,
                projector,
                split_prose_sentences,
            );
            math_block = Some(Vec::new());
            math_from = start;
            continue;
        }
        if logical.starts_with('|')
            && lines
                .get(index)
                .is_some_and(|next| crate::parser::is_delimiter_row(next))
            && let Some(header) = crate::parser::split_cells(logical)
            && let Some(delimiter) = crate::parser::split_cells(lines[index])
            && delimiter.len() == header.len()
        {
            flush_checklist(
                &mut checklist,
                &mut units,
                &mut spans,
                checklist_from,
                start,
            );
            flush_prose(
                &mut prose,
                &mut units,
                &mut spans,
                prose_from,
                start,
                projector,
                split_prose_sentences,
            );
            let aligns = delimiter.iter().map(|cell| cell_align(cell)).collect();
            index += 1;
            let mut rows = Vec::new();
            while let Some(cells) = lines
                .get(index)
                .filter(|line| line.starts_with('|'))
                .and_then(|line| crate::parser::split_cells(line))
            {
                let mut cells = cells;
                cells.resize(header.len(), String::new());
                rows.push(
                    cells
                        .iter()
                        .map(|cell| projector.project(cell))
                        .collect::<Vec<_>>(),
                );
                index += 1;
            }
            units.push(ContentUnit::Table {
                aligns,
                header: header.iter().map(|cell| projector.project(cell)).collect(),
                rows,
            });
            spans.push((start, index));
            continue;
        }
        if let Some(first) = quote_body(logical) {
            flush_checklist(
                &mut checklist,
                &mut units,
                &mut spans,
                checklist_from,
                start,
            );
            flush_prose(
                &mut prose,
                &mut units,
                &mut spans,
                prose_from,
                start,
                projector,
                split_prose_sentences,
            );
            let mut body = vec![first.to_string()];
            while let Some(next) = lines.get(index).and_then(|line| quote_body(line)) {
                body.push(next.to_string());
                index += 1;
            }
            units.push(ContentUnit::Quote {
                units: text_units_with(
                    &body.join("\n"),
                    projector,
                    split_prose_sentences,
                    diagrams,
                ),
            });
            spans.push((start, index));
            continue;
        }
        let trimmed = logical.trim();
        if trimmed.is_empty() {
            flush_checklist(
                &mut checklist,
                &mut units,
                &mut spans,
                checklist_from,
                start,
            );
            continue;
        }
        if let Some(mut items) = checklist_items_with(&[logical], projector) {
            flush_prose(
                &mut prose,
                &mut units,
                &mut spans,
                prose_from,
                start,
                projector,
                split_prose_sentences,
            );
            if checklist.is_empty() {
                checklist_from = start;
            }
            checklist.append(&mut items);
            continue;
        }
        if crate::inline::is_display_math_line(trimmed) {
            flush_checklist(
                &mut checklist,
                &mut units,
                &mut spans,
                checklist_from,
                start,
            );
            flush_prose(
                &mut prose,
                &mut units,
                &mut spans,
                prose_from,
                start,
                projector,
                split_prose_sentences,
            );
            units.push(ContentUnit::Sentence {
                text: trimmed.to_string(),
                runs: projector.project(trimmed),
            });
            spans.push((start, index));
            continue;
        }
        flush_checklist(
            &mut checklist,
            &mut units,
            &mut spans,
            checklist_from,
            start,
        );
        if prose.is_empty() {
            prose_from = start;
        } else {
            prose.push(' ');
        }
        prose.push_str(trimmed);
    }

    let end = lines.len();
    flush_checklist(&mut checklist, &mut units, &mut spans, checklist_from, end);
    flush_prose(
        &mut prose,
        &mut units,
        &mut spans,
        prose_from,
        end,
        projector,
        split_prose_sentences,
    );
    // The parser rejects an unclosed card `$$`, so this tail only fires on
    // free text: the gathered lines degrade to a code block, like the
    // unterminated fence below.
    if let Some(body) = math_block.take()
        && !body.is_empty()
    {
        units.push(ContentUnit::Code { lines: body });
        spans.push((math_from, end));
    }
    // An unterminated code fence still yields its gathered lines.
    if !code.is_empty() {
        let info = code_fence.map(|(_, _, info)| info).unwrap_or_default();
        units.push(fence_unit(&info, code, diagrams, projector));
        spans.push((code_from, end));
    }
    units
        .into_iter()
        .zip(spans)
        .map(|(unit, (from, to))| SpannedUnit { unit, from, to })
        .collect()
}

pub fn front_units(front: &str) -> Option<Vec<ContentUnit>> {
    let mut projector = DisplayProjector::default();
    front_units_with(front, &mut projector, &[])
}

pub(crate) fn front_units_with(
    front: &str,
    projector: &mut DisplayProjector,
    diagrams: &[crate::card::ResolvedDiagram],
) -> Option<Vec<ContentUnit>> {
    let units = text_units_with(front, projector, true, diagrams);
    units
        .iter()
        .any(|unit| match unit {
            ContentUnit::Checklist { .. } | ContentUnit::Table { .. } => true,
            ContentUnit::Sentence { runs, .. } => runs
                .iter()
                .any(|run| run.math.as_ref().is_some_and(|math| math.display)),
            ContentUnit::Code { .. } | ContentUnit::Diagram { .. } | ContentUnit::Quote { .. } => {
                true
            }
        })
        .then_some(units)
}

/// The structural units of a card's context, in source order. Context
/// renders prose line-by-line on every client, so this stream carries only
/// raw fences and closed nonempty bare-math blocks. The
/// context text is MASKED, so a mermaid fence resolves through its parse
/// record's unmasked fingerprint, never through the displayed text; a
/// record carrying spans or holes stays code until span binding ships.
/// A math fence needs no record: its displayed (masked) body projects
/// directly.
pub(crate) fn context_units_with(card: &Card) -> Vec<ContentUnit> {
    let context = &card.context;
    let diagrams = &card.resolved_diagrams;
    let fences = &card.answer_fences;
    let mut projector = DisplayProjector::default();
    let mut records = fences.iter();
    structural_units_with(context, &mut projector, |info, lines, projector| {
        if info.eq_ignore_ascii_case("math") && lines.iter().any(|line| !line.trim().is_empty()) {
            let source = lines.join("\n");
            ContentUnit::Sentence {
                runs: projector.project_display_math(&source),
                text: source,
            }
        } else {
            let mermaid = info.eq_ignore_ascii_case("mermaid");
            let record = if mermaid { records.next() } else { None };
            context_fence_unit(card, mermaid, lines, record, diagrams)
        }
    })
}

fn structural_units_with(
    lines: &[String],
    projector: &mut DisplayProjector,
    mut fence_unit: impl FnMut(&str, Vec<String>, &mut DisplayProjector) -> ContentUnit,
) -> Vec<ContentUnit> {
    let mut units = Vec::new();
    let mut open: Option<(char, usize, String)> = None;
    let mut interior: Vec<String> = Vec::new();
    let mut math_block: Option<Vec<String>> = None;
    for line in lines {
        if let Some(body) = math_block.as_mut() {
            if line.trim() == "$$" {
                let source = std::mem::take(body).join("\n");
                math_block = None;
                if !source.trim().is_empty() {
                    units.push(ContentUnit::Sentence {
                        runs: projector.project_display_math(&source),
                        text: source,
                    });
                }
            } else {
                body.push(line.clone());
            }
            continue;
        }
        match (open.as_ref(), fence_marker(line)) {
            (Some((ch, len, _)), Some(_))
                if crate::parser::closes_fence(line.trim_start(), *ch, *len) =>
            {
                let (_, _, info) = open.take().expect("matched Some above");
                units.push(fence_unit(&info, std::mem::take(&mut interior), projector));
            }
            (Some(_), _) => interior.push(line.clone()),
            (None, Some((marker, run))) => {
                open = Some((marker, run, fence_info(line, marker).to_string()));
            }
            (None, None) if line.trim() == "$$" => math_block = Some(Vec::new()),
            (None, None) => {}
        }
    }
    if !interior.is_empty() {
        units.push(ContentUnit::Code { lines: interior });
    }
    units
}

/// Section prose is never a diagram: nothing freezes a section's fence, so
/// there is no record to resolve a mermaid body against and it stays code.
/// Math fences and closed nonempty bare-math blocks need no record.
pub(crate) fn section_units(lines: &[String]) -> Vec<ContentUnit> {
    let mut projector = DisplayProjector::default();
    structural_units_with(lines, &mut projector, |info, lines, projector| {
        fence_unit(info, lines, &[], projector)
    })
}

fn context_fence_unit(
    card: &Card,
    mermaid: bool,
    lines: Vec<String>,
    record: Option<&crate::card::AnswerFence>,
    diagrams: &[crate::card::ResolvedDiagram],
) -> ContentUnit {
    if mermaid
        && let Some(record) = record
        && let Some(resolved) = diagrams
            .iter()
            .find(|d| d.fingerprint == record.fingerprint)
    {
        if record.spans.is_empty() {
            return ContentUnit::Diagram {
                src: resolved.png.display().to_string(),
                width: resolved.geometry.logical_width,
                height: resolved.geometry.logical_height,
                // The record's interior, not the displayed lines: the
                // authored source is what was frozen and rendered.
                alt: record.interior.to_string(),
                regions: Vec::new(),
                revealed_alt: None,
            };
        }
        if let Some(unit) = masked_diagram_unit(card, record, resolved) {
            return unit;
        }
    }
    ContentUnit::Code { lines }
}

/// The masked projection: every span in the fence must validate and bind
/// (complete-label-only), or the whole fence stays the masked-source code
/// unit for this card; a partial diagram would mask the wrong thing.
fn masked_diagram_unit(
    card: &Card,
    record: &crate::card::AnswerFence,
    resolved: &crate::card::ResolvedDiagram,
) -> Option<ContentUnit> {
    use crate::{
        parser::region::RegionKind,
        review::{RegionRole, RegionView},
    };

    let geometry = &resolved.geometry;
    crate::diagram::validate_label_sources(geometry, &record.interior).ok()?;
    let asked: Vec<usize> = match &card.region {
        None => Vec::new(),
        Some(crate::card::RegionSlot::Single { line, .. }) => vec![*line],
        Some(crate::card::RegionSlot::Group { members, .. }) => {
            members.iter().map(|member| member.line).collect()
        }
    };
    let covers_reveal = crate::review::covers_reveal(card);
    // label index -> (role, reveal) for every bound span; a label bound
    // twice cannot happen (spans never overlap, ranges never overlap).
    let mut bound: Vec<(usize, RegionRole, bool)> = Vec::new();
    for span in &record.spans {
        let index = crate::diagram::bind_span(geometry, span.line, span.start, span.end).ok()?;
        let kind = card
            .span_regions
            .iter()
            .find(|region| region.line == span.line)
            .map(|region| region.kind)?;
        let (role, reveal) = match kind {
            RegionKind::Cover => (RegionRole::Cover, covers_reveal),
            RegionKind::Blank if asked.contains(&span.line) => (RegionRole::Asked, true),
            RegionKind::Blank => (RegionRole::Mask, false),
        };
        bound.push((index, role, reveal));
    }
    let masked = |index: usize| bound.iter().any(|(bound_index, ..)| *bound_index == index);
    let revealed = |index: usize| {
        bound
            .iter()
            .any(|(bound_index, role, _)| *bound_index == index && *role == RegionRole::Asked)
    };
    // The accessible text is the RENDERED label inventory in reading order
    // (box y, then x), never the source: source ids can spell out a masked
    // label's text.
    let mut order: Vec<usize> = (0..geometry.labels.len()).collect();
    order.sort_by_key(|&index| {
        let bounds = &geometry.labels[index].bounds;
        (bounds.y, bounds.x)
    });
    let inventory = |shows: &dyn Fn(usize) -> bool| {
        let entries: Vec<&str> = order
            .iter()
            .map(|&index| {
                if shows(index) {
                    geometry.labels[index].text.as_str()
                } else {
                    "…"
                }
            })
            .collect();
        format!("diagram labels: {}", entries.join(", "))
    };
    let regions = bound
        .iter()
        .map(|&(index, role, reveal_on_answer)| {
            let bounds = &geometry.labels[index].bounds;
            RegionView {
                role,
                reveal_on_answer,
                x: f64::from(bounds.x),
                y: f64::from(bounds.y),
                width: f64::from(bounds.width),
                height: f64::from(bounds.height),
                unit: "px".to_string(),
            }
        })
        .collect();
    Some(ContentUnit::Diagram {
        src: resolved.png.display().to_string(),
        width: geometry.logical_width,
        height: geometry.logical_height,
        alt: inventory(&|index| !masked(index)),
        regions,
        revealed_alt: Some(inventory(&|index| !masked(index) || revealed(index))),
    })
}

pub(crate) fn fence_marker(line: &str) -> Option<(char, usize)> {
    let trimmed = line.trim_start();
    let ch = if trimmed.starts_with("```") {
        '`'
    } else if trimmed.starts_with("~~~") {
        '~'
    } else {
        return None;
    };
    Some((ch, trimmed.chars().take_while(|c| *c == ch).count()))
}

pub(crate) fn fence_info(line: &str, marker: char) -> &str {
    line.trim_start().trim_start_matches(marker).trim()
}

fn flush_checklist(
    checklist: &mut Vec<ChecklistItem>,
    units: &mut Vec<ContentUnit>,
    spans: &mut Vec<(usize, usize)>,
    from: usize,
    to: usize,
) {
    if !checklist.is_empty() {
        units.push(ContentUnit::Checklist {
            items: std::mem::take(checklist),
        });
        spans.push((from, to));
    }
}

fn flush_prose(
    prose: &mut String,
    units: &mut Vec<ContentUnit>,
    spans: &mut Vec<(usize, usize)>,
    from: usize,
    to: usize,
    projector: &mut DisplayProjector,
    split_prose_sentences: bool,
) {
    let chunks = if split_prose_sentences {
        split_sentences(prose)
    } else if prose.trim().is_empty() {
        Vec::new()
    } else {
        vec![prose.trim().to_string()]
    };
    for sentence in chunks {
        if !sentence.is_empty() {
            let runs = projector.project(&sentence);
            units.push(ContentUnit::Sentence {
                text: sentence,
                runs,
            });
            spans.push((from, to));
        }
    }
    prose.clear();
}

pub fn split_sentences(text: &str) -> Vec<String> {
    let chars: Vec<char> = text.chars().collect();
    let mut sentences = Vec::new();
    let mut start = 0;
    for i in 0..chars.len() {
        let ends_sentence = chars[i] == '.' && chars.get(i + 1).is_none_or(|c| c.is_whitespace());
        if ends_sentence {
            let sentence: String = chars[start..=i].iter().collect();
            if !sentence.trim().is_empty() {
                sentences.push(sentence.trim().to_string());
            }
            start = i + 1;
        }
    }
    let tail: String = chars[start..].iter().collect();
    if !tail.trim().is_empty() {
        sentences.push(tail.trim().to_string());
    }
    sentences
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ContextSpan {
    Text(String),
    Blank(String),
    Hidden(String),
}

pub fn context_spans(line: &str) -> Vec<ContextSpan> {
    let mut spans = Vec::new();
    let mut rest = line;
    while !rest.is_empty() {
        let blank = rest.find(BLANK);
        let hidden = rest.find(HIDDEN);
        let (pos, marker, is_blank) = match (blank, hidden) {
            (None, None) => {
                spans.push(ContextSpan::Text(rest.to_string()));
                break;
            }
            (Some(b), None) => (b, BLANK, true),
            (None, Some(h)) => (h, HIDDEN, false),
            (Some(b), Some(h)) if b <= h => (b, BLANK, true),
            (Some(_), Some(h)) => (h, HIDDEN, false),
        };
        if pos > 0 {
            spans.push(ContextSpan::Text(rest[..pos].to_string()));
        }
        let seg = marker.to_string();
        spans.push(if is_blank {
            ContextSpan::Blank(seg)
        } else {
            ContextSpan::Hidden(seg)
        });
        rest = &rest[pos + marker.len()..];
    }
    spans
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::card::AnswerSpace;

    fn note_units(card: &Card) -> Vec<ContentUnit> {
        note_views(card)
            .into_iter()
            .next()
            .map(|note| note.units)
            .unwrap_or_default()
    }

    fn card_with_note(note: &str) -> Card {
        Card::plain(
            Arc::from("s.txt"),
            "front".to_string(),
            vec!["back".to_string()],
            vec![crate::card::Note::bare(note.to_string())],
            1,
        )
    }

    fn sentence(text: &str) -> ContentUnit {
        ContentUnit::Sentence {
            text: text.into(),
            runs: crate::inline::parse_inline(text),
        }
    }

    #[test]
    fn a_bare_blockquote_run_is_one_quote_unit_carrying_its_own_units() {
        let mut projector = DisplayProjector::default();
        let lines = vec![
            "the answer".to_string(),
            "> a quoted passage".to_string(),
            "> its second line".to_string(),
        ];

        assert_eq!(
            vec![
                sentence("the answer"),
                ContentUnit::Quote {
                    units: vec![sentence("a quoted passage its second line")],
                },
            ],
            answer_units_with(&lines, &mut projector, &[]),
            "the run is one block, the marker never renders, and the quote's own \
             prose joins as prose does anywhere else"
        );
    }

    /// The typed target reads the block flags and the display reads the
    /// units. They are built from one scan, and this pins that they stay so.
    #[test]
    fn the_typed_target_and_the_display_agree_on_what_one_block_is() {
        let rows: Vec<(Vec<&str>, bool, &str)> = vec![
            (vec!["plain"], false, "no block at all"),
            (vec!["a", "> q"], true, "a bare quote run after prose"),
            (vec!["> q", "> r"], true, "a quote run of two lines"),
            (
                vec!["| a | b |", "| --- | --- |", "| 1 | 2 |"],
                true,
                "a table is a block too",
            ),
            (
                vec!["```text", "> q", "```"],
                false,
                "a fence's interior is source",
            ),
            (
                vec!["```text", "| a | b |", "| --- | --- |", "```"],
                false,
                "a fenced table is source",
            ),
            (vec!["$$", "> q", "$$"], false, "display math is source"),
        ];
        for (lines, expected, why) in rows {
            let owned: Vec<String> = lines.iter().map(|line| line.to_string()).collect();
            let mut projector = DisplayProjector::default();
            let units = answer_units_with(&owned, &mut projector, &[]);
            let has_block_unit = units
                .iter()
                .any(|unit| matches!(unit, ContentUnit::Quote { .. } | ContentUnit::Table { .. }));
            let card = parsed(&owned.join("\n"));
            let flagged = card_block_flags(&card, crate::card::AnswerSpace::Authored)
                .iter()
                .any(|blocked| *blocked);
            assert_eq!(expected, has_block_unit, "{why}: display units");
            assert_eq!(
                expected, flagged,
                "{why}: the typed target reads the same lines"
            );
        }
    }

    fn parsed(back: &str) -> Card {
        crate::parser::parse_str("t.md", &format!("## q\n{back}\n"))
            .unwrap()
            .remove(0)
    }

    type Span = (&'static str, usize, usize);

    fn spans(steps: &[AnswerStep]) -> Vec<Span> {
        steps
            .iter()
            .map(|step| match step {
                AnswerStep::Line { back_from, back_to } => ("line", *back_from, *back_to),
                AnswerStep::Quote {
                    back_from, back_to, ..
                } => ("quote", *back_from, *back_to),
                AnswerStep::Table {
                    back_from, back_to, ..
                } => ("table", *back_from, *back_to),
            })
            .collect()
    }

    type StepRow = (&'static str, Vec<Span>, &'static str);

    fn step_rows() -> Vec<StepRow> {
        vec![
            ("plain", vec![("line", 0, 1)], "no quotation at all"),
            (
                "a\n> q",
                vec![("line", 0, 1), ("quote", 1, 2)],
                "a quotation last",
            ),
            (
                "> q\n> r\nb",
                vec![("quote", 0, 2), ("line", 2, 3)],
                "a quotation first, spanning two lines",
            ),
            (
                "a\n> q\n> r\nb",
                vec![("line", 0, 1), ("quote", 1, 3), ("line", 3, 4)],
                "a quotation between prose",
            ),
            (
                "a\n> q\nb\n> r",
                vec![
                    ("line", 0, 1),
                    ("quote", 1, 2),
                    ("line", 2, 3),
                    ("quote", 3, 4),
                ],
                "two quotations do not merge across the prose between them",
            ),
            (
                "```text\n> q\n```",
                vec![("line", 0, 1), ("line", 1, 2), ("line", 2, 3)],
                "a fence's interior is source, never quotation",
            ),
        ]
    }

    #[test]
    fn a_quotation_run_is_one_step_wherever_it_sits() {
        for (back, expected, why) in step_rows() {
            let card = parsed(back);
            let mut projector = DisplayProjector::default();
            assert_eq!(
                expected,
                spans(&card_answer_steps(
                    &card,
                    &mut projector,
                    AnswerSpace::Displayed
                )),
                "{why}"
            );
        }
    }

    #[test]
    fn every_unit_span_is_ordered_in_bounds_and_never_overlaps() {
        let cases = [
            "just prose",
            "one\ntwo",
            "| a | b |\n| --- | --- |\n| 1 | 2 |",
            "lead in\n| a | b |\n| --- | --- |\n| 1 | 2 |\ntrail",
            "> quoted\n> still quoted\nplain after",
            "```\n| not | a table |\n```",
            "- [x] one\n- [ ] two",
            "$$\nx = 1\n$$",
            "",
        ];
        for text in cases {
            let mut projector = DisplayProjector::default();
            let spanned = text_units_spanned(text, &mut projector, false, &[]);
            let line_count = text.lines().count();
            let mut previous_end = 0;
            for unit in &spanned {
                assert!(
                    unit.from < unit.to,
                    "an empty span claims no line: {text:?} {:?}..{:?}",
                    unit.from,
                    unit.to
                );
                assert!(
                    unit.from >= previous_end,
                    "spans must not overlap or go backwards in {text:?}: {:?} after end {previous_end}",
                    unit.from
                );
                assert!(
                    unit.to <= line_count,
                    "a span must stay inside the input in {text:?}: {:?} > {line_count}",
                    unit.to
                );
                previous_end = unit.to;
            }
        }
    }

    // Every arrangement of a small line alphabet up to four lines, over the
    // domain the span consumers actually read: a block unit in an answer a
    // deck can hold. The parser is the gate rather than a hand-written
    // filter. Code and math spans are deliberately out of scope, and
    // {#renderer-math-fence-precedence} says why.
    #[test]
    fn a_block_unit_is_rebuildable_from_exactly_the_lines_its_span_claims() {
        const ALPHABET: [&str; 10] = [
            "prose",
            "more prose",
            "",
            "> quoted",
            "| a | b |",
            "| --- | --- |",
            "| 1 | 2 |",
            "```",
            "$$",
            "- [x] item",
        ];
        let mut cases: Vec<Vec<&str>> = vec![Vec::new()];
        let mut checked = 0usize;
        for _ in 0..4 {
            let mut next = Vec::new();
            for case in &cases {
                for line in ALPHABET {
                    let mut longer = case.clone();
                    longer.push(line);
                    next.push(longer);
                }
            }
            for case in &next {
                let text = case.join("\n");
                if crate::parser::parse_str("t.md", &format!("## q\n{text}\n")).is_err() {
                    continue;
                }
                let lines: Vec<&str> = text.lines().collect();
                let mut projector = DisplayProjector::default();
                for spanned in text_units_spanned(&text, &mut projector, false, &[])
                    .into_iter()
                    .filter(|spanned| {
                        matches!(
                            spanned.unit,
                            ContentUnit::Quote { .. } | ContentUnit::Table { .. }
                        )
                    })
                {
                    // The trailing newline keeps a span that ends on a blank
                    // line: `"a\n".lines()` drops it, `"a\n\n".lines()` does not.
                    let slice = format!("{}\n", lines[spanned.from..spanned.to].join("\n"));
                    let mut alone = DisplayProjector::default();
                    let rebuilt = text_units_spanned(&slice, &mut alone, false, &[]);
                    assert_eq!(
                        1,
                        rebuilt.len(),
                        "{text:?}: lines {}..{} claim one unit, alone they build {}",
                        spanned.from,
                        spanned.to,
                        rebuilt.len()
                    );
                    assert_eq!(
                        spanned.unit, rebuilt[0].unit,
                        "{text:?}: the unit spanning {}..{} is not what those lines build alone",
                        spanned.from, spanned.to
                    );
                    checked += 1;
                }
            }
            cases = next;
        }
        assert!(
            checked > 400,
            "the sweep checked only {checked} block spans"
        );
    }

    #[test]
    fn an_accepted_math_block_keeps_a_fence_marker_as_math_source() {
        let card = parsed("$$\nx + 1\n```\n$$");
        assert_eq!(
            ["$$", "x + 1", "```", "$$"],
            card.back_for_display(),
            "the parser accepts and preserves the complete display-math block"
        );

        let mut projector = DisplayProjector::default();
        let units = answer_units_with(card.back_for_display(), &mut projector, &[]);
        assert_eq!(
            1,
            units.len(),
            "one accepted math block is one rendered unit"
        );
        let ContentUnit::Sentence { text, runs } = &units[0] else {
            panic!("accepted display math must not degrade to code: {units:?}");
        };
        assert_eq!("x + 1\n```", text);
        assert_eq!(1, runs.len());
        assert!(runs[0].math.as_ref().is_some_and(|math| math.display));
    }

    #[test]
    fn a_table_run_is_one_span_over_its_header_delimiter_and_rows() {
        let mut projector = DisplayProjector::default();
        let spanned = text_units_spanned(
            "lead in\n| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |\ntrail",
            &mut projector,
            false,
            &[],
        );
        let table: Vec<_> = spanned
            .iter()
            .filter(|unit| matches!(unit.unit, ContentUnit::Table { .. }))
            .collect();
        assert_eq!(1, table.len(), "one table, one unit");
        assert_eq!(
            (1, 5),
            (table[0].from, table[0].to),
            "the span covers header, delimiter, and both rows, and nothing else"
        );
    }

    #[test]
    fn answer_steps_cover_the_displayed_back_exactly_once() {
        for (back, _, why) in step_rows() {
            let card = parsed(back);
            let mut projector = DisplayProjector::default();
            let steps = card_answer_steps(&card, &mut projector, AnswerSpace::Displayed);
            let mut next = 0;
            for (kind, from, to) in spans(&steps) {
                assert_eq!(next, from, "{why}: {kind} starts where the last step ended");
                assert!(from < to, "{why}: {kind} spans at least one line");
                next = to;
            }
            assert_eq!(
                card.back_for_display().len(),
                next,
                "{why}: the steps reach the end of the displayed back"
            );
        }
    }

    #[test]
    fn a_quote_step_carries_the_quotation_units_not_its_marker_lines() {
        let card = parsed("the answer\n> a quoted passage\n> its second line");
        let mut projector = DisplayProjector::default();
        let steps = card_answer_steps(&card, &mut projector, AnswerSpace::Displayed);

        assert_eq!(
            vec![
                AnswerStep::Line {
                    back_from: 0,
                    back_to: 1
                },
                AnswerStep::Quote {
                    back_from: 1,
                    back_to: 3,
                    units: vec![sentence("a quoted passage its second line")],
                },
            ],
            steps,
            "the marker never reaches a client, and the run joins as prose does"
        );
    }

    #[test]
    fn a_blank_span_that_is_a_greater_than_sign_is_a_gradeable_line() {
        let card = parsed("left > right\n<!-- blank: span hidden=\">\" boundary=char b:a1b2c3 -->");
        assert!(card.is_blank_card(), "the fixture is a blank card");
        let mut projector = DisplayProjector::default();

        assert_eq!(
            vec![("line", 0, 1)],
            spans(&card_answer_steps(
                &card,
                &mut projector,
                AnswerSpace::Displayed
            )),
            "a hidden span is exact text to reproduce, never quotation syntax"
        );
    }

    #[test]
    fn answer_steps_follow_the_displayed_back_when_a_reshape_replaced_it() {
        let mut card = parsed("one authored line");
        card.display_back = Some(vec![
            "reshaped prose".to_string(),
            "> a quotation the author never wrote".to_string(),
        ]);
        let mut projector = DisplayProjector::default();

        assert_eq!(
            vec![("line", 0, 1), ("quote", 1, 2)],
            spans(&card_answer_steps(
                &card,
                &mut projector,
                AnswerSpace::Displayed
            )),
            "a reshape replaces the answer on every surface, so it decides the steps"
        );
    }

    #[test]
    fn no_note_yields_no_units() {
        let card = Card::plain(
            Arc::from("s.txt"),
            "f".into(),
            vec!["b".into()],
            Vec::new(),
            1,
        );
        assert!(note_units(&card).is_empty());
    }

    #[test]
    fn checklist_items_preserve_the_authored_state_and_text() {
        assert_eq!(
            Some(vec![ChecklistItem {
                checked: true,
                text: "keep this".into(),
                runs: crate::inline::parse_inline("keep this"),
            }]),
            checklist_items(&["- [x] keep this"])
        );
    }

    #[test]
    fn prose_splits_into_sentences() {
        let units = note_units(&card_with_note("First one. Second one."));
        assert_eq!(units, vec![sentence("First one."), sentence("Second one.")]);
    }

    #[test]
    fn hard_wrapped_prose_joins_before_splitting() {
        let units = note_units(&card_with_note("A sentence spread\nacross two lines."));
        assert_eq!(units, vec![sentence("A sentence spread across two lines.")]);
    }

    #[test]
    fn ordinary_answer_units_join_authored_soft_wraps() {
        let mut projector = DisplayProjector::default();
        let lines = vec![
            "`state::open_store` loads the initialized deck, requires its".to_string(),
            "stable deck ID, and opens the document.".to_string(),
        ];
        assert_eq!(
            answer_units_with(&lines, &mut projector, &[]),
            vec![sentence(
                "`state::open_store` loads the initialized deck, requires its stable deck ID, and opens the document."
            )]
        );
    }

    #[test]
    fn display_math_line_flushes_surrounding_prose() {
        let units = note_units(&card_with_note("Before.\n$$x^2$$\nAfter."));
        assert_eq!(units.len(), 3);
        assert_eq!(units[0], sentence("Before."));
        let ContentUnit::Sentence { text, runs } = &units[1] else {
            panic!("display math should be a sentence unit");
        };
        assert_eq!(text, "$$x^2$$");
        assert_eq!(runs.len(), 1);
        assert!(runs[0].math.as_ref().unwrap().display);
        assert_eq!(units[2], sentence("After."));
    }

    #[test]
    fn display_math_makes_front_units_structural() {
        let units = front_units("Before\n$$x^2$$\nAfter").unwrap();
        assert_eq!(units.len(), 3);
        let ContentUnit::Sentence { runs, .. } = &units[1] else {
            panic!("display math should be a sentence unit");
        };
        assert!(runs[0].math.as_ref().unwrap().display);
    }

    #[test]
    fn a_multi_line_dollar_block_is_one_display_math_unit() {
        let units = note_units(&card_with_note("Before.\n$$\nx^2 +\ny^2\n$$\nAfter."));
        assert_eq!(units.len(), 3, "{units:?}");
        let ContentUnit::Sentence { text, runs } = &units[1] else {
            panic!("a dollar block should be a sentence unit: {units:?}");
        };
        assert_eq!(text, "x^2 +\ny^2", "the body joins, markers drop");
        assert_eq!(runs.len(), 1);
        let math = runs[0].math.as_ref().unwrap();
        assert!(math.display);
        assert!(
            math.svg
                .as_deref()
                .is_some_and(|svg| svg.starts_with("<svg"))
        );
        assert_eq!(units[2], sentence("After."));
    }

    #[test]
    fn a_multi_line_dollar_body_stays_inert_to_card_markup() {
        let deck = crate::parser::parse(
            "math",
            "## Why is the square positive?\n$$\nx^2\n\n> 0\n$$\n",
        )
        .unwrap();
        let card = &deck.cards[0];
        let mut projector = DisplayProjector::default();
        let units = answer_units_with(&card.back, &mut projector, &[]);
        let [ContentUnit::Sentence { text, runs }] = units.as_slice() else {
            panic!("the complete formula must stay one display unit: {units:?}");
        };
        assert_eq!(
            text, "x^2\n\n> 0",
            "blank and greater-than lines are verbatim math source"
        );
        assert!(runs[0].math.as_ref().is_some_and(|math| math.display));
        assert_eq!(
            card.only_note(),
            None,
            "a greater-than line inside display math must not become a card note"
        );
    }

    #[test]
    fn an_empty_dollar_pair_emits_no_unit() {
        let units = note_units(&card_with_note("Before.\n$$\n$$\nAfter."));
        assert_eq!(
            units,
            vec![sentence("Before."), sentence("After.")],
            "two markers with no content show nothing"
        );
    }

    #[test]
    fn a_dollar_line_inside_a_fence_stays_code() {
        let units = note_units(&card_with_note("```\n$$\nx^2\n$$\n```"));
        assert_eq!(
            units,
            vec![ContentUnit::Code {
                lines: vec!["$$".into(), "x^2".into(), "$$".into()]
            }]
        );
    }

    #[test]
    fn an_unterminated_dollar_block_in_free_text_degrades_to_code() {
        let units = note_units(&card_with_note("$$\nx^2"));
        assert_eq!(
            units,
            vec![ContentUnit::Code {
                lines: vec!["x^2".into()]
            }],
            "only free text can reach this: the parser rejects an unclosed card opener"
        );
    }

    #[test]
    fn a_math_fence_is_one_display_math_unit() {
        let units = note_units(&card_with_note(
            "Before.\n```math\nx^2 + y^2\n= z^2\n```\nAfter.",
        ));
        assert_eq!(units.len(), 3, "{units:?}");
        let ContentUnit::Sentence { text, runs } = &units[1] else {
            panic!("a math fence should be a sentence unit: {units:?}");
        };
        assert_eq!(text, "x^2 + y^2\n= z^2", "the body joins as one source");
        assert_eq!(runs.len(), 1);
        let math = runs[0].math.as_ref().unwrap();
        assert!(math.display);
        assert!(
            math.svg
                .as_deref()
                .is_some_and(|svg| svg.starts_with("<svg")),
            "a multi-line body still renders: {math:?}"
        );
        assert_eq!(units[2], sentence("After."));
    }

    #[test]
    fn a_math_fence_body_is_source_not_dollar_scanned() {
        let units = note_units(&card_with_note("```math\n$x^2$\n```"));
        let ContentUnit::Sentence { text, runs } = &units[0] else {
            panic!("expected a sentence unit: {units:?}");
        };
        assert_eq!(text, "$x^2$", "dollars in the body stay source");
        assert_eq!(runs[0].text, "$x^2$");
        assert!(runs[0].math.as_ref().unwrap().display);
    }

    #[test]
    fn an_empty_math_fence_stays_a_code_block() {
        for note in ["```math\n```", "```math\n   \n```"] {
            let units = note_units(&card_with_note(note));
            assert!(
                matches!(units.as_slice(), [ContentUnit::Code { .. }]),
                "{note}: {units:?}"
            );
        }
    }

    #[test]
    fn a_math_fence_makes_front_units_structural() {
        let units = front_units("Ready?\n```math\nx^2\n```").unwrap();
        assert_eq!(units.len(), 2, "{units:?}");
        let ContentUnit::Sentence { runs, .. } = &units[1] else {
            panic!("expected the math unit: {units:?}");
        };
        assert!(runs[0].math.as_ref().unwrap().display);
    }

    #[test]
    fn a_bare_table_becomes_one_aligned_table_unit() {
        let units = note_units(&card_with_note(
            "before\n| h1 | h2 |\n|:---|---:|\n| **a** | b |\n| c |\ntail",
        ));
        assert_eq!(3, units.len(), "{units:?}");
        let ContentUnit::Table {
            aligns,
            header,
            rows,
        } = &units[1]
        else {
            panic!("the pipe block is a table unit: {units:?}");
        };
        assert_eq!(&[CellAlign::Left, CellAlign::Right], aligns.as_slice());
        assert_eq!(
            vec!["h1", "h2"],
            header
                .iter()
                .map(|runs| runs.iter().map(|run| run.text.as_str()).collect::<String>())
                .collect::<Vec<_>>()
        );
        assert_eq!(2, rows.len(), "{rows:?}");
        assert!(
            rows[0][0].iter().any(|run| run.bold),
            "cell text renders inline styling: {rows:?}"
        );
        assert_eq!(
            2,
            rows[1].len(),
            "a short row pads to the header width: {rows:?}"
        );
        assert!(rows[1][1].is_empty(), "the padded cell is empty: {rows:?}");
        assert!(
            matches!(&units[2], ContentUnit::Sentence { text, .. } if text == "tail"),
            "prose resumes after the table: {units:?}"
        );
    }

    #[test]
    fn a_pipe_line_without_a_delimiter_row_stays_prose() {
        let units = note_units(&card_with_note("| not | a table |\njust prose"));
        assert!(
            units
                .iter()
                .all(|unit| matches!(unit, ContentUnit::Sentence { .. })),
            "{units:?}"
        );
    }

    #[test]
    fn a_table_inside_a_fence_stays_code() {
        let units = note_units(&card_with_note("```\n| a | b |\n|---|---|\n```"));
        assert_eq!(
            units,
            vec![ContentUnit::Code {
                lines: vec!["| a | b |".into(), "|---|---|".into()]
            }]
        );
    }

    #[test]
    fn a_mismatched_delimiter_width_is_not_a_table() {
        let units = note_units(&card_with_note("| a | b |\n|---|\nafter"));
        assert!(
            units
                .iter()
                .all(|unit| matches!(unit, ContentUnit::Sentence { .. })),
            "{units:?}"
        );
    }

    #[test]
    fn a_nested_fence_is_one_note_code_unit_to_its_matching_closer() {
        let units = note_units(&card_with_note("````\n```\ncode\n```\n````"));
        assert_eq!(
            units,
            vec![ContentUnit::Code {
                lines: vec!["```".into(), "code".into(), "```".into()]
            }]
        );
    }

    #[test]
    fn a_fence_shaped_content_line_with_info_does_not_close_the_fence() {
        let units = note_units(&card_with_note("````\n````rust\n$x$\n````"));
        assert_eq!(
            units,
            vec![ContentUnit::Code {
                lines: vec!["````rust".into(), "$x$".into()]
            }]
        );
    }

    #[test]
    fn dollars_in_fenced_code_never_render_as_math() {
        for fence in ["```", "~~~"] {
            let note = format!("{fence}\n$x^2$\n{fence}");
            let units = note_units(&card_with_note(&note));
            assert_eq!(
                units,
                vec![ContentUnit::Code {
                    lines: vec!["$x^2$".into()]
                }]
            );
        }
    }

    #[test]
    fn front_units_are_some_only_when_a_task_list_is_present() {
        assert_eq!(None, front_units("What is the capital of France?"));
        let units = front_units("Given this list:\n- [x] keep\n- [ ] drop").unwrap();
        assert_eq!(
            units,
            vec![
                ContentUnit::Sentence {
                    text: "Given this list:".into(),
                    runs: crate::inline::parse_inline("Given this list:"),
                },
                ContentUnit::Checklist {
                    items: vec![
                        ChecklistItem {
                            checked: true,
                            text: "keep".into(),
                            runs: crate::inline::parse_inline("keep"),
                        },
                        ChecklistItem {
                            checked: false,
                            text: "drop".into(),
                            runs: crate::inline::parse_inline("drop"),
                        },
                    ],
                },
            ]
        );
    }

    #[test]
    fn a_task_list_note_becomes_a_checklist_unit() {
        let units = note_units(&card_with_note("Recall:\n- [x] do this\n- [ ] not that"));
        assert_eq!(
            units,
            vec![
                ContentUnit::Sentence {
                    text: "Recall:".into(),
                    runs: crate::inline::parse_inline("Recall:"),
                },
                ContentUnit::Checklist {
                    items: vec![
                        ChecklistItem {
                            checked: true,
                            text: "do this".into(),
                            runs: crate::inline::parse_inline("do this"),
                        },
                        ChecklistItem {
                            checked: false,
                            text: "not that".into(),
                            runs: crate::inline::parse_inline("not that"),
                        },
                    ],
                },
            ]
        );
    }

    #[test]
    fn code_block_is_verbatim() {
        let note = "Intro here.\n```\nfn main() {\n    let x = 1;\n}\n```";
        let units = note_units(&card_with_note(note));
        assert_eq!(
            units,
            vec![
                sentence("Intro here."),
                ContentUnit::Code {
                    lines: vec!["fn main() {".into(), "    let x = 1;".into(), "}".into(),]
                },
            ]
        );
    }

    #[test]
    fn prose_after_code_is_its_own_unit() {
        let note = "```\ncode\n```\nAfter the block.";
        let units = note_units(&card_with_note(note));
        assert_eq!(
            units,
            vec![
                ContentUnit::Code {
                    lines: vec!["code".into()]
                },
                sentence("After the block."),
            ]
        );
    }

    #[test]
    fn unterminated_fence_still_yields_code() {
        let units = note_units(&card_with_note("```\nlonely line"));
        assert_eq!(
            units,
            vec![ContentUnit::Code {
                lines: vec!["lonely line".into()]
            }]
        );
    }

    #[test]
    fn period_in_number_does_not_split() {
        let units = note_units(&card_with_note("See section 2.1 for details."));
        assert_eq!(units, vec![sentence("See section 2.1 for details.")]);
    }

    #[test]
    fn note_units_serialize_as_the_documented_wire_shape() {
        let units = vec![
            ContentUnit::Sentence {
                text: "One owner.".into(),
                runs: crate::inline::parse_inline("One owner."),
            },
            ContentUnit::Code {
                lines: vec!["let s;".into()],
            },
            ContentUnit::Checklist {
                items: vec![ChecklistItem {
                    checked: true,
                    text: "Own it".into(),
                    runs: crate::inline::parse_inline("**Own** it"),
                }],
            },
        ];
        assert_eq!(
            serde_json::json!([
                {"kind": "sentence", "text": "One owner.", "runs": [{"text": "One owner."}]},
                {"kind": "code", "lines": ["let s;"]},
                {"kind": "checklist", "items": [{
                    "checked": true,
                    "text": "Own it",
                    "runs": [{"text": "Own", "bold": true}, {"text": " it"}]
                }]},
            ]),
            serde_json::to_value(&units).unwrap()
        );
    }

    #[test]
    fn context_spans_split_holes() {
        use ContextSpan::*;
        assert_eq!(context_spans("plain text"), vec![Text("plain text".into())]);
        assert_eq!(
            context_spans("To ⍰ or not to ⬚"),
            vec![
                Text("To ".into()),
                Blank("⍰".into()),
                Text(" or not to ".into()),
                Hidden("⬚".into()),
            ]
        );
        assert_eq!(
            context_spans("⍰ here"),
            vec![Blank("⍰".into()), Text(" here".into())]
        );
        assert_eq!(
            context_spans("⬚ before ⍰"),
            vec![
                Hidden("⬚".into()),
                Text(" before ".into()),
                Blank("⍰".into()),
            ]
        );
    }

    fn resolved(source: &str) -> Vec<crate::card::ResolvedDiagram> {
        vec![crate::card::ResolvedDiagram {
            fingerprint: crate::diagram::fingerprint(source),
            png: std::path::PathBuf::from("/ws/assets/deck-x/sha256-aa.png"),
            geometry: crate::diagram::DiagramGeometry {
                image: "sha256-aa.png".to_string(),
                image_width: 376,
                image_height: 228,
                logical_width: 188,
                logical_height: 114,
                labels: Vec::new(),
            },
        }]
    }

    /// A rendered diagram replaces its own fence in the ordered stream:
    /// surrounding prose keeps its position, and only a matching resolved
    /// stamp swaps.
    #[test]
    fn a_resolved_mermaid_fence_becomes_a_diagram_unit_in_its_own_slot() {
        let source = "flowchart LR\n A-->B";
        let text = "before\n```mermaid\nflowchart LR\n A-->B\n```\nafter";
        let mut projector = DisplayProjector::default();
        let units = text_units_with(text, &mut projector, false, &resolved(source));
        assert_eq!(3, units.len(), "{units:?}");
        assert!(matches!(&units[0], ContentUnit::Sentence { text, .. } if text == "before"));
        let ContentUnit::Diagram {
            src,
            width,
            height,
            alt,
            ..
        } = &units[1]
        else {
            panic!("the fence slot holds the diagram: {units:?}");
        };
        assert_eq!("/ws/assets/deck-x/sha256-aa.png", src);
        assert_eq!(
            (&188, &114),
            (width, height),
            "logical, not raster, dimensions"
        );
        assert_eq!(source, alt, "the fence source is the accessible text");
        assert!(matches!(&units[2], ContentUnit::Sentence { text, .. } if text == "after"));
    }

    #[test]
    fn a_section_fence_closes_only_on_its_own_marker() {
        let lines: Vec<String> = ["```", "~~~", "text", "```"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(
            vec![ContentUnit::Code {
                lines: vec!["~~~".into(), "text".into()]
            }],
            section_units(&lines),
            "a tilde run never closes a backtick fence"
        );
    }

    #[test]
    fn a_section_fence_shaped_line_with_info_stays_inside() {
        let lines: Vec<String> = ["````", "````rust", "x", "````"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(
            vec![ContentUnit::Code {
                lines: vec!["````rust".into(), "x".into()]
            }],
            section_units(&lines),
            "an info-carrying line is content, not a closer"
        );
    }

    #[test]
    fn a_math_fence_renders_in_section_and_context_walks() {
        let lines: Vec<String> = ["```math", "x^2", "```"]
            .iter()
            .map(|line| line.to_string())
            .collect();
        let section = section_units(&lines);
        let context = context_units_with(&context_card(&lines, Vec::new(), Vec::new()));
        for (surface, units) in [("section", section), ("context", context)] {
            let [ContentUnit::Sentence { text, runs }] = units.as_slice() else {
                panic!("a math fence in {surface} must be display math: {units:?}");
            };
            assert_eq!(text, "x^2");
            assert!(
                runs[0].math.as_ref().is_some_and(|math| math.display),
                "{surface} must carry a display math run: {runs:?}"
            );
        }
    }

    #[test]
    fn section_and_context_walks_share_the_bare_display_math_boundary() {
        let cases = [
            (
                "closed bare block",
                vec!["$$", "x^2 + y^2", "$$"],
                Some("x^2 + y^2"),
            ),
            (
                "unclosed bare opener stays prose",
                vec!["$$", "x^2 + y^2"],
                None,
            ),
            (
                "math fence control",
                vec!["```math", "x^2 + y^2", "```"],
                Some("x^2 + y^2"),
            ),
        ];

        for (case, source, expected) in cases {
            let lines: Vec<String> = source.into_iter().map(str::to_string).collect();
            let surfaces = [
                ("section", section_units(&lines)),
                (
                    "context",
                    context_units_with(&context_card(&lines, Vec::new(), Vec::new())),
                ),
            ];
            for (surface, units) in surfaces {
                match expected {
                    Some(expected) => {
                        let [ContentUnit::Sentence { text, runs }] = units.as_slice() else {
                            panic!("{case} on {surface} must be display math: {units:?}");
                        };
                        assert_eq!(expected, text, "{case} on {surface}");
                        assert!(
                            runs[0].math.as_ref().is_some_and(|math| math.display),
                            "{case} on {surface} must carry a display run: {runs:?}"
                        );
                    }
                    None => assert!(
                        units.is_empty(),
                        "{case} on {surface} must remain in the raw prose walk: {units:?}"
                    ),
                }
            }
        }
    }

    #[test]
    fn a_context_fence_shaped_line_with_info_stays_inside() {
        let context: Vec<String> = ["````", "````rust", "x", "````"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let units = context_units_with(&context_card(&context, Vec::new(), Vec::new()));
        assert_eq!(
            vec![ContentUnit::Code {
                lines: vec!["````rust".into(), "x".into()]
            }],
            units,
            "an info-carrying line is content, not a closer"
        );
    }

    #[test]
    fn a_nested_context_fence_is_one_code_unit_to_its_matching_closer() {
        let context: Vec<String> = ["````", "a", "```", "b", "````"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let units = context_units_with(&context_card(&context, Vec::new(), Vec::new()));
        assert_eq!(
            units,
            vec![ContentUnit::Code {
                lines: vec!["a".into(), "```".into(), "b".into()]
            }]
        );
    }

    fn context_card(
        context: &[String],
        diagrams: Vec<crate::card::ResolvedDiagram>,
        fences: Vec<crate::card::AnswerFence>,
    ) -> Card {
        let mut card = Card::plain(
            std::sync::Arc::from("deck.md"),
            "q".to_string(),
            vec!["answer".to_string()],
            Vec::new(),
            1,
        );
        card.context = context.to_vec();
        card.resolved_diagrams = diagrams;
        card.answer_fences = fences;
        card
    }

    fn record(source: &str) -> crate::card::AnswerFence {
        crate::card::AnswerFence {
            fingerprint: crate::diagram::fingerprint(source),
            interior: std::sync::Arc::from(source),
            spans: Vec::new(),
        }
    }

    /// The context stream's law: fence-shaped units only, one per closed
    /// fence in order; a clean record (no spans) whose unmasked
    /// fingerprint resolves swaps to the diagram, everything else is code.
    #[test]
    fn a_clean_recorded_context_fence_resolves_through_its_record() {
        let source = "flowchart LR\n A-->B";
        let context: Vec<String> = [
            "prose line",
            "```rust",
            "let x = 1;",
            "```",
            "```mermaid",
            "flowchart LR",
            " A-->B",
            "```",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let fences = vec![record(source)];
        let units = context_units_with(&context_card(&context, resolved(source), fences));
        assert_eq!(2, units.len(), "{units:?}");
        assert!(
            matches!(&units[0], ContentUnit::Code { lines } if lines == &["let x = 1;"]),
            "a non-mermaid fence is code and consumes no record: {units:?}"
        );
        let ContentUnit::Diagram { alt, .. } = &units[1] else {
            panic!("the mermaid fence resolves through its record: {units:?}");
        };
        assert_eq!(source, alt, "the clean interior is the accessible text");
    }

    #[test]
    fn a_record_with_spans_or_no_resolution_stays_code_in_context() {
        let source = "flowchart LR\n A-->B";
        let context: Vec<String> = ["```mermaid", "flowchart LR", " A-->B", "```"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let with_spans = crate::card::AnswerFence {
            spans: vec![crate::card::AnswerFenceSpan {
                line: 6,
                start: 0,
                end: 4,
            }],
            ..record(source)
        };
        let cases: [(Vec<crate::card::AnswerFence>, &str); 3] = [
            (vec![with_spans], "bound spans hold for span binding"),
            (vec![record("flowchart LR\n X-->Y")], "no resolution"),
            (Vec::new(), "no record at all"),
        ];
        for (fences, why) in cases {
            let units = context_units_with(&context_card(&context, resolved(source), fences));
            assert!(
                matches!(&units[0], ContentUnit::Code { .. }),
                "{why}: {units:?}"
            );
        }
    }

    #[test]
    fn a_masked_context_interior_resolves_by_record_never_by_its_own_text() {
        let authored = "flowchart LR\n![](x.png)\n A-->B";
        let context: Vec<String> = ["```mermaid", "flowchart LR", " A-->B", "```"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let fences = vec![record(authored)];
        let units = context_units_with(&context_card(&context, resolved(authored), fences));
        let ContentUnit::Diagram { alt, .. } = &units[0] else {
            panic!(
                "the record carries the unmasked fingerprint even where the \
                 displayed interior diverges: {units:?}"
            );
        };
        assert_eq!(
            authored, alt,
            "the accessible text is the authored interior, not the displayed one"
        );
    }

    /// Clients consume one fence-shaped unit per closed raw fence, so an
    /// empty fence must still emit its code unit: skipping it hands this
    /// fence the NEXT fence's unit and a later diagram lands one slot early.
    #[test]
    fn an_empty_fence_keeps_its_unit_slot_so_a_later_diagram_stays_aligned() {
        let source = "flowchart LR\n A-->B";
        let text = "```\n```\n```mermaid\nflowchart LR\n A-->B\n```";
        let mut projector = DisplayProjector::default();
        let units = text_units_with(text, &mut projector, false, &resolved(source));
        assert_eq!(2, units.len(), "{units:?}");
        assert!(
            matches!(&units[0], ContentUnit::Code { lines } if lines.is_empty()),
            "the empty fence holds its slot: {units:?}"
        );
        assert!(
            matches!(&units[1], ContentUnit::Diagram { .. }),
            "{units:?}"
        );
    }

    /// The server resolves availability: no resolved stamp, a stale
    /// fingerprint, or a non-mermaid fence all stay code units in place.
    #[test]
    fn unresolved_stale_and_foreign_fences_stay_code_units() {
        let mut projector = DisplayProjector::default();
        let cases: [(&str, Vec<crate::card::ResolvedDiagram>, &str); 3] = [
            (
                "```mermaid\nflowchart LR\n A-->B\n```",
                Vec::new(),
                "unfrozen",
            ),
            (
                "```mermaid\nflowchart LR\n A-->B\n```",
                resolved("flowchart LR\n A-->EDITED"),
                "stale fingerprint",
            ),
            (
                "```rust\nflowchart LR\n A-->B\n```",
                resolved("flowchart LR\n A-->B"),
                "non-mermaid fence",
            ),
        ];
        for (text, diagrams, why) in cases {
            let units = text_units_with(text, &mut projector, false, &diagrams);
            assert!(
                matches!(&units[0], ContentUnit::Code { .. }),
                "{why}: must stay a code unit, got {units:?}"
            );
        }
    }
}