element.rs

  1use crate::{BorrowWindow, Bounds, ElementId, LayoutId, Pixels, ViewContext};
  2use derive_more::{Deref, DerefMut};
  3pub(crate) use smallvec::SmallVec;
  4use std::{any::Any, mem};
  5
  6pub trait Element<V: 'static> {
  7    type ElementState: 'static;
  8
  9    fn id(&self) -> Option<ElementId>;
 10
 11    /// Called to initialize this element for the current frame. If this
 12    /// element had state in a previous frame, it will be passed in for the 3rd argument.
 13    fn initialize(
 14        &mut self,
 15        view_state: &mut V,
 16        element_state: Option<Self::ElementState>,
 17        cx: &mut ViewContext<V>,
 18    ) -> Self::ElementState;
 19    // where
 20    //     V: Any + Send + Sync;
 21
 22    fn layout(
 23        &mut self,
 24        view_state: &mut V,
 25        element_state: &mut Self::ElementState,
 26        cx: &mut ViewContext<V>,
 27    ) -> LayoutId;
 28    // where
 29    //     V: Any + Send + Sync;
 30
 31    fn paint(
 32        &mut self,
 33        bounds: Bounds<Pixels>,
 34        view_state: &mut V,
 35        element_state: &mut Self::ElementState,
 36        cx: &mut ViewContext<V>,
 37    );
 38
 39    // where
 40    //     Self::ViewState: Any + Send + Sync;
 41}
 42
 43#[derive(Deref, DerefMut, Default, Clone, Debug, Eq, PartialEq, Hash)]
 44pub struct GlobalElementId(SmallVec<[ElementId; 32]>);
 45
 46pub trait ParentElement<V: 'static> {
 47    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement<V>; 2]>;
 48
 49    fn child(mut self, child: impl Component<V>) -> Self
 50    where
 51        Self: Sized,
 52    {
 53        self.children_mut().push(child.render());
 54        self
 55    }
 56
 57    fn children(mut self, iter: impl IntoIterator<Item = impl Component<V>>) -> Self
 58    where
 59        Self: Sized,
 60    {
 61        self.children_mut()
 62            .extend(iter.into_iter().map(|item| item.render()));
 63        self
 64    }
 65}
 66
 67trait ElementObject<V> {
 68    fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>);
 69    fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId;
 70    fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>);
 71}
 72
 73struct RenderedElement<V: 'static, E: Element<V>> {
 74    element: E,
 75    phase: ElementRenderPhase<E::ElementState>,
 76}
 77
 78#[derive(Default)]
 79enum ElementRenderPhase<V> {
 80    #[default]
 81    Start,
 82    Initialized {
 83        frame_state: Option<V>,
 84    },
 85    LayoutRequested {
 86        layout_id: LayoutId,
 87        frame_state: Option<V>,
 88    },
 89    Painted,
 90}
 91
 92/// Internal struct that wraps an element to store Layout and ElementState after the element is rendered.
 93/// It's allocated as a trait object to erase the element type and wrapped in AnyElement<E::State> for
 94/// improved usability.
 95impl<V, E: Element<V>> RenderedElement<V, E> {
 96    fn new(element: E) -> Self {
 97        RenderedElement {
 98            element,
 99            phase: ElementRenderPhase::Start,
100        }
101    }
102}
103
104impl<V, E> ElementObject<V> for RenderedElement<V, E>
105where
106    E: Element<V>,
107    // E::ViewState: Any + Send + Sync,
108    E::ElementState: Any + Send + Sync,
109{
110    fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
111        let frame_state = if let Some(id) = self.element.id() {
112            cx.with_element_state(id, |element_state, cx| {
113                let element_state = self.element.initialize(view_state, element_state, cx);
114                ((), element_state)
115            });
116            None
117        } else {
118            let frame_state = self.element.initialize(view_state, None, cx);
119            Some(frame_state)
120        };
121
122        self.phase = ElementRenderPhase::Initialized { frame_state };
123    }
124
125    fn layout(&mut self, state: &mut V, cx: &mut ViewContext<V>) -> LayoutId {
126        let layout_id;
127        let mut frame_state;
128        match mem::take(&mut self.phase) {
129            ElementRenderPhase::Initialized {
130                frame_state: initial_frame_state,
131            } => {
132                frame_state = initial_frame_state;
133                if let Some(id) = self.element.id() {
134                    layout_id = cx.with_element_state(id, |element_state, cx| {
135                        let mut element_state = element_state.unwrap();
136                        let layout_id = self.element.layout(state, &mut element_state, cx);
137                        (layout_id, element_state)
138                    });
139                } else {
140                    layout_id = self
141                        .element
142                        .layout(state, frame_state.as_mut().unwrap(), cx);
143                }
144            }
145            _ => panic!("must call initialize before layout"),
146        };
147
148        self.phase = ElementRenderPhase::LayoutRequested {
149            layout_id,
150            frame_state,
151        };
152        layout_id
153    }
154
155    fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
156        self.phase = match mem::take(&mut self.phase) {
157            ElementRenderPhase::LayoutRequested {
158                layout_id,
159                mut frame_state,
160            } => {
161                let bounds = cx.layout_bounds(layout_id);
162                if let Some(id) = self.element.id() {
163                    cx.with_element_state(id, |element_state, cx| {
164                        let mut element_state = element_state.unwrap();
165                        self.element
166                            .paint(bounds, view_state, &mut element_state, cx);
167                        ((), element_state)
168                    });
169                } else {
170                    self.element
171                        .paint(bounds, view_state, frame_state.as_mut().unwrap(), cx);
172                }
173                ElementRenderPhase::Painted
174            }
175
176            _ => panic!("must call layout before paint"),
177        };
178    }
179}
180
181pub struct AnyElement<V>(Box<dyn ElementObject<V> + Send + Sync>);
182
183unsafe impl<V> Send for AnyElement<V> {}
184unsafe impl<V> Sync for AnyElement<V> {}
185
186impl<V> AnyElement<V> {
187    pub fn new<E>(element: E) -> Self
188    where
189        V: 'static,
190        E: 'static + Send + Sync,
191        E: Element<V>,
192        E::ElementState: Any + Send + Sync,
193    {
194        AnyElement(Box::new(RenderedElement::new(element)))
195    }
196
197    pub fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
198        self.0.initialize(view_state, cx);
199    }
200
201    pub fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId {
202        self.0.layout(view_state, cx)
203    }
204
205    pub fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
206        self.0.paint(view_state, cx)
207    }
208}
209
210pub trait Component<V> {
211    fn render(self) -> AnyElement<V>;
212
213    fn when(mut self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
214    where
215        Self: Sized,
216    {
217        if condition {
218            self = then(self);
219        }
220        self
221    }
222}
223
224impl<V> Component<V> for AnyElement<V> {
225    fn render(self) -> AnyElement<V> {
226        self
227    }
228}
229
230impl<V, E, F> Element<V> for Option<F>
231where
232    V: 'static,
233    E: 'static + Component<V> + Send + Sync,
234    F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + Sync + 'static,
235{
236    type ElementState = AnyElement<V>;
237
238    fn id(&self) -> Option<ElementId> {
239        None
240    }
241
242    fn initialize(
243        &mut self,
244        view_state: &mut V,
245        _rendered_element: Option<Self::ElementState>,
246        cx: &mut ViewContext<V>,
247    ) -> Self::ElementState {
248        let render = self.take().unwrap();
249        let mut rendered_element = (render)(view_state, cx).render();
250        rendered_element.initialize(view_state, cx);
251        rendered_element
252    }
253
254    fn layout(
255        &mut self,
256        view_state: &mut V,
257        rendered_element: &mut Self::ElementState,
258        cx: &mut ViewContext<V>,
259    ) -> LayoutId {
260        rendered_element.layout(view_state, cx)
261    }
262
263    fn paint(
264        &mut self,
265        _bounds: Bounds<Pixels>,
266        view_state: &mut V,
267        rendered_element: &mut Self::ElementState,
268        cx: &mut ViewContext<V>,
269    ) {
270        rendered_element.paint(view_state, cx)
271    }
272}
273
274impl<V, E, F> Component<V> for Option<F>
275where
276    V: 'static,
277    E: 'static + Component<V> + Send + Sync,
278    F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + Sync + 'static,
279{
280    fn render(self) -> AnyElement<V> {
281        AnyElement::new(self)
282    }
283}
284
285impl<V, E, F> Component<V> for F
286where
287    V: 'static,
288    E: 'static + Component<V> + Send + Sync,
289    F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + Sync + 'static,
290{
291    fn render(self) -> AnyElement<V> {
292        AnyElement::new(Some(self))
293    }
294}