Skip to main content

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