based/src/ui/primitives/width.rs
2025-01-17 14:55:55 +01:00

91 lines
2.3 KiB
Rust

use crate::ui::UIWidget;
use maud::{Markup, Render, html};
use super::{
flex::Either,
space::{Fraction, ScreenValue},
};
#[allow(non_snake_case)]
pub fn Width<T: UIWidget + 'static, S: Into<Either<ScreenValue, Fraction>>>(
size: S,
inner: T,
) -> WidthWidget {
WidthWidget(Box::new(inner), size.into(), 0)
}
#[allow(non_snake_case)]
pub fn MinWidth<T: UIWidget + 'static, S: Into<Either<ScreenValue, Fraction>>>(
size: S,
inner: T,
) -> WidthWidget {
WidthWidget(Box::new(inner), size.into(), 1)
}
#[allow(non_snake_case)]
pub fn MaxWidth<T: UIWidget + 'static, S: Into<Either<ScreenValue, Fraction>>>(
size: S,
inner: T,
) -> WidthWidget {
WidthWidget(Box::new(inner), size.into(), 2)
}
pub struct WidthWidget(Box<dyn UIWidget>, Either<ScreenValue, Fraction>, u8);
impl Render for WidthWidget {
fn render(&self) -> Markup {
self.render_with_class("")
}
}
impl UIWidget for WidthWidget {
fn can_inherit(&self) -> bool {
true
}
fn base_class(&self) -> Vec<String> {
match self.2 {
1 => {
return vec![format!(
"min-w-{}",
self.1
.map(|x| x.to_value().to_string(), |x| x.to_value().to_string())
)];
}
2 => {
return vec![format!(
"max-w-{}",
self.1
.map(|x| x.to_value().to_string(), |x| x.to_value().to_string())
)];
}
_ => {}
}
vec![format!(
"w-{}",
self.1
.map(|x| x.to_value().to_string(), |x| x.to_value().to_string())
)]
}
fn extended_class(&self) -> Vec<String> {
let mut c = self.base_class();
c.extend_from_slice(&self.0.extended_class());
c
}
fn render_with_class(&self, class: &str) -> Markup {
if self.0.as_ref().can_inherit() {
self.0
.as_ref()
.render_with_class(&format!("{} {class}", self.base_class().join(" ")))
} else {
html! {
div class=(format!("{} {class}", self.base_class().join(" "))) {
(self.0.as_ref())
}
}
}
}
}