pax-std 0.39.1

Standard library for Pax, including layouts, drawing primitives, and form controls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
#![allow(unused)]
use pax_engine::api::LocalProperty;
use std::cell::Cell;
use std::rc::Rc;

use crate::{EventBlocker, Group, Path, Rectangle, Scroller, Stacker, Text};
use crate::{TextStyle, Textbox};
use pax_engine::api::{Click, Event, Store, Stroke};
use pax_engine::api::{Color, Property};
use pax_engine::*;
use pax_runtime::api::NodeContext;

/// A text-filtered list control for selecting one item, with optional "new item" behavior.
///
/// Clicking or tapping the input opens the list. Filtering is case-sensitive,
/// with prefix matches first and alphabetical order within each group. Selecting
/// a row commits its index in `options`, copies its label to `text`, and closes
/// the list. Editing or blurring the input does not commit a selection or clear
/// the previous one. Bind `text` for the query and `selected` for the last choice.
///
/// This composed control uses a native Textbox and Pax list rows. It does not
/// implement arrow-key/Enter list selection or a complete accessible combobox
/// contract.
#[pax]
#[engine_import_path("pax_engine")]
#[inlined(
    if _options_visible {
        <Scroller
            anchor_y=0%
            y={100%+1px}
            height=500%
            width={100% + 8px}
            x=1px
            scroll_height={(Math::len(self._filtered_options)*100/5)%}
    		unclippable=true
        >
            <Stacker gutter=1px height={(Math::len(self._filtered_options)*100/5)%}>
                for option_data in self._filtered_options key option_data.key {
                    <ComboBoxListItem style=style background=background data={option_data} @new_item=self.dispatch_new_item/>
                }
            </Stacker>
            <Rectangle fill={stroke.paint} height={(Math::len(self._filtered_options)*100/5)%}/>
        </Scroller>
    }
    if self.text != "" && self.selected != None && !_options_visible {
        <Group  @click=self.remove_index x=100% width=30px>
            <EventBlocker/>
            <Path class="x_symbol" x=50% y=50% width=15px height=15px/>
        </Group>
    }
    <Textbox
        @click=on_click
        text=bind:text
        style=style
        background=background
        stroke=stroke
        corner_radius=corner_radius
    />

    @settings {
        @mount: on_mount
        @pre_render: update

    .x_symbol {
        elements: {[
            PathElement::Point(0%, 10%),
            PathElement::Line,
            PathElement::Point(50% - 10%, 50%),
            PathElement::Line,
            PathElement::Point(0%, 100% - 10%),
            PathElement::Line,
            PathElement::Point(10%, 100%),
            PathElement::Line,
            PathElement::Point(50%, 50% + 10%),
            PathElement::Line,
            PathElement::Point(100% - 10%, 100%),
            PathElement::Line,
            PathElement::Point(100%, 100% - 10%),
            PathElement::Line,
            PathElement::Point(50% + 10%, 50%),
            PathElement::Line,
            PathElement::Point(100%, 10%),
            PathElement::Line,
            PathElement::Point(100% - 10%, 0%),
            PathElement::Line,
            PathElement::Point(50%, 50% - 10%),
            PathElement::Line,
            PathElement::Point(10%, 0%),
            PathElement::Close
        ]},
        stroke: {
            paint: TRANSPARENT,
            width: 0
        },
        fill: rgb(200, 200, 200)
    }
}

)]
pub struct ComboBox {
    /// Text currently shown in the input.
    pub text: Property<String>,
    /// Index of the last selected option, or `None`. Editing `text` filters the
    /// list; clicking a row commits its original index in `options`.
    pub selected: Property<Option<usize>>,
    /// Available option labels; duplicate labels retain distinct indices.
    /// Changing this list refreshes the selected label at the existing index.
    /// An out-of-range selection becomes `None` and clears the text. Reordering
    /// options does not preserve an application's item identity automatically.
    pub options: Property<Vec<String>>,
    /// Behavior when the typed text does not match any option.
    pub new_item: Property<NewItem>,

    /// Textbox/list background color.
    pub background: Property<Color>,
    /// Textbox/list stroke.
    pub stroke: Property<Stroke>,
    /// Text style for the textbox and list items.
    pub style: Property<TextStyle>,
    /// Textbox corner radius, in pixels.
    pub corner_radius: Property<f64>,

    // Private filtered list backing the generated dropdown.
    pub _filtered_options: LocalProperty<Vec<ListItemData>>,
    // Private visibility flag for the generated dropdown.
    pub _options_visible: Property<bool>,

    // Private listener used to mirror `selected` into `text`.
    pub _selected_listener: LocalProperty<bool>,
}

/// Behavior when typed combo-box text does not match an existing option.
#[pax]
#[engine_import_path("pax_engine")]
pub enum NewItem {
    /// Show a disabled "No Results Found" row. This is the default.
    #[default]
    Disallow,
    /// Allow unmatched text without showing a no-results row. Initial free text
    /// is preserved when `selected` is `None`; this does not commit a new item.
    AllowInvalid,
    /// Show custom text when there are no matches; clicking or tapping the row
    /// triggers `@new_item`. The application must add/select the item itself.
    Text(String),
}

const ZERO_WIDTH_SPACE: &str = "\u{200B}";

struct SelectedIndProp(Property<Option<usize>>);
impl Store for SelectedIndProp {}

impl ComboBox {
    // Binds filtered options and selected-text synchronization.
    pub fn on_mount(&mut self, ctx: &NodeContext) {
        ctx.provide_store(SelectedIndProp(self.selected.clone()))
            .expect("ComboBox is mounting");
        self.bind_listeners();
    }

    fn bind_listeners(&mut self) {
        let options = self.options.local();
        let text = self.text.local();
        let new_item = self.new_item.local();
        let deps = [options.untyped(), text.untyped(), new_item.untyped()];
        self._filtered_options.replace_with(LocalProperty::computed(
            move || {
                let options = options.get();
                let text = text.get();
                let text = text.as_str();
                {
                    let mut options_sorted: Vec<(usize, &String)> =
                        options.iter().enumerate().collect();
                    options_sorted.sort_by_key(|&(_, v)| v);
                    let mut filtered_options: Vec<_> = options_sorted
                        .into_iter()
                        .filter(|(_, t)| t.contains(text))
                        .map(|(i, v)| ListItemData {
                            key: i,
                            text: v.clone(),
                            event: ComboBoxItemClickEvent::SelectIndex(i),
                        })
                        .collect();
                    filtered_options.sort_by_key(|v| !v.text.starts_with(text));
                    if filtered_options.is_empty() {
                        match new_item.get() {
                            NewItem::Disallow => filtered_options.push(ListItemData {
                                key: options.len(),
                                text: String::from("No Results Found"),
                                event: ComboBoxItemClickEvent::None,
                            }),
                            NewItem::Text(text) => filtered_options.push(ListItemData {
                                key: options.len(),
                                text,
                                event: ComboBoxItemClickEvent::NewItem,
                            }),
                            NewItem::AllowInvalid => (),
                        }
                    }
                    filtered_options
                }
            },
            &deps,
        ));
        let text = self.text.local();
        let options = self.options.local();
        let options_visible = self._options_visible.local();
        let new_item_behavior = self.new_item.local();

        let selected = self.selected.local();
        // Changing the no-match policy must not reset an in-progress query.
        let deps = [selected.untyped(), options.untyped()];

        let last = Rc::new(Cell::new(None));
        self._selected_listener
            .replace_with(LocalProperty::computed(
                move || {
                    // Remove the rows before changing their filter source, so descendants
                    // cannot evaluate bindings to indices removed by selection.
                    options_visible.set(false);
                    let requested = selected.get();
                    let selected_value = options
                        .read(|options| requested.and_then(|index| options.get(index).cloned()));
                    let current = requested.filter(|_| selected_value.is_some());
                    if current != requested {
                        selected.set(current);
                    }
                    let new_value = selected_value.unwrap_or_default();
                    if current.is_some()
                        || requested.is_some()
                        || last.get().is_some()
                        || !matches!(new_item_behavior.get(), NewItem::AllowInvalid)
                    {
                        text.set(new_value);
                    }
                    last.set(current);
                    true
                },
                &deps,
            ));
    }

    // Opens the option list.
    pub fn on_click(&mut self, ctx: &NodeContext, _event: Event<Click>) {
        self._options_visible.set(true);
    }

    // Clears the current selected item.
    pub fn remove_index(&mut self, ctx: &NodeContext, event: Event<Click>) {
        self.selected.set(None);
        self.text.set("".to_string());
    }

    // Forces selected-text synchronization during pre-render.
    pub fn update(&mut self, ctx: &NodeContext) {
        self._selected_listener.get();
    }

    // Emits the combo box's `new_item` event.
    pub fn dispatch_new_item(&mut self, ctx: &NodeContext) {
        ctx.dispatch_event("new_item").unwrap();
    }
}

// Internal list row used by `ComboBox`.
#[pax]
#[engine_import_path("pax_engine")]
#[inlined(
    <Text x=3px text={data.text} width={100%-3px} height=100% style=style/>
    <Rectangle fill=background/>

    @settings {
        @click: on_click
    }
)]
pub struct ComboBoxListItem {
    // Row payload.
    pub data: Property<ListItemData>,
    // Row background color.
    pub background: Property<Color>,
    // Row text style.
    pub style: Property<TextStyle>,
}

impl ComboBoxListItem {
    // Applies this row's action to the parent combo box.
    pub fn on_click(&mut self, ctx: &NodeContext, _event: Event<Click>) {
        match self.data.get().event {
            ComboBoxItemClickEvent::None => (),
            ComboBoxItemClickEvent::SelectIndex(index) => {
                let _ = ctx.with_store(|SelectedIndProp(selected): &mut SelectedIndProp| {
                    selected.set(Some(index));
                });
            }
            ComboBoxItemClickEvent::NewItem => {
                ctx.dispatch_event("new_item");
            }
        }
    }
}

// Internal row payload used by `ComboBoxListItem`.
#[pax]
#[engine_import_path("pax_engine")]
pub struct ListItemData {
    // Source index keeps filtered/reordered rows attached to their own payload.
    pub key: usize,
    // Row label shown in the dropdown.
    pub text: String,
    // Action dispatched when this row is selected.
    pub event: ComboBoxItemClickEvent,
}

// Internal row action for `ComboBoxListItem`.
#[pax]
#[engine_import_path("pax_engine")]
pub enum ComboBoxItemClickEvent {
    // Disabled row.
    #[default]
    None,
    // Selects an existing option index.
    SelectIndex(usize),
    // Dispatches `new_item`.
    NewItem,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn combo(options: &[&str]) -> ComboBox {
        let mut combo = ComboBox::default();
        combo
            .options
            .set(options.iter().map(|s| s.to_string()).collect());
        combo.bind_listeners();
        combo._selected_listener.get();
        combo
    }

    #[test]
    fn filtering_preserves_source_indices_and_ranks_prefixes_first() {
        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
        let _entered = graph.enter();
        let combo = combo(&["zBeta", "Beta", "Alpha"]);
        combo.text.set("Beta".into());
        let rows = {
            graph.import();
            combo._filtered_options.get()
        };
        assert_eq!(
            rows.iter().map(|row| row.text.as_str()).collect::<Vec<_>>(),
            vec!["Beta", "zBeta"]
        );
        assert!(matches!(
            rows[0].event,
            ComboBoxItemClickEvent::SelectIndex(1)
        ));
        assert!(matches!(
            rows[1].event,
            ComboBoxItemClickEvent::SelectIndex(0)
        ));
        assert_eq!(
            rows.iter().map(|row| row.key).collect::<Vec<_>>(),
            vec![1, 0]
        );
    }

    #[test]
    fn selection_closes_the_list_and_options_changes_update_the_label() {
        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
        let _entered = graph.enter();
        let combo = combo(&["Alpha", "Beta"]);
        combo._options_visible.set(true);
        combo.selected.set(Some(1));
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.text.get(), "Beta");
        assert!(!combo._options_visible.get());
        combo.options.set(vec!["Alpha".into(), "Renamed".into()]);
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.text.get(), "Renamed");
    }

    #[test]
    fn missing_and_out_of_range_selections_clear_without_panicking() {
        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
        let _entered = graph.enter();
        let combo = combo(&["Alpha", "Beta"]);
        for index in [2, usize::MAX] {
            combo.selected.set(Some(index));
            {
                graph.import();
                combo._selected_listener.get()
            };
            assert_eq!(combo.selected.get(), None);
            assert_eq!(combo.text.get(), "");
        }
        combo.selected.set(Some(1));
        {
            graph.import();
            combo._selected_listener.get()
        };
        combo.options.set(Vec::new());
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.selected.get(), None);
        assert_eq!(combo.text.get(), "");
    }

    #[test]
    fn changing_no_match_behavior_refreshes_existing_filter() {
        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
        let _entered = graph.enter();
        let combo = combo(&["Alpha"]);
        combo.text.set("missing".into());
        assert!(matches!(
            {
                graph.import();
                combo._filtered_options.get()
            }[0]
            .event,
            ComboBoxItemClickEvent::None
        ));
        combo.new_item.set(NewItem::Text("Create missing".into()));
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.text.get(), "missing");
        let rows = {
            graph.import();
            combo._filtered_options.get()
        };
        assert_eq!(rows[0].text, "Create missing");
        assert!(matches!(rows[0].event, ComboBoxItemClickEvent::NewItem));
        combo.new_item.set(NewItem::AllowInvalid);
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.text.get(), "missing");
        assert!({
            graph.import();
            combo._filtered_options.get()
        }
        .is_empty());
    }

    #[test]
    fn duplicate_labels_keep_distinct_option_keys() {
        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
        let _entered = graph.enter();
        let combo = combo(&["Same", "Same"]);
        let rows = {
            graph.import();
            combo._filtered_options.get()
        };
        assert_eq!(
            rows.iter().map(|row| row.key).collect::<Vec<_>>(),
            vec![0, 1]
        );
        combo.text.set("missing".into());
        assert_eq!(
            {
                graph.import();
                combo._filtered_options.get()
            }[0]
            .key,
            2
        );
    }

    #[test]
    fn allow_invalid_preserves_free_text_but_mirrors_committed_labels() {
        let graph = pax_engine::api::properties::PropertyGraph::new(|| {});
        let _entered = graph.enter();
        let mut combo = ComboBox::default();
        combo.options.set(vec!["Alpha".into()]);
        combo.new_item.set(NewItem::AllowInvalid);
        combo.text.set("Free text".into());
        combo.bind_listeners();
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.text.get(), "Free text");
        combo.selected.set(Some(0));
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.text.get(), "Alpha");
        combo.options.set(vec!["Renamed".into()]);
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.text.get(), "Renamed");
        combo.options.set(vec![]);
        {
            graph.import();
            combo._selected_listener.get()
        };
        assert_eq!(combo.selected.get(), None);
        assert_eq!(combo.text.get(), "");
    }
}