makeover 5.10.0

Shared theme loading for the make-family apps: TOML theme files parsed into intent-based color tokens, with perceptual derivations and WCAG contrast.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
//! Finding a look an app writes for itself instead of taking it from a token.
//!
//! Each [`Rule`] names one way a hand-written sheet can say a value makeover
//! already owns: a colour, a quiet ink faked with opacity, a status tint mixed
//! by hand, a length, a duration, a face, a token restated, a token nothing
//! defines. [`markup`] and [`script`] find the same thing written into HTML or
//! from a script. A gate runs them over the files people edit and refuses or
//! counts what it finds.

use std::collections::BTreeSet;

use crate::literals::{blank_unread, writes_colour};

/// One way of writing a look by hand.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Rule {
    /// A colour written as a literal.
    Colour,
    /// `opacity` below 1 outside an animation, which is a quiet ink or a hover
    /// tone with no contrast floor under it.
    OpacityInk,
    /// `color-mix` of a status or accent intent, which the toned surfaces and
    /// hover tokens already resolve with a floor.
    MixedTint,
    /// A literal length where the geometry scale has the step: an edge, a
    /// spacing, a radius, a type size, a shadow offset or a measure.
    Length,
    /// A literal time in a transition or an animation, which the reduced-motion
    /// block cannot reach.
    Duration,
    /// A literal `font-family`.
    Face,
    /// A custom property a generated sheet already defines, restated.
    TokenShadow,
    /// `var()` of a custom property that nothing defines, with no fallback.
    UndefinedVar,
    /// A `style` attribute that sets anything but custom properties.
    InlineStyle,
    /// A `<style>` block in markup.
    StyleBlock,
    /// An SVG `fill` or `stroke` attribute naming a paint of its own.
    SvgPaint,
    /// A script writing an element's style, or markup that carries one.
    ScriptStyle,
}

impl Rule {
    /// Every rule, in report order.
    pub const ALL: &[Self] = &[
        Self::Colour,
        Self::OpacityInk,
        Self::MixedTint,
        Self::Length,
        Self::Duration,
        Self::Face,
        Self::TokenShadow,
        Self::UndefinedVar,
        Self::InlineStyle,
        Self::StyleBlock,
        Self::SvgPaint,
        Self::ScriptStyle,
    ];

    /// The rule's stable id, the key a ceiling or an exemption names it by.
    #[must_use]
    pub const fn id(self) -> &'static str {
        match self {
            Self::Colour => "colour",
            Self::OpacityInk => "opacity-ink",
            Self::MixedTint => "mixed-tint",
            Self::Length => "length",
            Self::Duration => "duration",
            Self::Face => "face",
            Self::TokenShadow => "token-shadow",
            Self::UndefinedVar => "undefined-var",
            Self::InlineStyle => "inline-style",
            Self::StyleBlock => "style-block",
            Self::SvgPaint => "svg-paint",
            Self::ScriptStyle => "script-style",
        }
    }

    /// The rule named by `id`.
    #[must_use]
    pub fn from_id(id: &str) -> Option<Self> {
        Self::ALL.iter().copied().find(|r| r.id() == id)
    }
}

impl std::fmt::Display for Rule {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.id())
    }
}

/// A look written by hand: the rule, the line it is on counted from 1, and the
/// declaration that holds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    pub rule: Rule,
    pub line: usize,
    pub declaration: String,
}

impl std::fmt::Display for Finding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "line {} [{}]: {}",
            self.line, self.rule, self.declaration
        )
    }
}

/// What the sheets a page links define, which [`Rule::TokenShadow`] and
/// [`Rule::UndefinedVar`] read against.
#[derive(Debug, Clone, Default)]
pub struct Context {
    generated: BTreeSet<String>,
    defined: BTreeSet<String>,
}

impl Context {
    /// A context whose generated sheets are `sheets`.
    #[must_use]
    pub fn generated(sheets: &[&str]) -> Self {
        let mut ctx = Self::default();
        for sheet in sheets {
            for name in custom_properties(sheet) {
                ctx.generated.insert(name.clone());
                ctx.defined.insert(name);
            }
        }
        ctx
    }

    /// Adds the custom properties `sheet` defines, a hand sheet the same page
    /// links, so a token one part defines and another reads is not undefined.
    pub fn link(&mut self, sheet: &str) {
        self.defined.extend(custom_properties(sheet));
    }

    /// Adds names set where no sheet can see them: on an element's `style` by
    /// the renderer, or from a script.
    pub fn set_at_runtime<'a>(&mut self, names: impl IntoIterator<Item = &'a str>) {
        self.defined.extend(
            names
                .into_iter()
                .map(|n| n.trim_start_matches('-').to_string()),
        );
    }
}

/// Every declaration in `css` that writes a look by hand.
#[must_use]
pub fn css(css: &str, ctx: &Context) -> Vec<Finding> {
    let text = blank_unread(css);
    let decls = declarations(&text);
    let mut own: BTreeSet<String> = ctx.defined.clone();
    own.extend(
        decls
            .iter()
            .filter_map(|d| d.property.strip_prefix("--").map(str::to_string)),
    );
    let mut found = Vec::new();
    for d in &decls {
        for rule in rules_hit(d, ctx, &own) {
            found.push(Finding {
                rule,
                line: d.line,
                declaration: d.text.clone(),
            });
        }
    }
    found
}

fn rules_hit(d: &Decl, ctx: &Context, defined: &BTreeSet<String>) -> Vec<Rule> {
    let p = d.property.as_str();
    let v = d.value.as_str();
    let bare = blank_var_args(v);
    let mut hit = Vec::new();
    if writes_colour(p, v) {
        hit.push(Rule::Colour);
    }
    if p == "opacity" && !d.in_keyframes && opacity_below_one(v) {
        hit.push(Rule::OpacityInk);
    }
    if v.contains("color-mix(") && var_names(v).any(|n| TONES.contains(&n)) {
        hit.push(Rule::MixedTint);
    }
    if takes_scale_length(p) && has_unit(&bare, LENGTH_UNITS) {
        hit.push(Rule::Length);
    }
    if (p.starts_with("transition") || p.starts_with("animation")) && has_unit(&bare, TIME_UNITS) {
        hit.push(Rule::Duration);
    }
    if p == "font-family" && !is_token_or_keyword(v) {
        hit.push(Rule::Face);
    }
    if let Some(name) = p.strip_prefix("--")
        && ctx.generated.contains(name)
    {
        hit.push(Rule::TokenShadow);
    }
    if bare_vars(v).any(|n| !defined.contains(n)) {
        hit.push(Rule::UndefinedVar);
    }
    hit
}

/// The intents a hand mix should not tint with: each has a toned surface and a
/// hover the theme resolves.
const TONES: &[&str] = &["danger", "success", "warning", "info", "action"];

/// Absolute and font-relative units. Viewport and line units are not here: a
/// length relative to the window or the line is not a step the scale could own.
const LENGTH_UNITS: &[&str] = &[
    "px", "rem", "em", "ch", "ex", "pt", "pc", "cm", "mm", "in", "q",
];

const TIME_UNITS: &[&str] = &["ms", "s"];

/// Properties whose lengths the geometry scale owns, by stem.
fn takes_scale_length(p: &str) -> bool {
    const EXACT: &[&str] = &[
        "font-size",
        "box-shadow",
        "gap",
        "row-gap",
        "column-gap",
        "max-width",
        "max-inline-size",
    ];
    const STEMS: &[&str] = &["border", "outline", "padding", "margin"];
    EXACT.contains(&p)
        || STEMS
            .iter()
            .any(|s| p == *s || p.starts_with(&format!("{s}-")))
}

/// A declaration with what encloses it.
struct Decl {
    line: usize,
    property: String,
    value: String,
    text: String,
    in_keyframes: bool,
}

/// The declarations in blanked `text`, each with whether a `@keyframes` block
/// encloses it.
fn declarations(text: &str) -> Vec<Decl> {
    let mut out = Vec::new();
    let mut preludes: Vec<String> = Vec::new();
    let mut start = 0;
    for (at, c) in text.char_indices() {
        match c {
            '{' => {
                preludes.push(text[start..at].trim().to_ascii_lowercase());
                start = at + 1;
            }
            ';' | '}' => {
                let in_keyframes = preludes.iter().any(|p| p.contains("keyframes"));
                if let Some(d) = declaration(text, start, at, in_keyframes) {
                    out.push(d);
                }
                if c == '}' {
                    preludes.pop();
                }
                start = at + 1;
            }
            _ => {}
        }
    }
    out
}

fn declaration(text: &str, start: usize, end: usize, in_keyframes: bool) -> Option<Decl> {
    let segment = &text[start..end];
    let colon = segment.find(':')?;
    let property = segment[..colon].trim().to_ascii_lowercase();
    if property.is_empty() || property.contains(char::is_whitespace) || property.starts_with('@') {
        return None;
    }
    let lead = segment.len() - segment.trim_start().len();
    Some(Decl {
        line: text[..start + lead].matches('\n').count() + 1,
        property,
        value: segment[colon + 1..].trim().to_string(),
        text: segment.split_whitespace().collect::<Vec<_>>().join(" "),
        in_keyframes,
    })
}

/// The custom properties `css` defines, without their leading dashes.
fn custom_properties(css: &str) -> Vec<String> {
    declarations(&blank_unread(css))
        .into_iter()
        .filter_map(|d| d.property.strip_prefix("--").map(str::to_string))
        .collect()
}

fn opacity_below_one(value: &str) -> bool {
    let v = value.trim();
    let n = v
        .strip_suffix('%')
        .and_then(|p| p.trim().parse::<f64>().ok().map(|p| p / 100.0))
        .or_else(|| v.parse::<f64>().ok());
    n.is_some_and(|n| n > 0.0 && n < 1.0)
}

fn is_token_or_keyword(value: &str) -> bool {
    let v = value.trim().to_ascii_lowercase();
    v.starts_with("var(") || matches!(v.as_str(), "inherit" | "initial" | "unset" | "revert")
}

/// `value` with each `var(...)`'s arguments blanked, so a token's fallback is
/// not read as the author's own literal.
fn blank_var_args(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    let mut depth = 0usize;
    let mut i = 0;
    let b = value.as_bytes();
    while i < b.len() {
        if depth == 0 && value[i..].starts_with("var(") {
            out.push_str("var(");
            i += 4;
            depth = 1;
            continue;
        }
        let c = value[i..].chars().next().unwrap_or(' ');
        if depth > 0 {
            match c {
                '(' => depth += 1,
                ')' => depth -= 1,
                _ => {}
            }
            out.push(if depth == 0 { ')' } else { ' ' });
        } else {
            out.push(c);
        }
        i += c.len_utf8();
    }
    out
}

/// Whether `value` holds a nonzero number carrying one of `units`.
fn has_unit(value: &str, units: &[&str]) -> bool {
    let b = value.as_bytes();
    let mut i = 0;
    while i < b.len() {
        let starts = (b[i].is_ascii_digit() || b[i] == b'.')
            && (i == 0
                || !(b[i - 1].is_ascii_alphanumeric() || matches!(b[i - 1], b'_' | b'#' | b'.')));
        if !starts {
            i += 1;
            continue;
        }
        let num_end = i + b[i..]
            .iter()
            .take_while(|c| c.is_ascii_digit() || **c == b'.')
            .count();
        let unit_end = num_end
            + b[num_end..]
                .iter()
                .take_while(|c| c.is_ascii_alphabetic())
                .count();
        let unit = value[num_end..unit_end].to_ascii_lowercase();
        let nonzero = value[i..num_end]
            .bytes()
            .any(|c| (b'1'..=b'9').contains(&c));
        if nonzero && units.contains(&unit.as_str()) {
            return true;
        }
        i = unit_end.max(i + 1);
    }
    false
}

/// The custom property each `var(` in `value` reads, without its dashes.
fn var_names(value: &str) -> impl Iterator<Item = &str> {
    value.match_indices("var(").filter_map(move |(at, _)| {
        let rest = value[at + 4..].trim_start().strip_prefix("--")?;
        let len = rest
            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
            .unwrap_or(rest.len());
        Some(&rest[..len])
    })
}

/// The custom property each fallback-free `var(` in `value` reads.
fn bare_vars(value: &str) -> impl Iterator<Item = &str> {
    value.match_indices("var(").filter_map(move |(at, _)| {
        let rest = value[at + 4..].trim_start().strip_prefix("--")?;
        let len = rest
            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_'))
            .unwrap_or(rest.len());
        rest[len..]
            .trim_start()
            .starts_with(')')
            .then_some(&rest[..len])
    })
}

/// Every place `html` writes a look into the markup: a `style` attribute that
/// sets more than custom properties, a `<style>` block, an SVG paint of its own.
///
/// Comments (`<!-- -->`, and a template's `{# #}`) are not read. A `style`
/// attribute that only sets custom properties passes: that is data handed to a
/// rule, the way a renderer passes a bar's value.
#[must_use]
pub fn markup(html: &str) -> Vec<Finding> {
    let text = blank_between(&blank_between(html, "<!--", "-->"), "{#", "#}");
    let lower = text.to_ascii_lowercase();
    let mut found = Vec::new();
    let mut push = |rule, at: usize, quote: &str| {
        found.push(Finding {
            rule,
            line: text[..at].matches('\n').count() + 1,
            declaration: quote.split_whitespace().collect::<Vec<_>>().join(" "),
        });
    };
    for (at, _) in lower.match_indices("<style") {
        let next = lower[at + 6..].chars().next();
        if next.is_some_and(|c| c.is_whitespace() || c == '>') {
            push(Rule::StyleBlock, at, "<style>");
        }
    }
    for (name, rule) in [
        ("style", Rule::InlineStyle),
        ("fill", Rule::SvgPaint),
        ("stroke", Rule::SvgPaint),
    ] {
        for (at, value) in attributes(&text, &lower, name) {
            let writes = match rule {
                Rule::InlineStyle => !only_custom_properties(value),
                _ => !is_inherited_paint(value),
            };
            if writes {
                push(rule, at, &format!("{name}=\"{value}\""));
            }
        }
    }
    found.sort_by_key(|f| f.line);
    found
}

/// Every place `js` (a script or a TypeScript module) writes an element's look:
/// an assignment to `.style.<property>`, `style.cssText`, `setAttribute` of
/// `style`, or a string of markup that carries a `style` attribute.
///
/// Comments are not read. `style.setProperty` of a custom property passes, for
/// the reason [`markup`] passes a `style` of custom properties.
#[must_use]
pub fn script(js: &str) -> Vec<Finding> {
    let text = blank_script_comments(js);
    let mut found = Vec::new();
    let line_of = |at: usize| text[..at].matches('\n').count() + 1;
    let quote_at = |at: usize| {
        let start = text[..at].rfind('\n').map_or(0, |n| n + 1);
        let end = text[at..].find('\n').map_or(text.len(), |n| at + n);
        text[start..end].trim().to_string()
    };
    for (at, _) in text.match_indices(".style") {
        let rest = &text[at + 6..];
        let hit = if let Some(after) = rest.strip_prefix(".setProperty(") {
            !after
                .trim_start()
                .trim_start_matches(['\'', '"', '`'])
                .starts_with("--")
        } else if let Some(after) = rest.strip_prefix('.') {
            let len = after
                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
                .unwrap_or(after.len());
            let tail = after[len..].trim_start();
            len > 0 && tail.starts_with('=') && !tail.starts_with("==")
        } else {
            false
        };
        if hit {
            found.push(Finding {
                rule: Rule::ScriptStyle,
                line: line_of(at),
                declaration: quote_at(at),
            });
        }
    }
    for needle in [
        "setAttribute('style'",
        "setAttribute(\"style\"",
        "setAttribute(`style`",
    ] {
        for (at, _) in text.match_indices(needle) {
            found.push(Finding {
                rule: Rule::ScriptStyle,
                line: line_of(at),
                declaration: quote_at(at),
            });
        }
    }
    for (at, lit) in string_literals(&text) {
        let lower = lit.to_ascii_lowercase();
        let carries = attributes(lit, &lower, "style")
            .into_iter()
            .any(|(_, v)| !only_custom_properties(v));
        if carries {
            found.push(Finding {
                rule: Rule::ScriptStyle,
                line: line_of(at),
                declaration: quote_at(at),
            });
        }
    }
    found.sort_by_key(|f| f.line);
    found.dedup_by(|a, b| a.line == b.line && a.declaration == b.declaration);
    found
}

/// The value of each `name="..."` (or single-quoted) attribute in `text`, with
/// where it starts. `lower` is `text` lowercased, so names match in any case.
fn attributes<'a>(text: &'a str, lower: &str, name: &str) -> Vec<(usize, &'a str)> {
    let mut out = Vec::new();
    let pat = format!("{name}=");
    for (at, _) in lower.match_indices(&pat) {
        let before = lower[..at].chars().next_back();
        if !before.is_some_and(char::is_whitespace) {
            continue;
        }
        let rest = &text[at + pat.len()..];
        let Some(quote) = rest.chars().next().filter(|c| matches!(c, '"' | '\'')) else {
            continue;
        };
        let Some(end) = rest[1..].find(quote) else {
            continue;
        };
        out.push((at, &rest[1..=end]));
    }
    out
}

fn only_custom_properties(style: &str) -> bool {
    style
        .split(';')
        .map(str::trim)
        .filter(|d| !d.is_empty())
        .all(|d| d.starts_with("--") || d.starts_with("{{") || d.starts_with("{%"))
}

fn is_inherited_paint(value: &str) -> bool {
    let v = value.trim().to_ascii_lowercase();
    matches!(
        v.as_str(),
        "currentcolor" | "none" | "transparent" | "context-fill" | "context-stroke"
    ) || v.starts_with("var(")
        || v.starts_with("url(")
        || v.starts_with("{{")
}

/// `text` with everything from each `open` to its `close` blanked, newlines kept.
fn blank_between(text: &str, open: &str, close: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(start) = rest.find(open) {
        out.push_str(&rest[..start]);
        let end = rest[start..]
            .find(close)
            .map_or(rest.len(), |e| start + e + close.len());
        out.extend(
            rest[start..end]
                .chars()
                .map(|c| if c == '\n' { '\n' } else { ' ' }),
        );
        rest = &rest[end..];
    }
    out.push_str(rest);
    out
}

/// `js` with `//` and `/* */` comments blanked, strings kept, newlines kept.
fn blank_script_comments(js: &str) -> String {
    let b = js.as_bytes();
    let mut out = b.to_vec();
    let mut i = 0;
    let mut quote: Option<u8> = None;
    while i < b.len() {
        if let Some(q) = quote {
            if b[i] == b'\\' {
                i += 2;
                continue;
            }
            if b[i] == q {
                quote = None;
            }
            i += 1;
            continue;
        }
        match b[i] {
            b'\'' | b'"' | b'`' => quote = Some(b[i]),
            b'/' if b.get(i + 1) == Some(&b'/') => {
                while i < b.len() && b[i] != b'\n' {
                    out[i] = b' ';
                    i += 1;
                }
                continue;
            }
            b'/' if b.get(i + 1) == Some(&b'*') => {
                let end = js[i + 2..].find("*/").map_or(b.len(), |e| i + 2 + e + 2);
                for o in &mut out[i..end] {
                    if *o != b'\n' {
                        *o = b' ';
                    }
                }
                i = end;
                continue;
            }
            _ => {}
        }
        i += 1;
    }
    String::from_utf8(out).unwrap_or_default()
}

/// Each string literal in comment-blanked `js`, with where it starts.
fn string_literals(js: &str) -> Vec<(usize, &str)> {
    let b = js.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < b.len() {
        if matches!(b[i], b'\'' | b'"' | b'`') {
            let q = b[i];
            let mut j = i + 1;
            while j < b.len() && b[j] != q {
                j += if b[j] == b'\\' { 2 } else { 1 };
            }
            let end = j.min(b.len());
            out.push((i, &js[i + 1..end]));
            i = end + 1;
        } else {
            i += 1;
        }
    }
    out
}

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

    /// GO's sign-in callback page and an inline `<style>`; a style of custom
    /// properties (a renderer passing a bar's value) and a commented-out
    /// attribute pass.
    #[test]
    fn markup_that_writes_a_look_is_found() {
        let html = "<h1 style=\"color: #d33;\">Authorization Failed</h1>\n\
                    <div class=\"chart-bar\" style=\"--value:3;--most:9\"></div>\n\
                    <style>\n.a { color: red; }\n</style>\n\
                    <!-- <p style=\"color: red\"></p> -->\n\
                    <svg><path fill=\"#808080\" d=\"M0 0\"/><path fill=\"currentColor\"/><path stroke=\"var(--border)\"/></svg>\n\
                    <span style=\"{{ dynamic }}\"></span>\n";
        let found: Vec<(usize, Rule)> = markup(html).iter().map(|f| (f.line, f.rule)).collect();
        assert_eq!(
            found,
            vec![
                (1, Rule::InlineStyle),
                (3, Rule::StyleBlock),
                (7, Rule::SvgPaint)
            ]
        );
    }

    /// MNW's media player toggling `.style.display`, the embed player setting
    /// `.style.width`, markup built with a style; reading a style, comparing
    /// it, and setting a custom property pass.
    #[test]
    fn a_script_that_writes_a_look_is_found() {
        let js = "panel.style.display = 'none';\n\
                  fill.style.width = pct + '%';\n\
                  el.style.setProperty('--fill', pct + '%');\n\
                  if (el.style.display == 'none') {}\n\
                  const w = el.style.width;\n\
                  el.innerHTML = '<b style=\"color: red\">x</b>';\n\
                  el.setAttribute('style', 'color: red');\n\
                  // el.style.color = 'red';\n\
                  el.style.setProperty('color', 'red');\n\
                  el.style.cssText = 'color: red';\n";
        let lines: Vec<usize> = script(js).iter().map(|f| f.line).collect();
        assert_eq!(lines, vec![1, 2, 6, 7, 9, 10]);
    }

    fn rules(css_src: &str, ctx: &Context) -> Vec<(usize, Rule)> {
        css(css_src, ctx).iter().map(|f| (f.line, f.rule)).collect()
    }

    fn only(css_src: &str, rule: Rule) -> Vec<usize> {
        css(css_src, &Context::default())
            .iter()
            .filter(|f| f.rule == rule)
            .map(|f| f.line)
            .collect()
    }

    #[test]
    fn ids_round_trip() {
        for &r in Rule::ALL {
            assert_eq!(Rule::from_id(r.id()), Some(r));
        }
    }

    #[test]
    fn the_colour_rule_is_colour_literals() {
        let src = ".a { color: #fff; }\n.b { color: var(--content); }\n";
        assert_eq!(only(src, Rule::Colour), vec![1]);
        assert_eq!(crate::colour_literals(src).len(), 1);
    }

    /// MT's hover and placeholder fades (20-controls.css), and an animation's
    /// own frames, which are motion rather than an ink.
    #[test]
    fn opacity_as_an_ink_is_found_and_a_fade_is_not() {
        let src = "button.secondary:hover { opacity: 0.8; }\n\
                   input::placeholder { opacity: .5; }\n\
                   .hidden { opacity: 0; }\n\
                   .shown { opacity: 1; }\n\
                   @keyframes toast-in { from { opacity: 0.2; } to { opacity: 1; } }\n\
                   .half { opacity: 50%; }\n";
        assert_eq!(only(src, Rule::OpacityInk), vec![1, 2, 6]);
    }

    /// MNW 40-pages-misc.css:153 mixed --warning into the page for a banner;
    /// a mix of neutrals has no toned token to take instead.
    #[test]
    fn a_status_tint_mixed_by_hand_is_found() {
        let src = ".banner--warning { background: color-mix(in srgb, var(--warning) 14%, var(--surface-page)); }\n\
                   .inv:hover { background: color-mix(in oklch, var(--content) 85%, var(--surface-page)); }\n\
                   .ok { background: var(--warning-surface); color: var(--warning-text); }\n";
        assert_eq!(only(src, Rule::MixedTint), vec![1]);
    }

    /// MT's 1px borders and px padding, MNW's 1200px container, GO's 2px ring;
    /// tokens, zero, percentages, unitless numbers and a token's fallback pass.
    #[test]
    fn a_literal_length_the_scale_owns_is_found() {
        let src = ".a { border: 1px solid var(--border); }\n\
                   .b { padding: 6px 12px; }\n\
                   .c { max-width: 1200px; }\n\
                   .d { box-shadow: 0 0 0 2px var(--danger); }\n\
                   .e { border: var(--stroke-hairline) solid var(--border); margin: 0; }\n\
                   .f { padding: var(--gap-group) calc(2 * var(--step-snug)); }\n\
                   .g { width: 300px; line-height: 1.5; }\n\
                   .h { gap: var(--chart-gap, 2px); max-width: 100%; }\n\
                   .i { font-size: 0.875em; }\n\
                   .j { max-width: 100vw; padding-block: 1lh; }\n";
        assert_eq!(only(src, Rule::Length), vec![1, 2, 3, 4, 9]);
    }

    /// MT's 0.2s hovers and 0.3s toast; a token and zero pass.
    #[test]
    fn a_literal_duration_is_found() {
        let src = ".a { transition: opacity 0.2s ease; }\n\
                   .b { animation: toast-in 0.3s ease-out; }\n\
                   .c { transition: top var(--motion-fade) ease; }\n\
                   .d { transition-duration: 0s; }\n\
                   .e { transition: transform var(--timing-swift, 120ms) ease; }\n";
        assert_eq!(only(src, Rule::Duration), vec![1, 2]);
    }

    #[test]
    fn a_literal_face_is_found() {
        let src = ".a { font-family: system-ui, -apple-system, sans-serif; }\n\
                   .b { font-family: var(--font-sans); }\n\
                   .c { font-family: inherit; }\n";
        assert_eq!(only(src, Rule::Face), vec![1]);
    }

    /// GO's --border-width beside the generated --stroke-hairline is a parallel
    /// scale; restating a generated token by its own name is a shadow.
    #[test]
    fn restating_a_generated_token_is_a_shadow() {
        let ctx = Context::generated(&[":root { --stroke-hairline: 1px; --content: #000; }"]);
        let src = ":root { --content: #111; --border-width: 1px; }\n";
        let found = rules(src, &ctx);
        assert!(found.contains(&(1, Rule::TokenShadow)), "{found:?}");
        assert_eq!(
            found
                .iter()
                .filter(|(_, r)| *r == Rule::TokenShadow)
                .count(),
            1,
            "{found:?}"
        );
    }

    /// A token nothing defines draws nothing. A fallback is a host hook
    /// (quasi's --z-overlay) and passes; a name the sheet itself, a generated
    /// sheet or the renderer defines passes.
    #[test]
    fn a_token_nothing_defines_is_found() {
        let mut ctx = Context::generated(&[":root { --content: #000; }"]);
        ctx.set_at_runtime(["--value"]);
        let src = ":root { --local: 1rem; }\n\
                   .a { color: var(--contnet); }\n\
                   .b { color: var(--content); padding: var(--local); }\n\
                   .c { z-index: var(--z-overlay, 900); }\n\
                   .d { height: calc(var(--value) * 1%); }\n";
        assert_eq!(
            css(src, &ctx)
                .iter()
                .filter(|f| f.rule == Rule::UndefinedVar)
                .map(|f| f.line)
                .collect::<Vec<_>>(),
            vec![2]
        );
    }

    #[test]
    fn selectors_at_rules_and_comments_are_not_declarations() {
        let src = "/* padding: 6px; opacity: .5 */\n\
                   @media (hover: hover) and (pointer: fine) {\n\
                   .a:hover { color: var(--content); }\n\
                   }\n\
                   @layer reset, base;\n";
        let ctx = Context::generated(&[":root { --content: #000; }"]);
        assert_eq!(css(src, &ctx), vec![]);
    }

    #[test]
    fn one_declaration_can_break_two_rules() {
        let src = ".toast { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); }\n";
        assert_eq!(
            rules(src, &Context::default()),
            vec![(1, Rule::Colour), (1, Rule::Length)]
        );
    }
}