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