lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `SpeedDial`.
// cspell:words onfocusin onfocusout focusin focusout

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

use dioxus::prelude::*;

use crate::class::compose;
use crate::icons::{Icon, resolve_name};
use crate::overlay::{focus_element, is_escape};
use crate::time::sleep;

/// One action of a [`SpeedDial`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SpeedDialAction {
    /// Accessible name and visible label.
    pub label: String,
    /// Lucide icon name, such as `pencil`. Needs the default `icon-names` feature.
    pub icon: Option<String>,
    /// Value reported to `on_action`. Defaults to the label.
    pub value: Option<String>,
}

impl SpeedDialAction {
    /// An action labelled `label`.
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            ..Self::default()
        }
    }

    /// The same action with a Lucide icon.
    #[must_use]
    pub fn icon(mut self, name: impl Into<String>) -> Self {
        self.icon = Some(name.into());
        self
    }

    /// The same action with a value.
    #[must_use]
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }

    fn resolved_value(&self) -> String {
        self.value.clone().unwrap_or_else(|| self.label.clone())
    }
}

/// Direction a [`SpeedDial`] opens toward.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SpeedDialDirection {
    /// Above the trigger.
    #[default]
    Up,
    /// Below the trigger.
    Down,
    /// To the left of the trigger.
    Left,
    /// To the right of the trigger.
    Right,
}

impl SpeedDialDirection {
    /// The class suffix and `data-direction` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::Left => "left",
            Self::Right => "right",
        }
    }
}

/// The action index a key moves to, like `getSpeedDialNavigationIndex` in lumen-react.
pub(crate) fn speed_dial_index(key: &Key, current: Option<usize>, count: usize) -> Option<usize> {
    if count == 0 {
        return None;
    }

    match key {
        Key::Home => Some(0),
        Key::End => Some(count - 1),
        Key::ArrowDown | Key::ArrowRight => Some(current.map_or(0, |index| (index + 1) % count)),
        Key::ArrowUp | Key::ArrowLeft => {
            Some(current.map_or(count - 1, |index| (index + count - 1) % count))
        }
        _ => None,
    }
}

/// Props for [`SpeedDial`].
#[derive(Props, Clone, PartialEq)]
pub struct SpeedDialProps {
    /// The actions, in order.
    #[props(default)]
    pub actions: Vec<SpeedDialAction>,
    /// Called with the chosen action's value.
    pub on_action: Option<EventHandler<String>>,
    /// Opens the menu on first render.
    #[props(default)]
    pub default_open: bool,
    /// Called when the menu opens or closes.
    pub on_open_change: Option<EventHandler<bool>>,
    /// Direction the actions fan out toward.
    #[props(default)]
    pub direction: SpeedDialDirection,
    /// Accessible name of the trigger and the menu. Defaults to `Actions`.
    #[props(default = "Actions".to_string(), into)]
    pub label: String,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Extra menu content after the actions.
    pub children: Element,
}

/// A floating button that fans out a short menu of related actions.
///
/// The trigger toggles the menu. `ArrowDown` or `ArrowRight` on the trigger opens it and focuses
/// the first action; `ArrowUp` or `ArrowLeft` focuses the last. Inside the menu, arrow keys,
/// `Home`, and `End` move between actions, `Escape` closes it and returns focus to the trigger,
/// and choosing an action or moving focus elsewhere closes it.
#[component]
pub fn SpeedDial(props: SpeedDialProps) -> Element {
    let mut open = use_signal(|| props.default_open);
    let mut trigger = use_signal(|| None::<Rc<MountedData>>);
    let mut items = use_hook(|| CopyValue::new(Vec::<Option<Rc<MountedData>>>::new()));
    let mut focused = use_signal(|| None::<usize>);
    let mut focus_inside = use_signal(|| false);
    let count = props.actions.len();
    let on_open_change = props.on_open_change;
    let on_action = props.on_action;
    let is_open = open();
    let direction = props.direction.as_str();
    let class = compose([
        Some("ui-speed-dial"),
        Some(&format!("ui-speed-dial--{direction}")),
        props.class.as_deref(),
    ]);

    if items.peek().len() != count {
        items.write().resize(count, None);
    }

    let mut set_open = move |next: bool| {
        if *open.peek() != next {
            open.set(next);

            if let Some(handler) = on_open_change {
                handler.call(next);
            }
        }
    };
    let mut focus_action = move |index: usize| {
        set_open(true);

        spawn(async move {
            // Let the menu render open before moving focus into it.
            sleep(Duration::ZERO).await;
            let target = items.peek().get(index).cloned().flatten();
            focused.set(Some(index));
            focus_element(target);
        });
    };

    rsx! {
        div {
            class,
            "data-direction": direction,
            "data-state": if is_open { "open" } else { "closed" },
            "data-ui-bound": "true",
            "data-ui-speed-dial": "true",
            onfocusin: move |_| focus_inside.set(true),
            onfocusout: move |_| {
                focus_inside.set(false);

                spawn(async move {
                    // Focus moving inside the dial fires focusin right after this focusout.
                    sleep(Duration::ZERO).await;

                    if !*focus_inside.peek() {
                        set_open(false);
                    }
                });
            },
            ..props.attributes,
            button {
                aria_expanded: if is_open { "true" } else { "false" },
                aria_haspopup: "menu",
                aria_label: props.label.clone(),
                class: "ui-speed-dial__trigger",
                "data-ui-speed-dial-trigger": "true",
                r#type: "button",
                onclick: move |_| {
                    let next = !*open.peek();
                    set_open(next);
                },
                onkeydown: move |event| {
                    if is_escape(&event) {
                        set_open(false);
                    }

                    match event.key() {
                        Key::ArrowDown | Key::ArrowRight if count > 0 => {
                            event.prevent_default();
                            focus_action(0);
                        }
                        Key::ArrowUp | Key::ArrowLeft if count > 0 => {
                            event.prevent_default();
                            focus_action(count - 1);
                        }
                        _ => {}
                    }
                },
                onmounted: move |event| trigger.set(Some(event.data())),
                span { aria_hidden: "true", class: "ui-speed-dial__icon" }
            }
            menu {
                aria_label: props.label,
                class: "ui-speed-dial__actions",
                "data-ui-speed-dial-actions": "true",
                role: "menu",
                onkeydown: move |event| {
                    if is_escape(&event) {
                        event.prevent_default();
                        set_open(false);
                        focus_element(trigger());
                        return;
                    }

                    if let Some(index) = speed_dial_index(&event.key(), focused(), count) {
                        event.prevent_default();
                        focus_action(index);
                    }
                },
                for (index, action) in props.actions.into_iter().enumerate() {
                    {
                        let value = action.resolved_value();
                        let artwork = resolve_name(action.icon.as_deref());

                        rsx! {
                            li {
                                key: "{value}",
                                role: "presentation",
                                style: "--ui-speed-dial-index:{index}",
                                button {
                                    aria_label: action.label.clone(),
                                    class: "ui-speed-dial__action",
                                    "data-icon": action.icon.clone(),
                                    "data-value": value.clone(),
                                    role: "menuitem",
                                    r#type: "button",
                                    onclick: move |_| {
                                        set_open(false);

                                        if let Some(handler) = on_action {
                                            handler.call(value.clone());
                                        }
                                    },
                                    onfocus: move |_| focused.set(Some(index)),
                                    onmounted: move |event| {
                                        if let Some(slot) = items.write().get_mut(index) {
                                            *slot = Some(event.data());
                                        }
                                    },
                                    if let Some(artwork) = artwork {
                                        Icon { class: "ui-speed-dial__action-icon", icon: artwork }
                                    }
                                    span { class: "ui-speed-dial__action-label", "{action.label}" }
                                }
                            }
                        }
                    }
                }
                {props.children}
            }
        }
    }
}

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

    #[test]
    fn keys_wrap_through_actions() {
        assert_eq!(speed_dial_index(&Key::ArrowDown, Some(2), 3), Some(0));
        assert_eq!(speed_dial_index(&Key::ArrowLeft, Some(0), 3), Some(2));
        assert_eq!(speed_dial_index(&Key::Home, Some(2), 3), Some(0));
        assert_eq!(speed_dial_index(&Key::End, None, 3), Some(2));
        assert_eq!(speed_dial_index(&Key::ArrowDown, None, 3), Some(0));
        assert_eq!(speed_dial_index(&Key::Enter, Some(1), 3), None);
        assert_eq!(speed_dial_index(&Key::ArrowDown, None, 0), None);
    }
}