Skip to main content

pax_std/forms/
textbox.rs

1use crate::{Font, TextAlignHorizontal, TextAlignVertical, TextStyle};
2use pax_engine::api::LocalProperty;
3use pax_message::{AnyCreatePatch, TextboxPatch};
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_engine::pax;
11use pax_runtime_api::*;
12use std::rc::Rc;
13
14use crate::common::{native_surface_opacity, patch_if_needed, patch_liquid_glass_if_needed};
15
16/// A text input field, with support for styling and font specification.  Will be composited as a platform-specific
17/// native element, for example an `<input>` element in the browser or a `UITextField` on iOS.
18#[pax]
19#[engine_import_path("pax_engine")]
20#[primitive("pax_std::forms::textbox::TextboxInstance")]
21#[custom(Default)]
22pub struct Textbox {
23    /// Current text value.
24    pub text: Property<String>,
25    /// Textbox background color.
26    pub background: Property<Color>,
27    /// Placeholder text shown when empty, when supported by the chassis.
28    pub placeholder: Property<String>,
29    /// Border stroke.
30    pub stroke: Property<Stroke>,
31    /// Corner radius, in pixels.
32    pub corner_radius: Property<f64>,
33    /// Text style.
34    pub style: Property<TextStyle>,
35    /// Focus outline stroke.
36    pub outline: Property<Stroke>,
37    /// Requests focus when the textbox mounts.
38    pub focus_on_mount: Property<bool>,
39    /// Renders the textbox as a multiline text area when supported by the chassis.
40    pub multiline: Property<bool>,
41}
42
43impl Default for Textbox {
44    fn default() -> Self {
45        Self {
46            text: Default::default(),
47            background: Property::new(Color::rgb(249.into(), 250.into(), 251.into())),
48            stroke: Property::new(Stroke {
49                paint: Property::new(Color::rgb(209.into(), 213.into(), 219.into()).into()),
50                width: Property::new(Size::Pixels(1.into())),
51                cap: Property::new(StrokeCap::default()),
52                join: Property::new(StrokeJoin::default()),
53
54                ..Stroke::default()
55            }),
56            outline: Property::new(Stroke {
57                paint: Property::new(Color::rgb(0.into(), 0.into(), 0.into()).into()),
58                width: Property::new(Size::Pixels(1.into())),
59                cap: Property::new(StrokeCap::default()),
60                join: Property::new(StrokeJoin::default()),
61
62                ..Stroke::default()
63            }),
64            placeholder: Property::new("".into()),
65            corner_radius: Property::new(8.0.into()),
66            style: Property::new(TextStyle {
67                font: Property::new(Font::default()),
68                font_size: Property::new(Size::Pixels(Numeric::F64(14.0))),
69                fill: Property::new(Paint::Solid(Color::BLACK)),
70                underline: Property::new(false),
71                align_horizontal: Property::new(TextAlignHorizontal::Left),
72                align_multiline: Property::new(TextAlignHorizontal::Left),
73                align_vertical: Property::new(TextAlignVertical::Center),
74            }),
75            focus_on_mount: Property::new(false),
76            multiline: Property::new(false),
77        }
78    }
79}
80// Runtime instance backing `<Textbox>`.
81pub struct TextboxInstance {
82    base: BaseInstance,
83}
84
85impl InstanceNode for TextboxInstance {
86    fn instantiate(args: InstantiationArgs) -> Rc<Self>
87    where
88        Self: Sized,
89    {
90        Rc::new(Self {
91            base: BaseInstance::new(
92                args,
93                InstanceFlags {
94                    invisible_to_slot: false,
95                    invisible_to_raycasting: false,
96                    layer: Layer::Native,
97                    is_component: false,
98                    is_slot: false,
99                },
100            ),
101        })
102    }
103
104    fn handle_mount(
105        self: Rc<Self>,
106        expanded_node: &Rc<ExpandedNode>,
107        context: &Rc<RuntimeContext>,
108    ) {
109        // Send creation message
110        let id = expanded_node.id.clone();
111        context.enqueue_native_message(pax_message::NativeMessage::TextboxCreate(AnyCreatePatch {
112            id: id.to_u32(),
113            parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
114            render_layer_id: 0,
115        }));
116
117        // send update message when relevant properties change
118        let weak_self_ref = Rc::downgrade(&expanded_node);
119        let context = Rc::clone(context);
120        let last_patch = Rc::new(RefCell::new(TextboxPatch {
121            id: id.to_u32(),
122            ..Default::default()
123        }));
124
125        let deps: Vec<_> = borrow_mut!(expanded_node.properties_scope)
126            .values()
127            .cloned()
128            .map(|v| v.get_untyped_property().clone())
129            .chain([
130                expanded_node.transform_and_bounds.untyped(),
131                expanded_node.computed_opacity.untyped(),
132                expanded_node.occlusion.untyped(),
133                expanded_node.liquid_glass_scope.untyped(),
134            ])
135            .collect();
136        expanded_node
137            .changed_listener
138            .replace_with(LocalProperty::computed(
139                move || {
140                    let Some(expanded_node) = weak_self_ref.upgrade() else {
141                        return;
142                    };
143                    let id = expanded_node.id.clone();
144                    let mut old_state = borrow_mut!(last_patch);
145
146                    let mut patch = TextboxPatch {
147                        id: id.to_u32(),
148                        ..Default::default()
149                    };
150                    expanded_node.with_properties_unwrapped(|properties: &mut Textbox| {
151                        let computed_tab = expanded_node.transform_and_bounds.get();
152                        let (width, height) = computed_tab.bounds;
153                        let updates = [
154                            patch_if_needed(
155                                &mut old_state.text,
156                                &mut patch.text,
157                                properties.text.local().get(),
158                            ),
159                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
160                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
161                            patch_if_needed(
162                                &mut old_state.parent_frame,
163                                &mut patch.parent_frame,
164                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
165                            ),
166                            patch_if_needed(
167                                &mut old_state.z_index,
168                                &mut patch.z_index,
169                                expanded_node.occlusion.get().z_index,
170                            ),
171                            patch_if_needed(
172                                &mut old_state.transform,
173                                &mut patch.transform,
174                                computed_tab.transform.coeffs().to_vec(),
175                            ),
176                            patch_if_needed(
177                                &mut old_state.style,
178                                &mut patch.style,
179                                properties.style.local().get().message(true),
180                            ),
181                            patch_if_needed(
182                                &mut old_state.stroke_color,
183                                &mut patch.stroke_color,
184                                (&crate::common::native_stroke_color(
185                                    &properties.stroke.local().get(),
186                                ))
187                                    .into(),
188                            ),
189                            patch_if_needed(
190                                &mut old_state.stroke_width,
191                                &mut patch.stroke_width,
192                                properties
193                                    .stroke
194                                    .local()
195                                    .get()
196                                    .width
197                                    .local()
198                                    .get()
199                                    .get_pixels(width),
200                            ),
201                            patch_if_needed(
202                                &mut old_state.background,
203                                &mut patch.background,
204                                (&properties.background.local().get()).into(),
205                            ),
206                            patch_if_needed(
207                                &mut old_state.corner_radius,
208                                &mut patch.corner_radius,
209                                properties.corner_radius.local().get(),
210                            ),
211                            patch_if_needed(
212                                &mut old_state.focus_on_mount,
213                                &mut patch.focus_on_mount,
214                                properties.focus_on_mount.local().get(),
215                            ),
216                            patch_if_needed(
217                                &mut old_state.is_text_area,
218                                &mut patch.is_text_area,
219                                properties.multiline.local().get(),
220                            ),
221                            patch_if_needed(
222                                &mut old_state.placeholder,
223                                &mut patch.placeholder,
224                                properties.placeholder.local().get(),
225                            ),
226                            patch_if_needed(
227                                &mut old_state.outline_color,
228                                &mut patch.outline_color,
229                                (&crate::common::native_stroke_color(
230                                    &properties.outline.local().get(),
231                                ))
232                                    .into(),
233                            ),
234                            patch_if_needed(
235                                &mut old_state.outline_width,
236                                &mut patch.outline_width,
237                                properties
238                                    .outline
239                                    .local()
240                                    .get()
241                                    .width
242                                    .local()
243                                    .get()
244                                    .get_pixels(width),
245                            ),
246                            patch_if_needed(
247                                &mut old_state.opacity,
248                                &mut patch.opacity,
249                                native_surface_opacity(&expanded_node, &context),
250                            ),
251                            patch_liquid_glass_if_needed(
252                                &mut old_state.liquid_glass,
253                                &mut patch.liquid_glass,
254                                &expanded_node,
255                            ),
256                        ];
257                        if updates.into_iter().any(|v| v == true) {
258                            context.enqueue_native_message(
259                                pax_message::NativeMessage::TextboxUpdate(patch),
260                            );
261                        }
262                    });
263                    ()
264                },
265                &deps,
266            ));
267    }
268
269    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
270        let id = expanded_node.id.clone();
271        expanded_node
272            .changed_listener
273            .replace_with(LocalProperty::default());
274        context.enqueue_native_message(pax_message::NativeMessage::TextboxDelete(id.to_u32()));
275    }
276
277    fn base(&self) -> &BaseInstance {
278        &self.base
279    }
280
281    fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
282        false
283    }
284
285    fn handle_native_interrupt(
286        &self,
287        expanded_node: &Rc<ExpandedNode>,
288        interrupt: &pax_message::NativeInterrupt,
289    ) {
290        if let pax_message::NativeInterrupt::FormTextboxInput(args) = interrupt {
291            expanded_node.with_properties_unwrapped(|textbox: &mut Textbox| {
292                textbox.text.set(args.text.clone());
293            })
294        } else {
295            log::warn!("textbox element was handed interrupt it doesn't use");
296        }
297    }
298
299    fn resolve_debug(
300        &self,
301        f: &mut std::fmt::Formatter,
302        _expanded_node: Option<&ExpandedNode>,
303    ) -> std::fmt::Result {
304        f.debug_struct("Textbox").finish_non_exhaustive()
305    }
306}