element.rs

  1use crate::{
  2    AvailableSpace, BorrowWindow, Bounds, ElementId, LayoutId, Pixels, Point, Size, ViewContext,
  3};
  4use derive_more::{Deref, DerefMut};
  5pub(crate) use smallvec::SmallVec;
  6use std::{any::Any, fmt::Debug, mem};
  7
  8pub trait Element<V: 'static> {
  9    type ElementState: 'static;
 10
 11    fn element_id(&self) -> Option<ElementId>;
 12
 13    fn layout(
 14        &mut self,
 15        view_state: &mut V,
 16        element_state: Option<Self::ElementState>,
 17        cx: &mut ViewContext<V>,
 18    ) -> (LayoutId, Self::ElementState);
 19
 20    fn paint(
 21        &mut self,
 22        bounds: Bounds<Pixels>,
 23        view_state: &mut V,
 24        element_state: &mut Self::ElementState,
 25        cx: &mut ViewContext<V>,
 26    );
 27
 28    fn draw<T, R>(
 29        self,
 30        origin: Point<Pixels>,
 31        available_space: Size<T>,
 32        view_state: &mut V,
 33        cx: &mut ViewContext<V>,
 34        f: impl FnOnce(&Self::ElementState, &mut ViewContext<V>) -> R,
 35    ) -> R
 36    where
 37        Self: Sized,
 38        T: Clone + Default + Debug + Into<AvailableSpace>,
 39    {
 40        let mut element = RenderedElement {
 41            element: self,
 42            phase: ElementRenderPhase::Start,
 43        };
 44        element.draw(origin, available_space.map(Into::into), view_state, cx);
 45        if let ElementRenderPhase::Painted { frame_state } = &element.phase {
 46            if let Some(frame_state) = frame_state.as_ref() {
 47                f(&frame_state, cx)
 48            } else {
 49                let element_id = element
 50                    .element
 51                    .element_id()
 52                    .expect("we either have some frame_state or some element_id");
 53                cx.with_element_state(element_id, |element_state, cx| {
 54                    let element_state = element_state.unwrap();
 55                    let result = f(&element_state, cx);
 56                    (result, element_state)
 57                })
 58            }
 59        } else {
 60            unreachable!()
 61        }
 62    }
 63}
 64
 65#[derive(Deref, DerefMut, Default, Clone, Debug, Eq, PartialEq, Hash)]
 66pub struct GlobalElementId(SmallVec<[ElementId; 32]>);
 67
 68pub trait ParentComponent<V: 'static> {
 69    fn children_mut(&mut self) -> &mut SmallVec<[AnyElement<V>; 2]>;
 70
 71    fn child(mut self, child: impl Component<V>) -> Self
 72    where
 73        Self: Sized,
 74    {
 75        self.children_mut().push(child.render());
 76        self
 77    }
 78
 79    fn children(mut self, iter: impl IntoIterator<Item = impl Component<V>>) -> Self
 80    where
 81        Self: Sized,
 82    {
 83        self.children_mut()
 84            .extend(iter.into_iter().map(|item| item.render()));
 85        self
 86    }
 87}
 88
 89trait ElementObject<V> {
 90    fn element_id(&self) -> Option<ElementId>;
 91    fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId;
 92    fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>);
 93    fn measure(
 94        &mut self,
 95        available_space: Size<AvailableSpace>,
 96        view_state: &mut V,
 97        cx: &mut ViewContext<V>,
 98    ) -> Size<Pixels>;
 99    fn draw(
100        &mut self,
101        origin: Point<Pixels>,
102        available_space: Size<AvailableSpace>,
103        view_state: &mut V,
104        cx: &mut ViewContext<V>,
105    );
106}
107
108struct RenderedElement<V: 'static, E: Element<V>> {
109    element: E,
110    phase: ElementRenderPhase<E::ElementState>,
111}
112
113#[derive(Default)]
114enum ElementRenderPhase<V> {
115    #[default]
116    Start,
117    LayoutRequested {
118        layout_id: LayoutId,
119        frame_state: Option<V>,
120    },
121    LayoutComputed {
122        layout_id: LayoutId,
123        available_space: Size<AvailableSpace>,
124        frame_state: Option<V>,
125    },
126    Painted {
127        frame_state: Option<V>,
128    },
129}
130
131/// Internal struct that wraps an element to store Layout and ElementState after the element is rendered.
132/// It's allocated as a trait object to erase the element type and wrapped in AnyElement<E::State> for
133/// improved usability.
134impl<V, E: Element<V>> RenderedElement<V, E> {
135    fn new(element: E) -> Self {
136        RenderedElement {
137            element,
138            phase: ElementRenderPhase::Start,
139        }
140    }
141}
142
143impl<V, E> ElementObject<V> for RenderedElement<V, E>
144where
145    E: Element<V>,
146    E::ElementState: 'static,
147{
148    fn element_id(&self) -> Option<ElementId> {
149        self.element.element_id()
150    }
151
152    fn layout(&mut self, state: &mut V, cx: &mut ViewContext<V>) -> LayoutId {
153        let (layout_id, frame_state) = match mem::take(&mut self.phase) {
154            ElementRenderPhase::Start => {
155                if let Some(id) = self.element.element_id() {
156                    let layout_id = cx.with_element_state(id, |element_state, cx| {
157                        self.element.layout(state, element_state, cx)
158                    });
159                    (layout_id, None)
160                } else {
161                    let (layout_id, frame_state) = self.element.layout(state, None, cx);
162                    (layout_id, Some(frame_state))
163                }
164            }
165            ElementRenderPhase::LayoutRequested { .. }
166            | ElementRenderPhase::LayoutComputed { .. }
167            | ElementRenderPhase::Painted { .. } => {
168                panic!("element rendered twice")
169            }
170        };
171
172        self.phase = ElementRenderPhase::LayoutRequested {
173            layout_id,
174            frame_state,
175        };
176        layout_id
177    }
178
179    fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
180        self.phase = match mem::take(&mut self.phase) {
181            ElementRenderPhase::LayoutRequested {
182                layout_id,
183                mut frame_state,
184            }
185            | ElementRenderPhase::LayoutComputed {
186                layout_id,
187                mut frame_state,
188                ..
189            } => {
190                let bounds = cx.layout_bounds(layout_id);
191                if let Some(id) = self.element.element_id() {
192                    cx.with_element_state(id, |element_state, cx| {
193                        let mut element_state = element_state.unwrap();
194                        self.element
195                            .paint(bounds, view_state, &mut element_state, cx);
196                        ((), element_state)
197                    });
198                } else {
199                    self.element
200                        .paint(bounds, view_state, frame_state.as_mut().unwrap(), cx);
201                }
202                ElementRenderPhase::Painted { frame_state }
203            }
204
205            _ => panic!("must call layout before paint"),
206        };
207    }
208
209    fn measure(
210        &mut self,
211        available_space: Size<AvailableSpace>,
212        view_state: &mut V,
213        cx: &mut ViewContext<V>,
214    ) -> Size<Pixels> {
215        if matches!(&self.phase, ElementRenderPhase::Start) {
216            self.layout(view_state, cx);
217        }
218
219        let layout_id = match &mut self.phase {
220            ElementRenderPhase::LayoutRequested {
221                layout_id,
222                frame_state,
223            } => {
224                cx.compute_layout(*layout_id, available_space);
225                let layout_id = *layout_id;
226                self.phase = ElementRenderPhase::LayoutComputed {
227                    layout_id,
228                    available_space,
229                    frame_state: frame_state.take(),
230                };
231                layout_id
232            }
233            ElementRenderPhase::LayoutComputed {
234                layout_id,
235                available_space: prev_available_space,
236                ..
237            } => {
238                if available_space != *prev_available_space {
239                    cx.compute_layout(*layout_id, available_space);
240                    *prev_available_space = available_space;
241                }
242                *layout_id
243            }
244            _ => panic!("cannot measure after painting"),
245        };
246
247        cx.layout_bounds(layout_id).size
248    }
249
250    fn draw(
251        &mut self,
252        origin: Point<Pixels>,
253        available_space: Size<AvailableSpace>,
254        view_state: &mut V,
255        cx: &mut ViewContext<V>,
256    ) {
257        self.measure(available_space, view_state, cx);
258        cx.with_absolute_element_offset(origin, |cx| self.paint(view_state, cx))
259    }
260}
261
262pub struct AnyElement<V>(Box<dyn ElementObject<V>>);
263
264impl<V> AnyElement<V> {
265    pub fn new<E>(element: E) -> Self
266    where
267        V: 'static,
268        E: 'static + Element<V>,
269        E::ElementState: Any,
270    {
271        AnyElement(Box::new(RenderedElement::new(element)))
272    }
273
274    pub fn element_id(&self) -> Option<ElementId> {
275        self.0.element_id()
276    }
277
278    pub fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId {
279        self.0.layout(view_state, cx)
280    }
281
282    pub fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
283        self.0.paint(view_state, cx)
284    }
285
286    /// Initializes this element and performs layout within the given available space to determine its size.
287    pub fn measure(
288        &mut self,
289        available_space: Size<AvailableSpace>,
290        view_state: &mut V,
291        cx: &mut ViewContext<V>,
292    ) -> Size<Pixels> {
293        self.0.measure(available_space, view_state, cx)
294    }
295
296    /// Initializes this element and performs layout in the available space, then paints it at the given origin.
297    pub fn draw(
298        &mut self,
299        origin: Point<Pixels>,
300        available_space: Size<AvailableSpace>,
301        view_state: &mut V,
302        cx: &mut ViewContext<V>,
303    ) {
304        self.0.draw(origin, available_space, view_state, cx)
305    }
306}
307
308pub trait Component<V> {
309    fn render(self) -> AnyElement<V>;
310
311    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
312    where
313        Self: Sized,
314        U: Component<V>,
315    {
316        f(self)
317    }
318
319    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
320    where
321        Self: Sized,
322    {
323        self.map(|this| if condition { then(this) } else { this })
324    }
325
326    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
327    where
328        Self: Sized,
329    {
330        self.map(|this| {
331            if let Some(value) = option {
332                then(this, value)
333            } else {
334                this
335            }
336        })
337    }
338}
339
340impl<V> Component<V> for AnyElement<V> {
341    fn render(self) -> AnyElement<V> {
342        self
343    }
344}
345
346impl<V, E, F> Element<V> for Option<F>
347where
348    V: 'static,
349    E: 'static + Component<V>,
350    F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
351{
352    type ElementState = AnyElement<V>;
353
354    fn element_id(&self) -> Option<ElementId> {
355        None
356    }
357
358    fn layout(
359        &mut self,
360        view_state: &mut V,
361        _: Option<Self::ElementState>,
362        cx: &mut ViewContext<V>,
363    ) -> (LayoutId, Self::ElementState) {
364        let render = self.take().unwrap();
365        let mut rendered_element = (render)(view_state, cx).render();
366        let layout_id = rendered_element.layout(view_state, cx);
367        (layout_id, rendered_element)
368    }
369
370    fn paint(
371        &mut self,
372        _bounds: Bounds<Pixels>,
373        view_state: &mut V,
374        rendered_element: &mut Self::ElementState,
375        cx: &mut ViewContext<V>,
376    ) {
377        rendered_element.paint(view_state, cx)
378    }
379}
380
381impl<V, E, F> Component<V> for Option<F>
382where
383    V: 'static,
384    E: 'static + Component<V>,
385    F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
386{
387    fn render(self) -> AnyElement<V> {
388        AnyElement::new(self)
389    }
390}
391
392impl<V, E, F> Component<V> for F
393where
394    V: 'static,
395    E: 'static + Component<V>,
396    F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
397{
398    fn render(self) -> AnyElement<V> {
399        AnyElement::new(Some(self))
400    }
401}