use crate::core::component::Context;
use crate::html::assets::Asset;
use crate::html::{html, Markup, PreEscaped};
use crate::{util, AutoDefault, CowStr, Weight};
#[derive(AutoDefault)]
enum Source {
#[default]
From(CowStr),
Inline(CowStr, Box<dyn Fn(&mut Context) -> String + Send + Sync>),
}
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
pub enum TargetMedia {
#[default]
Default,
Print,
Screen,
Speech,
}
impl TargetMedia {
const fn as_str(self) -> Option<&'static str> {
match self {
TargetMedia::Default => None,
TargetMedia::Print => Some("print"),
TargetMedia::Screen => Some("screen"),
TargetMedia::Speech => Some("speech"),
}
}
}
#[derive(AutoDefault)]
pub struct StyleSheet {
source: Source, version: CowStr, media: TargetMedia, weight: Weight, }
impl StyleSheet {
pub fn from(path: impl Into<CowStr>) -> Self {
Self {
source: Source::From(path.into()),
..Default::default()
}
}
pub fn inline<F>(name: impl Into<CowStr>, f: F) -> Self
where
F: Fn(&mut Context) -> String + Send + Sync + 'static,
{
Self {
source: Source::Inline(name.into(), Box::new(f)),
..Default::default()
}
}
pub fn with_version(mut self, version: impl Into<CowStr>) -> Self {
self.version = version.into();
self
}
pub fn with_weight(mut self, value: Weight) -> Self {
self.weight = value;
self
}
pub fn for_media(mut self, media: TargetMedia) -> Self {
self.media = media;
self
}
}
impl Asset for StyleSheet {
fn name(&self) -> &str {
match &self.source {
Source::From(path) => path,
Source::Inline(name, _) => name,
}
}
fn weight(&self) -> Weight {
self.weight
}
fn render(&self, cx: &mut Context) -> Markup {
match &self.source {
Source::From(path) => html! {
link
rel="stylesheet"
href=(util::join_pair!(path, "?v=", &self.version))
media=[self.media.as_str()];
},
Source::Inline(_, f) => html! {
style { (PreEscaped((f)(cx))) };
},
}
}
}