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 ElementRenderPhase::Start => panic!("must call initialize before layout"),
138 ElementRenderPhase::LayoutRequested { .. } | ElementRenderPhase::Painted => {
139 panic!("element rendered twice")
140 }
141 };
142
143 self.phase = ElementRenderPhase::LayoutRequested {
144 layout_id,
145 frame_state,
146 };
147 layout_id
148 }
149
150 fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
151 self.phase = match mem::take(&mut self.phase) {
152 ElementRenderPhase::LayoutRequested {
153 layout_id,
154 mut frame_state,
155 } => {
156 let bounds = cx.layout_bounds(layout_id);
157 if let Some(id) = self.element.id() {
158 cx.with_element_state(id, |element_state, cx| {
159 let mut element_state = element_state.unwrap();
160 self.element
161 .paint(bounds, view_state, &mut element_state, cx);
162 ((), element_state)
163 });
164 } else {
165 self.element
166 .paint(bounds, view_state, frame_state.as_mut().unwrap(), cx);
167 }
168 ElementRenderPhase::Painted
169 }
170
171 _ => panic!("must call layout before paint"),
172 };
173 }
174}
175
176pub struct AnyElement<V>(Box<dyn ElementObject<V>>);
177
178impl<V> AnyElement<V> {
179 pub fn new<E>(element: E) -> Self
180 where
181 V: 'static,
182 E: 'static + Element<V>,
183 E::ElementState: Any,
184 {
185 AnyElement(Box::new(RenderedElement::new(element)))
186 }
187
188 pub fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
189 self.0.initialize(view_state, cx);
190 }
191
192 pub fn layout(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) -> LayoutId {
193 self.0.layout(view_state, cx)
194 }
195
196 pub fn paint(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
197 self.0.paint(view_state, cx)
198 }
199}
200
201pub trait Component<V> {
202 fn render(self) -> AnyElement<V>;
203
204 fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
205 where
206 Self: Sized,
207 U: Component<V>,
208 {
209 f(self)
210 }
211
212 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
213 where
214 Self: Sized,
215 {
216 self.map(|this| if condition { then(this) } else { this })
217 }
218
219 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
220 where
221 Self: Sized,
222 {
223 self.map(|this| {
224 if let Some(value) = option {
225 then(this, value)
226 } else {
227 this
228 }
229 })
230 }
231}
232
233impl<V> Component<V> for AnyElement<V> {
234 fn render(self) -> AnyElement<V> {
235 self
236 }
237}
238
239impl<V, E, F> Element<V> for Option<F>
240where
241 V: 'static,
242 E: 'static + Component<V>,
243 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
244{
245 type ElementState = AnyElement<V>;
246
247 fn id(&self) -> Option<ElementId> {
248 None
249 }
250
251 fn initialize(
252 &mut self,
253 view_state: &mut V,
254 _rendered_element: Option<Self::ElementState>,
255 cx: &mut ViewContext<V>,
256 ) -> Self::ElementState {
257 let render = self.take().unwrap();
258 let mut rendered_element = (render)(view_state, cx).render();
259 rendered_element.initialize(view_state, cx);
260 rendered_element
261 }
262
263 fn layout(
264 &mut self,
265 view_state: &mut V,
266 rendered_element: &mut Self::ElementState,
267 cx: &mut ViewContext<V>,
268 ) -> LayoutId {
269 rendered_element.layout(view_state, cx)
270 }
271
272 fn paint(
273 &mut self,
274 _bounds: Bounds<Pixels>,
275 view_state: &mut V,
276 rendered_element: &mut Self::ElementState,
277 cx: &mut ViewContext<V>,
278 ) {
279 rendered_element.paint(view_state, cx)
280 }
281}
282
283impl<V, E, F> Component<V> for Option<F>
284where
285 V: 'static,
286 E: 'static + Component<V>,
287 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
288{
289 fn render(self) -> AnyElement<V> {
290 AnyElement::new(self)
291 }
292}
293
294impl<V, E, F> Component<V> for F
295where
296 V: 'static,
297 E: 'static + Component<V>,
298 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
299{
300 fn render(self) -> AnyElement<V> {
301 AnyElement::new(Some(self))
302 }
303}