makeover-webview 0.117.0

The webview renderer for makeover-layout. Emits CSS, and is the one renderer that needs no palette: var() is the late binding, so resolution stays with the browser. With the build feature, writes a consumer's generated frontend files and checks the hand-written ones against them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
//! Checks that a hand-written frontend still agrees with the crate that
//! generates its siblings.
//!
//! The generated files cannot drift: they ask makeover-geometry for the answer.
//! The hand-written ones state it, and a stylesheet or a script that disagrees
//! with the crate raises no error at any point. It is a rule that quietly
//! stops matching where it used to. Cheaper to read a panic naming the line.
//!
//! Deliberately assertions and not substitutions. A JS or CSS file that has to
//! be generated to be correct stops being readable on its own, and it is worth
//! something that you can still open the frontend in a browser and have it
//! work.

use std::path::{Path, PathBuf};

use super::rerun;
use crate::Emit;
use crate::css_lex::{Lang, Role, is_ident, lex, matching_close};
use makeover_geometry::{Density, SizeClass};

/// The declaration this check reads. Shared vocabulary, not a parameter: two
/// apps and a server naming the same string want the same name for it.
const CONST_NAME: &str = "TOUCH_DENSITY";

/// The capability sniffs the media query replaced, so neither can come back by
/// copy-paste.
///
/// Both ask the hardware what it has rather than what is pointing at the
/// screen, so both say yes to a touchscreen laptop driving a mouse.
const SNIFFS: &[&str] = &["ontouchstart", "maxTouchPoints"];

/// Fail the build if a JS copy of the touch-density query has drifted from
/// [`Density::Touch`].
///
/// Every `.js` file under `js_dir`, recursively, must state the crate's own
/// media condition in a `const TOUCH_DENSITY = '...'`, at least one file must
/// declare it, and no file may name a capability sniff.
///
/// The string is the crate's and no app gets a say in it, which is why this
/// check takes no policy argument. The generated `geometry.css` already keys
/// its touch gap overrides on the same condition, so the gestures and the
/// spacing agree by construction rather than by two people remembering.
///
/// Emits `cargo::rerun-if-changed` for every file it read.
///
/// # Panics
///
/// If `js_dir` cannot be read, if no declaration is found, or if any file
/// disagrees with the crate. A build script has nowhere useful to return an
/// error to, and a frontend that disagrees with its own stylesheet is worse
/// than a failed build.
pub fn check_touch_density(js_dir: impl AsRef<Path>) {
    let js_dir = js_dir.as_ref();
    let want = Density::Touch.media_condition();
    let mut wrong: Vec<String> = Vec::new();
    let mut found = 0usize;

    let files = js_files(js_dir);
    for path in &files {
        let raw = read(path);
        // Read the code with comments blanked: a commented-out declaration is
        // not a declaration, and a comment naming a sniff is not a use. String
        // contents stay, because the literal being read is itself a string.
        let src = blank(&raw, Lang::Js);
        let name = shown(path, Some(js_dir));

        for (offset, literal) in touch_density_literals(&src) {
            found += 1;
            if literal != want {
                wrong.push(format!(
                    "  {name}:{}  {CONST_NAME} = '{literal}'",
                    line_of(&src, offset)
                ));
            }
        }

        for needle in SNIFFS {
            if let Some(offset) = src.find(needle) {
                wrong.push(format!(
                    "  {name}:{}  {needle} -- device sniff, not a density question",
                    line_of(&src, offset)
                ));
            }
        }
    }

    assert!(
        found > 0,
        "no {CONST_NAME} literal found under {}.\n\n\
         A frontend that asks whether it is being touched states\n\
         makeover_geometry::Density::Touch's media condition in a const of that\n\
         name, and this check exists to keep every copy equal to it. If the\n\
         const was renamed, rename it back rather than dropping the check; if\n\
         this frontend genuinely asks no density question, drop the call.",
        js_dir.display()
    );

    assert!(
        wrong.is_empty(),
        "hand-written touch detection disagrees with makeover_geometry::Density.\n\n\
         Density::Touch.media_condition() is: {want}\n\n\
         Wrong:\n{}\n\n\
         Fix the JS to state the crate's string. Never widen it to catch a\n\
         device the query misses: density is what is pointing at the screen,\n\
         and a laptop with a touchscreen and a mouse is a pointer device.",
        wrong.join("\n")
    );

    for path in &files {
        rerun(path);
    }
    // The directory too, so a file added under it reruns the check: a
    // rerun keyed only on the files that existed last time never sees the
    // one somebody just copied in.
    rerun(js_dir);
}

/// A file's text, for a check that cannot run without it.
fn read(path: &Path) -> String {
    std::fs::read_to_string(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
}

/// A path as a reader of the error sees it: relative to `root` when there is
/// one.
fn shown(path: &Path, root: Option<&Path>) -> String {
    root.and_then(|root| path.strip_prefix(root).ok())
        .unwrap_or(path)
        .display()
        .to_string()
}

/// The sheets under `frontend/css`, recursively, with the directory named for
/// a rerun so a sheet added later reruns the check.
fn frontend_css(frontend: &Path) -> (PathBuf, Vec<PathBuf>) {
    let css = frontend.join("css");
    rerun(&css);
    let files = files_with_extension(&css, "css");
    (css, files)
}

/// Every `.js` file under `dir`, recursively, sorted.
fn js_files(dir: &Path) -> Vec<PathBuf> {
    files_with_extension(dir, "js")
}

/// Every file under `dir` with extension `ext`, recursively, sorted.
///
/// Recursive because a consumer's frontend is not always one flat directory:
/// the Tauri apps keep `js/*.js`, the server keeps subdirectories under
/// `static/`, and a check that silently skipped the nested half would report
/// clean on the files most likely to have been copied.
fn files_with_extension(dir: &Path, ext: &str) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(d) = stack.pop() {
        for entry in std::fs::read_dir(&d)
            .unwrap_or_else(|e| panic!("read {}: {e}", d.display()))
            .flatten()
        {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if path.extension().is_some_and(|x| x == ext) {
                out.push(path);
            }
        }
    }
    out.sort();
    out
}

/// `(byte offset of the declaration, the literal's contents)` for every
/// `const TOUCH_DENSITY = '...'` in a JS source already passed through
/// [`blank`] with [`Lang::Js`], so a commented-out copy is not a declaration.
///
/// The name must stand alone, whitespace may surround the `=`, and the literal
/// may open with any of JS's three quote characters.
fn touch_density_literals(src: &str) -> Vec<(usize, &str)> {
    let mut out = Vec::new();
    let mut at = 0;
    while let Some(i) = src[at..].find(CONST_NAME) {
        let start = at + i;
        at = start + CONST_NAME.len();
        // A name glued to another identifier (`OLD_TOUCH_DENSITY`,
        // `TOUCH_DENSITY2`) is not this const.
        if start > 0 && is_ident_byte(src.as_bytes()[start - 1]) {
            continue;
        }
        if src.as_bytes().get(at).copied().is_some_and(is_ident_byte) {
            continue;
        }
        // `const NAME = '...'`, any run of whitespace around the `=`.
        let rest = &src[at..];
        let lead = rest.len() - rest.trim_start().len();
        let rest = &rest[lead..];
        if !rest.starts_with('=') {
            continue;
        }
        // `==`/`===` is a comparison, not a declaration: after the first `=`
        // the next non-space must open a literal.
        let rest = &rest[1..];
        let gap = rest.len() - rest.trim_start().len();
        let rest = &rest[gap..];
        let Some(quote @ ('\'' | '"' | '`')) = rest.chars().next() else {
            continue;
        };
        let body = at + lead + 1 + gap + quote.len_utf8();
        if let Some(j) = src[body..].find(quote) {
            out.push((start, &src[body..body + j]));
            at = body + j + 1;
        }
    }
    out
}

/// Whether `b` may appear in a JS identifier, so a substring hit on
/// [`CONST_NAME`] can be rejected as part of a longer name.
fn is_ident_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_' || b == b'$'
}

fn line_of(src: &str, offset: usize) -> usize {
    src[..offset].matches('\n').count() + 1
}

/// Which files a check reads.
#[derive(Debug, Clone)]
enum Source {
    /// A frontend directory, scanned recursively.
    Frontend(PathBuf),
    /// A named list of files.
    Files(Vec<PathBuf>),
}

impl Source {
    fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
        Self::Files(paths.iter().map(|p| p.as_ref().to_path_buf()).collect())
    }
}

/// Fail the build if a hand-written breakpoint has drifted from [`SizeClass`].
///
/// Every pixel width named by a media or container query must be a
/// [`SizeClass`] boundary or one of the [`tuning`](Self::tuning) widths. A
/// container query is checked the same way: `@container screen (width < 600px)`
/// states a width, and a container whose inline size tracks the shell is a
/// breakpoint in disguise, so it must move with [`SizeClass`] or be declared a
/// tuning width like any other.
///
/// ```no_run
/// makeover_webview::build::drift::Breakpoints::in_frontend("frontend")
///     .tuning(&[1400])
///     .run();
/// ```
///
/// Without this, moving `SizeClass::Medium::min_px` regenerates the emitted
/// stylesheets and leaves every hand-written query behind, and the result is a
/// stylesheet that disagrees with itself at the old boundary rather than an
/// error.
///
/// The generated stylesheets are scanned too, and pass by construction: they
/// ask makeover-geometry for the number rather than stating it. Scanning them
/// means a consumer never has to name which files are hand-written.
#[derive(Debug, Clone)]
#[must_use = "a check does nothing until it is run"]
pub struct Breakpoints {
    source: Source,
    tuning: Vec<u16>,
}

impl Breakpoints {
    /// Every `.css` under `frontend/css` and every `.js` under `frontend/js`,
    /// recursively.
    pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
        Self {
            source: Source::Frontend(frontend.as_ref().to_path_buf()),
            tuning: Vec::new(),
        }
    }

    /// A named list of files rather than a tree.
    ///
    /// For a frontend whose generated and hand-written files share a directory,
    /// with nothing to point a directory scan at: the MNW server keeps both
    /// under `static/` beside a bundler's output. The list is hand-maintained,
    /// and a stylesheet nobody adds to it is unchecked rather than failing, so
    /// prefer [`in_frontend`](Self::in_frontend) where the layout allows it.
    ///
    /// A `.js` path is read as script and anything else as stylesheet.
    pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
        Self {
            source: Source::files(paths),
            tuning: Vec::new(),
        }
    }

    /// Widths inside a shell where something reflows without the shell
    /// changing: a dashboard dropping from three columns to two, a pane's width
    /// cap ending.
    ///
    /// The one thing an app gets a say in. A shell boundary is a [`SizeClass`]
    /// edge and belongs to makeover-geometry; nothing switches shells at a
    /// tuning width, so it does not move when a size class does. Each entry
    /// owes a note beside it saying what it tunes: this list is where a genuine
    /// boundary goes to hide from the check.
    pub fn tuning(mut self, widths: &[u16]) -> Self {
        self.tuning.extend_from_slice(widths);
        self
    }

    /// Run the check. Emits `cargo::rerun-if-changed` for every file it read,
    /// and for the scanned directories.
    ///
    /// # Panics
    ///
    /// If a listed file cannot be read (a listed path that no longer exists is
    /// a check covering less than it says), or if any width is neither a
    /// size-class boundary nor a tuning width. A build script has nowhere
    /// useful to return an error to.
    pub fn run(&self) {
        match &self.source {
            Source::Frontend(frontend) => {
                let (_, mut files) = frontend_css(frontend);
                // A CSS-only frontend ships no `js/`; the scan is best-effort
                // and a missing directory is skipped rather than failing.
                let js = frontend.join("js");
                rerun(&js);
                if js.is_dir() {
                    files.extend(js_files(&js));
                }
                check_paths(&files, &self.tuning, Some(frontend));
            }
            Source::Files(paths) => check_paths(paths, &self.tuning, None),
        }
    }
}

/// The check itself. `root`, when given, is stripped from reported paths.
fn check_paths(paths: &[PathBuf], tuning_widths: &[u16], root: Option<&Path>) {
    let allowed = allowed_widths(tuning_widths);
    let edges = size_class_widths();
    let mut stale: Vec<String> = Vec::new();

    for path in paths {
        let raw = read(path);
        let name = shown(path, root);

        if path.extension().is_some_and(|x| x == "js") {
            // No declarations in JS, so any parenthesised width is a query.
            for (offset, bound) in js_widths(&blank(&raw, Lang::Js)) {
                if !bound.is_allowed(&allowed, &edges) {
                    stale.push(format!(
                        "  {name}:{}  ({})",
                        line_of(&raw, offset),
                        bound.width
                    ));
                }
            }
            continue;
        }

        // Comments first: a note about a breakpoint that used to be here is
        // prose, not a rule, and should not fail a build.
        let src = blank(&raw, Lang::Css);
        for (offset, condition) in media_conditions(&src) {
            for bound in media_bounds(condition) {
                if !bound.is_allowed(&allowed, &edges) {
                    stale.push(format!(
                        "  {name}:{}  @media{condition}  ({})",
                        line_of(&src, offset),
                        bound.width
                    ));
                }
            }
        }
    }

    assert!(
        stale.is_empty(),
        "hand-written breakpoints disagree with makeover_geometry::SizeClass.\n\n\
         Allowed: {allowed:?}\n\
         ({:?} come from SizeClass; {tuning_widths:?} were passed as tuning widths.)\n\n\
         Stale:\n{}\n\n\
         Size classes are written in range syntax, `(width < 600px)`, because\n\
         `(max-width: 599px)` leaves 599.5px in no class. If a size class moved,\n\
         update these to match. If one of these is a new\n\
         tuning width inside the wide shell rather than a shell boundary, add it\n\
         to the caller's tuning list with a note saying what it tunes.\n\n\
         Best of all, make the rule dimensional so it needs no threshold: a grid\n\
         wants repeat(auto-fit, minmax(<content floor>, 1fr)) and a size wants\n\
         clamp(). A threshold is for what appears and disappears.",
        allowed
            .iter()
            .filter(|px| !tuning_widths.contains(px))
            .collect::<Vec<_>>(),
        stale.join("\n")
    );

    for path in paths {
        rerun(path);
    }
}

/// Every width a hand-written media query is allowed to name.
///
/// Read out of [`SizeClass::media_condition`] rather than typed, which is the
/// whole point: that is the one place the numbers come from, and a bump in
/// makeover-geometry has to reach the stylesheet through here.
fn allowed_widths(tuning_widths: &[u16]) -> Vec<u16> {
    let mut widths = size_class_widths();
    widths.extend_from_slice(tuning_widths);
    widths.sort_unstable();
    widths.dedup();
    widths
}

/// The widths at which [`SizeClass`] changes, read out of it rather than
/// typed: where one class ends and the next begins. A hand-written bound on
/// one of these edges owns the point the classes either side both claim, so
/// the direction it is written in matters; a tuning width has no such edge.
fn size_class_widths() -> Vec<u16> {
    let mut widths: Vec<u16> = SizeClass::all()
        .iter()
        .flat_map(|c| media_widths(&c.media_condition()))
        .map(|width| match width {
            Width::Px(px) => px,
            Width::Other(raw) => {
                panic!("makeover-geometry wrote a size-class width this check cannot read: {raw}")
            }
        })
        .collect();
    widths.sort_unstable();
    widths.dedup();
    widths
}

/// A width named in a media condition.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Width {
    /// A whole number of CSS pixels: `600px`, or `37.5em` at the 16px a media
    /// query's `em` is measured against.
    Px(u16),
    /// Anything this cannot state in whole pixels: `599.98px`, `50vw`, `40ch`.
    /// Never a boundary, so always reported.
    Other(String),
}

/// A width named in a media condition, with the side of the comparison its
/// operator puts it on.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Bound {
    width: Width,
    direction: Direction,
}

/// Whether a bound is one edge of a partition, as a size class is written, or
/// straddles the boundary point instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
    /// `width < N`, `width >= N`, `N <= width` or `N > width`: the classes
    /// either side still partition at `N`.
    Edge,
    /// `max-width: N`, `width <= N`, `N >= width`, `width > N` or `N < width`:
    /// the bound claims the point at `N` itself, which [`SizeClass`] owns.
    Straddles,
}

impl Bound {
    /// A bound passes when its number is allowed and, when that number is a
    /// size-class edge, it is written as an edge rather than a bound that
    /// straddles it. A tuning width has no class on either side to disagree
    /// with, so its direction is left alone.
    fn is_allowed(&self, allowed: &[u16], edges: &[u16]) -> bool {
        match &self.width {
            Width::Px(px) => {
                allowed.contains(px)
                    && !(edges.contains(px) && self.direction == Direction::Straddles)
            }
            Width::Other(_) => false,
        }
    }
}

impl std::fmt::Display for Width {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Px(px) => write!(f, "{px}px"),
            Self::Other(raw) => f.write_str(raw),
        }
    }
}

/// Every width in a media condition, in the order it appears.
fn media_widths(condition: &str) -> Vec<Width> {
    media_bounds(condition)
        .into_iter()
        .map(|bound| bound.width)
        .collect()
}

/// Every width in a media condition with the direction its operator gives it,
/// in the order it appears.
///
/// Reads both spellings of a width feature: `(max-width: 599px)` and range
/// syntax, `(width < 600px)` or `(600px <= width < 840px)`, which is what
/// [`SizeClass::media_condition`] writes. A feature group is any `( ... )`
/// naming `width` and not `device-width`, and every length inside it counts,
/// including one nested in a function like `calc(...)`. Units are read rather
/// than assumed: `48em` is 768px, not 48.
fn media_bounds(condition: &str) -> Vec<Bound> {
    width_groups(condition)
        .into_iter()
        .flat_map(|(_, group)| lengths(group))
        .collect()
}

/// `(byte offset, inner text)` of every parenthesised group that names a width
/// feature. A nested group (`calc(...)`) stays inside its outer group's text,
/// so a width buried in a function is read rather than skipped.
fn width_groups(src: &str) -> Vec<(usize, &str)> {
    let mut out: Vec<(usize, &str)> = Vec::new();
    let mut stack: Vec<usize> = Vec::new();
    for (i, c) in src.char_indices() {
        match c {
            '(' => stack.push(i),
            ')' => {
                if let Some(start) = stack.pop() {
                    let inner = &src[start + 1..i];
                    // A group enclosing one already read, as in
                    // `matchMedia('(width < 600px)')`, adds nothing: the inner
                    // group is the feature. This keeps nesting for the sake of
                    // reading `calc(...)`, without reading a call around it.
                    let encloses_read = out.iter().any(|&(inner_start, _)| inner_start > start);
                    if names_width(inner) && !encloses_read {
                        out.push((start, inner));
                    }
                }
            }
            _ => {}
        }
    }
    out
}

/// Whether a feature group is about the viewport's width: `width`,
/// `min-width` or `max-width` as a whole word, not `device-width` and not a
/// longer identifier that ends in it.
fn names_width(inner: &str) -> bool {
    width_token_at(inner).is_some()
}

/// Byte offset of the `width` in a feature group: `width`, `min-width` or
/// `max-width` as a whole word, not `device-width` and not a longer
/// identifier that ends in it.
fn width_token_at(inner: &str) -> Option<usize> {
    inner.match_indices("width").find_map(|(at, _)| {
        let before = &inner[..at];
        let prefix_ok = before.is_empty()
            || before.ends_with("min-")
            || before.ends_with("max-")
            || before.chars().next_back().is_some_and(|c| !is_ident(c));
        let after = inner[at + "width".len()..].chars().next();
        (prefix_ok && after.is_none_or(|c| !is_ident(c))).then_some(at)
    })
}

/// Every `<number><unit>` in a feature group, each with the direction its
/// operator gives it.
fn lengths(group: &str) -> Vec<Bound> {
    let bytes = group.as_bytes();
    let width_at = width_token_at(group);
    let mut out = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        // A number may open with a digit or with a leading dot (`.5em`); it
        // must not continue an identifier or a preceding number.
        let prev_ok = i == 0
            || !(bytes[i - 1].is_ascii_alphanumeric()
                || bytes[i - 1] == b'-'
                || bytes[i - 1] == b'.');
        let starts_number = prev_ok
            && (bytes[i].is_ascii_digit()
                || (bytes[i] == b'.' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit)));
        if !starts_number {
            i += 1;
            continue;
        }
        let start = i;
        while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
            i += 1;
        }
        let number = &group[start..i];
        let unit_start = i;
        while i < bytes.len() && bytes[i].is_ascii_alphabetic() {
            i += 1;
        }
        let unit = &group[unit_start..i];
        if unit.is_empty() {
            continue;
        }
        let raw = &group[start..i];
        let scale = match unit {
            "px" => Some(1.0),
            "em" | "rem" => Some(16.0),
            _ => None,
        };
        let px = scale.and_then(|scale| number.parse::<f64>().ok().map(|n| n * scale));
        let width = match px {
            Some(px) if px.fract() == 0.0 && px >= 0.0 && px <= f64::from(u16::MAX) => {
                // Whole and in range, checked above.
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                Width::Px(px as u16)
            }
            _ => Width::Other(raw.to_string()),
        };
        out.push(Bound {
            width,
            direction: direction_of(group, start, i, width_at),
        });
    }
    out
}

/// Which side of `width` a number sits on, and whether its operator makes the
/// bound an [`Edge`](Direction::Edge) of the partition or one that
/// [`straddles`](Direction::Straddles) it.
///
/// The classes partition the viewport, so the bound between two of them is
/// exclusive on one side and inclusive on the other: `width < 600px` is an
/// edge, and so is `600px <= width`. `max-width: 600px` is not, because it
/// also matches the width where `Medium` begins.
fn direction_of(group: &str, start: usize, end: usize, width_at: Option<usize>) -> Direction {
    let Some(width_at) = width_at else {
        return Direction::Edge;
    };
    let width_end = width_at + "width".len();
    if start >= width_end {
        // The number is to the right of `width`.
        let op = &group[width_end..start];
        if op.contains("<=") {
            Direction::Straddles
        } else if op.contains(">=") || op.contains('<') {
            Direction::Edge
        } else if op.contains('>') {
            Direction::Straddles
        } else if group[..width_at].ends_with("min-") {
            Direction::Edge
        } else {
            // `max-width: N` and a bare `width: N` both claim `N` itself.
            Direction::Straddles
        }
    } else {
        // The number is to the left of `width`.
        let op = &group[end..width_at];
        if op.contains("<=") || op.contains('>') {
            Direction::Edge
        } else {
            Direction::Straddles
        }
    }
}

/// `(byte offset of the at-keyword, the condition text)`.
///
/// Reads the at-rules that carry a width condition: `@media` and `@container`
/// (case-insensitive, terminated by `{`), and `@custom-media` and `@import`,
/// which end at `;`. A container name ahead of its condition (`@container
/// screen (width < 600px)`) lands in the condition text, and [`width_groups`]
/// skips it, reading only the parenthesised width feature.
fn media_conditions(css: &str) -> Vec<(usize, &str)> {
    let lower = css.to_ascii_lowercase();
    let mut out = Vec::new();
    let mut at = 0;
    while let Some(rel) = lower[at..].find('@') {
        let start = at + rel;
        let kw_start = start + 1;
        let kw_end = css[kw_start..]
            .find(|c: char| !c.is_ascii_alphanumeric() && c != '-')
            .map_or(css.len(), |i| kw_start + i);
        let terminator = match &lower[kw_start..kw_end] {
            "media" | "container" => '{',
            "custom-media" | "import" => ';',
            _ => {
                at = start + 1;
                continue;
            }
        };
        match css[kw_end..].find(terminator) {
            Some(j) => {
                out.push((start, &css[kw_end..kw_end + j]));
                at = kw_end + j + 1;
            }
            None => break,
        }
    }
    out
}

/// `(byte offset, bound)` for every width feature in a JS source.
///
/// The parentheses are the whole test, and they have to be: a media condition
/// is always parenthesized and a CSS declaration never is, so `'max-width:
/// 320px'` in an inline-style string is not a breakpoint and must not read as
/// one. Range syntax, `(width < 600px)`, is read the same way as in a
/// stylesheet.
fn js_widths(src: &str) -> Vec<(usize, Bound)> {
    width_groups(src)
        .into_iter()
        .filter(|(_, group)| is_feature(group))
        .flat_map(|(offset, group)| lengths(group).into_iter().map(move |b| (offset, b)))
        .collect()
}

/// Whether a parenthesised group in script is a media feature rather than a
/// call's arguments: `(max-width: 600px)` or `(width < 600px)`, not
/// `Math.max(width, 600)`.
fn is_feature(group: &str) -> bool {
    let group = group.trim();
    let colon = ["min-width", "max-width", "width"].iter().any(|name| {
        group
            .strip_prefix(name)
            .is_some_and(|rest| rest.trim_start().starts_with(':'))
    });
    colon || group.contains(['<', '>'])
}

/// Blank the parts of `src` that are not code, keeping every byte offset.
///
/// Comments always go. String contents go in a stylesheet, where neither is a
/// rule and `content: "/*"` must not open a comment, and stay in script,
/// because a media query in script is a string (`matchMedia('(width <
/// 600px)')`). Blanked characters become as many spaces as they had bytes,
/// except that a newline stays a newline so line numbers still line up.
fn blank(src: &str, lang: Lang) -> String {
    let mut out = String::with_capacity(src.len());
    for (c, role) in lex(src, lang) {
        if role == Role::Code || (role == Role::Text && lang == Lang::Js) {
            out.push(c);
        } else if c == '\n' {
            out.push('\n');
        } else {
            out.extend(std::iter::repeat_n(' ', c.len_utf8()));
        }
    }
    out
}

/// Blank every `@layer <name> { ... }` block whose name is in `names`, keeping
/// byte offsets and line breaks. Comments and strings are skipped while the
/// braces are matched, the same way [`blank`] reads them.
///
/// An important declaration inside a dropped layer is still read: `!important`
/// inverts layer order, so a rule in an earlier layer marked important beats
/// every later layer, and dropping it whole would hide a real override. The
/// modern-reset reduced-motion idiom lives exactly there. [`blank_dropped_layer`]
/// keeps those rules and blanks the rest.
///
/// `@layer` and its name are read case-insensitively, and a dotted sublayer
/// (`@layer reset.base`) is beneath whatever `reset` is beneath.
fn drop_layers(css: &str, names: &[&str]) -> String {
    if names.is_empty() {
        return css.to_owned();
    }
    let scan = blank(css, Lang::Css);
    let scan = scan.as_bytes();
    let mut out = css.as_bytes().to_vec();
    let mut at = 0;
    while let Some(found) = find_at_layer(scan, at) {
        let mut i = found + b"@layer".len();
        while i < scan.len() && scan[i].is_ascii_whitespace() {
            i += 1;
        }
        let start = i;
        while i < scan.len()
            && (scan[i].is_ascii_alphanumeric() || matches!(scan[i], b'-' | b'_' | b'.'))
        {
            i += 1;
        }
        let name = &css[start..i];
        while i < scan.len() && scan[i].is_ascii_whitespace() {
            i += 1;
        }
        if i >= scan.len() || scan[i] != b'{' || !layer_is_beneath(name, names) {
            at = found + 1;
            continue;
        }
        match matching_close(scan, i, b'{', b'}') {
            Some(close) => {
                blank_dropped_layer(&mut out, scan, found, i, close);
                at = close + 1;
            }
            None => {
                blank_span(&mut out, found, scan.len());
                at = scan.len();
            }
        }
    }
    String::from_utf8(out).unwrap_or_else(|_| css.to_owned())
}

/// Whether a layer named `name` sits beneath every layer in `names`.
///
/// A sublayer is beneath its parent, so `reset.base` is beneath `reset`.
fn layer_is_beneath(name: &str, names: &[&str]) -> bool {
    names.iter().any(|beneath| {
        name == *beneath
            || name
                .strip_prefix(beneath)
                .is_some_and(|rest| rest.starts_with('.'))
    })
}

/// Case-insensitive `@layer` search, since at-rule keywords are case-insensitive
/// and `@LAYER` is the same rule as `@layer`.
fn find_at_layer(haystack: &[u8], from: usize) -> Option<usize> {
    let needle = b"@layer";
    let mut i = from;
    while i + needle.len() <= haystack.len() {
        if haystack[i..i + needle.len()].eq_ignore_ascii_case(needle) {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Blank the bytes of `out[start..end]` to spaces, keeping line breaks.
fn blank_span(out: &mut [u8], start: usize, end: usize) {
    for byte in &mut out[start..end] {
        if *byte != b'\n' {
            *byte = b' ';
        }
    }
}

/// Blank one dropped `@layer` block, keeping any declaration rule that carries
/// an `!important` declaration.
///
/// `head` is the index of the `@layer` keyword, `open` the opening brace and
/// `close` the matching closing brace. The header and closing brace are always
/// blanked so a kept rule rises to the surface; the rule bodies decide
/// themselves.
fn blank_dropped_layer(out: &mut [u8], scan: &[u8], head: usize, open: usize, close: usize) {
    blank_span(out, head, open + 1);
    blank_dropped_content(out, scan, open + 1, close);
    blank_span(out, close, close + 1);
}

/// Blank the non-important rules of a dropped layer's content, leaving any
/// declaration rule whose body carries `!important` where it is.
///
/// An at-rule block (`@media`, a nested `@layer`) is descended into, since a
/// rule it holds can carry the important declaration this keeps.
fn blank_dropped_content(out: &mut [u8], scan: &[u8], start: usize, end: usize) {
    let mut i = start;
    while i < end {
        let mut open = i;
        while open < end && scan[open] != b'{' && scan[open] != b';' {
            open += 1;
        }
        if open >= end {
            blank_span(out, i, end);
            break;
        }
        if scan[open] == b';' {
            blank_span(out, i, open + 1);
            i = open + 1;
            continue;
        }
        let Some(close) = matching_close(&scan[..end], open, b'{', b'}') else {
            blank_span(out, i, end);
            break;
        };
        let is_at_rule = scan[i..open]
            .iter()
            .position(|b| !b.is_ascii_whitespace())
            .is_some_and(|k| scan[i + k] == b'@');
        if is_at_rule {
            blank_dropped_content(out, scan, open + 1, close);
        } else if !has_important(&scan[open + 1..close]) {
            blank_span(out, i, close + 1);
        }
        i = close + 1;
    }
}

/// Whether a declaration block ends any declaration with `!important`, allowing
/// the whitespace the spec permits between the `!` and the keyword.
fn has_important(bytes: &[u8]) -> bool {
    let keyword = b"important";
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'!' {
            let mut k = i + 1;
            while k < bytes.len() && bytes[k].is_ascii_whitespace() {
                k += 1;
            }
            if k + keyword.len() <= bytes.len()
                && bytes[k..k + keyword.len()].eq_ignore_ascii_case(keyword)
            {
                return true;
            }
        }
        i += 1;
    }
    false
}

/// The layers a sheet's own order statement puts before `makeover`.
///
/// `@layer reset, quasi, makeover;` says that a rule in `reset` or `quasi`
/// loses to every generated rule whatever its selector, which is the same thing
/// [`Vocabulary::beneath`] lets an app state from its build script. A sheet
/// that states it itself (quasi-webview's `SCREEN_CSS` does, and every app that
/// serves it carries the statement) needs no second copy of the claim.
fn layers_ordered_below_makeover(css: &str) -> Vec<String> {
    let scan = blank(css, Lang::Css);
    let mut below = Vec::new();
    for statement in scan.split(';') {
        let Some(at) = statement.rfind("@layer") else {
            continue;
        };
        let names: Vec<&str> = statement[at + "@layer".len()..]
            .split(',')
            .map(str::trim)
            .collect();
        if names.iter().any(|name| name.contains(['{', '}'])) {
            continue;
        }
        if let Some(position) = names.iter().position(|name| *name == crate::CSS_LAYER) {
            below.extend(names[..position].iter().map(|name| (*name).to_string()));
        }
    }
    below
}

/// A reviewed exception to [`Vocabulary`]: a collision the app has read and
/// kept, with a note beside it saying why.
///
/// It expires when the collision does. An exception that no longer collides
/// fails the check, since an unused licence is where the next real collision
/// lands unnoticed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Allow<'a> {
    /// A hand-written rule on a generated class takes one of its properties.
    Class {
        /// The class, unprefixed as the stylesheet spells it.
        class: &'a str,
        /// The property both set.
        property: &'a str,
    },
    /// A bare element rule takes a property the generated sheet sets on a class
    /// that element carries.
    Element {
        /// The element the rule selects.
        element: &'a str,
        /// The generated class it reaches.
        class: &'a str,
        /// The property both set.
        property: &'a str,
    },
}

impl<'a> Allow<'a> {
    /// See [`Allow::Class`].
    pub const fn class(class: &'a str, property: &'a str) -> Self {
        Self::Class { class, property }
    }

    /// See [`Allow::Element`].
    pub const fn element(element: &'a str, class: &'a str, property: &'a str) -> Self {
        Self::Element {
            element,
            class,
            property,
        }
    }
}

/// Fail the build if a hand-written stylesheet takes a property the generated
/// one already sets, on the same class or on an element that carries it.
///
/// The generated sheet sits in `@layer makeover`. App CSS beats it whatever the
/// specificity, either by being unlayered or by sitting in a layer the app's
/// order statement puts after `makeover`, so an app declaration for a property
/// makeover already sets does not merge with it: it wins, silently, and the
/// design system's version of that component stops applying, and nothing looks.
///
/// # Two passes, because a rule can carry no class
///
/// The class pass compares an app `.button` against the generated `.button`.
/// It reads rules by the classes in their selectors, so a rule with no class in
/// it is invisible to it, and `button { color: var(--content) }` is exactly
/// that: it sets the property the generated `.button` sets on every described
/// act, `.button[data-tone="danger"]`'s tone included, which draws a
/// destructive act like an ordinary one.
///
/// The element pass reads that case. `crate::vocabulary::ELEMENT_CLASSES`
/// says which generated classes an element can carry (CSS cannot say it, and
/// the renderer can), and a bare element rule taking a property the design
/// system sets on one of those classes is the same defect as the class case.
///
/// Two things are not reported, both deliberately:
///
///   - A scoped rule (`.page button`). It reaches the elements inside one
///     region rather than every one of them, so whether it lands on a described
///     act depends on where that act renders. The certain case is the one this
///     reads.
///   - A property the app names on the class itself, from a rule that outranks
///     the element rule. Both are the app's and both sit in the same layer, so
///     that one contest is settled by specificity, and what reaches the design
///     system is the class rule, which the class pass has already reported
///     or reviewed. The rank matters: `.field` does not beat
///     `input[type="text"]`, and a handoff written as the weaker of the two is
///     a remedy that looks written and is not.
///
/// # Why properties and not class names
///
/// A shared class name is not by itself a divergence. An app `.badge` that sets
/// shape while the generated `.badge` sets colour is a correct split, and a
/// check on names would ask for it to be deleted. On properties, the split is
/// what the check enforces.
///
/// # The exception list
///
/// [`Allow::class`] names a `(class, property)` pair this app has reviewed and
/// kept.
/// Deciding which are legitimate here would need a selector matcher, and a check
/// that guesses wrong about specificity fails correct builds, so the app
/// declares it instead, the same shape as quasi-webview's `RENDERER_OWN`.
///
/// A reviewed pairing is a claim about who owns a property, and it expires when
/// the design system takes the property back.
///
/// [`Allow::element`] is the same thing one pass down: an element rule reaching
/// a generated class that has been read and kept.
///
/// The remedy is usually neither. A later layer can hand the property back
/// with `revert-layer`, which says "whatever the design system set here, keep
/// it" on the arms makeover actually paints, and that is a statement in the
/// stylesheet rather than a note in a build script. Handoffs are not reported by
/// either pass.
///
/// A pair that stops colliding fails too. A licence nobody is using is where
/// the next real collision lands and reads as company.
///
/// ```no_run
/// use makeover_webview::build::drift::{Allow, Vocabulary};
///
/// Vocabulary::in_frontend("frontend")
///     .generated(&["layout.css"])
///     // Reviewed: the card's shadow is the app's, on the hover arm only.
///     .allow(Allow::class("card", "box-shadow"))
///     .run(&makeover_webview::Emit::default());
/// ```
#[derive(Debug, Clone)]
#[must_use = "a check does nothing until it is run"]
pub struct Vocabulary<'a> {
    source: Source,
    generated: Vec<&'a str>,
    upstream: Vec<&'a str>,
    allowed: Vec<Allow<'a>>,
    beneath: Vec<&'a str>,
}

impl<'a> Vocabulary<'a> {
    /// Every `.css` under `frontend/css`, recursively.
    pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
        Self::from(Source::Frontend(frontend.as_ref().to_path_buf()))
    }

    /// A named list of stylesheets rather than a tree.
    ///
    /// For a frontend whose generated and hand-written sheets share a
    /// directory. Same trade as [`Breakpoints::files`]: the list is
    /// hand-maintained, and a stylesheet nobody adds to it is unchecked.
    pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
        Self::from(Source::files(paths))
    }

    fn from(source: Source) -> Self {
        Self {
            source,
            generated: Vec::new(),
            upstream: Vec::new(),
            allowed: Vec::new(),
            beneath: Vec::new(),
        }
    }

    /// Sheets this crate writes, which are skipped: the generated file setting
    /// a generated property is the point. Relative to `frontend/css` for
    /// [`in_frontend`](Self::in_frontend); matched against the end of each path
    /// for [`files`](Self::files).
    pub fn generated(mut self, names: &[&'a str]) -> Self {
        self.generated.extend_from_slice(names);
        self
    }

    /// The text of stylesheets that sit between makeover and the app and own
    /// the classes they style as makeover owns its own.
    ///
    /// quasi-webview's `SCREEN_CSS` is the case. This crate cannot name it,
    /// since quasi builds on this crate and not the other way round, so the app
    /// that links both hands it in. A hand-written sheet is checked against
    /// makeover's sheet and every upstream sheet together. A file whose text
    /// *is* an upstream sheet, the copy an app serves from its frontend, is
    /// checked against makeover alone and never read as clashing with itself.
    pub fn upstream(mut self, sheets: &[&'a str]) -> Self {
        self.upstream.extend_from_slice(sheets);
        self
    }

    /// Cascade layers the app orders before `makeover`, by name.
    ///
    /// A rule inside one loses to every generated rule whatever its selector,
    /// so it cannot take a property from the design system and is not read.
    /// The usual case is a reset: `@layer reset, makeover, ...` with
    /// `* { margin: 0; padding: 0 }` inside `@layer reset { }` clears browser
    /// defaults without zeroing the generated spacing. The order itself lives
    /// in the app's markup, which this check does not read, so naming a layer
    /// here is the app stating that order.
    pub fn beneath(mut self, layers: &[&'a str]) -> Self {
        self.beneath.extend_from_slice(layers);
        self
    }

    /// A reviewed exception. See [`Allow`].
    pub fn allow(mut self, allow: Allow<'a>) -> Self {
        self.allowed.push(allow);
        self
    }

    /// Several reviewed exceptions, for a list the app keeps as a `const`.
    pub fn allowing(mut self, allows: impl IntoIterator<Item = Allow<'a>>) -> Self {
        self.allowed.extend(allows);
        self
    }

    /// Run the check against the stylesheet `opts` generates. Emits
    /// `cargo::rerun-if-changed` for every file it read.
    ///
    /// # Panics
    ///
    /// If a directory or listed file cannot be read, if any hand-written sheet
    /// takes a generated property without an [`Allow`], or if an [`Allow`] no
    /// longer collides. A build script has nowhere useful to return an error
    /// to, and an app quietly overriding its own design system is worse than a
    /// failed build.
    pub fn run(&self, opts: &Emit) {
        let classes: Vec<(&str, &str)> = self
            .allowed
            .iter()
            .filter_map(|allow| match *allow {
                Allow::Class { class, property } => Some((class, property)),
                Allow::Element { .. } => None,
            })
            .collect();
        let elements: Vec<(&str, &str, &str)> = self
            .allowed
            .iter()
            .filter_map(|allow| match *allow {
                Allow::Element {
                    element,
                    class,
                    property,
                } => Some((element, class, property)),
                Allow::Class { .. } => None,
            })
            .collect();
        match &self.source {
            Source::Frontend(frontend) => {
                let (css, files) = frontend_css(frontend);
                let files: Vec<PathBuf> = files
                    .into_iter()
                    .filter(|p| !self.generated.contains(&shown(p, Some(&css)).as_str()))
                    .collect();
                check_vocabulary_paths(
                    &files,
                    opts,
                    Some(frontend),
                    &self.upstream,
                    &self.beneath,
                    &classes,
                    &elements,
                );
            }
            Source::Files(paths) => {
                let files: Vec<PathBuf> = paths
                    .iter()
                    .filter(|p| !self.generated.iter().any(|name| p.ends_with(name)))
                    .cloned()
                    .collect();
                check_vocabulary_paths(
                    &files,
                    opts,
                    None,
                    &self.upstream,
                    &self.beneath,
                    &classes,
                    &elements,
                );
            }
        }
    }
}

/// The check itself. `root`, when given, is stripped from reported paths.
fn check_vocabulary_paths(
    paths: &[PathBuf],
    opts: &Emit,
    root: Option<&Path>,
    upstream: &[&str],
    beneath: &[&str],
    allowed: &[(&str, &str)],
    allowed_elements: &[(&str, &str, &str)],
) {
    let sheet = crate::stylesheet(opts);
    let makeover = crate::vocabulary::declarations_by_class(&sheet);
    // What a hand-written sheet answers to: makeover's classes and every
    // upstream sheet's, merged per class.
    let mut owned = makeover.clone();
    for sheet in upstream {
        for (class, properties) in crate::vocabulary::declarations_by_class(sheet) {
            owned.entry(class).or_default().extend(properties);
        }
    }
    // The same two views one level down: per arm rather than per class, so a
    // variant the generated sheet styles is not folded into its base.
    let makeover_variants = crate::vocabulary::variants_by_class(&sheet);
    let mut owned_variants = makeover_variants.clone();
    for sheet in upstream {
        for (class, arms) in crate::vocabulary::variants_by_class(sheet) {
            let entry = owned_variants.entry(class).or_default();
            for (arm, properties) in arms {
                entry.entry(arm).or_default().extend(properties);
            }
        }
    }
    let mut cancels: Vec<String> = Vec::new();
    let mut clashes: Vec<String> = Vec::new();
    let mut seen: Vec<(String, String)> = Vec::new();
    let mut element_clashes: Vec<String> = Vec::new();
    let mut element_seen: Vec<(String, String, String)> = Vec::new();

    for path in paths {
        rerun(path);
        let raw = read(path);
        let name = shown(path, root);
        // An upstream sheet served from the frontend answers to makeover alone:
        // measured against itself every declaration in it would clash.
        let (generated, variants) = if upstream.contains(&raw.as_str()) {
            (&makeover, &makeover_variants)
        } else {
            (&owned, &owned_variants)
        };
        // A layer ordered before `makeover` cannot beat it, so its rules are
        // not read. See `Vocabulary::beneath`.
        let raw = drop_layers(&raw, beneath);
        // Read the app's sheet the same way the crate reads its own, or the two
        // sides are not comparable.
        let local = crate::vocabulary::declarations_by_class(&raw);
        for (class, properties) in &local {
            let Some(theirs) = generated.get(class) else {
                continue;
            };
            for property in properties.intersection(theirs) {
                seen.push((class.clone(), property.clone()));
                if allowed.contains(&(class.as_str(), property.as_str())) {
                    continue;
                }
                clashes.push(format!("  {name}  .{class} {{ {property} }}"));
            }
        }

        // The layer pass. A rule on the bare class reaches every element
        // carrying it, and from a later layer it beats every variant the design
        // system styles on that class, whatever their specificity. The class
        // pass cannot see this once the pair is reviewed: an `Allow` for
        // (button, color) written for one arm licensed cancelling
        // `[data-tone="danger"]` too, and goingson's destructive buttons lost
        // their tone that way. So no `Allow` silences it. The remedy is always
        // available: restate the variant, on its own arm, in the app's sheet.
        // A layer this sheet itself orders below makeover cannot cancel a
        // variant either, so it is read the way `beneath` is.
        let own_below = layers_ordered_below_makeover(&raw);
        let own_below: Vec<&str> = own_below.iter().map(String::as_str).collect();
        let above = drop_layers(&raw, &own_below);
        let bare = crate::vocabulary::bare_declarations(&above);
        let restated = crate::vocabulary::mentions_by_arm(&raw);
        for (class, properties) in &bare {
            let Some(arms) = variants.get(class) else {
                continue;
            };
            for property in properties {
                let lost: Vec<&str> = arms
                    .iter()
                    .filter(|(arm, theirs)| {
                        theirs.contains(property)
                            && !restated
                                .get(arm.as_str())
                                .is_some_and(|mentioned| mentioned.contains(property))
                    })
                    .map(|(arm, _)| arm.as_str())
                    .collect();
                if lost.is_empty() {
                    continue;
                }
                cancels.push(format!(
                    "  {name}  .{class} {{ {property} }}  cancels  {}",
                    lost.iter()
                        .map(|arm| format!("{arm} {{ {property} }}"))
                        .collect::<Vec<_>>()
                        .join(", ")
                ));
            }
        }

        // The second pass: a rule carrying no class at all, which the first one
        // cannot see. What the app says about the class itself settles the
        // pair, but only from a rule that outranks the element rule. Both are
        // the app's and both are in the same layer, so this one contest is
        // decided by specificity. `.field` does not beat `input[type="text"]`.
        let mentioned = crate::vocabulary::mentions_by_class(&raw);
        let by_element = crate::vocabulary::declarations_by_element(&raw);
        for (element, properties) in &by_element {
            for class in crate::vocabulary::classes_for_element(element, opts) {
                let Some(theirs) = generated.get(&class) else {
                    continue;
                };
                for (property, rank) in properties {
                    if !theirs.contains(property) {
                        continue;
                    }
                    // A tie goes to the class rule: at equal specificity the
                    // later rule wins, and a remedy is written after the rule
                    // it remedies.
                    let spoken_for = mentioned
                        .get(&class)
                        .and_then(|properties| properties.get(property))
                        .is_some_and(|theirs| theirs >= rank);
                    if spoken_for {
                        continue;
                    }
                    element_seen.push((element.clone(), class.clone(), property.clone()));
                    if allowed_elements.contains(&(
                        element.as_str(),
                        class.as_str(),
                        property.as_str(),
                    )) {
                        continue;
                    }
                    element_clashes.push(format!(
                        "  {name}  {element} {{ {property} }}  beats  .{class} {{ {property} }}"
                    ));
                }
            }
        }
    }

    assert!(
        cancels.is_empty(),
        "{} hand-written rule(s) on a bare generated class set a property the \
         design system varies on that class by state, tone or context. The app \
         sheet sits in a later cascade layer than @layer makeover, and layers \
         resolve before specificity, so each of these beats every variant named \
         beside it, everywhere:\n{}\n\nDelete the declaration, or restate each \
         cancelled variant in the app's sheet on its own arm, after the bare rule \
         (`color: revert-layer` hands the design system's value back). That is \
         the remedy the cascade allows; an allowed-list entry does not cover \
         this, because the reviewed pair is the class and the variants are \
         what it silently takes.",
        cancels.len(),
        cancels.join("\n")
    );

    assert!(
        clashes.is_empty(),
        "{} hand-written declaration(s) take a property the generated stylesheet, \
         or an upstream sheet named to this check, already sets on the same \
         class. App CSS wins over @layer makeover, whether by a later layer or \
         by being unlayered, so each of these wins over the design system \
         silently:\n{}\n\nDelete the declaration, or, if \
         it is a deliberate pairing on a different selector arm, add \
         (class, property) to this check's allowed list and say why beside it. \
         Count the consumers before deciding a divergence is worth keeping.",
        clashes.len(),
        clashes.join("\n")
    );

    assert!(
        element_clashes.is_empty(),
        "{} hand-written element rule(s) take a property the generated \
         stylesheet sets on a class that element carries. App CSS wins over \
         @layer makeover, whether by a later layer or by being unlayered, so a \
         described component rendered on one of these elements loses the \
         design system's version of that property silently, which can draw a \
         destructive act like an ordinary one:\n{}\n\nHand the \
         property back on the arms makeover paints \
         (`.{{class}}:disabled {{ color: revert-layer }}`), scope the element \
         rule so it stops reaching described markup, or add \
         (element, class, property) to this check's allowed-elements list and \
         say why beside it.",
        element_clashes.len(),
        element_clashes.join("\n")
    );

    assert_no_stale("allowed", allowed, |(class, property)| {
        seen.contains(&((*class).to_string(), (*property).to_string()))
    });
    assert_no_stale(
        "allowed-elements",
        allowed_elements,
        |(element, class, property)| {
            element_seen.contains(&(
                (*element).to_string(),
                (*class).to_string(),
                (*property).to_string(),
            ))
        },
    );
}

/// Fail on an allowed-list entry that no longer collides with anything.
fn assert_no_stale<T: std::fmt::Debug>(list: &str, entries: &[T], used: impl Fn(&T) -> bool) {
    let stale: Vec<&T> = entries.iter().filter(|entry| !used(entry)).collect();
    assert!(
        stale.is_empty(),
        "the {list} list declares {stale:?}, which no longer collides with \
         anything. Delete the entries: an exception nobody is using is where the \
         next real collision lands and reads as company."
    );
}

/// Whether `haystack` names `class` whole, rather than as part of a longer
/// name: `min-1` must not be read as used because `min-16` is, and `row` must
/// not be read as used because `row-flex` or `flex-row` is.
fn haystack_names(haystack: &str, class: &str) -> bool {
    haystack.match_indices(class).any(|(at, found)| {
        haystack[..at]
            .chars()
            .next_back()
            .is_none_or(|c| !is_ident(c))
            && haystack[at + found.len()..]
                .chars()
                .next()
                .is_none_or(|c| !is_ident(c))
    })
}

/// Warn when the generated vocabulary has grown dead, and fail when it grows
/// deader than the recorded high-water mark.
///
/// A generated class no markup emits is a rule shipped to every user for
/// nothing. Some dead vocabulary is normal, so the count alone is not a
/// failure; what this checks is the direction. Recording the count in the
/// build script makes a change that worsens it fail rather than go unnoticed.
///
/// One-sided, the same shape as the MNW server's `frontend_globals` seal:
/// exceeding `high_water` fails, coming in under it warns and asks for the seal
/// to be lowered. A build that fails because dead CSS was deleted would teach
/// the wrong lesson.
///
/// `markup` is every file that can carry a class: templates, `.js`, `.html`,
/// and any Rust that writes markup. A class is counted as used if its name
/// appears whole in any of them, which is deliberately generous. A stricter reading
/// would need to know how each app builds its class strings, and a check that
/// guesses wrong fails a correct build.
///
/// # Panics
///
/// If a listed file cannot be read, or if more classes are unused than
/// `high_water`.
pub fn check_vocabulary_use<P: AsRef<Path>>(markup: &[P], opts: &Emit, high_water: usize) {
    let generated = crate::vocabulary::names(opts);
    let mut haystack = String::new();
    for path in markup {
        let path = path.as_ref();
        rerun(path);
        haystack.push_str(&read(path));
        haystack.push('\n');
    }

    // A ladder is one piece of vocabulary, not one per rung. A column carries
    // whichever `min-N` rung its floor lands on and a table whichever `short-N`
    // `stacks-N` and `drop-*-N` rungs its floors need, so no site names every rung and counting each
    // would seal the dead count at the ladder's length. A ladder is used if any
    // rung is, and counted once if none is.
    const LADDERS: &[&str] = &[
        "min-",
        "short-",
        "stacks-",
        "drop-optional-",
        "drop-secondary-",
    ];
    let rung_of = |class: &str| -> Option<&'static str> {
        let name = class.strip_prefix(opts.class_prefix)?;
        LADDERS.iter().copied().find(|ladder| {
            name.strip_prefix(ladder)
                .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
        })
    };
    let mut unused: Vec<String> = generated
        .iter()
        .filter(|class| rung_of(class).is_none() && !haystack_names(&haystack, class))
        .cloned()
        .collect();
    for ladder in LADDERS {
        let rungs: Vec<&String> = generated
            .iter()
            .filter(|class| rung_of(class) == Some(ladder))
            .collect();
        if !rungs.is_empty() && !rungs.iter().any(|class| haystack_names(&haystack, class)) {
            unused.push(format!("{}{ladder}N", opts.class_prefix));
        }
    }

    assert!(
        unused.len() <= high_water,
        "{} of {} generated classes are emitted by no markup, above the recorded {}. \
         The vocabulary grew or the markup stopped using it:\n{}",
        unused.len(),
        generated.len(),
        high_water,
        unused
            .iter()
            .map(|c| format!("  .{c}"))
            .collect::<Vec<_>>()
            .join("\n")
    );

    if unused.len() < high_water {
        println!(
            "cargo::warning=dead makeover vocabulary is down to {} from a sealed {}; \
             lower the seal so it cannot grow back",
            unused.len(),
            high_water
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::scratch;
    use std::fmt::Write as _;

    fn write(dir: &Path, name: &str, src: &str) {
        if let Some(parent) = dir.join(name).parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(dir.join(name), src).unwrap();
    }

    fn declaring() -> String {
        format!(
            "const {CONST_NAME} = '{}';\n",
            Density::Touch.media_condition()
        )
    }

    #[test]
    fn the_crates_own_string_passes() {
        let dir = scratch("ok");
        write(&dir, "touch.js", &declaring());
        check_touch_density(&dir);
    }

    #[test]
    #[should_panic(expected = "disagrees with makeover_geometry::Density")]
    fn a_drifted_literal_fails() {
        let dir = scratch("drift");
        write(&dir, "touch.js", &declaring());
        write(
            &dir,
            "haptics.js",
            &format!("const {CONST_NAME} = '(pointer: coarse)';\n"),
        );
        check_touch_density(&dir);
    }

    #[test]
    #[should_panic(expected = "device sniff")]
    fn the_sniff_cannot_come_back() {
        let dir = scratch("sniff");
        write(&dir, "touch.js", &declaring());
        write(&dir, "legacy.js", "if ('ontouchstart' in window) {}\n");
        check_touch_density(&dir);
    }

    #[test]
    #[should_panic(expected = "no TOUCH_DENSITY literal found")]
    fn a_frontend_that_states_nothing_fails() {
        let dir = scratch("empty");
        write(&dir, "app.js", "export const x = 1;\n");
        check_touch_density(&dir);
    }

    #[test]
    fn a_use_site_is_not_a_declaration() {
        // The const is read far more often than it is declared, and a read
        // states no string. Counting one as a declaration would make the
        // `found > 0` assertion pass on a frontend that only imports it.
        let src =
            format!("import {{ {CONST_NAME} }} from './touch.js';\nmatchMedia({CONST_NAME});\n");
        assert!(
            touch_density_literals(&src).is_empty(),
            "{:?}",
            touch_density_literals(&src)
        );
    }

    #[test]
    fn whitespace_and_backtick_literals_read() {
        let want = Density::Touch.media_condition();
        for src in [
            format!("const {CONST_NAME}='{want}';\n"),
            format!("const {CONST_NAME} = `{want}`;\n"),
            format!("const {CONST_NAME} =\n  '{want}';\n"),
        ] {
            let found = touch_density_literals(&src);
            assert_eq!(found.len(), 1, "src: {src:?}");
            assert_eq!(found[0].1, want, "src: {src:?}");
        }
    }

    #[test]
    fn a_longer_identifier_is_not_the_const() {
        // A substring hit on the name must not pass as the declaration.
        let want = Density::Touch.media_condition();
        for src in [
            format!("const OLD_{CONST_NAME} = '{want}';\n"),
            format!("const {CONST_NAME}_OLD = '{want}';\n"),
        ] {
            assert!(touch_density_literals(&src).is_empty(), "src: {src:?}");
        }
    }

    #[test]
    #[should_panic(expected = "no TOUCH_DENSITY literal found")]
    fn a_commented_out_declaration_is_not_a_declaration() {
        // The real const can be deleted and a `//`-prefixed copy left behind;
        // the check must not count that as a declaration.
        let dir = scratch("commented-decl");
        write(
            &dir,
            "touch.js",
            &format!("// {}\n", declaring().trim_end()),
        );
        check_touch_density(&dir);
    }

    #[test]
    fn a_sniff_named_in_a_comment_is_not_a_use() {
        // The word appears, but only in prose about why the check exists.
        let dir = scratch("sniff-comment");
        write(&dir, "touch.js", &declaring());
        write(
            &dir,
            "note.js",
            "// never read ontouchstart or maxTouchPoints here\n",
        );
        check_touch_density(&dir);
    }

    #[test]
    #[should_panic(expected = "disagrees with makeover_geometry::Density")]
    fn a_wrong_literal_without_spaces_is_caught() {
        // The old reader required ` = ` and skipped this spelling entirely.
        let dir = scratch("loose-drift");
        write(&dir, "touch.js", &declaring());
        write(
            &dir,
            "haptics.js",
            &format!("const {CONST_NAME}='(pointer: coarse)';\n"),
        );
        check_touch_density(&dir);
    }

    #[test]
    fn nested_files_are_read() {
        // The server keeps its scripts in subdirectories, and the nested half
        // is the half most likely to be a copy.
        let dir = scratch("nested");
        write(&dir, "touch.js", &declaring());
        write(&dir, "screens/legacy.js", "navigator.maxTouchPoints > 0;\n");
        let files = js_files(&dir);
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn a_non_js_file_is_ignored() {
        let dir = scratch("nonjs");
        write(&dir, "touch.js", &declaring());
        write(&dir, "styles.css", "body { }\n");
        assert_eq!(js_files(&dir).len(), 1);
    }

    fn frontend(name: &str) -> PathBuf {
        let dir = scratch(name);
        std::fs::create_dir_all(dir.join("css")).unwrap();
        std::fs::create_dir_all(dir.join("js")).unwrap();
        dir
    }

    /// A width every size class agrees is a boundary.
    fn boundary() -> u16 {
        SizeClass::Medium.min_px()
    }

    #[test]
    fn the_crates_own_boundaries_pass() {
        let dir = frontend("bp-ok");
        write(
            &dir,
            "css/styles.css",
            &format!("@media (min-width: {}px) {{ body {{ }} }}\n", boundary()),
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
    fn a_stale_css_width_fails() {
        let dir = frontend("bp-css");
        write(&dir, "css/styles.css", "@media (max-width: 768px) { }\n");
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
    fn a_stale_js_width_fails() {
        let dir = frontend("bp-js");
        write(&dir, "js/shell.js", "matchMedia('(max-width: 768px)');\n");
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    fn a_declared_tuning_width_passes() {
        let dir = frontend("bp-tuning");
        write(&dir, "css/styles.css", "@media (min-width: 1400px) { }\n");
        Breakpoints::in_frontend(&dir).tuning(&[1400]).run();
    }

    #[test]
    fn a_container_query_on_a_shell_boundary_passes() {
        // `@container screen (width < 600px)` is a media query in disguise: the
        // `screen` container tracks the shell, so its width must be a SizeClass
        // boundary. 600 is one.
        let dir = frontend("bp-container-ok");
        write(
            &dir,
            "css/styles.css",
            &format!("@container screen (width < {}px) {{ }}\n", boundary()),
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
    fn a_stale_container_width_fails() {
        let dir = frontend("bp-container-stale");
        write(
            &dir,
            "css/styles.css",
            "@container screen (width < 768px) { }\n",
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    fn a_container_inline_size_condition_is_not_a_width_boundary() {
        // An inline-size container query on a component (`tab-strip`) is not a
        // shell width and reads no `width` feature, so it is left alone.
        let dir = frontend("bp-container-inline");
        write(
            &dir,
            "css/styles.css",
            "@container tab-strip (inline-size < 36rem) { }\n",
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    fn a_width_in_a_comment_is_prose() {
        // The note explaining which breakpoint used to be here is not a rule,
        // and failing a build on documentation would teach people to delete it.
        let dir = frontend("bp-comment");
        write(
            &dir,
            "css/styles.css",
            "/* was @media (max-width: 768px) until the size classes landed */\n",
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    fn an_unparenthesized_width_is_not_a_breakpoint() {
        // A JS string building an inline style states `max-width: 320px` with
        // no parentheses. It is a declaration, not a query, and the first
        // version of this check failed the build on one.
        let dir = frontend("bp-inline");
        write(
            &dir,
            "js/style.js",
            "el.style.cssText = 'max-width: 320px; display: block';\n",
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    fn nested_css_is_read() {
        // Same argument as the touch check: the nested half is the half most
        // likely to be a copy.
        let dir = frontend("bp-nested");
        write(
            &dir,
            "css/screens/detail.css",
            "@media (max-width: 768px) { }\n",
        );
        let found = std::panic::catch_unwind(|| Breakpoints::in_frontend(&dir).run());
        assert!(found.is_err(), "a nested stylesheet must be scanned");
    }

    #[test]
    fn a_css_only_frontend_scans_without_a_js_directory() {
        // A CSS-only frontend ships no `js/`, and the recommended `in_frontend`
        // form must scan the stylesheets rather than fail on the absent tree.
        let dir = scratch("bp-css-only");
        write(
            &dir,
            "css/styles.css",
            &format!("@media (min-width: {}px) {{ body {{ }} }}\n", boundary()),
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    fn a_named_list_is_checked() {
        let dir = frontend("bp-list");
        write(&dir, "css/style.css", "@media (max-width: 768px) { }\n");
        let listed = dir.join("css/style.css");
        let err = std::panic::catch_unwind(|| Breakpoints::files(&[&listed]).run()).unwrap_err();
        let msg = err.downcast_ref::<String>().expect("String payload");
        assert!(msg.contains("style.css:1"), "got: {msg}");
    }

    #[test]
    #[should_panic(expected = "read ")]
    fn a_listed_file_that_is_gone_fails() {
        // The list is hand-maintained, so a path that stopped existing is a
        // check quietly covering less than it claims. Louder than skipping it.
        let dir = frontend("bp-missing");
        Breakpoints::files(&[dir.join("css/never-written.css")]).run();
    }

    #[test]
    fn a_listed_js_file_is_parsed_as_script() {
        // The unparenthesized-declaration rule is what separates the two, and
        // picking the parser off the extension is the whole difference.
        let dir = frontend("bp-list-js");
        write(
            &dir,
            "js/style.js",
            "el.style.cssText = 'max-width: 320px';\n",
        );
        Breakpoints::files(&[dir.join("js/style.js")]).run();
    }

    #[test]
    fn the_error_names_the_file_and_line() {
        let dir = frontend("bp-message");
        write(
            &dir,
            "css/styles.css",
            "body { }\n@media (max-width: 768px) { }\n",
        );
        let err = std::panic::catch_unwind(|| Breakpoints::in_frontend(&dir).run()).unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(msg.contains("css/styles.css:2"), "got: {msg}");
    }

    #[test]
    fn a_rule_restating_an_upstream_class_fails_and_its_served_copy_does_not() {
        // quasi-webview's sheet owns `.run`'s gap the way makeover owns
        // `.card`'s shadow, and an app redrawing it wins silently the same way.
        let upstream = ".tile-set { gap: 4px; }\n";
        let dir = scratch("vocab-upstream");
        write(&dir, "css/quasi.css", upstream);
        write(&dir, "css/styles.css", ".tile-set { gap: 0; }\n");
        let err = std::panic::catch_unwind(|| {
            Vocabulary::in_frontend(&dir)
                .upstream(&[upstream])
                .run(&Emit::default());
        })
        .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(
            msg.contains("css/styles.css  .tile-set { gap }"),
            "got: {msg}"
        );
        assert!(
            !msg.contains("css/quasi.css"),
            "the served copy clashed with itself: {msg}"
        );

        // Without the upstream sheet named, the same tree passes, which is the
        // blind spot this closes.
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn a_rule_restating_a_generated_class_fails_and_names_it() {
        let dir = scratch("vocab-clash");
        // `.card` is makeover's. An app rule for it beats the generated one,
        // because app CSS is unlayered and the generated sheet is not.
        write(
            &dir,
            "css/styles.css",
            "body { color: red; }\n.card { box-shadow: none; }\n",
        );
        let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
            .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(msg.contains(".card"), "got: {msg}");
        assert!(msg.contains("box-shadow"), "got: {msg}");
        assert!(msg.contains("css/styles.css"), "got: {msg}");
    }

    #[test]
    fn an_app_class_of_its_own_is_left_alone() {
        let dir = scratch("vocab-clean");
        write(
            &dir,
            "css/styles.css",
            ".task-list-container { overflow: auto; }\n.day-plan-slot { height: 1rem; }\n",
        );
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn the_generated_sheet_is_skipped_rather_than_reported_against_itself() {
        let dir = scratch("vocab-generated");
        let opts = Emit::default();
        write(&dir, "css/layout.css", &crate::stylesheet(&opts));
        // Without the skip this is the loudest failure possible: every class in
        // the vocabulary, reported as a clash with the vocabulary.
        Vocabulary::in_frontend(&dir)
            .generated(&["layout.css"])
            .run(&opts);
    }

    #[test]
    fn a_prefixed_app_is_checked_against_its_own_prefix() {
        let dir = scratch("vocab-prefix");
        let opts = Emit::new().class_prefix("mo-");
        // Bare `.card` is the app's own class once the generated sheet writes
        // `.mo-card`, so this has to pass.
        write(&dir, "css/styles.css", ".card { box-shadow: none; }\n");
        Vocabulary::in_frontend(&dir).run(&opts);

        let dir = scratch("vocab-prefix-clash");
        write(&dir, "css/styles.css", ".mo-card { box-shadow: none; }\n");
        assert!(std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&opts)).is_err());
    }

    #[test]
    fn a_class_shared_without_a_shared_property_is_left_alone() {
        let dir = scratch("vocab-additive");
        // The generated `.cell-value` sets only the text colour, so an app
        // setting its shape shares the class and takes nothing from it.
        write(
            &dir,
            "css/styles.css",
            ".cell-value { padding: 2px; border-radius: 3px; font-weight: 600; }\n",
        );
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn a_reviewed_pair_passes_and_stops_passing_when_it_stops_colliding() {
        let dir = scratch("vocab-allowed");
        write(&dir, "css/styles.css", ".badge { padding: 0; }\n");
        Vocabulary::in_frontend(&dir)
            .allow(Allow::class("badge", "padding"))
            .run(&Emit::default());

        // The same licence against a sheet that no longer collides has to fail,
        // or the list only ever grows.
        let dir = scratch("vocab-allowed-stale");
        write(&dir, "css/styles.css", ".card { padding: 2px; }\n");
        let err = std::panic::catch_unwind(|| {
            Vocabulary::in_frontend(&dir)
                .allow(Allow::class("badge", "padding"))
                .run(&Emit::default());
        })
        .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(msg.contains("no longer collides"), "got: {msg}");
    }

    #[test]
    fn an_element_rule_clobbering_a_generated_class_fails_and_names_all_three() {
        let dir = scratch("vocab-element");
        // The defect that shipped for months: no class in the selector, so the
        // class pass sees nothing, and every described act in the app takes the
        // app's bevel instead of the design system's.
        write(&dir, "css/styles.css", "select { box-shadow: none; }\n");
        let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
            .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(msg.contains("select {"), "got: {msg}");
        assert!(msg.contains(".field"), "got: {msg}");
        assert!(msg.contains("box-shadow"), "got: {msg}");
        assert!(msg.contains("css/styles.css"), "got: {msg}");
    }

    #[test]
    fn a_universal_reset_after_the_design_system_is_caught() {
        // goingson and MNW both opened with `* { margin: 0; padding: 0 }` in a
        // layer after `makeover`, which zeroed every generated padding. Nothing
        // said so until a render showed cells with no padding.
        let dir = scratch("vocab-universal");
        write(&dir, "css/styles.css", "* { margin: 0; padding: 0; }\n");
        let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
            .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(msg.contains("* {"), "got: {msg}");
        assert!(msg.contains("padding"), "got: {msg}");
    }

    #[test]
    fn a_universal_reset_in_a_layer_beneath_makeover_is_not_read() {
        let dir = scratch("vocab-universal-beneath");
        write(
            &dir,
            "css/styles.css",
            "/* { */ @layer reset {\n  * { margin: 0; padding: 0; }\n}\n.x { content: \"}\"; }\n",
        );
        Vocabulary::in_frontend(&dir)
            .beneath(&["reset"])
            .run(&Emit::default());
    }

    #[test]
    fn an_important_rule_in_a_layer_beneath_makeover_is_still_read() {
        let dir = scratch("vocab-important-beneath");
        // `!important` inverts layer order, so an important declaration in a
        // layer beneath makeover beats every later layer. The reduced-motion
        // idiom writes exactly this shape, and dropping the layer whole would
        // hide the override.
        write(
            &dir,
            "css/styles.css",
            "@layer reset {\n  .field { box-shadow: none !important; }\n}\n",
        );
        let err = std::panic::catch_unwind(|| {
            Vocabulary::in_frontend(&dir)
                .beneath(&["reset"])
                .run(&Emit::default());
        })
        .unwrap_err();
        let msg = err.downcast_ref::<String>().expect("a String payload");
        assert!(msg.contains("box-shadow"), "got: {msg}");
    }

    #[test]
    fn a_layer_not_named_beneath_is_still_read() {
        let dir = scratch("vocab-universal-other-layer");
        write(
            &dir,
            "css/styles.css",
            "@layer base {\n  * { padding: 0; }\n}\n",
        );
        let err = std::panic::catch_unwind(|| {
            Vocabulary::in_frontend(&dir)
                .beneath(&["reset"])
                .run(&Emit::default());
        })
        .unwrap_err();
        let msg = err.downcast_ref::<String>().expect("a String payload");
        assert!(msg.contains("* {"), "got: {msg}");
    }

    #[test]
    fn a_universal_rule_touching_nothing_generated_is_not_a_clash() {
        let dir = scratch("vocab-universal-box");
        write(&dir, "css/styles.css", "* { box-sizing: border-box; }\n");
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn a_handoff_on_the_class_is_the_remedy_and_reads_as_one() {
        let dir = scratch("vocab-element-handoff");
        // What a consumer writes instead of an exception: the element rule
        // stays, and a later layer gives the property back on the class. The
        // check has to read that as settled or the remedy fails the build it
        // was written to fix.
        write(
            &dir,
            "css/styles.css",
            "select { box-shadow: none; }\n.field { box-shadow: revert-layer; }\n",
        );
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn a_property_the_app_states_on_the_class_is_not_the_element_rules_doing() {
        let dir = scratch("vocab-element-spoken-for");
        // Within the app's own sheet the class rule outranks the bare element
        // rule, so what reaches the design system is `.button`, not `button`.
        // The class pass has that pair, here as a reviewed one, and
        // reporting it twice would ask for two remedies for one collision.
        write(
            &dir,
            "css/styles.css",
            "select { box-shadow: none; }\n.field { box-shadow: none; }\n\
             .field:disabled,\n.field[aria-disabled=\"true\"],\n\
             .field[aria-invalid=\"true\"] {\n    box-shadow: revert-layer;\n}\n",
        );
        Vocabulary::in_frontend(&dir)
            .allow(Allow::class("field", "box-shadow"))
            .run(&Emit::default());
    }

    #[test]
    fn a_handoff_that_loses_to_the_rule_it_remedies_is_not_a_remedy() {
        let dir = scratch("vocab-element-weak-handoff");
        // The shape that reads as fixed and is not: both rules are the app's
        // and both are in the same layer, so the state on the element rule
        // decides, and the described field keeps the app's sunken fill.
        write(
            &dir,
            "css/styles.css",
            "select:focus { box-shadow: none; }\n.field { box-shadow: revert-layer; }\n",
        );
        let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
            .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(msg.contains(".field"), "got: {msg}");

        // Written to win, it is.
        let dir = scratch("vocab-element-strong-handoff");
        write(
            &dir,
            "css/styles.css",
            "select:focus { box-shadow: none; }\nselect.field { box-shadow: revert-layer; }\n",
        );
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn a_scoped_rule_is_not_read_as_an_element_rule() {
        let dir = scratch("vocab-element-scoped");
        // It reaches the buttons inside one region rather than every button, so
        // whether it lands on a described act depends on where that act
        // renders. Failing the build on a guess is the worse error.
        write(
            &dir,
            "css/styles.css",
            ".wizard select { box-shadow: none; }\n",
        );
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn an_element_the_design_system_never_renders_onto_is_left_alone() {
        let dir = scratch("vocab-element-unpaired");
        // `.card` is a container: no generated class sits on a `<footer>`, so
        // there is nothing for this rule to take.
        write(&dir, "css/styles.css", "footer { box-shadow: none; }\n");
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn a_bare_rule_that_cancels_a_tone_fails_even_when_the_pair_is_reviewed() {
        // goingson's case: a property on `.button` in the app layer beat
        // every `.button[data-tone]` arm, and the reviewed pair is what kept
        // the class pass quiet about it. The tone paints the ground now, so
        // the property that cancels it is `background`.
        let dir = scratch("vocab-cancel-tone");
        write(
            &dir,
            "css/styles.css",
            ".button { background: var(--surface-raised); }\n",
        );
        let err = std::panic::catch_unwind(|| {
            Vocabulary::in_frontend(&dir)
                .allow(Allow::class("button", "background"))
                .run(&Emit::default());
        })
        .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(
            msg.contains(".button { background }  cancels"),
            "got: {msg}"
        );
        assert!(
            msg.contains(".button[data-tone=\"danger\"] { background }"),
            "the message names the variant it cancels: {msg}"
        );
        assert!(msg.contains("restate"), "and the remedy: {msg}");
    }

    #[test]
    fn restating_every_cancelled_variant_on_its_own_arm_passes() {
        // The remedy the message gives, spelled with single quotes and loose
        // whitespace to show the arms compare as selectors rather than bytes.
        let opts = Emit::default();
        let variants = crate::vocabulary::variants_by_class(&crate::stylesheet(&opts));
        let mut css = String::from(".button { background: var(--surface-raised); }\n");
        for (arm, properties) in &variants["button"] {
            if properties.contains("background") {
                let loose = arm.replace('"', "'").replace(',', " , ");
                let _ = writeln!(css, "{loose} {{ background: revert-layer; }}");
            }
        }
        let dir = scratch("vocab-cancel-restated");
        write(&dir, "css/styles.css", &css);
        Vocabulary::in_frontend(&dir)
            .allow(Allow::class("button", "background"))
            .run(&opts);
    }

    #[test]
    fn a_scoped_or_qualified_rule_cancels_nothing_this_can_prove() {
        // Neither reaches every `.button`, so whether one lands on a toned act
        // depends on markup the check does not read.
        let dir = scratch("vocab-cancel-scoped");
        write(
            &dir,
            "css/styles.css",
            ".toolbar .button { color: var(--content); }\n\
             .button.quiet { color: var(--content); }\n",
        );
        // The class pass still reads both as `.button` declarations; the pair
        // is reviewed here so only the layer pass is under test.
        Vocabulary::in_frontend(&dir)
            .allow(Allow::class("button", "color"))
            .run(&Emit::default());
    }

    #[test]
    fn a_layer_the_sheet_orders_below_makeover_cancels_nothing() {
        // quasi-webview's SCREEN_CSS, as an app serves it: its own statement
        // puts `quasi` under `makeover`, so its `.button { cursor }` loses to
        // the disabled arm rather than cancelling it.
        let dir = scratch("vocab-cancel-own-order");
        write(
            &dir,
            "css/quasi.css",
            "@layer reset, quasi, makeover;\n\
             @layer quasi {\n    .button { cursor: pointer; }\n}\n",
        );
        Vocabulary::in_frontend(&dir)
            .allow(Allow::class("button", "cursor"))
            .run(&Emit::default());

        // The same rule in a layer the statement puts above makeover does.
        let dir = scratch("vocab-cancel-own-order-above");
        write(
            &dir,
            "css/app.css",
            "@layer reset, makeover, app;\n\
             @layer app {\n    .button { cursor: pointer; }\n}\n",
        );
        let err = std::panic::catch_unwind(|| {
            Vocabulary::in_frontend(&dir)
                .allow(Allow::class("button", "cursor"))
                .run(&Emit::default());
        })
        .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(msg.contains(".button { cursor }  cancels"), "got: {msg}");
    }

    #[test]
    fn a_handoff_on_the_bare_class_cancels_nothing() {
        let dir = scratch("vocab-cancel-handoff");
        write(&dir, "css/styles.css", ".button { color: revert-layer; }\n");
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[test]
    fn a_reviewed_element_pairing_passes_and_stops_passing_when_it_stops_colliding() {
        let dir = scratch("vocab-element-allowed");
        write(&dir, "css/styles.css", "select { box-shadow: none; }\n");
        Vocabulary::in_frontend(&dir)
            .allow(Allow::element("select", "field", "box-shadow"))
            .run(&Emit::default());

        // And the same licence against a sheet that no longer collides fails,
        // for the reason the class list's does.
        let dir = scratch("vocab-element-allowed-stale");
        write(&dir, "css/styles.css", "select { padding: 2px; }\n");
        let err = std::panic::catch_unwind(|| {
            Vocabulary::in_frontend(&dir)
                .allow(Allow::element("select", "field", "box-shadow"))
                .run(&Emit::default());
        })
        .unwrap_err();
        let msg = err
            .downcast_ref::<String>()
            .expect("panic payload is a String");
        assert!(msg.contains("no longer collides"), "got: {msg}");
    }

    /// How many rung classes the vocabulary holds, and on how many ladders.
    fn ladders(names: &std::collections::BTreeSet<String>) -> (usize, usize) {
        let mut rungs = 0;
        let mut ladders = 0;
        for ladder in [
            "min-",
            "short-",
            "stacks-",
            "drop-optional-",
            "drop-secondary-",
        ] {
            let here = names
                .iter()
                .filter(|c| {
                    c.strip_prefix(ladder)
                        .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
                })
                .count();
            rungs += here;
            ladders += usize::from(here > 0);
        }
        (rungs, ladders)
    }

    #[test]
    fn dead_vocabulary_above_the_seal_fails_and_below_it_passes() {
        let dir = scratch("vocab-seal");
        let opts = Emit::default();
        let names = crate::vocabulary::names(&opts);
        let (rungs, ladders) = ladders(&names);
        assert!(ladders >= 1, "the floor ladder is in the vocabulary");
        // Markup naming nothing: every class is unused, and each ladder counts
        // once rather than once a rung.
        let dead = names.len() - rungs + ladders;
        write(&dir, "index.html", "<div></div>\n");
        let markup = [dir.join("index.html")];

        check_vocabulary_use(&markup, &opts, dead);
        assert!(
            std::panic::catch_unwind(|| check_vocabulary_use(&markup, &opts, dead - 1)).is_err(),
            "a vocabulary deader than the seal has to fail"
        );
    }

    #[test]
    fn one_rung_of_the_floor_ladder_uses_the_ladder() {
        // A column carries whichever rung its floor lands on, so a site naming
        // one rung is using the ladder, and one naming none has one dead name.
        let opts = Emit::default();
        let names = crate::vocabulary::names(&opts);
        let (rungs, ladders) = ladders(&names);
        let dead = names.len() - rungs + ladders;

        let dir = scratch("vocab-ladder");
        write(&dir, "index.html", "<div class=\"cell min-16\"></div>\n");
        let one_rung = [dir.join("index.html")];
        // `cell` is named too, so two fewer than a page naming nothing.
        check_vocabulary_use(&one_rung, &opts, dead - 2);

        // A longer rung does not name a shorter one it starts with.
        write(&dir, "index.html", "<div class=\"min-24\"></div>\n");
        assert!(haystack_names("<div class=\"min-24\">", "min-24"));
        assert!(!haystack_names("<div class=\"min-24\">", "min-2"));
    }

    #[test]
    fn a_class_is_named_whole_on_both_sides() {
        assert!(haystack_names("class=\"row\"", "row"));
        assert!(!haystack_names("class=\"row-flex\"", "row"));
        assert!(!haystack_names("class=\"flex-row\"", "row"));
        assert!(haystack_names("el.classList.add('row')", "row"));
    }

    #[test]
    fn range_syntax_and_units_are_read() {
        assert_eq!(media_widths("(width < 600px)"), [Width::Px(600)]);
        assert_eq!(
            media_widths(" (600px <= width < 840px)"),
            [Width::Px(600), Width::Px(840)]
        );
        assert_eq!(media_widths(" (max-width: 48em)"), [Width::Px(768)]);
        assert_eq!(media_widths(" (min-width: 37.5rem)"), [Width::Px(600)]);
        assert_eq!(
            media_widths(" (max-width: 599.98px)"),
            [Width::Other("599.98px".into())]
        );
        assert_eq!(
            media_widths(" (width < 50vw)"),
            [Width::Other("50vw".into())]
        );
        let found = media_widths(" (min-height: 600px)");
        assert!(found.is_empty(), "{found:?}");
        let found = media_widths(" (max-device-width: 600px)");
        assert!(found.is_empty(), "{found:?}");
        let found = media_widths(" (hover: hover) and (pointer: fine)");
        assert!(found.is_empty(), "{found:?}");
    }

    #[test]
    fn every_size_class_condition_passes_its_own_check() {
        let dir = frontend("bp-classes");
        let mut css = String::new();
        for class in SizeClass::all() {
            let _ = writeln!(css, "@media {} {{ body {{ }} }}", class.media_condition());
        }
        write(&dir, "css/styles.css", &css);
        write(
            &dir,
            "js/shell.js",
            &format!("matchMedia('{}');\n", SizeClass::Compact.media_condition()),
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    #[should_panic(expected = "48em")]
    fn a_width_in_em_is_a_width_and_not_a_bare_number() {
        let dir = frontend("bp-em");
        write(&dir, "css/styles.css", "@media (max-width: 48em) { }\n");
        Breakpoints::in_frontend(&dir).tuning(&[48]).run();
    }

    #[test]
    #[should_panic(expected = "(width < 768px)")]
    fn a_stale_range_width_fails() {
        let dir = frontend("bp-range");
        write(&dir, "css/styles.css", "@media (width < 768px) { }\n");
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    #[should_panic(expected = "599px")]
    fn the_old_inclusive_compact_bound_is_stale() {
        let dir = frontend("bp-599");
        write(&dir, "css/styles.css", "@media (max-width: 599px) { }\n");
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    #[should_panic(expected = "(max-width: 600px)")]
    fn an_inclusive_bound_at_a_class_edge_is_stale() {
        // The number is a boundary, so a check that reads numbers alone lets
        // it through. At exactly 600px it agrees with Compact and the crate
        // says Medium.
        let dir = frontend("bp-600-inclusive");
        write(&dir, "css/styles.css", "@media (max-width: 600px) { }\n");
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    #[should_panic(expected = "(width <= 600px)")]
    fn an_inclusive_range_upper_bound_is_stale() {
        let dir = frontend("bp-le-600");
        write(&dir, "css/styles.css", "@media (width <= 600px) { }\n");
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    fn the_inclusive_lower_bound_and_edges_are_not_stale() {
        let dir = frontend("bp-edges-ok");
        write(
            &dir,
            "css/styles.css",
            "@media (min-width: 600px) { }\n\
             @media (600px <= width) { }\n\
             @media (width >= 840px) { }\n",
        );
        Breakpoints::in_frontend(&dir).run();
    }

    #[test]
    fn a_tuning_max_width_is_left_alone() {
        // No class sits on 1400px, so an inclusive bound there has nothing to
        // disagree with.
        let dir = frontend("bp-tuning-max");
        write(&dir, "css/styles.css", "@media (max-width: 1400px) { }\n");
        Breakpoints::in_frontend(&dir).tuning(&[1400]).run();
    }

    #[test]
    fn a_call_in_script_is_not_a_feature() {
        let found = js_widths("const w = Math.max(width, 600);");
        assert!(found.is_empty(), "{found:?}");
        let found = js_widths("el.style.cssText = 'max-width: 320px';");
        assert!(found.is_empty(), "{found:?}");
        assert_eq!(js_widths("matchMedia('(width < 600px)')").len(), 1);
    }

    #[test]
    fn a_slash_star_slash_opens_a_comment_rather_than_closing_one() {
        let css = "/*/ @media (max-width: 768px) { } */ a { }";
        let stripped = blank(css, Lang::Css);
        assert!(!stripped.contains("768"), "{stripped:?}");
        assert!(stripped.contains("a { }"));
        assert_eq!(stripped.len(), css.len());
    }

    #[test]
    fn a_comment_opener_inside_a_string_is_text() {
        // Read as a comment, the `/*` would blank the query after it.
        let css = "a::after { content: \"/*\"; }\n@media (max-width: 768px) { }\n";
        let src = blank(css, Lang::Css);
        assert_eq!(media_conditions(&src).len(), 1);
        assert!(src.contains("768"));

        let js = "const glob = '/*';\nmatchMedia('(width < 600px)');\n";
        assert_eq!(js_widths(&blank(js, Lang::Js)).len(), 1);
    }

    #[test]
    fn a_regex_literal_does_not_open_a_comment() {
        // `/\/*$/` matches trailing slashes; read as a block comment it blanks
        // every query after it.
        let js = "s.replace(/\\/*$/, '');\nmatchMedia('(width < 600px)');\n";
        assert_eq!(js_widths(&blank(js, Lang::Js)).len(), 1);
    }

    #[test]
    fn a_division_is_not_a_regex_literal() {
        // A `/` after a value divides; it must not swallow the line as regex.
        let js = "const half = a / b;\nmatchMedia('(width < 600px)');\n";
        assert_eq!(js_widths(&blank(js, Lang::Js)).len(), 1);
    }

    #[test]
    fn a_css_bad_string_ends_at_a_newline() {
        // An unterminated string is a parse error that ends at the newline;
        // read as an open string it swallows every rule after it.
        let css = "p::before { content: 'oops\n}\n@media (max-width: 768px) { }\n";
        let src = blank(css, Lang::Css);
        assert_eq!(media_conditions(&src).len(), 1);
        assert!(src.contains("768"));
    }

    #[test]
    fn an_escaped_quote_does_not_open_a_string() {
        let css = ".a\\'b { color: red; }\n@media (max-width: 768px) { }\n";
        let src = blank(css, Lang::Css);
        assert_eq!(media_conditions(&src).len(), 1);
    }

    #[test]
    fn an_unquoted_url_does_not_open_a_comment() {
        let css = "a { background: url(/img/*.png); }\n@media (max-width: 768px) { }\n";
        let src = blank(css, Lang::Css);
        assert_eq!(media_conditions(&src).len(), 1);
        // A quoted url is already text, and a comment after it still goes.
        let css = "a { background: url(\"/x/*.png\"); /* gone */ }\n\
                   @media (max-width: 768px) { }\n";
        let src = blank(css, Lang::Css);
        assert!(!src.contains("gone"), "{src:?}");
        assert_eq!(media_conditions(&src).len(), 1);
    }

    #[test]
    fn a_leading_dot_length_is_read() {
        // `.5em` is 8px, not the 80px the digits alone would give.
        assert_eq!(media_widths("(max-width: .5em)"), vec![Width::Px(8)]);
        assert_eq!(media_widths("(max-width: 37.5em)"), vec![Width::Px(600)]);
    }

    #[test]
    fn an_at_media_keyword_reads_in_any_case() {
        let conditions = media_conditions("@MEDIA (max-width: 768px) { body { } }");
        assert_eq!(conditions.len(), 1);
        assert_eq!(media_widths(conditions[0].1), vec![Width::Px(768)]);
    }

    #[test]
    fn a_width_nested_in_a_function_is_read() {
        assert_eq!(
            media_widths("(max-width: calc(768px))"),
            vec![Width::Px(768)]
        );
        // Arithmetic inside calc is read as its terms; the sum is not a clean
        // boundary, so nothing is silently skipped.
        assert!(media_widths("(max-width: calc(48em + 1px))").contains(&Width::Px(768)));
    }

    #[test]
    fn a_newline_does_not_reset_an_open_group() {
        assert_eq!(media_widths("(max-width:\n 768px)"), vec![Width::Px(768)]);
    }

    #[test]
    fn custom_media_and_import_carry_media_queries() {
        let css = "@custom-media --narrow (max-width: 768px);\n\
                   @import url(x.css) (max-width: 768px);\n";
        let conditions = media_conditions(css);
        assert_eq!(conditions.len(), 2);
        for (_, condition) in conditions {
            assert!(
                media_widths(condition).contains(&Width::Px(768)),
                "unread: {condition:?}"
            );
        }
    }

    #[test]
    fn a_query_in_a_script_comment_is_prose() {
        let js = "// was matchMedia('(width < 768px)')\n/* (max-width: 500px) */\n";
        let found = js_widths(&blank(js, Lang::Js));
        assert!(found.is_empty(), "{found:?}");
    }

    #[test]
    fn a_brace_inside_a_css_string_does_not_end_a_condition() {
        let css = "@media (width < 600px) { a::after { content: \"{\"; } }";
        let src = blank(css, Lang::Css);
        assert_eq!(media_conditions(&src).len(), 1);
    }

    #[test]
    fn blanking_keeps_byte_offsets_through_multibyte_text() {
        // An em dash in a comment and in a string: three bytes each, blanked
        // to three spaces, so everything after them sits where it did.
        let css = "/* a \u{2014} b */ a::after { content: \"\u{2014}\"; }\n@layer reset { * { padding: 0; } }";
        let src = blank(css, Lang::Css);
        assert_eq!(src.len(), css.len());
        let at = css.find("@layer").unwrap();
        assert_eq!(&src[at..at + 6], "@layer");
        let dropped = drop_layers(css, &["reset"]);
        assert!(!dropped.contains("padding"), "{dropped:?}");
    }

    #[test]
    fn a_dropped_layer_keeps_its_important_rules() {
        // `!important` inverts layer order, so a rule in a dropped layer marked
        // important beats the later makeover layer. Blanking the whole layer
        // would hide a real override; the rule stays and the rest is dropped.
        let css =
            "@layer reset {\n  * { padding: 0; }\n  .card { box-shadow: none !important; }\n}\n";
        let dropped = drop_layers(css, &["reset"]);
        assert!(!dropped.contains("padding"), "{dropped:?}");
        assert!(dropped.contains(".card"), "{dropped:?}");
        assert!(dropped.contains("box-shadow"), "{dropped:?}");
    }

    #[test]
    fn a_dropped_layer_reads_dotted_sublayers_and_uppercase() {
        let dotted = "@layer reset.base {\n  .x { color: red; }\n}\n";
        assert!(!drop_layers(dotted, &["reset"]).contains("color"));
        let upper = "@LAYER reset {\n  .x { color: red; }\n}\n";
        assert!(!drop_layers(upper, &["reset"]).contains("color"));
    }

    #[test]
    fn blanking_keeps_lines_and_offsets() {
        let css = "/* one\ntwo */\n\"x\ny\"\n@media (max-width: 1px) {}";
        let src = blank(css, Lang::Css);
        assert_eq!(src.len(), css.len());
        assert_eq!(src.lines().count(), css.lines().count());
    }

    #[test]
    fn both_quote_styles_read() {
        let want = Density::Touch.media_condition();
        for q in ['\'', '"'] {
            let src = format!("const {CONST_NAME} = {q}{want}{q};\n");
            let found = touch_density_literals(&src);
            assert_eq!(found.len(), 1);
            assert_eq!(found[0].1, want);
        }
    }

    #[test]
    fn a_file_list_skips_the_sheets_named_generated() {
        let dir = frontend("vocab-files");
        write(&dir, "css/layout.css", ".card { box-shadow: none; }\n");
        write(&dir, "css/app.css", "body { color: red; }\n");
        let files = [dir.join("css/layout.css"), dir.join("css/app.css")];
        Vocabulary::files(&files)
            .generated(&["layout.css"])
            .run(&Emit::default());
        let err = std::panic::catch_unwind(|| Vocabulary::files(&files).run(&Emit::default()))
            .unwrap_err();
        let msg = err.downcast_ref::<String>().cloned().unwrap_or_default();
        assert!(msg.contains("box-shadow"), "got: {msg}");
    }
}