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
//! `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);
}
}