1use crate::{
2 ArenaBox, AvailableSpace, BorrowWindow, Bounds, ElementId, LayoutId, Pixels, Point, Size,
3 ViewContext, WindowContext, ELEMENT_ARENA,
4};
5use derive_more::{Deref, DerefMut};
6pub(crate) use smallvec::SmallVec;
7use std::{any::Any, fmt::Debug};
8
9/// Implemented by types that participate in laying out and painting the contents of a window.
10/// Elements form a tree and are laid out according to web-based layout rules.
11/// Rather than calling methods on implementers of this trait directly, you'll usually call `into_any` to convert them into an AnyElement, which manages state internally.
12/// You can create custom elements by implementing this trait.
13pub trait Element: 'static + IntoElement {
14 type State: 'static;
15
16 fn request_layout(
17 &mut self,
18 state: Option<Self::State>,
19 cx: &mut WindowContext,
20 ) -> (LayoutId, Self::State);
21
22 fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut WindowContext);
23
24 fn into_any(self) -> AnyElement {
25 AnyElement::new(self)
26 }
27}
28
29/// Implemented by any type that can be converted into an element.
30pub trait IntoElement: Sized {
31 /// The specific type of element into which the implementing type is converted.
32 type Element: Element;
33
34 /// The [ElementId] of self once converted into an [Element].
35 /// If present, the resulting element's state will be carried across frames.
36 fn element_id(&self) -> Option<ElementId>;
37
38 /// Convert self into a type that implements [Element].
39 fn into_element(self) -> Self::Element;
40
41 /// Convert self into a dynamically-typed [AnyElement].
42 fn into_any_element(self) -> AnyElement {
43 self.into_element().into_any()
44 }
45
46 /// Convert into an element, then draw in the current window at the given origin.
47 /// The provided available space is provided to the layout engine to determine the size of the root element.
48 /// Once the element is drawn, its associated element staet is yielded to the given callback.
49 fn draw_and_update_state<T, R>(
50 self,
51 origin: Point<Pixels>,
52 available_space: Size<T>,
53 cx: &mut WindowContext,
54 f: impl FnOnce(&mut <Self::Element as Element>::State, &mut WindowContext) -> R,
55 ) -> R
56 where
57 T: Clone + Default + Debug + Into<AvailableSpace>,
58 {
59 let element = self.into_element();
60 let element_id = element.element_id();
61 let element = DrawableElement {
62 element: Some(element),
63 phase: ElementDrawPhase::Start,
64 };
65
66 let frame_state =
67 DrawableElement::draw(element, origin, available_space.map(Into::into), cx);
68
69 if let Some(mut frame_state) = frame_state {
70 f(&mut frame_state, cx)
71 } else {
72 cx.with_element_state(element_id.unwrap(), |element_state, cx| {
73 let mut element_state = element_state.unwrap();
74 let result = f(&mut element_state, cx);
75 (result, element_state)
76 })
77 }
78 }
79
80 /// Convert self to another type by calling the given closure. Useful in rendering code.
81 fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
82 where
83 Self: Sized,
84 U: IntoElement,
85 {
86 f(self)
87 }
88
89 /// Conditionally chain onto self with the given closure. Useful in rendering code.
90 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
91 where
92 Self: Sized,
93 {
94 self.map(|this| if condition { then(this) } else { this })
95 }
96
97 /// Conditionally chain onto self with the given closure if the given option is Some.
98 /// The contents of the option are provided to the closure.
99 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
100 where
101 Self: Sized,
102 {
103 self.map(|this| {
104 if let Some(value) = option {
105 then(this, value)
106 } else {
107 this
108 }
109 })
110 }
111}
112
113pub trait Render: 'static + Sized {
114 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement;
115}
116
117/// You can derive [IntoElement] on any type that implements this trait.
118/// It is used to allow views to be expressed in terms of abstract data.
119pub trait RenderOnce: 'static {
120 fn render(self, cx: &mut WindowContext) -> impl IntoElement;
121}
122
123pub trait ParentElement {
124 fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]>;
125
126 fn child(mut self, child: impl IntoElement) -> Self
127 where
128 Self: Sized,
129 {
130 self.children_mut().push(child.into_element().into_any());
131 self
132 }
133
134 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self
135 where
136 Self: Sized,
137 {
138 self.children_mut()
139 .extend(children.into_iter().map(|child| child.into_any_element()));
140 self
141 }
142}
143
144pub struct Component<C: RenderOnce>(Option<C>);
145
146impl<C: RenderOnce> Component<C> {
147 pub fn new(component: C) -> Self {
148 Component(Some(component))
149 }
150}
151
152impl<C: RenderOnce> Element for Component<C> {
153 type State = AnyElement;
154
155 fn request_layout(
156 &mut self,
157 _: Option<Self::State>,
158 cx: &mut WindowContext,
159 ) -> (LayoutId, Self::State) {
160 let mut element = self.0.take().unwrap().render(cx).into_any_element();
161 let layout_id = element.request_layout(cx);
162 (layout_id, element)
163 }
164
165 fn paint(&mut self, _: Bounds<Pixels>, element: &mut Self::State, cx: &mut WindowContext) {
166 element.paint(cx)
167 }
168}
169
170impl<C: RenderOnce> IntoElement for Component<C> {
171 type Element = Self;
172
173 fn element_id(&self) -> Option<ElementId> {
174 None
175 }
176
177 fn into_element(self) -> Self::Element {
178 self
179 }
180}
181
182#[derive(Deref, DerefMut, Default, Clone, Debug, Eq, PartialEq, Hash)]
183pub struct GlobalElementId(SmallVec<[ElementId; 32]>);
184
185trait ElementObject {
186 fn element_id(&self) -> Option<ElementId>;
187
188 fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId;
189
190 fn paint(&mut self, cx: &mut WindowContext);
191
192 fn measure(
193 &mut self,
194 available_space: Size<AvailableSpace>,
195 cx: &mut WindowContext,
196 ) -> Size<Pixels>;
197
198 fn draw(
199 &mut self,
200 origin: Point<Pixels>,
201 available_space: Size<AvailableSpace>,
202 cx: &mut WindowContext,
203 );
204}
205
206pub struct DrawableElement<E: Element> {
207 element: Option<E>,
208 phase: ElementDrawPhase<E::State>,
209}
210
211#[derive(Default)]
212enum ElementDrawPhase<S> {
213 #[default]
214 Start,
215 LayoutRequested {
216 layout_id: LayoutId,
217 frame_state: Option<S>,
218 },
219 LayoutComputed {
220 layout_id: LayoutId,
221 available_space: Size<AvailableSpace>,
222 frame_state: Option<S>,
223 },
224}
225
226/// A wrapper around an implementer of [Element] that allows it to be drawn in a window.
227impl<E: Element> DrawableElement<E> {
228 fn new(element: E) -> Self {
229 DrawableElement {
230 element: Some(element),
231 phase: ElementDrawPhase::Start,
232 }
233 }
234
235 fn element_id(&self) -> Option<ElementId> {
236 self.element.as_ref()?.element_id()
237 }
238
239 fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId {
240 let (layout_id, frame_state) = if let Some(id) = self.element.as_ref().unwrap().element_id()
241 {
242 let layout_id = cx.with_element_state(id, |element_state, cx| {
243 self.element
244 .as_mut()
245 .unwrap()
246 .request_layout(element_state, cx)
247 });
248 (layout_id, None)
249 } else {
250 let (layout_id, frame_state) = self.element.as_mut().unwrap().request_layout(None, cx);
251 (layout_id, Some(frame_state))
252 };
253
254 self.phase = ElementDrawPhase::LayoutRequested {
255 layout_id,
256 frame_state,
257 };
258 layout_id
259 }
260
261 fn paint(mut self, cx: &mut WindowContext) -> Option<E::State> {
262 match self.phase {
263 ElementDrawPhase::LayoutRequested {
264 layout_id,
265 frame_state,
266 }
267 | ElementDrawPhase::LayoutComputed {
268 layout_id,
269 frame_state,
270 ..
271 } => {
272 let bounds = cx.layout_bounds(layout_id);
273
274 if let Some(mut frame_state) = frame_state {
275 self.element
276 .take()
277 .unwrap()
278 .paint(bounds, &mut frame_state, cx);
279 Some(frame_state)
280 } else {
281 let element_id = self
282 .element
283 .as_ref()
284 .unwrap()
285 .element_id()
286 .expect("if we don't have frame state, we should have element state");
287 cx.with_element_state(element_id, |element_state, cx| {
288 let mut element_state = element_state.unwrap();
289 self.element
290 .take()
291 .unwrap()
292 .paint(bounds, &mut element_state, cx);
293 ((), element_state)
294 });
295 None
296 }
297 }
298
299 _ => panic!("must call layout before paint"),
300 }
301 }
302
303 fn measure(
304 &mut self,
305 available_space: Size<AvailableSpace>,
306 cx: &mut WindowContext,
307 ) -> Size<Pixels> {
308 if matches!(&self.phase, ElementDrawPhase::Start) {
309 self.request_layout(cx);
310 }
311
312 let layout_id = match &mut self.phase {
313 ElementDrawPhase::LayoutRequested {
314 layout_id,
315 frame_state,
316 } => {
317 cx.compute_layout(*layout_id, available_space);
318 let layout_id = *layout_id;
319 self.phase = ElementDrawPhase::LayoutComputed {
320 layout_id,
321 available_space,
322 frame_state: frame_state.take(),
323 };
324 layout_id
325 }
326 ElementDrawPhase::LayoutComputed {
327 layout_id,
328 available_space: prev_available_space,
329 ..
330 } => {
331 if available_space != *prev_available_space {
332 cx.compute_layout(*layout_id, available_space);
333 *prev_available_space = available_space;
334 }
335 *layout_id
336 }
337 _ => panic!("cannot measure after painting"),
338 };
339
340 cx.layout_bounds(layout_id).size
341 }
342
343 fn draw(
344 mut self,
345 origin: Point<Pixels>,
346 available_space: Size<AvailableSpace>,
347 cx: &mut WindowContext,
348 ) -> Option<E::State> {
349 self.measure(available_space, cx);
350 cx.with_absolute_element_offset(origin, |cx| self.paint(cx))
351 }
352}
353
354impl<E> ElementObject for Option<DrawableElement<E>>
355where
356 E: Element,
357 E::State: 'static,
358{
359 fn element_id(&self) -> Option<ElementId> {
360 self.as_ref().unwrap().element_id()
361 }
362
363 fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId {
364 DrawableElement::request_layout(self.as_mut().unwrap(), cx)
365 }
366
367 fn paint(&mut self, cx: &mut WindowContext) {
368 DrawableElement::paint(self.take().unwrap(), cx);
369 }
370
371 fn measure(
372 &mut self,
373 available_space: Size<AvailableSpace>,
374 cx: &mut WindowContext,
375 ) -> Size<Pixels> {
376 DrawableElement::measure(self.as_mut().unwrap(), available_space, cx)
377 }
378
379 fn draw(
380 &mut self,
381 origin: Point<Pixels>,
382 available_space: Size<AvailableSpace>,
383 cx: &mut WindowContext,
384 ) {
385 DrawableElement::draw(self.take().unwrap(), origin, available_space, cx);
386 }
387}
388
389pub struct AnyElement(ArenaBox<dyn ElementObject>);
390
391impl AnyElement {
392 pub fn new<E>(element: E) -> Self
393 where
394 E: 'static + Element,
395 E::State: Any,
396 {
397 let element = ELEMENT_ARENA
398 .with_borrow_mut(|arena| arena.alloc(|| Some(DrawableElement::new(element))))
399 .map(|element| element as &mut dyn ElementObject);
400 AnyElement(element)
401 }
402
403 pub fn request_layout(&mut self, cx: &mut WindowContext) -> LayoutId {
404 self.0.request_layout(cx)
405 }
406
407 pub fn paint(&mut self, cx: &mut WindowContext) {
408 self.0.paint(cx)
409 }
410
411 /// Initializes this element and performs layout within the given available space to determine its size.
412 pub fn measure(
413 &mut self,
414 available_space: Size<AvailableSpace>,
415 cx: &mut WindowContext,
416 ) -> Size<Pixels> {
417 self.0.measure(available_space, cx)
418 }
419
420 /// Initializes this element and performs layout in the available space, then paints it at the given origin.
421 pub fn draw(
422 &mut self,
423 origin: Point<Pixels>,
424 available_space: Size<AvailableSpace>,
425 cx: &mut WindowContext,
426 ) {
427 self.0.draw(origin, available_space, cx)
428 }
429
430 pub fn inner_id(&self) -> Option<ElementId> {
431 self.0.element_id()
432 }
433}
434
435impl Element for AnyElement {
436 type State = ();
437
438 fn request_layout(
439 &mut self,
440 _: Option<Self::State>,
441 cx: &mut WindowContext,
442 ) -> (LayoutId, Self::State) {
443 let layout_id = self.request_layout(cx);
444 (layout_id, ())
445 }
446
447 fn paint(&mut self, _: Bounds<Pixels>, _: &mut Self::State, cx: &mut WindowContext) {
448 self.paint(cx)
449 }
450}
451
452impl IntoElement for AnyElement {
453 type Element = Self;
454
455 fn element_id(&self) -> Option<ElementId> {
456 None
457 }
458
459 fn into_element(self) -> Self::Element {
460 self
461 }
462
463 fn into_any_element(self) -> AnyElement {
464 self
465 }
466}
467
468/// The empty element, which renders nothing.
469pub type Empty = ();
470
471impl IntoElement for () {
472 type Element = Self;
473
474 fn element_id(&self) -> Option<ElementId> {
475 None
476 }
477
478 fn into_element(self) -> Self::Element {
479 self
480 }
481}
482
483impl Element for () {
484 type State = ();
485
486 fn request_layout(
487 &mut self,
488 _state: Option<Self::State>,
489 cx: &mut WindowContext,
490 ) -> (LayoutId, Self::State) {
491 (cx.request_layout(&crate::Style::default(), None), ())
492 }
493
494 fn paint(
495 &mut self,
496 _bounds: Bounds<Pixels>,
497 _state: &mut Self::State,
498 _cx: &mut WindowContext,
499 ) {
500 }
501}