Skip to main content

makeover_webview/build/drift/
breakpoints.rs

1//! The breakpoint check: hand-written widths that have drifted from
2//! `SizeClass` and the tuning widths.
3
4use std::path::{Path, PathBuf};
5
6use super::{Source, blank, frontend_css, js_files, line_of, read, shown};
7use crate::build::rerun;
8use crate::css_lex::{Lang, is_ident};
9use makeover_geometry::SizeClass;
10
11/// Fail the build if a hand-written breakpoint has drifted from [`SizeClass`].
12///
13/// Every pixel width named by a media or container query must be a
14/// [`SizeClass`] boundary or one of the [`tuning`](Self::tuning) widths. A
15/// container query is checked the same way as a media query:
16/// `@container screen (width < 600px)` states a width.
17///
18/// A width on a [`SizeClass`] boundary must also be written as an edge of the
19/// partition, exclusive on one side: `width < 600px` and `600px <= width`
20/// pass, while `max-width: 600px`, `width <= 600px` and `width > 600px` fail,
21/// because each also claims the point where the next class begins. A tuning
22/// width may be written in either direction.
23///
24/// ```no_run
25/// makeover_webview::build::drift::Breakpoints::in_frontend("frontend")
26///     .tuning(&[1400])
27///     .run();
28/// ```
29///
30/// The generated stylesheets are scanned too, and pass: they take the
31/// number from makeover-geometry.
32#[derive(Debug, Clone)]
33#[must_use = "a check does nothing until it is run"]
34pub struct Breakpoints {
35    source: Source,
36    tuning: Vec<u16>,
37}
38
39impl Breakpoints {
40    /// Every `.css` under `frontend/css` and every `.js` under `frontend/js`,
41    /// recursively.
42    pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
43        Self {
44            source: Source::Frontend(frontend.as_ref().to_path_buf()),
45            tuning: Vec::new(),
46        }
47    }
48
49    /// A named list of files rather than a tree.
50    ///
51    /// For a frontend with no directory a scan can point at. A stylesheet not
52    /// on the list is not checked.
53    ///
54    /// A `.js` path is read as script and anything else as stylesheet.
55    pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
56        Self {
57            source: Source::files(paths),
58            tuning: Vec::new(),
59        }
60    }
61
62    /// Widths inside a shell where something reflows without the shell
63    /// changing: a dashboard dropping from three columns to two, a pane's width
64    /// cap ending.
65    ///
66    /// A tuning width does not move when a size class does. Each entry
67    /// carries a note beside it in the caller saying what it tunes.
68    pub fn tuning(mut self, widths: &[u16]) -> Self {
69        self.tuning.extend_from_slice(widths);
70        self
71    }
72
73    /// Run the check. Emits `cargo::rerun-if-changed` for every file it read,
74    /// and for the scanned directories.
75    ///
76    /// # Panics
77    ///
78    /// If a listed file cannot be read, including one that no longer exists;
79    /// if any width is neither a size-class boundary nor a tuning width; or if
80    /// a size-class boundary is written with an operator that straddles it
81    /// (`max-width: 600px`, `width <= 600px`).
82    pub fn run(&self) {
83        match &self.source {
84            Source::Frontend(frontend) => {
85                let (_, mut files) = frontend_css(frontend);
86                // A CSS-only frontend ships no `js/`; the scan is best-effort
87                // and a missing directory is skipped rather than failing.
88                let js = frontend.join("js");
89                rerun(&js);
90                if js.is_dir() {
91                    files.extend(js_files(&js));
92                }
93                check_paths(&files, &self.tuning, Some(frontend));
94            }
95            Source::Files(paths) => check_paths(paths, &self.tuning, None),
96        }
97    }
98}
99
100/// The check itself. `root`, when given, is stripped from reported paths.
101fn check_paths(paths: &[PathBuf], tuning_widths: &[u16], root: Option<&Path>) {
102    let allowed = allowed_widths(tuning_widths);
103    let edges = size_class_widths();
104    let mut stale: Vec<String> = Vec::new();
105
106    for path in paths {
107        let raw = read(path);
108        let name = shown(path, root);
109
110        if path.extension().is_some_and(|x| x == "js") {
111            // No declarations in JS, so any parenthesised width is a query.
112            for (offset, bound) in js_widths(&blank(&raw, Lang::Js)) {
113                if !bound.is_allowed(&allowed, &edges) {
114                    stale.push(format!(
115                        "  {name}:{}  ({})",
116                        line_of(&raw, offset),
117                        bound.width
118                    ));
119                }
120            }
121            continue;
122        }
123
124        // Comments first: a note about a breakpoint that used to be here is
125        // prose, not a rule, and should not fail a build.
126        let src = blank(&raw, Lang::Css);
127        for (offset, condition) in media_conditions(&src) {
128            for bound in media_bounds(condition) {
129                if !bound.is_allowed(&allowed, &edges) {
130                    stale.push(format!(
131                        "  {name}:{}  @media{condition}  ({})",
132                        line_of(&src, offset),
133                        bound.width
134                    ));
135                }
136            }
137        }
138    }
139
140    assert!(
141        stale.is_empty(),
142        "hand-written breakpoints disagree with makeover_geometry::SizeClass.\n\n\
143         Allowed: {allowed:?}\n\
144         ({:?} come from SizeClass; {tuning_widths:?} were passed as tuning widths.)\n\n\
145         Stale:\n{}\n\n\
146         Size classes are written in range syntax, `(width < 600px)`, because\n\
147         `(max-width: 599px)` leaves 599.5px in no class. If a size class moved,\n\
148         update these to match. If one of these is a new\n\
149         tuning width inside the wide shell rather than a shell boundary, add it\n\
150         to the caller's tuning list with a note saying what it tunes.\n\n\
151         Best of all, make the rule dimensional so it needs no threshold: a grid\n\
152         wants repeat(auto-fit, minmax(<content floor>, 1fr)) and a size wants\n\
153         clamp(). A threshold is for what appears and disappears.",
154        allowed
155            .iter()
156            .filter(|px| !tuning_widths.contains(px))
157            .collect::<Vec<_>>(),
158        stale.join("\n")
159    );
160
161    for path in paths {
162        rerun(path);
163    }
164}
165
166/// Every width a hand-written media query is allowed to name.
167///
168/// Read out of [`SizeClass::media_condition`], so a bump in makeover-geometry
169/// reaches the check.
170fn allowed_widths(tuning_widths: &[u16]) -> Vec<u16> {
171    let mut widths = size_class_widths();
172    widths.extend_from_slice(tuning_widths);
173    widths.sort_unstable();
174    widths.dedup();
175    widths
176}
177
178/// The widths at which [`SizeClass`] changes, read out of it rather than
179/// typed: where one class ends and the next begins. A hand-written bound on
180/// one of these edges owns the point the classes either side both claim, so
181/// the direction it is written in matters; a tuning width has no such edge.
182fn size_class_widths() -> Vec<u16> {
183    let mut widths: Vec<u16> = SizeClass::all()
184        .iter()
185        .flat_map(|c| media_widths(&c.media_condition()))
186        .map(|width| match width {
187            Width::Px(px) => px,
188            Width::Other(raw) => {
189                panic!("makeover-geometry wrote a size-class width this check cannot read: {raw}")
190            }
191        })
192        .collect();
193    widths.sort_unstable();
194    widths.dedup();
195    widths
196}
197
198/// A width named in a media condition.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub(super) enum Width {
201    /// A whole number of CSS pixels: `600px`, or `37.5em` at the 16px a media
202    /// query's `em` is measured against.
203    Px(u16),
204    /// Anything this cannot state in whole pixels: `599.98px`, `50vw`, `40ch`.
205    /// Never a boundary, so always reported.
206    Other(String),
207}
208
209/// A width named in a media condition, with the side of the comparison its
210/// operator puts it on.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub(super) struct Bound {
213    width: Width,
214    direction: Direction,
215}
216
217/// Whether a bound is one edge of a partition, as a size class is written, or
218/// straddles the boundary point instead.
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220enum Direction {
221    /// `width < N`, `width >= N`, `N <= width` or `N > width`: the classes
222    /// either side still partition at `N`.
223    Edge,
224    /// `max-width: N`, `width <= N`, `N >= width`, `width > N` or `N < width`:
225    /// the bound claims the point at `N` itself, which [`SizeClass`] owns.
226    Straddles,
227}
228
229impl Bound {
230    /// A bound passes when its number is allowed and, when that number is a
231    /// size-class edge, it is written as an edge rather than a bound that
232    /// straddles it. A tuning width has no class on either side to disagree
233    /// with, so its direction is left alone.
234    fn is_allowed(&self, allowed: &[u16], edges: &[u16]) -> bool {
235        match &self.width {
236            Width::Px(px) => {
237                allowed.contains(px)
238                    && !(edges.contains(px) && self.direction == Direction::Straddles)
239            }
240            Width::Other(_) => false,
241        }
242    }
243}
244
245impl std::fmt::Display for Width {
246    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247        match self {
248            Self::Px(px) => write!(f, "{px}px"),
249            Self::Other(raw) => f.write_str(raw),
250        }
251    }
252}
253
254/// Every width in a media condition, in the order it appears.
255pub(super) fn media_widths(condition: &str) -> Vec<Width> {
256    media_bounds(condition)
257        .into_iter()
258        .map(|bound| bound.width)
259        .collect()
260}
261
262/// Every width in a media condition with the direction its operator gives it,
263/// in the order it appears.
264///
265/// Reads both spellings of a width feature: `(max-width: 599px)` and range
266/// syntax, `(width < 600px)` or `(600px <= width < 840px)`, which is what
267/// [`SizeClass::media_condition`] writes. A feature group is any `( ... )`
268/// naming `width` and not `device-width`, and every length inside it counts,
269/// including one nested in a function like `calc(...)`. Units are read rather
270/// than assumed: `48em` is 768px, not 48.
271fn media_bounds(condition: &str) -> Vec<Bound> {
272    width_groups(condition)
273        .into_iter()
274        .flat_map(|(_, group)| lengths(group))
275        .collect()
276}
277
278/// `(byte offset, inner text)` of every parenthesised group that names a width
279/// feature. A nested group (`calc(...)`) stays inside its outer group's text,
280/// so a width buried in a function is read rather than skipped.
281fn width_groups(src: &str) -> Vec<(usize, &str)> {
282    let mut out: Vec<(usize, &str)> = Vec::new();
283    let mut stack: Vec<usize> = Vec::new();
284    for (i, c) in src.char_indices() {
285        match c {
286            '(' => stack.push(i),
287            ')' => {
288                if let Some(start) = stack.pop() {
289                    let inner = &src[start + 1..i];
290                    // A group enclosing one already read, as in
291                    // `matchMedia('(width < 600px)')`, adds nothing: the inner
292                    // group is the feature. This keeps nesting for the sake of
293                    // reading `calc(...)`, without reading a call around it.
294                    let encloses_read = out.iter().any(|&(inner_start, _)| inner_start > start);
295                    if names_width(inner) && !encloses_read {
296                        out.push((start, inner));
297                    }
298                }
299            }
300            _ => {}
301        }
302    }
303    out
304}
305
306/// Whether a feature group is about the viewport's width: `width`,
307/// `min-width` or `max-width` as a whole word, not `device-width` and not a
308/// longer identifier that ends in it.
309fn names_width(inner: &str) -> bool {
310    width_token_at(inner).is_some()
311}
312
313/// Byte offset of the `width` in a feature group: `width`, `min-width` or
314/// `max-width` as a whole word, not `device-width` and not a longer
315/// identifier that ends in it.
316fn width_token_at(inner: &str) -> Option<usize> {
317    inner.match_indices("width").find_map(|(at, _)| {
318        let before = &inner[..at];
319        let prefix_ok = before.is_empty()
320            || before.ends_with("min-")
321            || before.ends_with("max-")
322            || before.chars().next_back().is_some_and(|c| !is_ident(c));
323        let after = inner[at + "width".len()..].chars().next();
324        (prefix_ok && after.is_none_or(|c| !is_ident(c))).then_some(at)
325    })
326}
327
328/// Every `<number><unit>` in a feature group, each with the direction its
329/// operator gives it.
330fn lengths(group: &str) -> Vec<Bound> {
331    let bytes = group.as_bytes();
332    let width_at = width_token_at(group);
333    let mut out = Vec::new();
334    let mut i = 0;
335    while i < bytes.len() {
336        // A number may open with a digit or with a leading dot (`.5em`); it
337        // must not continue an identifier or a preceding number.
338        let prev_ok = i == 0
339            || !(bytes[i - 1].is_ascii_alphanumeric()
340                || bytes[i - 1] == b'-'
341                || bytes[i - 1] == b'.');
342        let starts_number = prev_ok
343            && (bytes[i].is_ascii_digit()
344                || (bytes[i] == b'.' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit)));
345        if !starts_number {
346            i += 1;
347            continue;
348        }
349        let start = i;
350        while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
351            i += 1;
352        }
353        let number = &group[start..i];
354        let unit_start = i;
355        while i < bytes.len() && bytes[i].is_ascii_alphabetic() {
356            i += 1;
357        }
358        let unit = &group[unit_start..i];
359        if unit.is_empty() {
360            continue;
361        }
362        let raw = &group[start..i];
363        let scale = match unit {
364            "px" => Some(1.0),
365            "em" | "rem" => Some(16.0),
366            _ => None,
367        };
368        let px = scale.and_then(|scale| number.parse::<f64>().ok().map(|n| n * scale));
369        let width = match px {
370            Some(px) if px.fract() == 0.0 && px >= 0.0 && px <= f64::from(u16::MAX) => {
371                // Whole and in range, checked above.
372                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
373                Width::Px(px as u16)
374            }
375            _ => Width::Other(raw.to_string()),
376        };
377        out.push(Bound {
378            width,
379            direction: direction_of(group, start, i, width_at),
380        });
381    }
382    out
383}
384
385/// Which side of `width` a number sits on, and whether its operator makes the
386/// bound an [`Edge`](Direction::Edge) of the partition or one that
387/// [`straddles`](Direction::Straddles) it.
388///
389/// The classes partition the viewport, so the bound between two of them is
390/// exclusive on one side and inclusive on the other: `width < 600px` is an
391/// edge, and so is `600px <= width`. `max-width: 600px` is not, because it
392/// also matches the width where `Medium` begins.
393fn direction_of(group: &str, start: usize, end: usize, width_at: Option<usize>) -> Direction {
394    let Some(width_at) = width_at else {
395        return Direction::Edge;
396    };
397    let width_end = width_at + "width".len();
398    if start >= width_end {
399        // The number is to the right of `width`.
400        let op = &group[width_end..start];
401        if op.contains("<=") {
402            Direction::Straddles
403        } else if op.contains(">=") || op.contains('<') {
404            Direction::Edge
405        } else if op.contains('>') {
406            Direction::Straddles
407        } else if group[..width_at].ends_with("min-") {
408            Direction::Edge
409        } else {
410            // `max-width: N` and a bare `width: N` both claim `N` itself.
411            Direction::Straddles
412        }
413    } else {
414        // The number is to the left of `width`.
415        let op = &group[end..width_at];
416        if op.contains("<=") || op.contains('>') {
417            Direction::Edge
418        } else {
419            Direction::Straddles
420        }
421    }
422}
423
424/// `(byte offset of the at-keyword, the condition text)`.
425///
426/// Reads the at-rules that carry a width condition: `@media` and `@container`
427/// (case-insensitive, terminated by `{`), and `@custom-media` and `@import`,
428/// which end at `;`. A container name ahead of its condition (`@container
429/// screen (width < 600px)`) lands in the condition text, and [`width_groups`]
430/// skips it, reading only the parenthesised width feature.
431pub(super) fn media_conditions(css: &str) -> Vec<(usize, &str)> {
432    let lower = css.to_ascii_lowercase();
433    let mut out = Vec::new();
434    let mut at = 0;
435    while let Some(rel) = lower[at..].find('@') {
436        let start = at + rel;
437        let kw_start = start + 1;
438        let kw_end = css[kw_start..]
439            .find(|c: char| !c.is_ascii_alphanumeric() && c != '-')
440            .map_or(css.len(), |i| kw_start + i);
441        let terminator = match &lower[kw_start..kw_end] {
442            "media" | "container" => '{',
443            "custom-media" | "import" => ';',
444            _ => {
445                at = start + 1;
446                continue;
447            }
448        };
449        match css[kw_end..].find(terminator) {
450            Some(j) => {
451                out.push((start, &css[kw_end..kw_end + j]));
452                at = kw_end + j + 1;
453            }
454            None => break,
455        }
456    }
457    out
458}
459
460/// `(byte offset, bound)` for every width feature in a JS source.
461///
462/// Only a parenthesised group is read: a media condition is always
463/// parenthesised and a CSS declaration never is, so `'max-width: 320px'` in
464/// an inline-style string is not a breakpoint. Range syntax,
465/// `(width < 600px)`, is read the same way as in a stylesheet.
466pub(super) fn js_widths(src: &str) -> Vec<(usize, Bound)> {
467    width_groups(src)
468        .into_iter()
469        .filter(|(_, group)| is_feature(group))
470        .flat_map(|(offset, group)| lengths(group).into_iter().map(move |b| (offset, b)))
471        .collect()
472}
473
474/// Whether a parenthesised group in script is a media feature rather than a
475/// call's arguments: `(max-width: 600px)` or `(width < 600px)`, not
476/// `Math.max(width, 600)`.
477fn is_feature(group: &str) -> bool {
478    let group = group.trim();
479    let colon = ["min-width", "max-width", "width"].iter().any(|name| {
480        group
481            .strip_prefix(name)
482            .is_some_and(|rest| rest.trim_start().starts_with(':'))
483    });
484    colon || group.contains(['<', '>'])
485}