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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! `ListBox`: an always-visible single or multiple selection list.

// cspell:words multiselectable oninvalid optgroup rposition

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

use dioxus::prelude::*;

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

const DEFAULT_EMPTY_MESSAGE: &str = "No options available";
const DEFAULT_LOADING_MESSAGE: &str = "Loading options";
/// 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";

/// A labelled run of options in a [`ListBox`], like consecutive lumen-react options that share a
/// `section`.
///
/// ```
/// use lumen_dioxus::{ListBoxGroup, SelectOption};
///
/// let groups = vec![
///     ListBoxGroup::new("Fruit", ["Apple", "Pear"]),
///     ListBoxGroup::ungrouped([SelectOption::new("water", "Water")]),
/// ];
///
/// assert_eq!(groups[0].label.as_deref(), Some("Fruit"));
/// assert_eq!(groups[1].options[0].value, "water");
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct ListBoxGroup {
    /// The section heading. `None` (or an empty label) renders the options without a group.
    pub label: Option<String>,
    /// The options in the group.
    pub options: Vec<SelectOption>,
}

impl ListBoxGroup {
    /// A labelled group.
    pub fn new<T: Into<SelectOption>>(
        label: impl Into<String>,
        options: impl IntoIterator<Item = T>,
    ) -> Self {
        Self {
            label: Some(label.into()),
            options: options.into_iter().map(Into::into).collect(),
        }
    }

    /// Options shown without a section heading.
    pub fn ungrouped<T: Into<SelectOption>>(options: impl IntoIterator<Item = T>) -> Self {
        Self {
            label: None,
            options: options.into_iter().map(Into::into).collect(),
        }
    }
}

/// Props for [`ListBox`].
// The flags mirror lumen-react's boolean `ListBox` props one to one, so the API stays the same
// across Lumen adapters.
#[allow(clippy::struct_excessive_bools)]
#[derive(Props, Clone, PartialEq)]
pub struct ListBoxProps {
    /// Options without a section heading, shown before `groups`.
    #[props(default)]
    pub options: Vec<SelectOption>,
    /// Options under section headings, shown after `options`.
    #[props(default)]
    pub groups: Vec<ListBoxGroup>,
    /// Controlled selected values. Leave unset to let the list manage itself.
    pub value: Option<Vec<String>>,
    /// Initially selected values when uncontrolled.
    #[props(default)]
    pub default_value: Vec<String>,
    /// Called with every selected value after each selection change.
    pub on_value_change: Option<EventHandler<Vec<String>>>,
    /// Lets the person select several options; activating an option toggles it.
    #[props(default)]
    pub multiple: bool,
    /// Selects the active option as the arrow keys, Home, End, or typeahead move it.
    #[props(default)]
    pub selection_follows_focus: bool,
    /// Disables selection and removes the list from the tab order.
    #[props(default)]
    pub disabled: bool,
    /// Shows `loading_message` instead of the options and blocks selection.
    #[props(default)]
    pub loading: bool,
    /// Marks the selection as required for form validation.
    #[props(default)]
    pub required: bool,
    /// Visible label rendered above the list; it names the list.
    #[props(into)]
    pub label: Option<String>,
    /// Text shown when there are no options. Defaults to "No options available".
    #[props(into)]
    pub empty_message: Option<String>,
    /// Status text while `loading`. Defaults to "Loading options".
    #[props(into)]
    pub loading_message: Option<String>,
    /// Id of the native control; option ids are `{id}-option-{index}`. Generated when unset.
    #[props(into)]
    pub id: Option<String>,
    /// Form field name. When set, hidden inputs submit the selected values.
    #[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>,
    /// Accessible name of the list.
    #[props(into)]
    pub aria_label: Option<String>,
    /// Id of the element that names the list. Wins over `aria_label` and `label`.
    #[props(into)]
    pub aria_labelledby: Option<String>,
    /// Ids of elements that describe the list.
    #[props(into)]
    pub aria_describedby: Option<String>,
    /// `aria-invalid` of the list, such as `"true"`.
    #[props(into)]
    pub aria_invalid: Option<String>,
    /// Id of the error message of the list.
    #[props(into)]
    pub aria_errormessage: Option<String>,
    /// Extra classes appended to the root after the Lumen class.
    #[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 `ListBox`.
    #[props(extends = GlobalAttributes, extends = select)]
    pub attributes: Vec<Attribute>,
}

/// One rendered group: its heading and the flat indexes of its options.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ListBoxRun {
    pub(crate) label: Option<String>,
    pub(crate) indexes: Vec<usize>,
}

/// Flattens `options` and `groups` into one option list and the runs to render, merging adjacent
/// runs with the same heading like lumen-react's section grouping.
pub(crate) fn list_box_runs(
    options: &[SelectOption],
    groups: &[ListBoxGroup],
) -> (Vec<SelectOption>, Vec<ListBoxRun>) {
    let mut flat = Vec::new();
    let mut runs: Vec<ListBoxRun> = Vec::new();
    let sources = std::iter::once((None, options)).chain(
        groups
            .iter()
            .map(|group| (group.label.as_deref(), group.options.as_slice())),
    );

    for (label, group_options) in sources {
        let label = label.filter(|text| !text.is_empty());

        for option in group_options {
            let index = flat.len();
            flat.push(option.clone());

            match runs.last_mut() {
                Some(run) if run.label.as_deref() == label => run.indexes.push(index),
                _ => runs.push(ListBoxRun {
                    label: label.map(str::to_string),
                    indexes: vec![index],
                }),
            }
        }
    }

    (flat, runs)
}

/// The id of a group heading, like lumen-react: `{id}-group-{label}:{values}` with every UTF-16
/// code unit outside `[A-Za-z0-9_-]` replaced by `-`.
pub(crate) fn list_box_group_label_id(
    control_id: &str,
    label: &str,
    values: impl IntoIterator<Item = impl AsRef<str>>,
) -> String {
    let mut key = format!("{label}:");

    for (position, value) in values.into_iter().enumerate() {
        if position > 0 {
            key.push('|');
        }

        key.push_str(value.as_ref());
    }

    let mut id = format!("{control_id}-group-");

    for character in key.chars() {
        if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
            id.push(character);
        } else {
            for _ in 0..character.len_utf16() {
                id.push('-');
            }
        }
    }

    id
}

fn is_enabled(options: &[SelectOption], index: usize) -> bool {
    options.get(index).is_some_and(|option| !option.disabled)
}

fn first_enabled(options: &[SelectOption]) -> Option<usize> {
    options.iter().position(|option| !option.disabled)
}

fn last_enabled(options: &[SelectOption]) -> Option<usize> {
    options.iter().rposition(|option| !option.disabled)
}

/// The active option: the remembered one while it exists and is enabled, then the first selected
/// enabled option, then the first enabled one. It never rests on a missing or disabled option.
pub(crate) fn resolve_active(
    options: &[SelectOption],
    active: Option<usize>,
    selected: &[String],
) -> Option<usize> {
    if let Some(index) = active.filter(|index| is_enabled(options, *index)) {
        return Some(index);
    }

    options
        .iter()
        .position(|option| !option.disabled && selected.contains(&option.value))
        .or_else(|| first_enabled(options))
}

/// The next enabled option in `forward` or backward direction from `resolved`, wrapping.
pub(crate) fn move_active(
    options: &[SelectOption],
    resolved: Option<usize>,
    forward: bool,
) -> Option<usize> {
    let len = options.len();
    let mut next = resolved.unwrap_or(0);

    for _ in 0..len {
        next = if forward {
            (next + 1) % len
        } else {
            (next + len - 1) % len
        };

        if !options[next].disabled {
            return Some(next);
        }
    }

    None
}

/// The selection after activating `index`, or `None` when the option is missing or disabled.
pub(crate) fn toggle_selection(
    options: &[SelectOption],
    selected: &[String],
    index: usize,
    multiple: bool,
) -> Option<Vec<String>> {
    let option = options.get(index).filter(|option| !option.disabled)?;

    if !multiple {
        return Some(vec![option.value.clone()]);
    }

    if selected.contains(&option.value) {
        Some(
            selected
                .iter()
                .filter(|value| **value != option.value)
                .cloned()
                .collect(),
        )
    } else {
        let mut next = selected.to_vec();
        next.push(option.value.clone());
        Some(next)
    }
}

/// The first enabled option whose lowercase label starts with `query`.
pub(crate) fn list_box_typeahead(options: &[SelectOption], query: &str) -> Option<usize> {
    options
        .iter()
        .position(|option| !option.disabled && option.label.to_lowercase().starts_with(query))
}

/// The value the hidden native `<select>` holds in single mode.
fn native_single_value(selected: &[String]) -> &str {
    selected.first().map_or("", String::as_str)
}

/// The values a native `<select>` with the same options and selection would submit: enabled
/// selected options in option order, and in single mode the empty choice when nothing matches.
pub(crate) fn list_box_submitted(
    options: &[SelectOption],
    selected: &[String],
    multiple: bool,
) -> Vec<String> {
    if multiple {
        return options
            .iter()
            .filter(|option| !option.disabled && selected.contains(&option.value))
            .map(|option| option.value.clone())
            .collect();
    }

    let value = native_single_value(selected);

    match options.iter().find(|option| option.value == value) {
        Some(option) if option.disabled => Vec::new(),
        Some(option) => vec![option.value.clone()],
        None => vec![String::new()],
    }
}

/// Whether the native `<select>` satisfies `required`.
fn selection_is_valid(options: &[SelectOption], selected: &[String], multiple: bool) -> bool {
    if multiple {
        options
            .iter()
            .any(|option| selected.contains(&option.value))
    } else {
        let value = native_single_value(selected);
        options.iter().any(|option| option.value == value)
    }
}

thread_local! {
    /// Set while one invalid list already took focus during the current validation pass.
    static INVALID_FOCUS_CLAIMED: Cell<bool> = const { Cell::new(false) };
}

/// Whether activating an option replaces the selection or toggles the option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum ListBoxSelection {
    #[default]
    Single,
    Multiple,
}

/// Values the list needs in its event handlers, refreshed on every render.
#[derive(Clone, Default, PartialEq)]
struct ListBoxSnapshot {
    options: Vec<SelectOption>,
    selected: Vec<String>,
    selection: ListBoxSelection,
    controlled: bool,
    unavailable: bool,
    follows_focus: bool,
    on_value_change: Option<EventHandler<Vec<String>>>,
}

#[derive(Clone, Copy)]
struct ListBoxMachine {
    snapshot: CopyValue<ListBoxSnapshot>,
    internal: Signal<Vec<String>>,
    active: Signal<Option<usize>>,
    typeahead: CopyValue<Typeahead>,
    invalid: Signal<bool>,
    list_node: CopyValue<Option<Rc<MountedData>>>,
}

impl ListBoxMachine {
    fn resolved_active(self) -> Option<usize> {
        let snapshot = self.snapshot.peek();
        resolve_active(&snapshot.options, *self.active.peek(), &snapshot.selected)
    }

    fn select(self, index: usize) {
        let (next, controlled, handler) = {
            let snapshot = self.snapshot.peek();

            if snapshot.unavailable {
                return;
            }

            let multiple = snapshot.selection == ListBoxSelection::Multiple;
            let Some(next) =
                toggle_selection(&snapshot.options, &snapshot.selected, index, multiple)
            else {
                return;
            };

            (next, snapshot.controlled, snapshot.on_value_change)
        };

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

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

    fn activate(self, index: Option<usize>) {
        let Some(index) = index else {
            return;
        };

        let mut active = self.active;
        active.set(Some(index));

        if self.snapshot.peek().follows_focus {
            self.select(index);
        }
    }

    fn navigation_key(self, key: &Key) -> bool {
        let options = self.snapshot.peek().options.clone();

        match key {
            Key::ArrowDown | Key::ArrowUp => {
                if !options.is_empty() {
                    let next =
                        move_active(&options, self.resolved_active(), *key == Key::ArrowDown);
                    self.activate(next);
                }
            }
            Key::Home => self.activate(first_enabled(&options)),
            Key::End => self.activate(last_enabled(&options)),
            key if *key == Key::Enter || is_space(key) => {
                if let Some(index) = self.resolved_active() {
                    self.select(index);
                }
            }
            _ => return false,
        }

        true
    }

    fn typeahead_key(self, event: &KeyboardEvent) -> bool {
        let Some(text) = printable_key(event) else {
            return false;
        };

        let query = extend_typeahead(self.typeahead, &text);
        let target = list_box_typeahead(&self.snapshot.peek().options, &query);
        self.activate(target);
        true
    }

    fn keydown(self, event: &KeyboardEvent) {
        if self.snapshot.peek().unavailable || event.is_composing() {
            return;
        }

        if self.navigation_key(&event.key()) || self.typeahead_key(event) {
            event.prevent_default();
        }
    }

    fn click(self, index: usize) {
        let usable = {
            let snapshot = self.snapshot.peek();
            !snapshot.unavailable && is_enabled(&snapshot.options, index)
        };

        if usable {
            let mut active = self.active;
            active.set(Some(index));
            self.select(index);
        }
    }

    /// The hidden native control failed validation: mark the list invalid and focus the first
    /// invalid list of the pass, as lumen-react does.
    fn invalid(self, event: &FormEvent) {
        event.prevent_default();

        let mut invalid = self.invalid;
        invalid.set(true);

        if INVALID_FOCUS_CLAIMED.with(|claimed| claimed.replace(true)) {
            return;
        }

        focus_element(self.list_node.peek().clone());

        // Release the claim after the validation pass, even if this list unmounts first.
        dioxus::core::spawn_forever(async {
            crate::time::sleep(Duration::ZERO).await;
            INVALID_FOCUS_CLAIMED.with(|claimed| claimed.set(false));
        });
    }
}

/// An always-visible list of options with single or multiple selection, following the WAI-ARIA
/// listbox pattern: the list is one focus stop and `aria-activedescendant` marks the active option.
///
/// Arrow keys, Home, and End move the active option past disabled ones; Enter and Space select it
/// (toggle in `multiple` mode); printable keys jump to the first matching label. A named list
/// submits its selection through hidden inputs on every renderer.
#[component]
pub fn ListBox(props: ListBoxProps) -> Element {
    let generated = use_unique_id();
    let control_id = props
        .id
        .clone()
        .unwrap_or_else(|| format!("ui-list-box-{generated}"));
    let (options, runs) = list_box_runs(&props.options, &props.groups);
    let internal = use_signal(|| props.default_value.clone());
    let selected = props.value.clone().unwrap_or_else(|| internal.cloned());
    let unavailable = props.disabled || props.loading;
    let multiple = props.multiple;

    let mut snapshot = use_hook(|| CopyValue::new(ListBoxSnapshot::default()));
    snapshot.set(ListBoxSnapshot {
        options: options.clone(),
        selected: selected.clone(),
        selection: if multiple {
            ListBoxSelection::Multiple
        } else {
            ListBoxSelection::Single
        },
        controlled: props.value.is_some(),
        unavailable,
        follows_focus: props.selection_follows_focus,
        on_value_change: props.on_value_change,
    });

    let machine = ListBoxMachine {
        snapshot,
        internal,
        active: use_signal(|| None),
        typeahead: use_hook(|| CopyValue::new(Typeahead::default())),
        invalid: use_signal(|| false),
        list_node: use_hook(|| CopyValue::new(None)),
    };

    // Lumen only clears the invalid state it generated, once the selection satisfies the control.
    let valid = unavailable || !props.required || selection_is_valid(&options, &selected, multiple);
    use_effect(use_reactive((&valid,), move |(valid,)| {
        let mut invalid = machine.invalid;

        if valid && *invalid.peek() {
            invalid.set(false);
        }
    }));

    let resolved = resolve_active(&options, *machine.active.read(), &selected);
    let generated_invalid = *machine.invalid.read() && !valid;
    let aria_invalid = props
        .aria_invalid
        .clone()
        .or_else(|| generated_invalid.then(|| "true".to_string()));
    let label_id = format!("{control_id}-label");
    // An explicit `aria-labelledby` wins, then `aria-label`, then the `label` prop.
    let labelled_by = if props.aria_labelledby.is_some() {
        props.aria_labelledby.clone()
    } else if props.aria_label.is_some() {
        None
    } else {
        props.label.as_ref().map(|_| label_id.clone())
    };
    let active_id = resolved
        .filter(|_| !props.loading)
        .map(|index| format!("{control_id}-option-{index}"));
    let submitted = props
        .name
        .clone()
        .filter(|_| !unavailable)
        .map(|name| (name, list_box_submitted(&options, &selected, multiple)));
    let single_value = native_single_value(&selected).to_string();
    let is_native_selected = |value: &str| {
        if multiple {
            selected.iter().any(|entry| entry == value)
        } else {
            single_value == value
        }
    };
    let class = compose([Some("ui-list-box"), props.class.as_deref()]);
    let empty_message = props
        .empty_message
        .clone()
        .unwrap_or_else(|| DEFAULT_EMPTY_MESSAGE.to_string());
    let loading_message = props
        .loading_message
        .clone()
        .unwrap_or_else(|| DEFAULT_LOADING_MESSAGE.to_string());
    let option_view = |index: usize| {
        let option = &options[index];
        let is_active = resolved == Some(index);

        rsx! {
            div {
                aria_disabled: option.disabled.then_some("true"),
                aria_selected: if selected.contains(&option.value) { "true" } else { "false" },
                class: compose([
                    Some("ui-list-box__option"),
                    is_active.then_some("ui-list-box__option--active"),
                ]),
                "data-active": is_active.then_some("true"),
                "data-ui-list-box-option": "true",
                "data-value": option.value.clone(),
                id: "{control_id}-option-{index}",
                role: "option",
                onclick: move |_| machine.click(index),
                "{option.label}"
            }
        }
    };

    rsx! {
        div {
            class,
            "data-multiple": multiple.then_some("true"),
            "data-ui-list-box": "true",
            "data-ui-owner": OWNER,
            if let Some(text) = props.label.clone() {
                label { class: "ui-label", r#for: control_id.clone(), id: label_id, "{text}" }
            }
            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: "ui-list-box__native",
                "data-ui-enhanced": "true",
                "data-ui-list-box-native": "true",
                disabled: unavailable,
                form: props.form.clone(),
                id: control_id.clone(),
                multiple,
                required: props.required,
                tabindex: "-1",
                // The visible list is the only focus stop; label clicks land here first.
                onfocus: move |_| focus_element(machine.list_node.peek().clone()),
                oninvalid: move |event| machine.invalid(&event),
                ..props.attributes,
                // An empty choice keeps a single selection empty until the person picks an option.
                if !multiple {
                    option { selected: single_value.is_empty(), value: "" }
                }
                for run in runs.iter() {
                    if let Some(heading) = run.label.clone() {
                        optgroup { label: heading,
                            for index in run.indexes.iter().copied() {
                                option {
                                    disabled: options[index].disabled,
                                    selected: is_native_selected(&options[index].value),
                                    value: options[index].value.clone(),
                                    "{options[index].label}"
                                }
                            }
                        }
                    } else {
                        for index in run.indexes.iter().copied() {
                            option {
                                disabled: options[index].disabled,
                                selected: is_native_selected(&options[index].value),
                                value: options[index].value.clone(),
                                "{options[index].label}"
                            }
                        }
                    }
                }
            }
            if let Some((name, values)) = submitted {
                for value in values {
                    input { form: props.form.clone(), name: name.clone(), r#type: "hidden", value }
                }
            }
            div {
                aria_activedescendant: active_id,
                aria_busy: props.loading.then_some("true"),
                aria_describedby: props.aria_describedby.clone(),
                aria_disabled: unavailable.then_some("true"),
                aria_errormessage: props.aria_errormessage.clone(),
                aria_invalid,
                aria_label: props.aria_label.clone(),
                aria_labelledby: labelled_by,
                aria_multiselectable: multiple.then_some("true"),
                aria_required: props.required.then_some("true"),
                class: "ui-list-box__list",
                "data-ui-list-box-list": "true",
                role: "listbox",
                tabindex: (!unavailable).then_some("0"),
                onkeydown: move |event| machine.keydown(&event),
                onmounted: move |event| {
                    let mut node = machine.list_node;
                    node.set(Some(event.data()));
                },
                if !props.loading {
                    if options.is_empty() {
                        div {
                            aria_disabled: "true",
                            class: "ui-list-box__empty",
                            role: "option",
                            "{empty_message}"
                        }
                    }
                    for run in runs.iter() {
                        if let Some(heading) = run.label.as_deref() {
                            div {
                                aria_labelledby: list_box_group_label_id(
                                    &control_id,
                                    heading,
                                    run.indexes.iter().map(|index| options[*index].value.as_str()),
                                ),
                                role: "group",
                                div {
                                    class: "ui-list-box__section",
                                    id: list_box_group_label_id(
                                        &control_id,
                                        heading,
                                        run.indexes.iter().map(|index| options[*index].value.as_str()),
                                    ),
                                    "{heading}"
                                }
                                for index in run.indexes.iter().copied() {
                                    {option_view(index)}
                                }
                            }
                        } else {
                            for index in run.indexes.iter().copied() {
                                {option_view(index)}
                            }
                        }
                    }
                }
            }
            if props.loading {
                p { class: "ui-list-box__status", role: "status", "{loading_message}" }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ListBoxGroup, list_box_group_label_id, list_box_runs, list_box_submitted,
        list_box_typeahead, move_active, resolve_active, selection_is_valid, toggle_selection,
    };
    use crate::SelectOption;

    fn reviewers() -> Vec<SelectOption> {
        vec![
            SelectOption::new("amina", "Amina").disabled(true),
            SelectOption::new("bruno", "Bruno"),
            SelectOption::new("chen", "Chen"),
        ]
    }

    fn strings(values: &[&str]) -> Vec<String> {
        values.iter().map(ToString::to_string).collect()
    }

    #[test]
    fn the_active_option_starts_on_the_selection_and_never_rests_on_disabled_ones() {
        let options = reviewers();

        assert_eq!(resolve_active(&options, None, &strings(&["chen"])), Some(2));
        assert_eq!(resolve_active(&options, None, &[]), Some(1));
        // A remembered disabled or missing option falls back.
        assert_eq!(
            resolve_active(&options, Some(0), &strings(&["chen"])),
            Some(2)
        );
        assert_eq!(resolve_active(&options, Some(9), &[]), Some(1));
        assert_eq!(
            resolve_active(&options, Some(1), &strings(&["chen"])),
            Some(1)
        );

        let disabled: Vec<SelectOption> = options
            .into_iter()
            .map(|option| option.disabled(true))
            .collect();
        assert_eq!(resolve_active(&disabled, None, &strings(&["chen"])), None);
        assert_eq!(resolve_active(&[], None, &[]), None);
    }

    #[test]
    fn arrow_keys_wrap_and_skip_disabled_options() {
        let options = reviewers();

        assert_eq!(move_active(&options, Some(1), true), Some(2));
        assert_eq!(move_active(&options, Some(2), true), Some(1));
        assert_eq!(move_active(&options, Some(1), false), Some(2));
        assert_eq!(move_active(&options, None, true), Some(1));
        assert_eq!(move_active(&[], None, true), None);

        let disabled = vec![SelectOption::new("x", "X").disabled(true)];
        assert_eq!(move_active(&disabled, None, true), None);
    }

    #[test]
    fn activation_replaces_or_toggles_the_selection() {
        let options = reviewers();
        let selected = strings(&["bruno"]);

        assert_eq!(
            toggle_selection(&options, &selected, 2, false),
            Some(strings(&["chen"]))
        );
        assert_eq!(
            toggle_selection(&options, &selected, 1, false),
            Some(strings(&["bruno"]))
        );
        assert_eq!(
            toggle_selection(&options, &selected, 2, true),
            Some(strings(&["bruno", "chen"]))
        );
        assert_eq!(
            toggle_selection(&options, &selected, 1, true),
            Some(Vec::new())
        );
        assert_eq!(toggle_selection(&options, &selected, 0, true), None);
        assert_eq!(toggle_selection(&options, &selected, 7, false), None);
    }

    #[test]
    fn typeahead_finds_the_first_enabled_label_from_the_top() {
        let options = vec![
            SelectOption::new("a", "Apple").disabled(true),
            SelectOption::new("b", "Avocado"),
            SelectOption::new("c", "Banana"),
        ];

        assert_eq!(list_box_typeahead(&options, "a"), Some(1));
        assert_eq!(list_box_typeahead(&options, "ba"), Some(2));
        assert_eq!(list_box_typeahead(&options, "z"), None);

        let many: Vec<SelectOption> = (0..5_000)
            .map(|index| format!("Item {index}").into())
            .collect();
        assert_eq!(list_box_typeahead(&many, &"i".repeat(20_000)), None);
    }

    #[test]
    fn submitted_values_match_a_native_select() {
        let options = reviewers();

        assert_eq!(list_box_submitted(&options, &[], false), strings(&[""]));
        assert_eq!(
            list_box_submitted(&options, &strings(&["chen"]), false),
            strings(&["chen"])
        );
        assert_eq!(
            list_box_submitted(&options, &strings(&["missing"]), false),
            strings(&[""])
        );
        assert_eq!(
            list_box_submitted(&options, &strings(&["amina"]), false),
            strings(&[])
        );
        assert_eq!(
            list_box_submitted(&options, &strings(&["chen", "amina", "bruno"]), true),
            strings(&["bruno", "chen"])
        );
        assert_eq!(list_box_submitted(&options, &[], true), strings(&[]));
    }

    #[test]
    fn required_validity_follows_the_native_select() {
        let options = reviewers();

        assert!(!selection_is_valid(&options, &[], false));
        assert!(!selection_is_valid(&options, &strings(&["missing"]), false));
        assert!(selection_is_valid(&options, &strings(&["bruno"]), false));
        assert!(!selection_is_valid(&options, &[], true));
        assert!(selection_is_valid(&options, &strings(&["chen"]), true));
    }

    #[test]
    fn groups_flatten_in_order_and_merge_adjacent_headings() {
        let (flat, runs) = list_box_runs(
            &[SelectOption::from("Loose")],
            &[
                ListBoxGroup::new("Fruit", ["Apple"]),
                ListBoxGroup::new("Fruit", ["Pear"]),
                ListBoxGroup::new("", ["Water"]),
                ListBoxGroup::ungrouped(["Tea"]),
                ListBoxGroup::new("Empty", Vec::<SelectOption>::new()),
            ],
        );

        let labels: Vec<&str> = flat.iter().map(|option| option.label.as_str()).collect();
        assert_eq!(labels, ["Loose", "Apple", "Pear", "Water", "Tea"]);
        assert_eq!(runs.len(), 3);
        assert_eq!(runs[0].label, None);
        assert_eq!(runs[1].label.as_deref(), Some("Fruit"));
        assert_eq!(runs[1].indexes, [1, 2]);
        assert_eq!(runs[2].label, None);
        assert_eq!(runs[2].indexes, [3, 4]);
    }

    #[test]
    fn group_ids_replace_each_utf16_unit_outside_the_safe_set() {
        assert_eq!(
            list_box_group_label_id("food", "Leafy greens", ["kale"]),
            "food-group-Leafy-greens-kale"
        );
        assert_eq!(
            list_box_group_label_id("food", "Fruits é", ["a b", "c"]),
            "food-group-Fruits---a-b-c"
        );
        assert_eq!(list_box_group_label_id("x", "😀", ["v"]), "x-group----v");

        let long = "é".repeat(50_000);
        assert_eq!(
            list_box_group_label_id("x", &long, ["v"]).len(),
            "x-group-".len() + 50_000 + 2
        );
    }
}