Skip to main content

gpui_authoring/
element.rs

1//! Elements are the workhorses of GPUI. They are responsible for laying out and painting all of
2//! the contents of a window. Elements form a tree and are laid out according to the web layout
3//! standards as implemented by [taffy](https://github.com/DioxusLabs/taffy). Most of the time,
4//! you won't need to interact with this module or these APIs directly. Elements provide their
5//! own APIs and GPUI, or other element implementation, uses the APIs in this module to convert
6//! that element tree into the pixels you see on the screen.
7//!
8//! # Element Basics
9//!
10//! Elements are constructed by calling [`Render::render()`] on the root view of the window,
11//! which recursively constructs the element tree from the current state of the application,.
12//! These elements are then laid out by Taffy, and painted to the screen according to their own
13//! implementation of [`Element::paint()`]. Before the start of the next frame, the entire element
14//! tree and any callbacks they have registered with GPUI are dropped and the process repeats.
15//!
16//! But some state is too simple and voluminous to store in every view that needs it, e.g.
17//! whether a hover has been started or not. For this, GPUI provides the [`Element::PrepaintState`], associated type.
18//!
19//! # Implementing your own elements
20//!
21//! Elements are intended to be the low level, imperative API to GPUI. They are responsible for upholding,
22//! or breaking, GPUI's features as they deem necessary. As an example, most GPUI elements are expected
23//! to stay in the bounds that their parent element gives them. But with [`Window::with_content_mask`],
24//! you can ignore this restriction and paint anywhere inside of the window's bounds. This is useful for overlays
25//! and popups and anything else that shows up 'on top' of other elements.
26//! With great power, comes great responsibility.
27//!
28//! However, most of the time, you won't need to implement your own elements. GPUI provides a number of
29//! elements that should cover most common use cases out of the box and it's recommended that you use those
30//! to construct `components`, using the [`RenderOnce`] trait and the `#[derive(IntoElement)]` macro. Only implement
31//! elements when you need to take manual control of the layout and painting process, such as when using
32//! your own custom layout algorithm or rendering a code editor.
33
34use crate::{
35    A11ySubtreeBuilder, App, ArenaBox, AvailableSpace, Bounds, Context, DispatchNodeId, ElementId,
36    FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,
37    util::FluentBuilder, window::with_element_arena,
38};
39use derive_more::{Deref, DerefMut};
40use std::{
41    any::Any,
42    fmt::{self, Debug, Display},
43    mem, panic,
44    sync::Arc,
45};
46
47/// Implemented by types that participate in laying out and painting the contents of a window.
48/// Elements form a tree and are laid out according to web-based layout rules, as implemented by Taffy.
49///
50/// You can create custom elements by implementing this trait. See the
51/// [authoring guide](crate::_authoring) for the three-phase lifecycle and for the
52/// methods an element may call while laying out and painting.
53pub trait Element: 'static + IntoElement {
54    /// The type of state returned from [`Element::request_layout`]. A mutable reference to this state is subsequently
55    /// provided to [`Element::prepaint`] and [`Element::paint`].
56    type RequestLayoutState: 'static;
57
58    /// The type of state returned from [`Element::prepaint`]. A mutable reference to this state is subsequently
59    /// provided to [`Element::paint`].
60    type PrepaintState: 'static;
61
62    /// If this element has a unique identifier, return it here. This is used to track elements across frames, and
63    /// will cause a GlobalElementId to be passed to the request_layout, prepaint, and paint methods.
64    ///
65    /// The global id can in turn be used to access state that's connected to an element with the same id across
66    /// frames. This id must be unique among children of the first containing element with an id.
67    fn id(&self) -> Option<ElementId>;
68
69    /// Source location where this element was constructed, used to disambiguate elements in the
70    /// inspector and navigate to their source code.
71    fn source_location(&self) -> Option<&'static panic::Location<'static>>;
72
73    /// Before an element can be painted, we need to know where it's going to be and how big it is.
74    /// Use this method to request a layout from Taffy and initialize the element's state.
75    fn request_layout(
76        &mut self,
77        id: Option<&GlobalElementId>,
78        window: &mut Window,
79        cx: &mut App,
80    ) -> (LayoutId, Self::RequestLayoutState);
81
82    /// After laying out an element, we need to commit its bounds to the current frame for hitbox
83    /// purposes. The state argument is the same state that was returned from [`Element::request_layout()`].
84    fn prepaint(
85        &mut self,
86        id: Option<&GlobalElementId>,
87        bounds: Bounds<Pixels>,
88        request_layout: &mut Self::RequestLayoutState,
89        window: &mut Window,
90        cx: &mut App,
91    ) -> Self::PrepaintState;
92
93    /// Once layout has been completed, this method will be called to paint the element to the screen.
94    /// The state argument is the same state that was returned from [`Element::request_layout()`].
95    fn paint(
96        &mut self,
97        id: Option<&GlobalElementId>,
98        bounds: Bounds<Pixels>,
99        request_layout: &mut Self::RequestLayoutState,
100        prepaint: &mut Self::PrepaintState,
101        window: &mut Window,
102        cx: &mut App,
103    );
104
105    /// Returns the accessible role for this element, if any.
106    /// Elements that return `None` are not included in the accessibility tree.
107    ///
108    /// Note: inclusion in accessibility tree requires non-`None` [`id`][Element::id].
109    ///
110    /// See the [accessibility guide](crate::_accessibility) for an overview.
111    fn a11y_role(&self) -> Option<accesskit::Role> {
112        None
113    }
114
115    /// Write accessibility properties to the given node.
116    /// Called only when `a11y_role()` returns `Some`.
117    ///
118    /// See the [accessibility guide](crate::_accessibility) for an overview.
119    fn write_a11y_info(&self, _node: &mut accesskit::Node) {}
120
121    /// Add synthetic child nodes to an [`Element`] that has an
122    /// [`.id()`][Element::id] and a [`.role()`][Element::a11y_role].
123    ///
124    /// Some elements may want to inject accessibility nodes that do not
125    /// correspond to any GPUI element. For example, a custom text field element
126    /// may want to inject synthetic child nodes for the text content.
127    ///
128    /// See [Synthetic children](crate::_accessibility#synthetic-children) in
129    /// the accessibility guide for more detail.
130    fn a11y_synthetic_children(
131        &mut self,
132        _prepaint: &mut Self::PrepaintState,
133        _builder: &mut A11ySubtreeBuilder,
134    ) {
135    }
136
137    /// Convert this element into a dynamically-typed [`AnyElement`].
138    fn into_any(self) -> AnyElement {
139        AnyElement::new(self)
140    }
141}
142
143/// Implemented by any type that can be converted into an element.
144pub trait IntoElement: Sized {
145    /// The specific type of element into which the implementing type is converted.
146    /// Useful for converting other types into elements automatically, like Strings
147    type Element: Element;
148
149    /// Convert self into a type that implements [`Element`].
150    fn into_element(self) -> Self::Element;
151
152    /// Convert self into a dynamically-typed [`AnyElement`].
153    fn into_any_element(self) -> AnyElement {
154        self.into_element().into_any()
155    }
156}
157
158impl<T: IntoElement> FluentBuilder for T {}
159
160/// An object that can be drawn to the screen. This is the trait that distinguishes "views" from
161/// other entities. Views are `Entity`'s which `impl Render` and drawn to the screen.
162pub trait Render: 'static + Sized {
163    /// Render this view into an element tree.
164    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement;
165}
166
167impl Render for Empty {
168    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
169        Empty
170    }
171}
172
173/// You can derive [`IntoElement`] on any type that implements this trait.
174/// It is used to construct reusable `components` out of plain data. Think of
175/// components as a recipe for a certain pattern of elements. RenderOnce allows
176/// you to invoke this pattern, without breaking the fluent builder pattern of
177/// the element APIs.
178pub trait RenderOnce: 'static {
179    /// Render this component into an element tree. Note that this method
180    /// takes ownership of self, as compared to [`Render::render()`] method
181    /// which takes a mutable reference.
182    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
183}
184
185/// This is a helper trait to provide a uniform interface for constructing elements that
186/// can accept any number of any kind of child elements
187pub trait ParentElement {
188    /// Extend this element's children with the given child elements.
189    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>);
190
191    /// Add a single child element to this element.
192    fn child(mut self, child: impl IntoElement) -> Self
193    where
194        Self: Sized,
195    {
196        self.extend(std::iter::once(child.into_any_element()));
197        self
198    }
199
200    /// Add multiple child elements to this element.
201    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self
202    where
203        Self: Sized,
204    {
205        self.extend(children.into_iter().map(|child| child.into_any_element()));
206        self
207    }
208}
209
210/// A globally unique identifier for an element, used to track state across frames.
211#[derive(Deref, DerefMut, Clone, Default, Debug, Eq, PartialEq, Hash)]
212pub struct GlobalElementId(pub(crate) Arc<[ElementId]>);
213
214impl Display for GlobalElementId {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        for (i, element_id) in self.0.iter().enumerate() {
217            if i > 0 {
218                write!(f, ".")?;
219            }
220            write!(f, "{}", element_id)?;
221        }
222        Ok(())
223    }
224}
225
226impl GlobalElementId {
227    pub(crate) fn accesskit_node_id(&self) -> accesskit::NodeId {
228        use std::hash::{Hash, Hasher};
229        let mut hasher = std::hash::DefaultHasher::default();
230        self.hash(&mut hasher);
231        accesskit::NodeId(hasher.finish())
232    }
233}
234
235trait ElementObject {
236    fn inner_element(&mut self) -> &mut dyn Any;
237
238    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
239
240    fn prepaint(&mut self, window: &mut Window, cx: &mut App);
241
242    fn paint(&mut self, window: &mut Window, cx: &mut App);
243
244    fn layout_as_root(
245        &mut self,
246        available_space: Size<AvailableSpace>,
247        window: &mut Window,
248        cx: &mut App,
249    ) -> Size<Pixels>;
250}
251
252/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window.
253pub struct Drawable<E: Element> {
254    /// The drawn element.
255    pub element: E,
256    phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
257}
258
259#[derive(Default)]
260enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
261    #[default]
262    Start,
263    RequestLayout {
264        layout_id: LayoutId,
265        global_id: Option<GlobalElementId>,
266        inspector_id: Option<InspectorElementId>,
267        request_layout: RequestLayoutState,
268    },
269    LayoutComputed {
270        layout_id: LayoutId,
271        global_id: Option<GlobalElementId>,
272        inspector_id: Option<InspectorElementId>,
273        available_space: Size<AvailableSpace>,
274        request_layout: RequestLayoutState,
275    },
276    Prepaint {
277        node_id: DispatchNodeId,
278        global_id: Option<GlobalElementId>,
279        inspector_id: Option<InspectorElementId>,
280        bounds: Bounds<Pixels>,
281        request_layout: RequestLayoutState,
282        prepaint: PrepaintState,
283    },
284    Painted,
285}
286
287/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window.
288impl<E: Element> Drawable<E> {
289    pub(crate) fn new(element: E) -> Self {
290        Drawable {
291            element,
292            phase: ElementDrawPhase::Start,
293        }
294    }
295
296    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
297        match mem::take(&mut self.phase) {
298            ElementDrawPhase::Start => {
299                let global_id = self.element.id().map(|element_id| {
300                    window.frame_state.element_id_stack.push(element_id);
301                    GlobalElementId(Arc::from(&*window.frame_state.element_id_stack))
302                });
303
304                let inspector_id;
305                #[cfg(any(feature = "inspector", debug_assertions))]
306                {
307                    inspector_id = self.element.source_location().map(|source| {
308                        let path = crate::InspectorElementPath {
309                            global_id: GlobalElementId(Arc::from(
310                                &*window.frame_state.element_id_stack,
311                            )),
312                            source_location: source,
313                        };
314                        window.build_inspector_element_id(path)
315                    });
316                }
317                #[cfg(not(any(feature = "inspector", debug_assertions)))]
318                {
319                    inspector_id = None;
320                }
321
322                let previous_inspector_id = window.set_inspector_element_id(inspector_id.clone());
323                let (layout_id, request_layout) =
324                    self.element.request_layout(global_id.as_ref(), window, cx);
325                window.set_inspector_element_id(previous_inspector_id);
326
327                if global_id.is_some() {
328                    window.frame_state.element_id_stack.pop();
329                }
330
331                self.phase = ElementDrawPhase::RequestLayout {
332                    layout_id,
333                    global_id,
334                    inspector_id,
335                    request_layout,
336                };
337                layout_id
338            }
339            _ => panic!("must call request_layout only once"),
340        }
341    }
342
343    pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
344        match mem::take(&mut self.phase) {
345            ElementDrawPhase::RequestLayout {
346                layout_id,
347                global_id,
348                inspector_id,
349                mut request_layout,
350            }
351            | ElementDrawPhase::LayoutComputed {
352                layout_id,
353                global_id,
354                inspector_id,
355                mut request_layout,
356                ..
357            } => {
358                if let Some(element_id) = self.element.id() {
359                    window.frame_state.element_id_stack.push(element_id);
360                    debug_assert_eq!(
361                        &*global_id.as_ref().unwrap().0,
362                        &*window.frame_state.element_id_stack
363                    );
364                }
365
366                let bounds = window.layout_bounds(layout_id);
367                let mut pushed_a11y_node = false;
368                if window.core.a11y.is_active() {
369                    if let Some(global_id) = global_id.as_ref() {
370                        if let Some(role) = self.element.a11y_role() {
371                            let node_id = global_id.accesskit_node_id();
372                            let mut node = accesskit::Node::new(role);
373                            let scale = window.scale_factor();
374                            node.set_bounds(accesskit::Rect {
375                                x0: (bounds.origin.x.0 * scale) as f64,
376                                y0: (bounds.origin.y.0 * scale) as f64,
377                                x1: ((bounds.origin.x.0 + bounds.size.width.0) * scale) as f64,
378                                y1: ((bounds.origin.y.0 + bounds.size.height.0) * scale) as f64,
379                            });
380                            self.element.write_a11y_info(&mut node);
381                            window.core.a11y.node_bounds.insert(node_id, bounds);
382                            pushed_a11y_node = window.core.a11y.nodes.push(node_id, node);
383                            #[cfg(debug_assertions)]
384                            if pushed_a11y_node {
385                                let view = window
386                                    .core
387                                    .a11y
388                                    .view_type_names
389                                    .get(&window.current_view())
390                                    .copied();
391                                let source_location = self.element.source_location();
392                                window.core.a11y.nodes.record_node_info(
393                                    node_id,
394                                    crate::window::a11y::debug::NodeDebugInfo {
395                                        synthetic: false,
396                                        view,
397                                        element_id: global_id.0.last().map(|id| format!("{id:?}")),
398                                        source_location,
399                                    },
400                                );
401                            }
402                        }
403                    }
404                }
405
406                let node_id = window.frame_state.next_frame.dispatch_tree.push_node();
407                let previous_inspector_id = window.set_inspector_element_id(inspector_id.clone());
408                let mut prepaint = self.element.prepaint(
409                    global_id.as_ref(),
410                    bounds,
411                    &mut request_layout,
412                    window,
413                    cx,
414                );
415                window.set_inspector_element_id(previous_inspector_id);
416                window.frame_state.next_frame.dispatch_tree.pop_node();
417
418                if pushed_a11y_node {
419                    if let Some(global_id) = global_id.as_ref() {
420                        #[cfg(debug_assertions)]
421                        let creator = crate::window::a11y::debug::NodeCreator {
422                            view: window
423                                .core
424                                .a11y
425                                .view_type_names
426                                .get(&window.current_view())
427                                .copied(),
428                            element_id: global_id.0.last().map(|id| format!("{id:?}")),
429                            source_location: self.element.source_location(),
430                        };
431                        let mut builder = A11ySubtreeBuilder::new(
432                            global_id.accesskit_node_id(),
433                            &mut window.core.a11y.nodes,
434                        );
435                        #[cfg(debug_assertions)]
436                        {
437                            builder = builder.with_creator(creator);
438                        }
439                        self.element
440                            .a11y_synthetic_children(&mut prepaint, &mut builder);
441                    }
442                    window.core.a11y.nodes.pop();
443                }
444
445                if global_id.is_some() {
446                    window.frame_state.element_id_stack.pop();
447                }
448
449                self.phase = ElementDrawPhase::Prepaint {
450                    node_id,
451                    global_id,
452                    inspector_id,
453                    bounds,
454                    request_layout,
455                    prepaint,
456                };
457            }
458            _ => panic!("must call request_layout before prepaint"),
459        }
460    }
461
462    pub(crate) fn paint(
463        &mut self,
464        window: &mut Window,
465        cx: &mut App,
466    ) -> (E::RequestLayoutState, E::PrepaintState) {
467        match mem::take(&mut self.phase) {
468            ElementDrawPhase::Prepaint {
469                node_id,
470                global_id,
471                inspector_id,
472                bounds,
473                mut request_layout,
474                mut prepaint,
475                ..
476            } => {
477                if let Some(element_id) = self.element.id() {
478                    window.frame_state.element_id_stack.push(element_id);
479                    debug_assert_eq!(
480                        &*global_id.as_ref().unwrap().0,
481                        &*window.frame_state.element_id_stack
482                    );
483                }
484
485                window
486                    .frame_state
487                    .next_frame
488                    .dispatch_tree
489                    .set_active_node(node_id);
490                let previous_inspector_id = window.set_inspector_element_id(inspector_id);
491                self.element.paint(
492                    global_id.as_ref(),
493                    bounds,
494                    &mut request_layout,
495                    &mut prepaint,
496                    window,
497                    cx,
498                );
499                window.set_inspector_element_id(previous_inspector_id);
500
501                if global_id.is_some() {
502                    window.frame_state.element_id_stack.pop();
503                }
504
505                self.phase = ElementDrawPhase::Painted;
506                (request_layout, prepaint)
507            }
508            _ => panic!("must call prepaint before paint"),
509        }
510    }
511
512    pub(crate) fn layout_as_root(
513        &mut self,
514        available_space: Size<AvailableSpace>,
515        window: &mut Window,
516        cx: &mut App,
517    ) -> Size<Pixels> {
518        if matches!(&self.phase, ElementDrawPhase::Start) {
519            self.request_layout(window, cx);
520        }
521
522        let layout_id = match mem::take(&mut self.phase) {
523            ElementDrawPhase::RequestLayout {
524                layout_id,
525                global_id,
526                inspector_id,
527                request_layout,
528            } => {
529                window.compute_layout(layout_id, available_space, cx);
530                self.phase = ElementDrawPhase::LayoutComputed {
531                    layout_id,
532                    global_id,
533                    inspector_id,
534                    available_space,
535                    request_layout,
536                };
537                layout_id
538            }
539            ElementDrawPhase::LayoutComputed {
540                layout_id,
541                global_id,
542                inspector_id,
543                available_space: prev_available_space,
544                request_layout,
545            } => {
546                if available_space != prev_available_space {
547                    window.compute_layout(layout_id, available_space, cx);
548                }
549                self.phase = ElementDrawPhase::LayoutComputed {
550                    layout_id,
551                    global_id,
552                    inspector_id,
553                    available_space,
554                    request_layout,
555                };
556                layout_id
557            }
558            _ => panic!("cannot measure after painting"),
559        };
560
561        window.layout_bounds(layout_id).size
562    }
563}
564
565impl<E> ElementObject for Drawable<E>
566where
567    E: Element,
568    E::RequestLayoutState: 'static,
569{
570    fn inner_element(&mut self) -> &mut dyn Any {
571        &mut self.element
572    }
573
574    #[inline]
575    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
576        Drawable::request_layout(self, window, cx)
577    }
578
579    #[inline]
580    fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
581        Drawable::prepaint(self, window, cx);
582    }
583
584    #[inline]
585    fn paint(&mut self, window: &mut Window, cx: &mut App) {
586        Drawable::paint(self, window, cx);
587    }
588
589    #[inline]
590    fn layout_as_root(
591        &mut self,
592        available_space: Size<AvailableSpace>,
593        window: &mut Window,
594        cx: &mut App,
595    ) -> Size<Pixels> {
596        Drawable::layout_as_root(self, available_space, window, cx)
597    }
598}
599
600/// A dynamically typed element that can be used to store any element type.
601pub struct AnyElement(ArenaBox<dyn ElementObject>);
602
603impl AnyElement {
604    pub(crate) fn new<E>(element: E) -> Self
605    where
606        E: 'static + Element,
607        E::RequestLayoutState: Any,
608    {
609        let element = with_element_arena(|arena| arena.alloc(|| Drawable::new(element)))
610            .map(|element| element as &mut dyn ElementObject);
611        AnyElement(element)
612    }
613
614    /// Attempt to downcast a reference to the boxed element to a specific type.
615    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
616        self.0.inner_element().downcast_mut::<T>()
617    }
618
619    /// Request the layout ID of the element stored in this `AnyElement`.
620    /// Used for laying out child elements in a parent element.
621    pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
622        self.0.request_layout(window, cx)
623    }
624
625    /// Prepares the element to be painted by storing its bounds, giving it a chance to draw hitboxes and
626    /// request autoscroll before the final paint pass is confirmed.
627    pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
628        let focus_assigned = window.frame_state.next_frame.focus.is_some();
629
630        self.0.prepaint(window, cx);
631
632        if !focus_assigned && let Some(focus_id) = window.frame_state.next_frame.focus {
633            return FocusHandle::for_id(focus_id, &cx.focus_handles);
634        }
635
636        None
637    }
638
639    /// Paints the element stored in this `AnyElement`.
640    pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
641        self.0.paint(window, cx);
642    }
643
644    /// Performs layout for this element within the given available space and returns its size.
645    pub fn layout_as_root(
646        &mut self,
647        available_space: Size<AvailableSpace>,
648        window: &mut Window,
649        cx: &mut App,
650    ) -> Size<Pixels> {
651        self.0.layout_as_root(available_space, window, cx)
652    }
653
654    /// Prepaints this element at the given absolute origin.
655    /// If any element in the subtree beneath this element is focused, its FocusHandle is returned.
656    pub fn prepaint_at(
657        &mut self,
658        origin: Point<Pixels>,
659        window: &mut Window,
660        cx: &mut App,
661    ) -> Option<FocusHandle> {
662        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
663    }
664
665    /// Performs layout on this element in the available space, then prepaints it at the given absolute origin.
666    /// If any element in the subtree beneath this element is focused, its FocusHandle is returned.
667    pub fn prepaint_as_root(
668        &mut self,
669        origin: Point<Pixels>,
670        available_space: Size<AvailableSpace>,
671        window: &mut Window,
672        cx: &mut App,
673    ) -> Option<FocusHandle> {
674        self.layout_as_root(available_space, window, cx);
675        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
676    }
677}
678
679impl Element for AnyElement {
680    type RequestLayoutState = ();
681    type PrepaintState = ();
682
683    fn id(&self) -> Option<ElementId> {
684        None
685    }
686
687    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
688        None
689    }
690
691    fn request_layout(
692        &mut self,
693        _: Option<&GlobalElementId>,
694        window: &mut Window,
695        cx: &mut App,
696    ) -> (LayoutId, Self::RequestLayoutState) {
697        let layout_id = self.request_layout(window, cx);
698        (layout_id, ())
699    }
700
701    fn prepaint(
702        &mut self,
703        _: Option<&GlobalElementId>,
704        _: Bounds<Pixels>,
705        _: &mut Self::RequestLayoutState,
706        window: &mut Window,
707        cx: &mut App,
708    ) {
709        self.prepaint(window, cx);
710    }
711
712    fn paint(
713        &mut self,
714        _: Option<&GlobalElementId>,
715        _: Bounds<Pixels>,
716        _: &mut Self::RequestLayoutState,
717        _: &mut Self::PrepaintState,
718        window: &mut Window,
719        cx: &mut App,
720    ) {
721        self.paint(window, cx);
722    }
723}
724
725impl IntoElement for AnyElement {
726    type Element = Self;
727
728    fn into_element(self) -> Self::Element {
729        self
730    }
731
732    fn into_any_element(self) -> AnyElement {
733        self
734    }
735}
736
737/// The empty element, which renders nothing.
738pub struct Empty;
739
740impl IntoElement for Empty {
741    type Element = Self;
742
743    fn into_element(self) -> Self::Element {
744        self
745    }
746}
747
748impl Element for Empty {
749    type RequestLayoutState = ();
750    type PrepaintState = ();
751
752    fn id(&self) -> Option<ElementId> {
753        None
754    }
755
756    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
757        None
758    }
759
760    fn request_layout(
761        &mut self,
762        _id: Option<&GlobalElementId>,
763        window: &mut Window,
764        cx: &mut App,
765    ) -> (LayoutId, Self::RequestLayoutState) {
766        (
767            window.request_layout(
768                Style {
769                    display: crate::Display::None,
770                    ..Default::default()
771                },
772                None,
773                cx,
774            ),
775            (),
776        )
777    }
778
779    fn prepaint(
780        &mut self,
781        _id: Option<&GlobalElementId>,
782        _bounds: Bounds<Pixels>,
783        _state: &mut Self::RequestLayoutState,
784        _window: &mut Window,
785        _cx: &mut App,
786    ) {
787    }
788
789    fn paint(
790        &mut self,
791        _id: Option<&GlobalElementId>,
792        _bounds: Bounds<Pixels>,
793        _request_layout: &mut Self::RequestLayoutState,
794        _prepaint: &mut Self::PrepaintState,
795        _window: &mut Window,
796        _cx: &mut App,
797    ) {
798    }
799}