devpage-core 0.2.5

devpage's core: documents, rendering, link checking, comments and designs, with no I/O runtime
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
//! Link checking: every link, image and diagram target a page holds must
//! reach a file in the served folder — and a heading on it, when it names one —
//! every external address must answer, and every diagram must draw.

use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use crate::designs::Designs;
use crate::document::{Document, Kind, KindName};
use crate::folder::{Folder, ServedFolder};
use crate::page::{self, Rendered};

use crate::external::{External, Link};
use crate::html;
use crate::problem::Problem;
use crate::widgets::{Modules, Widgets};

/// The pages a document is made of.
fn pages(document: &Document) -> Vec<PathBuf> {
    match &document.kind {
        Kind::Site { root } => vec![document.base.join(root)],
        Kind::Doc { chapters, .. } => chapters.clone(),
        Kind::Slides { slides, .. } => slides.iter().map(|slide| slide.file.clone()).collect(),
        Kind::Design => Vec::new(),
    }
}

/// Checks the folder's entry document and every page and document reachable
/// from it by links inside the served folder, each design it reaches as
/// `designs` — the folder's design store — holds it.
/// External links are checked when `checker` is given.
pub async fn document(
    folder: &Folder,
    designs: &Designs,
    checker: Option<&External>,
) -> Vec<Problem> {
    let document = &*folder.entry();
    let mut external = Vec::new();
    let mut problems = internal(folder, designs, document, &mut external, None);
    if let Kind::Design = document.kind {
        let address = document.part_name(&document.path());
        problems.extend(
            designs
                .problems(&address)
                .into_iter()
                // A design names its place by line and column.
                .map(|problem| Problem {
                    file: format!("{}:{}:{}", problem.file, problem.pos.line, problem.pos.col),
                    line: None,
                    message: problem.message,
                    target: None,
                }),
        );
    }
    if let Some(checker) = checker {
        problems.extend(checker.check(external).await);
    }
    problems
}

/// Every file the check follows from the folder's entry document, each once
/// and in path order: the document file, its pages, chapters or slides and every page
/// and document they reach, the images and files their links name, a design's
/// imports, images, themes and fonts, the logo, and the project widgets with
/// every module they import — what the document is made of, and nothing else
/// beside it. External addresses are not followed. A design's files are the
/// ones `designs`, the folder's design store, resolved it from.
pub fn files(folder: &Folder, designs: &Designs) -> Vec<PathBuf> {
    let mut files = BTreeSet::new();
    internal(
        folder,
        designs,
        &folder.entry(),
        &mut Vec::new(),
        Some(&mut files),
    );
    files.into_iter().collect()
}

/// Every file a slide of the deck at `deck` is drawn from, in path order:
/// the deck's file, its slides, what each slide embeds — an image, a design
/// and everything `designs` resolved it from, a font folder it listed among
/// them, another deck's slide PNG and that deck's files in turn — and the
/// deck's widgets folder with every widget in it and every module they
/// import. Each folder itself is among them: a font added to a design's
/// font folder changes the design, and a widget added, renamed or removed
/// changes which tags on a slide are widgets. An embedded file that isn't there yet is named as it would
/// be, so its arrival reaches the deck. A link a slide only points at is not
/// what it is drawn from. A deck that can't be loaded is drawn from its file.
pub fn drawn_from(
    deck: &Path,
    served: &ServedFolder,
    designs: &Designs,
    modules: &Modules,
) -> Vec<PathBuf> {
    let mut files = BTreeSet::new();
    deck_drawn_from(deck, served, designs, modules, &mut files);
    files.into_iter().collect()
}

fn deck_drawn_from(
    deck: &Path,
    served: &ServedFolder,
    designs: &Designs,
    modules: &Modules,
    files: &mut BTreeSet<PathBuf>,
) {
    // A deck reached again — a slide showing its own deck's PNG — adds
    // nothing.
    if !files.insert(deck.to_path_buf()) {
        return;
    }
    let Ok(document) = Document::load(deck, served) else {
        return;
    };
    let Kind::Slides { slides, .. } = &document.kind else {
        return;
    };
    let widgets = Widgets::of(&document, modules);
    if let Some(folder) = &document.widgets {
        files.insert(folder.clone());
        for widget in widget_files(folder) {
            let snapshot = modules.snapshot(served, &widget);
            files.extend(
                snapshot
                    .closure(&widget)
                    .into_iter()
                    .map(|(module, _)| module),
            );
        }
    }
    for slide in slides {
        files.insert(slide.file.clone());
        let rendered = page::read(&widgets, &slide.file);
        let folder = slide.file.parent().unwrap_or(Path::new("."));
        for target in rendered.embeds() {
            let html::Link::File { path, .. } = html::Link::classify(target) else {
                continue;
            };
            // A query — a design PNG's theme — names no other file.
            let path = path.split('?').next().unwrap_or_default();
            if path.is_empty() {
                continue;
            }
            // A path from the top is from the top of the served folder.
            let named = match path.strip_prefix('/') {
                Some(top) => served.path().join(top),
                None => folder.join(path),
            };
            if let Some(real) = served.file(&named) {
                if real.extension().is_some_and(|ext| ext == "design")
                    && let Some(address) = document.name(&real)
                {
                    files.extend(designs.made_of(&address));
                }
                files.insert(real);
                continue;
            }
            // A design's PNG address, with no real file of that name: the
            // design drawn.
            if let Some(design) = named
                .to_str()
                .and_then(|named| named.strip_suffix(".png"))
                .filter(|p| p.ends_with(".design"))
                .and_then(|design| served.file(Path::new(design)))
            {
                if let Some(address) = document.name(&design) {
                    files.extend(designs.made_of(&address));
                }
                files.insert(design);
                continue;
            }
            // A slide's PNG: `<deck>/<n>.png` is drawn from that deck.
            if let Some(other) = named
                .parent()
                .filter(|_| named.extension().is_some_and(|ext| ext == "png"))
                .and_then(|parent| served.file(parent))
                .filter(|parent| crate::document::kind_of(parent) == Some(KindName::Slides))
            {
                deck_drawn_from(&other, served, designs, modules, files);
                continue;
            }
            files.extend(served.named(&named));
        }
    }
}

/// A file the walk followed, kept when the caller asked for them: only
/// regular files inside the served folder, and every file a design is made
/// of, as `designs` read them — not a folder it listed.
fn follow(
    document: &Document,
    designs: &Designs,
    files: &mut Option<&mut BTreeSet<PathBuf>>,
    file: &Path,
) {
    let Some(files) = files.as_deref_mut() else {
        return;
    };
    if let Some(real) = document.served.file(file)
        && files.insert(real.clone())
        && real.extension().is_some_and(|ext| ext == "design")
        && let Some(address) = document.name(&real)
    {
        // A folder a design listed, or a file it asked for that isn't
        // there, is nothing to follow.
        files.extend(
            designs
                .made_of(&address)
                .into_iter()
                .filter_map(|file| document.served.file(&file)),
        );
    }
}

fn internal(
    folder: &Folder,
    designs: &Designs,
    document: &Document,
    external: &mut Vec<Link>,
    mut files: Option<&mut BTreeSet<PathBuf>>,
) -> Vec<Problem> {
    follow(document, designs, &mut files, &document.path());
    let mut problems = Vec::new();
    let mut seen = HashSet::new();
    let mut checked = Vec::new();
    // Every page of a deck the check reaches is a slide, however else it is
    // reached: its notes are judged once the whole walk is done.
    let mut slides = HashSet::new();
    let deck_pages = |linked: &Document, slides: &mut HashSet<PathBuf>| {
        let found = pages(linked);
        if matches!(linked.kind, Kind::Slides { .. }) {
            slides.extend(found.iter().cloned());
        }
        found
    };
    let mut queue: VecDeque<PathBuf> = deck_pages(document, &mut slides).into();
    // A page is checked as its nearest site's page, whichever document the
    // check started from — as the preview shows it. Widgets are read and
    // compiled once per check.
    let modules = Modules::default();
    let mut widget_folders = HashSet::new();
    let mut navbars = HashSet::new();
    let mut logos = HashSet::new();
    while let Some(page) = queue.pop_front() {
        if !seen.insert(page.clone()) {
            continue;
        }
        follow(document, designs, &mut files, &page);
        let owner = match folder.owner(&page) {
            Some(owner) => owner.document.ok(),
            // In no site, a page is shown as a doc of one chapter — unless it
            // is one of the doc's or deck's own files the check started from.
            None if matches!(document.kind, Kind::Site { .. }) => {
                Document::load(&page, &document.served).ok()
            }
            None => None,
        };
        let owner = owner.as_ref().unwrap_or(document);
        follow(document, designs, &mut files, &owner.path());
        let widgets = Widgets::of(owner, &modules);
        if let Some(folder) = &owner.widgets
            && widget_folders.insert(folder.clone())
        {
            problems.extend(widget_problems(owner, &widgets));
            if files.is_some() {
                for widget in widget_files(folder) {
                    let snapshot = modules.snapshot(&document.served, &widget);
                    for (module, _) in snapshot.closure(&widget) {
                        follow(document, designs, &mut files, &module);
                    }
                }
            }
        }
        if let Some(logo) = &owner.logo {
            follow(document, designs, &mut files, &owner.base.join(logo));
        }
        // A document's logo is checked once.
        if logos.insert(owner.path())
            && let Some(problem) = page::navbar::logo_problem(owner)
        {
            problems.push(problem);
        }
        // A site's navbar is checked once, and what it links to is checked too.
        if !owner.navbar.is_empty() && navbars.insert(owner.path()) {
            problems.extend(page::navbar::problems(owner));
            let (reached_files, web) = page::navbar::reached(owner);
            let file = owner.part_name(&owner.path());
            external.extend(web.into_iter().map(|address| (file.clone(), None, address)));
            for target in reached_files {
                follow(document, designs, &mut files, &target);
                if target.extension().is_some_and(|ext| ext == "md") {
                    queue.push_back(target);
                } else if let Ok(linked) = Document::load(&target, &document.served) {
                    queue.extend(deck_pages(&linked, &mut slides));
                }
            }
        }
        let rendered = page::read(&widgets, &page);
        let (found, reached) =
            page_links_with(folder, owner, &modules, designs, &rendered, external);
        problems.extend(found);
        checked.push(rendered);
        for target in reached {
            follow(document, designs, &mut files, &target);
            if target.extension().is_some_and(|ext| ext == "md") {
                queue.push_back(target);
            } else if target
                .extension()
                .is_some_and(|ext| ext == "yml" || ext == "yaml")
            {
                // An invalid one is a problem on the page linking to it.
                if let Ok(linked) = Document::load(&target, &document.served) {
                    queue.extend(deck_pages(&linked, &mut slides));
                }
            }
        }
    }
    for rendered in &checked {
        problems.extend(notes_problems(
            document,
            rendered,
            slides.contains(rendered.file()),
        ));
    }
    problems
}

/// A page's `<Notes>` that are out of place: any on a page that isn't a
/// slide, and every one after the first on a slide.
fn notes_problems(document: &Document, rendered: &Rendered, slide: bool) -> Vec<Problem> {
    // A page outside the served folder is no page of the check: the link to
    // it is the problem.
    let Some(file) = document.name(rendered.file()) else {
        return Vec::new();
    };
    // A slide's first `<Notes>` is its notes; a page has none.
    crate::markup::notes(rendered.source())
        .iter()
        .skip(usize::from(slide))
        .map(|note| Problem {
            file: file.clone(),
            line: Some(note.line),
            message: if slide {
                "a second <Notes> on one slide".to_string()
            } else {
                "<Notes> is only for a slide".to_string()
            },
            target: None,
        })
        .collect()
}

/// One page's problems and reached files, judged from its `rendered`
/// content — the content its page shows; its external links are collected
/// in `external` as (file, line, address). A heading another page holds is
/// one that page's content shows, its widgets read through `modules`.
fn page_links_with(
    folder: &Folder,
    document: &Document,
    modules: &Modules,
    designs: &Designs,
    rendered: &Rendered,
    external: &mut Vec<Link>,
) -> (Vec<Problem>, Vec<PathBuf>) {
    let page = rendered.file();
    let source = rendered.source();
    // A page outside the served folder is no page of the check: the link to
    // it is the problem.
    let Some(file) = document.name(page) else {
        return (Vec::new(), Vec::new());
    };
    let mut problems = Vec::new();
    for found in rendered.tag_problems() {
        let (line, message) = found.split_once(": ").unwrap_or(("", found));
        problems.push(Problem {
            file: file.clone(),
            line: line.parse().ok(),
            message: message.to_string(),
            target: None,
        });
    }
    let mut reached = Vec::new();
    // A diagram's `click … href "…"` lines are links in its drawing, found
    // with the rest; one that doesn't draw is a problem of its own.
    problems.extend(diagram_problems(source, &file));
    for link in rendered.links() {
        let (target, line) = (link.target.clone(), link.line);
        let (path, fragment) = match html::Link::classify(&target) {
            html::Link::File { path, fragment } => (path, fragment),
            html::Link::Web(_) => {
                external.push((file.clone(), line, target));
                continue;
            }
            html::Link::Elsewhere => continue, // mailto: and other schemes are not checked
        };
        let resolved = if path.is_empty() {
            Some(page.to_path_buf())
        } else {
            document
                .served
                .inside(&page.parent().unwrap_or(Path::new(".")).join(path))
        };
        // A design's PNG address is the design drawn, when no real file of
        // that name is there: the link is as good as the design.
        let resolved = resolved.or_else(|| {
            let design = path
                .strip_suffix(".png")
                .filter(|p| p.ends_with(".design"))?;
            document
                .served
                .file(&page.parent().unwrap_or(Path::new(".")).join(design))
        });
        let Some(resolved) = resolved else {
            problems.push(Problem {
                file: file.clone(),
                line,
                message: format!("broken link {target} — no such file"),
                target: Some(target.clone()),
            });
            continue;
        };
        // A heading is named by an id its page's content renders, widgets
        // expanded: this page's own, or the linked page's as shown.
        let no_heading = || Problem {
            file: file.clone(),
            line,
            message: format!("broken link {target} — no heading #{fragment}"),
            target: Some(target.clone()),
        };
        if !fragment.is_empty()
            && resolved.extension().is_some_and(|ext| ext == "md")
            && fragment.parse::<usize>().is_err()
            && !if path.is_empty() {
                rendered.ids()
            } else {
                page::ids(&resolved, folder, modules)
            }
            .contains(fragment)
        {
            problems.push(no_heading());
        }
        if resolved.extension().is_some_and(|ext| ext == "design")
            && let Some(address) = document.name(&resolved)
        {
            for problem in designs.problems(&address) {
                problems.push(Problem {
                    file: file.clone(),
                    line,
                    message: format!("broken design {target} — {problem}"),
                    target: Some(target.clone()),
                });
            }
        }
        if crate::document::kind_of(&resolved).is_some() {
            match Document::load(&resolved, &document.served) {
                Err(error) => {
                    problems.push(Problem {
                        file: file.clone(),
                        line,
                        message: format!(
                            "broken link {target} — {}",
                            relative(&format!("{error:#}"), document.served.path())
                        ),
                        target: Some(target.clone()),
                    });
                    continue;
                }
                // `#n` on a deck must name one of its slides.
                Ok(Document {
                    kind: Kind::Slides { slides, .. },
                    ..
                }) if !fragment.is_empty()
                    && !fragment
                        .parse::<usize>()
                        .is_ok_and(|n| (1..=slides.len()).contains(&n)) =>
                {
                    problems.push(Problem {
                        file: file.clone(),
                        line,
                        message: format!(
                            "broken link {target} — the deck has {} slide{}",
                            slides.len(),
                            if slides.len() == 1 { "" } else { "s" }
                        ),
                        target: Some(target.clone()),
                    });
                }
                // A heading in a doc is named by the id the doc renders it with.
                Ok(Document {
                    kind: Kind::Doc { .. },
                    ..
                }) if !fragment.is_empty()
                    && !page::ids(&resolved, folder, modules).contains(fragment) =>
                {
                    problems.push(no_heading());
                }
                Ok(_) => {}
            }
        }
        reached.push(resolved);
    }
    // In a site, a Topics entry outside the site's folder is left out of the sidebar.
    if matches!(document.kind, Kind::Site { .. }) {
        for topic in crate::nav::topics(source) {
            if let crate::nav::Target::Problem(message) =
                crate::nav::resolve(document, page, &topic.href)
                && message.ends_with("outside the site's folder")
            {
                problems.push(Problem {
                    file: file.clone(),
                    line: source
                        .find(&topic.href)
                        .map(|at| source[..at].lines().count().max(1)),
                    message,
                    target: Some(topic.href.clone()),
                });
            }
        }
    }
    problems.extend(crate::comments::yaml::problems(document, page));
    (problems, reached)
}

/// Each Mermaid fence of a page's Markdown that doesn't draw, at the fence's
/// line. Rendering the page drew them already, so they come from the cache.
fn diagram_problems(source: &str, file: &str) -> Vec<Problem> {
    use comrak::nodes::NodeValue;
    let arena = comrak::Arena::new();
    let root = comrak::parse_document(&arena, source, &page::markdown::options());
    let fences: Vec<(usize, String)> = root
        .descendants()
        .filter_map(|node| {
            let data = node.data.borrow();
            match &data.value {
                NodeValue::CodeBlock(block)
                    if block.fenced && block.info.split_whitespace().next() == Some("mermaid") =>
                {
                    Some((data.sourcepos.start.line, block.literal.clone()))
                }
                _ => None,
            }
        })
        .collect();
    let sources: Vec<String> = fences.iter().map(|(_, s)| s.clone()).collect();
    fences
        .iter()
        .zip(crate::diagrams::draw_all(&sources))
        .filter_map(|((line, _), drawn)| {
            let why = drawn.err()?;
            Some(Problem {
                file: file.to_string(),
                line: Some(*line),
                message: format!("broken diagram — {why}"),
                target: None,
            })
        })
        .collect()
}

/// The problems of a document's widgets folder, once per document rather than
/// once per page: a file with a system widget's name, and every widget or
/// helper that doesn't compile.
/// The project widget files directly in `folder`, sorted.
fn widget_files(folder: &Path) -> Vec<PathBuf> {
    let mut files: Vec<PathBuf> = std::fs::read_dir(folder)
        .into_iter()
        .flatten()
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| crate::widgets::is_widget_file(path, folder))
        .collect();
    files.sort();
    files
}

fn widget_problems(document: &Document, widgets: &Widgets) -> Vec<Problem> {
    let mut problems: Vec<Problem> = widgets
        .problems
        .iter()
        .map(|found| {
            let (widget_file, message) = found.split_once(" — ").unwrap_or(("", found));
            Problem {
                file: widget_file.to_string(),
                line: None,
                message: message.to_string(),
                target: None,
            }
        })
        .collect();
    let Some(folder) = &document.widgets else {
        return problems;
    };
    for file in widget_files(folder) {
        // A widget file outside the served folder is never read.
        let Some(name) = document.name(&file) else {
            continue;
        };
        if let Err(error) = widgets.compile(&file) {
            problems.push(Problem {
                file: name,
                line: None,
                message: format!("does not compile: {error}"),
                target: None,
            });
        }
    }
    problems
}

/// An error's text with the served folder's absolute path taken out, so
/// files read as their addresses do.
fn relative(text: &str, served: &Path) -> String {
    text.replace(
        &format!("{}{}", served.display(), std::path::MAIN_SEPARATOR),
        "",
    )
}

/// Where the preview tells someone about a problem it has just found: the
/// terminal in `devpage`, a recorder in tests.
pub trait Report: Send + Sync {
    fn problem(&self, problem: &Problem);
}

/// The preview's checks: what each page shows above itself as it is served.
/// One per devpage process, shared by every page — or, in server mode, one
/// per version.
pub struct Preview {
    external: Arc<External>,
    report: Arc<dyn Report>,
    /// Every problem reported so far: each is reported once.
    reported: Mutex<HashSet<Problem>>,
    /// The problems found for each document and its pages, when the files
    /// checked never change: kept, so each is checked once.
    kept: Option<Mutex<Kept>>,
}

/// A document's file and the pages checked, and the problems found on them.
type Kept = HashMap<(PathBuf, Vec<PathBuf>), Vec<Problem>>;

impl Preview {
    /// A preview of files that change: every view checks its page again.
    pub fn new(external: Arc<External>, report: Arc<dyn Report>) -> Self {
        Preview {
            external,
            report,
            reported: Mutex::default(),
            kept: None,
        }
    }

    /// A preview of files that never change — a published version's: each
    /// page is checked on its first view, and every later view gets the same
    /// problems without checking. Its external addresses are best left
    /// unasked: an answer arriving after a page's first view never shows.
    pub fn once(external: Arc<External>, report: Arc<dyn Report>) -> Self {
        Preview {
            kept: Some(Mutex::default()),
            ..Preview::new(external, report)
        }
    }

    /// The problems on the given pages of `document` — each page's content
    /// as its page shows it, rendered once for both — each design they reach
    /// as `designs` — the served folder's design store — holds it, and each
    /// page of `folder` they link into as its own content shows it: each is
    /// reported the
    /// first time it is found, and returned for the page to list. External
    /// addresses are checked in the background: a definite error shows from
    /// the next render, which its answer triggers; an address that can't be
    /// reached is retried, and shows only after three failures in a row,
    /// until it answers again.
    pub fn problems(
        &self,
        folder: &Folder,
        document: &Document,
        widgets: &Widgets,
        designs: &Designs,
        pages: &[Rendered],
    ) -> Vec<Problem> {
        let Some(kept) = &self.kept else {
            return self.check(folder, document, widgets, designs, pages);
        };
        let key = (
            document.path(),
            pages.iter().map(|page| page.file().to_path_buf()).collect(),
        );
        let lock = || kept.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(found) = lock().get(&key) {
            return found.clone();
        }
        // Checked without the lock, so a slow page holds up no other; two
        // first views at once both check, and find the same.
        let found = self.check(folder, document, widgets, designs, pages);
        lock().entry(key).or_insert(found).clone()
    }

    /// The problems on the given pages, checked now.
    fn check(
        &self,
        folder: &Folder,
        document: &Document,
        widgets: &Widgets,
        designs: &Designs,
        pages: &[Rendered],
    ) -> Vec<Problem> {
        let _check = tracing::info_span!("check").entered();
        let mut external = Vec::new();
        let mut problems = widget_problems(document, widgets);
        problems.extend(page::navbar::problems(document));
        problems.extend(page::navbar::logo_problem(document));
        problems.extend(pages.iter().flat_map(|page| {
            page_links_with(
                folder,
                document,
                widgets.cache(),
                designs,
                page,
                &mut external,
            )
            .0
        }));
        // The pages of a deck are its slides; any other page is not one.
        let slide = matches!(document.kind, Kind::Slides { .. });
        problems.extend(
            pages
                .iter()
                .flat_map(|page| notes_problems(document, page, slide)),
        );
        problems.extend(self.external.preview(external));
        let mut reported = self
            .reported
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        for problem in &problems {
            if reported.insert(problem.clone()) {
                self.report.problem(problem);
            }
        }
        problems
    }
}

/// Previews for tests that serve pages.
#[cfg(any(test, feature = "testing"))]
pub mod testing {
    use super::{Preview, Problem, Report};
    use crate::external::testing::offline;
    use std::sync::Arc;

    /// Tells no one.
    struct Silent;

    impl Report for Silent {
        fn problem(&self, _: &Problem) {}
    }

    /// A preview that asks no external address, announces on nothing and
    /// reports to no one.
    pub fn preview() -> Arc<Preview> {
        Arc::new(Preview::new(offline(), Arc::new(Silent)))
    }
}

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

    /// A folder opened on `document`, as `devpage check` opens one.
    pub(super) fn opened(document: &Document) -> Folder {
        Folder::new(Arc::new(
            Document::load(&document.path(), &document.served).unwrap(),
        ))
    }

    /// `document`'s widget set, read through a cache of its own.
    fn widgets_of(document: &Document) -> Widgets {
        Widgets::of(document, &crate::widgets::Modules::default())
    }

    /// The content of each of `files`, as `document` shows it: what the
    /// preview is given.
    pub(super) fn rendered(document: &Document, files: &[PathBuf]) -> Vec<Rendered> {
        let widgets = widgets_of(document);
        files
            .iter()
            .map(|file| page::read(&widgets, file))
            .collect()
    }

    /// A design store of its own for `document`'s served folder, as
    /// `devpage check` makes one.
    pub(super) fn designs_of(document: &Document) -> Designs {
        Designs::new(&document.served)
    }

    #[test]
    fn finds_missing_files_headings_and_climbs_out_of_the_served_folder() {
        let dir = std::env::temp_dir().join(format!("devpage-check-{}", std::process::id()));
        std::fs::create_dir_all(dir.join(".git")).unwrap();
        std::fs::write(
            dir.join("README.md"),
            "# Home\n\n[ok](b.md#two) [gone](nope.md)\n\n[bad](b.md#three) [out](../../x.md)\n\n```mermaid\nflowchart LR\n  a\n  click a href \"missing.md\"\n```\n",
        )
        .unwrap();
        std::fs::write(dir.join("b.md"), "# B\n\n## Two\n\n![logo](logo.png)\n").unwrap();
        std::fs::write(
            dir.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\n",
        )
        .unwrap();
        let doc = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();
        let found: Vec<String> = internal(
            &opened(&doc),
            &designs_of(&doc),
            &doc,
            &mut Vec::new(),
            None,
        )
        .iter()
        .map(ToString::to_string)
        .collect();
        assert_eq!(found.len(), 5, "{found:#?}");
        assert!(
            found.contains(&"README.md:3: broken link nope.md — no such file".to_string()),
            "{found:#?}"
        );
        assert!(found.iter().any(|p| p.contains("b.md#three — no heading")));
        assert!(found.iter().any(|p| p.contains("../../x.md")));
        assert!(found.iter().any(|p| p.contains("missing.md")));
        assert!(
            found
                .iter()
                .any(|p| p.starts_with("b.md:5: broken link logo.png")),
            "{found:#?}"
        );
    }

    #[test]
    fn a_diagram_that_does_not_parse_is_a_problem_at_its_fence() {
        let dir =
            std::env::temp_dir().join(format!("devpage-check-diagram-{}", std::process::id()));
        std::fs::create_dir_all(dir.join(".git")).unwrap();
        let page = "---\ntitle: x\n---\n# Home\n\n```mermaid\nflowchart LR\n  a --> b\n```\n\n````markdown\n```mermaid\nnot a diagram\n```\n````\n\n```mermaid\nsequenceDiagram\n  A->>B: one; two\n```\n";
        std::fs::write(dir.join("README.md"), page).unwrap();
        std::fs::write(
            dir.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\n",
        )
        .unwrap();
        let doc = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();
        let expected = "README.md:17: broken diagram — Parse error on line 2:\n  A->>B: one; two\n";
        // In `devpage check`, and in the page's problems.
        for found in [
            internal(
                &opened(&doc),
                &designs_of(&doc),
                &doc,
                &mut Vec::new(),
                None,
            ),
            testing::preview().problems(
                &opened(&doc),
                &doc,
                &widgets_of(&doc),
                &designs_of(&doc),
                &rendered(&doc, &[doc.base.join("README.md")]),
            ),
        ] {
            let found: Vec<String> = found.iter().map(ToString::to_string).collect();
            assert_eq!(found.len(), 1, "{found:#?}");
            assert!(found[0].starts_with(expected), "{found:#?}");
            assert!(found[0].contains("got 'NEWLINE'"), "{found:#?}");
        }
    }

    /// A design's problems and files come from the store the check is
    /// given: a design document checked and then zipped is resolved once,
    /// there.
    #[tokio::test]
    async fn a_design_is_checked_and_followed_through_the_store() {
        let dir = crate::designs::testing::served("check-store");
        let served = ServedFolder::new(&dir).unwrap();
        let folder = Folder::new(Arc::new(
            Document::load(&dir.join("app/screen.design"), &served).unwrap(),
        ));
        let designs = Designs::new(&served);
        assert!(document(&folder, &designs, None).await.is_empty());
        assert_eq!(
            files(&folder, &designs),
            [dir.join("app/button.design"), dir.join("app/screen.design")]
        );
        assert_eq!(designs.resolutions(), 1, "resolved once, in the store");
    }

    /// A page's problems name a design it embeds as the server's store holds
    /// it: checking the page keeps the design there, and a save the store is
    /// told of shows on the page.
    #[test]
    fn a_page_shows_an_embedded_designs_problems_as_the_store_holds_them() {
        let dir = crate::designs::testing::served("preview-store");
        let screen = dir.join("app/screen.design");
        let broken = crate::designs::testing::SCREEN.replace("<Button label", "<Button lable");
        std::fs::write(&screen, &broken).unwrap();
        std::fs::write(
            dir.join("page.md"),
            "# Page\n\n![Screen](app/screen.design)\n",
        )
        .unwrap();
        let doc = Document::load(&dir.join("page.md"), &ServedFolder::new(&dir).unwrap()).unwrap();
        let designs = Designs::new(&doc.served);
        let preview = testing::preview();
        let pages = rendered(&doc, &[dir.join("page.md")]);
        let found = preview.problems(&opened(&doc), &doc, &widgets_of(&doc), &designs, &pages);
        assert_eq!(found.len(), 1, "{found:#?}");
        assert!(
            found[0]
                .to_string()
                .starts_with("page.md:3: broken design app/screen.design — app/screen.design:5:"),
            "{found:#?}"
        );
        assert!(designs.resolve("app/screen.design").is_err());
        assert_eq!(designs.resolutions(), 1, "the page's check kept it");
        crate::designs::testing::save(&designs, &screen, crate::designs::testing::SCREEN);
        let found = preview.problems(&opened(&doc), &doc, &widgets_of(&doc), &designs, &pages);
        assert!(found.is_empty(), "{found:#?}");
    }
}

#[cfg(test)]
mod external {
    use super::tests::{designs_of, opened, rendered};
    use super::*;
    use crate::folder::ServedFolder;
    use crate::widgets::Modules;

    /// `document`'s widget set, read through a cache of its own.
    fn widgets_of(document: &Document) -> Widgets {
        Widgets::of(document, &Modules::default())
    }
    use crate::external::testing::offline;

    fn folder(name: &str, page: &str) -> Document {
        let dir = std::env::temp_dir().join(format!("devpage-{name}-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("README.md"), page).unwrap();
        std::fs::write(
            dir.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\n",
        )
        .unwrap();
        Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap()
    }

    #[tokio::test]
    async fn a_page_in_no_site_is_checked_as_a_doc() {
        let top = std::env::temp_dir().join(format!("devpage-no-site-{}", std::process::id()));
        let docs = top.join("docs");
        std::fs::create_dir_all(&docs).unwrap();
        std::fs::write(
            docs.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\n",
        )
        .unwrap();
        std::fs::write(docs.join("README.md"), "# Docs\n\n[repo](../README.md)\n").unwrap();
        std::fs::write(
            top.join("README.md"),
            "# Repo\n\n## Topics\n\n- [Contributing](CONTRIBUTING.md) — how.\n",
        )
        .unwrap();
        std::fs::write(top.join("CONTRIBUTING.md"), "# Contributing").unwrap();
        let site = Document::load(&docs, &ServedFolder::new(&top).unwrap()).unwrap();
        let found: Vec<String> = document(&opened(&site), &designs_of(&site), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        assert!(found.is_empty(), "{found:#?}");
    }

    #[tokio::test]
    async fn topics_are_checked_against_the_pages_own_site() {
        let doc = folder("sibling-topics", "# Home\n\n[other](o2/devpage.yml)\n");
        let o2 = doc.base.join("o2");
        std::fs::create_dir_all(o2.join("x")).unwrap();
        std::fs::write(o2.join("x/p.md"), "# P").unwrap();
        std::fs::write(doc.base.join("outside.md"), "# Outside").unwrap();
        std::fs::write(
            o2.join("devpage.yml"),
            "kind: site\ntitle: O\nroot: README.md\n",
        )
        .unwrap();
        std::fs::write(
            o2.join("README.md"),
            "# O\n\n## Topics\n\n- [P](x/p.md) — inside.\n- [Out](../outside.md) — not.\n",
        )
        .unwrap();
        let found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(found.len(), 1, "{found:#?}");
        assert!(
            found[0].starts_with("o2/README.md:6: Topics entry ../outside.md"),
            "{found:#?}"
        );
    }

    #[tokio::test]
    async fn a_heading_in_a_doc_is_checked_against_the_ids_it_renders() {
        let doc = folder(
            "doc-fragment",
            "# Home\n\n[real](d/devpage.yml#c1--real) [chapter](d/devpage.yml#c2) [none](d/devpage.yml#nosuch) [bare](d/devpage.yml#real)\n",
        );
        let d = doc.base.join("d");
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(d.join("c1.md"), "# One\n\n## Real\n").unwrap();
        std::fs::write(d.join("c2.md"), "# Two\n").unwrap();
        std::fs::write(
            d.join("devpage.yml"),
            "kind: doc\ntitle: D\nchapters: [c1.md, c2.md]\n",
        )
        .unwrap();
        let found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(
            found,
            vec![
                "README.md:3: broken link d/devpage.yml#nosuch — no heading #nosuch".to_string(),
                "README.md:3: broken link d/devpage.yml#real — no heading #real".to_string(),
            ],
            "{found:#?}"
        );
    }

    /// A link into another page — a Markdown file or a doc — must land on an
    /// id that page renders: `devpage check` and the preview say so alike.
    #[tokio::test]
    async fn a_broken_cross_page_anchor_is_a_problem_in_check_and_the_preview() {
        let doc = folder(
            "cross-anchor",
            "# Home\n\n[ok](other.md#there) [gone](other.md#nowhere)\n\n[ok](d/doc.yml#c1--real) [gone](d/doc.yml#nowhere)\n",
        );
        std::fs::write(doc.base.join("other.md"), "# Other\n\n## There\n").unwrap();
        let d = doc.base.join("d");
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(d.join("c1.md"), "# One\n\n## Real\n").unwrap();
        std::fs::write(d.join("c2.md"), "# Two\n").unwrap();
        std::fs::write(
            d.join("doc.yml"),
            "kind: doc\ntitle: D\nchapters: [c1.md, c2.md]\n",
        )
        .unwrap();
        let expected = [
            "README.md:3: broken link other.md#nowhere — no heading #nowhere",
            "README.md:5: broken link d/doc.yml#nowhere — no heading #nowhere",
        ];
        let checked: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(checked, expected, "{checked:#?}");
        let previewed: Vec<String> = preview(&doc, &[doc.base.join("README.md")])
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(previewed, expected, "{previewed:#?}");
    }

    /// A heading is one the linked page shows: its widgets' tags expanded —
    /// a system widget's and its own site's — and an unknown tag's content
    /// not shown.
    #[tokio::test]
    async fn a_link_lands_on_a_heading_as_its_page_shows_it_widgets_expanded() {
        let doc = folder(
            "widget-anchor",
            "# Home\n\n[a](other.md#one) [b](other.md#two) [c](other.md#boxed) \
             [d](other.md#hidden) [e](d/doc.yml#c1--inside) [f](#here)\n\n\
             <Steps>\n## Here\n</Steps>\n",
        );
        std::fs::write(
            doc.base.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
        )
        .unwrap();
        std::fs::create_dir_all(doc.base.join("widgets")).unwrap();
        std::fs::write(
            doc.base.join("widgets/Box.tsx"),
            "export default function Box({ children }) { return children; }\n",
        )
        .unwrap();
        std::fs::write(
            doc.base.join("other.md"),
            "# Other\n\n<Steps>\n## One\n## Two\n</Steps>\n\n<Box>\n## Boxed\n</Box>\n\n\
             <Nope>\n## Hidden\n</Nope>\n",
        )
        .unwrap();
        let d = doc.base.join("d");
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(d.join("c1.md"), "# One\n\n<Steps>\n## Inside\n</Steps>\n").unwrap();
        std::fs::write(d.join("c2.md"), "# Two\n").unwrap();
        std::fs::write(
            d.join("doc.yml"),
            "kind: doc\ntitle: D\nchapters: [c1.md, c2.md]\n",
        )
        .unwrap();
        let doc = Document::load(&doc.path(), &doc.served).unwrap();
        let broken = "README.md:3: broken link other.md#hidden — no heading #hidden";
        let checked: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(
            checked,
            [broken, "other.md:12: <Nope> is not a widget"],
            "{checked:#?}"
        );
        let previewed: Vec<String> = preview(&doc, &[doc.base.join("README.md")])
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(previewed, [broken], "{previewed:#?}");
    }

    #[tokio::test]
    async fn a_slide_number_must_be_one_the_deck_has() {
        let doc = folder(
            "deck-number",
            "# Home\n\n[two](deck/devpage.yml#2) [nine](deck/devpage.yml#9) [word](deck/devpage.yml#intro)\n",
        );
        std::fs::create_dir_all(doc.base.join("deck")).unwrap();
        std::fs::write(doc.base.join("deck/a.md"), "# A").unwrap();
        std::fs::write(doc.base.join("deck/b.md"), "# B").unwrap();
        std::fs::write(
            doc.base.join("deck/devpage.yml"),
            "kind: slides\ntitle: D\nslides: [a.md, b.md]\n",
        )
        .unwrap();
        let found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(
            found,
            vec![
                "README.md:3: broken link deck/devpage.yml#9 — the deck has 2 slides".to_string(),
                "README.md:3: broken link deck/devpage.yml#intro — the deck has 2 slides"
                    .to_string(),
            ],
            "{found:#?}"
        );
    }

    #[tokio::test]
    async fn notes_belong_on_a_slide_once() {
        let doc = folder(
            "notes",
            "# Home\n\n[deck](deck/devpage.yml) [page](page.md) [slide](deck/a.md)\n",
        );
        std::fs::create_dir_all(doc.base.join("deck")).unwrap();
        std::fs::write(
            doc.base.join("deck/a.md"),
            "# A\n\n<Notes>one</Notes>\n\n<Notes>two</Notes>\n",
        )
        .unwrap();
        std::fs::write(doc.base.join("deck/b.md"), "# B\n\n<Notes>fine</Notes>\n").unwrap();
        std::fs::write(
            doc.base.join("deck/devpage.yml"),
            "kind: slides\ntitle: D\nslides: [a.md, b.md]\n",
        )
        .unwrap();
        std::fs::write(doc.base.join("page.md"), "# Page\n\n<Notes>lost</Notes>\n").unwrap();
        let mut found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        found.sort();
        assert_eq!(
            found,
            vec![
                "deck/a.md:5: a second <Notes> on one slide".to_string(),
                "page.md:3: <Notes> is only for a slide".to_string(),
            ],
            "{found:#?}"
        );
        // The preview: a deck's slides, and a page of the site.
        let deck = Document::load(
            &doc.base.join("deck/devpage.yml"),
            &ServedFolder::new(&doc.base).unwrap(),
        )
        .unwrap();
        let shown: Vec<String> = preview(&deck, &pages(&deck))
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(shown, vec!["deck/a.md:5: a second <Notes> on one slide"]);
        let shown: Vec<String> = preview(&doc, &[doc.base.join("page.md")])
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(shown, vec!["page.md:3: <Notes> is only for a slide"]);
    }

    #[tokio::test]
    async fn unclosed_notes_are_a_problem() {
        let doc = folder("unclosed-notes", "# Home\n\n[deck](deck/devpage.yml)\n");
        std::fs::create_dir_all(doc.base.join("deck")).unwrap();
        std::fs::write(
            doc.base.join("deck/a.md"),
            "# A\n\n<Notes>\nSay this.\n</Note>\n",
        )
        .unwrap();
        std::fs::write(
            doc.base.join("deck/devpage.yml"),
            "kind: slides\ntitle: D\nslides: [a.md]\n",
        )
        .unwrap();
        let found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        let expected = vec!["deck/a.md:3: a <Notes> without its </Notes>".to_string()];
        assert_eq!(found, expected, "{found:#?}");
        let deck = Document::load(
            &doc.base.join("deck/devpage.yml"),
            &ServedFolder::new(&doc.base).unwrap(),
        )
        .unwrap();
        let shown: Vec<String> = preview(&deck, &pages(&deck))
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(shown, expected);
    }

    #[tokio::test]
    async fn a_broken_linked_document_is_named_by_its_address() {
        let doc = folder("linked-relative", "# Home\n\n[plan](plan/devpage.yml)\n");
        std::fs::create_dir_all(doc.base.join("plan")).unwrap();
        std::fs::write(
            doc.base.join("plan/devpage.yml"),
            "kind: doc\ntitle: P\nchapters: [missing.md]\n",
        )
        .unwrap();
        let found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(found.len(), 1, "{found:#?}");
        assert!(
            !found[0].contains(&doc.served.path().display().to_string()),
            "{found:#?}"
        );
        assert!(found[0].contains("in plan/devpage.yml"), "{found:#?}");
    }

    /// The problems a fresh preview finds at once.
    fn preview(doc: &Document, pages: &[PathBuf]) -> Vec<Problem> {
        Preview::new(offline(), Arc::new(Recorder::default())).problems(
            &super::tests::opened(doc),
            doc,
            &widgets_of(doc),
            &designs_of(doc),
            &rendered(doc, pages),
        )
    }

    /// A reporter that keeps what it is told, for tests.
    #[derive(Default)]
    struct Recorder(Mutex<Vec<String>>);

    impl Report for Recorder {
        fn problem(&self, problem: &Problem) {
            self.0.lock().unwrap().push(problem.to_string());
        }
    }

    #[test]
    fn the_preview_reports_each_problem_once_to_its_reporter() {
        let doc = folder("preview-report", "# Home\n\n[gone](gone.md)\n");
        let recorder = Arc::new(Recorder::default());
        let preview = Preview::new(offline(), recorder.clone());
        let pages = rendered(&doc, &[doc.base.join("README.md")]);
        assert_eq!(
            preview
                .problems(
                    &super::tests::opened(&doc),
                    &doc,
                    &widgets_of(&doc),
                    &designs_of(&doc),
                    &pages,
                )
                .len(),
            1
        );
        assert_eq!(
            preview
                .problems(
                    &super::tests::opened(&doc),
                    &doc,
                    &widgets_of(&doc),
                    &designs_of(&doc),
                    &pages,
                )
                .len(),
            1
        );
        assert_eq!(
            *recorder.0.lock().unwrap(),
            ["README.md:3: broken link gone.md — no such file"]
        );
    }

    #[test]
    fn a_preview_of_files_that_never_change_checks_each_page_once() {
        let doc = folder(
            "preview-once",
            "# Home\n\n[gone](gone.md) and [heading](README.md#nope)\n",
        );
        let preview = Preview::once(offline(), Arc::new(Recorder::default()));
        let problems = |files: &[PathBuf]| {
            preview.problems(
                &super::tests::opened(&doc),
                &doc,
                &widgets_of(&doc),
                &designs_of(&doc),
                &rendered(&doc, files),
            )
        };
        let pages = [doc.base.join("README.md")];
        let first = problems(&pages);
        assert_eq!(first.len(), 2, "{first:#?}");
        // Fixed on disk, which a version never is: the kept answer shows it
        // was not checked again.
        std::fs::write(doc.base.join("README.md"), "# Home\n").unwrap();
        for _ in 0..9 {
            assert_eq!(problems(&pages), first);
        }
        // Another page is checked on its own.
        std::fs::write(doc.base.join("two.md"), "# Two\n\n[gone](gone.md)\n").unwrap();
        assert_eq!(problems(&[doc.base.join("two.md")]).len(), 1);
    }

    #[test]
    fn a_preview_of_files_that_change_checks_on_every_view() {
        let doc = folder("preview-every", "# Home\n\n[gone](gone.md)\n");
        let preview = Preview::new(offline(), Arc::new(Recorder::default()));
        let problems = |files: &[PathBuf]| {
            preview.problems(
                &super::tests::opened(&doc),
                &doc,
                &widgets_of(&doc),
                &designs_of(&doc),
                &rendered(&doc, files),
            )
        };
        let pages = [doc.base.join("README.md")];
        assert_eq!(problems(&pages).len(), 1);
        std::fs::write(doc.base.join("README.md"), "# Home\n").unwrap();
        assert!(problems(&pages).is_empty());
    }

    #[tokio::test]
    async fn check_reports_the_navbar_once_and_follows_its_links() {
        let doc = folder("navbar-check", "# Home\n\n[Two](two.md)\n");
        std::fs::write(doc.base.join("two.md"), "# Two\n").unwrap();
        // Reached only through the navbar, with a broken link of its own.
        std::fs::write(doc.base.join("only.md"), "# Only\n\n[gone](gone.md)\n").unwrap();
        std::fs::write(
            doc.base.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  Only (no-such-icon): only.md\n  Missing: missing.md\n",
        )
        .unwrap();
        let doc = Document::load(&doc.base, &doc.served).unwrap();
        let found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        let count = |text: &str| found.iter().filter(|p| p.contains(text)).count();
        assert_eq!(count("navbar: no icon named no-such-icon"), 1, "{found:#?}");
        assert_eq!(count("navbar: missing.md — no such file"), 1, "{found:#?}");
        assert_eq!(count("only.md:3: broken link gone.md"), 1, "{found:#?}");
    }

    #[tokio::test]
    async fn check_reports_a_missing_logo_once() {
        let doc = folder("logo-check", "# Home\n\n[Two](two.md)\n");
        std::fs::write(doc.base.join("two.md"), "# Two\n").unwrap();
        std::fs::write(
            doc.base.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\nlogo: gone.svg\n",
        )
        .unwrap();
        let doc = Document::load(&doc.base, &doc.served).unwrap();
        let found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        let count = found
            .iter()
            .filter(|p| p.contains("logo: gone.svg — no such file"))
            .count();
        assert_eq!(count, 1, "{found:#?}");
    }

    #[tokio::test]
    async fn widget_problems_are_reported_by_check() {
        let doc = folder(
            "widget-problems",
            "# Home\n\n<Nope />\n\n<Callout>fine</Callout>\n\n[Two](two.md)\n",
        );
        std::fs::write(
            doc.base.join("two.md"),
            "# Two\n\n<Callout>also</Callout>\n",
        )
        .unwrap();
        std::fs::create_dir_all(doc.base.join("widgets")).unwrap();
        std::fs::write(
            doc.base.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
        )
        .unwrap();
        std::fs::write(
            doc.base.join("widgets/Callout.tsx"),
            "export default () => null;",
        )
        .unwrap();
        std::fs::write(doc.base.join("widgets/Broken.tsx"), "export default (").unwrap();
        // A helper that doesn't compile is a problem too.
        std::fs::write(doc.base.join("widgets/fmt.ts"), "export const x = ;").unwrap();
        let doc = Document::load(&doc.base, &doc.served).unwrap();
        let found: Vec<String> = document(&opened(&doc), &designs_of(&doc), None)
            .await
            .iter()
            .map(ToString::to_string)
            .collect();
        assert!(
            found
                .iter()
                .any(|p| p == "README.md:3: <Nope> is not a widget"),
            "{found:#?}"
        );
        assert!(
            found
                .iter()
                .any(|p| p.contains("widgets/Callout.tsx") && p.contains("system widget's name")),
            "{found:#?}"
        );
        assert!(
            found
                .iter()
                .any(|p| p.contains("widgets/Broken.tsx") && p.contains("does not compile")),
            "{found:#?}"
        );
        assert!(
            found
                .iter()
                .any(|p| p.contains("widgets/fmt.ts: does not compile: line 1:")),
            "{found:#?}"
        );
        assert!(
            !found.iter().any(|p| p.contains("<Callout> is not")),
            "{found:#?}"
        );
        // Two pages, but the widgets folder's problems are reported once.
        for once in ["Callout.tsx", "Broken.tsx", "fmt.ts"] {
            assert_eq!(
                found.iter().filter(|p| p.contains(once)).count(),
                1,
                "{once}: {found:#?}"
            );
        }
    }
}

#[cfg(test)]
mod documents {
    use super::tests::{designs_of, opened};
    use super::*;
    use crate::folder::ServedFolder;

    /// The top of the repository the core crate sits in.
    fn repository() -> PathBuf {
        Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/.."))
            .canonicalize()
            .unwrap()
    }

    #[test]
    fn the_fixture_doc_the_catalog_and_the_talk_have_no_broken_links() {
        for example in [
            "tests/fixtures/sync-design",
            "docs/talks/devpage",
            "docs/features",
        ] {
            let root = repository();
            let doc =
                Document::load(&root.join(example), &ServedFolder::new(&root).unwrap()).unwrap();
            let problems = internal(
                &opened(&doc),
                &designs_of(&doc),
                &doc,
                &mut Vec::new(),
                None,
            );
            assert!(problems.is_empty(), "{example}: {problems:#?}");
        }
    }

    /// devpage's own docs, from their root page: every internal link and
    /// anchor must hold. External links aren't checked, so no network.
    #[test]
    fn devpage_docs_have_no_broken_links() {
        let root = repository();
        let doc = Document::load(&root.join("docs"), &ServedFolder::new(&root).unwrap()).unwrap();
        let problems: Vec<String> = internal(
            &opened(&doc),
            &designs_of(&doc),
            &doc,
            &mut Vec::new(),
            None,
        )
        .iter()
        .map(ToString::to_string)
        .collect();
        assert!(problems.is_empty(), "{problems:#?}");
    }

    #[test]
    fn a_deck_is_drawn_from_what_its_slides_embed_and_not_what_they_link_to() {
        let dir = std::env::temp_dir().join(format!("devpage-drawn-from-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("talk")).unwrap();
        std::fs::create_dir_all(dir.join("img")).unwrap();
        let dir = dir.canonicalize().unwrap();
        let write = |file: &str, text: &str| std::fs::write(dir.join(file), text).unwrap();
        write(
            "talk/one.md",
            "# One\n\n![Dark](../screen.design.png?theme=dark)\n\n![Later](../img/later.png)\n\n![Other](../other.yml/1.png)\n\n![Top](/img/top.png)\n\n[Linked](../linked.md)\n\n<img src=\"https://example.com/x.png\">\n",
        );
        write(
            "talk/talk.yml",
            "kind: slides\ntitle: T\nslides: [one.md]\n",
        );
        write("screen.design", "<Frame width={10} height={10} />\n");
        write("img/top.png", "png");
        write("linked.md", "# Linked\n");
        write("other.md", "# Other\n\n![Back](talk/talk.yml/1.png)\n");
        write("other.yml", "kind: slides\ntitle: O\nslides: [other.md]\n");
        let served = ServedFolder::new(&dir).unwrap();
        let designs = Designs::new(&served);
        let files = drawn_from(
            &dir.join("talk/talk.yml"),
            &served,
            &designs,
            &Modules::default(),
        );
        let names: Vec<String> = files
            .iter()
            .map(|file| crate::folder::slashed(file.strip_prefix(&dir).unwrap()))
            .collect();
        assert_eq!(
            names,
            [
                "img/later.png",
                "img/top.png",
                "other.md",
                "other.yml",
                "screen.design",
                "talk/one.md",
                "talk/talk.yml",
            ]
        );
    }
}