lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Segmented`: a compact single-choice control.
//!
//! lumen-react renders each option as a visually hidden native radio inside a label. Blitz (Dioxus
//! Native) paints native radios itself, has no arrow-key navigation, and cannot keep a controlled
//! radio unchecked, so each option here is a `<button role="radio" class="ui-segmented__input">`
//! inside the same label, in a `role="radiogroup"` container. A hidden input submits the selection.

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

use dioxus::prelude::*;

use super::radio_group::radio_key_target;
use super::select_option::SelectOption;
use crate::ControlSize;
use crate::class::compose;
use crate::hooks::{Controllable, use_controllable};
use crate::overlay::focus_element;

/// Props for [`Segmented`].
#[derive(Props, Clone, PartialEq)]
pub struct SegmentedProps {
    /// Controlled selected value. Leave unset to let the control manage its selection.
    #[props(into)]
    pub value: Option<String>,
    /// Initially selected value when uncontrolled.
    #[props(into)]
    pub default_value: Option<String>,
    /// Called with the value the user selects.
    pub on_value_change: Option<EventHandler<String>>,
    /// The choices, in order.
    #[props(default)]
    pub options: Vec<SelectOption>,
    /// Form field name of the hidden input that submits the selection. Defaults to `segmented`,
    /// like lumen-react.
    #[props(default = "segmented".to_string(), into)]
    pub name: String,
    /// Control size.
    #[props(default)]
    pub visual_size: ControlSize,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute. Name the control with `aria_label`.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Extra content after the options.
    pub children: Element,
}

/// Requests `value`: stores it while uncontrolled and reports it when it differs from the current
/// selection.
fn choose(
    state: Controllable<Option<String>>,
    on_change: Option<EventHandler<String>>,
    value: &str,
) {
    if state.peek().as_deref() == Some(value) {
        return;
    }

    state.set(Some(value.to_string()));

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

/// The option that holds the Tab stop: the selected enabled option, or the first enabled one.
fn tab_stop(options: &[SelectOption], selected: Option<&str>) -> Option<usize> {
    options
        .iter()
        .position(|option| !option.disabled && Some(option.value.as_str()) == selected)
        .or_else(|| options.iter().position(|option| !option.disabled))
}

/// A row of mutually exclusive options, like a radio group drawn as a segmented button.
///
/// Click an option to select it; arrow keys move the selection (wrapping and skipping disabled
/// options) and Space selects the focused option, on every renderer.
#[component]
pub fn Segmented(props: SegmentedProps) -> Element {
    let state = use_controllable(
        props.value.clone().map(Some),
        || props.default_value.clone(),
        None,
    );
    let mut active = use_hook(|| CopyValue::new(None::<usize>));
    let mut mounted = use_hook(|| CopyValue::new(HashMap::<usize, Rc<MountedData>>::new()));
    let selected = state.get();
    let on_change = props.on_value_change;
    let options: Rc<[SelectOption]> = props.options.clone().into();
    let stop = tab_stop(&options, selected.as_deref());
    let size_class = match props.visual_size {
        ControlSize::Default => None,
        ControlSize::Sm => Some("ui-segmented--sm"),
        ControlSize::Lg => Some("ui-segmented--lg"),
    };
    let class = compose([Some("ui-segmented"), size_class, props.class.as_deref()]);
    let submitted = selected.clone();

    let options_view = options.iter().enumerate().map(|(index, option)| {
        let checked = selected.as_deref() == Some(option.value.as_str());
        let disabled = option.disabled;
        let click_value = option.value.clone();
        let key_options = Rc::clone(&options);

        rsx! {
            label {
                key: "{option.value}",
                class: "ui-segmented__option",
                onclick: move |event| {
                    // The option handles the click itself, so the browser must not forward it to
                    // the radio a second time.
                    event.prevent_default();

                    if disabled {
                        return;
                    }

                    active.set(Some(index));
                    choose(state, on_change, &click_value);
                    focus_element(mounted.peek().get(&index).cloned());
                },
                button {
                    aria_checked: if checked { "true" } else { "false" },
                    class: "ui-segmented__input",
                    disabled,
                    role: "radio",
                    tabindex: if stop == Some(index) { "0" } else { "-1" },
                    r#type: "button",
                    value: option.value.clone(),
                    onkeydown: move |event| {
                        let enabled: Vec<usize> = key_options
                            .iter()
                            .enumerate()
                            .filter(|(_, option)| !option.disabled)
                            .map(|(position, _)| position)
                            .collect();
                        let from = active
                            .peek()
                            .filter(|current| enabled.contains(current))
                            .unwrap_or(index);
                        let current = enabled.iter().position(|position| *position == from);

                        let Some(target) = radio_key_target(&event.key(), current, enabled.len())
                        else {
                            return;
                        };

                        event.prevent_default();

                        let Some(next) = enabled.get(target).copied() else {
                            return;
                        };

                        active.set(Some(next));
                        choose(state, on_change, &key_options[next].value);
                        focus_element(mounted.peek().get(&next).cloned());
                    },
                    onfocus: move |_| active.set(Some(index)),
                    onmounted: move |event| {
                        mounted.write().insert(index, event.data());
                    },
                }
                span { class: "ui-segmented__label", "{option.label}" }
            }
        }
    });

    rsx! {
        div { class, role: "radiogroup", ..props.attributes,
            {options_view}
            {props.children}
            if let Some(value) = submitted {
                input { r#type: "hidden", name: props.name, value }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{SelectOption, tab_stop};

    fn options() -> Vec<SelectOption> {
        vec![
            SelectOption::new("day", "Day").disabled(true),
            SelectOption::new("week", "Week"),
            SelectOption::new("month", "Month"),
        ]
    }

    #[test]
    fn the_selected_enabled_option_holds_the_tab_stop() {
        assert_eq!(tab_stop(&options(), Some("month")), Some(2));
    }

    #[test]
    fn the_first_enabled_option_holds_the_tab_stop_without_a_usable_selection() {
        assert_eq!(tab_stop(&options(), None), Some(1));
        assert_eq!(tab_stop(&options(), Some("day")), Some(1));
        assert_eq!(tab_stop(&options(), Some("missing")), Some(1));
        assert_eq!(tab_stop(&[], None), None);
    }
}