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