Skip to main content

pax_std/core/
group.rs

1use crate::common::{native_surface_opacity, patch_if_needed};
2use pax_engine::api::Property;
3use pax_engine::pax;
4use pax_message::{AnyCreatePatch, GlassSurfacePatch};
5use pax_runtime::api::{borrow, Layer};
6use pax_runtime::{
7    bind_content_measurement_effect, resolve_axis_autosize, sync_content_autosize_with_axes,
8    BaseInstance, ContentMeasurementGeometry, ExpandedNode, InstanceFlags, InstanceNode,
9    InstantiationArgs, RuntimeContext,
10};
11use std::cell::{Cell, RefCell};
12use std::iter;
13use std::rc::Rc;
14
15/// Gathers a set of children underneath a single render node:
16/// useful for composing transforms and simplifying render trees.
17#[pax]
18#[engine_import_path("pax_engine")]
19#[custom(Default)]
20#[primitive("pax_std::core::group::GroupInstance")]
21pub struct Group {
22    /// Automatically sizes the group to its direct content children when possible.
23    pub autosize: Property<bool>,
24    /// Optional override for whether autosize manages the `x` axis.
25    pub autosize_x: Property<Option<bool>>,
26    /// Optional override for whether autosize manages the `y` axis.
27    pub autosize_y: Property<Option<bool>>,
28    /// Corner radius used when the group materializes a native surface, in pixels.
29    pub corner_radius: Property<f64>,
30}
31
32impl Default for Group {
33    fn default() -> Self {
34        Self {
35            autosize: Property::new(false),
36            autosize_x: Property::new(None),
37            autosize_y: Property::new(None),
38            corner_radius: Property::new(0.0),
39        }
40    }
41}
42
43// Runtime instance backing `<Group>`.
44pub struct GroupInstance {
45    base: BaseInstance,
46}
47
48impl InstanceNode for GroupInstance {
49    fn instantiate(args: InstantiationArgs) -> Rc<Self>
50    where
51        Self: Sized,
52    {
53        Rc::new(Self {
54            base: BaseInstance::new(
55                args,
56                InstanceFlags {
57                    invisible_to_slot: false,
58                    invisible_to_raycasting: true,
59                    layer: Layer::DontCare,
60                    is_component: false,
61                    is_slot: false,
62                },
63            ),
64        })
65    }
66
67    fn resolve_debug(
68        &self,
69        f: &mut std::fmt::Formatter,
70        expanded_node: Option<&pax_runtime::ExpandedNode>,
71    ) -> std::fmt::Result {
72        match expanded_node {
73            Some(expanded_node) => expanded_node
74                .with_properties_unwrapped(|_g: &mut Group| f.debug_struct("Group").finish()),
75            None => f.debug_struct("Group").finish_non_exhaustive(),
76        }
77    }
78
79    fn base(&self) -> &BaseInstance {
80        &self.base
81    }
82
83    fn requires_non_reactive_update(&self, expanded_node: &ExpandedNode) -> bool {
84        !expanded_node.content_measurement_bound.get()
85    }
86
87    fn update(self: Rc<Self>, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
88        if expanded_node.content_measurement_bound.get() {
89            return;
90        }
91        let ctx = expanded_node.get_node_context(context);
92        let (autosize, autosize_x, autosize_y) =
93            expanded_node.with_properties_unwrapped(|group: &mut Group| {
94                (
95                    group.autosize.clone(),
96                    group.autosize_x.clone(),
97                    group.autosize_y.clone(),
98                )
99            });
100        let deps = [
101            autosize.untyped(),
102            autosize_x.untyped(),
103            autosize_y.untyped(),
104        ];
105        bind_content_measurement_effect(
106            expanded_node,
107            &ctx,
108            "group autosize",
109            ContentMeasurementGeometry::Placed,
110            &deps,
111            move |node, node_ctx| {
112                sync_content_autosize_with_axes(
113                    node,
114                    node_ctx,
115                    resolve_axis_autosize(autosize.get(), autosize_x.get(), true),
116                    resolve_axis_autosize(autosize.get(), autosize_y.get(), true),
117                );
118            },
119        );
120    }
121
122    fn handle_mount(
123        self: Rc<Self>,
124        expanded_node: &Rc<ExpandedNode>,
125        context: &Rc<RuntimeContext>,
126    ) {
127        let id = expanded_node.id.to_u32();
128        let initially_active = expanded_node.liquid_glass_scope.get().is_some();
129        let created = Rc::new(Cell::new(initially_active));
130        if initially_active {
131            context.enqueue_native_message(pax_message::NativeMessage::GlassSurfaceCreate(
132                AnyCreatePatch {
133                    id,
134                    parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
135                    render_layer_id: 0,
136                },
137            ));
138        }
139
140        let env = Rc::clone(&expanded_node.stack);
141        let children = borrow!(self.base().get_instance_children());
142        let children_with_envs = children.iter().cloned().zip(iter::repeat(env));
143        let new_children = expanded_node.generate_children(
144            children_with_envs,
145            context,
146            &expanded_node.parent_frame,
147            true,
148        );
149        expanded_node.children.set(new_children);
150
151        let last_patch = Rc::new(RefCell::new(GlassSurfacePatch {
152            id,
153            ..Default::default()
154        }));
155        let weak_self_ref = Rc::downgrade(expanded_node);
156        let context = Rc::clone(context);
157
158        let deps: Vec<_> = borrow!(expanded_node.properties_scope)
159            .values()
160            .cloned()
161            .map(|v| v.get_untyped_property().clone())
162            .chain([
163                expanded_node.transform_and_bounds.untyped(),
164                expanded_node.computed_opacity.untyped(),
165                expanded_node.occlusion.untyped(),
166                expanded_node.liquid_glass_scope.untyped(),
167            ])
168            .collect();
169
170        expanded_node
171            .changed_listener
172            .replace_with(Property::computed(
173                move || {
174                    let Some(expanded_node) = weak_self_ref.upgrade() else {
175                        return;
176                    };
177                    let Some(liquid_glass) = expanded_node.liquid_glass_scope.get() else {
178                        if created.replace(false) {
179                            context.enqueue_native_message(
180                                pax_message::NativeMessage::GlassSurfaceDelete(id),
181                            );
182                            *last_patch.borrow_mut() = GlassSurfacePatch {
183                                id,
184                                ..Default::default()
185                            };
186                        }
187                        return;
188                    };
189
190                    if !created.get() {
191                        context.enqueue_native_message(
192                            pax_message::NativeMessage::GlassSurfaceCreate(AnyCreatePatch {
193                                id,
194                                parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
195                                render_layer_id: 0,
196                            }),
197                        );
198                        created.set(true);
199                    }
200
201                    let mut old_state = last_patch.borrow_mut();
202                    let mut patch = GlassSurfacePatch {
203                        id,
204                        ..Default::default()
205                    };
206
207                    expanded_node.with_properties_unwrapped(|properties: &mut Group| {
208                        let computed_tab = expanded_node.transform_and_bounds.get();
209                        let (width, height) = computed_tab.bounds;
210                        let max_radius = 0.5 * width.min(height);
211                        let corner_radius = properties.corner_radius.get().clamp(0.0, max_radius);
212                        let liquid_glass = liquid_glass.to_message();
213                        let updates = [
214                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
215                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
216                            patch_if_needed(
217                                &mut old_state.transform,
218                                &mut patch.transform,
219                                computed_tab.transform.coeffs().to_vec(),
220                            ),
221                            patch_if_needed(
222                                &mut old_state.opacity,
223                                &mut patch.opacity,
224                                native_surface_opacity(&expanded_node, &context),
225                            ),
226                            patch_if_needed(
227                                &mut old_state.parent_frame,
228                                &mut patch.parent_frame,
229                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
230                            ),
231                            patch_if_needed(
232                                &mut old_state.z_index,
233                                &mut patch.z_index,
234                                expanded_node.occlusion.get().z_index,
235                            ),
236                            patch_if_needed(
237                                &mut old_state.corner_radius,
238                                &mut patch.corner_radius,
239                                corner_radius,
240                            ),
241                            patch_if_needed(
242                                &mut old_state.liquid_glass,
243                                &mut patch.liquid_glass,
244                                liquid_glass,
245                            ),
246                        ];
247
248                        if updates.into_iter().any(|v| v) {
249                            context.enqueue_native_message(
250                                pax_message::NativeMessage::GlassSurfaceUpdate(patch),
251                            );
252                        }
253                    });
254                },
255                &deps,
256            ));
257    }
258
259    fn handle_control_flow_node_expansion(
260        self: Rc<Self>,
261        expanded_node: &Rc<ExpandedNode>,
262        context: &Rc<RuntimeContext>,
263    ) {
264        // Detached sidecar trees are not mounted, but mask sources still need a
265        // fully expanded subtree so their descendants can contribute coverage.
266        let env = Rc::clone(&expanded_node.stack);
267        let children = borrow!(self.base().get_instance_children());
268        let children_with_envs = children.iter().cloned().zip(iter::repeat(env));
269        let children = expanded_node.generate_children(
270            children_with_envs,
271            context,
272            &expanded_node.parent_frame,
273            true,
274        );
275        for child in children.iter() {
276            child.recurse_control_flow_expansion(context);
277        }
278        expanded_node.children.set(children);
279    }
280
281    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
282        expanded_node
283            .changed_listener
284            .replace_with(Property::default());
285        if expanded_node.liquid_glass_scope.get().is_some() {
286            context.enqueue_native_message(pax_message::NativeMessage::GlassSurfaceDelete(
287                expanded_node.id.to_u32(),
288            ));
289        }
290    }
291
292    fn materializes_native_surface(&self, expanded_node: &ExpandedNode) -> bool {
293        expanded_node.liquid_glass_scope.get().is_some()
294    }
295
296    fn materializes_native_surface_before_children(&self, expanded_node: &ExpandedNode) -> bool {
297        self.materializes_native_surface(expanded_node)
298    }
299}