use thiserror::Error;
use crate::core::Hash32;
use crate::engine::Many;
use crate::loader::GlobBundle;
use crate::{Blueprint, error::HauchiwaError};
#[derive(Debug, Error)]
pub enum StyleError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Sass compilation error: {0}")]
Sass(#[from] Box<grass::Error>),
#[error("Build error: {0}")]
Build(#[from] crate::error::BuildError),
}
#[derive(Debug, Clone)]
pub struct Stylesheet {
pub path: camino::Utf8PathBuf,
}
pub struct CssLoader<'a, G>
where
G: Send + Sync,
{
blueprint: &'a mut Blueprint<G>,
entry_globs: Vec<String>,
watch_globs: Vec<String>,
minify: bool,
}
impl<'a, G> CssLoader<'a, G>
where
G: Send + Sync + 'static,
{
fn new(blueprint: &'a mut Blueprint<G>) -> Self {
Self {
blueprint,
entry_globs: Vec::new(),
watch_globs: Vec::new(),
minify: true,
}
}
pub fn entry(mut self, glob: impl Into<String>) -> Self {
self.entry_globs.push(glob.into());
self
}
pub fn watch(mut self, glob: impl Into<String>) -> Self {
self.watch_globs.push(glob.into());
self
}
pub fn minify(mut self, minify: bool) -> Self {
self.minify = minify;
self
}
pub fn register(self) -> Result<Many<Stylesheet>, HauchiwaError> {
let watch_globs = if self.watch_globs.is_empty() {
self.entry_globs.clone()
} else {
self.watch_globs
};
let minify = self.minify;
let task = GlobBundle::new(self.entry_globs, watch_globs, move |_, store, input| {
let style = if minify {
grass::OutputStyle::Compressed
} else {
grass::OutputStyle::Expanded
};
let options = grass::Options::default().style(style);
let data = grass::from_path(&input.path, &options).map_err(StyleError::Sass)?;
let hash = Hash32::hash(&data);
let path = store
.save(data.as_bytes(), "css")
.map_err(StyleError::Build)?;
Ok((hash, input.path, Stylesheet { path }))
})?;
Ok(self.blueprint.add_task_fine(task))
}
}
impl<G> Blueprint<G>
where
G: Send + Sync + 'static,
{
pub fn load_css(&mut self) -> CssLoader<'_, G> {
CssLoader::new(self)
}
}