makeover 5.7.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
//! Finding colour written into a stylesheet rather than taken from a token.
//!
//! A colour an app writes itself is a colour no floor reaches: makeover lifts
//! its own inks until they read on every ground, and a literal is whatever it
//! was typed as, under every theme. A build script runs this over the sheets
//! people edit and refuses what it finds.

/// A colour written as a literal: the line it is on, counted from 1, and the
/// declaration that holds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColourLiteral {
    pub line: usize,
    pub declaration: String,
}

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

/// Every declaration in `css` whose value writes a colour: a hex colour, a
/// colour function (`rgb()`, `oklch()` and the rest), or a named colour in a
/// property that takes one.
///
/// A mix or a relative colour built only from tokens has no literal in it and
/// passes, and so do `transparent`, `currentColor` and the system colours,
/// which name no colour of their own. Selectors, comments, strings and `url()`
/// are not read, so `#add` as an id or a hex digit in a data URI is not a
/// finding.
pub fn colour_literals(css: &str) -> Vec<ColourLiteral> {
    let text = blank_unread(css);
    let mut found = Vec::new();
    let mut start = 0;
    for (at, c) in text.char_indices() {
        if !matches!(c, '{' | '}' | ';') {
            continue;
        }
        // A segment that a `{` closes is a selector or an at-rule's prelude.
        if c != '{' {
            check_declaration(&text, start, at, &mut found);
        }
        start = at + 1;
    }
    check_declaration(&text, start, text.len(), &mut found);
    found
}

/// Records `text[start..end]` when it is a declaration whose value writes a
/// colour. Quoted from `text`, so a comment beside it is not part of the quote.
fn check_declaration(text: &str, start: usize, end: usize, found: &mut Vec<ColourLiteral>) {
    let segment = &text[start..end];
    let Some(colon) = segment.find(':') else {
        return;
    };
    let property = segment[..colon].trim().to_ascii_lowercase();
    if property.is_empty() || property.contains(char::is_whitespace) {
        return;
    }
    let value = &segment[colon + 1..];
    if !writes_colour(&property, value) {
        return;
    }
    let lead = segment.len() - segment.trim_start().len();
    let line = text[..start + lead].matches('\n').count() + 1;
    let declaration = segment.split_whitespace().collect::<Vec<_>>().join(" ");
    found.push(ColourLiteral { line, declaration });
}

/// Whether a declaration of `property` (lowercase) with `value` writes a colour.
pub(crate) fn writes_colour(property: &str, value: &str) -> bool {
    let takes_named = property.starts_with("--")
        || COLOUR_PROPERTIES
            .iter()
            .any(|p| property == *p || property.starts_with(&format!("{p}-")));
    has_hex(value) || has_colour_function(value) || takes_named && has_named(value)
}

/// `css` with comments, strings and `url(...)` blanked to spaces, newlines kept,
/// so every byte offset and line number still matches the source.
pub(crate) fn blank_unread(css: &str) -> String {
    let bytes = css.as_bytes();
    let mut out = bytes.to_vec();
    let mut i = 0;
    let blank = |out: &mut Vec<u8>, from: usize, to: usize| {
        for b in &mut out[from..to] {
            if *b != b'\n' {
                *b = b' ';
            }
        }
    };
    while i < bytes.len() {
        if bytes[i..].starts_with(b"/*") {
            let end = css[i + 2..]
                .find("*/")
                .map_or(bytes.len(), |e| i + 2 + e + 2);
            blank(&mut out, i, end);
            i = end;
        } else if bytes[i] == b'"' || bytes[i] == b'\'' {
            let quote = bytes[i];
            let mut j = i + 1;
            while j < bytes.len() && bytes[j] != quote {
                j += if bytes[j] == b'\\' { 2 } else { 1 };
            }
            let end = (j + 1).min(bytes.len());
            blank(&mut out, i, end);
            i = end;
        } else if bytes[i..].len() >= 4 && bytes[i..i + 4].eq_ignore_ascii_case(b"url(") {
            let end = css[i..].find(')').map_or(bytes.len(), |e| i + e + 1);
            blank(&mut out, i, end);
            i = end;
        } else {
            i += 1;
        }
    }
    // Only ASCII bytes were replaced, and only with ASCII, so it is still UTF-8.
    String::from_utf8(out).unwrap_or_default()
}

/// Properties whose value a named colour can be, by stem: `border` covers
/// `border-left-color` and the shorthand alike.
const COLOUR_PROPERTIES: &[&str] = &[
    "color",
    "background",
    "border",
    "outline",
    "box-shadow",
    "text-shadow",
    "text-decoration",
    "text-emphasis",
    "column-rule",
    "fill",
    "stroke",
    "caret-color",
    "accent-color",
    "scrollbar-color",
    "stop-color",
    "flood-color",
    "lighting-color",
];

fn has_hex(value: &str) -> bool {
    let bytes = value.as_bytes();
    bytes.iter().enumerate().any(|(i, &b)| {
        if b != b'#' {
            return false;
        }
        let digits = bytes[i + 1..]
            .iter()
            .take_while(|c| c.is_ascii_alphanumeric() || **c == b'-' || **c == b'_')
            .count();
        matches!(digits, 3 | 4 | 6 | 8)
            && bytes[i + 1..i + 1 + digits]
                .iter()
                .all(u8::is_ascii_hexdigit)
    })
}

/// The functions that write a colour from channels.
const COLOUR_FUNCTIONS: &[&str] = &[
    "rgb", "rgba", "hsl", "hsla", "hwb", "lab", "lch", "oklab", "oklch", "color",
];

fn has_colour_function(value: &str) -> bool {
    words(value).any(|(word, next)| {
        next == Some('(')
            && COLOUR_FUNCTIONS
                .iter()
                .any(|f| word.eq_ignore_ascii_case(f))
    })
}

fn has_named(value: &str) -> bool {
    words(value).any(|(word, next)| {
        next != Some('(')
            && NAMED_COLOURS
                .binary_search(&word.to_ascii_lowercase().as_str())
                .is_ok()
    })
}

/// Each identifier in `value` with the character after it. A custom property's
/// name is one identifier, `--content-on-black`, so a colour word inside it is
/// not read as a colour.
fn words(value: &str) -> impl Iterator<Item = (&str, Option<char>)> {
    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_';
    let mut rest = value;
    std::iter::from_fn(move || {
        let start = rest.find(is_ident)?;
        let tail = &rest[start..];
        let len = tail.find(|c: char| !is_ident(c)).unwrap_or(tail.len());
        let word = &tail[..len];
        let next = tail[len..].chars().next();
        rest = &tail[len..];
        Some((word, next))
    })
    .filter(|(word, _)| !word.starts_with("--") && !word.starts_with(|c: char| c.is_ascii_digit()))
}

/// The CSS named colours, sorted. `transparent`, `currentcolor` and the system
/// colours are not here: they name no colour of their own.
const NAMED_COLOURS: &[&str] = &[
    "aliceblue",
    "antiquewhite",
    "aqua",
    "aquamarine",
    "azure",
    "beige",
    "bisque",
    "black",
    "blanchedalmond",
    "blue",
    "blueviolet",
    "brown",
    "burlywood",
    "cadetblue",
    "chartreuse",
    "chocolate",
    "coral",
    "cornflowerblue",
    "cornsilk",
    "crimson",
    "cyan",
    "darkblue",
    "darkcyan",
    "darkgoldenrod",
    "darkgray",
    "darkgreen",
    "darkgrey",
    "darkkhaki",
    "darkmagenta",
    "darkolivegreen",
    "darkorange",
    "darkorchid",
    "darkred",
    "darksalmon",
    "darkseagreen",
    "darkslateblue",
    "darkslategray",
    "darkslategrey",
    "darkturquoise",
    "darkviolet",
    "deeppink",
    "deepskyblue",
    "dimgray",
    "dimgrey",
    "dodgerblue",
    "firebrick",
    "floralwhite",
    "forestgreen",
    "fuchsia",
    "gainsboro",
    "ghostwhite",
    "gold",
    "goldenrod",
    "gray",
    "green",
    "greenyellow",
    "grey",
    "honeydew",
    "hotpink",
    "indianred",
    "indigo",
    "ivory",
    "khaki",
    "lavender",
    "lavenderblush",
    "lawngreen",
    "lemonchiffon",
    "lightblue",
    "lightcoral",
    "lightcyan",
    "lightgoldenrodyellow",
    "lightgray",
    "lightgreen",
    "lightgrey",
    "lightpink",
    "lightsalmon",
    "lightseagreen",
    "lightskyblue",
    "lightslategray",
    "lightslategrey",
    "lightsteelblue",
    "lightyellow",
    "lime",
    "limegreen",
    "linen",
    "magenta",
    "maroon",
    "mediumaquamarine",
    "mediumblue",
    "mediumorchid",
    "mediumpurple",
    "mediumseagreen",
    "mediumslateblue",
    "mediumspringgreen",
    "mediumturquoise",
    "mediumvioletred",
    "midnightblue",
    "mintcream",
    "mistyrose",
    "moccasin",
    "navajowhite",
    "navy",
    "oldlace",
    "olive",
    "olivedrab",
    "orange",
    "orangered",
    "orchid",
    "palegoldenrod",
    "palegreen",
    "paleturquoise",
    "palevioletred",
    "papayawhip",
    "peachpuff",
    "peru",
    "pink",
    "plum",
    "powderblue",
    "purple",
    "rebeccapurple",
    "red",
    "rosybrown",
    "royalblue",
    "saddlebrown",
    "salmon",
    "sandybrown",
    "seagreen",
    "seashell",
    "sienna",
    "silver",
    "skyblue",
    "slateblue",
    "slategray",
    "slategrey",
    "snow",
    "springgreen",
    "steelblue",
    "tan",
    "teal",
    "thistle",
    "tomato",
    "turquoise",
    "violet",
    "wheat",
    "white",
    "whitesmoke",
    "yellow",
    "yellowgreen",
];

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

    fn lines(css: &str) -> Vec<usize> {
        colour_literals(css).iter().map(|f| f.line).collect()
    }

    #[test]
    fn the_named_colours_are_sorted_for_the_search() {
        assert!(NAMED_COLOURS.windows(2).all(|w| w[0] < w[1]));
    }

    #[test]
    fn each_way_of_writing_a_colour_is_found() {
        let css = ".a { color: #fff; }\n\
                   .b { background: rgba(0, 0, 0, 0.5); }\n\
                   .c { border-left: 1px solid white; }\n\
                   :root { --x: oklch(0.5 0.1 200); }\n\
                   .d { box-shadow: 0 0 0 1px color-mix(in oklch, var(--danger) 90%, black); }\n";
        assert_eq!(lines(css), vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn colour_built_from_tokens_passes() {
        let css = ".a { color: var(--danger-text); }\n\
                   .b { background: color-mix(in oklch, var(--content) 85%, var(--surface-page)); }\n\
                   .c { border-color: transparent; outline-color: currentColor; }\n\
                   .d { background: Canvas; }\n\
                   .e { background: oklch(from var(--action) l c h); }\n";
        // A relative colour is a function call, and its channels are the
        // token's, but the function is where an author can write a literal.
        assert_eq!(lines(css), vec![5]);
    }

    #[test]
    fn selectors_comments_strings_and_urls_are_not_read() {
        let css = "/* #fff and white are fine in prose */\n\
                   #add, #bad > .face { white-space: nowrap; }\n\
                   .a::before { content: \"#fff\"; }\n\
                   .b { background-image: url(data:image/svg+xml,%23fff); mask: url(#fade); }\n\
                   .c { font-family: \"White Rabbit\", Georgia; }\n\
                   .d { transition: color var(--timing-fast); }\n";
        assert!(
            colour_literals(css).is_empty(),
            "{:?}",
            colour_literals(css)
        );
    }

    #[test]
    fn a_comment_before_a_declaration_is_not_quoted() {
        let found = colour_literals(":root {\n  /* the page */\n  --surface-page: #ddd6c9;\n}");
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].line, 3);
        assert_eq!(found[0].declaration, "--surface-page: #ddd6c9");
    }

    #[test]
    fn a_colour_word_inside_a_token_name_is_not_a_colour() {
        assert_eq!(
            colour_literals(".a { color: var(--content-on-black); }"),
            Vec::new()
        );
    }

    #[test]
    fn the_finding_quotes_its_declaration_and_line() {
        let found = colour_literals("\n\n.a {\n    color:   #c0392b;\n}\n");
        assert_eq!(
            found,
            vec![ColourLiteral {
                line: 4,
                declaration: "color: #c0392b".to_owned()
            }]
        );
    }
}