use std::rc::Rc;
use crate::manager::{StyleContent, StyleId, StyleKey, StyleManager};
use crate::{Result, StyleSource};
#[derive(Debug, Clone)]
pub struct GlobalStyle {
inner: Rc<StyleContent>,
}
impl GlobalStyle {
fn create_impl(css: StyleSource, manager: StyleManager) -> Result<Self> {
let css = css.into_sheet();
let key = StyleKey {
is_global: true,
prefix: manager.prefix(),
ast: css,
};
let inner = manager.get_or_register_style(key)?;
let new_style = Self { inner };
Ok(new_style)
}
pub fn new<Css>(css: Css) -> Result<Self>
where
Css: TryInto<StyleSource>,
crate::Error: From<Css::Error>,
{
Self::new_with_manager(css, StyleManager::default())
}
pub fn new_with_manager<Css, M>(css: Css, manager: M) -> Result<Self>
where
Css: TryInto<StyleSource>,
crate::Error: From<Css::Error>,
M: Into<StyleManager>,
{
let mgr = manager.into();
Self::create_impl(css.try_into()?, mgr)
}
pub fn get_style_str(&self) -> &str {
self.inner.get_style_str()
}
pub fn unregister(&self) {
self.inner.unregister();
}
pub fn id(&self) -> &StyleId {
self.inner.id()
}
}
#[cfg(test)]
#[cfg(feature = "parser")]
mod tests {
use super::*;
#[test]
fn test_simple() {
let global_style =
GlobalStyle::new("background-color: black;").expect("Failed to create Style.");
assert_eq!(
global_style.get_style_str(),
r#":root {
background-color: black;
}
"#
);
}
#[test]
fn test_complex() {
let global_style = GlobalStyle::new(
r#"
background-color: black;
.with-class {
color: red;
}
@media screen and (max-width: 600px) {
color: yellow;
}
@supports (display: grid) {
display: grid;
}
header, footer {
border: 1px solid black;
}
"#,
)
.expect("Failed to create Style.");
assert_eq!(
global_style.get_style_str(),
r#":root {
background-color: black;
}
.with-class {
color: red;
}
@media screen and (max-width: 600px) {
:root {
color: yellow;
}
}
@supports (display: grid) {
:root {
display: grid;
}
}
header, footer {
border: 1px solid black;
}
"#,
)
}
}