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;
#[derive(Debug, Clone)]
#[must_use = "a check does nothing until it is run"]
pub struct Breakpoints {
source: Source,
tuning: Vec<u16>,
}
impl Breakpoints {
pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
Self {
source: Source::Frontend(frontend.as_ref().to_path_buf()),
tuning: Vec::new(),
}
}
pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
Self {
source: Source::files(paths),
tuning: Vec::new(),
}
}
pub fn tuning(mut self, widths: &[u16]) -> Self {
self.tuning.extend_from_slice(widths);
self
}
pub fn run(&self) {
match &self.source {
Source::Frontend(frontend) => {
let (_, mut files) = frontend_css(frontend);
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),
}
}
}
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") {
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;
}
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);
}
}
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
}
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
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Width {
Px(u16),
Other(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Bound {
width: Width,
direction: Direction,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
Edge,
Straddles,
}
impl Bound {
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),
}
}
}
pub(super) fn media_widths(condition: &str) -> Vec<Width> {
media_bounds(condition)
.into_iter()
.map(|bound| bound.width)
.collect()
}
fn media_bounds(condition: &str) -> Vec<Bound> {
width_groups(condition)
.into_iter()
.flat_map(|(_, group)| lengths(group))
.collect()
}
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];
let encloses_read = out.iter().any(|&(inner_start, _)| inner_start > start);
if names_width(inner) && !encloses_read {
out.push((start, inner));
}
}
}
_ => {}
}
}
out
}
fn names_width(inner: &str) -> bool {
width_token_at(inner).is_some()
}
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)
})
}
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() {
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) => {
#[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
}
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 {
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 {
Direction::Straddles
}
} else {
let op = &group[end..width_at];
if op.contains("<=") || op.contains('>') {
Direction::Edge
} else {
Direction::Straddles
}
}
}
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
}
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()
}
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(['<', '>'])
}