lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
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
515
516
517
518
519
//! `Combobox`: a text input with a filtered list of suggestions.

// cspell:words feff oncompositionstart oncompositionend onmousedown

use std::collections::HashMap;
use std::rc::Rc;

use dioxus::html::{ScrollBehavior, ScrollLogicalPosition, ScrollToOptions};
use dioxus::prelude::*;

use super::SelectOption;
use crate::class::compose;
use crate::hooks::{Controllable, use_controllable};
use crate::overlay::{DismissLayer, focus_element, wrap_index};

/// Props for [`Combobox`].
#[derive(Props, Clone, PartialEq)]
pub struct ComboboxProps {
    /// Id of the suggestion list. Option ids are `{list}-option-{index}`, and the input id
    /// defaults to `{list}-input`.
    #[props(into)]
    pub list: String,
    /// Visible label above the input. It also names the list.
    #[props(into)]
    pub label: Option<String>,
    /// The suggestions. Typing filters them by label or value, ignoring case and surrounding
    /// whitespace; choosing one puts its value in the input. Disabled options stay visible but
    /// are skipped by the arrow keys and ignore clicks.
    #[props(default)]
    pub options: Vec<SelectOption>,
    /// Controlled text. Leave unset to let the combobox keep its own text.
    #[props(into)]
    pub value: Option<String>,
    /// Initial text when uncontrolled.
    #[props(default, into)]
    pub default_value: String,
    /// Called with the new text on every edit and when an option is chosen.
    pub on_value_change: Option<EventHandler<String>>,
    /// Id of the input. Defaults to `{list}-input`.
    #[props(into)]
    pub id: Option<String>,
    /// The native input type. Defaults to `text`.
    #[props(default = "text".to_string(), into)]
    pub r#type: String,
    /// Disables the input and keeps the list closed.
    #[props(default)]
    pub disabled: bool,
    /// Makes the input read-only and keeps the list closed.
    #[props(default)]
    pub readonly: bool,
    /// Accessible name of the input and the list when there is no visible label.
    #[props(into)]
    pub aria_label: Option<String>,
    /// Id of the element that names the input and the list. Overrides the visible label as the
    /// list's name.
    #[props(into)]
    pub aria_labelledby: Option<String>,
    /// Called on every key press in the input, before the combobox handles it. Call
    /// `prevent_default` to skip the combobox's own handling of that key.
    pub onkeydown: Option<EventHandler<KeyboardEvent>>,
    /// Called when the input gains focus, after the list opens.
    pub onfocus: Option<EventHandler<FocusEvent>>,
    /// Called when the input loses focus, after the list closes.
    pub onblur: Option<EventHandler<FocusEvent>>,
    /// Extra classes appended to the input's `ui-input` class, like lumen-react's `className`.
    #[props(into)]
    pub class: Option<String>,
    /// Extra classes appended to the `ui-combobox` wrapper, like lumen-react's
    /// `wrapperClassName`.
    #[props(into)]
    pub wrapper_class: Option<String>,
    /// Any other `<input>` or global attribute, such as `name`, `placeholder`, or `form`. They go
    /// on the input, like lumen-react.
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// `String.prototype.trim` from JavaScript: Unicode whitespace plus the byte order mark, without
/// the next-line control that Rust's `trim` also removes.
fn js_trim(text: &str) -> &str {
    text.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}')
}

/// The filter query for the typed text: trimmed and lowercase, like lumen-react.
pub(crate) fn combobox_query(text: &str) -> String {
    js_trim(text).to_lowercase()
}

/// Whether an option stays visible for a query from [`combobox_query`]: an empty query keeps
/// every option, otherwise the label or the value must contain the query, ignoring case.
pub(crate) fn combobox_matches(option: &SelectOption, query: &str) -> bool {
    query.is_empty()
        || option.label.to_lowercase().contains(query)
        || option.value.to_lowercase().contains(query)
}

/// The options that stay visible for the typed text, in order.
pub(crate) fn combobox_visible<'a>(
    options: &'a [SelectOption],
    text: &str,
) -> Vec<&'a SelectOption> {
    let query = combobox_query(text);

    options
        .iter()
        .filter(|option| combobox_matches(option, &query))
        .collect()
}

/// Index of the active option among `visible`, or `None` when nothing is active or the active
/// value is no longer visible and enabled.
pub(crate) fn combobox_active_index(
    visible: &[&SelectOption],
    active: Option<&str>,
) -> Option<usize> {
    let active = active?;

    visible
        .iter()
        .position(|option| option.value == active)
        .filter(|index| !visible[*index].disabled)
}

/// The option that `ArrowDown` (`forward`) or `ArrowUp` makes active, skipping disabled options
/// and wrapping at both ends. With no current option, `ArrowDown` starts at the first enabled
/// option and `ArrowUp` at the last, like lumen-react.
pub(crate) fn combobox_step(
    visible: &[&SelectOption],
    current: Option<usize>,
    forward: bool,
) -> Option<usize> {
    let enabled: Vec<usize> = visible
        .iter()
        .enumerate()
        .filter(|(_, option)| !option.disabled)
        .map(|(index, _)| index)
        .collect();
    let position = current.and_then(|index| enabled.iter().position(|entry| *entry == index));

    wrap_index(position, if forward { 1 } else { -1 }, enabled.len()).map(|next| enabled[next])
}

/// Alt, Ctrl, and Meta (Command) shortcuts belong to the platform, not the combobox.
fn has_shortcut_modifier(event: &KeyboardEvent) -> bool {
    let modifiers = event.modifiers();

    modifiers.contains(Modifiers::ALT)
        || modifiers.contains(Modifiers::CONTROL)
        || modifiers.contains(Modifiers::META)
        || modifiers.contains(Modifiers::SUPER)
}

/// State shared by the combobox's event handlers. Every field is `Copy`.
#[derive(Clone, Copy)]
struct ComboboxState {
    value: Controllable<String>,
    open: Signal<bool>,
    active: Signal<Option<String>>,
    composing: Signal<bool>,
    input: Signal<Option<Rc<MountedData>>>,
    locked: bool,
}

impl ComboboxState {
    fn close(mut self) {
        if *self.open.peek() {
            self.open.set(false);
        }

        if self.active.peek().is_some() {
            self.active.set(None);
        }
    }

    fn open_list(mut self) {
        if !self.locked && !*self.open.peek() {
            self.open.set(true);
        }
    }

    fn select(self, option: &SelectOption) {
        if self.locked || option.disabled {
            return;
        }

        self.value.set(option.value.clone());
        focus_element(self.input.peek().clone());
        self.close();
    }
}

/// An editable combobox: a text input with a list of suggestions that filters as you type.
///
/// Focusing, clicking, or typing in the input opens the list. `ArrowDown` and `ArrowUp` open it
/// and move the active option (wrapping, skipping disabled options) while focus stays in the
/// input; `Enter` chooses the active option, `Escape` closes the list, and `Tab` or a click
/// outside closes it too. The input keeps `aria-expanded`, `aria-controls`, and
/// `aria-activedescendant` in sync, as in `@santi020k/lumen-react`.
///
/// The input submits its text with a form when you pass `name`. The open list renders in place,
/// without the `popover` attribute, after a [`DismissLayer`] that closes it on an outside click.
#[component]
pub fn Combobox(props: ComboboxProps) -> Element {
    let value = use_controllable(
        props.value.clone(),
        || props.default_value.clone(),
        props.on_value_change,
    );
    let open = use_signal(|| false);
    let active = use_signal(|| None::<String>);
    let composing = use_signal(|| false);
    let input = use_signal(|| None::<Rc<MountedData>>);
    let mut option_nodes = use_signal(HashMap::<usize, Rc<MountedData>>::new);
    let locked = props.disabled || props.readonly;
    let state = ComboboxState {
        value,
        open,
        active,
        composing,
        input,
        locked,
    };

    let list = props.list.clone();
    let input_id = props.id.clone().unwrap_or_else(|| format!("{list}-input"));
    let label = props.label.clone().filter(|label| !label.is_empty());
    let current = value.get();
    let visible = combobox_visible(&props.options, &current);
    let expanded = *open.read() && !locked;
    let active_index = combobox_active_index(&visible, active.read().as_deref());
    // The active option only counts while the list is open, like lumen-react's `activeId`.
    let selected = active_index.filter(|_| expanded);
    let active_id = selected.map(|index| format!("{list}-option-{index}"));
    let list_labelledby = props
        .aria_labelledby
        .clone()
        .or_else(|| label.as_ref().map(|_| format!("{input_id}-label")));

    // Keep the active option scrolled into view (web and desktop; Native has no element handles).
    use_effect(use_reactive((&selected,), move |(target,)| {
        let Some(node) = target.and_then(|index| option_nodes.peek().get(&index).cloned()) else {
            return;
        };

        spawn(async move {
            let _ = node
                .scroll_to_with_options(ScrollToOptions {
                    behavior: ScrollBehavior::Instant,
                    vertical: ScrollLogicalPosition::Nearest,
                    horizontal: ScrollLogicalPosition::Nearest,
                })
                .await;
        });
    }));

    let options = props.options.clone();
    let user_keydown = props.onkeydown;
    let user_focus = props.onfocus;
    let user_blur = props.onblur;
    let input_class = compose([Some("ui-input"), props.class.as_deref()]);
    let wrapper_class = compose([Some("ui-combobox"), props.wrapper_class.as_deref()]);

    rsx! {
        div { class: wrapper_class, "data-ui-combobox": "true",
            if expanded {
                DismissLayer { on_dismiss: move |()| state.close() }
            }
            if let Some(label) = label {
                label {
                    class: "ui-label",
                    r#for: input_id.clone(),
                    id: "{input_id}-label",
                    "{label}"
                }
            }
            input {
                aria_activedescendant: active_id,
                aria_autocomplete: "list",
                aria_controls: list.clone(),
                aria_expanded: if expanded { "true" } else { "false" },
                aria_label: props.aria_label.clone(),
                aria_labelledby: props.aria_labelledby.clone(),
                class: input_class,
                disabled: props.disabled,
                id: input_id.clone(),
                readonly: props.readonly,
                role: "combobox",
                r#type: props.r#type.clone(),
                value: current,
                oninput: move |event: FormEvent| {
                    let mut active = state.active;
                    let mut open = state.open;

                    state.value.set(event.value());
                    active.set(None);
                    open.set(true);
                },
                onfocus: move |event: FocusEvent| {
                    state.open_list();

                    if let Some(handler) = user_focus {
                        handler.call(event);
                    }
                },
                onclick: move |_| state.open_list(),
                onblur: move |event: FocusEvent| {
                    state.close();

                    if let Some(handler) = user_blur {
                        handler.call(event);
                    }
                },
                oncompositionstart: move |_| {
                    let mut composing = state.composing;
                    composing.set(true);
                },
                oncompositionend: move |_| {
                    let mut composing = state.composing;
                    composing.set(false);
                },
                onkeydown: move |event: KeyboardEvent| {
                    if let Some(handler) = user_keydown {
                        handler.call(event.clone());
                    }

                    if !event.default_action_enabled()
                        || event.is_composing()
                        || *state.composing.peek()
                        || has_shortcut_modifier(&event)
                        || state.locked
                    {
                        return;
                    }

                    let text = state.value.peek();
                    let visible = combobox_visible(&options, &text);
                    let expanded = *state.open.peek();
                    let current = combobox_active_index(&visible, state.active.peek().as_deref())
                        .filter(|_| expanded);

                    match event.key() {
                        Key::Escape => {
                            if !expanded {
                                return;
                            }

                            event.prevent_default();
                            event.stop_propagation();
                            state.close();
                        }
                        Key::ArrowDown | Key::ArrowUp => {
                            event.prevent_default();

                            let forward = event.key() == Key::ArrowDown;
                            let next = combobox_step(&visible, current, forward)
                                .map(|index| visible[index].value.clone());
                            let mut open = state.open;
                            let mut active = state.active;

                            open.set(true);
                            active.set(next);
                        }
                        Key::Enter => {
                            if let Some(index) = current {
                                event.prevent_default();
                                state.select(visible[index]);
                            }
                        }
                        // Dioxus Native has no blur events; leaving with Tab closes the list.
                        Key::Tab => state.close(),
                        _ => {}
                    }
                },
                onmounted: move |event| {
                    let mut input = state.input;
                    input.set(Some(event.data()));
                },
                ..props.attributes,
            }
            div {
                aria_label: props.aria_label.clone(),
                aria_labelledby: list_labelledby,
                class: "ui-combobox__list",
                hidden: !expanded,
                id: list.clone(),
                role: "listbox",
                for (index, option) in visible.into_iter().enumerate() {
                    button {
                        key: "{index}",
                        aria_disabled: option.disabled.then_some("true"),
                        aria_selected: if selected == Some(index) { "true" } else { "false" },
                        "data-ui-combobox-option": "true",
                        "data-value": option.value.clone(),
                        disabled: option.disabled,
                        id: "{list}-option-{index}",
                        role: "option",
                        tabindex: "-1",
                        r#type: "button",
                        onclick: {
                            let option = option.clone();
                            move |event: MouseEvent| {
                                // Keeps focus in the input on Dioxus Native, which would otherwise
                                // clear it after a click on a button.
                                event.prevent_default();
                                state.select(&option);
                            }
                        },
                        onmousedown: move |event: MouseEvent| event.prevent_default(),
                        onmounted: move |event| {
                            option_nodes.write().insert(index, event.data());
                        },
                        "{option.label}"
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        SelectOption, combobox_active_index, combobox_matches, combobox_query, combobox_step,
        combobox_visible, js_trim,
    };

    fn options() -> Vec<SelectOption> {
        vec![
            "Astro".into(),
            SelectOption::new("react", "React"),
            SelectOption::new("wc", "Web Components").disabled(true),
            "Svelte".into(),
        ]
    }

    #[test]
    fn the_query_is_trimmed_and_lowercase() {
        assert_eq!(combobox_query("  ReA \n"), "rea");
        assert_eq!(combobox_query("\u{feff}Astro\u{a0}"), "astro");
        assert_eq!(js_trim("\u{85}a"), "\u{85}a");
        assert_eq!(combobox_query(""), "");
    }

    #[test]
    fn options_match_by_label_or_value() {
        let option = SelectOption::new("wc", "Web Components");

        assert!(combobox_matches(&option, ""));
        assert!(combobox_matches(&option, "comp"));
        assert!(combobox_matches(&option, "wc"));
        assert!(!combobox_matches(&option, "react"));
    }

    #[test]
    fn visible_options_follow_the_typed_text() {
        let options = options();
        let labels = |text: &str| -> Vec<String> {
            combobox_visible(&options, text)
                .into_iter()
                .map(|option| option.label.clone())
                .collect()
        };

        assert_eq!(labels(""), ["Astro", "React", "Web Components", "Svelte"]);
        assert_eq!(labels(" RE "), ["React"]);
        assert_eq!(labels("e"), ["React", "Web Components", "Svelte"]);
        assert_eq!(labels("zzz"), Vec::<String>::new());
    }

    #[test]
    fn arrow_keys_wrap_and_skip_disabled_options() {
        let options = options();
        let visible = combobox_visible(&options, "");

        assert_eq!(combobox_step(&visible, None, true), Some(0));
        assert_eq!(combobox_step(&visible, None, false), Some(3));
        assert_eq!(combobox_step(&visible, Some(1), true), Some(3));
        assert_eq!(combobox_step(&visible, Some(3), true), Some(0));
        assert_eq!(combobox_step(&visible, Some(3), false), Some(1));
        assert_eq!(combobox_step(&visible, Some(0), false), Some(3));
        assert_eq!(combobox_step(&[], None, true), None);

        let only_disabled = [SelectOption::from("x").disabled(true)];
        let visible: Vec<&SelectOption> = only_disabled.iter().collect();
        assert_eq!(combobox_step(&visible, None, true), None);
    }

    #[test]
    fn the_active_option_must_stay_visible_and_enabled() {
        let options = options();
        let visible = combobox_visible(&options, "");

        assert_eq!(combobox_active_index(&visible, Some("react")), Some(1));
        assert_eq!(combobox_active_index(&visible, Some("wc")), None);
        assert_eq!(combobox_active_index(&visible, Some("gone")), None);
        assert_eq!(combobox_active_index(&visible, None), None);

        let filtered = combobox_visible(&options, "sv");
        assert_eq!(combobox_active_index(&filtered, Some("Svelte")), Some(0));
        assert_eq!(combobox_active_index(&filtered, Some("react")), None);
    }

    #[test]
    fn filtering_long_input_stays_linear() {
        let options: Vec<SelectOption> = (0..200)
            .map(|index| format!("option {index}").into())
            .collect();
        let text = "a".repeat(100_000);

        assert_eq!(
            combobox_visible(&options, &text),
            Vec::<&SelectOption>::new()
        );
        assert_eq!(
            combobox_query(&format!("{}x{}", " ".repeat(50_000), " ".repeat(50_000))),
            "x"
        );
    }
}