Skip to main content

makeover_build/
drift.rs

1//! Checks that a hand-written frontend still agrees with the crate that
2//! generates its siblings.
3//!
4//! The generated files cannot drift: they ask makeover-geometry for the answer.
5//! The hand-written ones state it, and a stylesheet or a script that disagrees
6//! with the crate raises no error at any point. It is a rule that quietly
7//! stops matching where it used to. Cheaper to read a panic naming the line.
8//!
9//! Deliberately assertions and not substitutions. A JS or CSS file that has to
10//! be generated to be correct stops being readable on its own, and it is worth
11//! something that you can still open the frontend in a browser and have it
12//! work.
13
14use std::path::{Path, PathBuf};
15
16use makeover_geometry::{Density, SizeClass};
17use makeover_webview::Emit;
18
19/// The declaration this check reads. Shared vocabulary, not a parameter: two
20/// apps and a server naming the same string want the same name for it.
21const CONST_NAME: &str = "TOUCH_DENSITY";
22
23/// The capability sniffs the media query replaced, so neither can come back by
24/// copy-paste.
25///
26/// Both ask the hardware what it has rather than what is pointing at the
27/// screen, so both say yes to a touchscreen laptop driving a mouse.
28const SNIFFS: &[&str] = &["ontouchstart", "maxTouchPoints"];
29
30/// Fail the build if a JS copy of the touch-density query has drifted from
31/// [`Density::Touch`].
32///
33/// Every `.js` file under `js_dir`, recursively, must state the crate's own
34/// media condition in a `const TOUCH_DENSITY = '...'`, at least one file must
35/// declare it, and no file may name a capability sniff.
36///
37/// The string is the crate's and no app gets a say in it, which is why this
38/// check takes no policy argument. The generated `geometry.css` already keys
39/// its touch gap overrides on the same condition, so the gestures and the
40/// spacing agree by construction rather than by two people remembering.
41///
42/// Emits `cargo:rerun-if-changed` for every file it read.
43///
44/// # Panics
45///
46/// If `js_dir` cannot be read, if no declaration is found, or if any file
47/// disagrees with the crate. A build script has nowhere useful to return an
48/// error to, and a frontend that disagrees with its own stylesheet is worse
49/// than a failed build.
50pub fn check_touch_density(js_dir: impl AsRef<Path>) {
51    let js_dir = js_dir.as_ref();
52    let want = Density::Touch.media_condition();
53    let mut wrong: Vec<String> = Vec::new();
54    let mut found = 0usize;
55
56    let files = js_files(js_dir);
57    for path in &files {
58        let src = std::fs::read_to_string(path)
59            .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
60        let name = path
61            .strip_prefix(js_dir)
62            .unwrap_or(path)
63            .display()
64            .to_string();
65
66        for (offset, literal) in touch_density_literals(&src) {
67            found += 1;
68            if literal != want {
69                wrong.push(format!(
70                    "  {name}:{}  {CONST_NAME} = '{literal}'",
71                    line_of(&src, offset)
72                ));
73            }
74        }
75
76        for needle in SNIFFS {
77            if let Some(offset) = src.find(needle) {
78                wrong.push(format!(
79                    "  {name}:{}  {needle} -- device sniff, not a density question",
80                    line_of(&src, offset)
81                ));
82            }
83        }
84    }
85
86    assert!(
87        found > 0,
88        "no {CONST_NAME} literal found under {}.\n\n\
89         A frontend that asks whether it is being touched states\n\
90         makeover_geometry::Density::Touch's media condition in a const of that\n\
91         name, and this check exists to keep every copy equal to it. If the\n\
92         const was renamed, rename it back rather than dropping the check; if\n\
93         this frontend genuinely asks no density question, drop the call.",
94        js_dir.display()
95    );
96
97    assert!(
98        wrong.is_empty(),
99        "hand-written touch detection disagrees with makeover_geometry::Density.\n\n\
100         Density::Touch.media_condition() is: {want}\n\n\
101         Wrong:\n{}\n\n\
102         Fix the JS to state the crate's string. Never widen it to catch a\n\
103         device the query misses: density is what is pointing at the screen,\n\
104         and a laptop with a touchscreen and a mouse is a pointer device.",
105        wrong.join("\n")
106    );
107
108    for path in &files {
109        println!("cargo:rerun-if-changed={}", path.display());
110    }
111    // The directory too, so a file added under it reruns the check: a
112    // rerun keyed only on the files that existed last time never sees the
113    // one somebody just copied in.
114    println!("cargo:rerun-if-changed={}", js_dir.display());
115}
116
117/// Every `.js` file under `dir`, recursively, sorted.
118fn js_files(dir: &Path) -> Vec<PathBuf> {
119    files_with_extension(dir, "js")
120}
121
122/// Every file under `dir` with extension `ext`, recursively, sorted.
123///
124/// Recursive because a consumer's frontend is not always one flat directory:
125/// the Tauri apps keep `js/*.js`, the server keeps subdirectories under
126/// `static/`, and a check that silently skipped the nested half would report
127/// clean on the files most likely to have been copied.
128fn files_with_extension(dir: &Path, ext: &str) -> Vec<PathBuf> {
129    let mut out = Vec::new();
130    let mut stack = vec![dir.to_path_buf()];
131    while let Some(d) = stack.pop() {
132        for entry in std::fs::read_dir(&d)
133            .unwrap_or_else(|e| panic!("read {}: {e}", d.display()))
134            .flatten()
135        {
136            let path = entry.path();
137            if path.is_dir() {
138                stack.push(path);
139            } else if path.extension().is_some_and(|x| x == ext) {
140                out.push(path);
141            }
142        }
143    }
144    out.sort();
145    out
146}
147
148/// `(byte offset of the declaration, the literal's contents)` for every
149/// `const TOUCH_DENSITY = '...'` in a JS source.
150fn touch_density_literals(src: &str) -> Vec<(usize, &str)> {
151    let mut out = Vec::new();
152    let mut at = 0;
153    while let Some(i) = src[at..].find(CONST_NAME) {
154        let start = at + i;
155        at = start + CONST_NAME.len();
156        // Only the declaration states the string; a use site reads the const.
157        let Some(rest) = src[at..].strip_prefix(" = ") else {
158            continue;
159        };
160        let open = at + " = ".len();
161        let Some(quote @ ('\'' | '"')) = rest.chars().next() else {
162            continue;
163        };
164        let body = open + 1;
165        if let Some(j) = src[body..].find(quote) {
166            out.push((start, &src[body..body + j]));
167            at = body + j + 1;
168        }
169    }
170    out
171}
172
173fn line_of(src: &str, offset: usize) -> usize {
174    src[..offset].matches('\n').count() + 1
175}
176
177/// Which files a check reads.
178#[derive(Debug, Clone)]
179enum Source {
180    /// A frontend directory, scanned recursively.
181    Frontend(PathBuf),
182    /// A named list of files.
183    Files(Vec<PathBuf>),
184}
185
186impl Source {
187    fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
188        Self::Files(paths.iter().map(|p| p.as_ref().to_path_buf()).collect())
189    }
190}
191
192/// Fail the build if a hand-written breakpoint has drifted from [`SizeClass`].
193///
194/// Every pixel width named by a media query must be a [`SizeClass`] boundary or
195/// one of the [`tuning`](Self::tuning) widths.
196///
197/// ```no_run
198/// makeover_build::drift::Breakpoints::in_frontend("frontend")
199///     .tuning(&[1400])
200///     .run();
201/// ```
202///
203/// Without this, moving `SizeClass::Medium::min_px` regenerates the emitted
204/// stylesheets and leaves every hand-written query behind, and the result is a
205/// stylesheet that disagrees with itself at the old boundary rather than an
206/// error.
207///
208/// The generated stylesheets are scanned too, and pass by construction: they
209/// ask makeover-geometry for the number rather than stating it. Scanning them
210/// means a consumer never has to name which files are hand-written.
211#[derive(Debug, Clone)]
212#[must_use = "a check does nothing until it is run"]
213pub struct Breakpoints {
214    source: Source,
215    tuning: Vec<u16>,
216}
217
218impl Breakpoints {
219    /// Every `.css` under `frontend/css` and every `.js` under `frontend/js`,
220    /// recursively.
221    pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
222        Self {
223            source: Source::Frontend(frontend.as_ref().to_path_buf()),
224            tuning: Vec::new(),
225        }
226    }
227
228    /// A named list of files rather than a tree.
229    ///
230    /// For a frontend whose generated and hand-written files share a directory,
231    /// with nothing to point a directory scan at: the MNW server keeps both
232    /// under `static/` beside a bundler's output. The list is hand-maintained,
233    /// and a stylesheet nobody adds to it is unchecked rather than failing, so
234    /// prefer [`in_frontend`](Self::in_frontend) where the layout allows it.
235    ///
236    /// A `.js` path is read as script and anything else as stylesheet.
237    pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
238        Self {
239            source: Source::files(paths),
240            tuning: Vec::new(),
241        }
242    }
243
244    /// Widths inside a shell where something reflows without the shell
245    /// changing: a dashboard dropping from three columns to two, a pane's width
246    /// cap ending.
247    ///
248    /// The one thing an app gets a say in. A shell boundary is a [`SizeClass`]
249    /// edge and belongs to makeover-geometry; nothing switches shells at a
250    /// tuning width, so it does not move when a size class does. Each entry
251    /// owes a note beside it saying what it tunes: this list is where a genuine
252    /// boundary goes to hide from the check.
253    pub fn tuning(mut self, widths: &[u16]) -> Self {
254        self.tuning.extend_from_slice(widths);
255        self
256    }
257
258    /// Run the check. Emits `cargo:rerun-if-changed` for every file it read,
259    /// and for the scanned directories.
260    ///
261    /// # Panics
262    ///
263    /// If a directory or a listed file cannot be read (a listed path that no
264    /// longer exists is a check covering less than it says), or if any width
265    /// is neither a size-class boundary nor a tuning width. A build script has
266    /// nowhere useful to return an error to.
267    pub fn run(&self) {
268        match &self.source {
269            Source::Frontend(frontend) => {
270                let mut files = files_with_extension(&frontend.join("css"), "css");
271                files.extend(js_files(&frontend.join("js")));
272                check_paths(&files, &self.tuning, Some(frontend));
273                // The directories too, so a file added later reruns it.
274                println!("cargo:rerun-if-changed={}", frontend.join("css").display());
275                println!("cargo:rerun-if-changed={}", frontend.join("js").display());
276            }
277            Source::Files(paths) => check_paths(paths, &self.tuning, None),
278        }
279    }
280}
281
282/// The check itself. `root`, when given, is stripped from reported paths.
283fn check_paths(paths: &[PathBuf], tuning_widths: &[u16], root: Option<&Path>) {
284    let allowed = allowed_widths(tuning_widths);
285    let mut stale: Vec<String> = Vec::new();
286
287    for path in paths {
288        let raw = std::fs::read_to_string(path)
289            .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
290        let name = match root {
291            Some(root) => display_name(root, path),
292            None => path.display().to_string(),
293        };
294
295        if path.extension().is_some_and(|x| x == "js") {
296            // No declarations in JS, so any parenthesised width is a query.
297            for (offset, width) in js_widths(&blank(&raw, Lang::Js)) {
298                if !width.is_allowed(&allowed) {
299                    stale.push(format!("  {name}:{}  ({width})", line_of(&raw, offset)));
300                }
301            }
302            continue;
303        }
304
305        // Comments first: a note about a breakpoint that used to be here is
306        // prose, not a rule, and should not fail a build.
307        let src = blank(&raw, Lang::Css);
308        for (offset, condition) in media_conditions(&src) {
309            for width in media_widths(condition) {
310                if !width.is_allowed(&allowed) {
311                    stale.push(format!(
312                        "  {name}:{}  @media{condition}  ({width})",
313                        line_of(&src, offset)
314                    ));
315                }
316            }
317        }
318    }
319
320    assert!(
321        stale.is_empty(),
322        "hand-written breakpoints disagree with makeover_geometry::SizeClass.\n\n\
323         Allowed: {allowed:?}\n\
324         ({:?} come from SizeClass; {tuning_widths:?} were passed as tuning widths.)\n\n\
325         Stale:\n{}\n\n\
326         Size classes are written in range syntax, `(width < 600px)`, because\n\
327         `(max-width: 599px)` leaves 599.5px in no class. If a size class moved,\n\
328         update these to match. If one of these is a new\n\
329         tuning width inside the wide shell rather than a shell boundary, add it\n\
330         to the caller's tuning list with a note saying what it tunes.\n\n\
331         Best of all, make the rule dimensional so it needs no threshold: a grid\n\
332         wants repeat(auto-fit, minmax(<content floor>, 1fr)) and a size wants\n\
333         clamp(). A threshold is for what appears and disappears.",
334        allowed
335            .iter()
336            .filter(|px| !tuning_widths.contains(px))
337            .collect::<Vec<_>>(),
338        stale.join("\n")
339    );
340
341    for path in paths {
342        println!("cargo:rerun-if-changed={}", path.display());
343    }
344}
345
346/// A path as the frontend sees it, for an error a reader can act on.
347fn display_name(frontend: &Path, path: &Path) -> String {
348    path.strip_prefix(frontend)
349        .unwrap_or(path)
350        .display()
351        .to_string()
352}
353
354/// Every width a hand-written media query is allowed to name.
355///
356/// Read out of [`SizeClass::media_condition`] rather than typed, which is the
357/// whole point: that is the one place the numbers come from, and a bump in
358/// makeover-geometry has to reach the stylesheet through here.
359fn allowed_widths(tuning_widths: &[u16]) -> Vec<u16> {
360    let mut widths: Vec<u16> = SizeClass::all()
361        .iter()
362        .flat_map(|c| media_widths(&c.media_condition()))
363        .map(|width| match width {
364            Width::Px(px) => px,
365            Width::Other(raw) => {
366                panic!("makeover-geometry wrote a size-class width this check cannot read: {raw}")
367            }
368        })
369        .collect();
370    widths.extend_from_slice(tuning_widths);
371    widths.sort_unstable();
372    widths.dedup();
373    widths
374}
375
376/// A width named in a media condition.
377#[derive(Debug, Clone, PartialEq, Eq)]
378enum Width {
379    /// A whole number of CSS pixels: `600px`, or `37.5em` at the 16px a media
380    /// query's `em` is measured against.
381    Px(u16),
382    /// Anything this cannot state in whole pixels: `599.98px`, `50vw`, `40ch`.
383    /// Never a boundary, so always reported.
384    Other(String),
385}
386
387impl Width {
388    fn is_allowed(&self, allowed: &[u16]) -> bool {
389        matches!(self, Self::Px(px) if allowed.contains(px))
390    }
391}
392
393impl std::fmt::Display for Width {
394    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395        match self {
396            Self::Px(px) => write!(f, "{px}px"),
397            Self::Other(raw) => f.write_str(raw),
398        }
399    }
400}
401
402/// Every width in a media condition, in the order it appears.
403///
404/// Reads both spellings of a width feature: `(max-width: 599px)` and range
405/// syntax, `(width < 600px)` or `(600px <= width < 840px)`, which is what
406/// [`SizeClass::media_condition`] writes. A feature group is any innermost
407/// `( ... )` naming `width` and not `device-width`, and every length inside it
408/// counts. Units are read rather than assumed: `48em` is 768px, not 48.
409fn media_widths(condition: &str) -> Vec<Width> {
410    width_groups(condition)
411        .into_iter()
412        .flat_map(|(_, group)| lengths(group))
413        .collect()
414}
415
416/// `(byte offset, inner text)` of every innermost parenthesised group that
417/// names a width feature.
418fn width_groups(src: &str) -> Vec<(usize, &str)> {
419    let mut out = Vec::new();
420    let mut open = None;
421    for (i, c) in src.char_indices() {
422        match c {
423            '(' => open = Some(i),
424            ')' => {
425                if let Some(start) = open.take() {
426                    let inner = &src[start + 1..i];
427                    if names_width(inner) {
428                        out.push((start, inner));
429                    }
430                }
431            }
432            '\n' => open = None,
433            _ => {}
434        }
435    }
436    out
437}
438
439/// Whether a feature group is about the viewport's width: `width`,
440/// `min-width` or `max-width` as a whole word, not `device-width` and not a
441/// longer identifier that ends in it.
442fn names_width(inner: &str) -> bool {
443    inner.match_indices("width").any(|(at, _)| {
444        let before = &inner[..at];
445        let prefix_ok = before.is_empty()
446            || before.ends_with("min-")
447            || before.ends_with("max-")
448            || before
449                .chars()
450                .next_back()
451                .is_some_and(|c| !c.is_ascii_alphanumeric() && c != '-' && c != '_');
452        let after = inner[at + "width".len()..].chars().next();
453        prefix_ok && after.is_none_or(|c| !c.is_ascii_alphanumeric() && c != '-' && c != '_')
454    })
455}
456
457/// Every `<number><unit>` in a feature group, as a [`Width`].
458fn lengths(group: &str) -> Vec<Width> {
459    let bytes = group.as_bytes();
460    let mut out = Vec::new();
461    let mut i = 0;
462    while i < bytes.len() {
463        let starts_number = bytes[i].is_ascii_digit()
464            && (i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'-'));
465        if !starts_number {
466            i += 1;
467            continue;
468        }
469        let start = i;
470        while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
471            i += 1;
472        }
473        let number = &group[start..i];
474        let unit_start = i;
475        while i < bytes.len() && bytes[i].is_ascii_alphabetic() {
476            i += 1;
477        }
478        let unit = &group[unit_start..i];
479        if unit.is_empty() {
480            continue;
481        }
482        let raw = &group[start..i];
483        let scale = match unit {
484            "px" => Some(1.0),
485            "em" | "rem" => Some(16.0),
486            _ => None,
487        };
488        let px = scale.and_then(|scale| number.parse::<f64>().ok().map(|n| n * scale));
489        out.push(match px {
490            Some(px) if px.fract() == 0.0 && px >= 0.0 && px <= f64::from(u16::MAX) => {
491                // Whole and in range, checked above.
492                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
493                Width::Px(px as u16)
494            }
495            _ => Width::Other(raw.to_string()),
496        });
497    }
498    out
499}
500
501/// `(byte offset of the `@media`, the condition text before the `{`)`.
502fn media_conditions(css: &str) -> Vec<(usize, &str)> {
503    let mut out = Vec::new();
504    let mut at = 0;
505    while let Some(i) = css[at..].find("@media") {
506        let start = at + i;
507        let after = start + "@media".len();
508        match css[after..].find('{') {
509            Some(j) => {
510                out.push((start, &css[after..after + j]));
511                at = after + j;
512            }
513            None => break,
514        }
515    }
516    out
517}
518
519/// `(byte offset, width)` for every width feature in a JS source.
520///
521/// The parentheses are the whole test, and they have to be: a media condition
522/// is always parenthesized and a CSS declaration never is, so `'max-width:
523/// 320px'` in an inline-style string is not a breakpoint and must not read as
524/// one. Range syntax, `(width < 600px)`, is read the same way as in a
525/// stylesheet.
526fn js_widths(src: &str) -> Vec<(usize, Width)> {
527    width_groups(src)
528        .into_iter()
529        .filter(|(_, group)| is_feature(group))
530        .flat_map(|(offset, group)| lengths(group).into_iter().map(move |w| (offset, w)))
531        .collect()
532}
533
534/// Whether a parenthesised group in script is a media feature rather than a
535/// call's arguments: `(max-width: 600px)` or `(width < 600px)`, not
536/// `Math.max(width, 600)`.
537fn is_feature(group: &str) -> bool {
538    let group = group.trim();
539    let colon = ["min-width", "max-width", "width"].iter().any(|name| {
540        group
541            .strip_prefix(name)
542            .is_some_and(|rest| rest.trim_start().starts_with(':'))
543    });
544    colon || group.contains(['<', '>'])
545}
546
547/// Which language a source is, for [`blank`].
548#[derive(Clone, Copy, PartialEq, Eq)]
549enum Lang {
550    /// Comments and string contents both go: neither is a rule, and
551    /// `content: "/*"` must not open a comment.
552    Css,
553    /// Comments go and strings stay, because a media query in script is a
554    /// string (`matchMedia('(width < 600px)')`). A `/*` or `//` inside one is
555    /// still text, not a comment.
556    Js,
557}
558
559/// Blank the parts of `src` that are not code, keeping every byte offset.
560///
561/// One scanner for both readers, and it tracks string literals so a comment
562/// opener inside one is text. Blanked characters become spaces, except that a
563/// newline stays a newline so line numbers still line up.
564fn blank(src: &str, lang: Lang) -> String {
565    #[derive(Clone, Copy)]
566    enum State {
567        Code,
568        Block,
569        Line,
570        Quoted(char),
571    }
572    // A blanked character becomes as many spaces as it had bytes, so every
573    // byte offset into the result is the same byte offset into `src`.
574    let blank_into = |out: &mut String, c: char| {
575        if c == '\n' {
576            out.push('\n');
577        } else {
578            out.extend(std::iter::repeat_n(' ', c.len_utf8()));
579        }
580    };
581    let mut out = String::with_capacity(src.len());
582    let mut state = State::Code;
583    let mut chars = src.chars().peekable();
584    while let Some(c) = chars.next() {
585        match state {
586            State::Code => match c {
587                '/' if chars.peek() == Some(&'*') => {
588                    chars.next();
589                    out.push_str("  ");
590                    state = State::Block;
591                }
592                '/' if lang == Lang::Js && chars.peek() == Some(&'/') => {
593                    chars.next();
594                    out.push_str("  ");
595                    state = State::Line;
596                }
597                '"' | '\'' | '`' if lang == Lang::Js || c != '`' => {
598                    out.push(c);
599                    state = State::Quoted(c);
600                }
601                _ => out.push(c),
602            },
603            State::Block => {
604                if c == '*' && chars.peek() == Some(&'/') {
605                    chars.next();
606                    out.push_str("  ");
607                    state = State::Code;
608                } else {
609                    blank_into(&mut out, c);
610                }
611            }
612            State::Line => {
613                blank_into(&mut out, c);
614                if c == '\n' {
615                    state = State::Code;
616                }
617            }
618            State::Quoted(quote) => {
619                let mut keep = |c: char| {
620                    if lang == Lang::Js {
621                        out.push(c);
622                    } else {
623                        blank_into(&mut out, c);
624                    }
625                };
626                if c == quote {
627                    out.push(c);
628                    state = State::Code;
629                } else if c == '\\' {
630                    keep(c);
631                    if let Some(escaped) = chars.next() {
632                        keep(escaped);
633                    }
634                } else {
635                    keep(c);
636                }
637            }
638        }
639    }
640    out
641}
642
643/// Blank every `@layer <name> { ... }` block whose name is in `names`, keeping
644/// byte offsets and line breaks. Comments and strings are skipped while the
645/// braces are matched, the same way [`blank`] reads them.
646fn drop_layers(css: &str, names: &[&str]) -> String {
647    if names.is_empty() {
648        return css.to_owned();
649    }
650    let scan = blank(css, Lang::Css);
651    let scan = scan.as_bytes();
652    let mut out = css.as_bytes().to_vec();
653    let mut at = 0;
654    while let Some(found) = find_from(scan, b"@layer", at) {
655        let mut i = found + b"@layer".len();
656        while i < scan.len() && scan[i].is_ascii_whitespace() {
657            i += 1;
658        }
659        let start = i;
660        while i < scan.len() && (scan[i].is_ascii_alphanumeric() || matches!(scan[i], b'-' | b'_'))
661        {
662            i += 1;
663        }
664        let name = &css[start..i];
665        while i < scan.len() && scan[i].is_ascii_whitespace() {
666            i += 1;
667        }
668        if i >= scan.len() || scan[i] != b'{' || !names.contains(&name) {
669            at = found + 1;
670            continue;
671        }
672        let mut depth = 0usize;
673        let mut end = scan.len();
674        for (k, &byte) in scan.iter().enumerate().skip(i) {
675            match byte {
676                b'{' => depth += 1,
677                b'}' => {
678                    depth -= 1;
679                    if depth == 0 {
680                        end = k + 1;
681                        break;
682                    }
683                }
684                _ => {}
685            }
686        }
687        for byte in &mut out[found..end] {
688            if *byte != b'\n' {
689                *byte = b' ';
690            }
691        }
692        at = end;
693    }
694    String::from_utf8(out).unwrap_or_else(|_| css.to_owned())
695}
696
697fn find_from(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
698    haystack
699        .get(from..)?
700        .windows(needle.len())
701        .position(|window| window == needle)
702        .map(|at| at + from)
703}
704
705/// A reviewed exception to [`Vocabulary`]: a collision the app has read and
706/// kept, with a note beside it saying why.
707///
708/// It expires when the collision does. An exception that no longer collides
709/// fails the check, since an unused licence is where the next real collision
710/// lands unnoticed.
711#[derive(Debug, Clone, Copy, PartialEq, Eq)]
712pub enum Allow<'a> {
713    /// A hand-written rule on a generated class takes one of its properties.
714    Class {
715        /// The class, unprefixed as the stylesheet spells it.
716        class: &'a str,
717        /// The property both set.
718        property: &'a str,
719    },
720    /// A bare element rule takes a property the generated sheet sets on a class
721    /// that element carries.
722    Element {
723        /// The element the rule selects.
724        element: &'a str,
725        /// The generated class it reaches.
726        class: &'a str,
727        /// The property both set.
728        property: &'a str,
729    },
730}
731
732impl<'a> Allow<'a> {
733    /// See [`Allow::Class`].
734    pub const fn class(class: &'a str, property: &'a str) -> Self {
735        Self::Class { class, property }
736    }
737
738    /// See [`Allow::Element`].
739    pub const fn element(element: &'a str, class: &'a str, property: &'a str) -> Self {
740        Self::Element {
741            element,
742            class,
743            property,
744        }
745    }
746}
747
748/// Fail the build if a hand-written stylesheet takes a property the generated
749/// one already sets, on the same class or on an element that carries it.
750///
751/// The generated sheet sits in `@layer makeover`. App CSS beats it whatever the
752/// specificity, either by being unlayered or by sitting in a layer the app's
753/// order statement puts after `makeover`, so an app declaration for a property
754/// makeover already sets does not merge with it: it wins, silently, and the
755/// design system's version of that component stops applying, and nothing looks.
756///
757/// # Two passes, because a rule can carry no class
758///
759/// The class pass compares an app `.button` against the generated `.button`.
760/// It reads rules by the classes in their selectors, so a rule with no class in
761/// it is invisible to it, and `button { color: var(--content) }` is exactly
762/// that: it sets the property the generated `.button` sets on every described
763/// act, `.button[data-tone="danger"]`'s tone included, which draws a
764/// destructive act like an ordinary one.
765///
766/// The element pass reads that case. `makeover_webview::vocabulary::ELEMENT_CLASSES`
767/// says which generated classes an element can carry (CSS cannot say it, and
768/// the renderer can), and a bare element rule taking a property the design
769/// system sets on one of those classes is the same defect as the class case.
770///
771/// Two things are not reported, both deliberately:
772///
773///   - A scoped rule (`.page button`). It reaches the elements inside one
774///     region rather than every one of them, so whether it lands on a described
775///     act depends on where that act renders. The certain case is the one this
776///     reads.
777///   - A property the app names on the class itself, from a rule that outranks
778///     the element rule. Both are the app's and both sit in the same layer, so
779///     that one contest is settled by specificity, and what reaches the design
780///     system is the class rule, which the class pass has already reported
781///     or reviewed. The rank matters: `.field` does not beat
782///     `input[type="text"]`, and a handoff written as the weaker of the two is
783///     a remedy that looks written and is not.
784///
785/// # Why properties and not class names
786///
787/// A shared class name is not by itself a divergence. An app `.badge` that sets
788/// shape while the generated `.badge` sets colour is a correct split, and a
789/// check on names would ask for it to be deleted. On properties, the split is
790/// what the check enforces.
791///
792/// # The exception list
793///
794/// [`Allow::class`] names a `(class, property)` pair this app has reviewed and
795/// kept.
796/// Deciding which are legitimate here would need a selector matcher, and a check
797/// that guesses wrong about specificity fails correct builds, so the app
798/// declares it instead, the same shape as quasi-webview's `RENDERER_OWN`.
799///
800/// A reviewed pairing is a claim about who owns a property, and it expires when
801/// the design system takes the property back.
802///
803/// [`Allow::element`] is the same thing one pass down: an element rule reaching
804/// a generated class that has been read and kept.
805///
806/// The remedy is usually neither. A later layer can hand the property back
807/// with `revert-layer`, which says "whatever the design system set here, keep
808/// it" on the arms makeover actually paints, and that is a statement in the
809/// stylesheet rather than a note in a build script. Handoffs are not reported by
810/// either pass.
811///
812/// A pair that stops colliding fails too. A licence nobody is using is where
813/// the next real collision lands and reads as company.
814///
815/// ```no_run
816/// use makeover_build::drift::{Allow, Vocabulary};
817///
818/// Vocabulary::in_frontend("frontend")
819///     .generated(&["layout.css"])
820///     // Reviewed: the card's shadow is the app's, on the hover arm only.
821///     .allow(Allow::class("card", "box-shadow"))
822///     .run(&makeover_build::Emit::default());
823/// ```
824#[derive(Debug, Clone)]
825#[must_use = "a check does nothing until it is run"]
826pub struct Vocabulary<'a> {
827    source: Source,
828    generated: Vec<&'a str>,
829    upstream: Vec<&'a str>,
830    allowed: Vec<Allow<'a>>,
831    beneath: Vec<&'a str>,
832}
833
834impl<'a> Vocabulary<'a> {
835    /// Every `.css` under `frontend/css`, recursively.
836    pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
837        Self::from(Source::Frontend(frontend.as_ref().to_path_buf()))
838    }
839
840    /// A named list of stylesheets rather than a tree.
841    ///
842    /// For a frontend whose generated and hand-written sheets share a
843    /// directory. Same trade as [`Breakpoints::files`]: the list is
844    /// hand-maintained, and a stylesheet nobody adds to it is unchecked.
845    pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
846        Self::from(Source::files(paths))
847    }
848
849    fn from(source: Source) -> Self {
850        Self {
851            source,
852            generated: Vec::new(),
853            upstream: Vec::new(),
854            allowed: Vec::new(),
855            beneath: Vec::new(),
856        }
857    }
858
859    /// Sheets this crate writes, which are skipped: the generated file setting
860    /// a generated property is the point. Relative to `frontend/css` for
861    /// [`in_frontend`](Self::in_frontend); matched against the end of each path
862    /// for [`files`](Self::files).
863    pub fn generated(mut self, names: &[&'a str]) -> Self {
864        self.generated.extend_from_slice(names);
865        self
866    }
867
868    /// The text of stylesheets that sit between makeover and the app and own
869    /// the classes they style as makeover owns its own.
870    ///
871    /// quasi-webview's `SCREEN_CSS` is the case. This crate cannot name it,
872    /// since quasi builds on this crate and not the other way round, so the app
873    /// that links both hands it in. A hand-written sheet is checked against
874    /// makeover's sheet and every upstream sheet together. A file whose text
875    /// *is* an upstream sheet, the copy an app serves from its frontend, is
876    /// checked against makeover alone and never read as clashing with itself.
877    pub fn upstream(mut self, sheets: &[&'a str]) -> Self {
878        self.upstream.extend_from_slice(sheets);
879        self
880    }
881
882    /// Cascade layers the app orders before `makeover`, by name.
883    ///
884    /// A rule inside one loses to every generated rule whatever its selector,
885    /// so it cannot take a property from the design system and is not read.
886    /// The usual case is a reset: `@layer reset, makeover, ...` with
887    /// `* { margin: 0; padding: 0 }` inside `@layer reset { }` clears browser
888    /// defaults without zeroing the generated spacing. The order itself lives
889    /// in the app's markup, which this check does not read, so naming a layer
890    /// here is the app stating that order.
891    pub fn beneath(mut self, layers: &[&'a str]) -> Self {
892        self.beneath.extend_from_slice(layers);
893        self
894    }
895
896    /// A reviewed exception. See [`Allow`].
897    pub fn allow(mut self, allow: Allow<'a>) -> Self {
898        self.allowed.push(allow);
899        self
900    }
901
902    /// Several reviewed exceptions, for a list the app keeps as a `const`.
903    pub fn allowing(mut self, allows: impl IntoIterator<Item = Allow<'a>>) -> Self {
904        self.allowed.extend(allows);
905        self
906    }
907
908    /// Run the check against the stylesheet `opts` generates. Emits
909    /// `cargo:rerun-if-changed` for every file it read.
910    ///
911    /// # Panics
912    ///
913    /// If a directory or listed file cannot be read, if any hand-written sheet
914    /// takes a generated property without an [`Allow`], or if an [`Allow`] no
915    /// longer collides. A build script has nowhere useful to return an error
916    /// to, and an app quietly overriding its own design system is worse than a
917    /// failed build.
918    pub fn run(&self, opts: &Emit) {
919        let classes: Vec<(&str, &str)> = self
920            .allowed
921            .iter()
922            .filter_map(|allow| match *allow {
923                Allow::Class { class, property } => Some((class, property)),
924                Allow::Element { .. } => None,
925            })
926            .collect();
927        let elements: Vec<(&str, &str, &str)> = self
928            .allowed
929            .iter()
930            .filter_map(|allow| match *allow {
931                Allow::Element {
932                    element,
933                    class,
934                    property,
935                } => Some((element, class, property)),
936                Allow::Class { .. } => None,
937            })
938            .collect();
939        match &self.source {
940            Source::Frontend(frontend) => {
941                let css = frontend.join("css");
942                let files: Vec<PathBuf> = files_with_extension(&css, "css")
943                    .into_iter()
944                    .filter(|p| {
945                        let name = p.strip_prefix(&css).unwrap_or(p).display().to_string();
946                        !self.generated.contains(&name.as_str())
947                    })
948                    .collect();
949                check_vocabulary_paths(
950                    &files,
951                    opts,
952                    Some(frontend),
953                    &self.upstream,
954                    &self.beneath,
955                    &classes,
956                    &elements,
957                );
958                // The directory too, so a stylesheet added later reruns it.
959                println!("cargo::rerun-if-changed={}", css.display());
960            }
961            Source::Files(paths) => {
962                let files: Vec<PathBuf> = paths
963                    .iter()
964                    .filter(|p| !self.generated.iter().any(|name| p.ends_with(name)))
965                    .cloned()
966                    .collect();
967                check_vocabulary_paths(
968                    &files,
969                    opts,
970                    None,
971                    &self.upstream,
972                    &self.beneath,
973                    &classes,
974                    &elements,
975                );
976            }
977        }
978    }
979}
980
981/// The check itself. `root`, when given, is stripped from reported paths.
982fn check_vocabulary_paths(
983    paths: &[PathBuf],
984    opts: &Emit,
985    root: Option<&Path>,
986    upstream: &[&str],
987    beneath: &[&str],
988    allowed: &[(&str, &str)],
989    allowed_elements: &[(&str, &str, &str)],
990) {
991    let makeover =
992        makeover_webview::vocabulary::declarations_by_class(&makeover_webview::stylesheet(opts));
993    // What a hand-written sheet answers to: makeover's classes and every
994    // upstream sheet's, merged per class.
995    let mut owned = makeover.clone();
996    for sheet in upstream {
997        for (class, properties) in makeover_webview::vocabulary::declarations_by_class(sheet) {
998            owned.entry(class).or_default().extend(properties);
999        }
1000    }
1001    let mut clashes: Vec<String> = Vec::new();
1002    let mut seen: Vec<(String, String)> = Vec::new();
1003    let mut element_clashes: Vec<String> = Vec::new();
1004    let mut element_seen: Vec<(String, String, String)> = Vec::new();
1005
1006    for path in paths {
1007        println!("cargo::rerun-if-changed={}", path.display());
1008        let raw = std::fs::read_to_string(path)
1009            .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
1010        let name = match root {
1011            Some(root) => display_name(root, path),
1012            None => path.display().to_string(),
1013        };
1014        // An upstream sheet served from the frontend answers to makeover alone:
1015        // measured against itself every declaration in it would clash.
1016        let generated = if upstream.contains(&raw.as_str()) {
1017            &makeover
1018        } else {
1019            &owned
1020        };
1021        // A layer ordered before `makeover` cannot beat it, so its rules are
1022        // not read. See `Vocabulary::beneath`.
1023        let raw = drop_layers(&raw, beneath);
1024        // Read the app's sheet the same way the crate reads its own, or the two
1025        // sides are not comparable.
1026        let local = makeover_webview::vocabulary::declarations_by_class(&raw);
1027        for (class, properties) in &local {
1028            let Some(theirs) = generated.get(class) else {
1029                continue;
1030            };
1031            for property in properties.intersection(theirs) {
1032                seen.push((class.clone(), property.clone()));
1033                if allowed.contains(&(class.as_str(), property.as_str())) {
1034                    continue;
1035                }
1036                clashes.push(format!("  {name}  .{class} {{ {property} }}"));
1037            }
1038        }
1039
1040        // The second pass: a rule carrying no class at all, which the first one
1041        // cannot see. What the app says about the class itself settles the
1042        // pair, but only from a rule that outranks the element rule. Both are
1043        // the app's and both are in the same layer, so this one contest is
1044        // decided by specificity. `.field` does not beat `input[type="text"]`.
1045        let mentioned = makeover_webview::vocabulary::mentions_by_class(&raw);
1046        let by_element = makeover_webview::vocabulary::declarations_by_element(&raw);
1047        for (element, properties) in &by_element {
1048            for class in makeover_webview::vocabulary::classes_for_element(element, opts) {
1049                let Some(theirs) = generated.get(&class) else {
1050                    continue;
1051                };
1052                for (property, rank) in properties {
1053                    if !theirs.contains(property) {
1054                        continue;
1055                    }
1056                    // A tie goes to the class rule: at equal specificity the
1057                    // later rule wins, and a remedy is written after the rule
1058                    // it remedies.
1059                    let spoken_for = mentioned
1060                        .get(&class)
1061                        .and_then(|properties| properties.get(property))
1062                        .is_some_and(|theirs| theirs >= rank);
1063                    if spoken_for {
1064                        continue;
1065                    }
1066                    element_seen.push((element.clone(), class.clone(), property.clone()));
1067                    if allowed_elements.contains(&(
1068                        element.as_str(),
1069                        class.as_str(),
1070                        property.as_str(),
1071                    )) {
1072                        continue;
1073                    }
1074                    element_clashes.push(format!(
1075                        "  {name}  {element} {{ {property} }}  beats  .{class} {{ {property} }}"
1076                    ));
1077                }
1078            }
1079        }
1080    }
1081
1082    assert!(
1083        clashes.is_empty(),
1084        "{} hand-written declaration(s) take a property the generated stylesheet, \
1085         or an upstream sheet named to this check, already sets on the same \
1086         class. App CSS wins over @layer makeover, whether by a later layer or \
1087         by being unlayered, so each of these wins over the design system \
1088         silently:\n{}\n\nDelete the declaration, or, if \
1089         it is a deliberate pairing on a different selector arm, add \
1090         (class, property) to this check's allowed list and say why beside it. \
1091         Count the consumers before deciding a divergence is worth keeping.",
1092        clashes.len(),
1093        clashes.join("\n")
1094    );
1095
1096    assert!(
1097        element_clashes.is_empty(),
1098        "{} hand-written element rule(s) take a property the generated \
1099         stylesheet sets on a class that element carries. App CSS wins over \
1100         @layer makeover, whether by a later layer or by being unlayered, so a \
1101         described component rendered on one of these elements loses the \
1102         design system's version of that property silently, which can draw a \
1103         destructive act like an ordinary one:\n{}\n\nHand the \
1104         property back on the arms makeover paints \
1105         (`.{{class}}:disabled {{ color: revert-layer }}`), scope the element \
1106         rule so it stops reaching described markup, or add \
1107         (element, class, property) to this check's allowed-elements list and \
1108         say why beside it.",
1109        element_clashes.len(),
1110        element_clashes.join("\n")
1111    );
1112
1113    let stale: Vec<&(&str, &str)> = allowed
1114        .iter()
1115        .filter(|(class, property)| {
1116            !seen.contains(&((*class).to_string(), (*property).to_string()))
1117        })
1118        .collect();
1119    assert!(
1120        stale.is_empty(),
1121        "the allowed list declares {stale:?}, which no longer collides with \
1122         anything. Delete the entries: an exception nobody is using is where the \
1123         next real collision lands and reads as company."
1124    );
1125
1126    let stale: Vec<&(&str, &str, &str)> = allowed_elements
1127        .iter()
1128        .filter(|(element, class, property)| {
1129            !element_seen.contains(&(
1130                (*element).to_string(),
1131                (*class).to_string(),
1132                (*property).to_string(),
1133            ))
1134        })
1135        .collect();
1136    assert!(
1137        stale.is_empty(),
1138        "the allowed-elements list declares {stale:?}, which no longer collides \
1139         with anything. Delete the entries: an exception nobody is using is \
1140         where the next real collision lands and reads as company."
1141    );
1142}
1143
1144/// Whether `haystack` names `class` whole, rather than as part of a longer
1145/// name: `min-1` must not be read as used because `min-16` is, and `row` must
1146/// not be read as used because `row-flex` or `flex-row` is.
1147fn haystack_names(haystack: &str, class: &str) -> bool {
1148    let part = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_';
1149    haystack.match_indices(class).any(|(at, found)| {
1150        haystack[..at].chars().next_back().is_none_or(|c| !part(c))
1151            && haystack[at + found.len()..]
1152                .chars()
1153                .next()
1154                .is_none_or(|c| !part(c))
1155    })
1156}
1157
1158/// Warn when the generated vocabulary has grown dead, and fail when it grows
1159/// deader than the recorded high-water mark.
1160///
1161/// A generated class no markup emits is a rule shipped to every user for
1162/// nothing. Some dead vocabulary is normal, so the count alone is not a
1163/// failure; what this checks is the direction. Recording the count in the
1164/// build script makes a change that worsens it fail rather than go unnoticed.
1165///
1166/// One-sided, the same shape as the MNW server's `frontend_globals` seal:
1167/// exceeding `high_water` fails, coming in under it warns and asks for the seal
1168/// to be lowered. A build that fails because dead CSS was deleted would teach
1169/// the wrong lesson.
1170///
1171/// `markup` is every file that can carry a class: templates, `.js`, `.html`,
1172/// and any Rust that writes markup. A class is counted as used if its name
1173/// appears whole in any of them, which is deliberately generous. A stricter reading
1174/// would need to know how each app builds its class strings, and a check that
1175/// guesses wrong fails a correct build.
1176///
1177/// # Panics
1178///
1179/// If a listed file cannot be read, or if more classes are unused than
1180/// `high_water`.
1181pub fn check_vocabulary_use<P: AsRef<Path>>(markup: &[P], opts: &Emit, high_water: usize) {
1182    let generated = makeover_webview::vocabulary::names(opts);
1183    let mut haystack = String::new();
1184    for path in markup {
1185        let path = path.as_ref();
1186        println!("cargo::rerun-if-changed={}", path.display());
1187        haystack.push_str(
1188            &std::fs::read_to_string(path)
1189                .unwrap_or_else(|e| panic!("read {}: {e}", path.display())),
1190        );
1191        haystack.push('\n');
1192    }
1193
1194    // A ladder is one piece of vocabulary, not one per rung. A column carries
1195    // whichever `min-N` rung its floor lands on and a table whichever `short-N`
1196    // rung its essentials need, so no site names every rung and counting each
1197    // would seal the dead count at the ladder's length. A ladder is used if any
1198    // rung is, and counted once if none is.
1199    const LADDERS: &[&str] = &["min-", "short-"];
1200    let rung_of = |class: &str| -> Option<&'static str> {
1201        let name = class.strip_prefix(opts.class_prefix)?;
1202        LADDERS.iter().copied().find(|ladder| {
1203            name.strip_prefix(ladder)
1204                .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
1205        })
1206    };
1207    let mut unused: Vec<String> = generated
1208        .iter()
1209        .filter(|class| rung_of(class).is_none() && !haystack_names(&haystack, class))
1210        .cloned()
1211        .collect();
1212    for ladder in LADDERS {
1213        let rungs: Vec<&String> = generated
1214            .iter()
1215            .filter(|class| rung_of(class) == Some(ladder))
1216            .collect();
1217        if !rungs.is_empty() && !rungs.iter().any(|class| haystack_names(&haystack, class)) {
1218            unused.push(format!("{}{ladder}N", opts.class_prefix));
1219        }
1220    }
1221
1222    assert!(
1223        unused.len() <= high_water,
1224        "{} of {} generated classes are emitted by no markup, above the recorded {}. \
1225         The vocabulary grew or the markup stopped using it:\n{}",
1226        unused.len(),
1227        generated.len(),
1228        high_water,
1229        unused
1230            .iter()
1231            .map(|c| format!("  .{c}"))
1232            .collect::<Vec<_>>()
1233            .join("\n")
1234    );
1235
1236    if unused.len() < high_water {
1237        println!(
1238            "cargo::warning=dead makeover vocabulary is down to {} from a sealed {}; \
1239             lower the seal so it cannot grow back",
1240            unused.len(),
1241            high_water
1242        );
1243    }
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248    use super::*;
1249    use std::fmt::Write as _;
1250
1251    fn scratch(name: &str) -> PathBuf {
1252        let dir =
1253            std::env::temp_dir().join(format!("makeover-drift-{}-{name}", std::process::id()));
1254        let _ = std::fs::remove_dir_all(&dir);
1255        std::fs::create_dir_all(&dir).expect("create scratch");
1256        dir
1257    }
1258
1259    fn write(dir: &Path, name: &str, src: &str) {
1260        if let Some(parent) = dir.join(name).parent() {
1261            std::fs::create_dir_all(parent).unwrap();
1262        }
1263        std::fs::write(dir.join(name), src).unwrap();
1264    }
1265
1266    fn declaring() -> String {
1267        format!(
1268            "const {CONST_NAME} = '{}';\n",
1269            Density::Touch.media_condition()
1270        )
1271    }
1272
1273    #[test]
1274    fn the_crates_own_string_passes() {
1275        let dir = scratch("ok");
1276        write(&dir, "touch.js", &declaring());
1277        check_touch_density(&dir);
1278    }
1279
1280    #[test]
1281    #[should_panic(expected = "disagrees with makeover_geometry::Density")]
1282    fn a_drifted_literal_fails() {
1283        let dir = scratch("drift");
1284        write(&dir, "touch.js", &declaring());
1285        write(
1286            &dir,
1287            "haptics.js",
1288            &format!("const {CONST_NAME} = '(pointer: coarse)';\n"),
1289        );
1290        check_touch_density(&dir);
1291    }
1292
1293    #[test]
1294    #[should_panic(expected = "device sniff")]
1295    fn the_sniff_cannot_come_back() {
1296        let dir = scratch("sniff");
1297        write(&dir, "touch.js", &declaring());
1298        write(&dir, "legacy.js", "if ('ontouchstart' in window) {}\n");
1299        check_touch_density(&dir);
1300    }
1301
1302    #[test]
1303    #[should_panic(expected = "no TOUCH_DENSITY literal found")]
1304    fn a_frontend_that_states_nothing_fails() {
1305        let dir = scratch("empty");
1306        write(&dir, "app.js", "export const x = 1;\n");
1307        check_touch_density(&dir);
1308    }
1309
1310    #[test]
1311    fn a_use_site_is_not_a_declaration() {
1312        // The const is read far more often than it is declared, and a read
1313        // states no string. Counting one as a declaration would make the
1314        // `found > 0` assertion pass on a frontend that only imports it.
1315        let src =
1316            format!("import {{ {CONST_NAME} }} from './touch.js';\nmatchMedia({CONST_NAME});\n");
1317        assert!(touch_density_literals(&src).is_empty());
1318    }
1319
1320    #[test]
1321    fn nested_files_are_read() {
1322        // The server keeps its scripts in subdirectories, and the nested half
1323        // is the half most likely to be a copy.
1324        let dir = scratch("nested");
1325        write(&dir, "touch.js", &declaring());
1326        write(&dir, "screens/legacy.js", "navigator.maxTouchPoints > 0;\n");
1327        let files = js_files(&dir);
1328        assert_eq!(files.len(), 2);
1329    }
1330
1331    #[test]
1332    fn a_non_js_file_is_ignored() {
1333        let dir = scratch("nonjs");
1334        write(&dir, "touch.js", &declaring());
1335        write(&dir, "styles.css", "body { }\n");
1336        assert_eq!(js_files(&dir).len(), 1);
1337    }
1338
1339    fn frontend(name: &str) -> PathBuf {
1340        let dir = scratch(name);
1341        std::fs::create_dir_all(dir.join("css")).unwrap();
1342        std::fs::create_dir_all(dir.join("js")).unwrap();
1343        dir
1344    }
1345
1346    /// A width every size class agrees is a boundary.
1347    fn boundary() -> u16 {
1348        SizeClass::Medium.min_px()
1349    }
1350
1351    #[test]
1352    fn the_crates_own_boundaries_pass() {
1353        let dir = frontend("bp-ok");
1354        write(
1355            &dir,
1356            "css/styles.css",
1357            &format!("@media (min-width: {}px) {{ body {{ }} }}\n", boundary()),
1358        );
1359        Breakpoints::in_frontend(&dir).run();
1360    }
1361
1362    #[test]
1363    #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
1364    fn a_stale_css_width_fails() {
1365        let dir = frontend("bp-css");
1366        write(&dir, "css/styles.css", "@media (max-width: 768px) { }\n");
1367        Breakpoints::in_frontend(&dir).run();
1368    }
1369
1370    #[test]
1371    #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
1372    fn a_stale_js_width_fails() {
1373        let dir = frontend("bp-js");
1374        write(&dir, "js/shell.js", "matchMedia('(max-width: 768px)');\n");
1375        Breakpoints::in_frontend(&dir).run();
1376    }
1377
1378    #[test]
1379    fn a_declared_tuning_width_passes() {
1380        let dir = frontend("bp-tuning");
1381        write(&dir, "css/styles.css", "@media (min-width: 1400px) { }\n");
1382        Breakpoints::in_frontend(&dir).tuning(&[1400]).run();
1383    }
1384
1385    #[test]
1386    fn a_width_in_a_comment_is_prose() {
1387        // The note explaining which breakpoint used to be here is not a rule,
1388        // and failing a build on documentation would teach people to delete it.
1389        let dir = frontend("bp-comment");
1390        write(
1391            &dir,
1392            "css/styles.css",
1393            "/* was @media (max-width: 768px) until the size classes landed */\n",
1394        );
1395        Breakpoints::in_frontend(&dir).run();
1396    }
1397
1398    #[test]
1399    fn an_unparenthesized_width_is_not_a_breakpoint() {
1400        // A JS string building an inline style states `max-width: 320px` with
1401        // no parentheses. It is a declaration, not a query, and the first
1402        // version of this check failed the build on one.
1403        let dir = frontend("bp-inline");
1404        write(
1405            &dir,
1406            "js/style.js",
1407            "el.style.cssText = 'max-width: 320px; display: block';\n",
1408        );
1409        Breakpoints::in_frontend(&dir).run();
1410    }
1411
1412    #[test]
1413    fn nested_css_is_read() {
1414        // Same argument as the touch check: the nested half is the half most
1415        // likely to be a copy.
1416        let dir = frontend("bp-nested");
1417        write(
1418            &dir,
1419            "css/screens/detail.css",
1420            "@media (max-width: 768px) { }\n",
1421        );
1422        let found = std::panic::catch_unwind(|| Breakpoints::in_frontend(&dir).run());
1423        assert!(found.is_err(), "a nested stylesheet must be scanned");
1424    }
1425
1426    #[test]
1427    fn a_named_list_is_checked() {
1428        let dir = frontend("bp-list");
1429        write(&dir, "css/style.css", "@media (max-width: 768px) { }\n");
1430        let listed = dir.join("css/style.css");
1431        let err = std::panic::catch_unwind(|| Breakpoints::files(&[&listed]).run()).unwrap_err();
1432        let msg = err.downcast_ref::<String>().expect("String payload");
1433        assert!(msg.contains("style.css:1"), "got: {msg}");
1434    }
1435
1436    #[test]
1437    #[should_panic(expected = "read ")]
1438    fn a_listed_file_that_is_gone_fails() {
1439        // The list is hand-maintained, so a path that stopped existing is a
1440        // check quietly covering less than it claims. Louder than skipping it.
1441        let dir = frontend("bp-missing");
1442        Breakpoints::files(&[dir.join("css/never-written.css")]).run();
1443    }
1444
1445    #[test]
1446    fn a_listed_js_file_is_parsed_as_script() {
1447        // The unparenthesized-declaration rule is what separates the two, and
1448        // picking the parser off the extension is the whole difference.
1449        let dir = frontend("bp-list-js");
1450        write(
1451            &dir,
1452            "js/style.js",
1453            "el.style.cssText = 'max-width: 320px';\n",
1454        );
1455        Breakpoints::files(&[dir.join("js/style.js")]).run();
1456    }
1457
1458    #[test]
1459    fn the_error_names_the_file_and_line() {
1460        let dir = frontend("bp-message");
1461        write(
1462            &dir,
1463            "css/styles.css",
1464            "body { }\n@media (max-width: 768px) { }\n",
1465        );
1466        let err = std::panic::catch_unwind(|| Breakpoints::in_frontend(&dir).run()).unwrap_err();
1467        let msg = err
1468            .downcast_ref::<String>()
1469            .expect("panic payload is a String");
1470        assert!(msg.contains("css/styles.css:2"), "got: {msg}");
1471    }
1472
1473    #[test]
1474    fn a_rule_restating_an_upstream_class_fails_and_its_served_copy_does_not() {
1475        // quasi-webview's sheet owns `.run`'s gap the way makeover owns
1476        // `.card`'s shadow, and an app redrawing it wins silently the same way.
1477        let upstream = ".tile-set { gap: 4px; }\n";
1478        let dir = scratch("vocab-upstream");
1479        write(&dir, "css/quasi.css", upstream);
1480        write(&dir, "css/styles.css", ".tile-set { gap: 0; }\n");
1481        let err = std::panic::catch_unwind(|| {
1482            Vocabulary::in_frontend(&dir)
1483                .upstream(&[upstream])
1484                .run(&Emit::default());
1485        })
1486        .unwrap_err();
1487        let msg = err
1488            .downcast_ref::<String>()
1489            .expect("panic payload is a String");
1490        assert!(
1491            msg.contains("css/styles.css  .tile-set { gap }"),
1492            "got: {msg}"
1493        );
1494        assert!(
1495            !msg.contains("css/quasi.css"),
1496            "the served copy clashed with itself: {msg}"
1497        );
1498
1499        // Without the upstream sheet named, the same tree passes, which is the
1500        // blind spot this closes.
1501        Vocabulary::in_frontend(&dir).run(&Emit::default());
1502    }
1503
1504    #[test]
1505    fn a_rule_restating_a_generated_class_fails_and_names_it() {
1506        let dir = scratch("vocab-clash");
1507        // `.card` is makeover's. An app rule for it beats the generated one,
1508        // because app CSS is unlayered and the generated sheet is not.
1509        write(
1510            &dir,
1511            "css/styles.css",
1512            "body { color: red; }\n.card { box-shadow: none; }\n",
1513        );
1514        let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
1515            .unwrap_err();
1516        let msg = err
1517            .downcast_ref::<String>()
1518            .expect("panic payload is a String");
1519        assert!(msg.contains(".card"), "got: {msg}");
1520        assert!(msg.contains("box-shadow"), "got: {msg}");
1521        assert!(msg.contains("css/styles.css"), "got: {msg}");
1522    }
1523
1524    #[test]
1525    fn an_app_class_of_its_own_is_left_alone() {
1526        let dir = scratch("vocab-clean");
1527        write(
1528            &dir,
1529            "css/styles.css",
1530            ".task-list-container { overflow: auto; }\n.day-plan-slot { height: 1rem; }\n",
1531        );
1532        Vocabulary::in_frontend(&dir).run(&Emit::default());
1533    }
1534
1535    #[test]
1536    fn the_generated_sheet_is_skipped_rather_than_reported_against_itself() {
1537        let dir = scratch("vocab-generated");
1538        let opts = Emit::default();
1539        write(&dir, "css/layout.css", &makeover_webview::stylesheet(&opts));
1540        // Without the skip this is the loudest failure possible: every class in
1541        // the vocabulary, reported as a clash with the vocabulary.
1542        Vocabulary::in_frontend(&dir)
1543            .generated(&["layout.css"])
1544            .run(&opts);
1545    }
1546
1547    #[test]
1548    fn a_prefixed_app_is_checked_against_its_own_prefix() {
1549        let dir = scratch("vocab-prefix");
1550        let opts = Emit::new().class_prefix("mo-");
1551        // Bare `.card` is the app's own class once the generated sheet writes
1552        // `.mo-card`, so this has to pass.
1553        write(&dir, "css/styles.css", ".card { box-shadow: none; }\n");
1554        Vocabulary::in_frontend(&dir).run(&opts);
1555
1556        let dir = scratch("vocab-prefix-clash");
1557        write(&dir, "css/styles.css", ".mo-card { box-shadow: none; }\n");
1558        assert!(std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&opts)).is_err());
1559    }
1560
1561    #[test]
1562    fn a_class_shared_without_a_shared_property_is_left_alone() {
1563        let dir = scratch("vocab-additive");
1564        // The generated `.cell-value` sets only the text colour, so an app
1565        // setting its shape shares the class and takes nothing from it.
1566        write(
1567            &dir,
1568            "css/styles.css",
1569            ".cell-value { padding: 2px; border-radius: 3px; font-weight: 600; }\n",
1570        );
1571        Vocabulary::in_frontend(&dir).run(&Emit::default());
1572    }
1573
1574    #[test]
1575    fn a_reviewed_pair_passes_and_stops_passing_when_it_stops_colliding() {
1576        let dir = scratch("vocab-allowed");
1577        write(&dir, "css/styles.css", ".card { box-shadow: none; }\n");
1578        Vocabulary::in_frontend(&dir)
1579            .allow(Allow::class("card", "box-shadow"))
1580            .run(&Emit::default());
1581
1582        // The same licence against a sheet that no longer collides has to fail,
1583        // or the list only ever grows.
1584        let dir = scratch("vocab-allowed-stale");
1585        write(&dir, "css/styles.css", ".card { padding: 2px; }\n");
1586        let err = std::panic::catch_unwind(|| {
1587            Vocabulary::in_frontend(&dir)
1588                .allow(Allow::class("card", "box-shadow"))
1589                .run(&Emit::default());
1590        })
1591        .unwrap_err();
1592        let msg = err
1593            .downcast_ref::<String>()
1594            .expect("panic payload is a String");
1595        assert!(msg.contains("no longer collides"), "got: {msg}");
1596    }
1597
1598    #[test]
1599    fn an_element_rule_clobbering_a_generated_class_fails_and_names_all_three() {
1600        let dir = scratch("vocab-element");
1601        // The defect that shipped for months: no class in the selector, so the
1602        // class pass sees nothing, and every described act in the app takes the
1603        // app's bevel instead of the design system's.
1604        write(&dir, "css/styles.css", "select { box-shadow: none; }\n");
1605        let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
1606            .unwrap_err();
1607        let msg = err
1608            .downcast_ref::<String>()
1609            .expect("panic payload is a String");
1610        assert!(msg.contains("select {"), "got: {msg}");
1611        assert!(msg.contains(".field"), "got: {msg}");
1612        assert!(msg.contains("box-shadow"), "got: {msg}");
1613        assert!(msg.contains("css/styles.css"), "got: {msg}");
1614    }
1615
1616    #[test]
1617    fn a_universal_reset_after_the_design_system_is_caught() {
1618        // goingson and MNW both opened with `* { margin: 0; padding: 0 }` in a
1619        // layer after `makeover`, which zeroed every generated padding. Nothing
1620        // said so until a render showed cells with no padding.
1621        let dir = scratch("vocab-universal");
1622        write(&dir, "css/styles.css", "* { margin: 0; padding: 0; }\n");
1623        let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
1624            .unwrap_err();
1625        let msg = err
1626            .downcast_ref::<String>()
1627            .expect("panic payload is a String");
1628        assert!(msg.contains("* {"), "got: {msg}");
1629        assert!(msg.contains("padding"), "got: {msg}");
1630    }
1631
1632    #[test]
1633    fn a_universal_reset_in_a_layer_beneath_makeover_is_not_read() {
1634        let dir = scratch("vocab-universal-beneath");
1635        write(
1636            &dir,
1637            "css/styles.css",
1638            "/* { */ @layer reset {\n  * { margin: 0; padding: 0; }\n}\n.x { content: \"}\"; }\n",
1639        );
1640        Vocabulary::in_frontend(&dir)
1641            .beneath(&["reset"])
1642            .run(&Emit::default());
1643    }
1644
1645    #[test]
1646    fn a_layer_not_named_beneath_is_still_read() {
1647        let dir = scratch("vocab-universal-other-layer");
1648        write(
1649            &dir,
1650            "css/styles.css",
1651            "@layer base {\n  * { padding: 0; }\n}\n",
1652        );
1653        let err = std::panic::catch_unwind(|| {
1654            Vocabulary::in_frontend(&dir)
1655                .beneath(&["reset"])
1656                .run(&Emit::default());
1657        })
1658        .unwrap_err();
1659        let msg = err.downcast_ref::<String>().expect("a String payload");
1660        assert!(msg.contains("* {"), "got: {msg}");
1661    }
1662
1663    #[test]
1664    fn a_universal_rule_touching_nothing_generated_is_not_a_clash() {
1665        let dir = scratch("vocab-universal-box");
1666        write(&dir, "css/styles.css", "* { box-sizing: border-box; }\n");
1667        Vocabulary::in_frontend(&dir).run(&Emit::default());
1668    }
1669
1670    #[test]
1671    fn a_handoff_on_the_class_is_the_remedy_and_reads_as_one() {
1672        let dir = scratch("vocab-element-handoff");
1673        // What a consumer writes instead of an exception: the element rule
1674        // stays, and a later layer gives the property back on the class. The
1675        // check has to read that as settled or the remedy fails the build it
1676        // was written to fix.
1677        write(
1678            &dir,
1679            "css/styles.css",
1680            "select { box-shadow: none; }\n.field { box-shadow: revert-layer; }\n",
1681        );
1682        Vocabulary::in_frontend(&dir).run(&Emit::default());
1683    }
1684
1685    #[test]
1686    fn a_property_the_app_states_on_the_class_is_not_the_element_rules_doing() {
1687        let dir = scratch("vocab-element-spoken-for");
1688        // Within the app's own sheet the class rule outranks the bare element
1689        // rule, so what reaches the design system is `.button`, not `button`.
1690        // The class pass has that pair, here as a reviewed one, and
1691        // reporting it twice would ask for two remedies for one collision.
1692        write(
1693            &dir,
1694            "css/styles.css",
1695            "select { box-shadow: none; }\n.field { box-shadow: none; }\n",
1696        );
1697        Vocabulary::in_frontend(&dir)
1698            .allow(Allow::class("field", "box-shadow"))
1699            .run(&Emit::default());
1700    }
1701
1702    #[test]
1703    fn a_handoff_that_loses_to_the_rule_it_remedies_is_not_a_remedy() {
1704        let dir = scratch("vocab-element-weak-handoff");
1705        // The shape that reads as fixed and is not: both rules are the app's
1706        // and both are in the same layer, so the state on the element rule
1707        // decides, and the described field keeps the app's sunken fill.
1708        write(
1709            &dir,
1710            "css/styles.css",
1711            "select:focus { box-shadow: none; }\n.field { box-shadow: revert-layer; }\n",
1712        );
1713        let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
1714            .unwrap_err();
1715        let msg = err
1716            .downcast_ref::<String>()
1717            .expect("panic payload is a String");
1718        assert!(msg.contains(".field"), "got: {msg}");
1719
1720        // Written to win, it is.
1721        let dir = scratch("vocab-element-strong-handoff");
1722        write(
1723            &dir,
1724            "css/styles.css",
1725            "select:focus { box-shadow: none; }\nselect.field { box-shadow: revert-layer; }\n",
1726        );
1727        Vocabulary::in_frontend(&dir).run(&Emit::default());
1728    }
1729
1730    #[test]
1731    fn a_scoped_rule_is_not_read_as_an_element_rule() {
1732        let dir = scratch("vocab-element-scoped");
1733        // It reaches the buttons inside one region rather than every button, so
1734        // whether it lands on a described act depends on where that act
1735        // renders. Failing the build on a guess is the worse error.
1736        write(
1737            &dir,
1738            "css/styles.css",
1739            ".wizard select { box-shadow: none; }\n",
1740        );
1741        Vocabulary::in_frontend(&dir).run(&Emit::default());
1742    }
1743
1744    #[test]
1745    fn an_element_the_design_system_never_renders_onto_is_left_alone() {
1746        let dir = scratch("vocab-element-unpaired");
1747        // `.card` is a container: no generated class sits on a `<footer>`, so
1748        // there is nothing for this rule to take.
1749        write(&dir, "css/styles.css", "footer { box-shadow: none; }\n");
1750        Vocabulary::in_frontend(&dir).run(&Emit::default());
1751    }
1752
1753    #[test]
1754    fn a_reviewed_element_pairing_passes_and_stops_passing_when_it_stops_colliding() {
1755        let dir = scratch("vocab-element-allowed");
1756        write(&dir, "css/styles.css", "select { box-shadow: none; }\n");
1757        Vocabulary::in_frontend(&dir)
1758            .allow(Allow::element("select", "field", "box-shadow"))
1759            .run(&Emit::default());
1760
1761        // And the same licence against a sheet that no longer collides fails,
1762        // for the reason the class list's does.
1763        let dir = scratch("vocab-element-allowed-stale");
1764        write(&dir, "css/styles.css", "select { padding: 2px; }\n");
1765        let err = std::panic::catch_unwind(|| {
1766            Vocabulary::in_frontend(&dir)
1767                .allow(Allow::element("select", "field", "box-shadow"))
1768                .run(&Emit::default());
1769        })
1770        .unwrap_err();
1771        let msg = err
1772            .downcast_ref::<String>()
1773            .expect("panic payload is a String");
1774        assert!(msg.contains("no longer collides"), "got: {msg}");
1775    }
1776
1777    /// How many rung classes the vocabulary holds, and on how many ladders.
1778    fn ladders(names: &std::collections::BTreeSet<String>) -> (usize, usize) {
1779        let mut rungs = 0;
1780        let mut ladders = 0;
1781        for ladder in ["min-", "short-"] {
1782            let here = names
1783                .iter()
1784                .filter(|c| {
1785                    c.strip_prefix(ladder)
1786                        .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
1787                })
1788                .count();
1789            rungs += here;
1790            ladders += usize::from(here > 0);
1791        }
1792        (rungs, ladders)
1793    }
1794
1795    #[test]
1796    fn dead_vocabulary_above_the_seal_fails_and_below_it_passes() {
1797        let dir = scratch("vocab-seal");
1798        let opts = Emit::default();
1799        let names = makeover_webview::vocabulary::names(&opts);
1800        let (rungs, ladders) = ladders(&names);
1801        assert!(ladders >= 1, "the floor ladder is in the vocabulary");
1802        // Markup naming nothing: every class is unused, and each ladder counts
1803        // once rather than once a rung.
1804        let dead = names.len() - rungs + ladders;
1805        write(&dir, "index.html", "<div></div>\n");
1806        let markup = [dir.join("index.html")];
1807
1808        check_vocabulary_use(&markup, &opts, dead);
1809        assert!(
1810            std::panic::catch_unwind(|| check_vocabulary_use(&markup, &opts, dead - 1)).is_err(),
1811            "a vocabulary deader than the seal has to fail"
1812        );
1813    }
1814
1815    #[test]
1816    fn one_rung_of_the_floor_ladder_uses_the_ladder() {
1817        // A column carries whichever rung its floor lands on, so a site naming
1818        // one rung is using the ladder, and one naming none has one dead name.
1819        let opts = Emit::default();
1820        let names = makeover_webview::vocabulary::names(&opts);
1821        let (rungs, ladders) = ladders(&names);
1822        let dead = names.len() - rungs + ladders;
1823
1824        let dir = scratch("vocab-ladder");
1825        write(&dir, "index.html", "<div class=\"cell min-16\"></div>\n");
1826        let one_rung = [dir.join("index.html")];
1827        // `cell` is named too, so two fewer than a page naming nothing.
1828        check_vocabulary_use(&one_rung, &opts, dead - 2);
1829
1830        // A longer rung does not name a shorter one it starts with.
1831        write(&dir, "index.html", "<div class=\"min-24\"></div>\n");
1832        assert!(haystack_names("<div class=\"min-24\">", "min-24"));
1833        assert!(!haystack_names("<div class=\"min-24\">", "min-2"));
1834    }
1835
1836    #[test]
1837    fn a_class_is_named_whole_on_both_sides() {
1838        assert!(haystack_names("class=\"row\"", "row"));
1839        assert!(!haystack_names("class=\"row-flex\"", "row"));
1840        assert!(!haystack_names("class=\"flex-row\"", "row"));
1841        assert!(haystack_names("el.classList.add('row')", "row"));
1842    }
1843
1844    #[test]
1845    fn range_syntax_and_units_are_read() {
1846        assert_eq!(media_widths("(width < 600px)"), [Width::Px(600)]);
1847        assert_eq!(
1848            media_widths(" (600px <= width < 840px)"),
1849            [Width::Px(600), Width::Px(840)]
1850        );
1851        assert_eq!(media_widths(" (max-width: 48em)"), [Width::Px(768)]);
1852        assert_eq!(media_widths(" (min-width: 37.5rem)"), [Width::Px(600)]);
1853        assert_eq!(
1854            media_widths(" (max-width: 599.98px)"),
1855            [Width::Other("599.98px".into())]
1856        );
1857        assert_eq!(
1858            media_widths(" (width < 50vw)"),
1859            [Width::Other("50vw".into())]
1860        );
1861        assert!(media_widths(" (min-height: 600px)").is_empty());
1862        assert!(media_widths(" (max-device-width: 600px)").is_empty());
1863        assert!(media_widths(" (hover: hover) and (pointer: fine)").is_empty());
1864    }
1865
1866    #[test]
1867    fn every_size_class_condition_passes_its_own_check() {
1868        let dir = frontend("bp-classes");
1869        let mut css = String::new();
1870        for class in SizeClass::all() {
1871            let _ = writeln!(css, "@media {} {{ body {{ }} }}", class.media_condition());
1872        }
1873        write(&dir, "css/styles.css", &css);
1874        write(
1875            &dir,
1876            "js/shell.js",
1877            &format!("matchMedia('{}');\n", SizeClass::Compact.media_condition()),
1878        );
1879        Breakpoints::in_frontend(&dir).run();
1880    }
1881
1882    #[test]
1883    #[should_panic(expected = "48em")]
1884    fn a_width_in_em_is_a_width_and_not_a_bare_number() {
1885        let dir = frontend("bp-em");
1886        write(&dir, "css/styles.css", "@media (max-width: 48em) { }\n");
1887        Breakpoints::in_frontend(&dir).tuning(&[48]).run();
1888    }
1889
1890    #[test]
1891    #[should_panic(expected = "(width < 768px)")]
1892    fn a_stale_range_width_fails() {
1893        let dir = frontend("bp-range");
1894        write(&dir, "css/styles.css", "@media (width < 768px) { }\n");
1895        Breakpoints::in_frontend(&dir).run();
1896    }
1897
1898    #[test]
1899    #[should_panic(expected = "599px")]
1900    fn the_old_inclusive_compact_bound_is_stale() {
1901        let dir = frontend("bp-599");
1902        write(&dir, "css/styles.css", "@media (max-width: 599px) { }\n");
1903        Breakpoints::in_frontend(&dir).run();
1904    }
1905
1906    #[test]
1907    fn a_call_in_script_is_not_a_feature() {
1908        assert!(js_widths("const w = Math.max(width, 600);").is_empty());
1909        assert!(js_widths("el.style.cssText = 'max-width: 320px';").is_empty());
1910        assert_eq!(js_widths("matchMedia('(width < 600px)')").len(), 1);
1911    }
1912
1913    #[test]
1914    fn a_slash_star_slash_opens_a_comment_rather_than_closing_one() {
1915        let css = "/*/ @media (max-width: 768px) { } */ a { }";
1916        let stripped = blank(css, Lang::Css);
1917        assert!(!stripped.contains("768"), "{stripped:?}");
1918        assert!(stripped.contains("a { }"));
1919        assert_eq!(stripped.len(), css.len());
1920    }
1921
1922    #[test]
1923    fn a_comment_opener_inside_a_string_is_text() {
1924        // Read as a comment, the `/*` would blank the query after it.
1925        let css = "a::after { content: \"/*\"; }\n@media (max-width: 768px) { }\n";
1926        let src = blank(css, Lang::Css);
1927        assert_eq!(media_conditions(&src).len(), 1);
1928        assert!(src.contains("768"));
1929
1930        let js = "const glob = '/*';\nmatchMedia('(width < 600px)');\n";
1931        assert_eq!(js_widths(&blank(js, Lang::Js)).len(), 1);
1932    }
1933
1934    #[test]
1935    fn a_query_in_a_script_comment_is_prose() {
1936        let js = "// was matchMedia('(width < 768px)')\n/* (max-width: 500px) */\n";
1937        assert!(js_widths(&blank(js, Lang::Js)).is_empty());
1938    }
1939
1940    #[test]
1941    fn a_brace_inside_a_css_string_does_not_end_a_condition() {
1942        let css = "@media (width < 600px) { a::after { content: \"{\"; } }";
1943        let src = blank(css, Lang::Css);
1944        assert_eq!(media_conditions(&src).len(), 1);
1945    }
1946
1947    #[test]
1948    fn blanking_keeps_byte_offsets_through_multibyte_text() {
1949        // An em dash in a comment and in a string: three bytes each, blanked
1950        // to three spaces, so everything after them sits where it did.
1951        let css = "/* a \u{2014} b */ a::after { content: \"\u{2014}\"; }\n@layer reset { * { padding: 0; } }";
1952        let src = blank(css, Lang::Css);
1953        assert_eq!(src.len(), css.len());
1954        let at = css.find("@layer").unwrap();
1955        assert_eq!(&src[at..at + 6], "@layer");
1956        let dropped = drop_layers(css, &["reset"]);
1957        assert!(!dropped.contains("padding"), "{dropped:?}");
1958    }
1959
1960    #[test]
1961    fn blanking_keeps_lines_and_offsets() {
1962        let css = "/* one\ntwo */\n\"x\ny\"\n@media (max-width: 1px) {}";
1963        let src = blank(css, Lang::Css);
1964        assert_eq!(src.len(), css.len());
1965        assert_eq!(src.lines().count(), css.lines().count());
1966    }
1967
1968    #[test]
1969    fn both_quote_styles_read() {
1970        let want = Density::Touch.media_condition();
1971        for q in ['\'', '"'] {
1972            let src = format!("const {CONST_NAME} = {q}{want}{q};\n");
1973            let found = touch_density_literals(&src);
1974            assert_eq!(found.len(), 1);
1975            assert_eq!(found[0].1, want);
1976        }
1977    }
1978
1979    #[test]
1980    fn a_file_list_skips_the_sheets_named_generated() {
1981        let dir = frontend("vocab-files");
1982        write(&dir, "css/layout.css", ".card { box-shadow: none; }\n");
1983        write(&dir, "css/app.css", "body { color: red; }\n");
1984        let files = [dir.join("css/layout.css"), dir.join("css/app.css")];
1985        Vocabulary::files(&files)
1986            .generated(&["layout.css"])
1987            .run(&Emit::default());
1988        let err = std::panic::catch_unwind(|| Vocabulary::files(&files).run(&Emit::default()))
1989            .unwrap_err();
1990        let msg = err.downcast_ref::<String>().cloned().unwrap_or_default();
1991        assert!(msg.contains("box-shadow"), "got: {msg}");
1992    }
1993}