Skip to main content

lumen_dioxus/inputs/
segmented.rs

1//! `Segmented`: a compact single-choice control.
2//!
3//! lumen-react renders each option as a visually hidden native radio inside a label. Blitz (Dioxus
4//! Native) paints native radios itself, has no arrow-key navigation, and cannot keep a controlled
5//! radio unchecked, so each option here is a `<button role="radio" class="ui-segmented__input">`
6//! inside the same label, in a `role="radiogroup"` container. A hidden input submits the selection.
7
8use std::collections::HashMap;
9use std::rc::Rc;
10
11use dioxus::prelude::*;
12
13use super::radio_group::radio_key_target;
14use super::select_option::SelectOption;
15use crate::ControlSize;
16use crate::class::compose;
17use crate::hooks::{Controllable, use_controllable};
18use crate::overlay::focus_element;
19
20/// Props for [`Segmented`].
21#[derive(Props, Clone, PartialEq)]
22pub struct SegmentedProps {
23    /// Controlled selected value. Leave unset to let the control manage its selection.
24    #[props(into)]
25    pub value: Option<String>,
26    /// Initially selected value when uncontrolled.
27    #[props(into)]
28    pub default_value: Option<String>,
29    /// Called with the value the user selects.
30    pub on_value_change: Option<EventHandler<String>>,
31    /// The choices, in order.
32    #[props(default)]
33    pub options: Vec<SelectOption>,
34    /// Form field name of the hidden input that submits the selection. Defaults to `segmented`,
35    /// like lumen-react.
36    #[props(default = "segmented".to_string(), into)]
37    pub name: String,
38    /// Control size.
39    #[props(default)]
40    pub visual_size: ControlSize,
41    /// Extra classes appended after the Lumen classes.
42    #[props(into)]
43    pub class: Option<String>,
44    /// Any other `<div>` or global attribute. Name the control with `aria_label`.
45    #[props(extends = GlobalAttributes, extends = div)]
46    pub attributes: Vec<Attribute>,
47    /// Extra content after the options.
48    pub children: Element,
49}
50
51/// Requests `value`: stores it while uncontrolled and reports it when it differs from the current
52/// selection.
53fn choose(
54    state: Controllable<Option<String>>,
55    on_change: Option<EventHandler<String>>,
56    value: &str,
57) {
58    if state.peek().as_deref() == Some(value) {
59        return;
60    }
61
62    state.set(Some(value.to_string()));
63
64    if let Some(handler) = on_change {
65        handler.call(value.to_string());
66    }
67}
68
69/// The option that holds the Tab stop: the selected enabled option, or the first enabled one.
70fn tab_stop(options: &[SelectOption], selected: Option<&str>) -> Option<usize> {
71    options
72        .iter()
73        .position(|option| !option.disabled && Some(option.value.as_str()) == selected)
74        .or_else(|| options.iter().position(|option| !option.disabled))
75}
76
77/// A row of mutually exclusive options, like a radio group drawn as a segmented button.
78///
79/// Click an option to select it; arrow keys move the selection (wrapping and skipping disabled
80/// options) and Space selects the focused option, on every renderer.
81#[component]
82pub fn Segmented(props: SegmentedProps) -> Element {
83    let state = use_controllable(
84        props.value.clone().map(Some),
85        || props.default_value.clone(),
86        None,
87    );
88    let mut active = use_hook(|| CopyValue::new(None::<usize>));
89    let mut mounted = use_hook(|| CopyValue::new(HashMap::<usize, Rc<MountedData>>::new()));
90    let selected = state.get();
91    let on_change = props.on_value_change;
92    let options: Rc<[SelectOption]> = props.options.clone().into();
93    let stop = tab_stop(&options, selected.as_deref());
94    let size_class = match props.visual_size {
95        ControlSize::Default => None,
96        ControlSize::Sm => Some("ui-segmented--sm"),
97        ControlSize::Lg => Some("ui-segmented--lg"),
98    };
99    let class = compose([Some("ui-segmented"), size_class, props.class.as_deref()]);
100    let submitted = selected.clone();
101
102    let options_view = options.iter().enumerate().map(|(index, option)| {
103        let checked = selected.as_deref() == Some(option.value.as_str());
104        let disabled = option.disabled;
105        let click_value = option.value.clone();
106        let key_options = Rc::clone(&options);
107
108        rsx! {
109            label {
110                key: "{option.value}",
111                class: "ui-segmented__option",
112                onclick: move |event| {
113                    // The option handles the click itself, so the browser must not forward it to
114                    // the radio a second time.
115                    event.prevent_default();
116
117                    if disabled {
118                        return;
119                    }
120
121                    active.set(Some(index));
122                    choose(state, on_change, &click_value);
123                    focus_element(mounted.peek().get(&index).cloned());
124                },
125                button {
126                    aria_checked: if checked { "true" } else { "false" },
127                    class: "ui-segmented__input",
128                    disabled,
129                    role: "radio",
130                    tabindex: if stop == Some(index) { "0" } else { "-1" },
131                    r#type: "button",
132                    value: option.value.clone(),
133                    onkeydown: move |event| {
134                        let enabled: Vec<usize> = key_options
135                            .iter()
136                            .enumerate()
137                            .filter(|(_, option)| !option.disabled)
138                            .map(|(position, _)| position)
139                            .collect();
140                        let from = active
141                            .peek()
142                            .filter(|current| enabled.contains(current))
143                            .unwrap_or(index);
144                        let current = enabled.iter().position(|position| *position == from);
145
146                        let Some(target) = radio_key_target(&event.key(), current, enabled.len())
147                        else {
148                            return;
149                        };
150
151                        event.prevent_default();
152
153                        let Some(next) = enabled.get(target).copied() else {
154                            return;
155                        };
156
157                        active.set(Some(next));
158                        choose(state, on_change, &key_options[next].value);
159                        focus_element(mounted.peek().get(&next).cloned());
160                    },
161                    onfocus: move |_| active.set(Some(index)),
162                    onmounted: move |event| {
163                        mounted.write().insert(index, event.data());
164                    },
165                }
166                span { class: "ui-segmented__label", "{option.label}" }
167            }
168        }
169    });
170
171    rsx! {
172        div { class, role: "radiogroup", ..props.attributes,
173            {options_view}
174            {props.children}
175            if let Some(value) = submitted {
176                input { r#type: "hidden", name: props.name, value }
177            }
178        }
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::{SelectOption, tab_stop};
185
186    fn options() -> Vec<SelectOption> {
187        vec![
188            SelectOption::new("day", "Day").disabled(true),
189            SelectOption::new("week", "Week"),
190            SelectOption::new("month", "Month"),
191        ]
192    }
193
194    #[test]
195    fn the_selected_enabled_option_holds_the_tab_stop() {
196        assert_eq!(tab_stop(&options(), Some("month")), Some(2));
197    }
198
199    #[test]
200    fn the_first_enabled_option_holds_the_tab_stop_without_a_usable_selection() {
201        assert_eq!(tab_stop(&options(), None), Some(1));
202        assert_eq!(tab_stop(&options(), Some("day")), Some(1));
203        assert_eq!(tab_stop(&options(), Some("missing")), Some(1));
204        assert_eq!(tab_stop(&[], None), None);
205    }
206}