Skip to main content

pax_std/forms/
button.rs

1use crate::{Font, TextAlignHorizontal, TextAlignVertical};
2use pax_engine::api::Paint;
3use pax_engine::*;
4use pax_message::{AnyCreatePatch, ButtonPatch};
5use pax_runtime::api::{borrow, borrow_mut, use_RefCell, Color, Numeric, Size, Stroke};
6use pax_runtime::api::{Layer, Property};
7use pax_runtime::{
8    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
9};
10use std::rc::Rc;
11use_RefCell!();
12use crate::common::{native_surface_opacity, patch_if_needed, patch_liquid_glass_if_needed};
13use crate::TextStyle;
14
15#[cfg(all(test, not(feature = "designtime")))]
16mod publication_tests {
17    use super::*;
18    use pax_engine::api::pax_value::{PaxAny, ToFromPaxAny};
19    use pax_engine::api::{Platform, Variable, OS};
20    use pax_runtime::{CommonPropertiesInit, PaxEngine, PropertiesInit, PropertiesScopeInit};
21    use std::collections::HashMap;
22
23    #[test]
24    fn worker_result_reaches_native_patch_in_the_first_settlement() {
25        let mut engine = PaxEngine::new_empty(
26            (320.0, 240.0),
27            Platform::Web,
28            OS::Mac,
29            Box::new(|| 0),
30            Default::default(),
31        );
32        let _graph = engine.runtime_context.property_graph.enter();
33        let value = Property::new(0_u32);
34        let local = value.local();
35        let deps = [local.untyped()];
36        let button = Button::default();
37        button.label.replace_with(LocalProperty::computed(
38            move || format!("value {}", local.get()),
39            &deps,
40        ));
41        let properties = Rc::new(RefCell::new(button.to_pax_any()));
42        let args = InstantiationArgs {
43            prototypical_common_properties: CommonPropertiesInit::Default,
44            prototypical_properties: PropertiesInit::Factory(Box::new(move |_, node| {
45                node.is_none().then(|| properties.clone())
46            })),
47            properties_scope: PropertiesScopeInit::Factory(Box::new(|properties| {
48                let properties = properties.borrow();
49                let button = Button::ref_from_pax_any(&properties).unwrap();
50                HashMap::from([(
51                    "label".into(),
52                    Variable::new_from_typed_property(button.label.clone()),
53                )])
54            })),
55            handler_registry: None,
56            children: None,
57            component_template: None,
58            component_settings: None,
59            template_node_identifier: None,
60            template_node_type_id: None,
61            template_node_selector_info: None,
62            transition_config: Default::default(),
63        };
64        let child = ButtonInstance::instantiate(args);
65        engine.mount_root_component(pax_runtime::ComponentInstance::instantiate(
66            InstantiationArgs {
67                prototypical_common_properties: CommonPropertiesInit::Default,
68                prototypical_properties: PropertiesInit::Factory(Box::new(|_, node| {
69                    node.is_none()
70                        .then(|| Rc::new(RefCell::new(PaxAny::Builtin(Default::default()))))
71                })),
72                properties_scope: PropertiesScopeInit::None,
73                handler_registry: None,
74                children: None,
75                component_template: Some(RefCell::new(vec![child])),
76                component_settings: None,
77                template_node_identifier: None,
78                template_node_type_id: None,
79                template_node_selector_info: None,
80                transition_config: Default::default(),
81            },
82        ));
83        engine.tick();
84        for n in 1..=3 {
85            let value = value.clone();
86            std::thread::spawn(move || value.set(n)).join().unwrap();
87            let messages = engine.tick();
88            assert!(messages.iter().any(|message| matches!(message,
89                pax_message::NativeMessage::ButtonUpdate(patch) if patch.content.as_deref() == Some(format!("value {n}").as_str())
90            )), "first settlement did not publish value {n}");
91        }
92    }
93}
94
95/// A button control, delegating to a platform-specific native button.
96#[pax]
97#[engine_import_path("pax_engine")]
98#[primitive("pax_std::forms::button::ButtonInstance")]
99#[custom(Default)]
100pub struct Button {
101    /// Text label displayed inside the button.
102    pub label: Property<String>,
103    /// Button background color.
104    pub color: Property<Color>,
105    /// Button background color while hovered, when supported.
106    pub hover_color: Property<Color>,
107    /// Button corner radius, in pixels.
108    pub corner_radius: Property<f64>,
109    /// Button outline stroke.
110    pub outline: Property<Stroke>,
111    /// Text style applied to the label.
112    pub style: Property<TextStyle>,
113}
114
115impl Default for Button {
116    fn default() -> Self {
117        Self {
118            color: Property::new(Color::GRAY),
119            hover_color: Property::new(Color::INDIGO),
120            corner_radius: Property::new(8.0),
121            label: Property::new(String::from("button")),
122            style: Property::new(TextStyle {
123                font: Property::new(Font::default()),
124                font_size: Property::new(Size::Pixels(Numeric::F64(20.0))),
125                fill: Property::new(Paint::Solid(Color::WHITE)),
126                underline: Property::new(false),
127                align_multiline: Property::new(TextAlignHorizontal::Center),
128                align_vertical: Property::new(TextAlignVertical::Center),
129                align_horizontal: Property::new(TextAlignHorizontal::Center),
130            }),
131
132            outline: Property::new(Stroke {
133                width: Property::new(Size::Pixels(0.into())),
134                ..Stroke::default()
135            }),
136        }
137    }
138}
139
140// Runtime instance backing `<Button>`.
141pub struct ButtonInstance {
142    base: BaseInstance,
143}
144
145impl InstanceNode for ButtonInstance {
146    fn instantiate(args: InstantiationArgs) -> Rc<Self>
147    where
148        Self: Sized,
149    {
150        Rc::new(Self {
151            base: BaseInstance::new(
152                args,
153                InstanceFlags {
154                    invisible_to_slot: false,
155                    invisible_to_raycasting: false,
156                    layer: Layer::Native,
157                    is_component: false,
158                    is_slot: false,
159                },
160            ),
161        })
162    }
163
164    fn handle_mount(
165        self: Rc<Self>,
166        expanded_node: &Rc<ExpandedNode>,
167        context: &Rc<RuntimeContext>,
168    ) {
169        // Send creation message
170        let id = expanded_node.id.clone();
171        context.enqueue_native_message(pax_message::NativeMessage::ButtonCreate(AnyCreatePatch {
172            id: id.to_u32(),
173            parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
174            render_layer_id: 0,
175        }));
176
177        // send update message when relevant properties change
178        let weak_self_ref = Rc::downgrade(&expanded_node);
179        let context = Rc::clone(context);
180        let last_patch = Rc::new(RefCell::new(ButtonPatch {
181            id: id.to_u32(),
182            ..Default::default()
183        }));
184
185        let deps: Vec<_> = borrow!(expanded_node.properties_scope)
186            .values()
187            .cloned()
188            .map(|v| v.get_untyped_property().clone())
189            .chain([
190                expanded_node.transform_and_bounds.untyped(),
191                expanded_node.computed_opacity.untyped(),
192                expanded_node.occlusion.untyped(),
193                expanded_node.liquid_glass_scope.untyped(),
194            ])
195            .collect();
196        expanded_node
197            .changed_listener
198            .replace_with(LocalProperty::computed(
199                move || {
200                    let Some(expanded_node) = weak_self_ref.upgrade() else {
201                        return;
202                    };
203                    let mut old_state = borrow_mut!(last_patch);
204
205                    let mut patch = ButtonPatch {
206                        id: expanded_node.id.to_u32(),
207                        ..Default::default()
208                    };
209                    expanded_node.with_properties_unwrapped(|properties: &mut Button| {
210                        let computed_tab = expanded_node.transform_and_bounds.get();
211                        let (width, height) = computed_tab.bounds;
212                        let updates = [
213                            patch_if_needed(
214                                &mut old_state.outline_stroke_color,
215                                &mut patch.outline_stroke_color,
216                                (&crate::common::native_stroke_color(
217                                    &properties.outline.local().get(),
218                                ))
219                                    .into(),
220                            ),
221                            patch_if_needed(
222                                &mut old_state.outline_stroke_width,
223                                &mut patch.outline_stroke_width,
224                                properties
225                                    .outline
226                                    .local()
227                                    .get()
228                                    .width
229                                    .local()
230                                    .get()
231                                    .expect_pixels()
232                                    .to_float(),
233                            ),
234                            patch_if_needed(
235                                &mut old_state.hover_color,
236                                &mut patch.hover_color,
237                                (&properties.hover_color.local().get()).into(),
238                            ),
239                            patch_if_needed(
240                                &mut old_state.corner_radius,
241                                &mut patch.corner_radius,
242                                properties.corner_radius.local().get(),
243                            ),
244                            patch_if_needed(
245                                &mut old_state.content,
246                                &mut patch.content,
247                                properties.label.local().get(),
248                            ),
249                            patch_if_needed(
250                                &mut old_state.color,
251                                &mut patch.color,
252                                (&properties.color.local().get()).into(),
253                            ),
254                            patch_if_needed(
255                                &mut old_state.style,
256                                &mut patch.style,
257                                properties.style.local().get().message(true),
258                            ),
259                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
260                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
261                            patch_if_needed(
262                                &mut old_state.parent_frame,
263                                &mut patch.parent_frame,
264                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
265                            ),
266                            patch_if_needed(
267                                &mut old_state.z_index,
268                                &mut patch.z_index,
269                                expanded_node.occlusion.get().z_index,
270                            ),
271                            patch_if_needed(
272                                &mut old_state.transform,
273                                &mut patch.transform,
274                                computed_tab.transform.coeffs().to_vec(),
275                            ),
276                            patch_if_needed(
277                                &mut old_state.opacity,
278                                &mut patch.opacity,
279                                native_surface_opacity(&expanded_node, &context),
280                            ),
281                            patch_liquid_glass_if_needed(
282                                &mut old_state.liquid_glass,
283                                &mut patch.liquid_glass,
284                                &expanded_node,
285                            ),
286                        ];
287                        if updates.into_iter().any(|v| v == true) {
288                            context.enqueue_native_message(
289                                pax_message::NativeMessage::ButtonUpdate(patch),
290                            );
291                        }
292                    });
293                    ()
294                },
295                &deps,
296            ));
297    }
298
299    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
300        let id = expanded_node.id.clone();
301        expanded_node
302            .changed_listener
303            .replace_with(LocalProperty::default());
304        context.enqueue_native_message(pax_message::NativeMessage::ButtonDelete(id.to_u32()));
305    }
306
307    fn base(&self) -> &BaseInstance {
308        &self.base
309    }
310
311    fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
312        false
313    }
314
315    fn resolve_debug(
316        &self,
317        f: &mut std::fmt::Formatter,
318        _expanded_node: Option<&ExpandedNode>,
319    ) -> std::fmt::Result {
320        f.debug_struct("Button").finish_non_exhaustive()
321    }
322}