Skip to main content

pax_std/forms/
dropdown.rs

1use crate::{Font, TextAlignHorizontal, TextAlignVertical, TextStyle};
2use pax_engine::api::LocalProperty;
3use pax_message::{AnyCreatePatch, DropdownPatch, NativeInterrupt};
4use pax_runtime::api as pax_runtime_api;
5use pax_runtime::api::{use_RefCell, Layer, Property};
6use pax_runtime::{
7    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
8};
9use_RefCell!();
10use pax_runtime_api::*;
11
12use pax_engine::pax;
13use std::rc::Rc;
14
15use crate::common::{native_surface_opacity, patch_if_needed, patch_liquid_glass_if_needed};
16
17/// A dropdown list control, delegating to a platform-specific native dropdown implementation.
18/// Allows the selection of a single option from a list of options.
19#[pax]
20#[engine_import_path("pax_engine")]
21#[primitive("pax_std::forms::dropdown::DropdownInstance")]
22#[custom(Default)]
23pub struct Dropdown {
24    /// Outline stroke for the dropdown control.
25    pub stroke: Property<Stroke>,
26    /// List of selectable option labels.
27    pub options: Property<Vec<String>>,
28    /// Index of the currently selected option.
29    pub selected_id: Property<u32>,
30    /// Text style for option labels.
31    pub style: Property<TextStyle>,
32    /// Dropdown background color.
33    pub background: Property<Color>,
34    /// Dropdown corner radius, in pixels.
35    pub corner_radius: Property<f64>,
36}
37
38impl Default for Dropdown {
39    fn default() -> Self {
40        Self {
41            options: Property::new(vec!["option 1".to_owned(), "option 2".to_owned()]),
42            selected_id: Property::new(0),
43            background: Property::new(Color::rgb(249.into(), 250.into(), 251.into())),
44            stroke: Property::new(Stroke {
45                paint: Property::new(Color::rgb(209.into(), 213.into(), 219.into()).into()),
46                width: Property::new(Size::Pixels(1.into())),
47                cap: Property::new(StrokeCap::default()),
48                join: Property::new(StrokeJoin::default()),
49
50                ..Stroke::default()
51            }),
52            corner_radius: Property::new(8.0.into()),
53            style: Property::new(TextStyle {
54                font: Property::new(Font::default()),
55                font_size: Property::new(Size::Pixels(Numeric::F64(14.0))),
56                fill: Property::new(Paint::Solid(Color::BLACK)),
57                underline: Property::new(false),
58                align_horizontal: Property::new(TextAlignHorizontal::Left),
59                align_multiline: Property::new(TextAlignHorizontal::Left),
60                align_vertical: Property::new(TextAlignVertical::Center),
61            }),
62        }
63    }
64}
65
66// Runtime instance backing `<Dropdown>`.
67pub struct DropdownInstance {
68    base: BaseInstance,
69}
70
71impl InstanceNode for DropdownInstance {
72    fn instantiate(args: InstantiationArgs) -> Rc<Self>
73    where
74        Self: Sized,
75    {
76        Rc::new(Self {
77            base: BaseInstance::new(
78                args,
79                InstanceFlags {
80                    invisible_to_slot: false,
81                    invisible_to_raycasting: false,
82                    layer: Layer::Native,
83                    is_component: false,
84                    is_slot: false,
85                },
86            ),
87        })
88    }
89
90    fn handle_mount(
91        self: Rc<Self>,
92        expanded_node: &Rc<ExpandedNode>,
93        context: &Rc<RuntimeContext>,
94    ) {
95        // Send creation message
96        let id = expanded_node.id.clone();
97        context.enqueue_native_message(pax_message::NativeMessage::DropdownCreate(
98            AnyCreatePatch {
99                id: id.to_u32(),
100                parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
101                render_layer_id: 0,
102            },
103        ));
104
105        // send update message when relevant properties change
106        let weak_self_ref = Rc::downgrade(&expanded_node);
107        let context = Rc::clone(context);
108        let last_patch = Rc::new(RefCell::new(DropdownPatch {
109            id: id.to_u32(),
110            ..Default::default()
111        }));
112
113        let deps: Vec<_> = borrow_mut!(expanded_node.properties_scope)
114            .values()
115            .cloned()
116            .map(|v| v.get_untyped_property().clone())
117            .chain([
118                expanded_node.transform_and_bounds.untyped(),
119                expanded_node.computed_opacity.untyped(),
120                expanded_node.occlusion.untyped(),
121                expanded_node.liquid_glass_scope.untyped(),
122            ])
123            .collect();
124        expanded_node
125            .changed_listener
126            .replace_with(LocalProperty::computed(
127                move || {
128                    let Some(expanded_node) = weak_self_ref.upgrade() else {
129                        return;
130                    };
131                    let id = expanded_node.id.clone();
132                    let mut old_state = borrow_mut!(last_patch);
133
134                    let mut patch = DropdownPatch {
135                        id: id.to_u32(),
136                        ..Default::default()
137                    };
138                    expanded_node.with_properties_unwrapped(|properties: &mut Dropdown| {
139                        let computed_tab = expanded_node.transform_and_bounds.get();
140                        let (width, height) = computed_tab.bounds;
141                        let updates = [
142                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
143                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
144                            patch_if_needed(
145                                &mut old_state.parent_frame,
146                                &mut patch.parent_frame,
147                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
148                            ),
149                            patch_if_needed(
150                                &mut old_state.z_index,
151                                &mut patch.z_index,
152                                expanded_node.occlusion.get().z_index,
153                            ),
154                            patch_if_needed(
155                                &mut old_state.transform,
156                                &mut patch.transform,
157                                computed_tab.transform.coeffs().to_vec(),
158                            ),
159                            patch_if_needed(
160                                &mut old_state.style,
161                                &mut patch.style,
162                                properties.style.local().get().message(true),
163                            ),
164                            patch_if_needed(
165                                &mut old_state.stroke_color,
166                                &mut patch.stroke_color,
167                                (&crate::common::native_stroke_color(
168                                    &properties.stroke.local().get(),
169                                ))
170                                    .into(),
171                            ),
172                            patch_if_needed(
173                                &mut old_state.stroke_width,
174                                &mut patch.stroke_width,
175                                properties
176                                    .stroke
177                                    .local()
178                                    .get()
179                                    .width
180                                    .local()
181                                    .get()
182                                    .get_pixels(width),
183                            ),
184                            patch_if_needed(
185                                &mut old_state.background,
186                                &mut patch.background,
187                                (&properties.background.local().get()).into(),
188                            ),
189                            patch_if_needed(
190                                &mut old_state.selected_id,
191                                &mut patch.selected_id,
192                                properties.selected_id.local().get(),
193                            ),
194                            patch_if_needed(
195                                &mut old_state.corner_radius,
196                                &mut patch.corner_radius,
197                                properties.corner_radius.local().get(),
198                            ),
199                            patch_if_needed(
200                                &mut old_state.options,
201                                &mut patch.options,
202                                properties.options.local().get(),
203                            ),
204                            patch_if_needed(
205                                &mut old_state.opacity,
206                                &mut patch.opacity,
207                                native_surface_opacity(&expanded_node, &context),
208                            ),
209                            patch_liquid_glass_if_needed(
210                                &mut old_state.liquid_glass,
211                                &mut patch.liquid_glass,
212                                &expanded_node,
213                            ),
214                        ];
215                        if updates.into_iter().any(|v| v == true) {
216                            context.enqueue_native_message(
217                                pax_message::NativeMessage::DropdownUpdate(patch),
218                            );
219                        }
220                    });
221                    ()
222                },
223                &deps,
224            ));
225    }
226
227    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
228        let id = expanded_node.id.clone();
229        expanded_node
230            .changed_listener
231            .replace_with(LocalProperty::default());
232        context.enqueue_native_message(pax_message::NativeMessage::DropdownDelete(id.to_u32()));
233    }
234
235    fn base(&self) -> &BaseInstance {
236        &self.base
237    }
238
239    fn resolve_debug(
240        &self,
241        f: &mut std::fmt::Formatter,
242        _expanded_node: Option<&ExpandedNode>,
243    ) -> std::fmt::Result {
244        f.debug_struct("Dropdown").finish_non_exhaustive()
245    }
246
247    fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
248        false
249    }
250
251    fn handle_native_interrupt(
252        &self,
253        expanded_node: &Rc<ExpandedNode>,
254        interrupt: &NativeInterrupt,
255    ) {
256        if let NativeInterrupt::FormDropdownChange(args) = interrupt {
257            expanded_node.with_properties_unwrapped(|props: &mut Dropdown| {
258                if props.selected_id.local().get() != args.selected_id {
259                    props.selected_id.set(args.selected_id)
260                }
261            });
262        }
263    }
264}