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
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,
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>>);
174
175impl<V> AnyElement<V> {
176 pub fn new<E>(element: E) -> Self
177 where
178 V: 'static,
179 E: 'static + Element<V>,
180 E::ElementState: Any,
181 {
182 AnyElement(Box::new(RenderedElement::new(element)))
183 }
184
185 pub fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
186 self.0.initialize(view_state, cx);
187 }
188
189 pub fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId {
190 self.0.layout(view_state, cx)
191 }
192
193 pub fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
194 self.0.paint(view_state, cx)
195 }
196}
197
198pub trait Component<V> {
199 fn render(self) -> AnyElement<V>;
200
201 fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
202 where
203 Self: Sized,
204 U: Component<V>,
205 {
206 f(self)
207 }
208
209 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
210 where
211 Self: Sized,
212 {
213 self.map(|this| if condition { then(this) } else { this })
214 }
215
216 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
217 where
218 Self: Sized,
219 {
220 self.map(|this| {
221 if let Some(value) = option {
222 then(this, value)
223 } else {
224 this
225 }
226 })
227 }
228}
229
230impl<V> Component<V> for AnyElement<V> {
231 fn render(self) -> AnyElement<V> {
232 self
233 }
234}
235
236impl<V, E, F> Element<V> for Option<F>
237where
238 V: 'static,
239 E: 'static + Component<V>,
240 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
241{
242 type ElementState = AnyElement<V>;
243
244 fn id(&self) -> Option<ElementId> {
245 None
246 }
247
248 fn initialize(
249 &mut self,
250 view_state: &mut V,
251 _rendered_element: Option<Self::ElementState>,
252 cx: &mut ViewContext<V>,
253 ) -> Self::ElementState {
254 let render = self.take().unwrap();
255 let mut rendered_element = (render)(view_state, cx).render();
256 rendered_element.initialize(view_state, cx);
257 rendered_element
258 }
259
260 fn layout(
261 &mut self,
262 view_state: &mut V,
263 rendered_element: &mut Self::ElementState,
264 cx: &mut ViewContext<V>,
265 ) -> LayoutId {
266 rendered_element.layout(view_state, cx)
267 }
268
269 fn paint(
270 &mut self,
271 _bounds: Bounds<Pixels>,
272 view_state: &mut V,
273 rendered_element: &mut Self::ElementState,
274 cx: &mut ViewContext<V>,
275 ) {
276 rendered_element.paint(view_state, cx)
277 }
278}
279
280impl<V, E, F> Component<V> for Option<F>
281where
282 V: 'static,
283 E: 'static + Component<V>,
284 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
285{
286 fn render(self) -> AnyElement<V> {
287 AnyElement::new(self)
288 }
289}
290
291impl<V, E, F> Component<V> for F
292where
293 V: 'static,
294 E: 'static + Component<V>,
295 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
296{
297 fn render(self) -> AnyElement<V> {
298 AnyElement::new(Some(self))
299 }
300}