diff --git a/tachys/src/view/add_attr.rs b/tachys/src/view/add_attr.rs index 4d4df9531..dc5dc102a 100644 --- a/tachys/src/view/add_attr.rs +++ b/tachys/src/view/add_attr.rs @@ -1,4 +1,4 @@ -use super::RenderHtml; +use super::{BoxedView, RenderHtml}; use crate::{html::attribute::Attribute, renderer::Renderer}; /// Allows adding a new attribute to some type, before it is rendered. @@ -44,3 +44,22 @@ macro_rules! no_attrs { } }; } + +impl AddAnyAttr for BoxedView +where + T: AddAnyAttr, + Rndr: Renderer, +{ + type Output> = + BoxedView>; + + fn add_any_attr>( + self, + attr: NewAttr, + ) -> Self::Output + where + Self::Output: RenderHtml, + { + BoxedView::new(self.into_inner().add_any_attr(attr)) + } +} diff --git a/tachys/src/view/mod.rs b/tachys/src/view/mod.rs index 9e349ee86..d6eeb8e83 100644 --- a/tachys/src/view/mod.rs +++ b/tachys/src/view/mod.rs @@ -425,3 +425,85 @@ pub enum Position { /// This is the last child of its parent. LastChild, } + +/// A view stored on the heap. +/// +/// This is a newtype around `Box<_>` that allows us to implement rendering traits on it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoxedView(Box); + +impl BoxedView { + /// Stores view on the heap. + pub fn new(value: T) -> Self { + Self(Box::new(value)) + } + + /// Deferences the view to its inner value. + pub fn into_inner(self) -> T { + *self.0 + } + + /// Gives a shared reference to the view. + pub fn as_ref(&self) -> &T { + &self.0 + } + + /// Gives an exclusive reference to the view. + pub fn as_mut(&mut self) -> &mut T { + &mut self.0 + } +} + +impl Render for BoxedView +where + T: Render, + Rndr: Renderer, +{ + type State = T::State; + + fn build(self) -> Self::State { + self.into_inner().build() + } + + fn rebuild(self, state: &mut Self::State) { + self.into_inner().rebuild(state); + } +} + +impl RenderHtml for BoxedView +where + T: RenderHtml, + Rndr: Renderer, +{ + type AsyncOutput = BoxedView; + + const MIN_LENGTH: usize = T::MIN_LENGTH; + + fn dry_resolve(&mut self) { + self.as_mut().dry_resolve(); + } + + async fn resolve(self) -> Self::AsyncOutput { + let inner = self.into_inner().resolve().await; + BoxedView::new(inner) + } + + fn to_html_with_buf( + self, + buf: &mut String, + position: &mut Position, + escape: bool, + mark_branches: bool, + ) { + self.into_inner() + .to_html_with_buf(buf, position, escape, mark_branches) + } + + fn hydrate( + self, + cursor: &Cursor, + position: &PositionState, + ) -> Self::State { + self.into_inner().hydrate::(cursor, position) + } +}