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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Anchored panels: `Popover`, `PopoverTrigger`, `PopoverPanel`, `HoverCard`, `Tooltip`,
//! `TooltipContent`, and `Popconfirm`.

// cspell:words onfocusin onfocusout

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

use dioxus::prelude::*;

use super::shared::{
    OpenState, button_class, focus_stored, menu_key_index, surface, use_open_state,
};
use crate::class::{Glass, compose};
use crate::hooks::{use_controllable, use_unique_id};
use crate::overlay::{DismissLayer, is_escape};
use crate::time::sleep;
use crate::{ButtonSize, ButtonVariant};

/// While open, a popover root sits above its dismiss layer (z-index 49); Lumen's popover panels
/// use z-index 40 for the in-flow fallback.
const RAISED_ROOT: &str = "z-index: 50";
const HOVER_CARD_CLOSE_DELAY: Duration = Duration::from_millis(150);
const TOOLTIP_DELAY: Duration = Duration::from_millis(250);

/// Shared state of a `Popover` or `HoverCard` and its trigger and panel.
#[derive(Clone, Copy)]
struct PopoverContext {
    open: OpenState,
    panel_id: CopyValue<String>,
    trigger: Signal<Option<Rc<MountedData>>>,
    trigger_disabled: CopyValue<bool>,
    restore_focus: CopyValue<bool>,
}

impl PopoverContext {
    fn set_open(self, open: bool, restore_focus: bool) {
        let mut restore = self.restore_focus;
        restore.set(restore_focus);
        self.open.set(open);
    }
}

fn use_popover_context(
    open: Option<bool>,
    default_open: bool,
    on_open_change: Option<EventHandler<bool>>,
) -> PopoverContext {
    let uid = use_unique_id();
    let state = use_open_state(open, default_open, on_open_change);
    let trigger = use_signal(|| None::<Rc<MountedData>>);
    let context = use_hook(|| PopoverContext {
        open: state,
        panel_id: CopyValue::new(format!("ui-menu-{uid}")),
        trigger,
        trigger_disabled: CopyValue::new(false),
        restore_focus: CopyValue::new(true),
    });

    use_context_provider(|| context);
    use_restore_focus(state.get(), context.restore_focus, trigger);
    context
}

/// Returns focus to the trigger when the panel closes, unless the close came from Tab.
fn use_restore_focus(
    open: bool,
    restore: CopyValue<bool>,
    trigger: Signal<Option<Rc<MountedData>>>,
) {
    let mut was_open = use_hook(|| CopyValue::new(open));

    use_effect(use_reactive((&open,), move |(open,)| {
        let previous = *was_open.peek();
        was_open.set(open);

        if !open && previous && *restore.peek() {
            focus_stored(trigger.peek().clone());
        }
    }));
}

fn use_popover(component: &str) -> PopoverContext {
    try_use_context::<PopoverContext>()
        .unwrap_or_else(|| panic!("{component} must be used inside a Lumen Popover or HoverCard."))
}

/// Props for [`Popover`].
#[derive(Props, Clone, PartialEq)]
pub struct PopoverProps {
    /// Controlled open state.
    pub open: Option<bool>,
    /// Initial open state when uncontrolled.
    #[props(default)]
    pub default_open: bool,
    /// Called with the requested open state.
    pub on_open_change: Option<EventHandler<bool>>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// 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>,
    /// A [`PopoverTrigger`] and a [`PopoverPanel`].
    pub children: Element,
}

/// A button that toggles a floating panel of rich content.
///
/// A click outside the open panel or Escape closes it and returns focus to the trigger.
#[component]
pub fn Popover(props: PopoverProps) -> Element {
    let context = use_popover_context(props.open, props.default_open, props.on_open_change);
    let open = context.open.get();
    let glass = props.glass.class("ui-popover");
    let class = compose([Some("ui-popover"), glass.as_deref(), props.class.as_deref()]);

    rsx! {
        if open {
            DismissLayer { on_dismiss: move |()| context.set_open(false, true) }
        }
        div {
            class,
            "data-surface": surface(props.glass),
            "data-ui-popover": "true",
            style: open.then_some(RAISED_ROOT),
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`PopoverTrigger`].
#[derive(Props, Clone, PartialEq)]
pub struct PopoverTriggerProps {
    /// Visual treatment.
    #[props(default)]
    pub variant: ButtonVariant,
    /// Control size.
    #[props(default)]
    pub size: ButtonSize,
    /// Disables the trigger. A disabled [`HoverCard`] trigger does not open on hover.
    #[props(default)]
    pub disabled: bool,
    /// Click handler. Call `prevent_default()` to keep the panel as it is.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Button label.
    pub children: Element,
}

/// The Lumen button that toggles a [`Popover`] or [`HoverCard`] panel.
#[component]
pub fn PopoverTrigger(props: PopoverTriggerProps) -> Element {
    let context = use_popover("PopoverTrigger");
    let open = context.open.get();
    let disabled = props.disabled;
    let mut trigger_disabled = context.trigger_disabled;
    trigger_disabled.set(disabled);
    let onclick = props.onclick;
    let mut trigger = context.trigger;
    let class = button_class(props.variant, props.size, props.class.as_deref());

    rsx! {
        button {
            aria_controls: context.panel_id.peek().clone(),
            aria_expanded: if open { "true" } else { "false" },
            aria_haspopup: "menu",
            class,
            "data-slot": "button",
            "data-ui-trigger": "true",
            disabled,
            r#type: "button",
            onclick: move |event: MouseEvent| {
                if let Some(handler) = onclick {
                    handler.call(event.clone());
                }

                if event.default_action_enabled() {
                    let next = !context.open.get();
                    context.set_open(next, true);
                }
            },
            onkeydown: move |event: KeyboardEvent| {
                if !event.default_action_enabled() {
                    return;
                }

                if is_escape(&event) && context.open.get() {
                    event.prevent_default();
                    context.set_open(false, true);
                } else if event.key() == Key::ArrowDown && !context.open.get() {
                    event.prevent_default();
                    context.set_open(true, true);
                }
            },
            onmounted: move |event| trigger.set(Some(event.data())),
            ..props.attributes,
            span { class: "ui-button__content", {props.children} }
        }
    }
}

/// Props for [`PopoverPanel`].
#[derive(Props, Clone, PartialEq)]
pub struct PopoverPanelProps {
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Panel content.
    pub children: Element,
}

/// The floating panel of a [`Popover`] or [`HoverCard`]. Escape inside it closes it.
#[component]
pub fn PopoverPanel(props: PopoverPanelProps) -> Element {
    let context = use_popover("PopoverPanel");
    let open = context.open.get();
    let class = compose([Some("ui-popover__panel"), props.class.as_deref()]);

    rsx! {
        div {
            class,
            "data-state": if open { "open" } else { "closed" },
            hidden: !open,
            id: context.panel_id.peek().clone(),
            onkeydown: move |event: KeyboardEvent| {
                if is_escape(&event) && event.default_action_enabled() {
                    event.prevent_default();
                    event.stop_propagation();
                    context.set_open(false, true);
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`HoverCard`].
#[derive(Props, Clone, PartialEq)]
pub struct HoverCardProps {
    /// Controlled open state.
    pub open: Option<bool>,
    /// Initial open state when uncontrolled.
    #[props(default)]
    pub default_open: bool,
    /// Called with the requested open state.
    pub on_open_change: Option<EventHandler<bool>>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<aside>` or global attribute.
    #[props(extends = GlobalAttributes, extends = aside)]
    pub attributes: Vec<Attribute>,
    /// A [`PopoverTrigger`] and a [`PopoverPanel`].
    pub children: Element,
}

/// A preview card that opens while the pointer or focus is on its trigger.
///
/// It closes 150 ms after the pointer leaves (unless focus is inside), when focus leaves, or on
/// Escape. The trigger also toggles it on click, which is the only way to open it on Dioxus
/// Native, where hover and focus events are not reported yet.
#[component]
pub fn HoverCard(props: HoverCardProps) -> Element {
    let context = use_popover_context(props.open, props.default_open, props.on_open_change);
    let mut generation = use_hook(|| CopyValue::new(0_u64));
    let mut focus_within = use_hook(|| CopyValue::new(false));
    let glass = props.glass.class("ui-hover-card");
    let class = compose([
        Some("ui-hover-card"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    let mut open_preview = move || {
        let next = *generation.peek() + 1;
        generation.set(next);

        if !*context.trigger_disabled.peek() {
            context.set_open(true, false);
        }
    };
    let mut schedule_close = move |delay: Duration| {
        let current = *generation.peek() + 1;
        generation.set(current);

        spawn(async move {
            sleep(delay).await;

            if *generation.peek() == current && !*focus_within.peek() {
                context.set_open(false, false);
            }
        });
    };

    rsx! {
        aside {
            class,
            "data-surface": surface(props.glass),
            "data-ui-hover-card": "true",
            onmouseenter: move |_| open_preview(),
            onmouseleave: move |_| schedule_close(HOVER_CARD_CLOSE_DELAY),
            onfocusin: move |_| {
                focus_within.set(true);
                open_preview();
            },
            onfocusout: move |_| {
                focus_within.set(false);
                schedule_close(Duration::ZERO);
            },
            ..props.attributes,
            {props.children}
        }
    }
}

#[derive(Clone, Copy)]
struct TooltipContext {
    open: OpenState,
    id: CopyValue<String>,
}

/// Props for [`Tooltip`].
#[derive(Props, Clone, PartialEq)]
pub struct TooltipProps {
    /// Controlled open state.
    pub open: Option<bool>,
    /// Initial open state when uncontrolled.
    #[props(default)]
    pub default_open: bool,
    /// Called with the requested open state.
    pub on_open_change: Option<EventHandler<bool>>,
    /// Hover delay before the tooltip opens. Defaults to 250 ms. Focus opens it at once.
    pub delay: Option<Duration>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<span>` or global attribute.
    #[props(extends = GlobalAttributes, extends = span)]
    pub attributes: Vec<Attribute>,
    /// The described control and a [`TooltipContent`].
    pub children: Element,
}

/// A short label shown while the pointer or focus is on a control.
///
/// Focus opens it at once and hover after `delay`; leaving, blur, or Escape closes it. Dioxus
/// Native does not report hover or focus events yet, so tooltips stay closed there unless `open`
/// is controlled.
#[component]
pub fn Tooltip(props: TooltipProps) -> Element {
    let uid = use_unique_id();
    let state = use_open_state(props.open, props.default_open, props.on_open_change);
    let context = use_hook(|| TooltipContext {
        open: state,
        id: CopyValue::new(format!("ui-tooltip-{uid}")),
    });
    use_context_provider(|| context);
    let mut generation = use_hook(|| CopyValue::new(0_u64));
    let delay = props.delay.unwrap_or(TOOLTIP_DELAY);
    let open = state.get();
    let class = compose([Some("ui-tooltip"), props.class.as_deref()]);

    let mut schedule_open = move |delay: Duration| {
        let current = *generation.peek() + 1;
        generation.set(current);

        if delay.is_zero() {
            state.set(true);
            return;
        }

        spawn(async move {
            sleep(delay).await;

            if *generation.peek() == current {
                state.set(true);
            }
        });
    };
    let mut close = move || {
        let next = *generation.peek() + 1;
        generation.set(next);
        state.set(false);
    };

    rsx! {
        span {
            aria_describedby: open.then(|| context.id.peek().clone()),
            class,
            "data-ui-tooltip": "true",
            onfocusin: move |_| schedule_open(Duration::ZERO),
            onfocusout: move |_| close(),
            onmouseenter: move |_| schedule_open(delay),
            onmouseleave: move |_| close(),
            onkeydown: move |event: KeyboardEvent| {
                if is_escape(&event) && event.default_action_enabled() && state.get() {
                    event.prevent_default();
                    close();
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`TooltipContent`].
#[derive(Props, Clone, PartialEq)]
pub struct TooltipContentProps {
    /// Classes for the tooltip. lumen-react adds none; the `ui-tooltip` root styles it.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<span>` or global attribute.
    #[props(extends = GlobalAttributes, extends = span)]
    pub attributes: Vec<Attribute>,
    /// Tooltip text.
    pub children: Element,
}

/// The `tooltip` text of a [`Tooltip`].
#[component]
pub fn TooltipContent(props: TooltipContentProps) -> Element {
    let context = try_use_context::<TooltipContext>()
        .unwrap_or_else(|| panic!("TooltipContent must be used inside a Lumen Tooltip."));
    let open = context.open.get();

    rsx! {
        span {
            class: props.class,
            hidden: !open,
            id: context.id.peek().clone(),
            role: "tooltip",
            ..props.attributes,
            {props.children}
        }
    }
}

/// Props for [`Popconfirm`].
#[derive(Props, Clone, PartialEq)]
pub struct PopconfirmProps {
    /// The question in the panel. Defaults to "Are you sure?".
    #[props(default = "Are you sure?".to_string(), into)]
    pub title: String,
    /// Cancel button label. Defaults to "Cancel".
    #[props(default = "Cancel".to_string(), into)]
    pub cancel_label: String,
    /// Confirm button label. Defaults to "Confirm".
    #[props(default = "Confirm".to_string(), into)]
    pub confirm_label: String,
    /// Disables the trigger.
    #[props(default)]
    pub disabled: bool,
    /// Called when the user confirms. The panel closes unless it calls `prevent_default()`.
    pub on_confirm: Option<EventHandler<MouseEvent>>,
    /// Called when the user cancels. The panel closes unless it calls `prevent_default()`.
    pub on_cancel: Option<EventHandler<MouseEvent>>,
    /// Controlled open state.
    pub open: Option<bool>,
    /// Initial open state when uncontrolled.
    #[props(default)]
    pub default_open: bool,
    /// Called with the requested open state.
    pub on_open_change: Option<EventHandler<bool>>,
    /// 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>,
    /// The trigger label.
    pub children: Element,
}

#[derive(Clone, Copy)]
struct PopconfirmFocus {
    trigger: Signal<Option<Rc<MountedData>>>,
    actions: Signal<[Option<Rc<MountedData>>; 2]>,
    active: CopyValue<Option<usize>>,
    restore: CopyValue<bool>,
}

impl PopconfirmFocus {
    fn focus_action(self, index: usize) {
        let mut active = self.active;
        active.set(Some(index));
        focus_stored(self.actions.peek()[index].clone());
    }
}

/// A trigger button with a small confirmation panel, for actions that need a second click.
///
/// Opening moves focus to Cancel; arrow keys switch between the two actions; Escape, Cancel,
/// Confirm, or a click outside closes the panel and returns focus to the trigger.
#[component]
pub fn Popconfirm(props: PopconfirmProps) -> Element {
    let panel_uid = use_unique_id();
    let title_id = use_unique_id();
    let state = use_controllable(props.open, || props.default_open, props.on_open_change);
    let focus = use_hook(|| PopconfirmFocus {
        trigger: Signal::new(None),
        actions: Signal::new([None, None]),
        active: CopyValue::new(None),
        restore: CopyValue::new(true),
    });
    let open = state.get();
    let mut was_open = use_hook(|| CopyValue::new(false));

    use_effect(use_reactive((&open,), move |(open,)| {
        let previous = *was_open.peek();
        was_open.set(open);

        if open && !previous {
            focus.focus_action(0);
        } else if !open && previous {
            let mut active = focus.active;
            active.set(None);

            if *focus.restore.peek() {
                focus_stored(focus.trigger.peek().clone());
            }
        }
    }));

    let set_open = move |next: bool, restore: bool| {
        let mut restore_slot = focus.restore;
        restore_slot.set(restore);
        state.set(next);
    };
    let panel_id = format!("ui-menu-{panel_uid}");
    let disabled = props.disabled;
    let (on_confirm, on_cancel) = (props.on_confirm, props.on_cancel);
    let class = compose([Some("ui-popover ui-popconfirm"), props.class.as_deref()]);
    let trigger_class = button_class(ButtonVariant::Default, ButtonSize::Default, None);
    let cancel_class = button_class(ButtonVariant::Ghost, ButtonSize::Sm, None);
    let confirm_class = button_class(ButtonVariant::Destructive, ButtonSize::Sm, None);
    let (mut trigger, mut actions) = (focus.trigger, focus.actions);

    rsx! {
        if open {
            DismissLayer { on_dismiss: move |()| set_open(false, true) }
        }
        div {
            class,
            "data-surface": "default",
            "data-ui-popconfirm": "true",
            "data-ui-popover": "true",
            style: open.then_some(RAISED_ROOT),
            ..props.attributes,
            span { class: "ui-popconfirm__trigger",
                button {
                    aria_controls: panel_id.clone(),
                    aria_expanded: if open { "true" } else { "false" },
                    aria_haspopup: "dialog",
                    class: trigger_class,
                    "data-slot": "button",
                    "data-ui-trigger": "true",
                    disabled,
                    r#type: "button",
                    onclick: move |_| {
                        if !disabled {
                            set_open(!state.get(), true);
                        }
                    },
                    onkeydown: move |event: KeyboardEvent| {
                        if disabled || !event.default_action_enabled() {
                            return;
                        }

                        if is_escape(&event) && state.get() {
                            event.prevent_default();
                            set_open(false, true);
                        } else if event.key() == Key::ArrowDown && !state.get() {
                            event.prevent_default();
                            set_open(true, true);
                        }
                    },
                    onmounted: move |event| trigger.set(Some(event.data())),
                    span { class: "ui-button__content", {props.children} }
                }
            }
            div {
                aria_labelledby: title_id.clone(),
                class: "ui-popover__panel ui-popconfirm__panel",
                "data-state": if open { "open" } else { "closed" },
                hidden: !open,
                id: panel_id,
                role: "dialog",
                onkeydown: move |event: KeyboardEvent| {
                    if !event.default_action_enabled() {
                        return;
                    }

                    if is_escape(&event) {
                        event.prevent_default();
                        event.stop_propagation();
                        set_open(false, true);
                    } else if event.key() == Key::Tab {
                        set_open(false, false);
                    } else if let Some(index) = menu_key_index(&event.key(), *focus.active.peek(), 2) {
                        event.prevent_default();
                        focus.focus_action(index);
                    }
                },
                p { class: "ui-popconfirm__message", id: title_id, {props.title} }
                div { class: "ui-popconfirm__actions",
                    button {
                        class: cancel_class,
                        "data-slot": "button",
                        "data-ui-popconfirm-cancel": "true",
                        r#type: "button",
                        onclick: move |event: MouseEvent| {
                            if let Some(handler) = on_cancel {
                                handler.call(event.clone());
                            }

                            if event.default_action_enabled() {
                                set_open(false, true);
                            }
                        },
                        onfocus: move |_| {
                            let mut active = focus.active;
                            active.set(Some(0));
                        },
                        onmounted: move |event| actions.write()[0] = Some(event.data()),
                        span { class: "ui-button__content", {props.cancel_label} }
                    }
                    button {
                        class: confirm_class,
                        "data-slot": "button",
                        "data-ui-popconfirm-confirm": "true",
                        r#type: "button",
                        onclick: move |event: MouseEvent| {
                            if let Some(handler) = on_confirm {
                                handler.call(event.clone());
                            }

                            if event.default_action_enabled() {
                                set_open(false, true);
                            }
                        },
                        onfocus: move |_| {
                            let mut active = focus.active;
                            active.set(Some(1));
                        },
                        onmounted: move |event| actions.write()[1] = Some(event.data()),
                        span { class: "ui-button__content", {props.confirm_label} }
                    }
                }
            }
        }
    }
}