Skip to main content

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