Skip to main content

pax_std/forms/
checkbox.rs

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