Skip to main content

pax_std/core/
group.rs

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