Skip to main content

pax_std/forms/
checkbox.rs

1use pax_engine::api::LocalProperty;
2use pax_message::{AnyCreatePatch, CheckboxPatch};
3use pax_runtime::api::{Layer, Property};
4use pax_runtime::{
5    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
6};
7use_RefCell!();
8use pax_engine::pax;
9use pax_runtime::api::*;
10
11use std::rc::Rc;
12
13use crate::common::{native_surface_opacity, patch_if_needed, patch_liquid_glass_if_needed};
14
15/// A checkbox control, delegating to a platform-specific native checkbox.
16#[pax]
17#[engine_import_path("pax_engine")]
18#[primitive("pax_std::forms::checkbox::CheckboxInstance")]
19#[custom(Default)]
20pub struct Checkbox {
21    /// The background color when unchecked
22    pub background: Property<Color>,
23    /// The background color when checked
24    pub background_checked: Property<Color>,
25    /// The outline stroke of the checkbox
26    pub outline: Property<Stroke>,
27    /// The border radius of the checkbox
28    pub corner_radius: Property<f64>,
29    /// Whether the checkbox is currently checked
30    pub checked: Property<bool>,
31}
32
33impl Default for Checkbox {
34    fn default() -> Self {
35        Self {
36            background: Property::new(Color::rgb(243.into(), 244.into(), 246.into())),
37            background_checked: Property::new(Color::rgb(27.into(), 100.into(), 242.into())),
38            outline: Property::new(Stroke {
39                paint: Property::new(Color::rgb(209.into(), 213.into(), 219.into()).into()),
40                width: Property::new(Size::Pixels(1.into())),
41                cap: Property::new(StrokeCap::default()),
42                join: Property::new(StrokeJoin::default()),
43
44                ..Stroke::default()
45            }),
46            corner_radius: Property::new(5.0),
47            checked: Property::new(false),
48        }
49    }
50}
51
52// Runtime instance backing `<Checkbox>`.
53pub struct CheckboxInstance {
54    base: BaseInstance,
55}
56
57impl InstanceNode for CheckboxInstance {
58    fn instantiate(args: InstantiationArgs) -> Rc<Self>
59    where
60        Self: Sized,
61    {
62        Rc::new(Self {
63            base: BaseInstance::new(
64                args,
65                InstanceFlags {
66                    invisible_to_slot: false,
67                    invisible_to_raycasting: false,
68                    layer: Layer::Native,
69                    is_component: false,
70                    is_slot: false,
71                },
72            ),
73        })
74    }
75
76    fn handle_mount(
77        self: Rc<Self>,
78        expanded_node: &Rc<ExpandedNode>,
79        context: &Rc<RuntimeContext>,
80    ) {
81        let id = expanded_node.id.to_u32();
82        context.enqueue_native_message(pax_message::NativeMessage::CheckboxCreate(
83            AnyCreatePatch {
84                id,
85                parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
86                render_layer_id: 0,
87            },
88        ));
89        let weak_self_ref = Rc::downgrade(&expanded_node);
90        let context = Rc::clone(context);
91        let last_patch = Rc::new(RefCell::new(CheckboxPatch {
92            id,
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                expanded_node.liquid_glass_scope.untyped(),
105            ])
106            .collect();
107        expanded_node
108            .changed_listener
109            .replace_with(LocalProperty::computed(
110                move || {
111                    let Some(expanded_node) = weak_self_ref.upgrade() else {
112                        return;
113                    };
114                    let mut old_state = borrow_mut!(last_patch);
115
116                    let mut patch = CheckboxPatch {
117                        id,
118                        ..Default::default()
119                    };
120                    expanded_node.with_properties_unwrapped(|properties: &mut Checkbox| {
121                        let computed_tab = expanded_node.transform_and_bounds.get();
122                        let (width, height) = computed_tab.bounds;
123                        let updates = [
124                            patch_if_needed(
125                                &mut old_state.background,
126                                &mut patch.background,
127                                (&properties.background.local().get()).into(),
128                            ),
129                            patch_if_needed(
130                                &mut old_state.background_checked,
131                                &mut patch.background_checked,
132                                (&properties.background_checked.local().get()).into(),
133                            ),
134                            patch_if_needed(
135                                &mut old_state.outline_color,
136                                &mut patch.outline_color,
137                                (&crate::common::native_stroke_color(
138                                    &properties.outline.local().get(),
139                                ))
140                                    .into(),
141                            ),
142                            patch_if_needed(
143                                &mut old_state.outline_width,
144                                &mut patch.outline_width,
145                                properties
146                                    .outline
147                                    .local()
148                                    .get()
149                                    .width
150                                    .local()
151                                    .get()
152                                    .expect_pixels()
153                                    .to_float(),
154                            ),
155                            patch_if_needed(
156                                &mut old_state.corner_radius,
157                                &mut patch.corner_radius,
158                                properties.corner_radius.local().get(),
159                            ),
160                            patch_if_needed(
161                                &mut old_state.checked,
162                                &mut patch.checked,
163                                properties.checked.local().get(),
164                            ),
165                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
166                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
167                            patch_if_needed(
168                                &mut old_state.parent_frame,
169                                &mut patch.parent_frame,
170                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
171                            ),
172                            patch_if_needed(
173                                &mut old_state.z_index,
174                                &mut patch.z_index,
175                                expanded_node.occlusion.get().z_index,
176                            ),
177                            patch_if_needed(
178                                &mut old_state.transform,
179                                &mut patch.transform,
180                                computed_tab.transform.coeffs().to_vec(),
181                            ),
182                            patch_if_needed(
183                                &mut old_state.opacity,
184                                &mut patch.opacity,
185                                native_surface_opacity(&expanded_node, &context),
186                            ),
187                            patch_liquid_glass_if_needed(
188                                &mut old_state.liquid_glass,
189                                &mut patch.liquid_glass,
190                                &expanded_node,
191                            ),
192                        ];
193                        if updates.into_iter().any(|v| v == true) {
194                            context.enqueue_native_message(
195                                pax_message::NativeMessage::CheckboxUpdate(patch),
196                            );
197                        }
198                    });
199                    ()
200                },
201                &deps,
202            ));
203    }
204
205    fn handle_native_interrupt(
206        &self,
207        expanded_node: &Rc<ExpandedNode>,
208        interrupt: &pax_message::NativeInterrupt,
209    ) {
210        if let pax_message::NativeInterrupt::FormCheckboxToggle(args) = interrupt {
211            expanded_node.with_properties_unwrapped(|checkbox: &mut Checkbox| {
212                checkbox.checked.set(args.state);
213            });
214        } else {
215            log::warn!("checkbox element was handed interrupt it doesn't use");
216        }
217    }
218
219    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
220        let id = expanded_node.id.clone();
221        expanded_node
222            .changed_listener
223            .replace_with(LocalProperty::default());
224        context.enqueue_native_message(pax_message::NativeMessage::CheckboxDelete(id.to_u32()));
225    }
226
227    fn base(&self) -> &BaseInstance {
228        &self.base
229    }
230
231    fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
232        false
233    }
234
235    fn resolve_debug(
236        &self,
237        f: &mut std::fmt::Formatter,
238        _expanded_node: Option<&ExpandedNode>,
239    ) -> std::fmt::Result {
240        f.debug_struct("Checkbox").finish_non_exhaustive()
241    }
242}