Skip to main content

iced_cube/overlay/
popover.rs

1//! A floating panel of any content, anchored to a trigger.
2//!
3//! The app owns whether the popover is open: pass it to
4//! [`open`](Popover::open) and close it again when
5//! [`on_dismiss`](Popover::on_dismiss) arrives, after Escape or a click
6//! outside. The popover is not modal: the rest of the window stays usable
7//! while it is open, and the click that dismisses it still reaches what it
8//! landed on.
9//!
10//! Escape reaches the content first, so a menu, combobox or command list
11//! inside the popover closes before the popover does.
12
13use iced::advanced::layout::{self, Layout};
14use iced::advanced::widget::operation::Focusable;
15use iced::advanced::widget::{Operation, Tree, Widget};
16use iced::advanced::{Clipboard, Shell, overlay, renderer};
17use iced::keyboard::key::Named;
18use iced::widget::container;
19use iced::{
20    Element, Event, Length, Rectangle, Renderer, Size, Theme, Vector, keyboard, mouse, widget,
21};
22
23use crate::keys::{self, Chord, Keymap};
24use crate::overlay::anchored::{Placement, anchored, surface_style};
25use crate::theme::{Tokens, space};
26
27pub use crate::overlay::anchored::{Align, Side};
28
29/// Default panel width in logical pixels.
30pub const WIDTH: f32 = 288.0;
31
32/// A popover builder. Convert it into an [`Element`] to render.
33pub struct Popover<'a, Message> {
34    trigger: Element<'a, Message>,
35    content: Element<'a, Message>,
36    open: bool,
37    on_dismiss: Option<Message>,
38    placement: Placement,
39    width: Length,
40    padding: f32,
41    keymap: Keymap<Action>,
42}
43
44impl<Message> std::fmt::Debug for Popover<'_, Message> {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.debug_struct("Popover")
47            .field("open", &self.open)
48            .field("dismissable", &self.on_dismiss.is_some())
49            .field("placement", &self.placement)
50            .field("width", &self.width)
51            .field("padding", &self.padding)
52            .field("keymap", &self.keymap)
53            .finish_non_exhaustive()
54    }
55}
56
57/// Shows `content` in a panel next to `trigger` while
58/// [`open`](Popover::open) is true. The trigger opens it itself, usually a
59/// button whose message sets the app's flag.
60pub fn popover<'a, Message>(
61    trigger: impl Into<Element<'a, Message>>,
62    content: impl Into<Element<'a, Message>>,
63) -> Popover<'a, Message> {
64    Popover {
65        trigger: trigger.into(),
66        content: content.into(),
67        open: false,
68        on_dismiss: None,
69        placement: Placement::default(),
70        width: Length::Fixed(WIDTH),
71        padding: space::LG,
72        keymap: default_keymap(),
73    }
74}
75
76impl<'a, Message> Popover<'a, Message> {
77    pub fn open(mut self, open: bool) -> Self {
78        self.open = open;
79        self
80    }
81
82    /// Sent on Escape and on a press outside the panel and the trigger.
83    /// Without it the popover only closes when the app says so.
84    pub fn on_dismiss(mut self, message: Message) -> Self {
85        self.on_dismiss = Some(message);
86        self
87    }
88
89    /// Which side of the trigger the panel appears on. Defaults to the bottom.
90    pub fn side(mut self, side: Side) -> Self {
91        self.placement.side = side;
92        self
93    }
94
95    /// How the panel lines up with the trigger. Defaults to the centre.
96    pub fn align(mut self, align: Align) -> Self {
97        self.placement.align = align;
98        self
99    }
100
101    /// Space between the trigger and the panel.
102    pub fn gap(mut self, gap: f32) -> Self {
103        self.placement.gap = gap;
104        self
105    }
106
107    /// Defaults to [`WIDTH`]. `Length::Shrink` fits the content.
108    pub fn width(mut self, width: impl Into<Length>) -> Self {
109        self.width = width.into();
110        self
111    }
112
113    /// Space inside the panel's border. Defaults to `space::LG`.
114    pub fn padding(mut self, padding: f32) -> Self {
115        self.padding = padding;
116        self
117    }
118
119    /// Replaces the [`default_keymap`]. The open popover dismisses itself
120    /// on the chords bound to [`Action::Close`].
121    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
122        self.keymap = keymap;
123        self
124    }
125}
126
127impl<'a, Message: Clone + 'a> From<Popover<'a, Message>> for Element<'a, Message> {
128    fn from(popover: Popover<'a, Message>) -> Self {
129        let Popover {
130            trigger,
131            content,
132            open,
133            on_dismiss,
134            placement,
135            width,
136            padding,
137            keymap,
138        } = popover;
139
140        let cycle = Cycle {
141            content,
142            keymap: keymap.clone(),
143        };
144        let panel = open.then(|| {
145            let panel: Element<'a, Message> = container(Element::new(cycle))
146                .width(width)
147                .padding(padding)
148                .style(|theme| style(&Tokens::of(theme)))
149                .into();
150            #[cfg(feature = "icedwright")]
151            let panel = icedwright_probe::semantic(panel)
152                .role(icedwright_probe::role::Dialog)
153                .component("iced_cube::popover")
154                .into();
155            panel
156        });
157        anchored(trigger)
158            .kind("iced_cube::popover")
159            .content(panel)
160            .placement(placement)
161            .pass_through(true)
162            .dismiss_keys(keymap.chords(&Action::Close).into_iter().cloned())
163            .on_dismiss_maybe(on_dismiss)
164            .into()
165    }
166}
167
168/// The panel style: the floating surface shared with menus.
169pub fn style(tokens: &Tokens) -> container::Style {
170    surface_style(tokens)
171}
172
173/// What a popover keyboard shortcut does.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175pub enum Action {
176    /// Opens a closed popover and closes an open one. Not bound by default.
177    Toggle,
178    Close,
179    /// Moves focus from a field in the panel to the next one, wrapping.
180    FocusNext,
181    /// Moves focus from a field in the panel to the previous one, wrapping.
182    FocusPrevious,
183}
184
185impl Action {
186    /// Whether the popover should be open after this action, or `None`
187    /// when it stays as it is.
188    pub fn apply(self, open: bool) -> Option<bool> {
189        match self {
190            Action::Toggle => Some(!open),
191            Action::Close => open.then_some(false),
192            Action::FocusNext | Action::FocusPrevious => None,
193        }
194    }
195}
196
197impl keys::Action for Action {
198    const ALL: &'static [Self] = &[
199        Action::Toggle,
200        Action::Close,
201        Action::FocusNext,
202        Action::FocusPrevious,
203    ];
204
205    fn defaults() -> Keymap<Self> {
206        default_keymap()
207    }
208
209    fn name(self) -> &'static str {
210        match self {
211            Action::Toggle => "Toggle",
212            Action::Close => "Close",
213            Action::FocusNext => "FocusNext",
214            Action::FocusPrevious => "FocusPrevious",
215        }
216    }
217
218    fn description(self) -> &'static str {
219        match self {
220            Action::Toggle => "Opens the popover, or closes it when it is open.",
221            Action::Close => "Closes the popover.",
222            Action::FocusNext => {
223                "Moves from a field in the popover to its next field, wrapping at the end."
224            }
225            Action::FocusPrevious => {
226                "Moves from a field in the popover to its previous field, wrapping at the start."
227            }
228        }
229    }
230}
231
232/// The default popover shortcuts:
233///
234/// | Keys | Action |
235/// | --- | --- |
236/// | `Escape` | [`Action::Close`] |
237/// | `Tab` | [`Action::FocusNext`] |
238/// | `Shift+Tab` | [`Action::FocusPrevious`] |
239///
240/// The focus actions only apply while a field inside the panel has focus,
241/// so Tab elsewhere moves on as usual.
242///
243/// An open popover with [`on_dismiss`](Popover::on_dismiss) resolves
244/// [`Action::Close`] itself, after its content has had the key, so pass a
245/// changed keymap with [`Popover::keymap`]. [`Action::Toggle`] has no
246/// default chord because a popover usually belongs to one button; bind one
247/// when a popover deserves an app-wide shortcut, and route it from
248/// [`keys::subscription`] with [`Action::apply`].
249pub fn default_keymap() -> Keymap<Action> {
250    Keymap::new()
251        .bind(Chord::named(Named::Escape), Action::Close)
252        .bind(Chord::named(Named::Tab), Action::FocusNext)
253        .bind(Chord::named(Named::Tab).shift(), Action::FocusPrevious)
254}
255
256/// The field to focus after `forward` or backward movement from the
257/// focused one, wrapping at either end, given whether each field in the
258/// panel has focus. `None` when no field in the panel has focus.
259fn cycle_target(focused: &[bool], forward: bool) -> Option<usize> {
260    let current = focused.iter().position(|focused| *focused)?;
261    let count = focused.len();
262    Some(if forward {
263        (current + 1) % count
264    } else {
265        (current + count - 1) % count
266    })
267}
268
269/// The panel's content, with Tab and Shift+Tab moving between its fields
270/// while one of them has focus.
271struct Cycle<'a, Message> {
272    content: Element<'a, Message>,
273    keymap: Keymap<Action>,
274}
275
276/// Whether each focusable widget has focus, in tree order.
277#[derive(Default)]
278struct Survey {
279    focused: Vec<bool>,
280}
281
282impl Operation for Survey {
283    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
284        operate(self);
285    }
286
287    fn focusable(
288        &mut self,
289        _id: Option<&widget::Id>,
290        _bounds: Rectangle,
291        state: &mut dyn Focusable,
292    ) {
293        self.focused.push(state.is_focused());
294    }
295}
296
297/// Focuses the focusable widget at `target` and unfocuses the others.
298struct Apply {
299    target: usize,
300    index: usize,
301}
302
303impl Operation for Apply {
304    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
305        operate(self);
306    }
307
308    fn focusable(
309        &mut self,
310        _id: Option<&widget::Id>,
311        _bounds: Rectangle,
312        state: &mut dyn Focusable,
313    ) {
314        if self.index == self.target {
315            state.focus();
316        } else {
317            state.unfocus();
318        }
319        self.index += 1;
320    }
321}
322
323impl<Message> Cycle<'_, Message> {
324    /// The movement a key press asks for, if it is a focus chord.
325    fn movement(&self, event: &Event) -> Option<bool> {
326        let Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event else {
327            return None;
328        };
329        match self.keymap.resolve(key, *modifiers)? {
330            Action::FocusNext => Some(true),
331            Action::FocusPrevious => Some(false),
332            Action::Toggle | Action::Close => None,
333        }
334    }
335}
336
337impl<Message> Widget<Message, Theme, Renderer> for Cycle<'_, Message> {
338    fn size(&self) -> Size<Length> {
339        self.content.as_widget().size()
340    }
341
342    fn size_hint(&self) -> Size<Length> {
343        self.content.as_widget().size_hint()
344    }
345
346    fn children(&self) -> Vec<Tree> {
347        vec![Tree::new(&self.content)]
348    }
349
350    fn diff(&self, tree: &mut Tree) {
351        tree.diff_children(std::slice::from_ref(&self.content));
352    }
353
354    fn layout(
355        &mut self,
356        tree: &mut Tree,
357        renderer: &Renderer,
358        limits: &layout::Limits,
359    ) -> layout::Node {
360        self.content
361            .as_widget_mut()
362            .layout(&mut tree.children[0], renderer, limits)
363    }
364
365    fn draw(
366        &self,
367        tree: &Tree,
368        renderer: &mut Renderer,
369        theme: &Theme,
370        style: &renderer::Style,
371        layout: Layout<'_>,
372        cursor: mouse::Cursor,
373        viewport: &Rectangle,
374    ) {
375        self.content.as_widget().draw(
376            &tree.children[0],
377            renderer,
378            theme,
379            style,
380            layout,
381            cursor,
382            viewport,
383        );
384    }
385
386    fn operate(
387        &mut self,
388        tree: &mut Tree,
389        layout: Layout<'_>,
390        renderer: &Renderer,
391        operation: &mut dyn Operation,
392    ) {
393        self.content
394            .as_widget_mut()
395            .operate(&mut tree.children[0], layout, renderer, operation);
396    }
397
398    fn update(
399        &mut self,
400        tree: &mut Tree,
401        event: &Event,
402        layout: Layout<'_>,
403        cursor: mouse::Cursor,
404        renderer: &Renderer,
405        clipboard: &mut dyn Clipboard,
406        shell: &mut Shell<'_, Message>,
407        viewport: &Rectangle,
408    ) {
409        let content = &mut tree.children[0];
410        self.content.as_widget_mut().update(
411            content, event, layout, cursor, renderer, clipboard, shell, viewport,
412        );
413        if shell.is_event_captured() {
414            return;
415        }
416        let Some(forward) = self.movement(event) else {
417            return;
418        };
419        let mut survey = Survey::default();
420        self.content
421            .as_widget_mut()
422            .operate(content, layout, renderer, &mut survey);
423        let Some(target) = cycle_target(&survey.focused, forward) else {
424            return;
425        };
426        self.content.as_widget_mut().operate(
427            content,
428            layout,
429            renderer,
430            &mut Apply { target, index: 0 },
431        );
432        shell.capture_event();
433        shell.request_redraw();
434    }
435
436    fn mouse_interaction(
437        &self,
438        tree: &Tree,
439        layout: Layout<'_>,
440        cursor: mouse::Cursor,
441        viewport: &Rectangle,
442        renderer: &Renderer,
443    ) -> mouse::Interaction {
444        self.content.as_widget().mouse_interaction(
445            &tree.children[0],
446            layout,
447            cursor,
448            viewport,
449            renderer,
450        )
451    }
452
453    fn overlay<'b>(
454        &'b mut self,
455        tree: &'b mut Tree,
456        layout: Layout<'b>,
457        renderer: &Renderer,
458        viewport: &Rectangle,
459        translation: Vector,
460    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
461        self.content.as_widget_mut().overlay(
462            &mut tree.children[0],
463            layout,
464            renderer,
465            viewport,
466            translation,
467        )
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474    use crate::theme::{dark, light};
475    use iced::widget::text;
476
477    #[test]
478    fn builder_defaults_to_closed_below_and_centred() {
479        let popover: Popover<'_, ()> = popover(text("Open"), text("Content"));
480        assert!(!popover.open);
481        assert!(popover.on_dismiss.is_none());
482        assert_eq!(popover.placement, Placement::default());
483        assert_eq!(popover.placement.side, Side::Bottom);
484        assert_eq!(popover.placement.align, Align::Center);
485        assert_eq!(popover.width, Length::Fixed(WIDTH));
486        assert_eq!(popover.padding, space::LG);
487        assert_eq!(popover.keymap, default_keymap());
488    }
489
490    #[test]
491    fn builder_sets_every_option() {
492        let popover: Popover<'_, u8> = popover(text("Open"), text("Content"))
493            .open(true)
494            .on_dismiss(1)
495            .side(Side::Right)
496            .align(Align::End)
497            .gap(10.0)
498            .width(Length::Shrink)
499            .padding(4.0)
500            .keymap(Keymap::new());
501        assert!(popover.keymap.is_empty());
502        assert!(popover.open);
503        assert_eq!(popover.on_dismiss, Some(1));
504        assert_eq!(popover.placement.side, Side::Right);
505        assert_eq!(popover.placement.align, Align::End);
506        assert_eq!(popover.placement.gap, 10.0);
507        assert_eq!(popover.width, Length::Shrink);
508        assert_eq!(popover.padding, 4.0);
509    }
510
511    #[test]
512    fn panel_uses_the_shared_surface_in_both_themes() {
513        for theme in [light(), dark()] {
514            let tokens = Tokens::of(&theme);
515            assert_eq!(style(&tokens), surface_style(&tokens));
516        }
517    }
518
519    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
520        let chord: Chord = chord.parse().unwrap();
521        keymap.resolve(chord.key(), chord.modifiers())
522    }
523
524    #[test]
525    fn default_keymap_closes_on_escape_and_moves_focus_on_tab() {
526        let keymap = default_keymap();
527        assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
528        assert_eq!(press(&keymap, "Tab"), Some(Action::FocusNext));
529        assert_eq!(press(&keymap, "Shift+Tab"), Some(Action::FocusPrevious));
530        assert!(keymap.chords(&Action::Toggle).is_empty());
531        assert_eq!(keymap.len(), 3);
532        assert_eq!(Keymap::<Action>::defaults(), keymap);
533    }
534
535    #[test]
536    fn focus_moves_between_fields_and_wraps() {
537        assert_eq!(cycle_target(&[true, false, false], true), Some(1));
538        assert_eq!(cycle_target(&[false, false, true], true), Some(0));
539        assert_eq!(cycle_target(&[true, false, false], false), Some(2));
540        assert_eq!(cycle_target(&[false, true], false), Some(0));
541        assert_eq!(
542            cycle_target(&[true], true),
543            Some(0),
544            "a lone field keeps focus"
545        );
546        assert_eq!(
547            cycle_target(&[false, false], true),
548            None,
549            "no field in the panel has focus"
550        );
551        assert_eq!(cycle_target(&[], true), None);
552    }
553
554    #[test]
555    fn focus_actions_leave_the_open_state_alone() {
556        assert_eq!(Action::FocusNext.apply(true), None);
557        assert_eq!(Action::FocusPrevious.apply(false), None);
558    }
559
560    #[test]
561    fn keymap_overrides_and_unbinding() {
562        let keymap = default_keymap()
563            .bind("I".parse().unwrap(), Action::Toggle)
564            .unbind(&"Escape".parse().unwrap());
565        assert_eq!(press(&keymap, "i"), Some(Action::Toggle));
566        assert_eq!(press(&keymap, "Escape"), None);
567    }
568
569    #[test]
570    fn actions_map_to_the_next_open_state() {
571        assert_eq!(Action::Toggle.apply(false), Some(true));
572        assert_eq!(Action::Toggle.apply(true), Some(false));
573        assert_eq!(Action::Close.apply(true), Some(false));
574        assert_eq!(Action::Close.apply(false), None);
575    }
576}