Skip to main content

lumen_dioxus/navigation/
speed_dial.rs

1//! `SpeedDial`.
2// cspell:words onfocusin onfocusout focusin focusout
3
4use std::rc::Rc;
5use std::time::Duration;
6
7use dioxus::prelude::*;
8
9use crate::class::compose;
10use crate::icons::{Icon, resolve_name};
11use crate::overlay::{focus_element, is_escape};
12use crate::time::sleep;
13
14/// One action of a [`SpeedDial`].
15#[derive(Clone, Debug, Default, PartialEq, Eq)]
16pub struct SpeedDialAction {
17    /// Accessible name and visible label.
18    pub label: String,
19    /// Lucide icon name, such as `pencil`. Needs the default `icon-names` feature.
20    pub icon: Option<String>,
21    /// Value reported to `on_action`. Defaults to the label.
22    pub value: Option<String>,
23}
24
25impl SpeedDialAction {
26    /// An action labelled `label`.
27    pub fn new(label: impl Into<String>) -> Self {
28        Self {
29            label: label.into(),
30            ..Self::default()
31        }
32    }
33
34    /// The same action with a Lucide icon.
35    #[must_use]
36    pub fn icon(mut self, name: impl Into<String>) -> Self {
37        self.icon = Some(name.into());
38        self
39    }
40
41    /// The same action with a value.
42    #[must_use]
43    pub fn value(mut self, value: impl Into<String>) -> Self {
44        self.value = Some(value.into());
45        self
46    }
47
48    fn resolved_value(&self) -> String {
49        self.value.clone().unwrap_or_else(|| self.label.clone())
50    }
51}
52
53/// Direction a [`SpeedDial`] opens toward.
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum SpeedDialDirection {
57    /// Above the trigger.
58    #[default]
59    Up,
60    /// Below the trigger.
61    Down,
62    /// To the left of the trigger.
63    Left,
64    /// To the right of the trigger.
65    Right,
66}
67
68impl SpeedDialDirection {
69    /// The class suffix and `data-direction` value.
70    pub fn as_str(self) -> &'static str {
71        match self {
72            Self::Up => "up",
73            Self::Down => "down",
74            Self::Left => "left",
75            Self::Right => "right",
76        }
77    }
78}
79
80/// The action index a key moves to, like `getSpeedDialNavigationIndex` in lumen-react.
81pub(crate) fn speed_dial_index(key: &Key, current: Option<usize>, count: usize) -> Option<usize> {
82    if count == 0 {
83        return None;
84    }
85
86    match key {
87        Key::Home => Some(0),
88        Key::End => Some(count - 1),
89        Key::ArrowDown | Key::ArrowRight => Some(current.map_or(0, |index| (index + 1) % count)),
90        Key::ArrowUp | Key::ArrowLeft => {
91            Some(current.map_or(count - 1, |index| (index + count - 1) % count))
92        }
93        _ => None,
94    }
95}
96
97/// Props for [`SpeedDial`].
98#[derive(Props, Clone, PartialEq)]
99pub struct SpeedDialProps {
100    /// The actions, in order.
101    #[props(default)]
102    pub actions: Vec<SpeedDialAction>,
103    /// Called with the chosen action's value.
104    pub on_action: Option<EventHandler<String>>,
105    /// Opens the menu on first render.
106    #[props(default)]
107    pub default_open: bool,
108    /// Called when the menu opens or closes.
109    pub on_open_change: Option<EventHandler<bool>>,
110    /// Direction the actions fan out toward.
111    #[props(default)]
112    pub direction: SpeedDialDirection,
113    /// Accessible name of the trigger and the menu. Defaults to `Actions`.
114    #[props(default = "Actions".to_string(), into)]
115    pub label: String,
116    /// Extra classes appended after the Lumen classes.
117    #[props(into)]
118    pub class: Option<String>,
119    /// Any other `<div>` or global attribute.
120    #[props(extends = GlobalAttributes, extends = div)]
121    pub attributes: Vec<Attribute>,
122    /// Extra menu content after the actions.
123    pub children: Element,
124}
125
126/// A floating button that fans out a short menu of related actions.
127///
128/// The trigger toggles the menu. `ArrowDown` or `ArrowRight` on the trigger opens it and focuses
129/// the first action; `ArrowUp` or `ArrowLeft` focuses the last. Inside the menu, arrow keys,
130/// `Home`, and `End` move between actions, `Escape` closes it and returns focus to the trigger,
131/// and choosing an action or moving focus elsewhere closes it.
132#[component]
133pub fn SpeedDial(props: SpeedDialProps) -> Element {
134    let mut open = use_signal(|| props.default_open);
135    let mut trigger = use_signal(|| None::<Rc<MountedData>>);
136    let mut items = use_hook(|| CopyValue::new(Vec::<Option<Rc<MountedData>>>::new()));
137    let mut focused = use_signal(|| None::<usize>);
138    let mut focus_inside = use_signal(|| false);
139    let count = props.actions.len();
140    let on_open_change = props.on_open_change;
141    let on_action = props.on_action;
142    let is_open = open();
143    let direction = props.direction.as_str();
144    let class = compose([
145        Some("ui-speed-dial"),
146        Some(&format!("ui-speed-dial--{direction}")),
147        props.class.as_deref(),
148    ]);
149
150    if items.peek().len() != count {
151        items.write().resize(count, None);
152    }
153
154    let mut set_open = move |next: bool| {
155        if *open.peek() != next {
156            open.set(next);
157
158            if let Some(handler) = on_open_change {
159                handler.call(next);
160            }
161        }
162    };
163    let mut focus_action = move |index: usize| {
164        set_open(true);
165
166        spawn(async move {
167            // Let the menu render open before moving focus into it.
168            sleep(Duration::ZERO).await;
169            let target = items.peek().get(index).cloned().flatten();
170            focused.set(Some(index));
171            focus_element(target);
172        });
173    };
174
175    rsx! {
176        div {
177            class,
178            "data-direction": direction,
179            "data-state": if is_open { "open" } else { "closed" },
180            "data-ui-bound": "true",
181            "data-ui-speed-dial": "true",
182            onfocusin: move |_| focus_inside.set(true),
183            onfocusout: move |_| {
184                focus_inside.set(false);
185
186                spawn(async move {
187                    // Focus moving inside the dial fires focusin right after this focusout.
188                    sleep(Duration::ZERO).await;
189
190                    if !*focus_inside.peek() {
191                        set_open(false);
192                    }
193                });
194            },
195            ..props.attributes,
196            button {
197                aria_expanded: if is_open { "true" } else { "false" },
198                aria_haspopup: "menu",
199                aria_label: props.label.clone(),
200                class: "ui-speed-dial__trigger",
201                "data-ui-speed-dial-trigger": "true",
202                r#type: "button",
203                onclick: move |_| {
204                    let next = !*open.peek();
205                    set_open(next);
206                },
207                onkeydown: move |event| {
208                    if is_escape(&event) {
209                        set_open(false);
210                    }
211
212                    match event.key() {
213                        Key::ArrowDown | Key::ArrowRight if count > 0 => {
214                            event.prevent_default();
215                            focus_action(0);
216                        }
217                        Key::ArrowUp | Key::ArrowLeft if count > 0 => {
218                            event.prevent_default();
219                            focus_action(count - 1);
220                        }
221                        _ => {}
222                    }
223                },
224                onmounted: move |event| trigger.set(Some(event.data())),
225                span { aria_hidden: "true", class: "ui-speed-dial__icon" }
226            }
227            menu {
228                aria_label: props.label,
229                class: "ui-speed-dial__actions",
230                "data-ui-speed-dial-actions": "true",
231                role: "menu",
232                onkeydown: move |event| {
233                    if is_escape(&event) {
234                        event.prevent_default();
235                        set_open(false);
236                        focus_element(trigger());
237                        return;
238                    }
239
240                    if let Some(index) = speed_dial_index(&event.key(), focused(), count) {
241                        event.prevent_default();
242                        focus_action(index);
243                    }
244                },
245                for (index, action) in props.actions.into_iter().enumerate() {
246                    {
247                        let value = action.resolved_value();
248                        let artwork = resolve_name(action.icon.as_deref());
249
250                        rsx! {
251                            li {
252                                key: "{value}",
253                                role: "presentation",
254                                style: "--ui-speed-dial-index:{index}",
255                                button {
256                                    aria_label: action.label.clone(),
257                                    class: "ui-speed-dial__action",
258                                    "data-icon": action.icon.clone(),
259                                    "data-value": value.clone(),
260                                    role: "menuitem",
261                                    r#type: "button",
262                                    onclick: move |_| {
263                                        set_open(false);
264
265                                        if let Some(handler) = on_action {
266                                            handler.call(value.clone());
267                                        }
268                                    },
269                                    onfocus: move |_| focused.set(Some(index)),
270                                    onmounted: move |event| {
271                                        if let Some(slot) = items.write().get_mut(index) {
272                                            *slot = Some(event.data());
273                                        }
274                                    },
275                                    if let Some(artwork) = artwork {
276                                        Icon { class: "ui-speed-dial__action-icon", icon: artwork }
277                                    }
278                                    span { class: "ui-speed-dial__action-label", "{action.label}" }
279                                }
280                            }
281                        }
282                    }
283                }
284                {props.children}
285            }
286        }
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::{Key, speed_dial_index};
293
294    #[test]
295    fn keys_wrap_through_actions() {
296        assert_eq!(speed_dial_index(&Key::ArrowDown, Some(2), 3), Some(0));
297        assert_eq!(speed_dial_index(&Key::ArrowLeft, Some(0), 3), Some(2));
298        assert_eq!(speed_dial_index(&Key::Home, Some(2), 3), Some(0));
299        assert_eq!(speed_dial_index(&Key::End, None, 3), Some(2));
300        assert_eq!(speed_dial_index(&Key::ArrowDown, None, 3), Some(0));
301        assert_eq!(speed_dial_index(&Key::Enter, Some(1), 3), None);
302        assert_eq!(speed_dial_index(&Key::ArrowDown, None, 0), None);
303    }
304}