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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
//! `Select`: Lumen's default styled option list, backed by a hidden native `<select>`.

// cspell:words focusin focusout onfocusin onfocusout onmousedown

use std::rc::Rc;
use std::time::Duration;

use dioxus::prelude::*;

use super::select_keyboard::{Typeahead, extend_typeahead, is_space, printable_key};
use crate::class::{Glass, compose};
use crate::hooks::use_unique_id;
use crate::overlay::{DismissLayer, focus_element};
use crate::{ControlSize, SelectOption};

/// Trigger text while nothing is selected and no placeholder is set.
const DEFAULT_TRIGGER_TEXT: &str = "Select an option";
/// Listbox text when there are no options and no `empty_message` is set.
const DEFAULT_EMPTY_MESSAGE: &str = "No options available";
/// Lumen's web runtime skips roots that carry `data-ui-owner`; it only checks that the attribute
/// exists. lumen-react's value keeps the markup identical.
const OWNER: &str = "react";
/// How long a `focusout` waits for a `focusin` inside the select before it closes the list. Dioxus
/// focus events carry no `relatedTarget`, so the move is detected by the event that follows.
const FOCUS_EXIT_DELAY: Duration = Duration::from_millis(30);

/// Props for [`Select`].
#[derive(Props, Clone, PartialEq)]
pub struct SelectProps {
    /// The choices, in order. A first option with an empty value is the placeholder choice: it
    /// stays selectable and takes `placeholder` as its label when its own label is empty.
    #[props(default)]
    pub options: Vec<SelectOption>,
    /// Controlled value. Leave unset to let the select manage itself.
    #[props(into)]
    pub value: Option<String>,
    /// Initial value when uncontrolled. Defaults to no selection.
    #[props(default, into)]
    pub default_value: String,
    /// Called with the option value every time the person picks an option.
    pub on_value_change: Option<EventHandler<String>>,
    /// Trigger text while nothing is selected. Defaults to "Select an option".
    #[props(into)]
    pub placeholder: Option<String>,
    /// Listbox text when there are no options. Defaults to "No options available".
    #[props(into)]
    pub empty_message: Option<String>,
    /// Disables the trigger and the native control.
    #[props(default)]
    pub disabled: bool,
    /// Marks the value as required for form validation.
    #[props(default)]
    pub required: bool,
    /// Id of the native control. The trigger is `{id}-trigger` and the listbox `{id}-listbox`.
    /// Generated when unset.
    #[props(into)]
    pub id: Option<String>,
    /// Form field name. When set, a hidden input submits the selected value.
    #[props(into)]
    pub name: Option<String>,
    /// Id of the form that owns the field when it is outside that form.
    #[props(into)]
    pub form: Option<String>,
    /// Trigger height.
    #[props(default)]
    pub visual_size: ControlSize,
    /// Glass intensity of the field and its listbox.
    #[props(default, into)]
    pub glass: Glass,
    /// Accessible name of the trigger and its listbox.
    #[props(into)]
    pub aria_label: Option<String>,
    /// Id of the element that names the trigger and its listbox.
    #[props(into)]
    pub aria_labelledby: Option<String>,
    /// Ids of elements that describe the trigger.
    #[props(into)]
    pub aria_describedby: Option<String>,
    /// `aria-invalid` of the trigger, such as `"true"`.
    #[props(into)]
    pub aria_invalid: Option<String>,
    /// Id of the error message of the trigger.
    #[props(into)]
    pub aria_errormessage: Option<String>,
    /// Extra classes appended to the field after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<select>` or global attribute. They go to the hidden native control, like the
    /// rest props of lumen-react's `Select`.
    #[props(extends = GlobalAttributes, extends = select)]
    pub attributes: Vec<Attribute>,
}

/// Options after the placeholder choice takes the `placeholder` text, like lumen-react's
/// `useSelectSourceOptions` for the `options` prop.
fn source_options(options: &[SelectOption], placeholder: Option<&str>) -> Vec<SelectOption> {
    let mut source = options.to_vec();

    if let (Some(first), Some(placeholder)) = (source.first_mut(), placeholder)
        && first.value.is_empty()
        && first.label.is_empty()
        && !placeholder.is_empty()
    {
        first.label = placeholder.to_string();
    }

    source
}

/// One of the keys that move between options.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SelectNavKey {
    /// `ArrowDown`: the next option, looping.
    Down,
    /// `ArrowUp`: the previous option, looping.
    Up,
    /// `Home`: the first option.
    Home,
    /// `End`: the last option.
    End,
}

impl SelectNavKey {
    fn from_key(key: &Key) -> Option<Self> {
        match key {
            Key::ArrowDown => Some(Self::Down),
            Key::ArrowUp => Some(Self::Up),
            Key::Home => Some(Self::Home),
            Key::End => Some(Self::End),
            _ => None,
        }
    }
}

/// Indexes of the options that can take focus.
fn enabled_indexes(options: &[SelectOption]) -> Vec<usize> {
    options
        .iter()
        .enumerate()
        .filter(|(_, option)| !option.disabled)
        .map(|(index, _)| index)
        .collect()
}

/// Position in `items` of the option navigation starts from: `current`, then the selected enabled
/// option, then the first enabled one. Like `indexOf`, a missing `current` counts as the first.
fn start_position(
    options: &[SelectOption],
    items: &[usize],
    selected: &str,
    current: Option<usize>,
) -> Option<usize> {
    let selected_item = items
        .iter()
        .copied()
        .find(|index| options[*index].value == selected);
    let current = current
        .or(selected_item)
        .or_else(|| items.first().copied())?;

    items.iter().position(|index| *index == current)
}

/// The option a navigation key focuses, like lumen-react's `focusOption`.
pub(crate) fn select_step(
    options: &[SelectOption],
    selected: &str,
    current: Option<usize>,
    key: SelectNavKey,
) -> Option<usize> {
    let items = enabled_indexes(options);
    let len = items.len();

    if len == 0 {
        return None;
    }

    let position = start_position(options, &items, selected, current).unwrap_or(0);
    let next = match key {
        SelectNavKey::Home => 0,
        SelectNavKey::End => len - 1,
        SelectNavKey::Down => (position + 1) % len,
        SelectNavKey::Up => (position + len - 1) % len,
    };

    items.get(next).copied()
}

/// The option Enter or Space focuses when they open the list: the selected enabled option, then
/// the first enabled one.
pub(crate) fn select_open_target(options: &[SelectOption], selected: &str) -> Option<usize> {
    let items = enabled_indexes(options);

    items
        .iter()
        .copied()
        .find(|index| options[*index].value == selected)
        .or_else(|| items.first().copied())
}

/// The option a typeahead query focuses, like lumen-react's `focusTypeaheadOption`: the search
/// starts after the current option and wraps, and compares trimmed lowercase labels.
pub(crate) fn select_typeahead(
    options: &[SelectOption],
    selected: &str,
    current: Option<usize>,
    query: &str,
) -> Option<usize> {
    let items = enabled_indexes(options);

    if items.is_empty() || query.is_empty() {
        return None;
    }

    let start =
        start_position(options, &items, selected, current).map_or(0, |position| position + 1);
    let start = start.min(items.len());

    items[start..]
        .iter()
        .chain(&items[..start])
        .copied()
        .find(|index| {
            options[*index]
                .label
                .trim()
                .to_lowercase()
                .starts_with(query)
        })
}

/// Values the select needs in its event handlers, refreshed on every render.
#[derive(Clone, Default, PartialEq)]
struct SelectSnapshot {
    options: Vec<SelectOption>,
    value: String,
    controlled: bool,
    disabled: bool,
    on_value_change: Option<EventHandler<String>>,
}

/// The open state, focus target, and typeahead of one select. It is `Copy`, so every handler can
/// capture it.
#[derive(Clone, Copy)]
struct SelectMachine {
    snapshot: CopyValue<SelectSnapshot>,
    internal: Signal<String>,
    open: Signal<bool>,
    /// The option keyboard focus is on. Dioxus Native cannot move focus, so keys that reach the
    /// trigger while an option is active act on that option.
    active: Signal<Option<usize>>,
    /// An option to focus once the list is visible.
    pending_focus: Signal<Option<usize>>,
    typeahead: CopyValue<Typeahead>,
    focus_generation: CopyValue<u64>,
    option_nodes: CopyValue<Vec<Option<Rc<MountedData>>>>,
    trigger_node: CopyValue<Option<Rc<MountedData>>>,
}

fn set_if_changed<T: PartialEq + 'static>(mut signal: Signal<T>, next: T) {
    if *signal.peek() != next {
        signal.set(next);
    }
}

impl SelectMachine {
    fn is_open(self) -> bool {
        *self.open.peek()
    }

    fn close(self) {
        set_if_changed(self.open, false);
        set_if_changed(self.active, None);
        set_if_changed(self.pending_focus, None);
    }

    fn reset_typeahead(mut self) {
        self.typeahead.write().reset();
    }

    fn toggle(self) {
        if self.snapshot.peek().disabled {
            return;
        }

        self.reset_typeahead();

        if self.is_open() {
            self.close();
        } else {
            set_if_changed(self.open, true);
        }
    }

    /// Opens the list and focuses `target` once it is visible.
    fn open_and_focus(self, target: Option<usize>) {
        set_if_changed(self.open, true);
        self.focus_option(target);
    }

    fn focus_option(mut self, target: Option<usize>) {
        if let Some(index) = target {
            set_if_changed(self.active, Some(index));
            self.pending_focus.set(Some(index));
        }
    }

    fn focus_trigger(self) {
        focus_element(self.trigger_node.peek().clone());
    }

    fn commit(self, value: String) {
        let (controlled, handler) = {
            let snapshot = self.snapshot.peek();
            (snapshot.controlled, snapshot.on_value_change)
        };

        if !controlled {
            let mut internal = self.internal;
            internal.set(value.clone());
        }

        if let Some(handler) = handler {
            handler.call(value);
        }
    }

    /// Picks an option, closes the list, and returns focus to the trigger.
    fn choose(self, index: usize) {
        let value = {
            let snapshot = self.snapshot.peek();

            match snapshot.options.get(index) {
                Some(option) if !option.disabled && !snapshot.disabled => option.value.clone(),
                _ => return,
            }
        };

        self.commit(value);
        self.close();
        self.focus_trigger();
    }

    /// Printable keys build a query that opens the list and focuses the next matching option.
    fn typeahead_key(self, event: &KeyboardEvent, current: Option<usize>) -> bool {
        let Some(text) = printable_key(event) else {
            return false;
        };

        // Space only extends an active query; otherwise it opens or selects like Enter.
        if text == " " && (self.typeahead.peek().is_empty() || !self.is_open()) {
            return false;
        }

        event.prevent_default();

        let query = extend_typeahead(self.typeahead, &text);
        let target = {
            let snapshot = self.snapshot.peek();
            select_typeahead(&snapshot.options, &snapshot.value, current, &query)
        };

        self.open_and_focus(target);
        true
    }

    fn trigger_key(self, event: &KeyboardEvent) {
        if event.is_composing() {
            return;
        }

        let key = event.key();

        // Tab leaves the select; close it here because Dioxus Native has no focus events.
        if key == Key::Tab {
            if self.is_open() {
                self.reset_typeahead();
                self.close();
            }

            return;
        }

        let active = *self.active.peek();

        if self.is_open()
            && let Some(active) = active
        {
            self.option_key(active, event);
            return;
        }

        if self.typeahead_key(event, None) {
            return;
        }

        if key == Key::Escape && self.is_open() {
            event.prevent_default();
            event.stop_propagation();
            self.close();
            return;
        }

        let nav = SelectNavKey::from_key(&key);

        if nav.is_none() && key != Key::Enter && !is_space(&key) {
            return;
        }

        event.prevent_default();
        self.reset_typeahead();

        let target = {
            let snapshot = self.snapshot.peek();

            match nav {
                Some(nav) => select_step(&snapshot.options, &snapshot.value, None, nav),
                None => select_open_target(&snapshot.options, &snapshot.value),
            }
        };

        self.open_and_focus(target);
    }

    fn option_key(self, index: usize, event: &KeyboardEvent) {
        if event.is_composing() || self.typeahead_key(event, Some(index)) {
            return;
        }

        let key = event.key();

        if key == Key::Escape && self.is_open() {
            event.prevent_default();
            event.stop_propagation();
            self.close();
            self.focus_trigger();
            return;
        }

        if key == Key::Enter || is_space(&key) {
            event.prevent_default();
            self.choose(index);
            return;
        }

        let Some(nav) = SelectNavKey::from_key(&key) else {
            return;
        };

        event.prevent_default();
        self.reset_typeahead();

        let target = {
            let snapshot = self.snapshot.peek();
            select_step(&snapshot.options, &snapshot.value, Some(index), nav)
        };

        self.focus_option(target);
    }

    fn focus_entered(mut self) {
        let next = self.focus_generation.peek().wrapping_add(1);
        self.focus_generation.set(next);
    }

    /// Closes the list when focus leaves the select instead of moving inside it.
    fn focus_left(mut self) {
        let generation = self.focus_generation.peek().wrapping_add(1);
        self.focus_generation.set(generation);

        spawn(async move {
            crate::time::sleep(FOCUS_EXIT_DELAY).await;

            if *self.focus_generation.peek() == generation {
                self.reset_typeahead();
                self.close();
            }
        });
    }

    fn store_option(mut self, index: usize, node: Rc<MountedData>) {
        let mut nodes = self.option_nodes.write();

        if nodes.len() <= index {
            nodes.resize(index + 1, None);
        }

        nodes[index] = Some(node);
    }
}

fn size_class(size: ControlSize) -> Option<&'static str> {
    match size {
        ControlSize::Default => None,
        ControlSize::Sm => Some("ui-select--sm"),
        ControlSize::Lg => Some("ui-select--lg"),
    }
}

/// Lumen's default option list: a `combobox` trigger that opens a `listbox` of options, with
/// keyboard navigation and typeahead, plus a hidden native `<select>` for labels and validation.
///
/// Arrow keys, Home, and End open the list and move between enabled options; Enter and Space
/// pick; Escape closes and returns focus to the trigger; printable keys search option labels.
/// A named select submits its value through a hidden input on every renderer.
#[component]
pub fn Select(props: SelectProps) -> Element {
    let generated = use_unique_id();
    let select_id = props
        .id
        .clone()
        .unwrap_or_else(|| format!("ui-select-{generated}"));
    let list_id = format!("{select_id}-listbox");
    let trigger_id = format!("{select_id}-trigger");

    let internal = use_signal(|| props.default_value.clone());
    let value = props.value.clone().unwrap_or_else(|| internal.cloned());
    let options = source_options(&props.options, props.placeholder.as_deref());
    let has_placeholder_option = props
        .options
        .first()
        .is_some_and(|option| option.value.is_empty());
    let selected = options.iter().find(|option| option.value == value);
    let has_selection = selected.is_some() && !value.is_empty();
    let trigger_text = selected
        .map(|option| option.label.clone())
        .or_else(|| props.placeholder.clone())
        .unwrap_or_else(|| DEFAULT_TRIGGER_TEXT.to_string());
    // The native value stays empty while nothing matches, so forms never submit an option the
    // person did not choose and `required` reports a missing value.
    let native_value = if selected.is_some() {
        value.clone()
    } else {
        String::new()
    };
    let submitted = props
        .name
        .clone()
        .filter(|_| !props.disabled && selected.is_some_and(|option| !option.disabled));
    let placeholder = props.placeholder.clone().filter(|text| !text.is_empty());
    let unmatched = selected.is_none();

    let mut snapshot = use_hook(|| CopyValue::new(SelectSnapshot::default()));
    snapshot.set(SelectSnapshot {
        options: options.clone(),
        value: value.clone(),
        controlled: props.value.is_some(),
        disabled: props.disabled,
        on_value_change: props.on_value_change,
    });

    let machine = SelectMachine {
        snapshot,
        internal,
        open: use_signal(|| false),
        active: use_signal(|| None),
        pending_focus: use_signal(|| None),
        typeahead: use_hook(|| CopyValue::new(Typeahead::default())),
        focus_generation: use_hook(|| CopyValue::new(0)),
        option_nodes: use_hook(|| CopyValue::new(Vec::new())),
        trigger_node: use_hook(|| CopyValue::new(None)),
    };

    // Options are hidden until the open render is applied, so focus moves after it.
    use_effect(move || {
        let Some(index) = *machine.pending_focus.read() else {
            return;
        };

        if !*machine.open.read() {
            return;
        }

        let node = machine.option_nodes.peek().get(index).cloned().flatten();
        focus_element(node);

        let mut pending = machine.pending_focus;
        pending.set(None);
    });

    let open = *machine.open.read();
    let active = *machine.active.read();
    let sizes = size_class(props.visual_size);
    let glass = props.glass.class("ui-select-field");
    let class = compose([
        Some("ui-select-field"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);
    let native_class = compose([Some("ui-select ui-select__native"), sizes]);
    let trigger_class = compose([Some("ui-select ui-select__trigger"), sizes]);
    let empty_message = props
        .empty_message
        .clone()
        .unwrap_or_else(|| DEFAULT_EMPTY_MESSAGE.to_string());

    rsx! {
        div {
            class,
            "data-placeholder": if has_selection { "false" } else { "true" },
            "data-ui-select": "true",
            "data-ui-owner": OWNER,
            "data-ui-glass-track": (props.glass != Glass::Off).then_some("true"),
            onfocusin: move |_| machine.focus_entered(),
            onfocusout: move |_| machine.focus_left(),
            select {
                aria_describedby: props.aria_describedby.clone(),
                aria_errormessage: props.aria_errormessage.clone(),
                aria_hidden: "true",
                aria_invalid: props.aria_invalid.clone(),
                aria_label: props.aria_label.clone(),
                aria_labelledby: props.aria_labelledby.clone(),
                class: native_class,
                "data-ui-enhanced": "true",
                "data-ui-select-native": "true",
                disabled: props.disabled,
                form: props.form.clone(),
                id: select_id,
                required: props.required,
                tabindex: "-1",
                // Labels and validation focus the hidden control; show focus on the trigger.
                onfocus: move |_| machine.focus_trigger(),
                onchange: move |event| machine.commit(event.value()),
                ..props.attributes,
                if !has_placeholder_option {
                    if let Some(text) = placeholder.clone() {
                        option {
                            "data-ui-select-placeholder": "true",
                            disabled: true,
                            selected: native_value.is_empty(),
                            value: "",
                            "{text}"
                        }
                    } else if unmatched {
                        option {
                            "data-ui-select-placeholder": "true",
                            disabled: true,
                            hidden: true,
                            selected: native_value.is_empty(),
                            value: "",
                        }
                    }
                }
                for choice in options.iter() {
                    option {
                        disabled: choice.disabled,
                        selected: choice.value == native_value,
                        value: choice.value.clone(),
                        "{choice.label}"
                    }
                }
            }
            if let Some(name) = submitted {
                input {
                    form: props.form.clone(),
                    name,
                    r#type: "hidden",
                    value: native_value.clone(),
                }
            }
            div { class: "ui-select__control", "data-ui-select-control": "true",
                button {
                    aria_controls: list_id.clone(),
                    aria_describedby: props.aria_describedby.clone(),
                    aria_errormessage: props.aria_errormessage.clone(),
                    aria_expanded: if open { "true" } else { "false" },
                    aria_haspopup: "listbox",
                    aria_invalid: props.aria_invalid.clone(),
                    aria_label: props.aria_label.clone(),
                    aria_labelledby: props.aria_labelledby.clone(),
                    aria_required: props.required.then_some("true"),
                    class: trigger_class,
                    "data-ui-select-trigger": "true",
                    disabled: props.disabled,
                    id: trigger_id,
                    role: "combobox",
                    r#type: "button",
                    onclick: move |_| machine.toggle(),
                    onkeydown: move |event| machine.trigger_key(&event),
                    onfocus: move |_| set_if_changed(machine.active, None),
                    onmounted: move |event| {
                        let mut node = machine.trigger_node;
                        node.set(Some(event.data()));
                    },
                    span { "data-ui-select-value": "true", "{trigger_text}" }
                }
                if open {
                    DismissLayer { on_dismiss: move |()| machine.close() }
                }
                div {
                    aria_label: props.aria_label.clone(),
                    aria_labelledby: props.aria_labelledby.clone(),
                    class: "ui-select__list",
                    "data-state": if open { "open" } else { "closed" },
                    "data-ui-select-list": "true",
                    hidden: !open,
                    id: list_id,
                    role: "listbox",
                    // A press keeps focus where it is, so browsers that do not focus buttons on
                    // click (Safari) never close the list through a focus change before the click.
                    onmousedown: move |event| event.prevent_default(),
                    if options.is_empty() {
                        div {
                            aria_disabled: "true",
                            class: "ui-select__empty",
                            "data-ui-select-empty": "true",
                            role: "option",
                            "{empty_message}"
                        }
                    }
                    for (index, choice) in options.iter().enumerate() {
                        button {
                            aria_disabled: choice.disabled.then_some("true"),
                            aria_selected: if choice.value == value { "true" } else { "false" },
                            "data-active": (open && active == Some(index)).then_some("true"),
                            "data-ui-select-option": "true",
                            "data-value": choice.value.clone(),
                            disabled: choice.disabled,
                            role: "option",
                            tabindex: "-1",
                            r#type: "button",
                            onclick: move |_| machine.choose(index),
                            onkeydown: move |event| machine.option_key(index, &event),
                            onmounted: move |event| machine.store_option(index, event.data()),
                            "{choice.label}"
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{SelectNavKey, select_open_target, select_step, select_typeahead, source_options};
    use crate::SelectOption;

    fn plans() -> Vec<SelectOption> {
        vec!["Free".into(), "Pro".into(), "Team".into()]
    }

    #[test]
    fn opening_keys_start_from_the_selected_option() {
        let options = plans();

        // lumen-react's `select-keyboard.test.ts` opening matrix with `defaultValue: 'Pro'`.
        assert_eq!(select_open_target(&options, "Pro"), Some(1));
        assert_eq!(
            select_step(&options, "Pro", None, SelectNavKey::Down),
            Some(2)
        );
        assert_eq!(
            select_step(&options, "Pro", None, SelectNavKey::Up),
            Some(0)
        );
        assert_eq!(
            select_step(&options, "Pro", None, SelectNavKey::Home),
            Some(0)
        );
        assert_eq!(
            select_step(&options, "Pro", None, SelectNavKey::End),
            Some(2)
        );
        assert_eq!(select_typeahead(&options, "Pro", None, "t"), Some(2));
    }

    #[test]
    fn without_a_selection_navigation_starts_from_the_first_option() {
        let options = plans();

        assert_eq!(select_open_target(&options, ""), Some(0));
        assert_eq!(select_step(&options, "", None, SelectNavKey::Down), Some(1));
        assert_eq!(select_step(&options, "", None, SelectNavKey::Up), Some(2));
    }

    #[test]
    fn navigation_loops_and_skips_disabled_options() {
        let options = vec![
            SelectOption::from("A"),
            SelectOption::new("b", "B").disabled(true),
            SelectOption::from("C"),
        ];

        assert_eq!(
            select_step(&options, "", Some(0), SelectNavKey::Down),
            Some(2)
        );
        assert_eq!(
            select_step(&options, "", Some(2), SelectNavKey::Down),
            Some(0)
        );
        assert_eq!(
            select_step(&options, "", Some(0), SelectNavKey::Up),
            Some(2)
        );
        // A selected disabled option is not a starting point.
        assert_eq!(select_open_target(&options, "b"), Some(0));
        assert_eq!(
            select_step(&options, "b", None, SelectNavKey::Down),
            Some(2)
        );

        let none = vec![SelectOption::new("x", "X").disabled(true)];
        assert_eq!(select_step(&none, "", None, SelectNavKey::Down), None);
        assert_eq!(select_open_target(&none, ""), None);
        assert_eq!(select_typeahead(&none, "", None, "x"), None);
    }

    #[test]
    fn typeahead_searches_after_the_current_option_and_wraps() {
        let options: Vec<SelectOption> =
            vec!["New Haven".into(), "New York".into(), "Newark".into()];

        // The query sequence of lumen-react's "Space continues an active typeahead query" test.
        let first = select_typeahead(&options, "", None, "n");
        assert_eq!(first, Some(1));
        let second = select_typeahead(&options, "", first, "ne");
        assert_eq!(second, Some(2));
        let third = select_typeahead(&options, "", second, "new");
        assert_eq!(third, Some(0));
        let fourth = select_typeahead(&options, "", third, "new ");
        assert_eq!(fourth, Some(1));
        assert_eq!(select_typeahead(&options, "", fourth, "new y"), Some(1));
        assert_eq!(select_typeahead(&options, "", None, ""), None);
        assert_eq!(select_typeahead(&options, "", None, "zz"), None);
    }

    #[test]
    fn typeahead_compares_trimmed_lowercase_labels() {
        let options = vec![
            SelectOption::new("a", "  Éclair "),
            SelectOption::new("b", "Beta"),
        ];

        assert_eq!(select_typeahead(&options, "b", None, "éc"), Some(0));
    }

    #[test]
    fn typeahead_handles_long_queries_and_many_options_linearly() {
        let options: Vec<SelectOption> = (0..5_000)
            .map(|index| format!("Option {index}").into())
            .collect();
        let query = "o".repeat(10_000);

        assert_eq!(select_typeahead(&options, "", None, &query), None);
        assert_eq!(
            select_typeahead(&options, "", None, "option 4999"),
            Some(4_999)
        );
    }

    #[test]
    fn the_placeholder_choice_takes_the_placeholder_text() {
        let options = vec![SelectOption::new("", ""), "Lima".into()];

        assert_eq!(
            source_options(&options, Some("Pick a city"))[0].label,
            "Pick a city"
        );
        assert_eq!(source_options(&options, Some(""))[0].label, "");
        assert_eq!(source_options(&options, None)[0].label, "");

        let labelled = vec![SelectOption::new("", "Any city"), "Lima".into()];
        assert_eq!(
            source_options(&labelled, Some("Pick a city"))[0].label,
            "Any city"
        );
    }
}