makeover-webview 0.130.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
//! Checks that a hand-written frontend still agrees with the crates that
//! generate its siblings.
//!
//! Each check reads the consumer's hand-written stylesheets or scripts,
//! compares what they state with what the crates generate, and panics naming
//! the file and line of every disagreement. None of them rewrites a file.

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

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

mod breakpoints;
mod vocabulary_use;

pub use breakpoints::Breakpoints;
pub use vocabulary_use::{Allow, Vocabulary, check_vocabulary_use};

/// The name of the declaration [`check_touch_density`] reads.
const CONST_NAME: &str = "TOUCH_DENSITY";

/// The capability sniffs [`check_touch_density`] refuses in any `.js` file.
///
/// 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`].
///
/// Reads every `.js` file under `js_dir`, recursively, with comments blanked.
/// At least one of them must declare `const TOUCH_DENSITY = '...'`; every
/// declaration found must state [`Density::Touch`]'s media condition; no file
/// may name a capability sniff. A file with no declaration passes. The check
/// takes no policy argument: the string is the crate's, the same condition
/// the generated `geometry.css` keys its touch overrides on.
///
/// Emits `cargo::rerun-if-changed` for every file it read and for `js_dir`.
///
/// # Panics
///
/// If `js_dir` cannot be read, if no declaration is found, if a declaration
/// states another condition, or if any file names a sniff.
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.
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())
    }
}

/// 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 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
}

#[cfg(test)]
mod tests {
    use super::breakpoints::{Width, js_widths, media_conditions, media_widths};
    use super::vocabulary_use::{haystack_names, haystack_words};
    use super::*;
    use crate::Emit;
    use crate::test_support::scratch;
    use makeover_geometry::SizeClass;

    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(',', " , ");
                putln!(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 repro_own_below_layer_still_clashes() {
        // A layer the sheet's own statement orders below makeover cannot beat
        // a generated rule, so it needs no Allow for a clash that cannot happen.
        let dir = scratch("vocab-own-below-clash");
        write(
            &dir,
            "css/quasi.css",
            "@layer reset, quasi, makeover;\n\
             @layer quasi {\n    .button { cursor: pointer; }\n    button { color: red; }\n}\n",
        );
        Vocabulary::in_frontend(&dir).run(&Emit::default());
    }

    #[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-",
            "tiles-",
            "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 the_word_set_names_what_the_whole_word_search_names() {
        let haystack = "<div class=\"row min-24 mk-cell\">el.classList.add('flex-row')</div>";
        let words = haystack_words(haystack);
        for class in [
            "row", "min-24", "min-2", "mk-cell", "cell", "flex-row", "flex", "div", "iv",
        ] {
            assert_eq!(
                words.contains(class),
                haystack_names(haystack, class),
                "{class}"
            );
        }
    }

    #[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() {
            putln!(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}");
    }
}