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
217impl<V> Component<V> for AnyElement<V> {
218 fn render(self) -> AnyElement<V> {
219 self
220 }
221}
222
223impl<V, E, F> Element<V> for Option<F>
224where
225 V: 'static,
226 E: 'static + Component<V>,
227 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
228{
229 type ElementState = AnyElement<V>;
230
231 fn id(&self) -> Option<ElementId> {
232 None
233 }
234
235 fn initialize(
236 &mut self,
237 view_state: &mut V,
238 _rendered_element: Option<Self::ElementState>,
239 cx: &mut ViewContext<V>,
240 ) -> Self::ElementState {
241 let render = self.take().unwrap();
242 let mut rendered_element = (render)(view_state, cx).render();
243 rendered_element.initialize(view_state, cx);
244 rendered_element
245 }
246
247 fn layout(
248 &mut self,
249 view_state: &mut V,
250 rendered_element: &mut Self::ElementState,
251 cx: &mut ViewContext<V>,
252 ) -> LayoutId {
253 rendered_element.layout(view_state, cx)
254 }
255
256 fn paint(
257 &mut self,
258 _bounds: Bounds<Pixels>,
259 view_state: &mut V,
260 rendered_element: &mut Self::ElementState,
261 cx: &mut ViewContext<V>,
262 ) {
263 rendered_element.paint(view_state, cx)
264 }
265}
266
267impl<V, E, F> Component<V> for Option<F>
268where
269 V: 'static,
270 E: 'static + Component<V>,
271 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
272{
273 fn render(self) -> AnyElement<V> {
274 AnyElement::new(self)
275 }
276}
277
278impl<V, E, F> Component<V> for F
279where
280 V: 'static,
281 E: 'static + Component<V>,
282 F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
283{
284 fn render(self) -> AnyElement<V> {
285 AnyElement::new(Some(self))
286 }
287}