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