tek/output/src/when.rs

42 lines
1.3 KiB
Rust

use crate::*;
/// Show an item only when a condition is true.
pub struct When<E, A>(pub PhantomData<E>, pub bool, pub A);
impl<E, A> When<E, A> {
pub fn new (c: bool, a: A) -> Self {
Self(Default::default(), c, a)
}
}
impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for When<E, RenderBox<'a, E>> {
fn try_from_edn (
state: &'a T, head: &EdnItem<&str>, tail: &'a [EdnItem<&str>]
) -> Option<Self> {
use EdnItem::*;
if let (Key("when"), [condition, content]) = (head, tail) {
Some(Self(
Default::default(),
state.get_bool(condition).expect("when: no condition"),
state.get_content(content).expect("when: no content")
))
} else {
None
}
}
}
impl<E: Output, A: Render<E>> Content<E> for When<E, A> {
fn layout (&self, to: E::Area) -> E::Area {
let Self(_, cond, item) = self;
let mut area = E::Area::zero();
if *cond {
let item_area = item.layout(to);
area[0] = item_area.x();
area[1] = item_area.y();
area[2] = item_area.w();
area[3] = item_area.h();
}
area.into()
}
fn render (&self, to: &mut E) {
let Self(_, cond, item) = self;
if *cond { item.render(to) }
}
}