makeover-webview 0.130.0

The webview renderer for makeover-layout. Emits CSS, and is the one renderer that needs no palette: var() is the late binding, so resolution stays with the browser. With the build feature, writes a consumer's generated frontend files and checks the hand-written ones against them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! The breakpoint check: hand-written widths that have drifted from
//! `SizeClass` and the tuning widths.

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

use super::{Source, blank, frontend_css, js_files, line_of, read, shown};
use crate::build::rerun;
use crate::css_lex::{Lang, is_ident};
use makeover_geometry::SizeClass;

/// Fail the build if a hand-written breakpoint has drifted from [`SizeClass`].
///
/// Every pixel width named by a media or container query must be a
/// [`SizeClass`] boundary or one of the [`tuning`](Self::tuning) widths. A
/// container query is checked the same way as a media query:
/// `@container screen (width < 600px)` states a width.
///
/// A width on a [`SizeClass`] boundary must also be written as an edge of the
/// partition, exclusive on one side: `width < 600px` and `600px <= width`
/// pass, while `max-width: 600px`, `width <= 600px` and `width > 600px` fail,
/// because each also claims the point where the next class begins. A tuning
/// width may be written in either direction.
///
/// ```no_run
/// makeover_webview::build::drift::Breakpoints::in_frontend("frontend")
///     .tuning(&[1400])
///     .run();
/// ```
///
/// The generated stylesheets are scanned too, and pass: they take the
/// number from makeover-geometry.
#[derive(Debug, Clone)]
#[must_use = "a check does nothing until it is run"]
pub struct Breakpoints {
    source: Source,
    tuning: Vec<u16>,
}

impl Breakpoints {
    /// Every `.css` under `frontend/css` and every `.js` under `frontend/js`,
    /// recursively.
    pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
        Self {
            source: Source::Frontend(frontend.as_ref().to_path_buf()),
            tuning: Vec::new(),
        }
    }

    /// A named list of files rather than a tree.
    ///
    /// For a frontend with no directory a scan can point at. A stylesheet not
    /// on the list is not checked.
    ///
    /// A `.js` path is read as script and anything else as stylesheet.
    pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
        Self {
            source: Source::files(paths),
            tuning: Vec::new(),
        }
    }

    /// Widths inside a shell where something reflows without the shell
    /// changing: a dashboard dropping from three columns to two, a pane's width
    /// cap ending.
    ///
    /// A tuning width does not move when a size class does. Each entry
    /// carries a note beside it in the caller saying what it tunes.
    pub fn tuning(mut self, widths: &[u16]) -> Self {
        self.tuning.extend_from_slice(widths);
        self
    }

    /// Run the check. Emits `cargo::rerun-if-changed` for every file it read,
    /// and for the scanned directories.
    ///
    /// # Panics
    ///
    /// If a listed file cannot be read, including one that no longer exists;
    /// if any width is neither a size-class boundary nor a tuning width; or if
    /// a size-class boundary is written with an operator that straddles it
    /// (`max-width: 600px`, `width <= 600px`).
    pub fn run(&self) {
        match &self.source {
            Source::Frontend(frontend) => {
                let (_, mut files) = frontend_css(frontend);
                // A CSS-only frontend ships no `js/`; the scan is best-effort
                // and a missing directory is skipped rather than failing.
                let js = frontend.join("js");
                rerun(&js);
                if js.is_dir() {
                    files.extend(js_files(&js));
                }
                check_paths(&files, &self.tuning, Some(frontend));
            }
            Source::Files(paths) => check_paths(paths, &self.tuning, 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 edges = size_class_widths();
    let mut stale: Vec<String> = Vec::new();

    for path in paths {
        let raw = read(path);
        let name = shown(path, root);

        if path.extension().is_some_and(|x| x == "js") {
            // No declarations in JS, so any parenthesised width is a query.
            for (offset, bound) in js_widths(&blank(&raw, Lang::Js)) {
                if !bound.is_allowed(&allowed, &edges) {
                    stale.push(format!(
                        "  {name}:{}  ({})",
                        line_of(&raw, offset),
                        bound.width
                    ));
                }
            }
            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 = blank(&raw, Lang::Css);
        for (offset, condition) in media_conditions(&src) {
            for bound in media_bounds(condition) {
                if !bound.is_allowed(&allowed, &edges) {
                    stale.push(format!(
                        "  {name}:{}  @media{condition}  ({})",
                        line_of(&src, offset),
                        bound.width
                    ));
                }
            }
        }
    }

    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\
         Size classes are written in range syntax, `(width < 600px)`, because\n\
         `(max-width: 599px)` leaves 599.5px in no class. If a size class moved,\n\
         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 {
        rerun(path);
    }
}

/// Every width a hand-written media query is allowed to name.
///
/// Read out of [`SizeClass::media_condition`], so a bump in makeover-geometry
/// reaches the check.
fn allowed_widths(tuning_widths: &[u16]) -> Vec<u16> {
    let mut widths = size_class_widths();
    widths.extend_from_slice(tuning_widths);
    widths.sort_unstable();
    widths.dedup();
    widths
}

/// The widths at which [`SizeClass`] changes, read out of it rather than
/// typed: where one class ends and the next begins. A hand-written bound on
/// one of these edges owns the point the classes either side both claim, so
/// the direction it is written in matters; a tuning width has no such edge.
fn size_class_widths() -> Vec<u16> {
    let mut widths: Vec<u16> = SizeClass::all()
        .iter()
        .flat_map(|c| media_widths(&c.media_condition()))
        .map(|width| match width {
            Width::Px(px) => px,
            Width::Other(raw) => {
                panic!("makeover-geometry wrote a size-class width this check cannot read: {raw}")
            }
        })
        .collect();
    widths.sort_unstable();
    widths.dedup();
    widths
}

/// A width named in a media condition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Width {
    /// A whole number of CSS pixels: `600px`, or `37.5em` at the 16px a media
    /// query's `em` is measured against.
    Px(u16),
    /// Anything this cannot state in whole pixels: `599.98px`, `50vw`, `40ch`.
    /// Never a boundary, so always reported.
    Other(String),
}

/// A width named in a media condition, with the side of the comparison its
/// operator puts it on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Bound {
    width: Width,
    direction: Direction,
}

/// Whether a bound is one edge of a partition, as a size class is written, or
/// straddles the boundary point instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
    /// `width < N`, `width >= N`, `N <= width` or `N > width`: the classes
    /// either side still partition at `N`.
    Edge,
    /// `max-width: N`, `width <= N`, `N >= width`, `width > N` or `N < width`:
    /// the bound claims the point at `N` itself, which [`SizeClass`] owns.
    Straddles,
}

impl Bound {
    /// A bound passes when its number is allowed and, when that number is a
    /// size-class edge, it is written as an edge rather than a bound that
    /// straddles it. A tuning width has no class on either side to disagree
    /// with, so its direction is left alone.
    fn is_allowed(&self, allowed: &[u16], edges: &[u16]) -> bool {
        match &self.width {
            Width::Px(px) => {
                allowed.contains(px)
                    && !(edges.contains(px) && self.direction == Direction::Straddles)
            }
            Width::Other(_) => false,
        }
    }
}

impl std::fmt::Display for Width {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Px(px) => write!(f, "{px}px"),
            Self::Other(raw) => f.write_str(raw),
        }
    }
}

/// Every width in a media condition, in the order it appears.
pub(super) fn media_widths(condition: &str) -> Vec<Width> {
    media_bounds(condition)
        .into_iter()
        .map(|bound| bound.width)
        .collect()
}

/// Every width in a media condition with the direction its operator gives it,
/// in the order it appears.
///
/// Reads both spellings of a width feature: `(max-width: 599px)` and range
/// syntax, `(width < 600px)` or `(600px <= width < 840px)`, which is what
/// [`SizeClass::media_condition`] writes. A feature group is any `( ... )`
/// naming `width` and not `device-width`, and every length inside it counts,
/// including one nested in a function like `calc(...)`. Units are read rather
/// than assumed: `48em` is 768px, not 48.
fn media_bounds(condition: &str) -> Vec<Bound> {
    width_groups(condition)
        .into_iter()
        .flat_map(|(_, group)| lengths(group))
        .collect()
}

/// `(byte offset, inner text)` of every parenthesised group that names a width
/// feature. A nested group (`calc(...)`) stays inside its outer group's text,
/// so a width buried in a function is read rather than skipped.
fn width_groups(src: &str) -> Vec<(usize, &str)> {
    let mut out: Vec<(usize, &str)> = Vec::new();
    let mut stack: Vec<usize> = Vec::new();
    for (i, c) in src.char_indices() {
        match c {
            '(' => stack.push(i),
            ')' => {
                if let Some(start) = stack.pop() {
                    let inner = &src[start + 1..i];
                    // A group enclosing one already read, as in
                    // `matchMedia('(width < 600px)')`, adds nothing: the inner
                    // group is the feature. This keeps nesting for the sake of
                    // reading `calc(...)`, without reading a call around it.
                    let encloses_read = out.iter().any(|&(inner_start, _)| inner_start > start);
                    if names_width(inner) && !encloses_read {
                        out.push((start, inner));
                    }
                }
            }
            _ => {}
        }
    }
    out
}

/// Whether a feature group is about the viewport's width: `width`,
/// `min-width` or `max-width` as a whole word, not `device-width` and not a
/// longer identifier that ends in it.
fn names_width(inner: &str) -> bool {
    width_token_at(inner).is_some()
}

/// Byte offset of the `width` in a feature group: `width`, `min-width` or
/// `max-width` as a whole word, not `device-width` and not a longer
/// identifier that ends in it.
fn width_token_at(inner: &str) -> Option<usize> {
    inner.match_indices("width").find_map(|(at, _)| {
        let before = &inner[..at];
        let prefix_ok = before.is_empty()
            || before.ends_with("min-")
            || before.ends_with("max-")
            || before.chars().next_back().is_some_and(|c| !is_ident(c));
        let after = inner[at + "width".len()..].chars().next();
        (prefix_ok && after.is_none_or(|c| !is_ident(c))).then_some(at)
    })
}

/// Every `<number><unit>` in a feature group, each with the direction its
/// operator gives it.
fn lengths(group: &str) -> Vec<Bound> {
    let bytes = group.as_bytes();
    let width_at = width_token_at(group);
    let mut out = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        // A number may open with a digit or with a leading dot (`.5em`); it
        // must not continue an identifier or a preceding number.
        let prev_ok = i == 0
            || !(bytes[i - 1].is_ascii_alphanumeric()
                || bytes[i - 1] == b'-'
                || bytes[i - 1] == b'.');
        let starts_number = prev_ok
            && (bytes[i].is_ascii_digit()
                || (bytes[i] == b'.' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit)));
        if !starts_number {
            i += 1;
            continue;
        }
        let start = i;
        while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
            i += 1;
        }
        let number = &group[start..i];
        let unit_start = i;
        while i < bytes.len() && bytes[i].is_ascii_alphabetic() {
            i += 1;
        }
        let unit = &group[unit_start..i];
        if unit.is_empty() {
            continue;
        }
        let raw = &group[start..i];
        let scale = match unit {
            "px" => Some(1.0),
            "em" | "rem" => Some(16.0),
            _ => None,
        };
        let px = scale.and_then(|scale| number.parse::<f64>().ok().map(|n| n * scale));
        let width = match px {
            Some(px) if px.fract() == 0.0 && px >= 0.0 && px <= f64::from(u16::MAX) => {
                // Whole and in range, checked above.
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                Width::Px(px as u16)
            }
            _ => Width::Other(raw.to_string()),
        };
        out.push(Bound {
            width,
            direction: direction_of(group, start, i, width_at),
        });
    }
    out
}

/// Which side of `width` a number sits on, and whether its operator makes the
/// bound an [`Edge`](Direction::Edge) of the partition or one that
/// [`straddles`](Direction::Straddles) it.
///
/// The classes partition the viewport, so the bound between two of them is
/// exclusive on one side and inclusive on the other: `width < 600px` is an
/// edge, and so is `600px <= width`. `max-width: 600px` is not, because it
/// also matches the width where `Medium` begins.
fn direction_of(group: &str, start: usize, end: usize, width_at: Option<usize>) -> Direction {
    let Some(width_at) = width_at else {
        return Direction::Edge;
    };
    let width_end = width_at + "width".len();
    if start >= width_end {
        // The number is to the right of `width`.
        let op = &group[width_end..start];
        if op.contains("<=") {
            Direction::Straddles
        } else if op.contains(">=") || op.contains('<') {
            Direction::Edge
        } else if op.contains('>') {
            Direction::Straddles
        } else if group[..width_at].ends_with("min-") {
            Direction::Edge
        } else {
            // `max-width: N` and a bare `width: N` both claim `N` itself.
            Direction::Straddles
        }
    } else {
        // The number is to the left of `width`.
        let op = &group[end..width_at];
        if op.contains("<=") || op.contains('>') {
            Direction::Edge
        } else {
            Direction::Straddles
        }
    }
}

/// `(byte offset of the at-keyword, the condition text)`.
///
/// Reads the at-rules that carry a width condition: `@media` and `@container`
/// (case-insensitive, terminated by `{`), and `@custom-media` and `@import`,
/// which end at `;`. A container name ahead of its condition (`@container
/// screen (width < 600px)`) lands in the condition text, and [`width_groups`]
/// skips it, reading only the parenthesised width feature.
pub(super) fn media_conditions(css: &str) -> Vec<(usize, &str)> {
    let lower = css.to_ascii_lowercase();
    let mut out = Vec::new();
    let mut at = 0;
    while let Some(rel) = lower[at..].find('@') {
        let start = at + rel;
        let kw_start = start + 1;
        let kw_end = css[kw_start..]
            .find(|c: char| !c.is_ascii_alphanumeric() && c != '-')
            .map_or(css.len(), |i| kw_start + i);
        let terminator = match &lower[kw_start..kw_end] {
            "media" | "container" => '{',
            "custom-media" | "import" => ';',
            _ => {
                at = start + 1;
                continue;
            }
        };
        match css[kw_end..].find(terminator) {
            Some(j) => {
                out.push((start, &css[kw_end..kw_end + j]));
                at = kw_end + j + 1;
            }
            None => break,
        }
    }
    out
}

/// `(byte offset, bound)` for every width feature in a JS source.
///
/// Only a parenthesised group is read: a media condition is always
/// parenthesised and a CSS declaration never is, so `'max-width: 320px'` in
/// an inline-style string is not a breakpoint. Range syntax,
/// `(width < 600px)`, is read the same way as in a stylesheet.
pub(super) fn js_widths(src: &str) -> Vec<(usize, Bound)> {
    width_groups(src)
        .into_iter()
        .filter(|(_, group)| is_feature(group))
        .flat_map(|(offset, group)| lengths(group).into_iter().map(move |b| (offset, b)))
        .collect()
}

/// Whether a parenthesised group in script is a media feature rather than a
/// call's arguments: `(max-width: 600px)` or `(width < 600px)`, not
/// `Math.max(width, 600)`.
fn is_feature(group: &str) -> bool {
    let group = group.trim();
    let colon = ["min-width", "max-width", "width"].iter().any(|name| {
        group
            .strip_prefix(name)
            .is_some_and(|rest| rest.trim_start().starts_with(':'))
    });
    colon || group.contains(['<', '>'])
}