Skip to main content

next_rust_view/
style.rs

1//! Stylesheets created by the `css_module!` and `global_css!` macros.
2//!
3//! The macros read and transform CSS **at compile time** and produce
4//! `&'static Stylesheet` values. A stylesheet participates in a page when a
5//! [`CssClass`] from it is used in `class(..)`, or when the stylesheet itself
6//! is placed in the view tree (global CSS). The renderer emits every used
7//! stylesheet exactly once per document as a `<style>` element, so pages
8//! only ship the CSS they actually use and streaming never produces a flash
9//! of unstyled content.
10
11use std::sync::OnceLock;
12
13use crate::node::{Node, View};
14
15static OVERRIDES: OnceLock<Vec<(&'static Stylesheet, &'static Stylesheet)>> = OnceLock::new();
16
17/// Render `to` wherever the view tree uses `from`, e.g. a stylesheet whose
18/// classes were renamed for a release build. Set once at startup; later
19/// calls are ignored.
20pub fn set_overrides(list: Vec<(&'static Stylesheet, &'static Stylesheet)>) {
21    let _ = OVERRIDES.set(list);
22}
23
24/// The stylesheet to render for `sheet`.
25pub(crate) fn resolve(sheet: &'static Stylesheet) -> &'static Stylesheet {
26    OVERRIDES
27        .get()
28        .and_then(|list| list.iter().find(|(from, _)| std::ptr::eq(*from, sheet)))
29        .map_or(sheet, |(_, to)| to)
30}
31
32/// A compiled stylesheet.
33#[derive(Debug, PartialEq, Eq)]
34pub struct Stylesheet {
35    /// Content hash (stable across builds for identical CSS).
36    pub id: &'static str,
37    /// Minified CSS text.
38    pub css: &'static str,
39    /// `Some` for stylesheets sent per page (the Tailwind build with the
40    /// CSS imported into it, `global_css!` sheets, UI components): each page
41    /// gets only the rules for the classes it renders, plus those for the
42    /// listed classes (added by scripts, outside the view tree). `None`:
43    /// sent whole.
44    pub per_class: Option<&'static [&'static str]>,
45    /// Classes that scripts add, by script (`"client/home.js"`,
46    /// `"assets/js/site.js"`, a `public/` path): sent with a page only when
47    /// it loads that script.
48    pub scripts: &'static [(&'static str, &'static [&'static str])],
49}
50
51impl View for &'static Stylesheet {
52    fn into_node(self) -> Node {
53        Node::Style(self)
54    }
55}
56
57/// A scoped class name from a CSS module.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct CssClass {
60    pub name: &'static str,
61    pub sheet: &'static Stylesheet,
62}
63
64impl CssClass {
65    pub const fn new(name: &'static str, sheet: &'static Stylesheet) -> Self {
66        Self { name, sheet }
67    }
68}
69
70impl std::fmt::Display for CssClass {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.write_str(self.name)
73    }
74}