on daa23fe help sign in
dodrio/src/render.rs
107 lines 2.7 kB history raw
1use crate::Node;
2use bumpalo::Bump;
3use std::any::Any;
4use std::rc::Rc;
5use wasm_bindgen::UnwrapThrowExt;
7pub trait Render {
8 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> Node<'bump>
9 where
10 'a: 'bump;
13impl<'r, R> Render for &'r R
14where
15 R: Render,
17 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> Node<'bump>
18 where
19 'a: 'bump,
20 {
21 (**self).render(bump)
22 }
25impl<R> Render for Rc<R>
26where
27 R: Render,
29 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> Node<'bump>
30 where
31 'a: 'bump,
32 {
33 (**self).render(bump)
34 }
37/// A `RootRender` is a render component that can be the root rendering component
38/// mounted to a virtual DOM.
39///
40/// In addition to rendering, it must also be `'static` so that it can be owned
41/// by the virtual DOM and `Any` so that it can be downcast to its concrete type
42/// by event listener callbacks.
43///
44/// You do not need to implement this trait by hand: there is a blanket
45/// implementation for all `Render` types that fulfill the `RootRender`
46/// requirements.
47pub trait RootRender: Any + Render {
48 /// Get this `&RootRender` trait object as an `&Any` trait object reference.
49 fn as_any(&self) -> &Any;
51 /// Get this `&mut RootRender` trait object as an `&mut Any` trait object
52 /// reference.
53 fn as_any_mut(&mut self) -> &mut Any;
56impl<T: Any + Render> RootRender for T {
57 fn as_any(&self) -> &Any {
58 self
59 }
61 fn as_any_mut(&mut self) -> &mut Any {
62 self
63 }
66impl dyn RootRender {
67 /// Downcast this shared `&dyn RootRender` trait object reference to its
68 /// underlying concrete type.
69 ///
70 /// # Panics
71 ///
72 /// Panics if this virtual DOM's root rendering component is not an `R`
73 /// instance.
74 pub fn unwrap_ref<R: RootRender>(&self) -> &R {
75 self.as_any()
76 .downcast_ref::<R>()
77 .expect_throw("bad `RootRender::unwrap_ref` call")
78 }
80 /// Downcast this exclusive `&mut dyn RootRender` trait object reference to
81 /// its underlying concrete type.
82 ///
83 /// # Panics
84 ///
85 /// Panics if this virtual DOM's root rendering component is not an `R`
86 /// instance.
87 pub fn unwrap_mut<R: RootRender>(&mut self) -> &mut R {
88 self.as_any_mut()
89 .downcast_mut::<R>()
90 .expect_throw("bad `RootRender::unwrap_ref` call")
91 }
94#[cfg(test)]
95mod tests {
96 #[test]
97 fn render_is_object_safe() {
98 #[allow(dead_code)]
99 fn takes_dyn_render(_: &dyn super::Render) {}
100 }
102 #[test]
103 fn root_render_is_object_safe() {
104 #[allow(dead_code)]
105 fn takes_dyn_render(_: &dyn super::RootRender) {}
106 }