makeover-build 0.21.0

Build-script support for the make-family design system: materialise makeover's themes and makeover-webview's stylesheet into a Tauri app's frontend, once, instead of copying the same twenty lines into every consumer's build.rs.
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
//! Checks that a hand-written frontend still agrees with the crate that
//! generates its siblings.
//!
//! The generated files cannot drift: they ask makeover-geometry for the answer.
//! The hand-written ones state it, and a stylesheet or a script that disagrees
//! with the crate is not an error at any point -- it is a rule that quietly
//! stops matching where it used to. Cheaper to read a panic naming the line.
//!
//! Deliberately assertions and not substitutions. A JS or CSS file that has to
//! be generated to be correct stops being readable on its own, and it is worth
//! something that you can still open the frontend in a browser and have it
//! work.

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

use makeover_geometry::{Density, SizeClass};

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

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

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

    let files = js_files(js_dir);
    for path in &files {
        let src = std::fs::read_to_string(path).expect("read js file");
        let name = path
            .strip_prefix(js_dir)
            .unwrap_or(path)
            .display()
            .to_string();

        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 {
        println!("cargo:rerun-if-changed={}", path.display());
    }
}

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

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

/// `(byte offset of the declaration, the literal's contents)` for every
/// `const TOUCH_DENSITY = '...'` in a JS source.
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();
        // Only the declaration states the string; a use site reads the const.
        let Some(rest) = src[at..].strip_prefix(" = ") else {
            continue;
        };
        let open = at + " = ".len();
        let Some(quote @ ('\'' | '"')) = rest.chars().next() else {
            continue;
        };
        let body = open + 1;
        if let Some(j) = src[body..].find(quote) {
            out.push((start, &src[body..body + j]));
            at = body + j + 1;
        }
    }
    out
}

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

/// Fail the build if a hand-written breakpoint has drifted from [`SizeClass`].
///
/// Every pixel width named by a media query under `frontend/css` or
/// `frontend/js`, recursively, must be a [`SizeClass`] boundary or one of
/// `tuning_widths`.
///
/// Without this, moving `SizeClass::Medium::min_px` regenerates the emitted
/// stylesheets and silently leaves every hand-written query behind, and what
/// you get is not an error but a stylesheet that disagrees with itself at the
/// old boundary.
///
/// `tuning_widths` is the one thing an app gets a say in, which is why this
/// takes a parameter where [`check_touch_density`] does not. A shell boundary
/// is a [`SizeClass`] edge and belongs to makeover-geometry; a tuning width is
/// a point inside a shell where something reflows without the shell changing --
/// a dashboard dropping from three columns to two, a pane's width cap ending.
/// Nothing switches shells at one, so it should not move when a size class
/// does. Pass `&[]` if the app has none, and treat every addition as owing a
/// note saying what it tunes: the list is where a genuine boundary goes to hide
/// from this check.
///
/// The generated stylesheets are scanned too, and pass by construction: they
/// ask makeover-geometry for the number rather than stating it. Scanning them
/// costs nothing and means a consumer never has to name which files are
/// hand-written.
///
/// Emits `cargo:rerun-if-changed` for every file it read.
///
/// # Panics
///
/// If `frontend/css` or `frontend/js` cannot be read, or if any width is
/// neither a size-class boundary nor a declared tuning width. A build script
/// has nowhere useful to return an error to.
pub fn check_breakpoints(frontend: impl AsRef<Path>, tuning_widths: &[u16]) {
    let frontend = frontend.as_ref();
    let mut files = files_with_extension(&frontend.join("css"), "css");
    files.extend(js_files(&frontend.join("js")));
    check_paths(&files, tuning_widths, Some(frontend));
}

/// [`check_breakpoints`] against a named list of files rather than a tree.
///
/// For a frontend whose generated and hand-written files share a directory, so
/// there is nothing to point a directory scan at: the MNW server keeps both
/// under `static/` alongside a bundler's output, and bundled third-party CSS
/// is exactly the place a width nobody chose would come from.
///
/// The cost is that the list is hand-maintained, and a stylesheet nobody adds
/// to it is unchecked rather than failing. Prefer [`check_breakpoints`] where
/// the layout allows it.
///
/// A `.js` path is parsed as script and anything else as stylesheet, which is
/// the only difference: a media condition is parenthesised in both.
///
/// # Panics
///
/// If a listed file cannot be read -- a listed path that no longer exists is a
/// check silently covering less than it says -- or if any width is neither a
/// size-class boundary nor a declared tuning width.
pub fn check_breakpoints_files<P: AsRef<Path>>(paths: &[P], tuning_widths: &[u16]) {
    let paths: Vec<PathBuf> = paths.iter().map(|p| p.as_ref().to_path_buf()).collect();
    check_paths(&paths, tuning_widths, None);
}

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

    for path in paths {
        let raw = std::fs::read_to_string(path)
            .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
        let name = match root {
            Some(root) => display_name(root, path),
            None => path.display().to_string(),
        };

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

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

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

    for path in paths {
        println!("cargo:rerun-if-changed={}", path.display());
    }
}

/// A path as the frontend sees it, for an error a reader can act on.
fn display_name(frontend: &Path, path: &Path) -> String {
    path.strip_prefix(frontend)
        .unwrap_or(path)
        .display()
        .to_string()
}

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

/// The pixel values in a media condition, in the order they appear.
fn media_widths(condition: &str) -> Vec<u16> {
    let mut out = Vec::new();
    let mut rest = condition;
    while let Some(i) = rest.find("-width:") {
        rest = &rest[i + "-width:".len()..];
        let digits: String = rest
            .trim_start()
            .chars()
            .take_while(char::is_ascii_digit)
            .collect();
        if let Ok(px) = digits.parse() {
            out.push(px);
        }
    }
    out
}

/// `(byte offset of the `@media`, the condition text before the `{`)`.
fn media_conditions(css: &str) -> Vec<(usize, &str)> {
    let mut out = Vec::new();
    let mut at = 0;
    while let Some(i) = css[at..].find("@media") {
        let start = at + i;
        let after = start + "@media".len();
        match css[after..].find('{') {
            Some(j) => {
                out.push((start, &css[after..after + j]));
                at = after + j;
            }
            None => break,
        }
    }
    out
}

/// `(byte offset, pixel value)` for every `(max-width: Npx)` in a JS source.
///
/// The parentheses are the whole test, and they have to be: a media condition
/// is always parenthesized and a CSS declaration never is, so `'max-width:
/// 320px'` in an inline-style string is not a breakpoint and must not read as
/// one. goingson's shared-updater.js builds exactly that, and the first version
/// of this check failed the build on it.
fn js_widths(src: &str) -> Vec<(usize, u16)> {
    let mut out = Vec::new();
    for pat in ["(max-width:", "(min-width:"] {
        let mut at = 0;
        while let Some(i) = src[at..].find(pat) {
            let start = at + i;
            let rest = src[start + pat.len()..].trim_start();
            let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
            if let Ok(px) = digits.parse()
                && rest[digits.len()..].starts_with("px)")
            {
                out.push((start, px));
            }
            at = start + pat.len();
        }
    }
    out
}

/// Replace every `/* ... */` with spaces, so byte offsets still line up.
fn strip_block_comments(css: &str) -> String {
    let bytes = css.as_bytes();
    let mut out = String::with_capacity(css.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i..].starts_with(b"/*") {
            let end = css[i..].find("*/").map_or(bytes.len(), |j| i + j + 2);
            for c in css[i..end].chars() {
                out.push(if c == '\n' { '\n' } else { ' ' });
            }
            i = end;
        } else {
            let c = css[i..].chars().next().unwrap();
            out.push(c);
            i += c.len_utf8();
        }
    }
    out
}

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

    fn scratch(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("makeover-drift-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("create scratch");
        dir
    }

    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());
    }

    #[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()),
        );
        check_breakpoints(&dir, &[]);
    }

    #[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");
        check_breakpoints(&dir, &[]);
    }

    #[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");
        check_breakpoints(&dir, &[]);
    }

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

    #[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",
        );
        check_breakpoints(&dir, &[]);
    }

    #[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",
        );
        check_breakpoints(&dir, &[]);
    }

    #[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(|| check_breakpoints(&dir, &[]));
        assert!(found.is_err(), "a nested stylesheet must be scanned");
    }

    #[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(|| check_breakpoints_files(&[&listed], &[])).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");
        check_breakpoints_files(&[dir.join("css/never-written.css")], &[]);
    }

    #[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",
        );
        check_breakpoints_files(&[dir.join("js/style.js")], &[]);
    }

    #[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(|| check_breakpoints(&dir, &[])).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 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);
        }
    }
}