lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! `RadioGroup` and `RadioGroupItem`: a single-choice fieldset with radios that work on every
//! renderer.
//!
//! lumen-react's `RadioGroup` is a styled `<fieldset>` around native radio inputs. Blitz (Dioxus
//! Native) draws native radios itself, ignores `appearance: none`, has no arrow-key navigation, and
//! cannot keep a controlled radio unchecked, so [`RadioGroupItem`] renders a `role="radio"` button
//! instead. The group owns the selected value, submits it through one hidden input, and gives its
//! radios roving focus with arrow keys that wrap and skip disabled radios.

// cspell:words fieldset

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

use dioxus::prelude::*;

use crate::class::compose;
use crate::overlay::{focus_element, wrap_index};

/// One radio registered with its group.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RadioEntry {
    order: usize,
    value: String,
    disabled: bool,
}

/// Selection, registration, and focus shared by the radios of a [`RadioGroup`].
#[derive(Clone, Copy)]
pub(crate) struct RadioGroupContext {
    selected: Memo<Option<String>>,
    internal: Signal<Option<String>>,
    controlled: CopyValue<bool>,
    on_change: CopyValue<Option<EventHandler<String>>>,
    disabled: Memo<bool>,
    entries: Signal<Vec<RadioEntry>>,
    next_order: CopyValue<usize>,
    mounted: CopyValue<HashMap<usize, Rc<MountedData>>>,
    /// The radio that last received focus, a click, or an arrow key. Dioxus Native cannot move
    /// focus, so keyboard navigation continues from here instead of from the focused element.
    active: CopyValue<Option<usize>>,
    /// Set after the group's first render, once every radio has registered.
    ready: Signal<bool>,
}

impl RadioGroupContext {
    /// Whether `value` is the selected value. Subscribes the caller.
    pub(crate) fn is_selected(&self, value: &str) -> bool {
        self.selected.read().as_deref() == Some(value)
    }

    /// Whether the whole group is disabled. Subscribes the caller.
    pub(crate) fn is_disabled(&self) -> bool {
        *self.disabled.read()
    }

    /// Requests `value`: stores it while uncontrolled and reports it when it differs from the
    /// current selection.
    pub(crate) fn select(&self, value: &str) {
        if self.selected.peek().as_deref() == Some(value) {
            return;
        }

        if !*self.controlled.peek() {
            let mut internal = self.internal;
            internal.set(Some(value.to_string()));
        }

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

    /// Adds or updates a radio. Writes only when something changed.
    fn register(&self, entry: RadioEntry) {
        if self.entries.peek().contains(&entry) {
            return;
        }

        let mut entries = self.entries;
        let mut list = entries.write();
        list.retain(|existing| existing.order != entry.order);
        list.push(entry);
    }

    fn unregister(&self, order: usize) {
        let mut entries = self.entries;

        if let Ok(mut list) = entries.try_write() {
            list.retain(|entry| entry.order != order);
        }

        let mut mounted = self.mounted;

        if let Ok(mut map) = mounted.try_write() {
            map.remove(&order);
        }
    }

    /// Enabled radios in render order. Empty while the group is disabled.
    fn enabled_entries(&self, subscribe: bool) -> Vec<RadioEntry> {
        let group_disabled = if subscribe {
            *self.disabled.read()
        } else {
            *self.disabled.peek()
        };

        if group_disabled {
            return Vec::new();
        }

        let mut entries = if subscribe {
            self.entries.read().clone()
        } else {
            self.entries.peek().clone()
        };

        entries.retain(|entry| !entry.disabled);
        entries.sort_by_key(|entry| entry.order);
        entries
    }

    /// Whether the radio is the group's single Tab stop: the selected enabled radio, or the first
    /// enabled radio while none is selected (or the selected value matches no enabled radio).
    pub(crate) fn is_tab_stop(&self, order: usize, value: &str, disabled: bool) -> bool {
        if disabled {
            return false;
        }

        let enabled = self.enabled_entries(true);
        let first_enabled = enabled.first().is_none_or(|first| first.order == order);

        match self.selected.read().as_deref() {
            None => first_enabled,
            Some(selected) if enabled.iter().any(|entry| entry.value == selected) => {
                selected == value
            }
            // During the first render, later radios have not registered yet, so a selection that
            // matches none of the radios so far is assumed to come later.
            Some(_) => *self.ready.read() && first_enabled,
        }
    }

    /// Selects a radio after a click and moves focus to it, as a native radio label does.
    pub(crate) fn activate(&self, order: usize, value: &str) {
        if *self.disabled.peek() {
            return;
        }

        let mut active = self.active;
        active.set(Some(order));
        self.select(value);
        focus_element(self.mounted.peek().get(&order).cloned());
    }

    /// Remembers the focused radio.
    pub(crate) fn remember(&self, order: usize) {
        let mut active = self.active;
        active.set(Some(order));
    }

    /// Stores a mounted radio so arrow keys can focus it.
    pub(crate) fn set_mounted(&self, order: usize, element: Rc<MountedData>) {
        let mut mounted = self.mounted;
        mounted.write().insert(order, element);
    }

    /// Arrow keys move the selection and focus to the next or previous enabled radio, wrapping;
    /// Space selects the current radio.
    pub(crate) fn handle_key(&self, order: usize, event: &KeyboardEvent) {
        let enabled = self.enabled_entries(false);
        let current_order = self
            .active
            .peek()
            .filter(|active| enabled.iter().any(|entry| entry.order == *active))
            .unwrap_or(order);
        let current = enabled
            .iter()
            .position(|entry| entry.order == current_order);

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

        event.prevent_default();

        let Some(entry) = enabled.get(target) else {
            return;
        };
        let mut active = self.active;
        active.set(Some(entry.order));
        self.select(&entry.value);
        focus_element(self.mounted.peek().get(&entry.order).cloned());
    }
}

/// The enclosing [`RadioGroup`], if any.
pub(crate) fn use_radio_group_context() -> Option<RadioGroupContext> {
    try_use_context::<RadioGroupContext>()
}

/// Registers a radio with its group, when there is one, and returns its render order.
///
/// Always calls the same hooks, so components can call it whether or not they are in a group.
pub(crate) fn use_radio_registration(
    group: Option<&RadioGroupContext>,
    value: &str,
    disabled: bool,
) -> usize {
    let group = group.copied();
    let order = use_hook(|| {
        group.map_or(0, |group| {
            let mut next = group.next_order;
            let order = *next.peek();
            next.set(order + 1);
            order
        })
    });

    if let Some(group) = group {
        group.register(RadioEntry {
            order,
            value: value.to_string(),
            disabled,
        });
    }

    use_drop(move || {
        if let Some(group) = group {
            group.unregister(order);
        }
    });

    order
}

/// Whether a key is the Space bar.
pub(crate) fn is_space(key: &Key) -> bool {
    matches!(key, Key::Character(text) if text == " ")
}

/// The arrow-key step of a radio group: right and down move forward, left and up move back.
fn arrow_step(key: &Key) -> Option<isize> {
    match key {
        Key::ArrowRight | Key::ArrowDown => Some(1),
        Key::ArrowLeft | Key::ArrowUp => Some(-1),
        _ => None,
    }
}

/// The index, within the `len` enabled radios, that a key selects: the current radio for Space,
/// or the next or previous one (wrapping) for an arrow key. `None` when the key does nothing.
pub(crate) fn radio_key_target(key: &Key, current: Option<usize>, len: usize) -> Option<usize> {
    if len == 0 {
        return None;
    }

    if is_space(key) {
        return current.filter(|index| *index < len);
    }

    wrap_index(current, arrow_step(key)?, len)
}

/// Props for [`RadioGroup`].
#[derive(Props, Clone, PartialEq)]
pub struct RadioGroupProps {
    /// Controlled selected value. Leave unset to let the group 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>>,
    /// Form field name. When set, a hidden input submits the selected value.
    #[props(into)]
    pub name: Option<String>,
    /// Disables the fieldset and every radio in it.
    #[props(default)]
    pub disabled: bool,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<fieldset>` or global attribute.
    #[props(extends = GlobalAttributes, extends = fieldset)]
    pub attributes: Vec<Attribute>,
    /// A `legend` and the [`RadioGroupItem`]s or [`RadioCard`](crate::RadioCard)s.
    pub children: Element,
}

/// A fieldset without a frame, for one choice among several.
///
/// Put [`RadioGroupItem`]s or [`RadioCard`](crate::RadioCard)s inside, with a `legend` first. The
/// group owns the selected value (`value`, `default_value`, `on_value_change`), submits it under
/// `name`, and gives its radios one Tab stop with arrow-key navigation, like native radios.
#[component]
pub fn RadioGroup(props: RadioGroupProps) -> Element {
    let internal = use_signal(|| props.default_value.clone());
    let selected = use_memo(use_reactive((&props.value,), move |(value,)| {
        value.or_else(|| internal.cloned())
    }));
    let disabled = use_memo(use_reactive((&props.disabled,), |(disabled,)| disabled));
    let mut ready = use_signal(|| false);
    let mut controlled = use_hook(|| CopyValue::new(false));
    let mut on_change = use_hook(|| CopyValue::new(None::<EventHandler<String>>));

    controlled.set(props.value.is_some());
    on_change.set(props.on_value_change);

    let context = use_context_provider(|| RadioGroupContext {
        selected,
        internal,
        controlled,
        on_change,
        disabled,
        entries: Signal::new(Vec::new()),
        next_order: CopyValue::new(0),
        mounted: CopyValue::new(HashMap::new()),
        active: CopyValue::new(None),
        ready,
    });

    use_effect(move || {
        if !*ready.peek() {
            ready.set(true);
        }
    });

    let selected_value = selected.read().clone();
    let selected_disabled = context
        .entries
        .read()
        .iter()
        .any(|entry| entry.disabled && Some(entry.value.as_str()) == selected_value.as_deref());
    let submitted = props
        .name
        .clone()
        .zip(selected_value)
        .filter(|_| !props.disabled && !selected_disabled);
    let class = compose([Some("ui-radio-group"), props.class.as_deref()]);

    rsx! {
        fieldset {
            class,
            "data-ui-radio-group": "true",
            disabled: props.disabled,
            ..props.attributes,
            {props.children}
            if let Some((name, value)) = submitted {
                input { r#type: "hidden", name, value }
            }
        }
    }
}

/// Props for [`RadioGroupItem`].
#[derive(Props, Clone, PartialEq)]
pub struct RadioGroupItemProps {
    /// The value this radio selects.
    #[props(into)]
    pub value: String,
    /// Makes the radio unavailable and skips it during keyboard navigation.
    #[props(default)]
    pub disabled: bool,
    /// Extra classes appended to the row `<label>`.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute, applied to the radio control.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// The visible label.
    pub children: Element,
}

/// One labelled radio in a [`RadioGroup`].
///
/// Renders `<label class="ui-label">` around a `<button role="radio" class="ui-dioxus-radio">` and
/// the label text. A click anywhere on the row selects it; arrow keys move and select, and Space
/// selects, on every renderer.
///
/// # Panics
///
/// Panics when it is not inside a [`RadioGroup`].
#[component]
pub fn RadioGroupItem(props: RadioGroupItemProps) -> Element {
    let group = use_radio_group_context()
        .unwrap_or_else(|| panic!("RadioGroupItem must be used inside a Lumen RadioGroup."));
    let order = use_radio_registration(Some(&group), &props.value, props.disabled);
    let disabled = props.disabled || group.is_disabled();
    let checked = group.is_selected(&props.value);
    let tab_stop = group.is_tab_stop(order, &props.value, props.disabled);
    let class = compose([Some("ui-label"), props.class.as_deref()]);
    let click_value = props.value.clone();

    rsx! {
        label {
            class,
            onclick: move |event| {
                // The row handles the click itself, so the browser must not forward it to the radio.
                event.prevent_default();

                if !disabled {
                    group.activate(order, &click_value);
                }
            },
            button {
                aria_checked: if checked { "true" } else { "false" },
                class: "ui-dioxus-radio",
                disabled,
                role: "radio",
                tabindex: if tab_stop { "0" } else { "-1" },
                r#type: "button",
                value: props.value,
                onkeydown: move |event| group.handle_key(order, &event),
                onfocus: move |_| group.remember(order),
                onmounted: move |event| group.set_mounted(order, event.data()),
                ..props.attributes,
            }
            {props.children}
        }
    }
}

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

    #[test]
    fn arrow_keys_wrap_through_enabled_radios() {
        assert_eq!(radio_key_target(&Key::ArrowRight, Some(0), 3), Some(1));
        assert_eq!(radio_key_target(&Key::ArrowDown, Some(2), 3), Some(0));
        assert_eq!(radio_key_target(&Key::ArrowLeft, Some(0), 3), Some(2));
        assert_eq!(radio_key_target(&Key::ArrowUp, Some(1), 3), Some(0));
    }

    #[test]
    fn arrows_without_a_current_radio_start_at_an_end() {
        assert_eq!(radio_key_target(&Key::ArrowRight, None, 3), Some(0));
        assert_eq!(radio_key_target(&Key::ArrowLeft, None, 3), Some(2));
    }

    #[test]
    fn space_selects_the_current_radio_only() {
        let space = Key::Character(" ".to_string());

        assert!(is_space(&space));
        assert_eq!(radio_key_target(&space, Some(1), 3), Some(1));
        assert_eq!(radio_key_target(&space, None, 3), None);
        assert_eq!(radio_key_target(&space, Some(5), 3), None);
    }

    #[test]
    fn other_keys_and_empty_groups_do_nothing() {
        assert_eq!(radio_key_target(&Key::Enter, Some(0), 3), None);
        assert_eq!(radio_key_target(&Key::Home, Some(1), 3), None);
        assert_eq!(radio_key_target(&Key::ArrowRight, Some(0), 0), None);
        assert!(!is_space(&Key::Character("a".to_string())));
    }
}