Skip to main content

wgpui/
element.rs

1//! Elements are the workhorses of WGPUI. 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 WGPUI, 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 WGPUI 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, WGPUI 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 WGPUI. They are responsible for upholding,
22//! or breaking, WGPUI's features as they deem necessary. As an example, most WGPUI 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. WGPUI 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, ELEMENT_ARENA, ElementId,
36    FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,
37    util::FluentBuilder,
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 accessibility role for this element, if any.
107    fn a11y_role(&self) -> Option<accesskit::Role> {
108        None
109    }
110
111    /// Writes accessibility metadata for this element into `node`.
112    fn write_a11y_info(&self, _node: &mut accesskit::Node) {}
113
114    /// Moves explicit accessibility action handlers into the current rendered frame.
115    fn take_a11y_actions(&mut self) -> Vec<(accesskit::Action, crate::A11yActionListener)> {
116        Vec::new()
117    }
118
119    /// Returns the focus handle associated with this accessible element.
120    fn a11y_focus_handle(&self) -> Option<crate::FocusHandle> {
121        None
122    }
123
124    /// Whether this element reports accessibility focus while a containing element holds keyboard focus.
125    fn a11y_reports_active_descendant(&self) -> bool {
126        false
127    }
128
129    /// Allows elements to contribute synthetic accessibility children.
130    fn a11y_synthetic_children(
131        &mut self,
132        _prepaint: &mut Self::PrepaintState,
133        _builder: &mut crate::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_element().into_any()));
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/// An element for rendering components. An implementation detail of the [`IntoElement`] derive macro
211/// for [`RenderOnce`]
212#[doc(hidden)]
213pub struct Component<C: RenderOnce> {
214    component: Option<C>,
215    #[cfg(debug_assertions)]
216    source: &'static core::panic::Location<'static>,
217}
218
219impl<C: RenderOnce> Component<C> {
220    /// Create a new component from the given RenderOnce type.
221    #[track_caller]
222    pub fn new(component: C) -> Self {
223        Component {
224            component: Some(component),
225            #[cfg(debug_assertions)]
226            source: core::panic::Location::caller(),
227        }
228    }
229}
230
231impl<C: RenderOnce> Element for Component<C> {
232    type RequestLayoutState = AnyElement;
233    type PrepaintState = ();
234
235    fn id(&self) -> Option<ElementId> {
236        None
237    }
238
239    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
240        #[cfg(debug_assertions)]
241        return Some(self.source);
242
243        #[cfg(not(debug_assertions))]
244        return None;
245    }
246
247    fn request_layout(
248        &mut self,
249        _id: Option<&GlobalElementId>,
250        _inspector_id: Option<&InspectorElementId>,
251        window: &mut Window,
252        cx: &mut App,
253    ) -> (LayoutId, Self::RequestLayoutState) {
254        window.with_global_id(ElementId::Name(type_name::<C>().into()), |_, window| {
255            let mut element = self
256                .component
257                .take()
258                .unwrap()
259                .render(window, cx)
260                .into_any_element();
261
262            let layout_id = element.request_layout(window, cx);
263            (layout_id, element)
264        })
265    }
266
267    fn prepaint(
268        &mut self,
269        _id: Option<&GlobalElementId>,
270        _inspector_id: Option<&InspectorElementId>,
271        _: Bounds<Pixels>,
272        element: &mut AnyElement,
273        window: &mut Window,
274        cx: &mut App,
275    ) {
276        window.with_global_id(ElementId::Name(type_name::<C>().into()), |_, window| {
277            element.prepaint(window, cx);
278        })
279    }
280
281    fn paint(
282        &mut self,
283        _id: Option<&GlobalElementId>,
284        _inspector_id: Option<&InspectorElementId>,
285        _: Bounds<Pixels>,
286        element: &mut Self::RequestLayoutState,
287        _: &mut Self::PrepaintState,
288        window: &mut Window,
289        cx: &mut App,
290    ) {
291        window.with_global_id(ElementId::Name(type_name::<C>().into()), |_, window| {
292            element.paint(window, cx);
293        })
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
321trait ElementObject {
322    fn inner_element(&mut self) -> &mut dyn Any;
323
324    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
325
326    fn prepaint(&mut self, window: &mut Window, cx: &mut App);
327
328    fn paint(&mut self, window: &mut Window, cx: &mut App);
329
330    fn layout_as_root(
331        &mut self,
332        available_space: Size<AvailableSpace>,
333        window: &mut Window,
334        cx: &mut App,
335    ) -> Size<Pixels>;
336}
337
338/// The concrete element for a stateless view rendered through [`RenderOnce`].
339pub type ViewElement<V> = Component<V>;
340
341/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window.
342pub struct Drawable<E: Element> {
343    /// The drawn element.
344    pub element: E,
345    phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
346}
347
348#[derive(Default)]
349enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
350    #[default]
351    Start,
352    RequestLayout {
353        layout_id: LayoutId,
354        global_id: Option<GlobalElementId>,
355        inspector_id: Option<InspectorElementId>,
356        request_layout: RequestLayoutState,
357    },
358    LayoutComputed {
359        layout_id: LayoutId,
360        global_id: Option<GlobalElementId>,
361        inspector_id: Option<InspectorElementId>,
362        available_space: Size<AvailableSpace>,
363        request_layout: RequestLayoutState,
364    },
365    Prepaint {
366        node_id: DispatchNodeId,
367        global_id: Option<GlobalElementId>,
368        inspector_id: Option<InspectorElementId>,
369        bounds: Bounds<Pixels>,
370        request_layout: RequestLayoutState,
371        prepaint: PrepaintState,
372    },
373    Painted,
374}
375
376/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window.
377impl<E: Element> Drawable<E> {
378    pub(crate) fn new(element: E) -> Self {
379        Drawable {
380            element,
381            phase: ElementDrawPhase::Start,
382        }
383    }
384
385    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
386        match mem::take(&mut self.phase) {
387            ElementDrawPhase::Start => {
388                let global_id = self.element.id().map(|element_id| {
389                    window.element_id_stack.push(element_id);
390                    GlobalElementId(Arc::from(&*window.element_id_stack))
391                });
392
393                let inspector_id;
394                #[cfg(any(feature = "inspector", debug_assertions))]
395                {
396                    inspector_id = self.element.source_location().map(|source| {
397                        let path = crate::InspectorElementPath {
398                            global_id: GlobalElementId(Arc::from(&*window.element_id_stack)),
399                            source_location: source,
400                        };
401                        window.build_inspector_element_id(path)
402                    });
403                }
404                #[cfg(not(any(feature = "inspector", debug_assertions)))]
405                {
406                    inspector_id = None;
407                }
408
409                let (layout_id, request_layout) = self.element.request_layout(
410                    global_id.as_ref(),
411                    inspector_id.as_ref(),
412                    window,
413                    cx,
414                );
415
416                if global_id.is_some() {
417                    window.element_id_stack.pop();
418                }
419
420                self.phase = ElementDrawPhase::RequestLayout {
421                    layout_id,
422                    global_id,
423                    inspector_id,
424                    request_layout,
425                };
426                layout_id
427            }
428            _ => panic!("must call request_layout only once"),
429        }
430    }
431
432    pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
433        match mem::take(&mut self.phase) {
434            ElementDrawPhase::RequestLayout {
435                layout_id,
436                global_id,
437                inspector_id,
438                mut request_layout,
439            }
440            | ElementDrawPhase::LayoutComputed {
441                layout_id,
442                global_id,
443                inspector_id,
444                mut request_layout,
445                ..
446            } => {
447                if let Some(element_id) = self.element.id() {
448                    window.element_id_stack.push(element_id);
449                    debug_assert_eq!(&*global_id.as_ref().unwrap().0, &*window.element_id_stack);
450                }
451
452                let bounds = window.layout_bounds(layout_id);
453                let node_id = window.next_frame.dispatch_tree.push_node();
454                let prepaint = self.element.prepaint(
455                    global_id.as_ref(),
456                    inspector_id.as_ref(),
457                    bounds,
458                    &mut request_layout,
459                    window,
460                    cx,
461                );
462                window.next_frame.dispatch_tree.pop_node();
463
464                if global_id.is_some() {
465                    window.element_id_stack.pop();
466                }
467
468                self.phase = ElementDrawPhase::Prepaint {
469                    node_id,
470                    global_id,
471                    inspector_id,
472                    bounds,
473                    request_layout,
474                    prepaint,
475                };
476            }
477            _ => panic!("must call request_layout before prepaint"),
478        }
479    }
480
481    pub(crate) fn paint(
482        &mut self,
483        window: &mut Window,
484        cx: &mut App,
485    ) -> (E::RequestLayoutState, E::PrepaintState) {
486        match mem::take(&mut self.phase) {
487            ElementDrawPhase::Prepaint {
488                node_id,
489                global_id,
490                inspector_id,
491                bounds,
492                mut request_layout,
493                mut prepaint,
494                ..
495            } => {
496                if let Some(element_id) = self.element.id() {
497                    window.element_id_stack.push(element_id);
498                    debug_assert_eq!(&*global_id.as_ref().unwrap().0, &*window.element_id_stack);
499                }
500
501                window.next_frame.dispatch_tree.set_active_node(node_id);
502                let a11y_id = window.begin_a11y_node(&mut self.element, global_id.as_ref(), bounds);
503                self.element.paint(
504                    global_id.as_ref(),
505                    inspector_id.as_ref(),
506                    bounds,
507                    &mut request_layout,
508                    &mut prepaint,
509                    window,
510                    cx,
511                );
512
513                if let Some(a11y_id) = a11y_id {
514                    if let Some(mut builder) =
515                        crate::A11ySubtreeBuilder::new(a11y_id, &mut window.a11y_nodes)
516                    {
517                        self.element
518                            .a11y_synthetic_children(&mut prepaint, &mut builder);
519                    }
520                    window.a11y_nodes.pop();
521                }
522
523                if global_id.is_some() {
524                    window.element_id_stack.pop();
525                }
526
527                self.phase = ElementDrawPhase::Painted;
528                (request_layout, prepaint)
529            }
530            _ => panic!("must call prepaint before paint"),
531        }
532    }
533
534    pub(crate) fn layout_as_root(
535        &mut self,
536        available_space: Size<AvailableSpace>,
537        window: &mut Window,
538        cx: &mut App,
539    ) -> Size<Pixels> {
540        if matches!(&self.phase, ElementDrawPhase::Start) {
541            window.with_profiled_request_layout(|window| self.request_layout(window, cx));
542        }
543
544        let layout_id = match mem::take(&mut self.phase) {
545            ElementDrawPhase::RequestLayout {
546                layout_id,
547                global_id,
548                inspector_id,
549                request_layout,
550            } => {
551                window.compute_layout(layout_id, available_space, cx);
552                self.phase = ElementDrawPhase::LayoutComputed {
553                    layout_id,
554                    global_id,
555                    inspector_id,
556                    available_space,
557                    request_layout,
558                };
559                layout_id
560            }
561            ElementDrawPhase::LayoutComputed {
562                layout_id,
563                global_id,
564                inspector_id,
565                available_space: prev_available_space,
566                request_layout,
567            } => {
568                if available_space != prev_available_space {
569                    window.compute_layout(layout_id, available_space, cx);
570                }
571                self.phase = ElementDrawPhase::LayoutComputed {
572                    layout_id,
573                    global_id,
574                    inspector_id,
575                    available_space,
576                    request_layout,
577                };
578                layout_id
579            }
580            _ => panic!("cannot measure after painting"),
581        };
582
583        window.layout_bounds(layout_id).size
584    }
585}
586
587impl<E> ElementObject for Drawable<E>
588where
589    E: Element,
590    E::RequestLayoutState: 'static,
591{
592    fn inner_element(&mut self) -> &mut dyn Any {
593        &mut self.element
594    }
595
596    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
597        Drawable::request_layout(self, window, cx)
598    }
599
600    fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
601        Drawable::prepaint(self, window, cx);
602    }
603
604    fn paint(&mut self, window: &mut Window, cx: &mut App) {
605        Drawable::paint(self, window, cx);
606    }
607
608    fn layout_as_root(
609        &mut self,
610        available_space: Size<AvailableSpace>,
611        window: &mut Window,
612        cx: &mut App,
613    ) -> Size<Pixels> {
614        Drawable::layout_as_root(self, available_space, window, cx)
615    }
616}
617
618/// A dynamically typed element that can be used to store any element type.
619pub struct AnyElement(ArenaBox<dyn ElementObject>);
620
621impl AnyElement {
622    pub(crate) fn new<E>(element: E) -> Self
623    where
624        E: 'static + Element,
625        E::RequestLayoutState: Any,
626    {
627        let element = ELEMENT_ARENA
628            .with_borrow_mut(|arena| arena.alloc(|| Drawable::new(element)))
629            .map(|element| element as &mut dyn ElementObject);
630        AnyElement(element)
631    }
632
633    /// Attempt to downcast a reference to the boxed element to a specific type.
634    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
635        self.0.inner_element().downcast_mut::<T>()
636    }
637
638    /// Request the layout ID of the element stored in this `AnyElement`.
639    /// Used for laying out child elements in a parent element.
640    pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
641        self.0.request_layout(window, cx)
642    }
643
644    /// Prepares the element to be painted by storing its bounds, giving it a chance to draw hitboxes and
645    /// request autoscroll before the final paint pass is confirmed.
646    pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
647        let focus_assigned = window.next_frame.focus.is_some();
648
649        self.0.prepaint(window, cx);
650
651        if !focus_assigned && let Some(focus_id) = window.next_frame.focus {
652            return FocusHandle::for_id(focus_id, &cx.focus_handles);
653        }
654
655        None
656    }
657
658    /// Paints the element stored in this `AnyElement`.
659    pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
660        self.0.paint(window, cx);
661    }
662
663    /// Performs layout for this element within the given available space and returns its size.
664    pub fn layout_as_root(
665        &mut self,
666        available_space: Size<AvailableSpace>,
667        window: &mut Window,
668        cx: &mut App,
669    ) -> Size<Pixels> {
670        self.0.layout_as_root(available_space, window, cx)
671    }
672
673    /// Prepaints this element at the given absolute origin.
674    /// If any element in the subtree beneath this element is focused, its FocusHandle is returned.
675    pub fn prepaint_at(
676        &mut self,
677        origin: Point<Pixels>,
678        window: &mut Window,
679        cx: &mut App,
680    ) -> Option<FocusHandle> {
681        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
682    }
683
684    /// Performs layout on this element in the available space, then prepaints it at the given absolute origin.
685    /// If any element in the subtree beneath this element is focused, its FocusHandle is returned.
686    pub fn prepaint_as_root(
687        &mut self,
688        origin: Point<Pixels>,
689        available_space: Size<AvailableSpace>,
690        window: &mut Window,
691        cx: &mut App,
692    ) -> Option<FocusHandle> {
693        self.layout_as_root(available_space, window, cx);
694        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
695    }
696}
697
698impl Element for AnyElement {
699    type RequestLayoutState = ();
700    type PrepaintState = ();
701
702    fn id(&self) -> Option<ElementId> {
703        None
704    }
705
706    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
707        None
708    }
709
710    fn request_layout(
711        &mut self,
712        _: Option<&GlobalElementId>,
713        _inspector_id: Option<&InspectorElementId>,
714        window: &mut Window,
715        cx: &mut App,
716    ) -> (LayoutId, Self::RequestLayoutState) {
717        let layout_id = self.request_layout(window, cx);
718        (layout_id, ())
719    }
720
721    fn prepaint(
722        &mut self,
723        _: Option<&GlobalElementId>,
724        _inspector_id: Option<&InspectorElementId>,
725        _: Bounds<Pixels>,
726        _: &mut Self::RequestLayoutState,
727        window: &mut Window,
728        cx: &mut App,
729    ) {
730        self.prepaint(window, cx);
731    }
732
733    fn paint(
734        &mut self,
735        _: Option<&GlobalElementId>,
736        _inspector_id: Option<&InspectorElementId>,
737        _: Bounds<Pixels>,
738        _: &mut Self::RequestLayoutState,
739        _: &mut Self::PrepaintState,
740        window: &mut Window,
741        cx: &mut App,
742    ) {
743        self.paint(window, cx);
744    }
745}
746
747impl IntoElement for AnyElement {
748    type Element = Self;
749
750    fn into_element(self) -> Self::Element {
751        self
752    }
753
754    fn into_any_element(self) -> AnyElement {
755        self
756    }
757}
758
759/// The empty element, which renders nothing.
760pub struct Empty;
761
762impl IntoElement for Empty {
763    type Element = Self;
764
765    fn into_element(self) -> Self::Element {
766        self
767    }
768}
769
770impl Element for Empty {
771    type RequestLayoutState = ();
772    type PrepaintState = ();
773
774    fn id(&self) -> Option<ElementId> {
775        None
776    }
777
778    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
779        None
780    }
781
782    fn request_layout(
783        &mut self,
784        _id: Option<&GlobalElementId>,
785        _inspector_id: Option<&InspectorElementId>,
786        window: &mut Window,
787        cx: &mut App,
788    ) -> (LayoutId, Self::RequestLayoutState) {
789        (
790            window.request_layout(
791                Style {
792                    display: crate::Display::None,
793                    ..Default::default()
794                },
795                None,
796                cx,
797            ),
798            (),
799        )
800    }
801
802    fn prepaint(
803        &mut self,
804        _id: Option<&GlobalElementId>,
805        _inspector_id: Option<&InspectorElementId>,
806        _bounds: Bounds<Pixels>,
807        _state: &mut Self::RequestLayoutState,
808        _window: &mut Window,
809        _cx: &mut App,
810    ) {
811    }
812
813    fn paint(
814        &mut self,
815        _id: Option<&GlobalElementId>,
816        _inspector_id: Option<&InspectorElementId>,
817        _bounds: Bounds<Pixels>,
818        _request_layout: &mut Self::RequestLayoutState,
819        _prepaint: &mut Self::PrepaintState,
820        _window: &mut Window,
821        _cx: &mut App,
822    ) {
823    }
824}