1use std::path::{Path, PathBuf};
15
16use makeover_geometry::{Density, SizeClass};
17use makeover_webview::Emit;
18
19const CONST_NAME: &str = "TOUCH_DENSITY";
22
23const SNIFFS: &[&str] = &["ontouchstart", "maxTouchPoints"];
29
30pub fn check_touch_density(js_dir: impl AsRef<Path>) {
51 let js_dir = js_dir.as_ref();
52 let want = Density::Touch.media_condition();
53 let mut wrong: Vec<String> = Vec::new();
54 let mut found = 0usize;
55
56 let files = js_files(js_dir);
57 for path in &files {
58 let src = std::fs::read_to_string(path)
59 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
60 let name = path
61 .strip_prefix(js_dir)
62 .unwrap_or(path)
63 .display()
64 .to_string();
65
66 for (offset, literal) in touch_density_literals(&src) {
67 found += 1;
68 if literal != want {
69 wrong.push(format!(
70 " {name}:{} {CONST_NAME} = '{literal}'",
71 line_of(&src, offset)
72 ));
73 }
74 }
75
76 for needle in SNIFFS {
77 if let Some(offset) = src.find(needle) {
78 wrong.push(format!(
79 " {name}:{} {needle} -- device sniff, not a density question",
80 line_of(&src, offset)
81 ));
82 }
83 }
84 }
85
86 assert!(
87 found > 0,
88 "no {CONST_NAME} literal found under {}.\n\n\
89 A frontend that asks whether it is being touched states\n\
90 makeover_geometry::Density::Touch's media condition in a const of that\n\
91 name, and this check exists to keep every copy equal to it. If the\n\
92 const was renamed, rename it back rather than dropping the check; if\n\
93 this frontend genuinely asks no density question, drop the call.",
94 js_dir.display()
95 );
96
97 assert!(
98 wrong.is_empty(),
99 "hand-written touch detection disagrees with makeover_geometry::Density.\n\n\
100 Density::Touch.media_condition() is: {want}\n\n\
101 Wrong:\n{}\n\n\
102 Fix the JS to state the crate's string. Never widen it to catch a\n\
103 device the query misses: density is what is pointing at the screen,\n\
104 and a laptop with a touchscreen and a mouse is a pointer device.",
105 wrong.join("\n")
106 );
107
108 for path in &files {
109 println!("cargo:rerun-if-changed={}", path.display());
110 }
111 println!("cargo:rerun-if-changed={}", js_dir.display());
115}
116
117fn js_files(dir: &Path) -> Vec<PathBuf> {
119 files_with_extension(dir, "js")
120}
121
122fn files_with_extension(dir: &Path, ext: &str) -> Vec<PathBuf> {
129 let mut out = Vec::new();
130 let mut stack = vec![dir.to_path_buf()];
131 while let Some(d) = stack.pop() {
132 for entry in std::fs::read_dir(&d)
133 .unwrap_or_else(|e| panic!("read {}: {e}", d.display()))
134 .flatten()
135 {
136 let path = entry.path();
137 if path.is_dir() {
138 stack.push(path);
139 } else if path.extension().is_some_and(|x| x == ext) {
140 out.push(path);
141 }
142 }
143 }
144 out.sort();
145 out
146}
147
148fn touch_density_literals(src: &str) -> Vec<(usize, &str)> {
151 let mut out = Vec::new();
152 let mut at = 0;
153 while let Some(i) = src[at..].find(CONST_NAME) {
154 let start = at + i;
155 at = start + CONST_NAME.len();
156 let Some(rest) = src[at..].strip_prefix(" = ") else {
158 continue;
159 };
160 let open = at + " = ".len();
161 let Some(quote @ ('\'' | '"')) = rest.chars().next() else {
162 continue;
163 };
164 let body = open + 1;
165 if let Some(j) = src[body..].find(quote) {
166 out.push((start, &src[body..body + j]));
167 at = body + j + 1;
168 }
169 }
170 out
171}
172
173fn line_of(src: &str, offset: usize) -> usize {
174 src[..offset].matches('\n').count() + 1
175}
176
177#[derive(Debug, Clone)]
179enum Source {
180 Frontend(PathBuf),
182 Files(Vec<PathBuf>),
184}
185
186impl Source {
187 fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
188 Self::Files(paths.iter().map(|p| p.as_ref().to_path_buf()).collect())
189 }
190}
191
192#[derive(Debug, Clone)]
212#[must_use = "a check does nothing until it is run"]
213pub struct Breakpoints {
214 source: Source,
215 tuning: Vec<u16>,
216}
217
218impl Breakpoints {
219 pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
222 Self {
223 source: Source::Frontend(frontend.as_ref().to_path_buf()),
224 tuning: Vec::new(),
225 }
226 }
227
228 pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
238 Self {
239 source: Source::files(paths),
240 tuning: Vec::new(),
241 }
242 }
243
244 pub fn tuning(mut self, widths: &[u16]) -> Self {
254 self.tuning.extend_from_slice(widths);
255 self
256 }
257
258 pub fn run(&self) {
268 match &self.source {
269 Source::Frontend(frontend) => {
270 let mut files = files_with_extension(&frontend.join("css"), "css");
271 files.extend(js_files(&frontend.join("js")));
272 check_paths(&files, &self.tuning, Some(frontend));
273 println!("cargo:rerun-if-changed={}", frontend.join("css").display());
275 println!("cargo:rerun-if-changed={}", frontend.join("js").display());
276 }
277 Source::Files(paths) => check_paths(paths, &self.tuning, None),
278 }
279 }
280}
281
282fn check_paths(paths: &[PathBuf], tuning_widths: &[u16], root: Option<&Path>) {
284 let allowed = allowed_widths(tuning_widths);
285 let mut stale: Vec<String> = Vec::new();
286
287 for path in paths {
288 let raw = std::fs::read_to_string(path)
289 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
290 let name = match root {
291 Some(root) => display_name(root, path),
292 None => path.display().to_string(),
293 };
294
295 if path.extension().is_some_and(|x| x == "js") {
296 for (offset, width) in js_widths(&blank(&raw, Lang::Js)) {
298 if !width.is_allowed(&allowed) {
299 stale.push(format!(" {name}:{} ({width})", line_of(&raw, offset)));
300 }
301 }
302 continue;
303 }
304
305 let src = blank(&raw, Lang::Css);
308 for (offset, condition) in media_conditions(&src) {
309 for width in media_widths(condition) {
310 if !width.is_allowed(&allowed) {
311 stale.push(format!(
312 " {name}:{} @media{condition} ({width})",
313 line_of(&src, offset)
314 ));
315 }
316 }
317 }
318 }
319
320 assert!(
321 stale.is_empty(),
322 "hand-written breakpoints disagree with makeover_geometry::SizeClass.\n\n\
323 Allowed: {allowed:?}\n\
324 ({:?} come from SizeClass; {tuning_widths:?} were passed as tuning widths.)\n\n\
325 Stale:\n{}\n\n\
326 Size classes are written in range syntax, `(width < 600px)`, because\n\
327 `(max-width: 599px)` leaves 599.5px in no class. If a size class moved,\n\
328 update these to match. If one of these is a new\n\
329 tuning width inside the wide shell rather than a shell boundary, add it\n\
330 to the caller's tuning list with a note saying what it tunes.\n\n\
331 Best of all, make the rule dimensional so it needs no threshold: a grid\n\
332 wants repeat(auto-fit, minmax(<content floor>, 1fr)) and a size wants\n\
333 clamp(). A threshold is for what appears and disappears.",
334 allowed
335 .iter()
336 .filter(|px| !tuning_widths.contains(px))
337 .collect::<Vec<_>>(),
338 stale.join("\n")
339 );
340
341 for path in paths {
342 println!("cargo:rerun-if-changed={}", path.display());
343 }
344}
345
346fn display_name(frontend: &Path, path: &Path) -> String {
348 path.strip_prefix(frontend)
349 .unwrap_or(path)
350 .display()
351 .to_string()
352}
353
354fn allowed_widths(tuning_widths: &[u16]) -> Vec<u16> {
360 let mut widths: Vec<u16> = SizeClass::all()
361 .iter()
362 .flat_map(|c| media_widths(&c.media_condition()))
363 .map(|width| match width {
364 Width::Px(px) => px,
365 Width::Other(raw) => {
366 panic!("makeover-geometry wrote a size-class width this check cannot read: {raw}")
367 }
368 })
369 .collect();
370 widths.extend_from_slice(tuning_widths);
371 widths.sort_unstable();
372 widths.dedup();
373 widths
374}
375
376#[derive(Debug, Clone, PartialEq, Eq)]
378enum Width {
379 Px(u16),
382 Other(String),
385}
386
387impl Width {
388 fn is_allowed(&self, allowed: &[u16]) -> bool {
389 matches!(self, Self::Px(px) if allowed.contains(px))
390 }
391}
392
393impl std::fmt::Display for Width {
394 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395 match self {
396 Self::Px(px) => write!(f, "{px}px"),
397 Self::Other(raw) => f.write_str(raw),
398 }
399 }
400}
401
402fn media_widths(condition: &str) -> Vec<Width> {
410 width_groups(condition)
411 .into_iter()
412 .flat_map(|(_, group)| lengths(group))
413 .collect()
414}
415
416fn width_groups(src: &str) -> Vec<(usize, &str)> {
419 let mut out = Vec::new();
420 let mut open = None;
421 for (i, c) in src.char_indices() {
422 match c {
423 '(' => open = Some(i),
424 ')' => {
425 if let Some(start) = open.take() {
426 let inner = &src[start + 1..i];
427 if names_width(inner) {
428 out.push((start, inner));
429 }
430 }
431 }
432 '\n' => open = None,
433 _ => {}
434 }
435 }
436 out
437}
438
439fn names_width(inner: &str) -> bool {
443 inner.match_indices("width").any(|(at, _)| {
444 let before = &inner[..at];
445 let prefix_ok = before.is_empty()
446 || before.ends_with("min-")
447 || before.ends_with("max-")
448 || before
449 .chars()
450 .next_back()
451 .is_some_and(|c| !c.is_ascii_alphanumeric() && c != '-' && c != '_');
452 let after = inner[at + "width".len()..].chars().next();
453 prefix_ok && after.is_none_or(|c| !c.is_ascii_alphanumeric() && c != '-' && c != '_')
454 })
455}
456
457fn lengths(group: &str) -> Vec<Width> {
459 let bytes = group.as_bytes();
460 let mut out = Vec::new();
461 let mut i = 0;
462 while i < bytes.len() {
463 let starts_number = bytes[i].is_ascii_digit()
464 && (i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'-'));
465 if !starts_number {
466 i += 1;
467 continue;
468 }
469 let start = i;
470 while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
471 i += 1;
472 }
473 let number = &group[start..i];
474 let unit_start = i;
475 while i < bytes.len() && bytes[i].is_ascii_alphabetic() {
476 i += 1;
477 }
478 let unit = &group[unit_start..i];
479 if unit.is_empty() {
480 continue;
481 }
482 let raw = &group[start..i];
483 let scale = match unit {
484 "px" => Some(1.0),
485 "em" | "rem" => Some(16.0),
486 _ => None,
487 };
488 let px = scale.and_then(|scale| number.parse::<f64>().ok().map(|n| n * scale));
489 out.push(match px {
490 Some(px) if px.fract() == 0.0 && px >= 0.0 && px <= f64::from(u16::MAX) => {
491 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
493 Width::Px(px as u16)
494 }
495 _ => Width::Other(raw.to_string()),
496 });
497 }
498 out
499}
500
501fn media_conditions(css: &str) -> Vec<(usize, &str)> {
503 let mut out = Vec::new();
504 let mut at = 0;
505 while let Some(i) = css[at..].find("@media") {
506 let start = at + i;
507 let after = start + "@media".len();
508 match css[after..].find('{') {
509 Some(j) => {
510 out.push((start, &css[after..after + j]));
511 at = after + j;
512 }
513 None => break,
514 }
515 }
516 out
517}
518
519fn js_widths(src: &str) -> Vec<(usize, Width)> {
527 width_groups(src)
528 .into_iter()
529 .filter(|(_, group)| is_feature(group))
530 .flat_map(|(offset, group)| lengths(group).into_iter().map(move |w| (offset, w)))
531 .collect()
532}
533
534fn is_feature(group: &str) -> bool {
538 let group = group.trim();
539 let colon = ["min-width", "max-width", "width"].iter().any(|name| {
540 group
541 .strip_prefix(name)
542 .is_some_and(|rest| rest.trim_start().starts_with(':'))
543 });
544 colon || group.contains(['<', '>'])
545}
546
547#[derive(Clone, Copy, PartialEq, Eq)]
549enum Lang {
550 Css,
553 Js,
557}
558
559fn blank(src: &str, lang: Lang) -> String {
565 #[derive(Clone, Copy)]
566 enum State {
567 Code,
568 Block,
569 Line,
570 Quoted(char),
571 }
572 let blank_into = |out: &mut String, c: char| {
575 if c == '\n' {
576 out.push('\n');
577 } else {
578 out.extend(std::iter::repeat_n(' ', c.len_utf8()));
579 }
580 };
581 let mut out = String::with_capacity(src.len());
582 let mut state = State::Code;
583 let mut chars = src.chars().peekable();
584 while let Some(c) = chars.next() {
585 match state {
586 State::Code => match c {
587 '/' if chars.peek() == Some(&'*') => {
588 chars.next();
589 out.push_str(" ");
590 state = State::Block;
591 }
592 '/' if lang == Lang::Js && chars.peek() == Some(&'/') => {
593 chars.next();
594 out.push_str(" ");
595 state = State::Line;
596 }
597 '"' | '\'' | '`' if lang == Lang::Js || c != '`' => {
598 out.push(c);
599 state = State::Quoted(c);
600 }
601 _ => out.push(c),
602 },
603 State::Block => {
604 if c == '*' && chars.peek() == Some(&'/') {
605 chars.next();
606 out.push_str(" ");
607 state = State::Code;
608 } else {
609 blank_into(&mut out, c);
610 }
611 }
612 State::Line => {
613 blank_into(&mut out, c);
614 if c == '\n' {
615 state = State::Code;
616 }
617 }
618 State::Quoted(quote) => {
619 let mut keep = |c: char| {
620 if lang == Lang::Js {
621 out.push(c);
622 } else {
623 blank_into(&mut out, c);
624 }
625 };
626 if c == quote {
627 out.push(c);
628 state = State::Code;
629 } else if c == '\\' {
630 keep(c);
631 if let Some(escaped) = chars.next() {
632 keep(escaped);
633 }
634 } else {
635 keep(c);
636 }
637 }
638 }
639 }
640 out
641}
642
643fn drop_layers(css: &str, names: &[&str]) -> String {
647 if names.is_empty() {
648 return css.to_owned();
649 }
650 let scan = blank(css, Lang::Css);
651 let scan = scan.as_bytes();
652 let mut out = css.as_bytes().to_vec();
653 let mut at = 0;
654 while let Some(found) = find_from(scan, b"@layer", at) {
655 let mut i = found + b"@layer".len();
656 while i < scan.len() && scan[i].is_ascii_whitespace() {
657 i += 1;
658 }
659 let start = i;
660 while i < scan.len() && (scan[i].is_ascii_alphanumeric() || matches!(scan[i], b'-' | b'_'))
661 {
662 i += 1;
663 }
664 let name = &css[start..i];
665 while i < scan.len() && scan[i].is_ascii_whitespace() {
666 i += 1;
667 }
668 if i >= scan.len() || scan[i] != b'{' || !names.contains(&name) {
669 at = found + 1;
670 continue;
671 }
672 let mut depth = 0usize;
673 let mut end = scan.len();
674 for (k, &byte) in scan.iter().enumerate().skip(i) {
675 match byte {
676 b'{' => depth += 1,
677 b'}' => {
678 depth -= 1;
679 if depth == 0 {
680 end = k + 1;
681 break;
682 }
683 }
684 _ => {}
685 }
686 }
687 for byte in &mut out[found..end] {
688 if *byte != b'\n' {
689 *byte = b' ';
690 }
691 }
692 at = end;
693 }
694 String::from_utf8(out).unwrap_or_else(|_| css.to_owned())
695}
696
697fn find_from(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
698 haystack
699 .get(from..)?
700 .windows(needle.len())
701 .position(|window| window == needle)
702 .map(|at| at + from)
703}
704
705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
712pub enum Allow<'a> {
713 Class {
715 class: &'a str,
717 property: &'a str,
719 },
720 Element {
723 element: &'a str,
725 class: &'a str,
727 property: &'a str,
729 },
730}
731
732impl<'a> Allow<'a> {
733 pub const fn class(class: &'a str, property: &'a str) -> Self {
735 Self::Class { class, property }
736 }
737
738 pub const fn element(element: &'a str, class: &'a str, property: &'a str) -> Self {
740 Self::Element {
741 element,
742 class,
743 property,
744 }
745 }
746}
747
748#[derive(Debug, Clone)]
825#[must_use = "a check does nothing until it is run"]
826pub struct Vocabulary<'a> {
827 source: Source,
828 generated: Vec<&'a str>,
829 upstream: Vec<&'a str>,
830 allowed: Vec<Allow<'a>>,
831 beneath: Vec<&'a str>,
832}
833
834impl<'a> Vocabulary<'a> {
835 pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
837 Self::from(Source::Frontend(frontend.as_ref().to_path_buf()))
838 }
839
840 pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
846 Self::from(Source::files(paths))
847 }
848
849 fn from(source: Source) -> Self {
850 Self {
851 source,
852 generated: Vec::new(),
853 upstream: Vec::new(),
854 allowed: Vec::new(),
855 beneath: Vec::new(),
856 }
857 }
858
859 pub fn generated(mut self, names: &[&'a str]) -> Self {
864 self.generated.extend_from_slice(names);
865 self
866 }
867
868 pub fn upstream(mut self, sheets: &[&'a str]) -> Self {
878 self.upstream.extend_from_slice(sheets);
879 self
880 }
881
882 pub fn beneath(mut self, layers: &[&'a str]) -> Self {
892 self.beneath.extend_from_slice(layers);
893 self
894 }
895
896 pub fn allow(mut self, allow: Allow<'a>) -> Self {
898 self.allowed.push(allow);
899 self
900 }
901
902 pub fn allowing(mut self, allows: impl IntoIterator<Item = Allow<'a>>) -> Self {
904 self.allowed.extend(allows);
905 self
906 }
907
908 pub fn run(&self, opts: &Emit) {
919 let classes: Vec<(&str, &str)> = self
920 .allowed
921 .iter()
922 .filter_map(|allow| match *allow {
923 Allow::Class { class, property } => Some((class, property)),
924 Allow::Element { .. } => None,
925 })
926 .collect();
927 let elements: Vec<(&str, &str, &str)> = self
928 .allowed
929 .iter()
930 .filter_map(|allow| match *allow {
931 Allow::Element {
932 element,
933 class,
934 property,
935 } => Some((element, class, property)),
936 Allow::Class { .. } => None,
937 })
938 .collect();
939 match &self.source {
940 Source::Frontend(frontend) => {
941 let css = frontend.join("css");
942 let files: Vec<PathBuf> = files_with_extension(&css, "css")
943 .into_iter()
944 .filter(|p| {
945 let name = p.strip_prefix(&css).unwrap_or(p).display().to_string();
946 !self.generated.contains(&name.as_str())
947 })
948 .collect();
949 check_vocabulary_paths(
950 &files,
951 opts,
952 Some(frontend),
953 &self.upstream,
954 &self.beneath,
955 &classes,
956 &elements,
957 );
958 println!("cargo::rerun-if-changed={}", css.display());
960 }
961 Source::Files(paths) => {
962 let files: Vec<PathBuf> = paths
963 .iter()
964 .filter(|p| !self.generated.iter().any(|name| p.ends_with(name)))
965 .cloned()
966 .collect();
967 check_vocabulary_paths(
968 &files,
969 opts,
970 None,
971 &self.upstream,
972 &self.beneath,
973 &classes,
974 &elements,
975 );
976 }
977 }
978 }
979}
980
981fn check_vocabulary_paths(
983 paths: &[PathBuf],
984 opts: &Emit,
985 root: Option<&Path>,
986 upstream: &[&str],
987 beneath: &[&str],
988 allowed: &[(&str, &str)],
989 allowed_elements: &[(&str, &str, &str)],
990) {
991 let makeover =
992 makeover_webview::vocabulary::declarations_by_class(&makeover_webview::stylesheet(opts));
993 let mut owned = makeover.clone();
996 for sheet in upstream {
997 for (class, properties) in makeover_webview::vocabulary::declarations_by_class(sheet) {
998 owned.entry(class).or_default().extend(properties);
999 }
1000 }
1001 let mut clashes: Vec<String> = Vec::new();
1002 let mut seen: Vec<(String, String)> = Vec::new();
1003 let mut element_clashes: Vec<String> = Vec::new();
1004 let mut element_seen: Vec<(String, String, String)> = Vec::new();
1005
1006 for path in paths {
1007 println!("cargo::rerun-if-changed={}", path.display());
1008 let raw = std::fs::read_to_string(path)
1009 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
1010 let name = match root {
1011 Some(root) => display_name(root, path),
1012 None => path.display().to_string(),
1013 };
1014 let generated = if upstream.contains(&raw.as_str()) {
1017 &makeover
1018 } else {
1019 &owned
1020 };
1021 let raw = drop_layers(&raw, beneath);
1024 let local = makeover_webview::vocabulary::declarations_by_class(&raw);
1027 for (class, properties) in &local {
1028 let Some(theirs) = generated.get(class) else {
1029 continue;
1030 };
1031 for property in properties.intersection(theirs) {
1032 seen.push((class.clone(), property.clone()));
1033 if allowed.contains(&(class.as_str(), property.as_str())) {
1034 continue;
1035 }
1036 clashes.push(format!(" {name} .{class} {{ {property} }}"));
1037 }
1038 }
1039
1040 let mentioned = makeover_webview::vocabulary::mentions_by_class(&raw);
1046 let by_element = makeover_webview::vocabulary::declarations_by_element(&raw);
1047 for (element, properties) in &by_element {
1048 for class in makeover_webview::vocabulary::classes_for_element(element, opts) {
1049 let Some(theirs) = generated.get(&class) else {
1050 continue;
1051 };
1052 for (property, rank) in properties {
1053 if !theirs.contains(property) {
1054 continue;
1055 }
1056 let spoken_for = mentioned
1060 .get(&class)
1061 .and_then(|properties| properties.get(property))
1062 .is_some_and(|theirs| theirs >= rank);
1063 if spoken_for {
1064 continue;
1065 }
1066 element_seen.push((element.clone(), class.clone(), property.clone()));
1067 if allowed_elements.contains(&(
1068 element.as_str(),
1069 class.as_str(),
1070 property.as_str(),
1071 )) {
1072 continue;
1073 }
1074 element_clashes.push(format!(
1075 " {name} {element} {{ {property} }} beats .{class} {{ {property} }}"
1076 ));
1077 }
1078 }
1079 }
1080 }
1081
1082 assert!(
1083 clashes.is_empty(),
1084 "{} hand-written declaration(s) take a property the generated stylesheet, \
1085 or an upstream sheet named to this check, already sets on the same \
1086 class. App CSS wins over @layer makeover, whether by a later layer or \
1087 by being unlayered, so each of these wins over the design system \
1088 silently:\n{}\n\nDelete the declaration, or, if \
1089 it is a deliberate pairing on a different selector arm, add \
1090 (class, property) to this check's allowed list and say why beside it. \
1091 Count the consumers before deciding a divergence is worth keeping.",
1092 clashes.len(),
1093 clashes.join("\n")
1094 );
1095
1096 assert!(
1097 element_clashes.is_empty(),
1098 "{} hand-written element rule(s) take a property the generated \
1099 stylesheet sets on a class that element carries. App CSS wins over \
1100 @layer makeover, whether by a later layer or by being unlayered, so a \
1101 described component rendered on one of these elements loses the \
1102 design system's version of that property silently, which can draw a \
1103 destructive act like an ordinary one:\n{}\n\nHand the \
1104 property back on the arms makeover paints \
1105 (`.{{class}}:disabled {{ color: revert-layer }}`), scope the element \
1106 rule so it stops reaching described markup, or add \
1107 (element, class, property) to this check's allowed-elements list and \
1108 say why beside it.",
1109 element_clashes.len(),
1110 element_clashes.join("\n")
1111 );
1112
1113 let stale: Vec<&(&str, &str)> = allowed
1114 .iter()
1115 .filter(|(class, property)| {
1116 !seen.contains(&((*class).to_string(), (*property).to_string()))
1117 })
1118 .collect();
1119 assert!(
1120 stale.is_empty(),
1121 "the allowed list declares {stale:?}, which no longer collides with \
1122 anything. Delete the entries: an exception nobody is using is where the \
1123 next real collision lands and reads as company."
1124 );
1125
1126 let stale: Vec<&(&str, &str, &str)> = allowed_elements
1127 .iter()
1128 .filter(|(element, class, property)| {
1129 !element_seen.contains(&(
1130 (*element).to_string(),
1131 (*class).to_string(),
1132 (*property).to_string(),
1133 ))
1134 })
1135 .collect();
1136 assert!(
1137 stale.is_empty(),
1138 "the allowed-elements list declares {stale:?}, which no longer collides \
1139 with anything. Delete the entries: an exception nobody is using is \
1140 where the next real collision lands and reads as company."
1141 );
1142}
1143
1144fn haystack_names(haystack: &str, class: &str) -> bool {
1148 let part = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_';
1149 haystack.match_indices(class).any(|(at, found)| {
1150 haystack[..at].chars().next_back().is_none_or(|c| !part(c))
1151 && haystack[at + found.len()..]
1152 .chars()
1153 .next()
1154 .is_none_or(|c| !part(c))
1155 })
1156}
1157
1158pub fn check_vocabulary_use<P: AsRef<Path>>(markup: &[P], opts: &Emit, high_water: usize) {
1182 let generated = makeover_webview::vocabulary::names(opts);
1183 let mut haystack = String::new();
1184 for path in markup {
1185 let path = path.as_ref();
1186 println!("cargo::rerun-if-changed={}", path.display());
1187 haystack.push_str(
1188 &std::fs::read_to_string(path)
1189 .unwrap_or_else(|e| panic!("read {}: {e}", path.display())),
1190 );
1191 haystack.push('\n');
1192 }
1193
1194 let rung = |class: &str| {
1199 class
1200 .strip_prefix(opts.class_prefix)
1201 .and_then(|name| name.strip_prefix("min-"))
1202 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
1203 };
1204 let ladder_used = generated
1205 .iter()
1206 .any(|class| rung(class) && haystack_names(&haystack, class));
1207 let mut unused: Vec<&String> = generated
1208 .iter()
1209 .filter(|class| !rung(class) && !haystack_names(&haystack, class))
1210 .collect();
1211 let ladder_name = format!("{}min-N", opts.class_prefix);
1212 if !ladder_used && generated.iter().any(|class| rung(class)) {
1213 unused.push(&ladder_name);
1214 }
1215
1216 assert!(
1217 unused.len() <= high_water,
1218 "{} of {} generated classes are emitted by no markup, above the recorded {}. \
1219 The vocabulary grew or the markup stopped using it:\n{}",
1220 unused.len(),
1221 generated.len(),
1222 high_water,
1223 unused
1224 .iter()
1225 .map(|c| format!(" .{c}"))
1226 .collect::<Vec<_>>()
1227 .join("\n")
1228 );
1229
1230 if unused.len() < high_water {
1231 println!(
1232 "cargo::warning=dead makeover vocabulary is down to {} from a sealed {}; \
1233 lower the seal so it cannot grow back",
1234 unused.len(),
1235 high_water
1236 );
1237 }
1238}
1239
1240#[cfg(test)]
1241mod tests {
1242 use super::*;
1243 use std::fmt::Write as _;
1244
1245 fn scratch(name: &str) -> PathBuf {
1246 let dir =
1247 std::env::temp_dir().join(format!("makeover-drift-{}-{name}", std::process::id()));
1248 let _ = std::fs::remove_dir_all(&dir);
1249 std::fs::create_dir_all(&dir).expect("create scratch");
1250 dir
1251 }
1252
1253 fn write(dir: &Path, name: &str, src: &str) {
1254 if let Some(parent) = dir.join(name).parent() {
1255 std::fs::create_dir_all(parent).unwrap();
1256 }
1257 std::fs::write(dir.join(name), src).unwrap();
1258 }
1259
1260 fn declaring() -> String {
1261 format!(
1262 "const {CONST_NAME} = '{}';\n",
1263 Density::Touch.media_condition()
1264 )
1265 }
1266
1267 #[test]
1268 fn the_crates_own_string_passes() {
1269 let dir = scratch("ok");
1270 write(&dir, "touch.js", &declaring());
1271 check_touch_density(&dir);
1272 }
1273
1274 #[test]
1275 #[should_panic(expected = "disagrees with makeover_geometry::Density")]
1276 fn a_drifted_literal_fails() {
1277 let dir = scratch("drift");
1278 write(&dir, "touch.js", &declaring());
1279 write(
1280 &dir,
1281 "haptics.js",
1282 &format!("const {CONST_NAME} = '(pointer: coarse)';\n"),
1283 );
1284 check_touch_density(&dir);
1285 }
1286
1287 #[test]
1288 #[should_panic(expected = "device sniff")]
1289 fn the_sniff_cannot_come_back() {
1290 let dir = scratch("sniff");
1291 write(&dir, "touch.js", &declaring());
1292 write(&dir, "legacy.js", "if ('ontouchstart' in window) {}\n");
1293 check_touch_density(&dir);
1294 }
1295
1296 #[test]
1297 #[should_panic(expected = "no TOUCH_DENSITY literal found")]
1298 fn a_frontend_that_states_nothing_fails() {
1299 let dir = scratch("empty");
1300 write(&dir, "app.js", "export const x = 1;\n");
1301 check_touch_density(&dir);
1302 }
1303
1304 #[test]
1305 fn a_use_site_is_not_a_declaration() {
1306 let src =
1310 format!("import {{ {CONST_NAME} }} from './touch.js';\nmatchMedia({CONST_NAME});\n");
1311 assert!(touch_density_literals(&src).is_empty());
1312 }
1313
1314 #[test]
1315 fn nested_files_are_read() {
1316 let dir = scratch("nested");
1319 write(&dir, "touch.js", &declaring());
1320 write(&dir, "screens/legacy.js", "navigator.maxTouchPoints > 0;\n");
1321 let files = js_files(&dir);
1322 assert_eq!(files.len(), 2);
1323 }
1324
1325 #[test]
1326 fn a_non_js_file_is_ignored() {
1327 let dir = scratch("nonjs");
1328 write(&dir, "touch.js", &declaring());
1329 write(&dir, "styles.css", "body { }\n");
1330 assert_eq!(js_files(&dir).len(), 1);
1331 }
1332
1333 fn frontend(name: &str) -> PathBuf {
1334 let dir = scratch(name);
1335 std::fs::create_dir_all(dir.join("css")).unwrap();
1336 std::fs::create_dir_all(dir.join("js")).unwrap();
1337 dir
1338 }
1339
1340 fn boundary() -> u16 {
1342 SizeClass::Medium.min_px()
1343 }
1344
1345 #[test]
1346 fn the_crates_own_boundaries_pass() {
1347 let dir = frontend("bp-ok");
1348 write(
1349 &dir,
1350 "css/styles.css",
1351 &format!("@media (min-width: {}px) {{ body {{ }} }}\n", boundary()),
1352 );
1353 Breakpoints::in_frontend(&dir).run();
1354 }
1355
1356 #[test]
1357 #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
1358 fn a_stale_css_width_fails() {
1359 let dir = frontend("bp-css");
1360 write(&dir, "css/styles.css", "@media (max-width: 768px) { }\n");
1361 Breakpoints::in_frontend(&dir).run();
1362 }
1363
1364 #[test]
1365 #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
1366 fn a_stale_js_width_fails() {
1367 let dir = frontend("bp-js");
1368 write(&dir, "js/shell.js", "matchMedia('(max-width: 768px)');\n");
1369 Breakpoints::in_frontend(&dir).run();
1370 }
1371
1372 #[test]
1373 fn a_declared_tuning_width_passes() {
1374 let dir = frontend("bp-tuning");
1375 write(&dir, "css/styles.css", "@media (min-width: 1400px) { }\n");
1376 Breakpoints::in_frontend(&dir).tuning(&[1400]).run();
1377 }
1378
1379 #[test]
1380 fn a_width_in_a_comment_is_prose() {
1381 let dir = frontend("bp-comment");
1384 write(
1385 &dir,
1386 "css/styles.css",
1387 "/* was @media (max-width: 768px) until the size classes landed */\n",
1388 );
1389 Breakpoints::in_frontend(&dir).run();
1390 }
1391
1392 #[test]
1393 fn an_unparenthesized_width_is_not_a_breakpoint() {
1394 let dir = frontend("bp-inline");
1398 write(
1399 &dir,
1400 "js/style.js",
1401 "el.style.cssText = 'max-width: 320px; display: block';\n",
1402 );
1403 Breakpoints::in_frontend(&dir).run();
1404 }
1405
1406 #[test]
1407 fn nested_css_is_read() {
1408 let dir = frontend("bp-nested");
1411 write(
1412 &dir,
1413 "css/screens/detail.css",
1414 "@media (max-width: 768px) { }\n",
1415 );
1416 let found = std::panic::catch_unwind(|| Breakpoints::in_frontend(&dir).run());
1417 assert!(found.is_err(), "a nested stylesheet must be scanned");
1418 }
1419
1420 #[test]
1421 fn a_named_list_is_checked() {
1422 let dir = frontend("bp-list");
1423 write(&dir, "css/style.css", "@media (max-width: 768px) { }\n");
1424 let listed = dir.join("css/style.css");
1425 let err = std::panic::catch_unwind(|| Breakpoints::files(&[&listed]).run()).unwrap_err();
1426 let msg = err.downcast_ref::<String>().expect("String payload");
1427 assert!(msg.contains("style.css:1"), "got: {msg}");
1428 }
1429
1430 #[test]
1431 #[should_panic(expected = "read ")]
1432 fn a_listed_file_that_is_gone_fails() {
1433 let dir = frontend("bp-missing");
1436 Breakpoints::files(&[dir.join("css/never-written.css")]).run();
1437 }
1438
1439 #[test]
1440 fn a_listed_js_file_is_parsed_as_script() {
1441 let dir = frontend("bp-list-js");
1444 write(
1445 &dir,
1446 "js/style.js",
1447 "el.style.cssText = 'max-width: 320px';\n",
1448 );
1449 Breakpoints::files(&[dir.join("js/style.js")]).run();
1450 }
1451
1452 #[test]
1453 fn the_error_names_the_file_and_line() {
1454 let dir = frontend("bp-message");
1455 write(
1456 &dir,
1457 "css/styles.css",
1458 "body { }\n@media (max-width: 768px) { }\n",
1459 );
1460 let err = std::panic::catch_unwind(|| Breakpoints::in_frontend(&dir).run()).unwrap_err();
1461 let msg = err
1462 .downcast_ref::<String>()
1463 .expect("panic payload is a String");
1464 assert!(msg.contains("css/styles.css:2"), "got: {msg}");
1465 }
1466
1467 #[test]
1468 fn a_rule_restating_an_upstream_class_fails_and_its_served_copy_does_not() {
1469 let upstream = ".tile-set { gap: 4px; }\n";
1472 let dir = scratch("vocab-upstream");
1473 write(&dir, "css/quasi.css", upstream);
1474 write(&dir, "css/styles.css", ".tile-set { gap: 0; }\n");
1475 let err = std::panic::catch_unwind(|| {
1476 Vocabulary::in_frontend(&dir)
1477 .upstream(&[upstream])
1478 .run(&Emit::default());
1479 })
1480 .unwrap_err();
1481 let msg = err
1482 .downcast_ref::<String>()
1483 .expect("panic payload is a String");
1484 assert!(
1485 msg.contains("css/styles.css .tile-set { gap }"),
1486 "got: {msg}"
1487 );
1488 assert!(
1489 !msg.contains("css/quasi.css"),
1490 "the served copy clashed with itself: {msg}"
1491 );
1492
1493 Vocabulary::in_frontend(&dir).run(&Emit::default());
1496 }
1497
1498 #[test]
1499 fn a_rule_restating_a_generated_class_fails_and_names_it() {
1500 let dir = scratch("vocab-clash");
1501 write(
1504 &dir,
1505 "css/styles.css",
1506 "body { color: red; }\n.card { box-shadow: none; }\n",
1507 );
1508 let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
1509 .unwrap_err();
1510 let msg = err
1511 .downcast_ref::<String>()
1512 .expect("panic payload is a String");
1513 assert!(msg.contains(".card"), "got: {msg}");
1514 assert!(msg.contains("box-shadow"), "got: {msg}");
1515 assert!(msg.contains("css/styles.css"), "got: {msg}");
1516 }
1517
1518 #[test]
1519 fn an_app_class_of_its_own_is_left_alone() {
1520 let dir = scratch("vocab-clean");
1521 write(
1522 &dir,
1523 "css/styles.css",
1524 ".task-list-container { overflow: auto; }\n.day-plan-slot { height: 1rem; }\n",
1525 );
1526 Vocabulary::in_frontend(&dir).run(&Emit::default());
1527 }
1528
1529 #[test]
1530 fn the_generated_sheet_is_skipped_rather_than_reported_against_itself() {
1531 let dir = scratch("vocab-generated");
1532 let opts = Emit::default();
1533 write(&dir, "css/layout.css", &makeover_webview::stylesheet(&opts));
1534 Vocabulary::in_frontend(&dir)
1537 .generated(&["layout.css"])
1538 .run(&opts);
1539 }
1540
1541 #[test]
1542 fn a_prefixed_app_is_checked_against_its_own_prefix() {
1543 let dir = scratch("vocab-prefix");
1544 let opts = Emit::new().class_prefix("mo-");
1545 write(&dir, "css/styles.css", ".card { box-shadow: none; }\n");
1548 Vocabulary::in_frontend(&dir).run(&opts);
1549
1550 let dir = scratch("vocab-prefix-clash");
1551 write(&dir, "css/styles.css", ".mo-card { box-shadow: none; }\n");
1552 assert!(std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&opts)).is_err());
1553 }
1554
1555 #[test]
1556 fn a_class_shared_without_a_shared_property_is_left_alone() {
1557 let dir = scratch("vocab-additive");
1558 write(
1561 &dir,
1562 "css/styles.css",
1563 ".cell-value { padding: 2px; border-radius: 3px; font-weight: 600; }\n",
1564 );
1565 Vocabulary::in_frontend(&dir).run(&Emit::default());
1566 }
1567
1568 #[test]
1569 fn a_reviewed_pair_passes_and_stops_passing_when_it_stops_colliding() {
1570 let dir = scratch("vocab-allowed");
1571 write(&dir, "css/styles.css", ".card { box-shadow: none; }\n");
1572 Vocabulary::in_frontend(&dir)
1573 .allow(Allow::class("card", "box-shadow"))
1574 .run(&Emit::default());
1575
1576 let dir = scratch("vocab-allowed-stale");
1579 write(&dir, "css/styles.css", ".card { padding: 2px; }\n");
1580 let err = std::panic::catch_unwind(|| {
1581 Vocabulary::in_frontend(&dir)
1582 .allow(Allow::class("card", "box-shadow"))
1583 .run(&Emit::default());
1584 })
1585 .unwrap_err();
1586 let msg = err
1587 .downcast_ref::<String>()
1588 .expect("panic payload is a String");
1589 assert!(msg.contains("no longer collides"), "got: {msg}");
1590 }
1591
1592 #[test]
1593 fn an_element_rule_clobbering_a_generated_class_fails_and_names_all_three() {
1594 let dir = scratch("vocab-element");
1595 write(&dir, "css/styles.css", "select { box-shadow: none; }\n");
1599 let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
1600 .unwrap_err();
1601 let msg = err
1602 .downcast_ref::<String>()
1603 .expect("panic payload is a String");
1604 assert!(msg.contains("select {"), "got: {msg}");
1605 assert!(msg.contains(".field"), "got: {msg}");
1606 assert!(msg.contains("box-shadow"), "got: {msg}");
1607 assert!(msg.contains("css/styles.css"), "got: {msg}");
1608 }
1609
1610 #[test]
1611 fn a_universal_reset_after_the_design_system_is_caught() {
1612 let dir = scratch("vocab-universal");
1616 write(&dir, "css/styles.css", "* { margin: 0; padding: 0; }\n");
1617 let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
1618 .unwrap_err();
1619 let msg = err
1620 .downcast_ref::<String>()
1621 .expect("panic payload is a String");
1622 assert!(msg.contains("* {"), "got: {msg}");
1623 assert!(msg.contains("padding"), "got: {msg}");
1624 }
1625
1626 #[test]
1627 fn a_universal_reset_in_a_layer_beneath_makeover_is_not_read() {
1628 let dir = scratch("vocab-universal-beneath");
1629 write(
1630 &dir,
1631 "css/styles.css",
1632 "/* { */ @layer reset {\n * { margin: 0; padding: 0; }\n}\n.x { content: \"}\"; }\n",
1633 );
1634 Vocabulary::in_frontend(&dir)
1635 .beneath(&["reset"])
1636 .run(&Emit::default());
1637 }
1638
1639 #[test]
1640 fn a_layer_not_named_beneath_is_still_read() {
1641 let dir = scratch("vocab-universal-other-layer");
1642 write(
1643 &dir,
1644 "css/styles.css",
1645 "@layer base {\n * { padding: 0; }\n}\n",
1646 );
1647 let err = std::panic::catch_unwind(|| {
1648 Vocabulary::in_frontend(&dir)
1649 .beneath(&["reset"])
1650 .run(&Emit::default());
1651 })
1652 .unwrap_err();
1653 let msg = err.downcast_ref::<String>().expect("a String payload");
1654 assert!(msg.contains("* {"), "got: {msg}");
1655 }
1656
1657 #[test]
1658 fn a_universal_rule_touching_nothing_generated_is_not_a_clash() {
1659 let dir = scratch("vocab-universal-box");
1660 write(&dir, "css/styles.css", "* { box-sizing: border-box; }\n");
1661 Vocabulary::in_frontend(&dir).run(&Emit::default());
1662 }
1663
1664 #[test]
1665 fn a_handoff_on_the_class_is_the_remedy_and_reads_as_one() {
1666 let dir = scratch("vocab-element-handoff");
1667 write(
1672 &dir,
1673 "css/styles.css",
1674 "select { box-shadow: none; }\n.field { box-shadow: revert-layer; }\n",
1675 );
1676 Vocabulary::in_frontend(&dir).run(&Emit::default());
1677 }
1678
1679 #[test]
1680 fn a_property_the_app_states_on_the_class_is_not_the_element_rules_doing() {
1681 let dir = scratch("vocab-element-spoken-for");
1682 write(
1687 &dir,
1688 "css/styles.css",
1689 "select { box-shadow: none; }\n.field { box-shadow: none; }\n",
1690 );
1691 Vocabulary::in_frontend(&dir)
1692 .allow(Allow::class("field", "box-shadow"))
1693 .run(&Emit::default());
1694 }
1695
1696 #[test]
1697 fn a_handoff_that_loses_to_the_rule_it_remedies_is_not_a_remedy() {
1698 let dir = scratch("vocab-element-weak-handoff");
1699 write(
1703 &dir,
1704 "css/styles.css",
1705 "select:focus { box-shadow: none; }\n.field { box-shadow: revert-layer; }\n",
1706 );
1707 let err = std::panic::catch_unwind(|| Vocabulary::in_frontend(&dir).run(&Emit::default()))
1708 .unwrap_err();
1709 let msg = err
1710 .downcast_ref::<String>()
1711 .expect("panic payload is a String");
1712 assert!(msg.contains(".field"), "got: {msg}");
1713
1714 let dir = scratch("vocab-element-strong-handoff");
1716 write(
1717 &dir,
1718 "css/styles.css",
1719 "select:focus { box-shadow: none; }\nselect.field { box-shadow: revert-layer; }\n",
1720 );
1721 Vocabulary::in_frontend(&dir).run(&Emit::default());
1722 }
1723
1724 #[test]
1725 fn a_scoped_rule_is_not_read_as_an_element_rule() {
1726 let dir = scratch("vocab-element-scoped");
1727 write(
1731 &dir,
1732 "css/styles.css",
1733 ".wizard select { box-shadow: none; }\n",
1734 );
1735 Vocabulary::in_frontend(&dir).run(&Emit::default());
1736 }
1737
1738 #[test]
1739 fn an_element_the_design_system_never_renders_onto_is_left_alone() {
1740 let dir = scratch("vocab-element-unpaired");
1741 write(&dir, "css/styles.css", "footer { box-shadow: none; }\n");
1744 Vocabulary::in_frontend(&dir).run(&Emit::default());
1745 }
1746
1747 #[test]
1748 fn a_reviewed_element_pairing_passes_and_stops_passing_when_it_stops_colliding() {
1749 let dir = scratch("vocab-element-allowed");
1750 write(&dir, "css/styles.css", "select { box-shadow: none; }\n");
1751 Vocabulary::in_frontend(&dir)
1752 .allow(Allow::element("select", "field", "box-shadow"))
1753 .run(&Emit::default());
1754
1755 let dir = scratch("vocab-element-allowed-stale");
1758 write(&dir, "css/styles.css", "select { padding: 2px; }\n");
1759 let err = std::panic::catch_unwind(|| {
1760 Vocabulary::in_frontend(&dir)
1761 .allow(Allow::element("select", "field", "box-shadow"))
1762 .run(&Emit::default());
1763 })
1764 .unwrap_err();
1765 let msg = err
1766 .downcast_ref::<String>()
1767 .expect("panic payload is a String");
1768 assert!(msg.contains("no longer collides"), "got: {msg}");
1769 }
1770
1771 #[test]
1772 fn dead_vocabulary_above_the_seal_fails_and_below_it_passes() {
1773 let dir = scratch("vocab-seal");
1774 let opts = Emit::default();
1775 let names = makeover_webview::vocabulary::names(&opts);
1776 let rungs = names.iter().filter(|c| c.starts_with("min-")).count();
1777 assert!(rungs > 1, "the floor ladder is in the vocabulary");
1778 let dead = names.len() - rungs + 1;
1781 write(&dir, "index.html", "<div></div>\n");
1782 let markup = [dir.join("index.html")];
1783
1784 check_vocabulary_use(&markup, &opts, dead);
1785 assert!(
1786 std::panic::catch_unwind(|| check_vocabulary_use(&markup, &opts, dead - 1)).is_err(),
1787 "a vocabulary deader than the seal has to fail"
1788 );
1789 }
1790
1791 #[test]
1792 fn one_rung_of_the_floor_ladder_uses_the_ladder() {
1793 let opts = Emit::default();
1796 let names = makeover_webview::vocabulary::names(&opts);
1797 let rungs = names.iter().filter(|c| c.starts_with("min-")).count();
1798 let dead = names.len() - rungs + 1;
1799
1800 let dir = scratch("vocab-ladder");
1801 write(&dir, "index.html", "<div class=\"cell min-16\"></div>\n");
1802 let one_rung = [dir.join("index.html")];
1803 check_vocabulary_use(&one_rung, &opts, dead - 2);
1805
1806 write(&dir, "index.html", "<div class=\"min-24\"></div>\n");
1808 assert!(haystack_names("<div class=\"min-24\">", "min-24"));
1809 assert!(!haystack_names("<div class=\"min-24\">", "min-2"));
1810 }
1811
1812 #[test]
1813 fn a_class_is_named_whole_on_both_sides() {
1814 assert!(haystack_names("class=\"row\"", "row"));
1815 assert!(!haystack_names("class=\"row-flex\"", "row"));
1816 assert!(!haystack_names("class=\"flex-row\"", "row"));
1817 assert!(haystack_names("el.classList.add('row')", "row"));
1818 }
1819
1820 #[test]
1821 fn range_syntax_and_units_are_read() {
1822 assert_eq!(media_widths("(width < 600px)"), [Width::Px(600)]);
1823 assert_eq!(
1824 media_widths(" (600px <= width < 840px)"),
1825 [Width::Px(600), Width::Px(840)]
1826 );
1827 assert_eq!(media_widths(" (max-width: 48em)"), [Width::Px(768)]);
1828 assert_eq!(media_widths(" (min-width: 37.5rem)"), [Width::Px(600)]);
1829 assert_eq!(
1830 media_widths(" (max-width: 599.98px)"),
1831 [Width::Other("599.98px".into())]
1832 );
1833 assert_eq!(
1834 media_widths(" (width < 50vw)"),
1835 [Width::Other("50vw".into())]
1836 );
1837 assert!(media_widths(" (min-height: 600px)").is_empty());
1838 assert!(media_widths(" (max-device-width: 600px)").is_empty());
1839 assert!(media_widths(" (hover: hover) and (pointer: fine)").is_empty());
1840 }
1841
1842 #[test]
1843 fn every_size_class_condition_passes_its_own_check() {
1844 let dir = frontend("bp-classes");
1845 let mut css = String::new();
1846 for class in SizeClass::all() {
1847 let _ = writeln!(css, "@media {} {{ body {{ }} }}", class.media_condition());
1848 }
1849 write(&dir, "css/styles.css", &css);
1850 write(
1851 &dir,
1852 "js/shell.js",
1853 &format!("matchMedia('{}');\n", SizeClass::Compact.media_condition()),
1854 );
1855 Breakpoints::in_frontend(&dir).run();
1856 }
1857
1858 #[test]
1859 #[should_panic(expected = "48em")]
1860 fn a_width_in_em_is_a_width_and_not_a_bare_number() {
1861 let dir = frontend("bp-em");
1862 write(&dir, "css/styles.css", "@media (max-width: 48em) { }\n");
1863 Breakpoints::in_frontend(&dir).tuning(&[48]).run();
1864 }
1865
1866 #[test]
1867 #[should_panic(expected = "(width < 768px)")]
1868 fn a_stale_range_width_fails() {
1869 let dir = frontend("bp-range");
1870 write(&dir, "css/styles.css", "@media (width < 768px) { }\n");
1871 Breakpoints::in_frontend(&dir).run();
1872 }
1873
1874 #[test]
1875 #[should_panic(expected = "599px")]
1876 fn the_old_inclusive_compact_bound_is_stale() {
1877 let dir = frontend("bp-599");
1878 write(&dir, "css/styles.css", "@media (max-width: 599px) { }\n");
1879 Breakpoints::in_frontend(&dir).run();
1880 }
1881
1882 #[test]
1883 fn a_call_in_script_is_not_a_feature() {
1884 assert!(js_widths("const w = Math.max(width, 600);").is_empty());
1885 assert!(js_widths("el.style.cssText = 'max-width: 320px';").is_empty());
1886 assert_eq!(js_widths("matchMedia('(width < 600px)')").len(), 1);
1887 }
1888
1889 #[test]
1890 fn a_slash_star_slash_opens_a_comment_rather_than_closing_one() {
1891 let css = "/*/ @media (max-width: 768px) { } */ a { }";
1892 let stripped = blank(css, Lang::Css);
1893 assert!(!stripped.contains("768"), "{stripped:?}");
1894 assert!(stripped.contains("a { }"));
1895 assert_eq!(stripped.len(), css.len());
1896 }
1897
1898 #[test]
1899 fn a_comment_opener_inside_a_string_is_text() {
1900 let css = "a::after { content: \"/*\"; }\n@media (max-width: 768px) { }\n";
1902 let src = blank(css, Lang::Css);
1903 assert_eq!(media_conditions(&src).len(), 1);
1904 assert!(src.contains("768"));
1905
1906 let js = "const glob = '/*';\nmatchMedia('(width < 600px)');\n";
1907 assert_eq!(js_widths(&blank(js, Lang::Js)).len(), 1);
1908 }
1909
1910 #[test]
1911 fn a_query_in_a_script_comment_is_prose() {
1912 let js = "// was matchMedia('(width < 768px)')\n/* (max-width: 500px) */\n";
1913 assert!(js_widths(&blank(js, Lang::Js)).is_empty());
1914 }
1915
1916 #[test]
1917 fn a_brace_inside_a_css_string_does_not_end_a_condition() {
1918 let css = "@media (width < 600px) { a::after { content: \"{\"; } }";
1919 let src = blank(css, Lang::Css);
1920 assert_eq!(media_conditions(&src).len(), 1);
1921 }
1922
1923 #[test]
1924 fn blanking_keeps_byte_offsets_through_multibyte_text() {
1925 let css = "/* a \u{2014} b */ a::after { content: \"\u{2014}\"; }\n@layer reset { * { padding: 0; } }";
1928 let src = blank(css, Lang::Css);
1929 assert_eq!(src.len(), css.len());
1930 let at = css.find("@layer").unwrap();
1931 assert_eq!(&src[at..at + 6], "@layer");
1932 let dropped = drop_layers(css, &["reset"]);
1933 assert!(!dropped.contains("padding"), "{dropped:?}");
1934 }
1935
1936 #[test]
1937 fn blanking_keeps_lines_and_offsets() {
1938 let css = "/* one\ntwo */\n\"x\ny\"\n@media (max-width: 1px) {}";
1939 let src = blank(css, Lang::Css);
1940 assert_eq!(src.len(), css.len());
1941 assert_eq!(src.lines().count(), css.lines().count());
1942 }
1943
1944 #[test]
1945 fn both_quote_styles_read() {
1946 let want = Density::Touch.media_condition();
1947 for q in ['\'', '"'] {
1948 let src = format!("const {CONST_NAME} = {q}{want}{q};\n");
1949 let found = touch_density_literals(&src);
1950 assert_eq!(found.len(), 1);
1951 assert_eq!(found[0].1, want);
1952 }
1953 }
1954
1955 #[test]
1956 fn a_file_list_skips_the_sheets_named_generated() {
1957 let dir = frontend("vocab-files");
1958 write(&dir, "css/layout.css", ".card { box-shadow: none; }\n");
1959 write(&dir, "css/app.css", "body { color: red; }\n");
1960 let files = [dir.join("css/layout.css"), dir.join("css/app.css")];
1961 Vocabulary::files(&files)
1962 .generated(&["layout.css"])
1963 .run(&Emit::default());
1964 let err = std::panic::catch_unwind(|| Vocabulary::files(&files).run(&Emit::default()))
1965 .unwrap_err();
1966 let msg = err.downcast_ref::<String>().cloned().unwrap_or_default();
1967 assert!(msg.contains("box-shadow"), "got: {msg}");
1968 }
1969}