Skip to main content

next_rust/
font.rs

1//! Local font helper.
2
3use next_rust_view::{Metadata, Node, raw_html};
4
5/// A self-hosted font.
6///
7/// ```ignore
8/// static INTER: LazyLock<LocalFont> = LazyLock::new(|| {
9///     LocalFont::new("Inter", asset!("fonts/inter-var.woff2")).weight("100 900")
10/// });
11/// // layout.rs
12/// pub fn metadata() -> Metadata { INTER.metadata() }
13/// pub fn Layout(children: Children) -> impl View { div![INTER.style(), children] }
14/// ```
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct LocalFont {
17    family: String,
18    sources: Vec<String>,
19    weight: String,
20    style: String,
21    display: String,
22    fallback: String,
23    preload: bool,
24}
25
26fn clean(s: &str) -> String {
27    s.chars().filter(|c| !matches!(c, '"' | '\'' | '<' | '>' | ';' | '{' | '}' | '\\' | '\n' | '\r')).collect()
28}
29
30impl LocalFont {
31    pub fn new(family: &str, url: &str) -> Self {
32        LocalFont {
33            family: clean(family),
34            sources: vec![clean(url)],
35            weight: "400".into(),
36            style: "normal".into(),
37            display: "swap".into(),
38            fallback: "system-ui, sans-serif".into(),
39            preload: true,
40        }
41    }
42
43    /// Additional source (e.g. a `.woff` fallback).
44    pub fn source(mut self, url: &str) -> Self {
45        self.sources.push(clean(url));
46        self
47    }
48
49    /// `"400"`, `"700"`, or a variable range like `"100 900"`.
50    pub fn weight(mut self, w: &str) -> Self {
51        self.weight = clean(w);
52        self
53    }
54
55    pub fn style(mut self, s: &str) -> Self {
56        self.style = clean(s);
57        self
58    }
59
60    /// `font-display` (default `swap`).
61    pub fn display(mut self, d: &str) -> Self {
62        self.display = clean(d);
63        self
64    }
65
66    pub fn fallback(mut self, f: &str) -> Self {
67        self.fallback = clean(f);
68        self
69    }
70
71    pub fn preload(mut self, p: bool) -> Self {
72        self.preload = p;
73        self
74    }
75
76    /// `font-family` value including fallbacks.
77    pub fn family(&self) -> String {
78        format!("\"{}\", {}", self.family, self.fallback)
79    }
80
81    pub fn css(&self) -> String {
82        let srcs: Vec<String> = self
83            .sources
84            .iter()
85            .map(|u| {
86                let fmt = match u.rsplit('.').next() {
87                    Some("woff2") => " format(\"woff2\")",
88                    Some("woff") => " format(\"woff\")",
89                    Some("ttf") => " format(\"truetype\")",
90                    Some("otf") => " format(\"opentype\")",
91                    _ => "",
92                };
93                format!("url(\"{u}\"){fmt}")
94            })
95            .collect();
96        format!(
97            "@font-face{{font-family:\"{}\";src:{};font-weight:{};font-style:{};font-display:{}}}",
98            self.family,
99            srcs.join(","),
100            self.weight,
101            self.style,
102            self.display
103        )
104    }
105
106    /// `<style>` element with the `@font-face` rule.
107    pub fn style_node(&self) -> Node {
108        raw_html(format!("<style>{}</style>", self.css()))
109    }
110
111    /// Metadata preloading the primary font file.
112    pub fn metadata(&self) -> Metadata {
113        match (self.preload, self.sources.first()) {
114            (true, Some(src)) => Metadata::new().preload_font(src.clone()),
115            _ => Metadata::new(),
116        }
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn font_css_is_sanitized() {
126        let f = LocalFont::new("Inter\"</style>", "/fonts/inter.woff2").weight("100 900");
127        assert_eq!(
128            f.css(),
129            "@font-face{font-family:\"Inter/style\";src:url(\"/fonts/inter.woff2\") format(\"woff2\");font-weight:100 900;font-style:normal;font-display:swap}"
130        );
131        assert_eq!(f.metadata().preloads.len(), 1);
132    }
133}