Skip to main content

pax_std/forms/
combo_box.rs

1#![allow(unused)]
2use std::cell::Cell;
3use std::rc::Rc;
4
5use crate::{EventBlocker, Group, Path, Rectangle, Scroller, Stacker, Text};
6use crate::{TextStyle, Textbox};
7use pax_engine::api::{Click, Event, MouseDown, Store, Stroke, TextboxChange};
8use pax_engine::api::{Color, Property};
9use pax_engine::*;
10use pax_runtime::api::NodeContext;
11
12/// A text-filtered list control for selecting one item, with optional "new item" behavior.
13#[pax]
14#[engine_import_path("pax_engine")]
15#[inlined(
16    if _options_visible {
17        <Scroller
18            anchor_y=0%
19            y={100%+1px}
20            height=500%
21            width={100% + 8px}
22            x=1px
23            scroll_height={(Math::len(self._filtered_options)*100/5)%}
24    		unclippable=true
25        >
26            <Stacker gutter=1px>
27                for option_data in self._filtered_options {
28                    <ComboBoxListItem style=style background=background data={option_data} @new_item=self.dispatch_new_item/>
29                }
30            </Stacker>
31            <Rectangle fill={stroke.color}/>
32        </Scroller>
33    }
34    if self.text != "" && self.selected != None && !_options_visible {
35        <Group  @click=self.remove_index x=100% width=30px>
36            <EventBlocker/>
37            <Path class="x_symbol" x=50% y=50% width=15px height=15px/>
38        </Group>
39    }
40    <Textbox
41        @click=on_click
42        text=bind:text
43        style=style
44        background=background
45        stroke=stroke
46        corner_radius=corner_radius
47        @textbox_change=self.textbox_change
48    />
49
50    @settings {
51        @mount: on_mount
52        @pre_render: update
53
54    .x_symbol {
55        elements: {[
56            PathElement::Point(0%, 10%),
57            PathElement::Line,
58            PathElement::Point(50% - 10%, 50%),
59            PathElement::Line,
60            PathElement::Point(0%, 100% - 10%),
61            PathElement::Line,
62            PathElement::Point(10%, 100%),
63            PathElement::Line,
64            PathElement::Point(50%, 50% + 10%),
65            PathElement::Line,
66            PathElement::Point(100% - 10%, 100%),
67            PathElement::Line,
68            PathElement::Point(100%, 100% - 10%),
69            PathElement::Line,
70            PathElement::Point(50% + 10%, 50%),
71            PathElement::Line,
72            PathElement::Point(100%, 10%),
73            PathElement::Line,
74            PathElement::Point(100% - 10%, 0%),
75            PathElement::Line,
76            PathElement::Point(50%, 50% - 10%),
77            PathElement::Line,
78            PathElement::Point(10%, 0%),
79            PathElement::Close
80        ]},
81        stroke: {
82            width: 0
83        },
84        fill: rgb(200, 200, 200)
85    }
86}
87
88)]
89pub struct ComboBox {
90    /// Text currently shown in the input.
91    pub text: Property<String>,
92    /// Selected option index, or `None` when there is no valid selection.
93    pub selected: Property<Option<usize>>,
94    /// Available option labels.
95    pub options: Property<Vec<String>>,
96    /// Behavior when the typed text does not match any option.
97    pub new_item: Property<NewItem>,
98
99    /// Textbox/list background color.
100    pub background: Property<Color>,
101    /// Textbox/list stroke.
102    pub stroke: Property<Stroke>,
103    /// Text style for the textbox and list items.
104    pub style: Property<TextStyle>,
105    /// Textbox corner radius, in pixels.
106    pub corner_radius: Property<f64>,
107
108    // Private filtered list backing the generated dropdown.
109    pub _filtered_options: Property<Vec<ListItemData>>,
110    // Private visibility flag for the generated dropdown.
111    pub _options_visible: Property<bool>,
112
113    // Private listener used to mirror `selected` into `text`.
114    pub _selected_listener: Property<bool>,
115}
116
117/// Behavior when typed combo-box text does not match an existing option.
118#[pax]
119#[engine_import_path("pax_engine")]
120pub enum NewItem {
121    /// Show "No items found" and do not allow adding a new item.
122    #[default]
123    Disallow,
124    /// Allows invalid text in the text box on commit, setting `selected` to `None`.
125    AllowInvalid,
126    /// Shows custom text when there are no matches; clicking it triggers the `@new_item` event.
127    Text(String),
128}
129
130const ZERO_WIDTH_SPACE: &str = "\u{200B}";
131
132struct SelectedIndProp(Property<Option<usize>>);
133impl Store for SelectedIndProp {}
134
135impl ComboBox {
136    // Binds filtered options and selected-text synchronization.
137    pub fn on_mount(&mut self, ctx: &NodeContext) {
138        ctx.push_local_store(SelectedIndProp(self.selected.clone()));
139        let options = self.options.clone();
140        let text = self.text.clone();
141        let deps = [options.untyped(), text.untyped()];
142        let new_item = self.new_item.clone();
143        self._filtered_options.replace_with(Property::computed(
144            move || {
145                options.read(|options| {
146                    text.read(|text| {
147                        let mut options_sorted: Vec<(usize, &String)> =
148                            options.iter().enumerate().collect();
149                        options_sorted.sort_by_key(|&(_, v)| v);
150                        let mut filtered_options: Vec<_> = options_sorted
151                            .into_iter()
152                            .filter(|(_, t)| t.contains(text))
153                            .map(|(i, v)| ListItemData {
154                                text: v.clone(),
155                                event: ComboBoxItemClickEvent::SelectIndex(i),
156                            })
157                            .collect();
158                        filtered_options.sort_by_key(|v| v.text.starts_with(text));
159                        if filtered_options.is_empty() {
160                            match new_item.get() {
161                                NewItem::Disallow => filtered_options.push(ListItemData {
162                                    text: String::from("No Results Found"),
163                                    event: ComboBoxItemClickEvent::None,
164                                }),
165                                NewItem::Text(text) => filtered_options.push(ListItemData {
166                                    text,
167                                    event: ComboBoxItemClickEvent::NewItem,
168                                }),
169                                NewItem::AllowInvalid => (),
170                            }
171                        }
172                        filtered_options
173                    })
174                })
175            },
176            &deps,
177        ));
178        let text = self.text.clone();
179        let options = self.options.clone();
180        let options_visible = self._options_visible.clone();
181        let new_item_behavior = self.new_item.clone();
182
183        let selected = self.selected.clone();
184        let deps = [selected.untyped()];
185
186        let last = Rc::new(Cell::new(None));
187        self._selected_listener.replace_with(Property::computed(
188            move || {
189                let selected = selected.get();
190                let new_value = if let Some(selected) = selected {
191                    options.read(|options| {
192                        let index = selected.clamp(0, options.len());
193                        options[index].clone()
194                    })
195                } else {
196                    "".to_string()
197                };
198                match new_item_behavior.get() {
199                    NewItem::AllowInvalid => {
200                        if last.get() != selected || text.get().is_empty() {
201                            text.set(new_value)
202                        }
203                    }
204                    _ => text.set(new_value),
205                }
206                options_visible.set(false);
207                last.set(selected);
208                true
209            },
210            &deps,
211        ));
212    }
213
214    // Opens the option list.
215    pub fn on_click(&mut self, ctx: &NodeContext, _event: Event<Click>) {
216        self._options_visible.set(true);
217    }
218
219    // Revalidates the current selection after textbox edits.
220    pub fn textbox_change(&mut self, ctx: &NodeContext, _event: Event<TextboxChange>) {
221        self.selected.set(self.selected.get());
222    }
223
224    // Clears the current selected item.
225    pub fn remove_index(&mut self, ctx: &NodeContext, event: Event<Click>) {
226        self.selected.set(None);
227        self.text.set("".to_string());
228    }
229
230    // Forces selected-text synchronization during pre-render.
231    pub fn update(&mut self, ctx: &NodeContext) {
232        self._selected_listener.get();
233    }
234
235    // Emits the combo box's `new_item` event.
236    pub fn dispatch_new_item(&mut self, ctx: &NodeContext) {
237        ctx.dispatch_event("new_item").unwrap();
238    }
239}
240
241// Internal list row used by `ComboBox`.
242#[pax]
243#[engine_import_path("pax_engine")]
244#[inlined(
245    <Text x=3px text={data.text} width={100%-3px} height=100% style=style/>
246    <Rectangle fill=background/>
247
248    @settings {
249        @mouse_down: on_click
250    }
251)]
252pub struct ComboBoxListItem {
253    // Row payload.
254    pub data: Property<ListItemData>,
255    // Row background color.
256    pub background: Property<Color>,
257    // Row text style.
258    pub style: Property<TextStyle>,
259}
260
261impl ComboBoxListItem {
262    // Applies this row's action to the parent combo box.
263    pub fn on_click(&mut self, ctx: &NodeContext, _event: Event<MouseDown>) {
264        match self.data.get().event {
265            ComboBoxItemClickEvent::None => (),
266            ComboBoxItemClickEvent::SelectIndex(index) => {
267                let _ = ctx.peek_local_store(|SelectedIndProp(selected): &mut SelectedIndProp| {
268                    selected.set(Some(index));
269                });
270            }
271            ComboBoxItemClickEvent::NewItem => {
272                ctx.dispatch_event("new_item");
273            }
274        }
275    }
276}
277
278// Internal row payload used by `ComboBoxListItem`.
279#[pax]
280#[engine_import_path("pax_engine")]
281pub struct ListItemData {
282    // Row label shown in the dropdown.
283    pub text: String,
284    // Action dispatched when this row is selected.
285    pub event: ComboBoxItemClickEvent,
286}
287
288// Internal row action for `ComboBoxListItem`.
289#[pax]
290#[engine_import_path("pax_engine")]
291pub enum ComboBoxItemClickEvent {
292    // Disabled row.
293    #[default]
294    None,
295    // Selects an existing option index.
296    SelectIndex(usize),
297    // Dispatches `new_item`.
298    NewItem,
299}