Skip to main content

lumen_dioxus/overlays/
popover.rs

1//! Anchored panels: `Popover`, `PopoverTrigger`, `PopoverPanel`, `HoverCard`, `Tooltip`,
2//! `TooltipContent`, and `Popconfirm`.
3
4// cspell:words onfocusin onfocusout
5
6use std::rc::Rc;
7use std::time::Duration;
8
9use dioxus::prelude::*;
10
11use super::shared::{
12    OpenState, button_class, focus_stored, menu_key_index, surface, use_open_state,
13};
14use crate::class::{Glass, compose};
15use crate::hooks::{use_controllable, use_unique_id};
16use crate::overlay::{DismissLayer, is_escape};
17use crate::time::sleep;
18use crate::{ButtonSize, ButtonVariant};
19
20/// While open, a popover root sits above its dismiss layer (z-index 49); Lumen's popover panels
21/// use z-index 40 for the in-flow fallback.
22const RAISED_ROOT: &str = "z-index: 50";
23const HOVER_CARD_CLOSE_DELAY: Duration = Duration::from_millis(150);
24const TOOLTIP_DELAY: Duration = Duration::from_millis(250);
25
26/// Shared state of a `Popover` or `HoverCard` and its trigger and panel.
27#[derive(Clone, Copy)]
28struct PopoverContext {
29    open: OpenState,
30    panel_id: CopyValue<String>,
31    trigger: Signal<Option<Rc<MountedData>>>,
32    trigger_disabled: CopyValue<bool>,
33    restore_focus: CopyValue<bool>,
34}
35
36impl PopoverContext {
37    fn set_open(self, open: bool, restore_focus: bool) {
38        let mut restore = self.restore_focus;
39        restore.set(restore_focus);
40        self.open.set(open);
41    }
42}
43
44fn use_popover_context(
45    open: Option<bool>,
46    default_open: bool,
47    on_open_change: Option<EventHandler<bool>>,
48) -> PopoverContext {
49    let uid = use_unique_id();
50    let state = use_open_state(open, default_open, on_open_change);
51    let trigger = use_signal(|| None::<Rc<MountedData>>);
52    let context = use_hook(|| PopoverContext {
53        open: state,
54        panel_id: CopyValue::new(format!("ui-menu-{uid}")),
55        trigger,
56        trigger_disabled: CopyValue::new(false),
57        restore_focus: CopyValue::new(true),
58    });
59
60    use_context_provider(|| context);
61    use_restore_focus(state.get(), context.restore_focus, trigger);
62    context
63}
64
65/// Returns focus to the trigger when the panel closes, unless the close came from Tab.
66fn use_restore_focus(
67    open: bool,
68    restore: CopyValue<bool>,
69    trigger: Signal<Option<Rc<MountedData>>>,
70) {
71    let mut was_open = use_hook(|| CopyValue::new(open));
72
73    use_effect(use_reactive((&open,), move |(open,)| {
74        let previous = *was_open.peek();
75        was_open.set(open);
76
77        if !open && previous && *restore.peek() {
78            focus_stored(trigger.peek().clone());
79        }
80    }));
81}
82
83fn use_popover(component: &str) -> PopoverContext {
84    try_use_context::<PopoverContext>()
85        .unwrap_or_else(|| panic!("{component} must be used inside a Lumen Popover or HoverCard."))
86}
87
88/// Props for [`Popover`].
89#[derive(Props, Clone, PartialEq)]
90pub struct PopoverProps {
91    /// Controlled open state.
92    pub open: Option<bool>,
93    /// Initial open state when uncontrolled.
94    #[props(default)]
95    pub default_open: bool,
96    /// Called with the requested open state.
97    pub on_open_change: Option<EventHandler<bool>>,
98    /// Glass intensity.
99    #[props(default, into)]
100    pub glass: Glass,
101    /// Extra classes appended after the Lumen classes.
102    #[props(into)]
103    pub class: Option<String>,
104    /// Any other `<div>` or global attribute.
105    #[props(extends = GlobalAttributes, extends = div)]
106    pub attributes: Vec<Attribute>,
107    /// A [`PopoverTrigger`] and a [`PopoverPanel`].
108    pub children: Element,
109}
110
111/// A button that toggles a floating panel of rich content.
112///
113/// A click outside the open panel or Escape closes it and returns focus to the trigger.
114#[component]
115pub fn Popover(props: PopoverProps) -> Element {
116    let context = use_popover_context(props.open, props.default_open, props.on_open_change);
117    let open = context.open.get();
118    let glass = props.glass.class("ui-popover");
119    let class = compose([Some("ui-popover"), glass.as_deref(), props.class.as_deref()]);
120
121    rsx! {
122        if open {
123            DismissLayer { on_dismiss: move |()| context.set_open(false, true) }
124        }
125        div {
126            class,
127            "data-surface": surface(props.glass),
128            "data-ui-popover": "true",
129            style: open.then_some(RAISED_ROOT),
130            ..props.attributes,
131            {props.children}
132        }
133    }
134}
135
136/// Props for [`PopoverTrigger`].
137#[derive(Props, Clone, PartialEq)]
138pub struct PopoverTriggerProps {
139    /// Visual treatment.
140    #[props(default)]
141    pub variant: ButtonVariant,
142    /// Control size.
143    #[props(default)]
144    pub size: ButtonSize,
145    /// Disables the trigger. A disabled [`HoverCard`] trigger does not open on hover.
146    #[props(default)]
147    pub disabled: bool,
148    /// Click handler. Call `prevent_default()` to keep the panel as it is.
149    pub onclick: Option<EventHandler<MouseEvent>>,
150    /// Extra classes appended after the Lumen classes.
151    #[props(into)]
152    pub class: Option<String>,
153    /// Any other `<button>` or global attribute.
154    #[props(extends = GlobalAttributes, extends = button)]
155    pub attributes: Vec<Attribute>,
156    /// Button label.
157    pub children: Element,
158}
159
160/// The Lumen button that toggles a [`Popover`] or [`HoverCard`] panel.
161#[component]
162pub fn PopoverTrigger(props: PopoverTriggerProps) -> Element {
163    let context = use_popover("PopoverTrigger");
164    let open = context.open.get();
165    let disabled = props.disabled;
166    let mut trigger_disabled = context.trigger_disabled;
167    trigger_disabled.set(disabled);
168    let onclick = props.onclick;
169    let mut trigger = context.trigger;
170    let class = button_class(props.variant, props.size, props.class.as_deref());
171
172    rsx! {
173        button {
174            aria_controls: context.panel_id.peek().clone(),
175            aria_expanded: if open { "true" } else { "false" },
176            aria_haspopup: "menu",
177            class,
178            "data-slot": "button",
179            "data-ui-trigger": "true",
180            disabled,
181            r#type: "button",
182            onclick: move |event: MouseEvent| {
183                if let Some(handler) = onclick {
184                    handler.call(event.clone());
185                }
186
187                if event.default_action_enabled() {
188                    let next = !context.open.get();
189                    context.set_open(next, true);
190                }
191            },
192            onkeydown: move |event: KeyboardEvent| {
193                if !event.default_action_enabled() {
194                    return;
195                }
196
197                if is_escape(&event) && context.open.get() {
198                    event.prevent_default();
199                    context.set_open(false, true);
200                } else if event.key() == Key::ArrowDown && !context.open.get() {
201                    event.prevent_default();
202                    context.set_open(true, true);
203                }
204            },
205            onmounted: move |event| trigger.set(Some(event.data())),
206            ..props.attributes,
207            span { class: "ui-button__content", {props.children} }
208        }
209    }
210}
211
212/// Props for [`PopoverPanel`].
213#[derive(Props, Clone, PartialEq)]
214pub struct PopoverPanelProps {
215    /// Extra classes appended after the Lumen class.
216    #[props(into)]
217    pub class: Option<String>,
218    /// Any other `<div>` or global attribute.
219    #[props(extends = GlobalAttributes, extends = div)]
220    pub attributes: Vec<Attribute>,
221    /// Panel content.
222    pub children: Element,
223}
224
225/// The floating panel of a [`Popover`] or [`HoverCard`]. Escape inside it closes it.
226#[component]
227pub fn PopoverPanel(props: PopoverPanelProps) -> Element {
228    let context = use_popover("PopoverPanel");
229    let open = context.open.get();
230    let class = compose([Some("ui-popover__panel"), props.class.as_deref()]);
231
232    rsx! {
233        div {
234            class,
235            "data-state": if open { "open" } else { "closed" },
236            hidden: !open,
237            id: context.panel_id.peek().clone(),
238            onkeydown: move |event: KeyboardEvent| {
239                if is_escape(&event) && event.default_action_enabled() {
240                    event.prevent_default();
241                    event.stop_propagation();
242                    context.set_open(false, true);
243                }
244            },
245            ..props.attributes,
246            {props.children}
247        }
248    }
249}
250
251/// Props for [`HoverCard`].
252#[derive(Props, Clone, PartialEq)]
253pub struct HoverCardProps {
254    /// Controlled open state.
255    pub open: Option<bool>,
256    /// Initial open state when uncontrolled.
257    #[props(default)]
258    pub default_open: bool,
259    /// Called with the requested open state.
260    pub on_open_change: Option<EventHandler<bool>>,
261    /// Glass intensity.
262    #[props(default, into)]
263    pub glass: Glass,
264    /// Extra classes appended after the Lumen classes.
265    #[props(into)]
266    pub class: Option<String>,
267    /// Any other `<aside>` or global attribute.
268    #[props(extends = GlobalAttributes, extends = aside)]
269    pub attributes: Vec<Attribute>,
270    /// A [`PopoverTrigger`] and a [`PopoverPanel`].
271    pub children: Element,
272}
273
274/// A preview card that opens while the pointer or focus is on its trigger.
275///
276/// It closes 150 ms after the pointer leaves (unless focus is inside), when focus leaves, or on
277/// Escape. The trigger also toggles it on click, which is the only way to open it on Dioxus
278/// Native, where hover and focus events are not reported yet.
279#[component]
280pub fn HoverCard(props: HoverCardProps) -> Element {
281    let context = use_popover_context(props.open, props.default_open, props.on_open_change);
282    let mut generation = use_hook(|| CopyValue::new(0_u64));
283    let mut focus_within = use_hook(|| CopyValue::new(false));
284    let glass = props.glass.class("ui-hover-card");
285    let class = compose([
286        Some("ui-hover-card"),
287        glass.as_deref(),
288        props.class.as_deref(),
289    ]);
290
291    let mut open_preview = move || {
292        let next = *generation.peek() + 1;
293        generation.set(next);
294
295        if !*context.trigger_disabled.peek() {
296            context.set_open(true, false);
297        }
298    };
299    let mut schedule_close = move |delay: Duration| {
300        let current = *generation.peek() + 1;
301        generation.set(current);
302
303        spawn(async move {
304            sleep(delay).await;
305
306            if *generation.peek() == current && !*focus_within.peek() {
307                context.set_open(false, false);
308            }
309        });
310    };
311
312    rsx! {
313        aside {
314            class,
315            "data-surface": surface(props.glass),
316            "data-ui-hover-card": "true",
317            onmouseenter: move |_| open_preview(),
318            onmouseleave: move |_| schedule_close(HOVER_CARD_CLOSE_DELAY),
319            onfocusin: move |_| {
320                focus_within.set(true);
321                open_preview();
322            },
323            onfocusout: move |_| {
324                focus_within.set(false);
325                schedule_close(Duration::ZERO);
326            },
327            ..props.attributes,
328            {props.children}
329        }
330    }
331}
332
333#[derive(Clone, Copy)]
334struct TooltipContext {
335    open: OpenState,
336    id: CopyValue<String>,
337}
338
339/// Props for [`Tooltip`].
340#[derive(Props, Clone, PartialEq)]
341pub struct TooltipProps {
342    /// Controlled open state.
343    pub open: Option<bool>,
344    /// Initial open state when uncontrolled.
345    #[props(default)]
346    pub default_open: bool,
347    /// Called with the requested open state.
348    pub on_open_change: Option<EventHandler<bool>>,
349    /// Hover delay before the tooltip opens. Defaults to 250 ms. Focus opens it at once.
350    pub delay: Option<Duration>,
351    /// Extra classes appended after the Lumen class.
352    #[props(into)]
353    pub class: Option<String>,
354    /// Any other `<span>` or global attribute.
355    #[props(extends = GlobalAttributes, extends = span)]
356    pub attributes: Vec<Attribute>,
357    /// The described control and a [`TooltipContent`].
358    pub children: Element,
359}
360
361/// A short label shown while the pointer or focus is on a control.
362///
363/// Focus opens it at once and hover after `delay`; leaving, blur, or Escape closes it. Dioxus
364/// Native does not report hover or focus events yet, so tooltips stay closed there unless `open`
365/// is controlled.
366#[component]
367pub fn Tooltip(props: TooltipProps) -> Element {
368    let uid = use_unique_id();
369    let state = use_open_state(props.open, props.default_open, props.on_open_change);
370    let context = use_hook(|| TooltipContext {
371        open: state,
372        id: CopyValue::new(format!("ui-tooltip-{uid}")),
373    });
374    use_context_provider(|| context);
375    let mut generation = use_hook(|| CopyValue::new(0_u64));
376    let delay = props.delay.unwrap_or(TOOLTIP_DELAY);
377    let open = state.get();
378    let class = compose([Some("ui-tooltip"), props.class.as_deref()]);
379
380    let mut schedule_open = move |delay: Duration| {
381        let current = *generation.peek() + 1;
382        generation.set(current);
383
384        if delay.is_zero() {
385            state.set(true);
386            return;
387        }
388
389        spawn(async move {
390            sleep(delay).await;
391
392            if *generation.peek() == current {
393                state.set(true);
394            }
395        });
396    };
397    let mut close = move || {
398        let next = *generation.peek() + 1;
399        generation.set(next);
400        state.set(false);
401    };
402
403    rsx! {
404        span {
405            aria_describedby: open.then(|| context.id.peek().clone()),
406            class,
407            "data-ui-tooltip": "true",
408            onfocusin: move |_| schedule_open(Duration::ZERO),
409            onfocusout: move |_| close(),
410            onmouseenter: move |_| schedule_open(delay),
411            onmouseleave: move |_| close(),
412            onkeydown: move |event: KeyboardEvent| {
413                if is_escape(&event) && event.default_action_enabled() && state.get() {
414                    event.prevent_default();
415                    close();
416                }
417            },
418            ..props.attributes,
419            {props.children}
420        }
421    }
422}
423
424/// Props for [`TooltipContent`].
425#[derive(Props, Clone, PartialEq)]
426pub struct TooltipContentProps {
427    /// Classes for the tooltip. lumen-react adds none; the `ui-tooltip` root styles it.
428    #[props(into)]
429    pub class: Option<String>,
430    /// Any other `<span>` or global attribute.
431    #[props(extends = GlobalAttributes, extends = span)]
432    pub attributes: Vec<Attribute>,
433    /// Tooltip text.
434    pub children: Element,
435}
436
437/// The `tooltip` text of a [`Tooltip`].
438#[component]
439pub fn TooltipContent(props: TooltipContentProps) -> Element {
440    let context = try_use_context::<TooltipContext>()
441        .unwrap_or_else(|| panic!("TooltipContent must be used inside a Lumen Tooltip."));
442    let open = context.open.get();
443
444    rsx! {
445        span {
446            class: props.class,
447            hidden: !open,
448            id: context.id.peek().clone(),
449            role: "tooltip",
450            ..props.attributes,
451            {props.children}
452        }
453    }
454}
455
456/// Props for [`Popconfirm`].
457#[derive(Props, Clone, PartialEq)]
458pub struct PopconfirmProps {
459    /// The question in the panel. Defaults to "Are you sure?".
460    #[props(default = "Are you sure?".to_string(), into)]
461    pub title: String,
462    /// Cancel button label. Defaults to "Cancel".
463    #[props(default = "Cancel".to_string(), into)]
464    pub cancel_label: String,
465    /// Confirm button label. Defaults to "Confirm".
466    #[props(default = "Confirm".to_string(), into)]
467    pub confirm_label: String,
468    /// Disables the trigger.
469    #[props(default)]
470    pub disabled: bool,
471    /// Called when the user confirms. The panel closes unless it calls `prevent_default()`.
472    pub on_confirm: Option<EventHandler<MouseEvent>>,
473    /// Called when the user cancels. The panel closes unless it calls `prevent_default()`.
474    pub on_cancel: Option<EventHandler<MouseEvent>>,
475    /// Controlled open state.
476    pub open: Option<bool>,
477    /// Initial open state when uncontrolled.
478    #[props(default)]
479    pub default_open: bool,
480    /// Called with the requested open state.
481    pub on_open_change: Option<EventHandler<bool>>,
482    /// Extra classes appended after the Lumen classes.
483    #[props(into)]
484    pub class: Option<String>,
485    /// Any other `<div>` or global attribute.
486    #[props(extends = GlobalAttributes, extends = div)]
487    pub attributes: Vec<Attribute>,
488    /// The trigger label.
489    pub children: Element,
490}
491
492#[derive(Clone, Copy)]
493struct PopconfirmFocus {
494    trigger: Signal<Option<Rc<MountedData>>>,
495    actions: Signal<[Option<Rc<MountedData>>; 2]>,
496    active: CopyValue<Option<usize>>,
497    restore: CopyValue<bool>,
498}
499
500impl PopconfirmFocus {
501    fn focus_action(self, index: usize) {
502        let mut active = self.active;
503        active.set(Some(index));
504        focus_stored(self.actions.peek()[index].clone());
505    }
506}
507
508/// A trigger button with a small confirmation panel, for actions that need a second click.
509///
510/// Opening moves focus to Cancel; arrow keys switch between the two actions; Escape, Cancel,
511/// Confirm, or a click outside closes the panel and returns focus to the trigger.
512#[component]
513pub fn Popconfirm(props: PopconfirmProps) -> Element {
514    let panel_uid = use_unique_id();
515    let title_id = use_unique_id();
516    let state = use_controllable(props.open, || props.default_open, props.on_open_change);
517    let focus = use_hook(|| PopconfirmFocus {
518        trigger: Signal::new(None),
519        actions: Signal::new([None, None]),
520        active: CopyValue::new(None),
521        restore: CopyValue::new(true),
522    });
523    let open = state.get();
524    let mut was_open = use_hook(|| CopyValue::new(false));
525
526    use_effect(use_reactive((&open,), move |(open,)| {
527        let previous = *was_open.peek();
528        was_open.set(open);
529
530        if open && !previous {
531            focus.focus_action(0);
532        } else if !open && previous {
533            let mut active = focus.active;
534            active.set(None);
535
536            if *focus.restore.peek() {
537                focus_stored(focus.trigger.peek().clone());
538            }
539        }
540    }));
541
542    let set_open = move |next: bool, restore: bool| {
543        let mut restore_slot = focus.restore;
544        restore_slot.set(restore);
545        state.set(next);
546    };
547    let panel_id = format!("ui-menu-{panel_uid}");
548    let disabled = props.disabled;
549    let (on_confirm, on_cancel) = (props.on_confirm, props.on_cancel);
550    let class = compose([Some("ui-popover ui-popconfirm"), props.class.as_deref()]);
551    let trigger_class = button_class(ButtonVariant::Default, ButtonSize::Default, None);
552    let cancel_class = button_class(ButtonVariant::Ghost, ButtonSize::Sm, None);
553    let confirm_class = button_class(ButtonVariant::Destructive, ButtonSize::Sm, None);
554    let (mut trigger, mut actions) = (focus.trigger, focus.actions);
555
556    rsx! {
557        if open {
558            DismissLayer { on_dismiss: move |()| set_open(false, true) }
559        }
560        div {
561            class,
562            "data-surface": "default",
563            "data-ui-popconfirm": "true",
564            "data-ui-popover": "true",
565            style: open.then_some(RAISED_ROOT),
566            ..props.attributes,
567            span { class: "ui-popconfirm__trigger",
568                button {
569                    aria_controls: panel_id.clone(),
570                    aria_expanded: if open { "true" } else { "false" },
571                    aria_haspopup: "dialog",
572                    class: trigger_class,
573                    "data-slot": "button",
574                    "data-ui-trigger": "true",
575                    disabled,
576                    r#type: "button",
577                    onclick: move |_| {
578                        if !disabled {
579                            set_open(!state.get(), true);
580                        }
581                    },
582                    onkeydown: move |event: KeyboardEvent| {
583                        if disabled || !event.default_action_enabled() {
584                            return;
585                        }
586
587                        if is_escape(&event) && state.get() {
588                            event.prevent_default();
589                            set_open(false, true);
590                        } else if event.key() == Key::ArrowDown && !state.get() {
591                            event.prevent_default();
592                            set_open(true, true);
593                        }
594                    },
595                    onmounted: move |event| trigger.set(Some(event.data())),
596                    span { class: "ui-button__content", {props.children} }
597                }
598            }
599            div {
600                aria_labelledby: title_id.clone(),
601                class: "ui-popover__panel ui-popconfirm__panel",
602                "data-state": if open { "open" } else { "closed" },
603                hidden: !open,
604                id: panel_id,
605                role: "dialog",
606                onkeydown: move |event: KeyboardEvent| {
607                    if !event.default_action_enabled() {
608                        return;
609                    }
610
611                    if is_escape(&event) {
612                        event.prevent_default();
613                        event.stop_propagation();
614                        set_open(false, true);
615                    } else if event.key() == Key::Tab {
616                        set_open(false, false);
617                    } else if let Some(index) = menu_key_index(&event.key(), *focus.active.peek(), 2) {
618                        event.prevent_default();
619                        focus.focus_action(index);
620                    }
621                },
622                p { class: "ui-popconfirm__message", id: title_id, {props.title} }
623                div { class: "ui-popconfirm__actions",
624                    button {
625                        class: cancel_class,
626                        "data-slot": "button",
627                        "data-ui-popconfirm-cancel": "true",
628                        r#type: "button",
629                        onclick: move |event: MouseEvent| {
630                            if let Some(handler) = on_cancel {
631                                handler.call(event.clone());
632                            }
633
634                            if event.default_action_enabled() {
635                                set_open(false, true);
636                            }
637                        },
638                        onfocus: move |_| {
639                            let mut active = focus.active;
640                            active.set(Some(0));
641                        },
642                        onmounted: move |event| actions.write()[0] = Some(event.data()),
643                        span { class: "ui-button__content", {props.cancel_label} }
644                    }
645                    button {
646                        class: confirm_class,
647                        "data-slot": "button",
648                        "data-ui-popconfirm-confirm": "true",
649                        r#type: "button",
650                        onclick: move |event: MouseEvent| {
651                            if let Some(handler) = on_confirm {
652                                handler.call(event.clone());
653                            }
654
655                            if event.default_action_enabled() {
656                                set_open(false, true);
657                            }
658                        },
659                        onfocus: move |_| {
660                            let mut active = focus.active;
661                            active.set(Some(1));
662                        },
663                        onmounted: move |event| actions.write()[1] = Some(event.data()),
664                        span { class: "ui-button__content", {props.confirm_label} }
665                    }
666                }
667            }
668        }
669    }
670}