tek/output/src/view.rs

87 lines
3.5 KiB
Rust

use crate::*;
#[macro_export] macro_rules! view {
($Output:ty: |$self:ident: $State:ty| $expr:expr; {
$($sym:literal => $body:expr),* $(,)?
}) => {
impl Content<$Output> for $State {
fn content (&$self) -> impl Render<$Output> { $expr }
}
impl<'a> ViewContext<'a, $Output> for $State {
fn get_content_sym (&'a $self, value: &Value<'a>) -> Option<RenderBox<'a, $Output>> {
if let Value::Sym(s) = value {
match *s {
$($sym => Some($body),)*
_ => None
}
} else {
panic!("expected content, got: {value:?}")
}
}
}
}
}
// An ephemeral wrapper around view state and view description,
// that is meant to be constructed and returned from [Content::content].
pub struct View<'a, T>(pub &'a T, pub SourceIter<'a>);
impl<'a, O: Output + 'a, T: ViewContext<'a, O>> Content<O> for View<'a, T> {
fn content (&self) -> impl Render<O> {
let iter = self.1.clone();
while let Some((Token { value, .. }, _)) = iter.next() {
if let Some(content) = self.0.get_content(&value) {
return Some(content)
}
}
return None
}
}
// Provides components to the view.
pub trait ViewContext<'a, E: Output + 'a>: Send + Sync
+ Context<bool>
+ Context<usize>
+ Context<E::Unit>
{
fn get_content (&'a self, value: &Value<'a>) -> Option<RenderBox<'a, E>> {
match value {
Value::Sym(_) => self.get_content_sym(value),
Value::Exp(_, _) => self.get_content_exp(value),
_ => panic!("only :symbols and (expressions) accepted here")
}
}
fn get_content_sym (&'a self, value: &Value<'a>) -> Option<RenderBox<'a, E>>;
fn get_content_exp (&'a self, value: &Value<'a>) -> Option<RenderBox<'a, E>> {
try_delegate!(self, *value, When::<RenderBox<'a, E>>);
try_delegate!(self, *value, Either::<RenderBox<'a, E>, RenderBox<'a, E>>);
try_delegate!(self, *value, Align::<RenderBox<'a, E>>);
try_delegate!(self, *value, Bsp::<RenderBox<'a, E>, RenderBox<'a, E>>);
try_delegate!(self, *value, Fill::<RenderBox<'a, E>>);
try_delegate!(self, *value, Fixed::<_, RenderBox<'a, E>>);
try_delegate!(self, *value, Min::<_, RenderBox<'a, E>>);
try_delegate!(self, *value, Max::<_, RenderBox<'a, E>>);
try_delegate!(self, *value, Shrink::<_, RenderBox<'a, E>>);
try_delegate!(self, *value, Expand::<_, RenderBox<'a, E>>);
try_delegate!(self, *value, Push::<_, RenderBox<'a, E>>);
try_delegate!(self, *value, Pull::<_, RenderBox<'a, E>>);
try_delegate!(self, *value, Margin::<_, RenderBox<'a, E>>);
try_delegate!(self, *value, Padding::<_, RenderBox<'a, E>>);
None
}
}
#[macro_export] macro_rules! try_delegate {
($s:ident, $atom:expr, $T:ty) => {
if let Some(value) = <$T>::try_from_atom($s, $atom) {
return Some(value.boxed())
}
}
}
#[macro_export] macro_rules! try_from_expr {
(<$l:lifetime, $E:ident>: $Struct:ty: |$state:ident, $iter:ident|$body:expr) => {
impl<$l, $E: Output + $l, T: ViewContext<$l, $E>> TryFromAtom<$l, T> for $Struct {
fn try_from_expr ($state: &$l T, $iter: TokenIter<'a>) -> Option<Self> {
let mut $iter = $iter.clone();
$body;
None
}
}
}
}