Skip to main content

eternal_ui/
style.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Themes and inline styles.
6
7use std::fmt;
8use std::path::Path;
9
10use eternal_styler::{Error, Stylesheet};
11
12/// The stylesheet [`Ui::new`](crate::Ui::new) starts with: dark, dense,
13/// flat, 1px borders, in the spirit of Aseprite. Read it to see which
14/// classes it understands (`panel`, `toolbar`, `primary`, `title`, `dim`).
15pub const DEFAULT_THEME_CSS: &str = include_str!("../themes/pixel-dark.css");
16
17/// The default theme, parsed.
18pub fn default_theme() -> Stylesheet {
19    Stylesheet::parse(DEFAULT_THEME_CSS).expect("the built-in theme parses")
20}
21
22/// Reads and parses a stylesheet from a file.
23pub fn load_stylesheet(path: impl AsRef<Path>) -> Result<Stylesheet, LoadError> {
24    let path = path.as_ref();
25    let css = std::fs::read_to_string(path).map_err(|source| LoadError::Io {
26        path: path.display().to_string(),
27        source,
28    })?;
29    Stylesheet::parse(&css).map_err(|source| LoadError::Parse {
30        path: path.display().to_string(),
31        source,
32    })
33}
34
35/// A stylesheet file could not be read or parsed.
36#[derive(Debug)]
37pub enum LoadError {
38    Io {
39        path: String,
40        source: std::io::Error,
41    },
42    Parse {
43        path: String,
44        source: Error,
45    },
46}
47
48impl fmt::Display for LoadError {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self {
51            Self::Io { path, source } => write!(f, "{path}: {source}"),
52            Self::Parse { path, source } => write!(f, "{path}: {source}"),
53        }
54    }
55}
56
57impl std::error::Error for LoadError {
58    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
59        match self {
60            Self::Io { source, .. } => Some(source),
61            Self::Parse { source, .. } => Some(source),
62        }
63    }
64}
65
66/// Builds inline CSS from Rust values, for `style={...}` attributes whose
67/// values are computed.
68///
69/// ```
70/// use eternal_ui::Style;
71///
72/// let width = 120.0;
73/// let style = Style::new().width_px(width).padding_px(4.0).set("color", "#fff");
74/// assert_eq!(style.to_string(), "width: 120px; padding: 4px; color: #fff");
75/// ```
76///
77/// The result is parsed by eternal-styler like any other CSS, so a
78/// property it does not know is reported when the element is built.
79#[derive(Clone, Debug, Default, PartialEq, Eq)]
80pub struct Style {
81    declarations: Vec<(String, String)>,
82}
83
84impl Style {
85    pub fn new() -> Self {
86        Self::default()
87    }
88
89    /// Any property and value, as CSS text.
90    pub fn set(mut self, property: &str, value: impl fmt::Display) -> Self {
91        self.declarations
92            .push((property.to_owned(), value.to_string()));
93        self
94    }
95
96    pub fn width_px(self, px: f32) -> Self {
97        self.set("width", Px(px))
98    }
99
100    pub fn height_px(self, px: f32) -> Self {
101        self.set("height", Px(px))
102    }
103
104    pub fn min_width_px(self, px: f32) -> Self {
105        self.set("min-width", Px(px))
106    }
107
108    pub fn min_height_px(self, px: f32) -> Self {
109        self.set("min-height", Px(px))
110    }
111
112    pub fn padding_px(self, px: f32) -> Self {
113        self.set("padding", Px(px))
114    }
115
116    pub fn margin_px(self, px: f32) -> Self {
117        self.set("margin", Px(px))
118    }
119
120    pub fn gap_px(self, px: f32) -> Self {
121        self.set("gap", Px(px))
122    }
123
124    /// Any CSS colour syntax, such as `#1e1e1e` or `oklch(60% 0.1 250)`.
125    pub fn color(self, css: &str) -> Self {
126        self.set("color", css)
127    }
128
129    pub fn background(self, css: &str) -> Self {
130        self.set("background-color", css)
131    }
132
133    /// A uniform border: `border(1.0, "solid", "#000")`.
134    pub fn border(self, width_px: f32, style: &str, color: &str) -> Self {
135        self.set("border", format_args!("{} {style} {color}", Px(width_px)))
136    }
137
138    pub fn font_size_px(self, px: f32) -> Self {
139        self.set("font-size", Px(px))
140    }
141
142    pub fn opacity(self, opacity: f32) -> Self {
143        self.set("opacity", opacity)
144    }
145
146    pub fn is_empty(&self) -> bool {
147        self.declarations.is_empty()
148    }
149}
150
151impl fmt::Display for Style {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        for (index, (property, value)) in self.declarations.iter().enumerate() {
154            if index > 0 {
155                f.write_str("; ")?;
156            }
157            write!(f, "{property}: {value}")?;
158        }
159        Ok(())
160    }
161}
162
163/// A pixel length that prints without a trailing `.0`.
164struct Px(f32);
165
166impl fmt::Display for Px {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        if self.0.fract() == 0.0 {
169            write!(f, "{}px", self.0 as i64)
170        } else {
171            write!(f, "{}px", self.0)
172        }
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn default_theme_parses() {
182        let theme = default_theme();
183        assert!(theme.len() > 10);
184    }
185
186    #[test]
187    fn style_builder_prints_css() {
188        assert_eq!(Style::new().to_string(), "");
189        assert_eq!(
190            Style::new()
191                .border(1.0, "solid", "#000")
192                .opacity(0.5)
193                .width_px(12.5)
194                .to_string(),
195            "border: 1px solid #000; opacity: 0.5; width: 12.5px"
196        );
197        assert!(
198            eternal_styler::DeclarationBlock::parse(
199                &Style::new().padding_px(4.0).background("#123").to_string()
200            )
201            .is_ok()
202        );
203    }
204}