wgpui/elements/
container_query.rs1use refineable::Refineable as _;
6
7use crate::{
8 AnyElement, App, AvailableSpace, Bounds, Element, ElementId, GlobalElementId,
9 InspectorElementId, IntoElement, LayoutId, Pixels, Size, Style, StyleRefinement, Styled,
10 Window, relative,
11};
12
13pub fn container_query<E>(
21 render: impl 'static + FnOnce(Size<Pixels>, &mut Window, &mut App) -> E,
22) -> ContainerQuery
23where
24 E: IntoElement,
25{
26 let mut base_style = StyleRefinement::default();
27 base_style.size.width = Some(relative(1.).into());
28 base_style.size.height = Some(relative(1.).into());
29
30 ContainerQuery {
31 render: Some(Box::new(|size, window, cx| {
32 render(size, window, cx).into_any_element()
33 })),
34 style: base_style,
35 }
36}
37
38pub struct ContainerQuery {
40 render: Option<Box<dyn FnOnce(Size<Pixels>, &mut Window, &mut App) -> AnyElement>>,
41 style: StyleRefinement,
42}
43
44impl Element for ContainerQuery {
45 type RequestLayoutState = ();
46 type PrepaintState = Option<AnyElement>;
47
48 fn id(&self) -> Option<ElementId> {
49 None
50 }
51
52 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
53 None
54 }
55
56 fn request_layout(
57 &mut self,
58 _id: Option<&GlobalElementId>,
59 _inspector_id: Option<&InspectorElementId>,
60 window: &mut Window,
61 cx: &mut App,
62 ) -> (LayoutId, Self::RequestLayoutState) {
63 let mut style = Style::default();
64 style.refine(&self.style);
65 let layout_id = window.request_layout(style, [], cx);
66 (layout_id, ())
67 }
68
69 fn prepaint(
70 &mut self,
71 _id: Option<&GlobalElementId>,
72 _inspector_id: Option<&InspectorElementId>,
73 bounds: Bounds<Pixels>,
74 _request_layout: &mut Self::RequestLayoutState,
75 window: &mut Window,
76 cx: &mut App,
77 ) -> Option<AnyElement> {
78 let render = self.render.take()?;
79 let mut child = render(bounds.size, window, cx);
80 child.layout_as_root(bounds.size.map(AvailableSpace::Definite), window, cx);
81 child.prepaint_at(bounds.origin, window, cx);
82 Some(child)
83 }
84
85 fn paint(
86 &mut self,
87 _id: Option<&GlobalElementId>,
88 _inspector_id: Option<&InspectorElementId>,
89 _bounds: Bounds<Pixels>,
90 _request_layout: &mut Self::RequestLayoutState,
91 prepaint: &mut Self::PrepaintState,
92 window: &mut Window,
93 cx: &mut App,
94 ) {
95 if let Some(child) = prepaint {
96 child.paint(window, cx);
97 }
98 }
99}
100
101impl IntoElement for ContainerQuery {
102 type Element = Self;
103
104 fn into_element(self) -> Self::Element {
105 self
106 }
107}
108
109impl Styled for ContainerQuery {
110 fn style(&mut self) -> &mut StyleRefinement {
111 &mut self.style
112 }
113}