makeover_build/lib.rs
1//! Build-script support for the make-family design system.
2//!
3//! <!-- wiki: makeover-geometry -->
4//!
5//! Every consumer materialises the same generated files from a `build.rs`.
6//! This is that code, once.
7//!
8//! # Density
9//!
10//! [`geometry_css`] keys the touch preset on capability: touch hangs off "not
11//! a fine, hovering pointer" and never off a user-agent string or a
12//! breakpoint. An app with a manual override passes the selector it sets to
13//! `explicit_touch`.
14//!
15//! # Why these files are generated rather than checked in
16//!
17//! Tauri's resource globs are read by its CLI against the crate directory, so
18//! they cannot point into a registry checkout or `OUT_DIR`. Materialising into
19//! the crate keeps the source crate authoritative without vendoring a second
20//! copy that drifts. Every path written here is expected to be gitignored.
21//!
22//! # The other half: what is checked rather than written
23//!
24//! A consumer's frontend is not all generated. The stylesheet and the scripts
25//! are hand-written and state some of the same facts the generated files ask
26//! the crates for, so they can drift where a generated file cannot. [`drift`]
27//! holds the checks that keep them honest, and they are assertions rather than
28//! substitutions on purpose: a file that has to be generated to be correct
29//! stops being readable on its own.
30
31#![forbid(unsafe_code)]
32
33pub mod drift;
34
35use std::path::Path;
36
37pub use drift::{Allow, Breakpoints, Vocabulary, check_touch_density, check_vocabulary_use};
38
39/// Re-exported so a consumer's `build.rs` needs one dependency rather than
40/// three. Nothing here wraps it; the emitter's options are the emitter's.
41pub use makeover_webview::Emit;
42
43/// The filenames [`typography_css`]'s `@font-face` rules fetch.
44///
45/// Re-exported for the same reason as [`Emit`], and load-bearing for a further
46/// one: the consumer's own build script writes those two files, so the emitter
47/// and the writer have to agree on the name. Through this they agree on a
48/// constant rather than on a string typed in two repositories.
49pub use makeover::{WEBFONT_MONO_FILE, WEBFONT_SANS_FILE};
50
51/// Layer 0 of the font model, re-exported for the same one-dependency reason.
52///
53/// A build script composing an override needs all four names and has no other
54/// reason to depend on `makeover` directly.
55pub use makeover::{FontFace, FontOverride, FontSlot, Typography};
56
57/// Write only when the bytes differ, so a generated file does not invalidate
58/// the build script that generated it.
59///
60/// Every emitter here writes into a directory the drift checks also read, and
61/// cargo compares a watched file's mtime against the build script's own
62/// `output`. An unconditional write moves that mtime on every run, so every run
63/// becomes the reason for the next one and the script runs on every build.
64///
65/// A read before each write costs microseconds, and the common
66/// case is that nothing changed: these files are a pure function of the crate
67/// version and the `Emit` options.
68fn write_if_changed(path: &Path, contents: &str, what: &str) {
69 if std::fs::read_to_string(path).is_ok_and(|existing| existing == contents) {
70 return;
71 }
72 std::fs::write(path, contents).unwrap_or_else(|error| panic!("write {what}: {error}"));
73}
74
75/// Write the themes `makeover` ships into `dir`, as `<id>.toml`.
76///
77/// Clears stale `.toml` files first, so a theme removed or renamed upstream
78/// does not linger in the bundle from a previous build. Omitting that step
79/// shows up as a theme that will not go away.
80///
81/// # Panics
82///
83/// If the directory cannot be created, read, or written. A build script has
84/// nowhere useful to return an error to, and a half-materialised theme set is
85/// worse than a failed build.
86pub fn themes(dir: impl AsRef<Path>) {
87 let dir = dir.as_ref();
88 std::fs::create_dir_all(dir).expect("create themes dir");
89
90 let shipped: std::collections::BTreeSet<String> = makeover::embedded_themes()
91 .map(|(id, _)| id.to_string())
92 .collect();
93
94 // Only what upstream no longer ships. Clearing the directory first and
95 // writing every theme back was the same thing by result and not by mtime:
96 // it left `write_if_changed` nothing to compare against, so every build
97 // rewrote every theme and the script invalidated itself through them.
98 for entry in std::fs::read_dir(dir).expect("read themes dir").flatten() {
99 let path = entry.path();
100 if path.extension().is_some_and(|e| e == "toml")
101 && !path
102 .file_stem()
103 .and_then(|stem| stem.to_str())
104 .is_some_and(|stem| shipped.contains(stem))
105 {
106 std::fs::remove_file(&path).expect("remove stale theme");
107 }
108 }
109
110 for (id, source) in makeover::embedded_themes() {
111 write_if_changed(&dir.join(format!("{id}.toml")), source, "theme");
112 }
113}
114
115/// Write `makeover-webview`'s component stylesheet to `path`.
116///
117/// Baked at build time rather than applied from JS the way the intent layer
118/// is, because composition never changes at runtime: no theme may reach it, so
119/// there is nothing to re-apply and no second pass over `:root` to pay for on
120/// load.
121///
122/// # Panics
123///
124/// If the file cannot be written.
125pub fn layout_css(path: impl AsRef<Path>, opts: &makeover_webview::Emit) {
126 write_if_changed(
127 path.as_ref(),
128 &makeover_webview::stylesheet(opts),
129 "layout css",
130 );
131}
132
133/// Write `makeover-geometry`'s spacing layer, with its canonical density
134/// selection, to `path`.
135///
136/// The policy is the crate's, not this one's: touch hangs off
137/// the negation of a fine, hovering pointer because density is a capability rather
138/// than a device or a width, and `explicit_touch` names a selector an app sets
139/// when the user has chosen. See [`makeover_geometry::density_css`]. All this
140/// adds is the generated-file banner and the write.
141///
142/// Both spacing axes land here, in the order the crate defines them.
143/// [`makeover_geometry::size_class_css`] follows the density block because it
144/// is the narrower claim: density says what is pointing at the screen, size
145/// class says how much screen there is, and on a compact window the two shells
146/// tighten regardless of which density selected them.
147///
148/// # Panics
149///
150/// If the file cannot be written.
151pub fn geometry_css(path: impl AsRef<Path>, explicit_touch: Option<&str>) {
152 let mut css = String::from(
153 "/* Generated by makeover-build from makeover-geometry. Do not edit.\n \
154 Spacing is named by relationship, not by size. Touch density is a\n \
155 capability question: a narrow desktop window still has a pointer, a\n \
156 full-width tablet still has a finger. Window width is the separate\n \
157 question below it: on a compact window the two shells tighten. */\n",
158 );
159 css.push_str(&makeover_geometry::density_css(explicit_touch));
160 css.push('\n');
161 css.push_str(&makeover_geometry::size_class_css());
162 write_if_changed(path.as_ref(), &css, "geometry css");
163}
164
165/// Write `makeover-timing`'s time axis, and the motion-off block that rides
166/// with it, to `path`.
167///
168/// The third generated axis, and it arrives the same way the spacing one does:
169/// a consumer that calls this gets `--timing-*`, `--motion-fade` and
170/// `--cadence-activity` without stating a number anywhere. All this adds is the
171/// banner and the write; `makeover_timing::timing_css` is the whole file and
172/// already wraps itself in [`makeover_geometry::CSS_LAYER`].
173///
174/// # Its own file, for the reason geometry has its own file
175///
176/// One generated file per crate, named for the axis it carries. Time is not a
177/// narrower claim about space the way size class is about density, so folding
178/// it into `geometry.css` would leave a file whose banner names one crate and
179/// whose contents come from two. The cost is a fourth `<link>` in the consumer,
180/// which is the cost the family already pays three times.
181///
182/// # The `prefers-reduced-motion` block is not optional
183///
184/// `makeover_timing::timing_css` emits the `:root` values and then a media
185/// block overriding two of them. Both land here, in that order, because they
186/// are one statement: a sheet carrying only the values animates at every rung
187/// for a reader who asked it not to, and does it silently.
188///
189/// # Panics
190///
191/// If the file cannot be written.
192pub fn timing_css(path: impl AsRef<Path>) {
193 let mut css = String::from(
194 "/* Generated by makeover-build from makeover-timing. Do not edit.\n \
195 A duration is named by what it is waiting for; the number follows.\n \
196 Three axes: how long a state lasts, how long a change takes, and how\n \
197 often a repeating mark repeats. The reduced-motion block below zeroes\n \
198 the last two and leaves the waits alone. A reader asking for less\n \
199 motion has not asked for a notice to leave early. */\n",
200 );
201 css.push_str(&makeover_timing::timing_css());
202 write_if_changed(path.as_ref(), &css, "timing css");
203}
204
205/// Write the house typography layer to `path`: the two `@font-face` rules and
206/// the two tokens they back.
207///
208/// `font_url` is the directory the consumer serves its fonts from, without a
209/// trailing slash: `/static/fonts` on the MNW server, `fonts` for a Tauri
210/// frontend loading relative to its index.
211///
212/// Generated rather than hand-written for the same reason the spacing layer is:
213/// the facts are the crates' and stating them per app is how three apps came to
214/// hold three different answers to `--font-mono`. It is a separate file from
215/// the layout stylesheet because `@font-face` rules take no part in the
216/// cascade and a consumer may need to load them ahead of a layer order it
217/// declares elsewhere.
218///
219/// # The consumer still has to put the faces there
220///
221/// This writes the CSS that fetches `QuasiMono.woff2` and `QuasiBody.woff2`; it
222/// does not write the fonts. It cannot: they are cut by `quasi-type`, which is
223/// `publish = false`, and this crate is on crates.io. A consumer takes
224/// quasi-type as a git dependency in its own `build.rs` and calls
225/// `quasi_type::cut`, the way `shop-font` does, writing each slot's woff2 under
226/// [`makeover::WEBFONT_MONO_FILE`] and [`makeover::WEBFONT_SANS_FILE`].
227///
228/// # Panics
229///
230/// If the file cannot be written.
231pub fn typography_css(path: impl AsRef<Path>, font_url: &str) {
232 typography_css_from(path, &makeover::Typography::house(font_url));
233}
234
235/// [`typography_css`], for a product that overrides a slot.
236///
237/// Layer 0 of the font model. A product with a brand face declares it here,
238/// once, and the generated sheet carries both the `@font-face` and the token,
239/// which replaces the hand-maintained `@font-face` block plus a
240/// `--font-heading` nothing else in the tree knew about:
241///
242/// ```no_run
243/// use makeover_build::{FontFace, FontOverride, FontSlot, Typography};
244///
245/// makeover_build::typography_css_from(
246/// "static/typography.css",
247/// &Typography::house("/static/fonts").with_override(
248/// FontOverride::new(FontSlot::Display, "\"Young Serif\", serif")
249/// .with_face(FontFace::new("Young Serif", ["ysrf.woff2", "ysrf.ttf"])),
250/// ),
251/// );
252/// ```
253///
254/// The product still ships the face itself, exactly as it does for the house
255/// two: this writes the CSS that fetches it and cannot produce a font.
256///
257/// # Panics
258///
259/// If the file cannot be written.
260pub fn typography_css_from(path: impl AsRef<Path>, typography: &makeover::Typography) {
261 let mut css = String::from(
262 "/* Generated by makeover-build from makeover. Do not edit.\n \
263 Two needs, two names, then a system generic. The faces are cut by\n \
264 quasi-type from Atkinson Hyperlegible plus the house glyph set, and\n \
265 both are variable over wght 200-800 in one file, which is why the\n \
266 @font-face rules name the range. The mono face opens at ExtraLight.\n \
267 A third token here is this product's own brand face, declared as an\n \
268 override in its build script. */\n\n",
269 );
270 css.push_str(&typography.css());
271 write_if_changed(path.as_ref(), &css, "typography css");
272}
273
274/// All the generated files at the layout every Tauri consumer already uses:
275/// `themes/` beside the manifest, and
276/// `frontend/css/{geometry,timing,layout,typography}.css` under it.
277///
278/// Pass `env!("CARGO_MANIFEST_DIR")`. Consumers that want different paths call
279/// [`themes`], [`layout_css`] and [`typography_css`] directly.
280///
281/// The font URL is `../fonts`. A `url()` in a stylesheet resolves against the
282/// stylesheet rather than the page, so from `frontend/css/typography.css` that
283/// is `frontend/fonts`: the one layout a Tauri app has, since its frontend is
284/// served from its own directory.
285///
286/// # Panics
287///
288/// If any file cannot be written.
289pub fn tauri_frontend(
290 manifest_dir: impl AsRef<Path>,
291 opts: &makeover_webview::Emit,
292 explicit_touch: Option<&str>,
293) {
294 tauri_frontend_with(
295 manifest_dir,
296 opts,
297 explicit_touch,
298 &makeover::Typography::house("../fonts"),
299 );
300}
301
302/// [`tauri_frontend`], for a product that overrides a font slot.
303///
304/// Separate rather than a fourth parameter, so an app with no font override
305/// does not have to name the house typography.
306///
307/// The base URL is the caller's: pass `Typography::house("../fonts")` unless
308/// the app serves fonts from somewhere other than the one layout a Tauri
309/// frontend has.
310///
311/// # Panics
312///
313/// If any file cannot be written.
314pub fn tauri_frontend_with(
315 manifest_dir: impl AsRef<Path>,
316 opts: &makeover_webview::Emit,
317 explicit_touch: Option<&str>,
318 typography: &makeover::Typography,
319) {
320 let root = manifest_dir.as_ref();
321 let css = root.join("frontend").join("css");
322 themes(root.join("themes"));
323 geometry_css(css.join("geometry.css"), explicit_touch);
324 // Beside geometry rather than after layout: both are value files the
325 // component sheet reads, and a consumer's `<link>` order follows this one.
326 timing_css(css.join("timing.css"));
327 layout_css(css.join("layout.css"), opts);
328 typography_css_from(css.join("typography.css"), typography);
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334
335 /// A scratch directory keyed by process id, so a parallel test run does
336 /// not collide. No timestamp: the pid is enough and is deterministic
337 /// within a run.
338 fn scratch(name: &str) -> std::path::PathBuf {
339 let dir =
340 std::env::temp_dir().join(format!("makeover-build-{}-{name}", std::process::id()));
341 let _ = std::fs::remove_dir_all(&dir);
342 std::fs::create_dir_all(&dir).expect("create scratch");
343 dir
344 }
345
346 #[test]
347 fn themes_are_written_one_file_per_id() {
348 let dir = scratch("themes");
349 themes(&dir);
350 let count = std::fs::read_dir(&dir).unwrap().count();
351 assert_eq!(count, makeover::embedded_themes().count());
352 assert!(count > 0, "makeover ships no themes?");
353 }
354
355 #[test]
356 fn a_theme_removed_upstream_does_not_linger() {
357 // The detail that makes this worth sharing rather than retyping.
358 let dir = scratch("stale");
359 std::fs::write(dir.join("gone-upstream.toml"), "# stale").unwrap();
360 themes(&dir);
361 assert!(!dir.join("gone-upstream.toml").exists());
362 }
363
364 #[test]
365 fn a_second_run_touches_nothing() {
366 // The property the whole write-if-changed pass exists for: a build
367 // script that rewrites its own outputs invalidates itself, and cargo
368 // then reruns it on every build whatever changed. Asserted on mtime
369 // rather than on content, because content was always correct; it was
370 // the mtime that was the bug.
371 let dir = scratch("idempotent");
372 themes(&dir);
373 let before: Vec<_> = std::fs::read_dir(&dir)
374 .unwrap()
375 .flatten()
376 .map(|e| (e.path(), e.metadata().unwrap().modified().unwrap()))
377 .collect();
378 assert!(!before.is_empty(), "themes() wrote nothing to compare");
379
380 themes(&dir);
381 for (path, was) in before {
382 let now = std::fs::metadata(&path).unwrap().modified().unwrap();
383 assert_eq!(
384 was,
385 now,
386 "{} was rewritten by a second run with nothing changed",
387 path.display()
388 );
389 }
390 }
391
392 #[test]
393 fn a_non_theme_file_is_left_alone() {
394 // Only .toml is cleared, so a README or a .gitignore in the bundle
395 // directory survives a rebuild.
396 let dir = scratch("keep");
397 std::fs::write(dir.join("README.md"), "not a theme").unwrap();
398 themes(&dir);
399 assert!(dir.join("README.md").exists());
400 }
401
402 #[test]
403 fn the_stylesheet_lands_and_names_no_colour() {
404 let dir = scratch("css");
405 let path = dir.join("layout.css");
406 layout_css(&path, &makeover_webview::Emit::default());
407 let css = std::fs::read_to_string(&path).unwrap();
408 assert!(css.contains("--bevel-raised"));
409 assert!(
410 !css.contains('#'),
411 "a colour literal reached a build output"
412 );
413 }
414
415 #[test]
416 fn the_typography_file_declares_the_faces_before_the_tokens_that_name_them() {
417 // The vocabulary itself is tested in makeover. What is this crate's
418 // job is that both halves reach one file, in an order that works: a
419 // `@font-face` may follow its use in the cascade, but reading the file
420 // is how anyone finds out a face is fetched at all.
421 let dir = scratch("typography");
422 let path = dir.join("typography.css");
423 typography_css(&path, "/static/fonts");
424 let css = std::fs::read_to_string(&path).unwrap();
425
426 assert!(css.starts_with("/* Generated by makeover-build"));
427 assert!(
428 css.find("@font-face").unwrap() < css.find(":root").unwrap(),
429 "the tokens come first, so the file reads as a stack with no ground"
430 );
431 assert!(css.contains("url(\"/static/fonts/QuasiMono.woff2\")"));
432 assert!(css.contains("--font-sans: \"Quasi Body\", sans-serif;"));
433
434 // Not a cascade layer. `@font-face` takes no part in the cascade and a
435 // consumer may need these rules ahead of a layer order it declares
436 // elsewhere, so wrapping this file in one would be a silent trap.
437 assert!(!css.contains("@layer"));
438 }
439
440 #[test]
441 fn an_overridden_slot_reaches_the_same_file_as_the_house_two() {
442 // Layer 0's whole point: the brand face stops being a hand-maintained
443 // `@font-face` in the app's own stylesheet and becomes a line in the
444 // generated one, beside the slots it sits next to.
445 let dir = scratch("typography-override");
446 let path = dir.join("typography.css");
447 typography_css_from(
448 &path,
449 &Typography::house("/static/fonts").with_override(
450 FontOverride::new(FontSlot::Display, "\"Young Serif\", serif")
451 .with_face(FontFace::new("Young Serif", ["ysrf.woff2", "ysrf.ttf"])),
452 ),
453 );
454 let css = std::fs::read_to_string(&path).unwrap();
455
456 // `@font-face {`, not `@font-face`: the header comment names the
457 // at-rule too, and counting that would make this pass for the wrong
458 // reason the day the comment is reworded.
459 assert_eq!(css.matches("@font-face {").count(), 3);
460 assert!(css.contains("--font-display: \"Young Serif\", serif;"));
461 assert!(css.contains("--font-mono: \"Quasi Mono\", monospace;"));
462 assert!(css.contains("url(\"/static/fonts/ysrf.ttf\") format(\"truetype\")"));
463 assert!(!css.contains("@layer"));
464 }
465
466 #[test]
467 fn the_default_tauri_layout_is_the_house_layer_and_nothing_else() {
468 // `tauri_frontend` delegating through `tauri_frontend_with` must not
469 // change a byte for the three consumers already calling it.
470 let dir = scratch("tauri-default");
471 let plain = dir.join("plain.css");
472 let house = dir.join("house.css");
473 typography_css(&plain, "../fonts");
474 typography_css_from(&house, &Typography::house("../fonts"));
475 assert_eq!(
476 std::fs::read_to_string(&plain).unwrap(),
477 std::fs::read_to_string(&house).unwrap()
478 );
479 }
480
481 #[test]
482 fn the_geometry_file_carries_the_crates_policy_and_a_banner() {
483 // The policy itself is tested in makeover-geometry. What is this
484 // crate's job is that the banner is there and the policy reached the
485 // file at all.
486 let dir = scratch("geometry");
487 let path = dir.join("geometry.css");
488 geometry_css(&path, Some(".ui-mode-mobile"));
489 let css = std::fs::read_to_string(&path).unwrap();
490 assert!(css.starts_with("/* Generated by makeover-build"));
491 assert!(css.contains(&format!(
492 "@media {}",
493 makeover_geometry::Density::Touch.media_condition()
494 )));
495 assert!(css.contains(".ui-mode-mobile"));
496 // The width axis rides along, and only the shells are in it: a gap
497 // between two controls in a width query is the bug size_class_css
498 // exists to keep out.
499 assert!(css.contains("--gap-pane"), "no compact shell override");
500 let compact = css
501 .split(&format!(
502 "@media {}",
503 makeover_geometry::SizeClass::Compact.media_condition()
504 ))
505 .nth(1)
506 .expect("compact block");
507 assert!(
508 !compact.contains("--gap-peer"),
509 "a control gap crept into a width query"
510 );
511 }
512
513 #[test]
514 fn the_timing_file_carries_the_values_and_the_block_that_overrides_them() {
515 // The rungs themselves are tested in makeover-timing. What is this
516 // crate's to get wrong is dropping half the file: the values are
517 // useless noise without the media block, and the media block on its
518 // own overrides nothing.
519 let dir = scratch("timing");
520 let path = dir.join("timing.css");
521 timing_css(&path);
522 let css = std::fs::read_to_string(&path).unwrap();
523 assert!(css.starts_with("/* Generated by makeover-build"));
524 // One token per axis, so a crate that grows a fourth axis and is not
525 // emitted here fails somewhere other than on screen.
526 assert!(css.contains("--timing-dismiss"), "no intent tokens");
527 assert!(css.contains("--motion-fade"), "no motion token");
528 assert!(css.contains("--cadence-activity"), "no cadence token");
529 assert!(
530 css.contains("@media (prefers-reduced-motion: reduce)"),
531 "the values shipped without the block that turns them off"
532 );
533 // The block comes after the values it overrides. Same specificity,
534 // so the order is the whole of the win.
535 assert!(
536 css.find(":root").unwrap() < css.find("prefers-reduced-motion").unwrap(),
537 "the motion-off block cannot override values declared after it"
538 );
539 // Inside the family's layer, like every other generated sheet:
540 // unlayered declarations outrank every named layer, so a generated
541 // file outside it beats the app's own overrides.
542 assert!(css.contains(makeover_geometry::CSS_LAYER));
543 }
544
545 #[test]
546 fn the_tauri_layout_puts_all_four_where_the_apps_look() {
547 let root = scratch("tauri");
548 std::fs::create_dir_all(root.join("frontend").join("css")).unwrap();
549 tauri_frontend(&root, &makeover_webview::Emit::default(), None);
550 let css = root.join("frontend").join("css");
551 for file in ["geometry.css", "timing.css", "layout.css", "typography.css"] {
552 assert!(css.join(file).exists(), "{file} was not written");
553 }
554 assert!(root.join("themes").is_dir());
555 }
556}