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 utility stylesheets (Tailwind): each page gets only the
40 /// rules for the classes it renders, plus those for the listed classes
41 /// (used by code outside the view tree). `None`: sent whole.
42 pub per_class: Option<&'static [&'static str]>,
43}
44
45impl View for &'static Stylesheet {
46 fn into_node(self) -> Node {
47 Node::Style(self)
48 }
49}
50
51/// A scoped class name from a CSS module.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct CssClass {
54 pub name: &'static str,
55 pub sheet: &'static Stylesheet,
56}
57
58impl CssClass {
59 pub const fn new(name: &'static str, sheet: &'static Stylesheet) -> Self {
60 Self { name, sheet }
61 }
62}
63
64impl std::fmt::Display for CssClass {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 f.write_str(self.name)
67 }
68}