Skip to main content

pax_std/forms/
button.rs

1use crate::{Font, TextAlignHorizontal, TextAlignVertical};
2use pax_engine::api::Fill;
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/// A button control, delegating to a platform-specific native button.
16#[pax]
17#[engine_import_path("pax_engine")]
18#[primitive("pax_std::forms::button::ButtonInstance")]
19#[custom(Default)]
20pub struct Button {
21    /// Text label displayed inside the button.
22    pub label: Property<String>,
23    /// Button background color.
24    pub color: Property<Color>,
25    /// Button background color while hovered, when supported.
26    pub hover_color: Property<Color>,
27    /// Button corner radius, in pixels.
28    pub corner_radius: Property<f64>,
29    /// Button outline stroke.
30    pub outline: Property<Stroke>,
31    /// Text style applied to the label.
32    pub style: Property<TextStyle>,
33}
34
35impl Default for Button {
36    fn default() -> Self {
37        Self {
38            color: Property::new(Color::GRAY),
39            hover_color: Property::new(Color::INDIGO),
40            corner_radius: Property::new(8.0),
41            label: Property::new(String::from("button")),
42            style: Property::new(TextStyle {
43                font: Property::new(Font::default()),
44                font_size: Property::new(Size::Pixels(Numeric::F64(20.0))),
45                fill: Property::new(Fill::Solid(Color::WHITE)),
46                underline: Property::new(false),
47                align_multiline: Property::new(TextAlignHorizontal::Center),
48                align_vertical: Property::new(TextAlignVertical::Center),
49                align_horizontal: Property::new(TextAlignHorizontal::Center),
50            }),
51
52            outline: Property::new(Stroke::default()),
53        }
54    }
55}
56
57// Runtime instance backing `<Button>`.
58pub struct ButtonInstance {
59    base: BaseInstance,
60}
61
62impl InstanceNode for ButtonInstance {
63    fn instantiate(args: InstantiationArgs) -> Rc<Self>
64    where
65        Self: Sized,
66    {
67        Rc::new(Self {
68            base: BaseInstance::new(
69                args,
70                InstanceFlags {
71                    invisible_to_slot: false,
72                    invisible_to_raycasting: false,
73                    layer: Layer::Native,
74                    is_component: false,
75                    is_slot: false,
76                },
77            ),
78        })
79    }
80
81    fn handle_mount(
82        self: Rc<Self>,
83        expanded_node: &Rc<ExpandedNode>,
84        context: &Rc<RuntimeContext>,
85    ) {
86        // Send creation message
87        let id = expanded_node.id.clone();
88        context.enqueue_native_message(pax_message::NativeMessage::ButtonCreate(AnyCreatePatch {
89            id: id.to_u32(),
90            parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
91            render_layer_id: 0,
92        }));
93
94        // send update message when relevant properties change
95        let weak_self_ref = Rc::downgrade(&expanded_node);
96        let context = Rc::clone(context);
97        let last_patch = Rc::new(RefCell::new(ButtonPatch {
98            id: id.to_u32(),
99            ..Default::default()
100        }));
101
102        let deps: Vec<_> = borrow!(expanded_node.properties_scope)
103            .values()
104            .cloned()
105            .map(|v| v.get_untyped_property().clone())
106            .chain([
107                expanded_node.transform_and_bounds.untyped(),
108                expanded_node.computed_opacity.untyped(),
109                expanded_node.occlusion.untyped(),
110                expanded_node.liquid_glass_scope.untyped(),
111            ])
112            .collect();
113        expanded_node
114            .changed_listener
115            .replace_with(Property::computed(
116                move || {
117                    let Some(expanded_node) = weak_self_ref.upgrade() else {
118                        return;
119                    };
120                    let mut old_state = borrow_mut!(last_patch);
121
122                    let mut patch = ButtonPatch {
123                        id: expanded_node.id.to_u32(),
124                        ..Default::default()
125                    };
126                    expanded_node.with_properties_unwrapped(|properties: &mut Button| {
127                        let computed_tab = expanded_node.transform_and_bounds.get();
128                        let (width, height) = computed_tab.bounds;
129                        let updates = [
130                            patch_if_needed(
131                                &mut old_state.outline_stroke_color,
132                                &mut patch.outline_stroke_color,
133                                (&properties.outline.get().color.get()).into(),
134                            ),
135                            patch_if_needed(
136                                &mut old_state.outline_stroke_width,
137                                &mut patch.outline_stroke_width,
138                                properties
139                                    .outline
140                                    .get()
141                                    .width
142                                    .get()
143                                    .expect_pixels()
144                                    .to_float(),
145                            ),
146                            patch_if_needed(
147                                &mut old_state.hover_color,
148                                &mut patch.hover_color,
149                                (&properties.hover_color.get()).into(),
150                            ),
151                            patch_if_needed(
152                                &mut old_state.corner_radius,
153                                &mut patch.corner_radius,
154                                properties.corner_radius.get(),
155                            ),
156                            patch_if_needed(
157                                &mut old_state.content,
158                                &mut patch.content,
159                                properties.label.get(),
160                            ),
161                            patch_if_needed(
162                                &mut old_state.color,
163                                &mut patch.color,
164                                (&properties.color.get()).into(),
165                            ),
166                            patch_if_needed(
167                                &mut old_state.style,
168                                &mut patch.style,
169                                (&properties.style.get()).into(),
170                            ),
171                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
172                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
173                            patch_if_needed(
174                                &mut old_state.parent_frame,
175                                &mut patch.parent_frame,
176                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
177                            ),
178                            patch_if_needed(
179                                &mut old_state.z_index,
180                                &mut patch.z_index,
181                                expanded_node.occlusion.get().z_index,
182                            ),
183                            patch_if_needed(
184                                &mut old_state.transform,
185                                &mut patch.transform,
186                                computed_tab.transform.coeffs().to_vec(),
187                            ),
188                            patch_if_needed(
189                                &mut old_state.opacity,
190                                &mut patch.opacity,
191                                native_surface_opacity(&expanded_node, &context),
192                            ),
193                            patch_liquid_glass_if_needed(
194                                &mut old_state.liquid_glass,
195                                &mut patch.liquid_glass,
196                                &expanded_node,
197                            ),
198                        ];
199                        if updates.into_iter().any(|v| v == true) {
200                            context.enqueue_native_message(
201                                pax_message::NativeMessage::ButtonUpdate(patch),
202                            );
203                        }
204                    });
205                    ()
206                },
207                &deps,
208            ));
209    }
210
211    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
212        let id = expanded_node.id.clone();
213        expanded_node
214            .changed_listener
215            .replace_with(Property::default());
216        context.enqueue_native_message(pax_message::NativeMessage::ButtonDelete(id.to_u32()));
217    }
218
219    fn base(&self) -> &BaseInstance {
220        &self.base
221    }
222
223    fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
224        false
225    }
226
227    fn resolve_debug(
228        &self,
229        f: &mut std::fmt::Formatter,
230        _expanded_node: Option<&ExpandedNode>,
231    ) -> std::fmt::Result {
232        f.debug_struct("Button").finish_non_exhaustive()
233    }
234}