vizia_core/util/
mod.rs

1use std::path::{Path, PathBuf};
2
3/// Helper trait for getting CSS from a string or path.
4pub trait IntoCssStr: 'static {
5    /// Returns a string containing CSS.
6    fn get_style(&self) -> Result<String, std::io::Error>;
7}
8
9impl IntoCssStr for CSS {
10    fn get_style(&self) -> Result<String, std::io::Error> {
11        match self {
12            CSS::Path(path) => std::fs::read_to_string(path),
13
14            CSS::String(style_string) => Ok(style_string.to_owned()),
15        }
16    }
17}
18
19impl IntoCssStr for &'static str {
20    fn get_style(&self) -> Result<String, std::io::Error> {
21        Ok(self.to_string())
22    }
23}
24
25impl IntoCssStr for PathBuf {
26    fn get_style(&self) -> Result<String, std::io::Error> {
27        std::fs::read_to_string(self)
28    }
29}
30
31impl IntoCssStr for Path {
32    fn get_style(&self) -> Result<String, std::io::Error> {
33        std::fs::read_to_string(self)
34    }
35}
36
37#[doc(hidden)]
38pub enum CSS {
39    Path(PathBuf),
40    String(String),
41}
42
43impl CSS {
44    pub fn from_string(style: &str) -> Self {
45        Self::String(style.to_owned())
46    }
47
48    pub fn from_file(path: impl AsRef<Path>) -> Self {
49        Self::Path(path.as_ref().to_owned())
50    }
51}
52
53impl From<&str> for CSS {
54    fn from(value: &str) -> Self {
55        CSS::from_string(value)
56    }
57}
58
59impl From<PathBuf> for CSS {
60    fn from(value: PathBuf) -> Self {
61        CSS::from_file(value)
62    }
63}
64
65#[cfg(debug_assertions)]
66#[macro_export]
67/// A macro which parses CSS from a file at runtime in debug mode, and includes the file in the binary in release mode.
68macro_rules! include_style {
69    ($filename:tt) => {
70        $crate::util::CSS::from_file(concat!(env!("CARGO_MANIFEST_DIR"), "/", $filename))
71    };
72}
73
74#[cfg(not(debug_assertions))]
75#[macro_export]
76macro_rules! include_style {
77    ($filename:tt) => {
78        $crate::prelude::CSS::from_string(include_str!(concat!(
79            env!("CARGO_MANIFEST_DIR"),
80            "/",
81            $filename
82        )))
83    };
84}