devpage 0.2.2

Live documents from a repository: sites, docs and slides from Markdown, and UI designs drawn from code — with comments, link checking and PDF
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
//! The canvas in Chrome: painting on the GPU and the CPU against the server's
//! PNG, interactions, embedding and printing. They drive chrome-headless-shell;
//! run them with `cargo test -- --ignored`.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use chromiumoxide::Page;
use chromiumoxide::browser::Browser;
use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
use chromiumoxide::cdp::browser_protocol::page::{
    AddScriptToEvaluateOnNewDocumentParams, CaptureScreenshotParams, Viewport,
};
use chromiumoxide::layout::Point;
use futures::StreamExt;
use tokio::sync::broadcast;

use devpage_design::render::{self, Difference};

use crate::document::Document;
use crate::pdf::Profile;
use crate::server;

/// A screen of two buttons — Pay navigates, Sheet opens an overlay — a next
/// screen with a back button, and the overlay with a close button. Every box
/// is fixed, so the test knows where each one is.
fn designs(dir: &Path) {
    let files = [
        (
            "button.design",
            r##"<Frame props={{ label: "Button", fill: "#2563eb" }} width={200} height={40} fill={fill} radius={8} layout="row" align="center" justify="center">
  <Text size={16} weight={600} color="#ffffff">{label}</Text>
</Frame>"##,
        ),
        (
            "screen.design",
            r##"import Button from "./button.design"
<Frame width={400} height={300} fill="#f8fafc" layout="column" padding={20} gap={20}>
  <Button label="Pay" onClick="navigate ./next.design" />
  <Button label="Sheet" fill="#16a34a" onClick="overlay ./sheet.design" />
  <Frame width={360} height={100} fill="#e2e8f0" radius={12} shadow={{ y: 4, blur: 12, color: "#0f172a33" }} />
</Frame>"##,
        ),
        (
            "next.design",
            r##"import Button from "./button.design"
<Frame width={400} height={300} fill="#fef3c7" layout="column" padding={20}>
  <Button label="Back" onClick="back" />
</Frame>"##,
        ),
        (
            "sheet.design",
            r##"import Button from "./button.design"
<Frame width={240} height={100} fill="#ffffff" layout="column" padding={20}>
  <Button label="Close" fill="#dc2626" onClick="close" />
</Frame>"##,
        ),
    ];
    for (name, source) in files {
        std::fs::write(dir.join(name), source).unwrap();
    }
}

fn folder(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("devpage-canvas-{}-{name}", std::process::id()));
    std::fs::remove_dir_all(&dir).ok();
    std::fs::create_dir_all(&dir).unwrap();
    let dir = dir.canonicalize().unwrap();
    designs(&dir);
    dir
}

/// Serves `dir`, entered at `entry`; returns its address.
async fn serve(dir: &Path, entry: &str) -> String {
    let document = Arc::new(Document::load(&dir.join(entry), dir).unwrap());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let (changes, _) = broadcast::channel(16);
    let router = server::router(document, changes, Some(server::Identity::Local("T".into())));
    tokio::spawn(async move { axum::serve(listener, router).await.ok() });
    format!("http://{address}")
}

/// Serves `dir`, entered at `entry`, and hands back its design store, so a
/// test can tell it about a saved file as the watcher would.
async fn serve_designs(dir: &Path, entry: &str) -> (String, super::Designs) {
    let document = Arc::new(Document::load(&dir.join(entry), dir).unwrap());
    let designs = super::Designs::new(dir.to_path_buf());
    let changes = broadcast::channel(16).0;
    let router = server::router_with_index(
        Arc::new(crate::document::Entry::new(document)),
        Arc::new(crate::index::Index::build(dir)),
        designs.clone(),
        changes.clone(),
        Some(server::Identity::Local("T".into())),
        crate::slide_png::Shots::new(&changes),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    tokio::spawn(async move { axum::serve(listener, router).await.ok() });
    (format!("http://{address}"), designs)
}

/// A headless Chrome with WebGPU. chrome-headless-shell keeps its GPU
/// process off unless `enable-gpu` is passed; with it, WebGPU gets the real
/// adapter and screenshots include the WebGPU canvas as the reader sees it,
/// composited — without it they hold black where the canvas is. chromiumoxide
/// adds the `--` itself.
async fn chrome() -> (Browser, tokio::task::JoinHandle<()>, Profile) {
    let profile = Profile::new();
    let config = profile
        .chrome()
        .await
        .unwrap()
        .arg("enable-unsafe-webgpu")
        .arg("enable-gpu");
    let (browser, mut handler) = Browser::launch(config.build().unwrap()).await.unwrap();
    let events = tokio::spawn(async move { while handler.next().await.is_some() {} });
    (browser, events, profile)
}

async fn eval<T: serde::de::DeserializeOwned>(page: &Page, js: &str) -> T {
    page.evaluate(js).await.unwrap().into_value().unwrap()
}

/// Waits until `js` is true, for up to 20 seconds.
async fn until(page: &Page, js: &str) {
    for _ in 0..200 {
        if page
            .evaluate(js)
            .await
            .ok()
            .and_then(|v| v.into_value::<bool>().ok())
            .unwrap_or(false)
        {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    panic!("timed out waiting for {js}");
}

/// Where a design pixel is on the screen: the canvas's view, as the design
/// script records it, from the canvas `selector`.
async fn on_screen(page: &Page, selector: &str, x: f64, y: f64) -> Point {
    let [zoom, vx, vy, left, top]: [f64; 5] = eval(
        page,
        &format!(
            "(() => {{ const c = document.querySelector('{selector}'); const b = c.getBoundingClientRect(); \
             return [...c.dataset.view.split(',').map(Number), b.left, b.top]; }})()"
        ),
    )
    .await;
    Point::new(left + vx + x * zoom, top + vy + y * zoom)
}

/// The design's drawing, `width` × `height` pixels, on the canvas page and
/// `margin` pixels around it, as a PNG.
async fn screenshot(page: &Page, width: f64, height: f64, margin: f64) -> Vec<u8> {
    let at = on_screen(page, "canvas.design", -margin, -margin).await;
    page.screenshot(
        CaptureScreenshotParams::builder()
            .clip(Viewport {
                x: at.x,
                y: at.y,
                width: width + 2.0 * margin,
                height: height + 2.0 * margin,
                scale: 1.0,
            })
            .build(),
    )
    .await
    .unwrap()
}

/// The color on the screen at `at`, as `[r, g, b]`.
/// Waits until the screen pixel `at` is `color`, for up to 20 seconds: a
/// navigation opens a stream and paints when its scene arrives, which takes
/// as long as the machine's load makes it.
async fn until_pixel(page: &Page, at: Point, color: [u8; 3]) {
    let mut last = [0; 3];
    for _ in 0..200 {
        last = pixel(page, at).await;
        if last == color {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    panic!("timed out waiting for {color:?} at {at:?}, last {last:?}");
}

async fn pixel(page: &Page, at: Point) -> [u8; 3] {
    let bytes = page
        .screenshot(
            CaptureScreenshotParams::builder()
                .clip(Viewport {
                    x: at.x.floor(),
                    y: at.y.floor(),
                    width: 1.0,
                    height: 1.0,
                    scale: 1.0,
                })
                .build(),
        )
        .await
        .unwrap();
    let bytes = serde_json::to_string(&bytes).unwrap();
    eval(
        page,
        &format!(
            "(async () => {{
              const bitmap = await createImageBitmap(new Blob([new Uint8Array({bytes})], {{ type: 'image/png' }}));
              const c = new OffscreenCanvas(1, 1);
              const ctx = c.getContext('2d');
              ctx.drawImage(bitmap, 0, 0);
              return [...ctx.getImageData(0, 0, 1, 1).data.slice(0, 3)];
            }})()"
        ),
    )
    .await
}

/// How the screenshot `shot` differs from the server's PNG at `png`, laid over
/// the page's background as the screen shows it and with `margin` pixels of
/// that background around it — compared by the engine's own rule, so the test
/// and the constraint can't drift apart. The margin is where a surface that
/// drew more than the drawing would show it.
async fn difference(
    page: &Page,
    address: &str,
    shot: &[u8],
    png: &str,
    margin: usize,
) -> Option<Difference> {
    let background: [f64; 3] = eval(
        page,
        "getComputedStyle(document.body).backgroundColor.match(/[\\d.]+/g).slice(0, 3).map(Number)",
    )
    .await;
    let served = reqwest::get(format!("{address}{png}"))
        .await
        .unwrap()
        .bytes()
        .await
        .unwrap();
    let (drawing, width, height) = render::pixels(&served).unwrap();
    let (width, height) = (width as usize, height as usize);
    let outer = width + 2 * margin;
    let page_color = [
        background[0] as u8,
        background[1] as u8,
        background[2] as u8,
        255,
    ];
    let mut b = page_color.repeat(outer * (height + 2 * margin));
    for y in 0..height {
        for x in 0..width {
            let px = &drawing[4 * (y * width + x)..][..4];
            let alpha = px[3] as f64 / 255.0;
            let to = &mut b[4 * ((y + margin) * outer + x + margin)..][..4];
            for k in 0..3 {
                to[k] = (px[k] as f64 * alpha + background[k] * (1.0 - alpha)).round() as u8;
            }
        }
    }
    let (mut a, _, _) = render::pixels(shot).unwrap();
    for px in a.chunks_mut(4) {
        px[3] = 255;
    }
    render::compare(&a, &b, outer)
}

/// Each example design on the canvas page matches the server's PNG of it
/// within the engine's tolerance: the CPU canvas is that very painting, the
/// GPU canvas another rasterizer of the same display list.
async fn the_examples_match_their_pngs(webgpu: bool) {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let address = serve(root, "docs/designs/checkout/checkout.design").await;
    let paths = ["button", "checkout", "confirmation", "details"]
        .map(|name| format!("/docs/designs/checkout/{name}.design"));
    canvases_match_their_pngs(&address, &paths, webgpu).await;
}

/// Each design at `paths` on the canvas page, in each theme, on the GPU or
/// the CPU, matches the server's PNG of it within the engine's tolerance.
async fn canvases_match_their_pngs(address: &str, paths: &[String], webgpu: bool) {
    let (mut browser, events, _profile) = chrome().await;
    let mut failures = Vec::new();
    for (theme, path) in ["light", "dark"]
        .into_iter()
        .flat_map(|theme| paths.iter().map(move |path| (theme, path)))
    {
        let name = path.as_str();
        let page = browser.new_page("about:blank").await.unwrap();
        // Room for the tallest example at 100%, at one device pixel per pixel.
        page.execute(SetDeviceMetricsOverrideParams::new(1280, 1000, 1.0, false))
            .await
            .unwrap();
        if !webgpu {
            // A browser without WebGPU, from the page's first script on.
            page.execute(AddScriptToEvaluateOnNewDocumentParams::new(
                "delete Navigator.prototype.gpu;",
            ))
            .await
            .unwrap();
        }
        page.goto(format!("{address}{path}?theme={theme}"))
            .await
            .unwrap();
        until(
            &page,
            "document.querySelector('canvas.design')?.dataset.painted === 'true'",
        )
        .await;
        let backend: String = eval(
            &page,
            "document.querySelector('canvas.design').dataset.backend",
        )
        .await;
        assert_eq!(backend, if webgpu { "gpu" } else { "cpu" });
        let [zoom, width, height]: [f64; 3] = eval(
            &page,
            "(() => { const c = document.querySelector('canvas.design');              return [Number(c.dataset.view.split(',')[0]), ...c.dataset.size.split(',').map(Number)]; })()",
        )
        .await;
        assert_eq!(zoom, 1.0, "{name} isn't shown at 100%");
        // Let the GPU's frame reach the screen.
        tokio::time::sleep(Duration::from_millis(300)).await;
        const MARGIN: usize = 24;
        let shot = screenshot(&page, width, height, MARGIN as f64).await;
        let d = difference(
            &page,
            address,
            &shot,
            &format!("{path}.png?theme={theme}"),
            MARGIN,
        )
        .await;
        eprintln!("{backend} {theme} {name}: {d:?}");
        if !d.is_some_and(|d| d.within_tolerance()) {
            failures.push(format!("{backend} {theme} {name}: {d:?}"));
        }
        page.close().await.ok();
    }
    assert!(failures.is_empty(), "{failures:#?}");
    browser.close().await.ok();
    events.abort();
}

/// A design that mixes families — a variable font at weights from 300 to
/// 900, a folder of static faces, and a paragraph that wraps — draws
/// on the canvas, on the GPU and on the CPU, as the server's PNG: the same
/// line breaks, the same glyphs.
async fn font_files_match_their_pngs(webgpu: bool) {
    let dir = folder(if webgpu { "fonts-gpu" } else { "fonts-cpu" });
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    std::fs::create_dir_all(dir.join("fonts/Static")).unwrap();
    std::fs::copy(
        root.join("docs/designs/checkout/fonts/Figtree/Figtree-Variable.ttf"),
        dir.join("fonts/Figtree.ttf"),
    )
    .unwrap();
    for face in ["Regular", "Bold"] {
        std::fs::copy(
            root.join(format!("design/fonts/Inter-{face}.ttf")),
            dir.join(format!("fonts/Static/Inter-{face}.ttf")),
        )
        .unwrap();
    }
    std::fs::write(
        dir.join("themes.yml"),
        "kind: themes\nfonts:\n  figtree: ./fonts/Figtree.ttf\n  inter: ./fonts/Static\nlight:\n  bg: \"#ffffff\"\n  text: \"#0f172a\"\ndark:\n  bg: \"#0f172a\"\n  text: \"#f1f5f9\"\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("type.design"),
        r#"<Frame width={360} fill={theme.bg} layout="column" padding={16} gap={8}>
  <Text font="figtree" size={28} weight={900} color={theme.text}>Heavy headline</Text>
  <Text font="figtree" size={20} weight={300} color={theme.text}>Light subtitle</Text>
  <Text font="figtree" width="fill" size={15} lineHeight={1.5} color={theme.text}>Washed linen with a relaxed fit, cut wide through the body and finished by hand. Machine wash cold, tumble dry low.</Text>
  <Text font="inter" weight={700} color={theme.text}>Static bold face</Text>
  <Text color={theme.text}>Inter, embedded</Text>
</Frame>"#,
    )
    .unwrap();
    let address = serve(&dir, "type.design").await;
    canvases_match_their_pngs(&address, &["/type.design".to_string()], webgpu).await;
}

#[tokio::test]
#[ignore]
async fn font_files_on_the_gpu_match_the_png() {
    font_files_match_their_pngs(true).await;
}

#[tokio::test]
#[ignore]
async fn font_files_on_the_cpu_match_the_png() {
    font_files_match_their_pngs(false).await;
}

#[tokio::test]
#[ignore]
async fn the_canvas_on_the_gpu_matches_the_png() {
    the_examples_match_their_pngs(true).await;
}

#[tokio::test]
#[ignore]
async fn the_canvas_on_the_cpu_matches_the_png() {
    the_examples_match_their_pngs(false).await;
}

#[tokio::test]
#[ignore]
async fn a_click_navigates_back_returns_and_an_overlay_opens_and_closes() {
    let dir = folder("click");
    let address = serve(&dir, "screen.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/screen.design").as_str())
        .await
        .unwrap();
    let painted = "document.querySelector('body > canvas.design')?.dataset.painted === 'true'";
    until(&page, painted).await;

    // The pointer is a hand over a button, and not beside it.
    let pay = on_screen(&page, "body > canvas.design", 120.0, 40.0).await;
    page.move_mouse(pay).await.unwrap();
    until(
        &page,
        "document.querySelector('body > canvas.design').style.cursor === 'pointer'",
    )
    .await;

    // Pay navigates: the address changes and the next design is drawn.
    page.click(pay).await.unwrap();
    until(&page, "location.pathname === '/next.design'").await;
    until(&page, painted).await;
    // Back, on the next screen, returns.
    let back = on_screen(&page, "body > canvas.design", 120.0, 40.0).await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    page.click(back).await.unwrap();
    until(&page, "location.pathname === '/screen.design'").await;

    // Sheet opens the overlay, centered; its Close closes it.
    tokio::time::sleep(Duration::from_millis(500)).await;
    let sheet = on_screen(&page, "body > canvas.design", 120.0, 100.0).await;
    page.click(sheet).await.unwrap();
    until(
        &page,
        "document.querySelector('.design-overlay canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    let close = on_screen(&page, ".design-overlay canvas.design", 120.0, 40.0).await;
    page.click(close).await.unwrap();
    until(&page, "!document.querySelector('.design-overlay')").await;
    assert_eq!(
        eval::<String>(&page, "location.pathname").await,
        "/screen.design"
    );
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn an_interaction_inside_an_instance_from_another_folder_opens_its_own_target() {
    let dir = folder("nested");
    for (name, source) in [
        (
            "lib/tile.design",
            r##"<Frame width={200} height={40} fill="#2563eb" onClick="navigate ./far.design" />"##,
        ),
        (
            "lib/far.design",
            r##"<Frame width={400} height={300} fill="#fef3c7" />"##,
        ),
        (
            "app/home.design",
            r##"import Tile from "../lib/tile.design"
<Frame width={400} height={300} fill="#f8fafc" layout="column" padding={20}>
  <Tile />
</Frame>"##,
        ),
    ] {
        let path = dir.join(name);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, source).unwrap();
    }
    let address = serve(&dir, "app/home.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/app/home.design").as_str())
        .await
        .unwrap();
    let painted = "document.querySelector('body > canvas.design')?.dataset.painted === 'true'";
    until(&page, painted).await;

    // The tile's path is beside the tile's file, not beside the screen's.
    let tile = on_screen(&page, "body > canvas.design", 120.0, 40.0).await;
    page.click(tile).await.unwrap();
    until(&page, "location.pathname === '/lib/far.design'").await;
    until(&page, painted).await;
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn an_embedded_design_draws_and_survives_a_page_edit() {
    let dir = folder("embed");
    std::fs::write(
        dir.join("page.md"),
        "# Page\n\nThe screen:\n\n![The screen](screen.design)\n",
    )
    .unwrap();
    let address = serve(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/page.md").as_str())
        .await
        .unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    // At its own size: the 400 × 300 screen is never enlarged to the page.
    let [width, height]: [f64; 2] = eval(
        &page,
        "(() => { const b = document.querySelector('canvas.design').getBoundingClientRect(); \
         return [b.width, b.height]; })()",
    )
    .await;
    assert_eq!([width, height], [400.0, 300.0]);

    // Clicking Pay navigates inside the embed, not the page: the next
    // design's yellow replaces the screen's grey.
    page.evaluate("document.querySelector('canvas.design').marked = true")
        .await
        .unwrap();
    // Beside the Pay button: the design's own background.
    let corner = on_screen(&page, "canvas.design", 300.0, 40.0).await;
    let grey = pixel(&page, corner).await;
    assert_eq!(grey, [0xf8, 0xfa, 0xfc]);
    let pay = on_screen(&page, "canvas.design", 120.0, 40.0).await;
    page.click(pay).await.unwrap();
    until_pixel(&page, corner, [0xfe, 0xf3, 0xc7]).await;
    assert_eq!(eval::<String>(&page, "location.pathname").await, "/page.md");

    // A page edit swaps the text and keeps the very same canvas.
    std::fs::write(
        dir.join("page.md"),
        "# Page\n\nThe screen, edited:\n\n![The screen](screen.design)\n",
    )
    .unwrap();
    page.evaluate("load(location.href)").await.unwrap();
    until(
        &page,
        "document.querySelector('article').textContent.includes('edited')",
    )
    .await;
    assert!(
        eval::<bool>(
            &page,
            "document.querySelector('canvas.design').marked === true"
        )
        .await
    );
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn a_doc_prints_its_embedded_design() {
    let dir = folder("print");
    std::fs::write(
        dir.join("doc.md"),
        "# Doc\n\n![The screen](screen.design)\n",
    )
    .unwrap();
    let document = Arc::new(Document::load(&dir.join("doc.md"), &dir).unwrap());
    let with = dir.join("with.pdf");
    crate::pdf::print(document, &with).await.unwrap();
    std::fs::write(dir.join("plain.md"), "# Doc\n\nNo design.\n").unwrap();
    let document = Arc::new(Document::load(&dir.join("plain.md"), &dir).unwrap());
    let without = dir.join("without.pdf");
    crate::pdf::print(document, &without).await.unwrap();
    // The painted canvas is an image in the PDF; the page without one has none.
    let images = |path: &Path| {
        let bytes = std::fs::read(path).unwrap();
        bytes.windows(13).filter(|w| w == b"/Subtype /Ima").count()
    };
    assert!(images(&with) > 0, "no image in the printed doc");
    assert_eq!(images(&without), 0);
}

#[tokio::test]
#[ignore]
async fn the_wheel_zooms_about_the_pointer_and_pans() {
    let dir = folder("zoom");
    let address = serve(&dir, "screen.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/screen.design").as_str())
        .await
        .unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    let view = || async {
        eval::<String>(
            &page,
            "document.querySelector('canvas.design').dataset.view",
        )
        .await
    };
    // Fit to the window: 400 × 300 at 100%, centered.
    let fitted = view().await;
    let [zoom, x, y]: [f64; 3] = serde_json::from_str(&format!("[{fitted}]")).unwrap();
    assert_eq!(zoom, 1.0);
    assert!(x > 0.0 && y > 0.0, "{fitted}");

    // ⌘ and the wheel zooms in, keeping the design point under the pointer.
    let pointer = on_screen(&page, "canvas.design", 100.0, 100.0).await;
    page.evaluate(format!(
        "document.querySelector('canvas.design').dispatchEvent(new WheelEvent('wheel', \
         {{ deltaY: -100, metaKey: true, clientX: {}, clientY: {}, bubbles: true, cancelable: true }}))",
        pointer.x, pointer.y
    ))
    .await
    .unwrap();
    until(
        &page,
        "document.querySelector('canvas.design').dataset.view.split(',')[0] > 2",
    )
    .await;
    let after = on_screen(&page, "canvas.design", 100.0, 100.0).await;
    assert!((after.x - pointer.x).abs() < 0.5 && (after.y - pointer.y).abs() < 0.5);

    // The wheel alone pans — recorded when the next frame paints, which a
    // busy machine can take a while to reach.
    let before: String = view().await;
    page.evaluate(
        "document.querySelector('canvas.design').dispatchEvent(new WheelEvent('wheel', \
         { deltaX: 40, deltaY: 0, bubbles: true, cancelable: true }))",
    )
    .await
    .unwrap();
    until(
        &page,
        &format!("document.querySelector('canvas.design').dataset.view !== '{before}'"),
    )
    .await;
    let panned = on_screen(&page, "canvas.design", 100.0, 100.0).await;
    assert!((panned.x - (after.x - 40.0)).abs() < 0.5);
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn an_undone_typo_clears_the_problems() {
    let dir = folder("undo");
    let (address, designs) = serve_designs(&dir, "screen.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/screen.design").as_str())
        .await
        .unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    let file = dir.join("screen.design");
    let good = std::fs::read_to_string(&file).unwrap();
    std::fs::write(&file, good.replace("<Button label", "<Button lable")).unwrap();
    designs.changed(&file);
    until(&page, "!!document.querySelector('.design-problems')").await;
    // Saved back as it was: the scene is the one the canvas already has.
    std::fs::write(&file, &good).unwrap();
    designs.changed(&file);
    until(&page, "!document.querySelector('.design-problems')").await;
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn a_deleted_design_comes_back_when_written_again() {
    let dir = folder("deleted");
    std::fs::write(
        dir.join("page.md"),
        "# Page\n\nThe next screen:\n\n![Next](next.design)\n",
    )
    .unwrap();
    let (address, designs) = serve_designs(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    for at in ["next.design", "page.md"] {
        let page = browser.new_page("about:blank").await.unwrap();
        // Count the watch calls the page makes.
        page.execute(AddScriptToEvaluateOnNewDocumentParams::new(
            "window.watchCalls = 0; const f = window.fetch; \
             window.fetch = (url, ...rest) => { if (String(url).includes('/Watch')) window.watchCalls++; return f(url, ...rest); };",
        ))
        .await
        .unwrap();
        page.goto(format!("{address}/{at}")).await.unwrap();
        until(
            &page,
            "document.querySelector('canvas.design')?.dataset.painted === 'true'",
        )
        .await;
        let file = dir.join("next.design");
        let source = std::fs::read_to_string(&file).unwrap();
        std::fs::remove_file(&file).unwrap();
        designs.changed(&file);
        until(&page, "!!document.querySelector('.design-problems')").await;
        let calls: u32 = eval(&page, "window.watchCalls").await;
        // Deleted, it isn't asked for again and again: the one stream stays
        // open for it. Long enough for three reconnects, were it reconnecting.
        tokio::time::sleep(Duration::from_millis(3500)).await;
        let later: u32 = eval(&page, "window.watchCalls").await;
        assert_eq!(later, calls, "{at}: the page kept reopening its stream");
        // The page fetched again — a branch switch touches every file — and
        // the design written back: it draws again, without a reload.
        if at == "page.md" {
            page.evaluate("load(location.href)").await.ok();
        }
        std::fs::write(&file, source).unwrap();
        designs.changed(&file);
        until(&page, "!document.querySelector('.design-problems')").await;
        page.close().await.ok();
    }
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn a_canvas_says_so_when_the_engine_does_not_load() {
    let dir = folder("no-engine");
    let address = serve(&dir, "screen.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser.new_page("about:blank").await.unwrap();
    // A browser that can't compile the module.
    page.execute(AddScriptToEvaluateOnNewDocumentParams::new(
        "const no = () => Promise.reject(new Error('no WebAssembly here')); \
         WebAssembly.instantiate = no; WebAssembly.instantiateStreaming = no;",
    ))
    .await
    .unwrap();
    page.goto(format!("{address}/screen.design")).await.unwrap();
    until(&page, "!!document.querySelector('.design-failed')").await;
    let text: String = eval(
        &page,
        "document.querySelector('.design-failed').textContent",
    )
    .await;
    assert!(text.contains("design engine didn't load"), "{text}");
    assert!(text.contains("no WebAssembly here"), "{text}");
    browser.close().await.ok();
    events.abort();
}

/// The canvas's CSS size and its gaps to the backdrop's content box, left and
/// right: `[width, height, left gap, right gap]`.
const EMBED_BOX: &str = "(() => { const c = document.querySelector('canvas.design'); \
    const s = c.parentElement; const st = getComputedStyle(s); \
    const b = c.getBoundingClientRect(); const o = s.getBoundingClientRect(); \
    return [b.width, b.height, \
      b.left - o.left - parseFloat(st.paddingLeft), \
      o.right - parseFloat(st.paddingRight) - b.right]; })()";

/// Opens `path` in a `width` × `height` window and waits for its design.
async fn embedded(
    browser: &mut Browser,
    address: &str,
    path: &str,
    width: i64,
    height: i64,
) -> Page {
    let page = browser.new_page("about:blank").await.unwrap();
    page.execute(SetDeviceMetricsOverrideParams::new(
        width, height, 1.0, false,
    ))
    .await
    .unwrap();
    page.goto(format!("{address}{path}")).await.unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    page
}

#[tokio::test]
#[ignore]
async fn an_embedded_design_is_its_own_size_centred_and_only_ever_scaled_down() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let dir = folder("own-size");
    std::fs::write(
        dir.join("page.md"),
        "# Page\n\n![The screen](screen.design)\n",
    )
    .unwrap();
    let address = serve(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;

    // A wide window: 400 × 300, as the design is, centred on its backdrop.
    let page = embedded(&mut browser, &address, "/page.md", 1280, 1000).await;
    let [w, h, left, right]: [f64; 4] = eval(&page, EMBED_BOX).await;
    assert_eq!([w, h], [400.0, 300.0]);
    assert!(
        left > 0.0 && (left - right).abs() <= 1.0,
        "{left} vs {right}"
    );
    assert!(
        eval::<String>(
            &page,
            "document.querySelector('canvas.design').dataset.view"
        )
        .await
        .starts_with("1,")
    );

    // A narrow window: scaled down to the backdrop's width, keeping its shape.
    let page = embedded(&mut browser, &address, "/page.md", 300, 1000).await;
    let [w, h, left, right]: [f64; 4] = eval(&page, EMBED_BOX).await;
    assert!(
        w < 300.0 && left >= 0.0 && right >= -0.5,
        "{w} {left} {right}"
    );
    assert!((h - w * 0.75).abs() <= 1.0, "{h} for {w}");

    // A short window: scaled down until the whole design is in view.
    let page = embedded(&mut browser, &address, "/page.md", 1280, 240).await;
    let [w, h, _, _]: [f64; 4] = eval(&page, EMBED_BOX).await;
    assert!(h <= 240.0 && (h - w * 0.75).abs() <= 1.0, "{w} × {h}");

    // The real example: the 390-wide checkout screen stays 390 wide in a doc.
    let address = serve(root, "docs/boxes/viewer/designs/README.md").await;
    let page = embedded(
        &mut browser,
        &address,
        "/docs/boxes/viewer/designs/README.md",
        1280,
        1000,
    )
    .await;
    let [w, _, left, right]: [f64; 4] = eval(&page, EMBED_BOX).await;
    assert_eq!(w, 390.0);
    assert!((left - right).abs() <= 1.0, "{left} vs {right}");
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn the_backdrops_link_opens_the_design_it_shows_on_its_canvas_page() {
    let dir = folder("open-link");
    std::fs::create_dir_all(dir.join("notes")).unwrap();
    std::fs::write(
        dir.join("notes/page.md"),
        "# Page\n\n![The screen](../screen.design)\n",
    )
    .unwrap();
    let address = serve(&dir, "notes/page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = embedded(&mut browser, &address, "/notes/page.md", 1280, 1000).await;
    let link = "document.querySelector('.design-embed a.design-open')";
    let theme: String = eval(&page, "document.documentElement.dataset.theme").await;
    assert_eq!(
        eval::<String>(&page, &format!("{link}.getAttribute('href')")).await,
        format!("/screen.design?theme={theme}")
    );
    // After a navigation inside the embed the link follows the design shown.
    let corner = on_screen(&page, "canvas.design", 300.0, 40.0).await;
    let pay = on_screen(&page, "canvas.design", 120.0, 40.0).await;
    page.click(pay).await.unwrap();
    until_pixel(&page, corner, [0xfe, 0xf3, 0xc7]).await;
    assert_eq!(
        eval::<String>(&page, &format!("{link}.getAttribute('href')")).await,
        format!("/next.design?theme={theme}")
    );
    page.evaluate(format!("{link}.click()")).await.unwrap();
    until(
        &page,
        "location.pathname === '/next.design' && document.body.classList.contains('design-page')",
    )
    .await;
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn a_small_design_is_not_enlarged_on_its_canvas_page() {
    let dir = folder("small");
    let address = serve(&dir, "button.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = embedded(&mut browser, &address, "/button.design", 1280, 1000).await;
    let view: String = eval(
        &page,
        "document.querySelector('canvas.design').dataset.view",
    )
    .await;
    let [zoom, x, y]: [f64; 3] = view
        .split(',')
        .map(|n| n.parse().unwrap())
        .collect::<Vec<_>>()
        .try_into()
        .unwrap();
    assert_eq!(zoom, 1.0);
    // Centred in the 1280 × 1000 window.
    assert_eq!(
        [x, y],
        [
            ((1280.0 - 200.0) / 2.0_f64).round(),
            ((1000.0 - 40.0) / 2.0_f64).round()
        ]
    );
    browser.close().await.ok();
    events.abort();
}

/// Counts the page's watch calls, and how many are still open: each call's
/// signal, until the page aborts it.
const WATCH_COUNTER: &str = "window.watches = []; const f = window.fetch; \
    window.fetch = (url, options = {}) => { \
      if (String(url).includes('/Watch')) window.watches.push(options.signal); \
      return f(url, options); };";

const OPEN_WATCHES: &str = "window.watches.filter((s) => s && !s.aborted).length";

/// A page embedding eight designs, each its own file.
fn eight(dir: &Path, name: &str) {
    let screen = std::fs::read_to_string(dir.join("screen.design")).unwrap();
    let mut page = String::from("# Eight\n\n");
    for n in 1..=8 {
        std::fs::write(dir.join(format!("s{n}.design")), &screen).unwrap();
        page.push_str(&format!("![Screen {n}](s{n}.design)\n\n"));
    }
    std::fs::write(dir.join(name), page).unwrap();
}

#[tokio::test]
#[ignore]
async fn eight_embedded_designs_paint_through_one_stream_and_the_page_still_loads() {
    let dir = folder("eight");
    eight(&dir, "page.md");
    let address = serve(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser.new_page("about:blank").await.unwrap();
    page.execute(AddScriptToEvaluateOnNewDocumentParams::new(WATCH_COUNTER))
        .await
        .unwrap();
    page.goto(format!("{address}/page.md")).await.unwrap();
    until(
        &page,
        "[...document.querySelectorAll('canvas.design')].filter((c) => c.dataset.painted === 'true').length === 8",
    )
    .await;
    assert_eq!(eval::<u32>(&page, OPEN_WATCHES).await, 1);

    // The page can still fetch: an edit swapped in, every canvas kept.
    page.evaluate("document.querySelectorAll('canvas.design').forEach((c) => c.marked = true)")
        .await
        .unwrap();
    let mut edited = std::fs::read_to_string(dir.join("page.md")).unwrap();
    edited.push_str("Edited.\n");
    std::fs::write(dir.join("page.md"), edited).unwrap();
    page.evaluate("load(location.href)").await.unwrap();
    until(
        &page,
        "document.querySelector('article').textContent.includes('Edited.')",
    )
    .await;
    assert_eq!(
        eval::<u32>(
            &page,
            "[...document.querySelectorAll('canvas.design')].filter((c) => c.marked).length"
        )
        .await,
        8
    );
    // The same designs: the stream wasn't reopened.
    assert_eq!(eval::<u32>(&page, "window.watches.length").await, 1);
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn a_doc_with_eight_embeds_prints_as_fast_as_one_with_one() {
    let dir = folder("print-eight");
    eight(&dir, "eight.md");
    std::fs::write(
        dir.join("one.md"),
        "# One\n\n![The screen](screen.design)\n",
    )
    .unwrap();
    let time = |name: &'static str| {
        let dir = dir.clone();
        async move {
            let document = Arc::new(Document::load(&dir.join(name), &dir).unwrap());
            let started = std::time::Instant::now();
            crate::pdf::print(document, &dir.join(format!("{name}.pdf")))
                .await
                .unwrap();
            started.elapsed()
        }
    };
    let one = time("one.md").await;
    let eight = time("eight.md").await;
    // Without one stream per page, the eighth design never painted and the
    // print waited out its 20 seconds.
    assert!(
        eight < one + Duration::from_secs(5),
        "eight embeds took {eight:?}, one took {one:?}"
    );
}

#[tokio::test]
#[ignore]
async fn leaving_the_last_design_in_place_closes_the_stream() {
    let dir = folder("leave");
    std::fs::write(
        dir.join("page.md"),
        "# Page\n\n![The screen](screen.design)\n\n[Plain](plain.md)\n",
    )
    .unwrap();
    std::fs::write(dir.join("plain.md"), "# Plain\n\nNo design.\n").unwrap();
    let address = serve(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser.new_page("about:blank").await.unwrap();
    page.execute(AddScriptToEvaluateOnNewDocumentParams::new(WATCH_COUNTER))
        .await
        .unwrap();
    page.goto(format!("{address}/page.md")).await.unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    assert_eq!(eval::<u32>(&page, OPEN_WATCHES).await, 1);
    page.evaluate("document.body.marked = true").await.unwrap();
    page.evaluate("[...document.querySelectorAll('article a')].find((a) => a.textContent === 'Plain').click()")
        .await
        .unwrap();
    until(
        &page,
        "document.querySelector('article').textContent.includes('No design.')",
    )
    .await;
    // In place, not a full load, and no watch stream left open.
    assert!(eval::<bool>(&page, "document.body.marked === true").await);
    until(&page, &format!("{OPEN_WATCHES} === 0")).await;
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn an_embed_with_problems_survives_a_page_refetch() {
    let dir = folder("embed-problems");
    std::fs::write(
        dir.join("page.md"),
        "# Page\n\n![The screen](screen.design)\n",
    )
    .unwrap();
    let (address, designs) = serve_designs(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/page.md").as_str())
        .await
        .unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    page.evaluate("document.querySelector('canvas.design').marked = true")
        .await
        .unwrap();
    let screen = std::fs::read_to_string(dir.join("screen.design")).unwrap();
    std::fs::write(
        dir.join("screen.design"),
        screen.replace("<Button label", "<Button lable"),
    )
    .unwrap();
    designs.changed(&dir.join("screen.design"));
    until(
        &page,
        "!!document.querySelector('.design-embed .design-problems')",
    )
    .await;
    page.evaluate("load(location.href)").await.unwrap();
    // Swapped in, and the canvas — with the problems bar before it — kept.
    until(
        &page,
        "document.querySelector('canvas.design')?.marked === true \
         && !!document.querySelector('.design-embed .design-problems')",
    )
    .await;
    browser.close().await.ok();
    events.abort();
}

/// A design that paints nothing over its 120 × 80 box, so the screen shows
/// whatever the canvas puts behind a design there.
const GLASS: &str = r##"<Frame width={120} height={80} fill="#00000000" />"##;

/// Waits until the screen pixel `inside` matches the pixel `outside`, for up
/// to 20 seconds; returns the color.
async fn until_same(page: &Page, inside: Point, outside: Point) -> [u8; 3] {
    let (mut a, mut b) = ([0; 3], [1; 3]);
    for _ in 0..200 {
        a = pixel(page, inside).await;
        b = pixel(page, outside).await;
        if a == b {
            return a;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    panic!("timed out: inside {a:?}, outside {b:?}");
}

#[tokio::test]
#[ignore]
async fn the_canvas_page_switches_theme_and_paints_behind_the_design_in_it() {
    let dir = folder("theme-page");
    std::fs::write(dir.join("glass.design"), GLASS).unwrap();
    let address = serve(&dir, "glass.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/glass.design").as_str())
        .await
        .unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    let inside = on_screen(&page, "canvas.design", 60.0, 40.0).await;
    let outside = on_screen(&page, "canvas.design", 60.0, 140.0).await;
    let before: String = eval(&page, "document.documentElement.dataset.theme").await;
    let first = until_same(&page, inside, outside).await;

    page.find_element(".theme-toggle")
        .await
        .unwrap()
        .click()
        .await
        .unwrap();
    let after: String = eval(&page, "document.documentElement.dataset.theme").await;
    assert_ne!(before, after);
    let second = until_same(&page, inside, outside).await;
    assert_ne!(first, second, "the background didn't change with the theme");

    // The choice is kept, under the same name the page script uses.
    page.reload().await.unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    assert_eq!(
        eval::<String>(&page, "document.documentElement.dataset.theme").await,
        after
    );
    browser.close().await.ok();
    events.abort();
}

/// A design in red in its light theme and in blue in its dark one.
fn themed(dir: &Path) {
    std::fs::write(
        dir.join("themes.yml"),
        "kind: themes\nlight:\n  bg: \"#ff0000\"\ndark:\n  bg: \"#0000ff\"\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("tile.design"),
        "<Frame width={120} height={80} fill={theme.bg} />",
    )
    .unwrap();
}

const RED: [u8; 3] = [255, 0, 0];
const BLUE: [u8; 3] = [0, 0, 255];

/// Opens a fresh tab whose remembered theme is `theme`.
async fn tab_in(browser: &mut Browser, theme: &str) -> Page {
    let page = browser.new_page("about:blank").await.unwrap();
    page.execute(SetDeviceMetricsOverrideParams::new(1280, 1000, 1.0, false))
        .await
        .unwrap();
    page.execute(AddScriptToEvaluateOnNewDocumentParams::new(format!(
        "try {{ if (!sessionStorage.getItem('set')) {{ localStorage.setItem('devpage-theme', '{theme}'); sessionStorage.setItem('set', '1'); }} }} catch {{}}"
    )))
    .await
    .unwrap();
    page
}

/// On a dark page a themed embed is drawn dark; its own switch turns only
/// it, design and backdrop, and is kept when the page switches; the Open
/// link carries the theme it shows; and a design that isn't themed has no
/// switch.
#[tokio::test]
#[ignore]
async fn an_embed_follows_its_page_and_its_own_switch_turns_only_it() {
    let dir = folder("theme-own");
    themed(&dir);
    std::fs::write(
        dir.join("page.md"),
        "# Page\n\n![One](tile.design)\n\n![Two](tile.design)\n\n![Plain](screen.design)\n",
    )
    .unwrap();
    let address = serve(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = tab_in(&mut browser, "dark").await;
    page.goto(format!("{address}/page.md")).await.unwrap();
    until(
        &page,
        "[...document.querySelectorAll('canvas.design')].every((c) => c.dataset.painted === 'true')",
    )
    .await;
    let one = on_screen(&page, r#"canvas.design[aria-label="One"]"#, 60.0, 40.0).await;
    let two = on_screen(&page, r#"canvas.design[aria-label="Two"]"#, 60.0, 40.0).await;
    until_pixel(&page, one, BLUE).await;
    until_pixel(&page, two, BLUE).await;
    let shown = "[...document.querySelectorAll('.design-theme')].map((b) => !b.hidden)";
    assert_eq!(eval::<Vec<bool>>(&page, shown).await, [true, true, false]);
    let backdrop = |label: &str| {
        format!("document.querySelector(\"canvas.design[aria-label='{label}']\").parentElement")
    };
    let backdrop_color =
        |label: &str| format!("getComputedStyle({}).backgroundColor", backdrop(label));
    let dark_backdrop: String = eval(&page, &backdrop_color("Two")).await;

    // The first embed's own switch: only it turns light, backdrop and all.
    page.evaluate(format!(
        "{}.querySelector('.design-theme').click()",
        backdrop("One")
    ))
    .await
    .unwrap();
    until_pixel(&page, one, RED).await;
    assert_eq!(pixel(&page, two).await, BLUE);
    assert_eq!(
        eval::<String>(&page, "document.documentElement.dataset.theme").await,
        "dark",
        "the page is as it was"
    );
    assert_ne!(
        eval::<String>(&page, &backdrop_color("One")).await,
        dark_backdrop
    );
    let href = |label: &str| {
        format!(
            "{}.querySelector('a.design-open').getAttribute('href')",
            backdrop(label)
        )
    };
    assert_eq!(
        eval::<String>(&page, &href("One")).await,
        "/tile.design?theme=light"
    );
    assert_eq!(
        eval::<String>(&page, &href("Two")).await,
        "/tile.design?theme=dark"
    );

    // The page switches to light and back: the second embed follows it, the
    // first stays where the reader put it.
    for (theme, two_color) in [("light", RED), ("dark", BLUE)] {
        page.find_element(".theme-toggle")
            .await
            .unwrap()
            .click()
            .await
            .unwrap();
        assert_eq!(
            eval::<String>(&page, "document.documentElement.dataset.theme").await,
            theme
        );
        until_pixel(&page, two, two_color).await;
        assert_eq!(pixel(&page, one).await, RED, "after the page went {theme}");
    }
    browser.close().await.ok();
    events.abort();
}

/// `?theme=` on the canvas page's address shows that theme for the view and
/// leaves the remembered choice alone.
#[tokio::test]
#[ignore]
async fn the_canvas_page_shows_the_theme_its_address_names() {
    let dir = folder("theme-address");
    themed(&dir);
    let address = serve(&dir, "tile.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = tab_in(&mut browser, "light").await;
    page.goto(format!("{address}/tile.design?theme=dark"))
        .await
        .unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    assert_eq!(
        eval::<String>(&page, "document.documentElement.dataset.theme").await,
        "dark"
    );
    let inside = on_screen(&page, "canvas.design", 60.0, 40.0).await;
    until_pixel(&page, inside, BLUE).await;
    assert_eq!(
        eval::<String>(&page, "localStorage.getItem('devpage-theme')").await,
        "light",
        "the remembered choice is untouched"
    );
    // Its switch still switches, and is remembered.
    page.find_element(".theme-toggle")
        .await
        .unwrap()
        .click()
        .await
        .unwrap();
    until_pixel(&page, inside, RED).await;
    assert_eq!(
        eval::<String>(&page, "localStorage.getItem('devpage-theme')").await,
        "light"
    );
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn an_embedded_design_paints_again_when_the_page_switches_theme() {
    let dir = folder("theme-embed");
    std::fs::write(dir.join("glass.design"), GLASS).unwrap();
    std::fs::write(dir.join("page.md"), "# Page\n\n![Glass](glass.design)\n").unwrap();
    let address = serve(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/page.md").as_str())
        .await
        .unwrap();
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    // Inside the design, and on the backdrop beside it, clear of the shadow the
    // backdrop puts under a design.
    let inside = on_screen(&page, "canvas.design", 60.0, 40.0).await;
    let outside = on_screen(&page, "canvas.design", -120.0, 40.0).await;
    let first = until_same(&page, inside, outside).await;
    let before: String = eval(&page, "document.documentElement.dataset.theme").await;
    page.find_element(".theme-toggle")
        .await
        .unwrap()
        .click()
        .await
        .unwrap();
    let after: String = eval(&page, "document.documentElement.dataset.theme").await;
    assert_ne!(before, after);
    let second = until_same(&page, inside, outside).await;
    assert_ne!(first, second, "the backdrop didn't change with the theme");
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn a_design_on_a_widget_slide_fits_the_slide_on_screen_and_on_paper() {
    let dir = folder("slide");
    // A tall design on the second slide, inside a project widget — as the
    // showcase deck's slides are: React mounts the widget's content, so the
    // design's canvas is made again after the page script first looks.
    std::fs::write(
        dir.join("tall.design"),
        r##"<Frame width={300} height={1400} fill="#2563eb" />"##,
    )
    .unwrap();
    std::fs::create_dir_all(dir.join("widgets")).unwrap();
    std::fs::write(
        dir.join("widgets/Box.tsx"),
        "export default function Box({ children }) { return <div className=\"box\">{children}</div>; }\n",
    )
    .unwrap();
    std::fs::write(dir.join("one.md"), "# One\n").unwrap();
    std::fs::write(
        dir.join("two.md"),
        "# Two\n\n<Box>\n\n![Tall](tall.design)\n\n</Box>\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("deck.yml"),
        "kind: slides\ntitle: Deck\nwidgets: widgets\nslides: [one.md, two.md]\n",
    )
    .unwrap();
    // A design on a slide that isn't shown waits; shown, it fits the room
    // the slide leaves it, inside the slide's 1080 pixels.
    let address = serve(&dir, "deck.yml").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/deck.yml#1").as_str())
        .await
        .unwrap();
    until(
        &page,
        "!!document.querySelector('.box canvas.design[data-started]')",
    )
    .await;
    // Changing slides refetches the deck, and React mounts the widget's
    // content again: the canvas is measured in the same step that finds it
    // painted, so a remount between two steps can't leave nothing to measure.
    page.evaluate("location.hash = '#2'").await.unwrap();
    until(
        &page,
        "(() => { const c = document.querySelector('.box canvas.design'); \
         if (c?.dataset.painted !== 'true') return false; const s = c.closest('.slide'); \
         const scale = s.getBoundingClientRect().height / s.offsetHeight; \
         window.measured = [(c.getBoundingClientRect().bottom - s.getBoundingClientRect().top) / scale, s.offsetHeight]; \
         return true; })()",
    )
    .await;
    let [bottom, slide]: [f64; 2] = eval(&page, "window.measured").await;
    assert!(
        bottom <= slide,
        "the design runs past the slide: {bottom} > {slide}"
    );
    browser.close().await.ok();
    events.abort();
    // On paper: printed promptly, the design painted in it.
    let document = Arc::new(Document::load(&dir.join("deck.yml"), &dir).unwrap());
    let pdf = dir.join("deck.pdf");
    let started = std::time::Instant::now();
    crate::pdf::print(document, &pdf).await.unwrap();
    assert!(
        started.elapsed() < Duration::from_secs(15),
        "printing waited out its cap: {:?}",
        started.elapsed()
    );
    let bytes = std::fs::read(&pdf).unwrap();
    assert!(
        bytes.windows(13).any(|w| w == b"/Subtype /Ima"),
        "no image in the printed deck"
    );
}

#[tokio::test]
#[ignore]
async fn an_embed_in_a_widget_keeps_where_it_navigated_across_a_page_refetch() {
    let dir = folder("widget-refetch");
    std::fs::create_dir_all(dir.join("widgets")).unwrap();
    std::fs::write(
        dir.join("widgets/Box.tsx"),
        "export default function Box({ children }) { return <div className=\"box\">{children}</div>; }\n",
    )
    .unwrap();
    let page_source = |text: &str| {
        format!("# Doc\n\n{text}\n\n<Box>\n\n![The screen](screen.design)\n\n</Box>\n")
    };
    std::fs::write(dir.join("doc.md"), page_source("Before.")).unwrap();
    std::fs::write(
        dir.join("doc.yml"),
        "kind: doc\ntitle: Doc\nwidgets: widgets\nchapters: [doc.md]\n",
    )
    .unwrap();
    let address = serve(&dir, "doc.yml").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/doc.yml").as_str())
        .await
        .unwrap();
    let painted = "document.querySelector('.box canvas.design')?.dataset.painted === 'true'";
    until(&page, painted).await;
    // Pay navigates inside the embed: the next design's yellow.
    let corner = on_screen(&page, ".box canvas.design", 300.0, 40.0).await;
    let pay = on_screen(&page, ".box canvas.design", 120.0, 40.0).await;
    page.click(pay).await.unwrap();
    until_pixel(&page, corner, [0xfe, 0xf3, 0xc7]).await;

    // The page changes and is fetched again: React makes the widget again,
    // and the embed still shows where it was — with its way back.
    std::fs::write(dir.join("doc.md"), page_source("After.")).unwrap();
    page.evaluate("load(location.href)").await.unwrap();
    until(
        &page,
        "document.querySelector('article')?.textContent.includes('After.')",
    )
    .await;
    until(&page, painted).await;
    let corner = on_screen(&page, ".box canvas.design", 300.0, 40.0).await;
    until_pixel(&page, corner, [0xfe, 0xf3, 0xc7]).await;
    assert_eq!(
        eval::<usize>(
            &page,
            "document.querySelectorAll('.box a.design-open').length"
        )
        .await,
        1,
        "one link to the canvas page"
    );
    // Back, inside the embed: the screen's grey again.
    let back = on_screen(&page, ".box canvas.design", 120.0, 40.0).await;
    page.click(back).await.unwrap();
    until_pixel(&page, corner, [0xf8, 0xfa, 0xfc]).await;
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn the_canvas_pages_switch_leaves_the_problems_bar_whole() {
    let dir = folder("corner");
    std::fs::write(
        dir.join("broken.design"),
        r##"<Frame width={200} height={100} fill="#ffffff" lable="typo" />"##,
    )
    .unwrap();
    let address = serve(&dir, "broken.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/broken.design").as_str())
        .await
        .unwrap();
    until(&page, "!!document.querySelector('body > .design-problems')").await;
    for theme in ["light", "dark"] {
        page.evaluate(format!(
            "document.documentElement.dataset.theme = '{theme}'"
        ))
        .await
        .unwrap();
        let overlap: bool = eval(
            &page,
            "(() => { const a = document.querySelector('body > .design-problems').getBoundingClientRect(); \
             const b = document.querySelector('#devpage-corner').getBoundingClientRect(); \
             return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; })()",
        )
        .await;
        assert!(!overlap, "the switch covers the problems bar in {theme}");
    }
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn an_embed_inside_a_widget_on_a_page_in_a_subfolder_finds_its_design() {
    let dir = folder("widget-subfolder");
    let sub = dir.join("sub");
    std::fs::create_dir_all(&sub).unwrap();
    designs(&sub);
    std::fs::write(
        dir.join("devpage.yml"),
        "kind: site\ntitle: Site\nroot: README.md\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("README.md"),
        "# Root\n\n## Topics\n\n- [Sub](sub/page.md)\n",
    )
    .unwrap();
    std::fs::write(
        sub.join("page.md"),
        "# Sub\n\n![Plain](button.design)\n\n<Callout>\n\n![In a callout](button.design)\n\n</Callout>\n\n\
<Tabs>\n<Tab title=\"One\">\n\n![In a tab](button.design)\n\n</Tab>\n</Tabs>\n\n\
<Steps>\n\n1. In a step\n\n   ![In a step](button.design)\n\n2. In a callout in a step\n\n   <Callout>\n\n   ![In a callout in a step](button.design)\n\n   </Callout>\n\n</Steps>\n",
    )
    .unwrap();
    let address = serve(&dir, "devpage.yml").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/sub/page.md").as_str())
        .await
        .unwrap();
    // Five embeds — plain, in a Callout, in a Tab, in a step, and in a Callout
    // inside a step, which mounts only in the nested pass after Steps draws
    // its items — each paints its design and links to it beside the page, not
    // at the top of the served folder.
    until(
        &page,
        "document.querySelectorAll('canvas.design').length === 5 \
         && [...document.querySelectorAll('canvas.design')].every((c) => c.dataset.painted === 'true')",
    )
    .await;
    let links: Vec<String> = eval(
        &page,
        "[...document.querySelectorAll('a.design-open')].map((a) => new URL(a.href).pathname)",
    )
    .await;
    assert_eq!(links, vec!["/sub/button.design"; 5]);
    assert_eq!(
        eval::<usize>(
            &page,
            "document.querySelectorAll('.design-problems').length"
        )
        .await,
        0,
        "no embed reports a problem"
    );
    browser.close().await.ok();
    events.abort();
}

/// A design that appears after the page has loaded — in a tab other than the
/// first, which `Tabs` puts on the page only when it opens — draws when it
/// appears, even on a page whose only design it is; closing the tab and
/// opening it again draws it again.
#[tokio::test]
#[ignore]
async fn a_design_in_a_tab_opened_later_draws_when_it_appears() {
    let dir = folder("later-tab");
    designs(&dir);
    std::fs::write(
        dir.join("page.md"),
        "# Tabs\n\n<Tabs>\n<Tab title=\"Words\">\n\nNo design here.\n\n</Tab>\n<Tab title=\"Design\">\n\n![Button](button.design)\n\n</Tab>\n</Tabs>\n",
    )
    .unwrap();
    let address = serve(&dir, "page.md").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser
        .new_page(format!("{address}/page.md").as_str())
        .await
        .unwrap();
    until(&page, "document.documentElement.dataset.ready === 'true'").await;
    assert_eq!(
        eval::<usize>(&page, "document.querySelectorAll('canvas.design').length").await,
        0,
        "the second tab isn't on the page yet"
    );
    let open =
        |n: usize| format!("document.querySelectorAll('.tabs-bar button')[{n}].click(); true");
    eval::<bool>(&page, &open(1)).await;
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    eval::<bool>(&page, &open(0)).await;
    until(&page, "!document.querySelector('canvas.design')").await;
    eval::<bool>(&page, &open(1)).await;
    until(
        &page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    browser.close().await.ok();
    events.abort();
}

/// A design on a slide, in a window smaller than the 1920 × 1080 stage the
/// deck scales down: the whole drawing is painted — each corner shows its own
/// color — and a click lands where the reader sees it. Checked on the GPU and
/// on the CPU, at two window sizes.
async fn a_design_on_a_scaled_slide_is_painted_whole(webgpu: bool) {
    let dir = folder(if webgpu {
        "scaled-slide-gpu"
    } else {
        "scaled-slide-cpu"
    });
    // Four corner squares of different colors on white; the bottom-right one
    // navigates to a green screen.
    std::fs::write(
        dir.join("corners.design"),
        r##"<Frame width={800} height={600} fill="#ffffff">
  <Rect x={0} y={0} width={200} height={150} fill="#ff0000" />
  <Rect x={600} y={0} width={200} height={150} fill="#00ff00" />
  <Rect x={0} y={450} width={200} height={150} fill="#0000ff" />
  <Rect x={600} y={450} width={200} height={150} fill="#ffff00" onClick="navigate ./next.design" />
</Frame>"##,
    )
    .unwrap();
    std::fs::write(
        dir.join("next.design"),
        r##"<Frame width={800} height={600} fill="#00ff00" />"##,
    )
    .unwrap();
    std::fs::write(
        dir.join("one.md"),
        "# Corners\n\n![Corners](corners.design)\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("deck.yml"),
        "kind: slides\ntitle: Deck\nslides: [one.md]\n",
    )
    .unwrap();
    let address = serve(&dir, "deck.yml").await;
    let (mut browser, events, _profile) = chrome().await;
    for (width, height) in [(1280, 720), (1600, 900)] {
        let page = browser.new_page("about:blank").await.unwrap();
        page.execute(SetDeviceMetricsOverrideParams::new(
            width, height, 1.0, false,
        ))
        .await
        .unwrap();
        if !webgpu {
            page.execute(AddScriptToEvaluateOnNewDocumentParams::new(
                "delete Navigator.prototype.gpu;",
            ))
            .await
            .unwrap();
        }
        page.goto(format!("{address}/deck.yml#1")).await.unwrap();
        until(
            &page,
            "document.querySelector('canvas.design')?.dataset.painted === 'true'",
        )
        .await;
        // Let the GPU's frame reach the screen.
        tokio::time::sleep(Duration::from_millis(300)).await;
        // The canvas's box on the screen, with the slide's scale applied.
        let [left, top, w, h]: [f64; 4] = eval(
            &page,
            "(() => { const b = document.querySelector('canvas.design').getBoundingClientRect(); \
             return [b.left, b.top, b.width, b.height]; })()",
        )
        .await;
        let at = |fx: f64, fy: f64| Point::new(left + w * fx, top + h * fy);
        for (point, color, corner) in [
            (at(0.1, 0.1), [255, 0, 0], "top left"),
            (at(0.9, 0.1), [0, 255, 0], "top right"),
            (at(0.1, 0.9), [0, 0, 255], "bottom left"),
            (at(0.9, 0.9), [255, 255, 0], "bottom right"),
            (at(0.5, 0.5), [255, 255, 255], "middle"),
        ] {
            let seen = pixel(&page, point).await;
            assert_eq!(
                seen, color,
                "{width}×{height}, webgpu {webgpu}: the {corner} shows {seen:?}"
            );
        }
        // The bottom-right square, where the reader sees it, navigates.
        page.click(at(0.9, 0.9)).await.unwrap();
        until_pixel(&page, at(0.1, 0.1), [0, 255, 0]).await;
        page.close().await.ok();
    }
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn a_design_on_a_scaled_slide_is_painted_whole_on_the_gpu() {
    a_design_on_a_scaled_slide_is_painted_whole(true).await;
}

#[tokio::test]
#[ignore]
async fn a_design_on_a_scaled_slide_is_painted_whole_on_the_cpu() {
    a_design_on_a_scaled_slide_is_painted_whole(false).await;
}

/// A PNG of `w` × `h` pixels filled with `fill`, painted by the engine.
fn painted_png(w: u32, h: u32, fill: &str) -> Vec<u8> {
    let files: std::collections::HashMap<String, String> = [(
        "p.design".to_string(),
        format!(r##"<Frame width={{{w}}} height={{{h}}} fill="{fill}" />"##),
    )]
    .into();
    let scene = devpage_design::resolve(&files, "p.design").unwrap();
    devpage_design::png(
        &mut devpage_design::Renderer::new(),
        &scene,
        devpage_design::Theme::Light,
    )
    .unwrap()
}

/// How the GPU canvas of the design `name`, open on `page` at 100%, differs
/// from the server's PNG of it — by the engine's one rule, as
/// `the_examples_match_their_pngs` compares the examples. On a failure the
/// screen is kept in the temporary folder for a look.
async fn gpu_against_png(page: &Page, address: &str, name: &str) -> Result<(), String> {
    gpu_against_png_within(page, address, name, 24).await
}

/// `gpu_against_png`, with `margin` pixels of the page's background around
/// the drawing: none for an embed, whose surroundings are its backdrop.
async fn gpu_against_png_within(
    page: &Page,
    address: &str,
    name: &str,
    margin: usize,
) -> Result<(), String> {
    until(
        page,
        "document.querySelector('canvas.design')?.dataset.painted === 'true'",
    )
    .await;
    let backend: String = eval(
        page,
        "document.querySelector('canvas.design').dataset.backend",
    )
    .await;
    assert_eq!(backend, "gpu");
    let [zoom, width, height]: [f64; 3] = eval(
        page,
        "(() => { const c = document.querySelector('canvas.design'); return [Number(c.dataset.view.split(',')[0]), ...c.dataset.size.split(',').map(Number)]; })()",
    )
    .await;
    assert_eq!(zoom, 1.0, "{name} isn't shown at 100%");
    tokio::time::sleep(Duration::from_millis(300)).await;
    let shot = screenshot(page, width, height, margin as f64).await;
    let d = difference(page, address, &shot, &format!("/{name}.design.png"), margin).await;
    eprintln!("gpu {name}: {d:?}");
    if d.is_some_and(|d| d.within_tolerance()) {
        return Ok(());
    }
    let at = std::env::temp_dir().join(format!("devpage-gpu-{name}.png"));
    std::fs::write(&at, &shot).ok();
    Err(format!("gpu {name}: {d:?}; the screen is {}", at.display()))
}

/// Opens each design in `dir` on its canvas page, on the GPU, and compares
/// it with its PNG.
async fn the_gpu_matches_the_png(dir: &Path, names: &[&str]) {
    let address = serve(dir, &format!("{}.design", names[0])).await;
    let (mut browser, events, _profile) = chrome().await;
    let mut failures = Vec::new();
    for name in names {
        let page = browser.new_page("about:blank").await.unwrap();
        page.execute(SetDeviceMetricsOverrideParams::new(1280, 1000, 1.0, false))
            .await
            .unwrap();
        page.goto(format!("{address}/{name}.design")).await.unwrap();
        if let Err(e) = gpu_against_png(&page, &address, name).await {
            failures.push(e);
        }
        page.close().await.ok();
    }
    assert!(failures.is_empty(), "{failures:#?}");
    browser.close().await.ok();
    events.abort();
}

/// Images past what the GPU's atlas holds draw on the GPU as in the PNG: a
/// file wider than the atlas, resampled once to fit, and twelve distinct
/// 2000-pixel files together — vello leaves out, silently, any image its
/// atlas has no room for, and the canvas shows no hole.
#[tokio::test]
#[ignore]
async fn images_larger_than_the_gpu_atlas_draw_on_the_gpu_as_in_the_png() {
    let dir = folder("big-images");
    // Smooth, so sampling it smaller differs between rasterizers only as an
    // edge does.
    std::fs::write(
        dir.join("wide.png"),
        painted_png(
            9000,
            300,
            "linear-gradient(90deg, #ff0000 0%, #00ff00 25%, #0000ff 50%, #ffff00 75%, #ff00ff 100%)",
        ),
    )
    .unwrap();
    std::fs::write(
        dir.join("wide.design"),
        r##"<Frame width={980} height={52} fill="#ffffff" padding={10}><Image src="wide.png" width={960} height={32} /></Frame>"##,
    )
    .unwrap();
    let colors = [
        "#ef4444", "#f97316", "#eab308", "#22c55e", "#06b6d4", "#3b82f6", "#8b5cf6", "#ec4899",
        "#14b8a6", "#84cc16", "#a855f7", "#64748b",
    ];
    let mut rows = [String::new(), String::new()];
    for (i, c) in colors.iter().enumerate() {
        std::fs::write(
            dir.join(format!("big{i}.png")),
            painted_png(
                2000,
                2000,
                &format!("linear-gradient({}deg, {c} 0%, #ffffff 100%)", 30 * i),
            ),
        )
        .unwrap();
        rows[i / 6].push_str(&format!(
            r#"<Image src="big{i}.png" width={{90}} height={{90}} />"#
        ));
    }
    let many = |rows: &[String; 2]| {
        format!(
            r##"<Frame layout="column" gap={{6}} padding={{10}} fill="#ffffff">
  <Frame layout="row" gap={{6}}>{}</Frame>
  <Frame layout="row" gap={{6}}>{}</Frame>
</Frame>"##,
            rows[0], rows[1]
        )
    };
    std::fs::write(dir.join("many.design"), many(&rows)).unwrap();
    the_gpu_matches_the_png(&dir, &["wide", "many"]).await;

    // A save that swaps six of them for six new ones: drawn with an atlas
    // of its own, the new drawing's images don't compete with the last's.
    let (address, designs) = serve_designs(&dir, "many.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser.new_page("about:blank").await.unwrap();
    page.execute(SetDeviceMetricsOverrideParams::new(1280, 1000, 1.0, false))
        .await
        .unwrap();
    page.goto(format!("{address}/many.design")).await.unwrap();
    gpu_against_png(&page, &address, "many").await.unwrap();
    let mut swapped = String::new();
    for (i, color) in colors.iter().take(6).enumerate() {
        std::fs::write(
            dir.join(format!("new{i}.png")),
            painted_png(
                2000,
                2000,
                &format!(
                    "linear-gradient({}deg, #0f172a 0%, {color} 100%)",
                    45 + 20 * i
                ),
            ),
        )
        .unwrap();
        swapped.push_str(&format!(
            r#"<Image src="new{i}.png" width={{90}} height={{90}} />"#
        ));
    }
    eval::<bool>(
        &page,
        "(document.querySelector('canvas.design').dataset.painted = 'false', true)",
    )
    .await;
    std::fs::write(dir.join("many.design"), many(&[rows[0].clone(), swapped])).unwrap();
    designs.changed(&dir.join("many.design"));
    gpu_against_png(&page, &address, "many").await.unwrap();
    browser.close().await.ok();
    events.abort();
}

/// Shadows drawn in pieces — a box far larger than its blur, round corners
/// as discs' edges, an ellipse in wedges — draw on the GPU as in the PNG:
/// the pieces add up there too, with no seam.
#[tokio::test]
#[ignore]
async fn shadows_in_pieces_draw_on_the_gpu_as_in_the_png() {
    let dir = folder("shadow-pieces");
    std::fs::write(
        dir.join("shadows.design"),
        r##"<Frame width={1100} height={760} fill="#f8fafc" layout="none">
  <Rect x={40} y={40} width={600} height={400} radius={[2, 60, 12, 120]} fill="#ffffff" shadow={{ y: 6, blur: 4, color: "#0f172a66" }} />
  <Ellipse x={700} y={60} width={360} height={200} fill="#ffffff" shadow={{ x: 4, blur: 3, color: "#1e3a8a80" }} />
  <Ellipse x={700} y={320} width={360} height={360} fill="#ffffff" shadow={{ blur: 2, spread: 6, color: "#000000" }} />
  <Rect x={40} y={500} width={600} height={6} fill="#ffffff" shadow={{ blur: 5, color: "#7c3aed" }} />
  <Rect x={40} y={560} width={620} height={160} radius={80} fill="#ffffff" shadow={{ blur: 2, color: "#000000aa" }} />
</Frame>"##,
    )
    .unwrap();
    the_gpu_matches_the_png(&dir, &["shadows"]).await;
}

/// Navigating on one canvas from a design whose images fill the GPU's atlas
/// — four 4096-pixel squares — to another with an image of its own draws
/// the second as its PNG does, on a canvas page and inside an embed alike:
/// the new drawing's images never share an atlas with the last design's.
#[tokio::test]
#[ignore]
async fn a_navigation_from_a_full_atlas_draws_the_next_design_as_its_png() {
    let dir = folder("atlas-navigation");
    for (name, color) in [
        ("red", "#dc0000"),
        ("green", "#00c800"),
        ("blue", "#0000dc"),
        ("yellow", "#dcdc00"),
        ("magenta", "#c800c8"),
    ] {
        std::fs::write(
            dir.join(format!("{name}.png")),
            painted_png(4096, 4096, color),
        )
        .unwrap();
    }
    std::fs::write(
        dir.join("a.design"),
        r##"<Frame width={400} height={100} fill="#ffffff" layout="row">
  <Image src="red.png" width={100} height={100} onClick="navigate ./b.design" />
  <Image src="green.png" width={100} height={100} />
  <Image src="blue.png" width={100} height={100} />
  <Image src="yellow.png" width={100} height={100} />
</Frame>"##,
    )
    .unwrap();
    std::fs::write(
        dir.join("b.design"),
        r##"<Frame width={400} height={300} fill="#ffffff" layout="row">
  <Image src="magenta.png" width={200} height={200} />
</Frame>"##,
    )
    .unwrap();
    std::fs::write(dir.join("page.md"), "# Page\n\n![A](a.design)\n").unwrap();
    let address = serve(&dir, "a.design").await;
    let (mut browser, events, _profile) = chrome().await;
    let mut failures = Vec::new();
    for (start, margin) in ["a.design", "page.md"].into_iter().zip([24, 0]) {
        let page = browser.new_page("about:blank").await.unwrap();
        page.execute(SetDeviceMetricsOverrideParams::new(1280, 1000, 1.0, false))
            .await
            .unwrap();
        page.goto(format!("{address}/{start}")).await.unwrap();
        if let Err(e) = gpu_against_png_within(&page, &address, "a", margin).await {
            failures.push(format!("{start}: {e}"));
        }
        eval::<bool>(
            &page,
            "(document.querySelector('canvas.design').dataset.painted = 'false', true)",
        )
        .await;
        let red = on_screen(&page, "canvas.design", 50.0, 50.0).await;
        page.click(red).await.unwrap();
        until(
            &page,
            "document.querySelector('canvas.design').dataset.size === '400,300'",
        )
        .await;
        if let Err(e) = gpu_against_png_within(&page, &address, "b", margin).await {
            failures.push(format!("{start}: {e}"));
        }
        page.close().await.ok();
    }
    assert!(failures.is_empty(), "{failures:#?}");
    browser.close().await.ok();
    events.abort();
}

#[tokio::test]
#[ignore]
async fn a_swap_keeps_a_design_outside_a_widget_and_stops_watching_a_removed_widgets() {
    let dir = folder("removed-widget");
    std::fs::create_dir_all(dir.join("widgets")).unwrap();
    std::fs::write(
        dir.join("widgets/Box.tsx"),
        "export default function Box({ children }) { return <div className=\"box\">{children}</div>; }\n",
    )
    .unwrap();
    let with_box =
        "# Doc\n\n![The screen](screen.design)\n\n<Box>\n\n![Next](next.design)\n\n</Box>\n";
    std::fs::write(dir.join("doc.md"), with_box).unwrap();
    std::fs::write(
        dir.join("doc.yml"),
        "kind: doc\ntitle: Doc\nwidgets: widgets\nchapters: [doc.md]\n",
    )
    .unwrap();
    let address = serve(&dir, "doc.yml").await;
    let (mut browser, events, _profile) = chrome().await;
    let page = browser.new_page("about:blank").await.unwrap();
    page.execute(AddScriptToEvaluateOnNewDocumentParams::new(WATCH_COUNTER))
        .await
        .unwrap();
    page.goto(format!("{address}/doc.yml")).await.unwrap();
    until(
        &page,
        "[...document.querySelectorAll('canvas.design')].filter((c) => c.dataset.painted === 'true').length === 2",
    )
    .await;
    page.evaluate("window.outside = [...document.querySelectorAll('canvas.design')].find((c) => !c.closest('.box')); window.before = window.watches.length")
        .await
        .unwrap();
    assert!(eval::<bool>(&page, "!!window.outside && !window.outside.closest('.box')").await);

    // The Box goes: the design outside keeps its canvas, and the page's one
    // stream is opened again without the Box's design.
    std::fs::write(
        dir.join("doc.md"),
        "# Doc\n\n![The screen](screen.design)\n\nNo box.\n",
    )
    .unwrap();
    page.evaluate("load(location.href)").await.unwrap();
    until(
        &page,
        "document.querySelector('article').textContent.includes('No box.')",
    )
    .await;
    until(
        &page,
        &format!("window.watches.length === window.before + 1 && {OPEN_WATCHES} === 1"),
    )
    .await;
    assert!(
        eval::<bool>(
            &page,
            "window.outside === document.querySelector('canvas.design') && !document.querySelector('.box')"
        )
        .await
    );
    browser.close().await.ok();
    events.abort();
}