Skip to main content

pax_std/core/
event_blocker.rs

1use pax_engine::api::LocalProperty;
2use std::iter;
3use std::rc::Rc;
4
5use crate::common::native_surface_opacity;
6use crate::patch_if_needed;
7use pax_engine::api::{borrow, borrow_mut, use_RefCell, Color};
8use pax_engine::pax;
9use pax_message::{AnyCreatePatch, EventBlockerPatch};
10use pax_runtime::api::{Layer, Property};
11use pax_runtime::{
12    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
13};
14use_RefCell!();
15
16#[pax]
17#[engine_import_path("pax_engine")]
18#[primitive("pax_std::core::event_blocker::EventBlockerInstance")]
19#[custom(Default)]
20/// Native surface that absorbs pointer events before they reach content beneath it.
21///
22/// `background` defaults to transparent. A solid background is useful for modal
23/// underlays that must composite above native controls and scroller canvas islands.
24pub struct EventBlocker {
25    /// Solid background painted by the native surface.
26    pub background: Property<Color>,
27}
28
29impl Default for EventBlocker {
30    fn default() -> Self {
31        Self {
32            background: Property::new(Color::TRANSPARENT),
33        }
34    }
35}
36
37// Runtime instance backing `<EventBlocker>`.
38pub struct EventBlockerInstance {
39    base: BaseInstance,
40}
41
42impl InstanceNode for EventBlockerInstance {
43    fn instantiate(args: InstantiationArgs) -> Rc<Self>
44    where
45        Self: Sized,
46    {
47        Rc::new(Self {
48            base: BaseInstance::new(
49                args,
50                InstanceFlags {
51                    invisible_to_slot: false,
52                    invisible_to_raycasting: false,
53                    layer: Layer::Native,
54                    is_component: false,
55                    is_slot: false,
56                },
57            ),
58        })
59    }
60
61    fn handle_mount(
62        self: Rc<Self>,
63        expanded_node: &Rc<ExpandedNode>,
64        context: &Rc<RuntimeContext>,
65    ) {
66        let id = expanded_node.id.clone();
67        context.enqueue_native_message(pax_message::NativeMessage::EventBlockerCreate(
68            AnyCreatePatch {
69                id: id.to_u32(),
70                parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
71                render_layer_id: 0,
72            },
73        ));
74
75        // bellow is the same as default impl for adding children in instance_node
76        let env = Rc::clone(&expanded_node.stack);
77        let children = borrow!(self.base().get_instance_children());
78        let children_with_envs = children.iter().cloned().zip(iter::repeat(env));
79
80        let new_children = expanded_node.generate_children(
81            children_with_envs,
82            context,
83            &expanded_node.parent_frame,
84            true,
85        );
86        expanded_node.children.set(new_children);
87
88        // send update message when relevant properties change
89        let weak_self_ref = Rc::downgrade(&expanded_node);
90        let context = Rc::clone(context);
91        let last_patch = Rc::new(RefCell::new(EventBlockerPatch {
92            id: id.to_u32(),
93            ..Default::default()
94        }));
95
96        let deps: Vec<_> = borrow!(expanded_node.properties_scope)
97            .values()
98            .cloned()
99            .map(|v| v.get_untyped_property().clone())
100            .chain([
101                expanded_node.transform_and_bounds.untyped(),
102                expanded_node.computed_opacity.untyped(),
103                expanded_node.occlusion.untyped(),
104            ])
105            .collect();
106        expanded_node
107            .changed_listener
108            .replace_with(LocalProperty::computed(
109                move || {
110                    let Some(expanded_node) = weak_self_ref.upgrade() else {
111                        return;
112                    };
113                    let id = expanded_node.id.to_u32();
114                    let mut old_state = borrow_mut!(last_patch);
115
116                    let mut patch = EventBlockerPatch {
117                        id,
118                        ..Default::default()
119                    };
120                    expanded_node.with_properties_unwrapped(|properties: &mut EventBlocker| {
121                        let computed_tab = expanded_node.transform_and_bounds.get();
122                        let (width, height) = computed_tab.bounds;
123
124                        let updates = [
125                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
126                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
127                            patch_if_needed(
128                                &mut old_state.parent_frame,
129                                &mut patch.parent_frame,
130                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
131                            ),
132                            patch_if_needed(
133                                &mut old_state.z_index,
134                                &mut patch.z_index,
135                                expanded_node.occlusion.get().z_index,
136                            ),
137                            patch_if_needed(
138                                &mut old_state.transform,
139                                &mut patch.transform,
140                                computed_tab.transform.coeffs().to_vec(),
141                            ),
142                            patch_if_needed(
143                                &mut old_state.opacity,
144                                &mut patch.opacity,
145                                native_surface_opacity(&expanded_node, &context),
146                            ),
147                            patch_if_needed(
148                                &mut old_state.background,
149                                &mut patch.background,
150                                (&properties.background.local().get()).into(),
151                            ),
152                        ];
153
154                        if updates.into_iter().any(|v| v == true) {
155                            context.enqueue_native_message(
156                                pax_message::NativeMessage::EventBlockerUpdate(patch),
157                            );
158                        }
159                    });
160                    ()
161                },
162                &deps,
163            ));
164    }
165
166    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
167        let id = expanded_node.id.clone();
168        expanded_node
169            .changed_listener
170            .replace_with(LocalProperty::default());
171        context.enqueue_native_message(pax_message::NativeMessage::EventBlockerDelete(id.to_u32()));
172    }
173
174    fn resolve_debug(
175        &self,
176        f: &mut std::fmt::Formatter,
177        expanded_node: Option<&ExpandedNode>,
178    ) -> std::fmt::Result {
179        match expanded_node {
180            Some(expanded_node) => {
181                expanded_node.with_properties_unwrapped(|_f: &mut EventBlocker| {
182                    f.debug_struct("EventBlocker").finish()
183                })
184            }
185            None => f.debug_struct("EventBlocker").finish_non_exhaustive(),
186        }
187    }
188
189    fn base(&self) -> &BaseInstance {
190        &self.base
191    }
192}