Skip to main content

pax_std/forms/
combo_box.rs

1#![allow(unused)]
2use pax_engine::api::LocalProperty;
3use std::cell::Cell;
4use std::rc::Rc;
5
6use crate::{EventBlocker, Group, Path, Rectangle, Scroller, Stacker, Text};
7use crate::{TextStyle, Textbox};
8use pax_engine::api::{Click, Event, Store, Stroke};
9use pax_engine::api::{Color, Property};
10use pax_engine::*;
11use pax_runtime::api::NodeContext;
12
13/// A text-filtered list control for selecting one item, with optional "new item" behavior.
14///
15/// Clicking or tapping the input opens the list. Filtering is case-sensitive,
16/// with prefix matches first and alphabetical order within each group. Selecting
17/// a row commits its index in `options`, copies its label to `text`, and closes
18/// the list. Editing or blurring the input does not commit a selection or clear
19/// the previous one. Bind `text` for the query and `selected` for the last choice.
20///
21/// This composed control uses a native Textbox and Pax list rows. It does not
22/// implement arrow-key/Enter list selection or a complete accessible combobox
23/// contract.
24#[pax]
25#[engine_import_path("pax_engine")]
26#[inlined(
27    if _options_visible {
28        <Scroller
29            anchor_y=0%
30            y={100%+1px}
31            height=500%
32            width={100% + 8px}
33            x=1px
34            scroll_height={(Math::len(self._filtered_options)*100/5)%}
35    		unclippable=true
36        >
37            <Stacker gutter=1px height={(Math::len(self._filtered_options)*100/5)%}>
38                for option_data in self._filtered_options key option_data.key {
39                    <ComboBoxListItem style=style background=background data={option_data} @new_item=self.dispatch_new_item/>
40                }
41            </Stacker>
42            <Rectangle fill={stroke.paint} height={(Math::len(self._filtered_options)*100/5)%}/>
43        </Scroller>
44    }
45    if self.text != "" && self.selected != None && !_options_visible {
46        <Group  @click=self.remove_index x=100% width=30px>
47            <EventBlocker/>
48            <Path class="x_symbol" x=50% y=50% width=15px height=15px/>
49        </Group>
50    }
51    <Textbox
52        @click=on_click
53        text=bind:text
54        style=style
55        background=background
56        stroke=stroke
57        corner_radius=corner_radius
58    />
59
60    @settings {
61        @mount: on_mount
62        @pre_render: update
63
64    .x_symbol {
65        elements: {[
66            PathElement::Point(0%, 10%),
67            PathElement::Line,
68            PathElement::Point(50% - 10%, 50%),
69            PathElement::Line,
70            PathElement::Point(0%, 100% - 10%),
71            PathElement::Line,
72            PathElement::Point(10%, 100%),
73            PathElement::Line,
74            PathElement::Point(50%, 50% + 10%),
75            PathElement::Line,
76            PathElement::Point(100% - 10%, 100%),
77            PathElement::Line,
78            PathElement::Point(100%, 100% - 10%),
79            PathElement::Line,
80            PathElement::Point(50% + 10%, 50%),
81            PathElement::Line,
82            PathElement::Point(100%, 10%),
83            PathElement::Line,
84            PathElement::Point(100% - 10%, 0%),
85            PathElement::Line,
86            PathElement::Point(50%, 50% - 10%),
87            PathElement::Line,
88            PathElement::Point(10%, 0%),
89            PathElement::Close
90        ]},
91        stroke: {
92            paint: TRANSPARENT,
93            width: 0
94        },
95        fill: rgb(200, 200, 200)
96    }
97}
98
99)]
100pub struct ComboBox {
101    /// Text currently shown in the input.
102    pub text: Property<String>,
103    /// Index of the last selected option, or `None`. Editing `text` filters the
104    /// list; clicking a row commits its original index in `options`.
105    pub selected: Property<Option<usize>>,
106    /// Available option labels; duplicate labels retain distinct indices.
107    /// Changing this list refreshes the selected label at the existing index.
108    /// An out-of-range selection becomes `None` and clears the text. Reordering
109    /// options does not preserve an application's item identity automatically.
110    pub options: Property<Vec<String>>,
111    /// Behavior when the typed text does not match any option.
112    pub new_item: Property<NewItem>,
113
114    /// Textbox/list background color.
115    pub background: Property<Color>,
116    /// Textbox/list stroke.
117    pub stroke: Property<Stroke>,
118    /// Text style for the textbox and list items.
119    pub style: Property<TextStyle>,
120    /// Textbox corner radius, in pixels.
121    pub corner_radius: Property<f64>,
122
123    // Private filtered list backing the generated dropdown.
124    pub _filtered_options: LocalProperty<Vec<ListItemData>>,
125    // Private visibility flag for the generated dropdown.
126    pub _options_visible: Property<bool>,
127
128    // Private listener used to mirror `selected` into `text`.
129    pub _selected_listener: LocalProperty<bool>,
130}
131
132/// Behavior when typed combo-box text does not match an existing option.
133#[pax]
134#[engine_import_path("pax_engine")]
135pub enum NewItem {
136    /// Show a disabled "No Results Found" row. This is the default.
137    #[default]
138    Disallow,
139    /// Allow unmatched text without showing a no-results row. Initial free text
140    /// is preserved when `selected` is `None`; this does not commit a new item.
141    AllowInvalid,
142    /// Show custom text when there are no matches; clicking or tapping the row
143    /// triggers `@new_item`. The application must add/select the item itself.
144    Text(String),
145}
146
147const ZERO_WIDTH_SPACE: &str = "\u{200B}";
148
149struct SelectedIndProp(Property<Option<usize>>);
150impl Store for SelectedIndProp {}
151
152impl ComboBox {
153    // Binds filtered options and selected-text synchronization.
154    pub fn on_mount(&mut self, ctx: &NodeContext) {
155        ctx.provide_store(SelectedIndProp(self.selected.clone()))
156            .expect("ComboBox is mounting");
157        self.bind_listeners();
158    }
159
160    fn bind_listeners(&mut self) {
161        let options = self.options.local();
162        let text = self.text.local();
163        let new_item = self.new_item.local();
164        let deps = [options.untyped(), text.untyped(), new_item.untyped()];
165        self._filtered_options.replace_with(LocalProperty::computed(
166            move || {
167                let options = options.get();
168                let text = text.get();
169                let text = text.as_str();
170                {
171                    let mut options_sorted: Vec<(usize, &String)> =
172                        options.iter().enumerate().collect();
173                    options_sorted.sort_by_key(|&(_, v)| v);
174                    let mut filtered_options: Vec<_> = options_sorted
175                        .into_iter()
176                        .filter(|(_, t)| t.contains(text))
177                        .map(|(i, v)| ListItemData {
178                            key: i,
179                            text: v.clone(),
180                            event: ComboBoxItemClickEvent::SelectIndex(i),
181                        })
182                        .collect();
183                    filtered_options.sort_by_key(|v| !v.text.starts_with(text));
184                    if filtered_options.is_empty() {
185                        match new_item.get() {
186                            NewItem::Disallow => filtered_options.push(ListItemData {
187                                key: options.len(),
188                                text: String::from("No Results Found"),
189                                event: ComboBoxItemClickEvent::None,
190                            }),
191                            NewItem::Text(text) => filtered_options.push(ListItemData {
192                                key: options.len(),
193                                text,
194                                event: ComboBoxItemClickEvent::NewItem,
195                            }),
196                            NewItem::AllowInvalid => (),
197                        }
198                    }
199                    filtered_options
200                }
201            },
202            &deps,
203        ));
204        let text = self.text.local();
205        let options = self.options.local();
206        let options_visible = self._options_visible.local();
207        let new_item_behavior = self.new_item.local();
208
209        let selected = self.selected.local();
210        // Changing the no-match policy must not reset an in-progress query.
211        let deps = [selected.untyped(), options.untyped()];
212
213        let last = Rc::new(Cell::new(None));
214        self._selected_listener
215            .replace_with(LocalProperty::computed(
216                move || {
217                    // Remove the rows before changing their filter source, so descendants
218                    // cannot evaluate bindings to indices removed by selection.
219                    options_visible.set(false);
220                    let requested = selected.get();
221                    let selected_value = options
222                        .read(|options| requested.and_then(|index| options.get(index).cloned()));
223                    let current = requested.filter(|_| selected_value.is_some());
224                    if current != requested {
225                        selected.set(current);
226                    }
227                    let new_value = selected_value.unwrap_or_default();
228                    if current.is_some()
229                        || requested.is_some()
230                        || last.get().is_some()
231                        || !matches!(new_item_behavior.get(), NewItem::AllowInvalid)
232                    {
233                        text.set(new_value);
234                    }
235                    last.set(current);
236                    true
237                },
238                &deps,
239            ));
240    }
241
242    // Opens the option list.
243    pub fn on_click(&mut self, ctx: &NodeContext, _event: Event<Click>) {
244        self._options_visible.set(true);
245    }
246
247    // Clears the current selected item.
248    pub fn remove_index(&mut self, ctx: &NodeContext, event: Event<Click>) {
249        self.selected.set(None);
250        self.text.set("".to_string());
251    }
252
253    // Forces selected-text synchronization during pre-render.
254    pub fn update(&mut self, ctx: &NodeContext) {
255        self._selected_listener.get();
256    }
257
258    // Emits the combo box's `new_item` event.
259    pub fn dispatch_new_item(&mut self, ctx: &NodeContext) {
260        ctx.dispatch_event("new_item").unwrap();
261    }
262}
263
264// Internal list row used by `ComboBox`.
265#[pax]
266#[engine_import_path("pax_engine")]
267#[inlined(
268    <Text x=3px text={data.text} width={100%-3px} height=100% style=style/>
269    <Rectangle fill=background/>
270
271    @settings {
272        @click: on_click
273    }
274)]
275pub struct ComboBoxListItem {
276    // Row payload.
277    pub data: Property<ListItemData>,
278    // Row background color.
279    pub background: Property<Color>,
280    // Row text style.
281    pub style: Property<TextStyle>,
282}
283
284impl ComboBoxListItem {
285    // Applies this row's action to the parent combo box.
286    pub fn on_click(&mut self, ctx: &NodeContext, _event: Event<Click>) {
287        match self.data.get().event {
288            ComboBoxItemClickEvent::None => (),
289            ComboBoxItemClickEvent::SelectIndex(index) => {
290                let _ = ctx.with_store(|SelectedIndProp(selected): &mut SelectedIndProp| {
291                    selected.set(Some(index));
292                });
293            }
294            ComboBoxItemClickEvent::NewItem => {
295                ctx.dispatch_event("new_item");
296            }
297        }
298    }
299}
300
301// Internal row payload used by `ComboBoxListItem`.
302#[pax]
303#[engine_import_path("pax_engine")]
304pub struct ListItemData {
305    // Source index keeps filtered/reordered rows attached to their own payload.
306    pub key: usize,
307    // Row label shown in the dropdown.
308    pub text: String,
309    // Action dispatched when this row is selected.
310    pub event: ComboBoxItemClickEvent,
311}
312
313// Internal row action for `ComboBoxListItem`.
314#[pax]
315#[engine_import_path("pax_engine")]
316pub enum ComboBoxItemClickEvent {
317    // Disabled row.
318    #[default]
319    None,
320    // Selects an existing option index.
321    SelectIndex(usize),
322    // Dispatches `new_item`.
323    NewItem,
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    fn combo(options: &[&str]) -> ComboBox {
331        let mut combo = ComboBox::default();
332        combo
333            .options
334            .set(options.iter().map(|s| s.to_string()).collect());
335        combo.bind_listeners();
336        combo._selected_listener.get();
337        combo
338    }
339
340    #[test]
341    fn filtering_preserves_source_indices_and_ranks_prefixes_first() {
342        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
343        let _entered = graph.enter();
344        let combo = combo(&["zBeta", "Beta", "Alpha"]);
345        combo.text.set("Beta".into());
346        let rows = {
347            graph.import();
348            combo._filtered_options.get()
349        };
350        assert_eq!(
351            rows.iter().map(|row| row.text.as_str()).collect::<Vec<_>>(),
352            vec!["Beta", "zBeta"]
353        );
354        assert!(matches!(
355            rows[0].event,
356            ComboBoxItemClickEvent::SelectIndex(1)
357        ));
358        assert!(matches!(
359            rows[1].event,
360            ComboBoxItemClickEvent::SelectIndex(0)
361        ));
362        assert_eq!(
363            rows.iter().map(|row| row.key).collect::<Vec<_>>(),
364            vec![1, 0]
365        );
366    }
367
368    #[test]
369    fn selection_closes_the_list_and_options_changes_update_the_label() {
370        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
371        let _entered = graph.enter();
372        let combo = combo(&["Alpha", "Beta"]);
373        combo._options_visible.set(true);
374        combo.selected.set(Some(1));
375        {
376            graph.import();
377            combo._selected_listener.get()
378        };
379        assert_eq!(combo.text.get(), "Beta");
380        assert!(!combo._options_visible.get());
381        combo.options.set(vec!["Alpha".into(), "Renamed".into()]);
382        {
383            graph.import();
384            combo._selected_listener.get()
385        };
386        assert_eq!(combo.text.get(), "Renamed");
387    }
388
389    #[test]
390    fn missing_and_out_of_range_selections_clear_without_panicking() {
391        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
392        let _entered = graph.enter();
393        let combo = combo(&["Alpha", "Beta"]);
394        for index in [2, usize::MAX] {
395            combo.selected.set(Some(index));
396            {
397                graph.import();
398                combo._selected_listener.get()
399            };
400            assert_eq!(combo.selected.get(), None);
401            assert_eq!(combo.text.get(), "");
402        }
403        combo.selected.set(Some(1));
404        {
405            graph.import();
406            combo._selected_listener.get()
407        };
408        combo.options.set(Vec::new());
409        {
410            graph.import();
411            combo._selected_listener.get()
412        };
413        assert_eq!(combo.selected.get(), None);
414        assert_eq!(combo.text.get(), "");
415    }
416
417    #[test]
418    fn changing_no_match_behavior_refreshes_existing_filter() {
419        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
420        let _entered = graph.enter();
421        let combo = combo(&["Alpha"]);
422        combo.text.set("missing".into());
423        assert!(matches!(
424            {
425                graph.import();
426                combo._filtered_options.get()
427            }[0]
428            .event,
429            ComboBoxItemClickEvent::None
430        ));
431        combo.new_item.set(NewItem::Text("Create missing".into()));
432        {
433            graph.import();
434            combo._selected_listener.get()
435        };
436        assert_eq!(combo.text.get(), "missing");
437        let rows = {
438            graph.import();
439            combo._filtered_options.get()
440        };
441        assert_eq!(rows[0].text, "Create missing");
442        assert!(matches!(rows[0].event, ComboBoxItemClickEvent::NewItem));
443        combo.new_item.set(NewItem::AllowInvalid);
444        {
445            graph.import();
446            combo._selected_listener.get()
447        };
448        assert_eq!(combo.text.get(), "missing");
449        assert!({
450            graph.import();
451            combo._filtered_options.get()
452        }
453        .is_empty());
454    }
455
456    #[test]
457    fn duplicate_labels_keep_distinct_option_keys() {
458        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
459        let _entered = graph.enter();
460        let combo = combo(&["Same", "Same"]);
461        let rows = {
462            graph.import();
463            combo._filtered_options.get()
464        };
465        assert_eq!(
466            rows.iter().map(|row| row.key).collect::<Vec<_>>(),
467            vec![0, 1]
468        );
469        combo.text.set("missing".into());
470        assert_eq!(
471            {
472                graph.import();
473                combo._filtered_options.get()
474            }[0]
475            .key,
476            2
477        );
478    }
479
480    #[test]
481    fn allow_invalid_preserves_free_text_but_mirrors_committed_labels() {
482        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
483        let _entered = graph.enter();
484        let mut combo = ComboBox::default();
485        combo.options.set(vec!["Alpha".into()]);
486        combo.new_item.set(NewItem::AllowInvalid);
487        combo.text.set("Free text".into());
488        combo.bind_listeners();
489        {
490            graph.import();
491            combo._selected_listener.get()
492        };
493        assert_eq!(combo.text.get(), "Free text");
494        combo.selected.set(Some(0));
495        {
496            graph.import();
497            combo._selected_listener.get()
498        };
499        assert_eq!(combo.text.get(), "Alpha");
500        combo.options.set(vec!["Renamed".into()]);
501        {
502            graph.import();
503            combo._selected_listener.get()
504        };
505        assert_eq!(combo.text.get(), "Renamed");
506        combo.options.set(vec![]);
507        {
508            graph.import();
509            combo._selected_listener.get()
510        };
511        assert_eq!(combo.selected.get(), None);
512        assert_eq!(combo.text.get(), "");
513    }
514}