Skip to main content

max / makeover-build

47.2 KB · 1217 lines History Blame Raw
1 //! Checks that a hand-written frontend still agrees with the crate that
2 //! generates its siblings.
3 //!
4 //! The generated files cannot drift: they ask makeover-geometry for the answer.
5 //! The hand-written ones state it, and a stylesheet or a script that disagrees
6 //! with the crate is not an error at any point -- it is a rule that quietly
7 //! stops matching where it used to. Cheaper to read a panic naming the line.
8 //!
9 //! Deliberately assertions and not substitutions. A JS or CSS file that has to
10 //! be generated to be correct stops being readable on its own, and it is worth
11 //! something that you can still open the frontend in a browser and have it
12 //! work.
13
14 use std::path::{Path, PathBuf};
15
16 use makeover_geometry::{Density, SizeClass};
17 use makeover_webview::Emit;
18
19 /// The declaration this check reads. Shared vocabulary, not a parameter: two
20 /// apps and a server naming the same string want the same name for it.
21 const CONST_NAME: &str = "TOUCH_DENSITY";
22
23 /// The capability sniffs the media query replaced, so neither can come back by
24 /// copy-paste.
25 ///
26 /// Both ask the hardware what it has rather than what is pointing at the
27 /// screen, so both say yes to a touchscreen laptop driving a mouse.
28 const SNIFFS: &[&str] = &["ontouchstart", "maxTouchPoints"];
29
30 /// Fail the build if a JS copy of the touch-density query has drifted from
31 /// [`Density::Touch`].
32 ///
33 /// Every `.js` file under `js_dir`, recursively, must state the crate's own
34 /// media condition in a `const TOUCH_DENSITY = '...'`, at least one file must
35 /// declare it, and no file may name a capability sniff.
36 ///
37 /// The string is the crate's and no app gets a say in it, which is why this
38 /// check takes no policy argument. The generated `geometry.css` already keys
39 /// its touch gap overrides on the same condition, so the gestures and the
40 /// spacing agree by construction rather than by two people remembering.
41 ///
42 /// Emits `cargo:rerun-if-changed` for every file it read.
43 ///
44 /// # Panics
45 ///
46 /// If `js_dir` cannot be read, if no declaration is found, or if any file
47 /// disagrees with the crate. A build script has nowhere useful to return an
48 /// error to, and a frontend that disagrees with its own stylesheet is worse
49 /// than a failed build.
50 pub 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).expect("read js file");
59 let name = path
60 .strip_prefix(js_dir)
61 .unwrap_or(path)
62 .display()
63 .to_string();
64
65 for (offset, literal) in touch_density_literals(&src) {
66 found += 1;
67 if literal != want {
68 wrong.push(format!(
69 " {name}:{} {CONST_NAME} = '{literal}'",
70 line_of(&src, offset)
71 ));
72 }
73 }
74
75 for needle in SNIFFS {
76 if let Some(offset) = src.find(needle) {
77 wrong.push(format!(
78 " {name}:{} {needle} -- device sniff, not a density question",
79 line_of(&src, offset)
80 ));
81 }
82 }
83 }
84
85 assert!(
86 found > 0,
87 "no {CONST_NAME} literal found under {}.\n\n\
88 A frontend that asks whether it is being touched states\n\
89 makeover_geometry::Density::Touch's media condition in a const of that\n\
90 name, and this check exists to keep every copy equal to it. If the\n\
91 const was renamed, rename it back rather than dropping the check; if\n\
92 this frontend genuinely asks no density question, drop the call.",
93 js_dir.display()
94 );
95
96 assert!(
97 wrong.is_empty(),
98 "hand-written touch detection disagrees with makeover_geometry::Density.\n\n\
99 Density::Touch.media_condition() is: {want}\n\n\
100 Wrong:\n{}\n\n\
101 Fix the JS to state the crate's string. Never widen it to catch a\n\
102 device the query misses: density is what is pointing at the screen,\n\
103 and a laptop with a touchscreen and a mouse is a pointer device.",
104 wrong.join("\n")
105 );
106
107 for path in &files {
108 println!("cargo:rerun-if-changed={}", path.display());
109 }
110 }
111
112 /// Every `.js` file under `dir`, recursively, sorted.
113 fn js_files(dir: &Path) -> Vec<PathBuf> {
114 files_with_extension(dir, "js")
115 }
116
117 /// Every file under `dir` with extension `ext`, recursively, sorted.
118 ///
119 /// Recursive because a consumer's frontend is not always one flat directory:
120 /// the Tauri apps keep `js/*.js`, the server keeps subdirectories under
121 /// `static/`, and a check that silently skipped the nested half would report
122 /// clean on the files most likely to have been copied.
123 fn files_with_extension(dir: &Path, ext: &str) -> Vec<PathBuf> {
124 let mut out = Vec::new();
125 let mut stack = vec![dir.to_path_buf()];
126 while let Some(d) = stack.pop() {
127 for entry in std::fs::read_dir(&d)
128 .unwrap_or_else(|e| panic!("read {}: {e}", d.display()))
129 .flatten()
130 {
131 let path = entry.path();
132 if path.is_dir() {
133 stack.push(path);
134 } else if path.extension().is_some_and(|x| x == ext) {
135 out.push(path);
136 }
137 }
138 }
139 out.sort();
140 out
141 }
142
143 /// `(byte offset of the declaration, the literal's contents)` for every
144 /// `const TOUCH_DENSITY = '...'` in a JS source.
145 fn touch_density_literals(src: &str) -> Vec<(usize, &str)> {
146 let mut out = Vec::new();
147 let mut at = 0;
148 while let Some(i) = src[at..].find(CONST_NAME) {
149 let start = at + i;
150 at = start + CONST_NAME.len();
151 // Only the declaration states the string; a use site reads the const.
152 let Some(rest) = src[at..].strip_prefix(" = ") else {
153 continue;
154 };
155 let open = at + " = ".len();
156 let Some(quote @ ('\'' | '"')) = rest.chars().next() else {
157 continue;
158 };
159 let body = open + 1;
160 if let Some(j) = src[body..].find(quote) {
161 out.push((start, &src[body..body + j]));
162 at = body + j + 1;
163 }
164 }
165 out
166 }
167
168 fn line_of(src: &str, offset: usize) -> usize {
169 src[..offset].matches('\n').count() + 1
170 }
171
172 /// Fail the build if a hand-written breakpoint has drifted from [`SizeClass`].
173 ///
174 /// Every pixel width named by a media query under `frontend/css` or
175 /// `frontend/js`, recursively, must be a [`SizeClass`] boundary or one of
176 /// `tuning_widths`.
177 ///
178 /// Without this, moving `SizeClass::Medium::min_px` regenerates the emitted
179 /// stylesheets and silently leaves every hand-written query behind, and what
180 /// you get is not an error but a stylesheet that disagrees with itself at the
181 /// old boundary.
182 ///
183 /// `tuning_widths` is the one thing an app gets a say in, which is why this
184 /// takes a parameter where [`check_touch_density`] does not. A shell boundary
185 /// is a [`SizeClass`] edge and belongs to makeover-geometry; a tuning width is
186 /// a point inside a shell where something reflows without the shell changing --
187 /// a dashboard dropping from three columns to two, a pane's width cap ending.
188 /// Nothing switches shells at one, so it should not move when a size class
189 /// does. Pass `&[]` if the app has none, and treat every addition as owing a
190 /// note saying what it tunes: the list is where a genuine boundary goes to hide
191 /// from this check.
192 ///
193 /// The generated stylesheets are scanned too, and pass by construction: they
194 /// ask makeover-geometry for the number rather than stating it. Scanning them
195 /// costs nothing and means a consumer never has to name which files are
196 /// hand-written.
197 ///
198 /// Emits `cargo:rerun-if-changed` for every file it read.
199 ///
200 /// # Panics
201 ///
202 /// If `frontend/css` or `frontend/js` cannot be read, or if any width is
203 /// neither a size-class boundary nor a declared tuning width. A build script
204 /// has nowhere useful to return an error to.
205 pub fn check_breakpoints(frontend: impl AsRef<Path>, tuning_widths: &[u16]) {
206 let frontend = frontend.as_ref();
207 let mut files = files_with_extension(&frontend.join("css"), "css");
208 files.extend(js_files(&frontend.join("js")));
209 check_paths(&files, tuning_widths, Some(frontend));
210 }
211
212 /// [`check_breakpoints`] against a named list of files rather than a tree.
213 ///
214 /// For a frontend whose generated and hand-written files share a directory, so
215 /// there is nothing to point a directory scan at: the MNW server keeps both
216 /// under `static/` alongside a bundler's output, and bundled third-party CSS
217 /// is exactly the place a width nobody chose would come from.
218 ///
219 /// The cost is that the list is hand-maintained, and a stylesheet nobody adds
220 /// to it is unchecked rather than failing. Prefer [`check_breakpoints`] where
221 /// the layout allows it.
222 ///
223 /// A `.js` path is parsed as script and anything else as stylesheet, which is
224 /// the only difference: a media condition is parenthesised in both.
225 ///
226 /// # Panics
227 ///
228 /// If a listed file cannot be read -- a listed path that no longer exists is a
229 /// check silently covering less than it says -- or if any width is neither a
230 /// size-class boundary nor a declared tuning width.
231 pub fn check_breakpoints_files<P: AsRef<Path>>(paths: &[P], tuning_widths: &[u16]) {
232 let paths: Vec<PathBuf> = paths.iter().map(|p| p.as_ref().to_path_buf()).collect();
233 check_paths(&paths, tuning_widths, None);
234 }
235
236 /// The check itself. `root`, when given, is stripped from reported paths.
237 fn check_paths(paths: &[PathBuf], tuning_widths: &[u16], root: Option<&Path>) {
238 let allowed = allowed_widths(tuning_widths);
239 let mut stale: Vec<String> = Vec::new();
240
241 for path in paths {
242 let raw = std::fs::read_to_string(path)
243 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
244 let name = match root {
245 Some(root) => display_name(root, path),
246 None => path.display().to_string(),
247 };
248
249 if path.extension().is_some_and(|x| x == "js") {
250 // No declarations in JS, so any parenthesised width is a query.
251 for (offset, px) in js_widths(&raw) {
252 if !allowed.contains(&px) {
253 stale.push(format!(" {name}:{} ({px}px)", line_of(&raw, offset)));
254 }
255 }
256 continue;
257 }
258
259 // Comments first: a note about a breakpoint that used to be here is
260 // prose, not a rule, and should not fail a build.
261 let src = strip_block_comments(&raw);
262 for (offset, condition) in media_conditions(&src) {
263 for px in media_widths(condition) {
264 if !allowed.contains(&px) {
265 stale.push(format!(
266 " {name}:{} @media{condition} ({px}px)",
267 line_of(&src, offset)
268 ));
269 }
270 }
271 }
272 }
273
274 assert!(
275 stale.is_empty(),
276 "hand-written breakpoints disagree with makeover_geometry::SizeClass.\n\n\
277 Allowed: {allowed:?}\n\
278 ({:?} come from SizeClass; {tuning_widths:?} were passed as tuning widths.)\n\n\
279 Stale:\n{}\n\n\
280 If a size class moved, update these to match. If one of these is a new\n\
281 tuning width inside the wide shell rather than a shell boundary, add it\n\
282 to the caller's tuning list with a note saying what it tunes.\n\n\
283 Best of all, make the rule dimensional so it needs no threshold: a grid\n\
284 wants repeat(auto-fit, minmax(<content floor>, 1fr)) and a size wants\n\
285 clamp(). A threshold is for what appears and disappears.",
286 allowed
287 .iter()
288 .filter(|px| !tuning_widths.contains(px))
289 .collect::<Vec<_>>(),
290 stale.join("\n")
291 );
292
293 for path in paths {
294 println!("cargo:rerun-if-changed={}", path.display());
295 }
296 }
297
298 /// A path as the frontend sees it, for an error a reader can act on.
299 fn display_name(frontend: &Path, path: &Path) -> String {
300 path.strip_prefix(frontend)
301 .unwrap_or(path)
302 .display()
303 .to_string()
304 }
305
306 /// Every width a hand-written media query is allowed to name.
307 ///
308 /// Read out of [`SizeClass::media_condition`] rather than typed, which is the
309 /// whole point: that is the one place the numbers come from, and a bump in
310 /// makeover-geometry has to reach the stylesheet through here.
311 fn allowed_widths(tuning_widths: &[u16]) -> Vec<u16> {
312 let mut widths: Vec<u16> = SizeClass::all()
313 .iter()
314 .flat_map(|c| media_widths(&c.media_condition()))
315 .collect();
316 widths.extend_from_slice(tuning_widths);
317 widths.sort_unstable();
318 widths.dedup();
319 widths
320 }
321
322 /// The pixel values in a media condition, in the order they appear.
323 fn media_widths(condition: &str) -> Vec<u16> {
324 let mut out = Vec::new();
325 let mut rest = condition;
326 while let Some(i) = rest.find("-width:") {
327 rest = &rest[i + "-width:".len()..];
328 let digits: String = rest
329 .trim_start()
330 .chars()
331 .take_while(char::is_ascii_digit)
332 .collect();
333 if let Ok(px) = digits.parse() {
334 out.push(px);
335 }
336 }
337 out
338 }
339
340 /// `(byte offset of the `@media`, the condition text before the `{`)`.
341 fn media_conditions(css: &str) -> Vec<(usize, &str)> {
342 let mut out = Vec::new();
343 let mut at = 0;
344 while let Some(i) = css[at..].find("@media") {
345 let start = at + i;
346 let after = start + "@media".len();
347 match css[after..].find('{') {
348 Some(j) => {
349 out.push((start, &css[after..after + j]));
350 at = after + j;
351 }
352 None => break,
353 }
354 }
355 out
356 }
357
358 /// `(byte offset, pixel value)` for every `(max-width: Npx)` in a JS source.
359 ///
360 /// The parentheses are the whole test, and they have to be: a media condition
361 /// is always parenthesized and a CSS declaration never is, so `'max-width:
362 /// 320px'` in an inline-style string is not a breakpoint and must not read as
363 /// one. goingson's shared-updater.js builds exactly that, and the first version
364 /// of this check failed the build on it.
365 fn js_widths(src: &str) -> Vec<(usize, u16)> {
366 let mut out = Vec::new();
367 for pat in ["(max-width:", "(min-width:"] {
368 let mut at = 0;
369 while let Some(i) = src[at..].find(pat) {
370 let start = at + i;
371 let rest = src[start + pat.len()..].trim_start();
372 let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
373 if let Ok(px) = digits.parse()
374 && rest[digits.len()..].starts_with("px)")
375 {
376 out.push((start, px));
377 }
378 at = start + pat.len();
379 }
380 }
381 out
382 }
383
384 /// Replace every `/* ... */` with spaces, so byte offsets still line up.
385 fn strip_block_comments(css: &str) -> String {
386 let bytes = css.as_bytes();
387 let mut out = String::with_capacity(css.len());
388 let mut i = 0;
389 while i < bytes.len() {
390 if bytes[i..].starts_with(b"/*") {
391 let end = css[i..].find("*/").map_or(bytes.len(), |j| i + j + 2);
392 for c in css[i..end].chars() {
393 out.push(if c == '\n' { '\n' } else { ' ' });
394 }
395 i = end;
396 } else {
397 let c = css[i..].chars().next().unwrap();
398 out.push(c);
399 i += c.len_utf8();
400 }
401 }
402 out
403 }
404
405 /// Fail the build if a hand-written stylesheet takes a property the generated
406 /// one already sets -- on the same class, or on an element that carries it.
407 ///
408 /// The generated sheet sits in `@layer makeover`. App CSS beats it whatever the
409 /// specificity, either by being unlayered or by sitting in a layer the app's
410 /// order statement puts after `makeover`, so an app declaration for a property
411 /// makeover already sets does not merge with it: it wins, silently, and the
412 /// design system's version of that component stops applying, and nothing looks.
413 ///
414 /// # Two passes, because a rule can carry no class
415 ///
416 /// The class pass is the original: an app `.button` against the generated
417 /// `.button`. It reads rules by the classes in their selectors, so a rule with
418 /// no class in it is invisible to it -- and `button { color: var(--content) }`
419 /// is exactly that. It sets the same property the generated `.button` sets, on
420 /// every described act in the app, and it took `.button[data-tone="danger"]`'s
421 /// tone with it: a destructive act rendered indistinguishable from an ordinary
422 /// one for months, with this check reporting nothing.
423 ///
424 /// The element pass closes it. `makeover_webview::vocabulary::ELEMENT_CLASSES`
425 /// says which generated classes an element can carry -- CSS cannot say it, and
426 /// the renderer can -- and a bare element rule taking a property the design
427 /// system sets on one of those classes is the same defect as the class case.
428 ///
429 /// Two things are not reported, both deliberately:
430 ///
431 /// - A scoped rule (`.page button`). It reaches the elements inside one
432 /// region rather than every one of them, so whether it lands on a described
433 /// act depends on where that act renders. The certain case is the one this
434 /// reads.
435 /// - A property the app names on the class itself, from a rule that outranks
436 /// the element rule. Both are the app's and both sit in the same layer, so
437 /// that one contest is settled by specificity, and what reaches the design
438 /// system is the class rule -- which the class pass has already, reported
439 /// or reviewed. The rank matters: `.field` does not beat
440 /// `input[type="text"]`, and a handoff written as the weaker of the two is
441 /// a remedy that looks written and is not.
442 ///
443 /// # Why properties and not class names
444 ///
445 /// A shared class name is not by itself a divergence, and the first run of this
446 /// check against goingson is what settled it: nine classes are shared and every
447 /// one is deliberate. `.badge` sets shape in the app and colour in the
448 /// generated sheet, and the app's own comment beside it reads "Fill, edge and
449 /// text colour come from the generated .badge in layout.css. Do not add
450 /// background, border or box-shadow here." That arrangement is correct, so a
451 /// check on names would have asked for it to be deleted. On properties, the
452 /// comment becomes the check.
453 ///
454 /// # The exception list
455 ///
456 /// `allowed` is `(class, property)` pairs this app has reviewed and kept.
457 /// Deciding which are legitimate here would need a selector matcher, and a check
458 /// that guesses wrong about specificity fails correct builds -- so the app
459 /// declares it instead, the same shape as quasi-webview's `RENDERER_OWN`.
460 ///
461 /// A reviewed pairing is a claim about who owns a property, and it expires when
462 /// the design system takes the property back.
463 ///
464 /// `allowed_elements` is the same thing one pass down: `(element, class,
465 /// property)` triples where a bare element rule reaching a generated class has
466 /// been read and kept.
467 ///
468 /// The remedy is usually neither list. A later layer can hand the property back
469 /// with `revert-layer`, which says "whatever the design system set here, keep
470 /// it" on the arms makeover actually paints, and that is a statement in the
471 /// stylesheet rather than a note in a build script. Handoffs are not reported by
472 /// either pass.
473 ///
474 /// A pair that stops colliding fails too. A licence nobody is using is where
475 /// the next real collision lands and reads as company.
476 ///
477 /// `frontend` is the directory holding `css/`. `generated` names the sheets
478 /// this crate writes, relative to `frontend/css`, which are skipped: the
479 /// generated file setting a generated property is the point.
480 ///
481 /// Emits `cargo:rerun-if-changed` for every file it read.
482 ///
483 /// # Panics
484 ///
485 /// If `frontend/css` cannot be read, if any hand-written sheet takes a
486 /// generated property without declaring it, or if a declared pair no longer
487 /// collides. A build script has nowhere useful to return an error to, and an
488 /// app quietly overriding its own design system is worse than a failed build.
489 pub fn check_vocabulary(
490 frontend: impl AsRef<Path>,
491 opts: &Emit,
492 generated: &[&str],
493 allowed: &[(&str, &str)],
494 allowed_elements: &[(&str, &str, &str)],
495 ) {
496 let frontend = frontend.as_ref();
497 let css = frontend.join("css");
498 let files: Vec<PathBuf> = files_with_extension(&css, "css")
499 .into_iter()
500 .filter(|p| {
501 let name = p.strip_prefix(&css).unwrap_or(p).display().to_string();
502 !generated.contains(&name.as_str())
503 })
504 .collect();
505 check_vocabulary_paths(&files, opts, Some(frontend), allowed, allowed_elements);
506 }
507
508 /// [`check_vocabulary`] against a named list of files rather than a tree.
509 ///
510 /// For a frontend whose generated and hand-written sheets share a directory, so
511 /// a directory scan has nothing to point at. Same trade as
512 /// [`check_breakpoints_files`]: the list is hand-maintained, and a stylesheet
513 /// nobody adds to it is unchecked rather than failing.
514 ///
515 /// # Panics
516 ///
517 /// As [`check_vocabulary`].
518 pub fn check_vocabulary_files<P: AsRef<Path>>(
519 paths: &[P],
520 opts: &Emit,
521 allowed: &[(&str, &str)],
522 allowed_elements: &[(&str, &str, &str)],
523 ) {
524 let paths: Vec<PathBuf> = paths.iter().map(|p| p.as_ref().to_path_buf()).collect();
525 check_vocabulary_paths(&paths, opts, None, allowed, allowed_elements);
526 }
527
528 /// The check itself. `root`, when given, is stripped from reported paths.
529 fn check_vocabulary_paths(
530 paths: &[PathBuf],
531 opts: &Emit,
532 root: Option<&Path>,
533 allowed: &[(&str, &str)],
534 allowed_elements: &[(&str, &str, &str)],
535 ) {
536 let generated =
537 makeover_webview::vocabulary::declarations_by_class(&makeover_webview::stylesheet(opts));
538 let mut clashes: Vec<String> = Vec::new();
539 let mut seen: Vec<(String, String)> = Vec::new();
540 let mut element_clashes: Vec<String> = Vec::new();
541 let mut element_seen: Vec<(String, String, String)> = Vec::new();
542
543 for path in paths {
544 println!("cargo::rerun-if-changed={}", path.display());
545 let raw = std::fs::read_to_string(path)
546 .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
547 let name = match root {
548 Some(root) => display_name(root, path),
549 None => path.display().to_string(),
550 };
551 // Read the app's sheet the same way the crate reads its own, or the two
552 // sides are not comparable.
553 let local = makeover_webview::vocabulary::declarations_by_class(&raw);
554 for (class, properties) in &local {
555 let Some(theirs) = generated.get(class) else {
556 continue;
557 };
558 for property in properties.intersection(theirs) {
559 seen.push((class.clone(), property.clone()));
560 if allowed.contains(&(class.as_str(), property.as_str())) {
561 continue;
562 }
563 clashes.push(format!(" {name} .{class} {{ {property} }}"));
564 }
565 }
566
567 // The second pass: a rule carrying no class at all, which the first one
568 // cannot see. What the app says about the class itself settles the
569 // pair, but only from a rule that outranks the element rule -- both are
570 // the app's and both are in the same layer, so this one contest is
571 // decided by specificity. `.field` does not beat `input[type="text"]`.
572 let mentioned = makeover_webview::vocabulary::mentions_by_class(&raw);
573 let by_element = makeover_webview::vocabulary::declarations_by_element(&raw);
574 for (element, properties) in &by_element {
575 for class in makeover_webview::vocabulary::classes_for_element(element, opts) {
576 let Some(theirs) = generated.get(&class) else {
577 continue;
578 };
579 for (property, rank) in properties {
580 if !theirs.contains(property) {
581 continue;
582 }
583 // A tie goes to the class rule: at equal specificity the
584 // later rule wins, and a remedy is written after the rule
585 // it remedies.
586 let spoken_for = mentioned
587 .get(&class)
588 .and_then(|properties| properties.get(property))
589 .is_some_and(|theirs| theirs >= rank);
590 if spoken_for {
591 continue;
592 }
593 element_seen.push((element.clone(), class.clone(), property.clone()));
594 if allowed_elements.contains(&(
595 element.as_str(),
596 class.as_str(),
597 property.as_str(),
598 )) {
599 continue;
600 }
601 element_clashes.push(format!(
602 " {name} {element} {{ {property} }} beats .{class} {{ {property} }}"
603 ));
604 }
605 }
606 }
607 }
608
609 assert!(
610 clashes.is_empty(),
611 "{} hand-written declaration(s) take a property the generated stylesheet \
612 already sets on the same class. App CSS wins over @layer makeover, \
613 whether by a later layer or by being unlayered, so each of these wins \
614 over the design system silently:\n{}\n\nDelete the declaration, or, if \
615 it is a deliberate pairing on a different selector arm, add \
616 (class, property) to this check's allowed list and say why beside it. \
617 Count the consumers before deciding a divergence is worth keeping.",
618 clashes.len(),
619 clashes.join("\n")
620 );
621
622 assert!(
623 element_clashes.is_empty(),
624 "{} hand-written element rule(s) take a property the generated \
625 stylesheet sets on a class that element carries. App CSS wins over \
626 @layer makeover, whether by a later layer or by being unlayered, so a \
627 described component rendered on one of these elements loses the \
628 design system's version of that property silently -- which is how a \
629 destructive act came to look like an ordinary one:\n{}\n\nHand the \
630 property back on the arms makeover paints \
631 (`.{{class}}:disabled {{ color: revert-layer }}`), scope the element \
632 rule so it stops reaching described markup, or add \
633 (element, class, property) to this check's allowed-elements list and \
634 say why beside it.",
635 element_clashes.len(),
636 element_clashes.join("\n")
637 );
638
639 let stale: Vec<&(&str, &str)> = allowed
640 .iter()
641 .filter(|(class, property)| {
642 !seen.contains(&((*class).to_string(), (*property).to_string()))
643 })
644 .collect();
645 assert!(
646 stale.is_empty(),
647 "the allowed list declares {stale:?}, which no longer collides with \
648 anything. Delete the entries: an exception nobody is using is where the \
649 next real collision lands and reads as company."
650 );
651
652 let stale: Vec<&(&str, &str, &str)> = allowed_elements
653 .iter()
654 .filter(|(element, class, property)| {
655 !element_seen.contains(&(
656 (*element).to_string(),
657 (*class).to_string(),
658 (*property).to_string(),
659 ))
660 })
661 .collect();
662 assert!(
663 stale.is_empty(),
664 "the allowed-elements list declares {stale:?}, which no longer collides \
665 with anything. Delete the entries: an exception nobody is using is \
666 where the next real collision lands and reads as company."
667 );
668 }
669
670 /// Warn when the generated vocabulary has grown dead, and fail when it grows
671 /// deader than the recorded high-water mark.
672 ///
673 /// A generated class no markup emits is a rule shipped to every user for
674 /// nothing, and the proportion was large when it was first measured: 42% of the
675 /// vocabulary unused in goingson, 67% in the MNW server, 84% in Balanced
676 /// Breakfast. Those are not failures on their own or no app would build. What
677 /// this converts is the direction: dead vocabulary becoming a number in a build
678 /// script means a change that worsens it stops being something somebody
679 /// notices.
680 ///
681 /// One-sided, the same shape as the MNW server's `frontend_globals` seal:
682 /// exceeding `high_water` fails, coming in under it warns and asks for the seal
683 /// to be lowered. A build that fails because dead CSS was deleted would teach
684 /// the wrong lesson.
685 ///
686 /// `markup` is every file that can carry a class: templates, `.js`, `.html`,
687 /// and any Rust that writes markup. A class is counted as used if its name
688 /// appears in any of them, which is deliberately generous. A stricter reading
689 /// would need to know how each app builds its class strings, and a check that
690 /// guesses wrong fails a correct build.
691 ///
692 /// # Panics
693 ///
694 /// If a listed file cannot be read, or if more classes are unused than
695 /// `high_water`.
696 pub fn check_vocabulary_use<P: AsRef<Path>>(markup: &[P], opts: &Emit, high_water: usize) {
697 let generated = makeover_webview::vocabulary::names(opts);
698 let mut haystack = String::new();
699 for path in markup {
700 let path = path.as_ref();
701 println!("cargo::rerun-if-changed={}", path.display());
702 haystack.push_str(
703 &std::fs::read_to_string(path)
704 .unwrap_or_else(|e| panic!("read {}: {e}", path.display())),
705 );
706 haystack.push('\n');
707 }
708
709 let unused: Vec<&String> = generated
710 .iter()
711 .filter(|class| !haystack.contains(class.as_str()))
712 .collect();
713
714 assert!(
715 unused.len() <= high_water,
716 "{} of {} generated classes are emitted by no markup, above the recorded {}. \
717 The vocabulary grew or the markup stopped using it:\n{}",
718 unused.len(),
719 generated.len(),
720 high_water,
721 unused
722 .iter()
723 .map(|c| format!(" .{c}"))
724 .collect::<Vec<_>>()
725 .join("\n")
726 );
727
728 if unused.len() < high_water {
729 println!(
730 "cargo::warning=dead makeover vocabulary is down to {} from a sealed {}; \
731 lower the seal so it cannot grow back",
732 unused.len(),
733 high_water
734 );
735 }
736 }
737
738 #[cfg(test)]
739 mod tests {
740 use super::*;
741
742 fn scratch(name: &str) -> PathBuf {
743 let dir =
744 std::env::temp_dir().join(format!("makeover-drift-{}-{name}", std::process::id()));
745 let _ = std::fs::remove_dir_all(&dir);
746 std::fs::create_dir_all(&dir).expect("create scratch");
747 dir
748 }
749
750 fn write(dir: &Path, name: &str, src: &str) {
751 if let Some(parent) = dir.join(name).parent() {
752 std::fs::create_dir_all(parent).unwrap();
753 }
754 std::fs::write(dir.join(name), src).unwrap();
755 }
756
757 fn declaring() -> String {
758 format!(
759 "const {CONST_NAME} = '{}';\n",
760 Density::Touch.media_condition()
761 )
762 }
763
764 #[test]
765 fn the_crates_own_string_passes() {
766 let dir = scratch("ok");
767 write(&dir, "touch.js", &declaring());
768 check_touch_density(&dir);
769 }
770
771 #[test]
772 #[should_panic(expected = "disagrees with makeover_geometry::Density")]
773 fn a_drifted_literal_fails() {
774 let dir = scratch("drift");
775 write(&dir, "touch.js", &declaring());
776 write(
777 &dir,
778 "haptics.js",
779 &format!("const {CONST_NAME} = '(pointer: coarse)';\n"),
780 );
781 check_touch_density(&dir);
782 }
783
784 #[test]
785 #[should_panic(expected = "device sniff")]
786 fn the_sniff_cannot_come_back() {
787 let dir = scratch("sniff");
788 write(&dir, "touch.js", &declaring());
789 write(&dir, "legacy.js", "if ('ontouchstart' in window) {}\n");
790 check_touch_density(&dir);
791 }
792
793 #[test]
794 #[should_panic(expected = "no TOUCH_DENSITY literal found")]
795 fn a_frontend_that_states_nothing_fails() {
796 let dir = scratch("empty");
797 write(&dir, "app.js", "export const x = 1;\n");
798 check_touch_density(&dir);
799 }
800
801 #[test]
802 fn a_use_site_is_not_a_declaration() {
803 // The const is read far more often than it is declared, and a read
804 // states no string. Counting one as a declaration would make the
805 // `found > 0` assertion pass on a frontend that only imports it.
806 let src =
807 format!("import {{ {CONST_NAME} }} from './touch.js';\nmatchMedia({CONST_NAME});\n");
808 assert!(touch_density_literals(&src).is_empty());
809 }
810
811 #[test]
812 fn nested_files_are_read() {
813 // The server keeps its scripts in subdirectories, and the nested half
814 // is the half most likely to be a copy.
815 let dir = scratch("nested");
816 write(&dir, "touch.js", &declaring());
817 write(&dir, "screens/legacy.js", "navigator.maxTouchPoints > 0;\n");
818 let files = js_files(&dir);
819 assert_eq!(files.len(), 2);
820 }
821
822 #[test]
823 fn a_non_js_file_is_ignored() {
824 let dir = scratch("nonjs");
825 write(&dir, "touch.js", &declaring());
826 write(&dir, "styles.css", "body { }\n");
827 assert_eq!(js_files(&dir).len(), 1);
828 }
829
830 fn frontend(name: &str) -> PathBuf {
831 let dir = scratch(name);
832 std::fs::create_dir_all(dir.join("css")).unwrap();
833 std::fs::create_dir_all(dir.join("js")).unwrap();
834 dir
835 }
836
837 /// A width every size class agrees is a boundary.
838 fn boundary() -> u16 {
839 SizeClass::Medium.min_px()
840 }
841
842 #[test]
843 fn the_crates_own_boundaries_pass() {
844 let dir = frontend("bp-ok");
845 write(
846 &dir,
847 "css/styles.css",
848 &format!("@media (min-width: {}px) {{ body {{ }} }}\n", boundary()),
849 );
850 check_breakpoints(&dir, &[]);
851 }
852
853 #[test]
854 #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
855 fn a_stale_css_width_fails() {
856 let dir = frontend("bp-css");
857 write(&dir, "css/styles.css", "@media (max-width: 768px) { }\n");
858 check_breakpoints(&dir, &[]);
859 }
860
861 #[test]
862 #[should_panic(expected = "disagree with makeover_geometry::SizeClass")]
863 fn a_stale_js_width_fails() {
864 let dir = frontend("bp-js");
865 write(&dir, "js/shell.js", "matchMedia('(max-width: 768px)');\n");
866 check_breakpoints(&dir, &[]);
867 }
868
869 #[test]
870 fn a_declared_tuning_width_passes() {
871 let dir = frontend("bp-tuning");
872 write(&dir, "css/styles.css", "@media (min-width: 1400px) { }\n");
873 check_breakpoints(&dir, &[1400]);
874 }
875
876 #[test]
877 fn a_width_in_a_comment_is_prose() {
878 // The note explaining which breakpoint used to be here is not a rule,
879 // and failing a build on documentation would teach people to delete it.
880 let dir = frontend("bp-comment");
881 write(
882 &dir,
883 "css/styles.css",
884 "/* was @media (max-width: 768px) until the size classes landed */\n",
885 );
886 check_breakpoints(&dir, &[]);
887 }
888
889 #[test]
890 fn an_unparenthesized_width_is_not_a_breakpoint() {
891 // A JS string building an inline style states `max-width: 320px` with
892 // no parentheses. It is a declaration, not a query, and the first
893 // version of this check failed the build on one.
894 let dir = frontend("bp-inline");
895 write(
896 &dir,
897 "js/style.js",
898 "el.style.cssText = 'max-width: 320px; display: block';\n",
899 );
900 check_breakpoints(&dir, &[]);
901 }
902
903 #[test]
904 fn nested_css_is_read() {
905 // Same argument as the touch check: the nested half is the half most
906 // likely to be a copy.
907 let dir = frontend("bp-nested");
908 write(
909 &dir,
910 "css/screens/detail.css",
911 "@media (max-width: 768px) { }\n",
912 );
913 let found = std::panic::catch_unwind(|| check_breakpoints(&dir, &[]));
914 assert!(found.is_err(), "a nested stylesheet must be scanned");
915 }
916
917 #[test]
918 fn a_named_list_is_checked() {
919 let dir = frontend("bp-list");
920 write(&dir, "css/style.css", "@media (max-width: 768px) { }\n");
921 let listed = dir.join("css/style.css");
922 let err =
923 std::panic::catch_unwind(|| check_breakpoints_files(&[&listed], &[])).unwrap_err();
924 let msg = err.downcast_ref::<String>().expect("String payload");
925 assert!(msg.contains("style.css:1"), "got: {msg}");
926 }
927
928 #[test]
929 #[should_panic(expected = "read ")]
930 fn a_listed_file_that_is_gone_fails() {
931 // The list is hand-maintained, so a path that stopped existing is a
932 // check quietly covering less than it claims. Louder than skipping it.
933 let dir = frontend("bp-missing");
934 check_breakpoints_files(&[dir.join("css/never-written.css")], &[]);
935 }
936
937 #[test]
938 fn a_listed_js_file_is_parsed_as_script() {
939 // The unparenthesized-declaration rule is what separates the two, and
940 // picking the parser off the extension is the whole difference.
941 let dir = frontend("bp-list-js");
942 write(
943 &dir,
944 "js/style.js",
945 "el.style.cssText = 'max-width: 320px';\n",
946 );
947 check_breakpoints_files(&[dir.join("js/style.js")], &[]);
948 }
949
950 #[test]
951 fn the_error_names_the_file_and_line() {
952 let dir = frontend("bp-message");
953 write(
954 &dir,
955 "css/styles.css",
956 "body { }\n@media (max-width: 768px) { }\n",
957 );
958 let err = std::panic::catch_unwind(|| check_breakpoints(&dir, &[])).unwrap_err();
959 let msg = err
960 .downcast_ref::<String>()
961 .expect("panic payload is a String");
962 assert!(msg.contains("css/styles.css:2"), "got: {msg}");
963 }
964
965 #[test]
966 fn a_rule_restating_a_generated_class_fails_and_names_it() {
967 let dir = scratch("vocab-clash");
968 // `.card` is makeover's. An app rule for it beats the generated one,
969 // because app CSS is unlayered and the generated sheet is not.
970 write(
971 &dir,
972 "css/styles.css",
973 "body { color: red; }\n.card { box-shadow: none; }\n",
974 );
975 let err =
976 std::panic::catch_unwind(|| check_vocabulary(&dir, &Emit::default(), &[], &[], &[]))
977 .unwrap_err();
978 let msg = err
979 .downcast_ref::<String>()
980 .expect("panic payload is a String");
981 assert!(msg.contains(".card"), "got: {msg}");
982 assert!(msg.contains("box-shadow"), "got: {msg}");
983 assert!(msg.contains("css/styles.css"), "got: {msg}");
984 }
985
986 #[test]
987 fn an_app_class_of_its_own_is_left_alone() {
988 let dir = scratch("vocab-clean");
989 write(
990 &dir,
991 "css/styles.css",
992 ".task-list-container { overflow: auto; }\n.day-plan-slot { height: 1rem; }\n",
993 );
994 check_vocabulary(&dir, &Emit::default(), &[], &[], &[]);
995 }
996
997 #[test]
998 fn the_generated_sheet_is_skipped_rather_than_reported_against_itself() {
999 let dir = scratch("vocab-generated");
1000 let opts = Emit::default();
1001 write(&dir, "css/layout.css", &makeover_webview::stylesheet(&opts));
1002 // Without the skip this is the loudest failure possible: every class in
1003 // the vocabulary, reported as a clash with the vocabulary.
1004 check_vocabulary(&dir, &opts, &["layout.css"], &[], &[]);
1005 }
1006
1007 #[test]
1008 fn a_prefixed_app_is_checked_against_its_own_prefix() {
1009 let dir = scratch("vocab-prefix");
1010 let opts = Emit {
1011 class_prefix: "mo-",
1012 ..Emit::default()
1013 };
1014 // Bare `.card` is the app's own class once the generated sheet writes
1015 // `.mo-card`, so this has to pass.
1016 write(&dir, "css/styles.css", ".card { box-shadow: none; }\n");
1017 check_vocabulary(&dir, &opts, &[], &[], &[]);
1018
1019 let dir = scratch("vocab-prefix-clash");
1020 write(&dir, "css/styles.css", ".mo-card { box-shadow: none; }\n");
1021 assert!(std::panic::catch_unwind(|| check_vocabulary(&dir, &opts, &[], &[], &[])).is_err());
1022 }
1023
1024 #[test]
1025 fn a_class_shared_without_a_shared_property_is_left_alone() {
1026 let dir = scratch("vocab-additive");
1027 // What goingson actually does: the generated `.badge` sets the text
1028 // colour and the app sets the shape. Same class, no argument.
1029 write(
1030 &dir,
1031 "css/styles.css",
1032 ".badge { padding: 2px; border-radius: 3px; font-weight: 600; }\n",
1033 );
1034 check_vocabulary(&dir, &Emit::default(), &[], &[], &[]);
1035 }
1036
1037 #[test]
1038 fn a_reviewed_pair_passes_and_stops_passing_when_it_stops_colliding() {
1039 let dir = scratch("vocab-allowed");
1040 write(&dir, "css/styles.css", ".card { box-shadow: none; }\n");
1041 check_vocabulary(&dir, &Emit::default(), &[], &[("card", "box-shadow")], &[]);
1042
1043 // The same licence against a sheet that no longer collides has to fail,
1044 // or the list only ever grows.
1045 let dir = scratch("vocab-allowed-stale");
1046 write(&dir, "css/styles.css", ".card { padding: 2px; }\n");
1047 let err = std::panic::catch_unwind(|| {
1048 check_vocabulary(&dir, &Emit::default(), &[], &[("card", "box-shadow")], &[]);
1049 })
1050 .unwrap_err();
1051 let msg = err
1052 .downcast_ref::<String>()
1053 .expect("panic payload is a String");
1054 assert!(msg.contains("no longer collides"), "got: {msg}");
1055 }
1056
1057 #[test]
1058 fn an_element_rule_clobbering_a_generated_class_fails_and_names_all_three() {
1059 let dir = scratch("vocab-element");
1060 // The defect that shipped for months: no class in the selector, so the
1061 // class pass sees nothing, and every described act in the app takes the
1062 // app's bevel instead of the design system's.
1063 write(&dir, "css/styles.css", "select { box-shadow: none; }\n");
1064 let err =
1065 std::panic::catch_unwind(|| check_vocabulary(&dir, &Emit::default(), &[], &[], &[]))
1066 .unwrap_err();
1067 let msg = err
1068 .downcast_ref::<String>()
1069 .expect("panic payload is a String");
1070 assert!(msg.contains("select {"), "got: {msg}");
1071 assert!(msg.contains(".field"), "got: {msg}");
1072 assert!(msg.contains("box-shadow"), "got: {msg}");
1073 assert!(msg.contains("css/styles.css"), "got: {msg}");
1074 }
1075
1076 #[test]
1077 fn a_handoff_on_the_class_is_the_remedy_and_reads_as_one() {
1078 let dir = scratch("vocab-element-handoff");
1079 // What a consumer writes instead of an exception: the element rule
1080 // stays, and a later layer gives the property back on the class. The
1081 // check has to read that as settled or the remedy fails the build it
1082 // was written to fix.
1083 write(
1084 &dir,
1085 "css/styles.css",
1086 "select { box-shadow: none; }\n.field { box-shadow: revert-layer; }\n",
1087 );
1088 check_vocabulary(&dir, &Emit::default(), &[], &[], &[]);
1089 }
1090
1091 #[test]
1092 fn a_property_the_app_states_on_the_class_is_not_the_element_rules_doing() {
1093 let dir = scratch("vocab-element-spoken-for");
1094 // Within the app's own sheet the class rule outranks the bare element
1095 // rule, so what reaches the design system is `.button`, not `button`.
1096 // The class pass has that pair -- here as a reviewed one -- and
1097 // reporting it twice would ask for two remedies for one collision.
1098 write(
1099 &dir,
1100 "css/styles.css",
1101 "select { box-shadow: none; }\n.field { box-shadow: none; }\n",
1102 );
1103 check_vocabulary(&dir, &Emit::default(), &[], &[("field", "box-shadow")], &[]);
1104 }
1105
1106 #[test]
1107 fn a_handoff_that_loses_to_the_rule_it_remedies_is_not_a_remedy() {
1108 let dir = scratch("vocab-element-weak-handoff");
1109 // The shape that reads as fixed and is not: both rules are the app's
1110 // and both are in the same layer, so the state on the element rule
1111 // decides, and the described field keeps the app's sunken fill.
1112 write(
1113 &dir,
1114 "css/styles.css",
1115 "select:focus { box-shadow: none; }\n.field { box-shadow: revert-layer; }\n",
1116 );
1117 let err =
1118 std::panic::catch_unwind(|| check_vocabulary(&dir, &Emit::default(), &[], &[], &[]))
1119 .unwrap_err();
1120 let msg = err
1121 .downcast_ref::<String>()
1122 .expect("panic payload is a String");
1123 assert!(msg.contains(".field"), "got: {msg}");
1124
1125 // Written to win, it is.
1126 let dir = scratch("vocab-element-strong-handoff");
1127 write(
1128 &dir,
1129 "css/styles.css",
1130 "select:focus { box-shadow: none; }\nselect.field { box-shadow: revert-layer; }\n",
1131 );
1132 check_vocabulary(&dir, &Emit::default(), &[], &[], &[]);
1133 }
1134
1135 #[test]
1136 fn a_scoped_rule_is_not_read_as_an_element_rule() {
1137 let dir = scratch("vocab-element-scoped");
1138 // It reaches the buttons inside one region rather than every button, so
1139 // whether it lands on a described act depends on where that act
1140 // renders. Failing the build on a guess is the worse error.
1141 write(
1142 &dir,
1143 "css/styles.css",
1144 ".wizard select { box-shadow: none; }\n",
1145 );
1146 check_vocabulary(&dir, &Emit::default(), &[], &[], &[]);
1147 }
1148
1149 #[test]
1150 fn an_element_the_design_system_never_renders_onto_is_left_alone() {
1151 let dir = scratch("vocab-element-unpaired");
1152 // `.card` is a container: no generated class sits on a `<footer>`, so
1153 // there is nothing for this rule to take.
1154 write(&dir, "css/styles.css", "footer { box-shadow: none; }\n");
1155 check_vocabulary(&dir, &Emit::default(), &[], &[], &[]);
1156 }
1157
1158 #[test]
1159 fn a_reviewed_element_pairing_passes_and_stops_passing_when_it_stops_colliding() {
1160 let dir = scratch("vocab-element-allowed");
1161 write(&dir, "css/styles.css", "select { box-shadow: none; }\n");
1162 check_vocabulary(
1163 &dir,
1164 &Emit::default(),
1165 &[],
1166 &[],
1167 &[("select", "field", "box-shadow")],
1168 );
1169
1170 // And the same licence against a sheet that no longer collides fails,
1171 // for the reason the class list's does.
1172 let dir = scratch("vocab-element-allowed-stale");
1173 write(&dir, "css/styles.css", "select { padding: 2px; }\n");
1174 let err = std::panic::catch_unwind(|| {
1175 check_vocabulary(
1176 &dir,
1177 &Emit::default(),
1178 &[],
1179 &[],
1180 &[("select", "field", "box-shadow")],
1181 );
1182 })
1183 .unwrap_err();
1184 let msg = err
1185 .downcast_ref::<String>()
1186 .expect("panic payload is a String");
1187 assert!(msg.contains("no longer collides"), "got: {msg}");
1188 }
1189
1190 #[test]
1191 fn dead_vocabulary_above_the_seal_fails_and_below_it_passes() {
1192 let dir = scratch("vocab-seal");
1193 let opts = Emit::default();
1194 let all = makeover_webview::vocabulary::names(&opts).len();
1195 // Markup naming nothing: every class is unused.
1196 write(&dir, "index.html", "<div></div>\n");
1197 let markup = [dir.join("index.html")];
1198
1199 check_vocabulary_use(&markup, &opts, all);
1200 assert!(
1201 std::panic::catch_unwind(|| check_vocabulary_use(&markup, &opts, all - 1)).is_err(),
1202 "a vocabulary deader than the seal has to fail"
1203 );
1204 }
1205
1206 #[test]
1207 fn both_quote_styles_read() {
1208 let want = Density::Touch.media_condition();
1209 for q in ['\'', '"'] {
1210 let src = format!("const {CONST_NAME} = {q}{want}{q};\n");
1211 let found = touch_density_literals(&src);
1212 assert_eq!(found.len(), 1);
1213 assert_eq!(found[0].1, want);
1214 }
1215 }
1216 }
1217