Skip to main content

iced_cube/overlay/
anchored.rs

1//! Floats a panel next to an anchor element: the one layer popovers, menus,
2//! the combobox and select lists, and the command list's keys are built on.
3//!
4//! [`anchored`] wraps an anchor, such as a trigger button or a text field,
5//! and while it has content draws that content above everything else.
6//! [`place`] is the pure positioning logic: it puts the panel on one
7//! [`Side`] of the anchor, aligned by [`Align`], then flips and shifts it to
8//! stay inside the window.
9//!
10//! Every open panel follows the same rules:
11//!
12//! - Events reach the content first, including panels nested inside it, so
13//!   Escape closes the innermost layer.
14//! - [`on_key`](Anchored::on_key) sees the key presses the content leaves,
15//!   while the panel is open or something in the anchor has focus.
16//! - [`on_dismiss`](Anchored::on_dismiss) is sent at most once per event: on
17//!   a [dismiss chord](Anchored::dismiss_keys), a press outside the panel and
18//!   the anchor, or, with [`dismiss_on_blur`](Anchored::dismiss_on_blur),
19//!   when the anchor loses focus.
20//! - That outside press is captured, so nothing underneath sees it, unless
21//!   the panel [passes it through](Anchored::pass_through).
22//! - Presses on the anchor are left to the anchor, so a trigger can toggle
23//!   the panel itself. Presses inside the panel never reach the widgets
24//!   underneath it.
25
26use iced::advanced::layout::{self, Layout};
27use iced::advanced::overlay;
28use iced::advanced::renderer;
29use iced::advanced::widget::operation::Focusable;
30use iced::advanced::widget::{Id, Operation, Tree, Widget, tree};
31use iced::advanced::{Clipboard, Shell};
32use iced::keyboard::{self, key::Named};
33use iced::widget::container;
34use iced::{
35    Background, Border, Color, Element, Event, Length, Point, Rectangle, Renderer, Shadow, Size,
36    Theme, Vector, mouse, touch,
37};
38
39use crate::keys::{self, Chord};
40use crate::theme::{Tokens, fade, radius};
41
42/// Default space between the anchor and the panel, in logical pixels.
43pub const GAP: f32 = 4.0;
44
45/// Space kept between the panel and the edges of the window.
46pub const MARGIN: f32 = 8.0;
47
48/// The side of the anchor the panel appears on.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
50pub enum Side {
51    Top,
52    #[default]
53    Bottom,
54    Left,
55    Right,
56}
57
58impl Side {
59    pub const ALL: [Side; 4] = [Side::Top, Side::Bottom, Side::Left, Side::Right];
60
61    pub fn opposite(self) -> Side {
62        match self {
63            Side::Top => Side::Bottom,
64            Side::Bottom => Side::Top,
65            Side::Left => Side::Right,
66            Side::Right => Side::Left,
67        }
68    }
69
70    fn is_vertical(self) -> bool {
71        matches!(self, Side::Top | Side::Bottom)
72    }
73}
74
75/// How the panel lines up with the anchor along that side.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
77pub enum Align {
78    /// Left edges meet (or top edges, on the left and right sides).
79    Start,
80    #[default]
81    Center,
82    /// Right edges meet (or bottom edges, on the left and right sides).
83    End,
84}
85
86impl Align {
87    pub const ALL: [Align; 3] = [Align::Start, Align::Center, Align::End];
88
89    fn mirrored(self) -> Align {
90        match self {
91            Align::Start => Align::End,
92            Align::Center => Align::Center,
93            Align::End => Align::Start,
94        }
95    }
96}
97
98/// Where a panel sits relative to its anchor.
99#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct Placement {
101    pub side: Side,
102    pub align: Align,
103    /// Space between the anchor and the panel.
104    pub gap: f32,
105    /// Shift along the side, away from the aligned edge.
106    pub offset: f32,
107}
108
109impl Default for Placement {
110    fn default() -> Self {
111        Self {
112            side: Side::default(),
113            align: Align::default(),
114            gap: GAP,
115            offset: 0.0,
116        }
117    }
118}
119
120impl Placement {
121    pub fn new(side: Side, align: Align) -> Self {
122        Self {
123            side,
124            align,
125            ..Self::default()
126        }
127    }
128
129    pub fn gap(mut self, gap: f32) -> Self {
130        self.gap = gap;
131        self
132    }
133
134    pub fn offset(mut self, offset: f32) -> Self {
135        self.offset = offset;
136        self
137    }
138}
139
140/// Positions a panel of `size` next to `anchor`, keeping it inside
141/// `viewport` less [`MARGIN`].
142///
143/// The panel moves to the opposite side when it does not fit on the
144/// requested one and does fit there, and to the mirrored alignment when it
145/// would overflow along the side. A panel on the left or right that fits on
146/// neither moves below the anchor, or above it, rather than covering it.
147/// Whatever still overflows is shifted back inside, pinned to the top left
148/// if the panel is larger than the window.
149pub fn place(
150    anchor: Rectangle,
151    size: Size,
152    viewport: Rectangle,
153    placement: Placement,
154) -> Rectangle {
155    let side = choose_side(anchor, size, viewport.shrink(MARGIN), placement);
156    place_on(anchor, size, viewport, placement, side)
157}
158
159/// The side [`place`] would put a panel of `size` on.
160pub(crate) fn side_for(
161    anchor: Rectangle,
162    size: Size,
163    viewport: Rectangle,
164    placement: Placement,
165) -> Side {
166    choose_side(anchor, size, viewport.shrink(MARGIN), placement)
167}
168
169/// Positions a panel as [`place`] does, on a side already chosen.
170fn place_on(
171    anchor: Rectangle,
172    size: Size,
173    viewport: Rectangle,
174    placement: Placement,
175    side: Side,
176) -> Rectangle {
177    let area = viewport.shrink(MARGIN);
178    // The offset runs along the requested side, so it does not carry over
179    // to a side across it.
180    let offset = if side.is_vertical() == placement.side.is_vertical() {
181        placement.offset
182    } else {
183        0.0
184    };
185
186    let main = match side {
187        Side::Top => anchor.y - placement.gap - size.height,
188        Side::Bottom => anchor.y + anchor.height + placement.gap,
189        Side::Left => anchor.x - placement.gap - size.width,
190        Side::Right => anchor.x + anchor.width + placement.gap,
191    };
192
193    let (start, length, extent, low, high) = if side.is_vertical() {
194        (
195            anchor.x,
196            anchor.width,
197            size.width,
198            area.x,
199            area.x + area.width,
200        )
201    } else {
202        (
203            anchor.y,
204            anchor.height,
205            size.height,
206            area.y,
207            area.y + area.height,
208        )
209    };
210    let cross_at = |align: Align| match align {
211        Align::Start => start + offset,
212        Align::Center => start + (length - extent) / 2.0 + offset,
213        Align::End => start + length - extent - offset,
214    };
215    let fits = |value: f32| value >= low && value + extent <= high;
216    let preferred = cross_at(placement.align);
217    let mirrored = cross_at(placement.align.mirrored());
218    let cross = if !fits(preferred) && fits(mirrored) {
219        mirrored
220    } else {
221        preferred
222    };
223
224    let (x, y) = if side.is_vertical() {
225        (cross, main)
226    } else {
227        (main, cross)
228    };
229    Rectangle::new(
230        Point::new(
231            clamp(x, area.x, area.x + area.width - size.width),
232            clamp(y, area.y, area.y + area.height - size.height),
233        ),
234        size,
235    )
236}
237
238/// The side [`place`] puts the panel on: the requested side, else the
239/// opposite one, else (for the left and right) below or above. With no
240/// side that fits, the roomier of the requested pair wins, keeping the
241/// requested side on a tie.
242fn choose_side(anchor: Rectangle, size: Size, area: Rectangle, placement: Placement) -> Side {
243    let room = |side: Side| room(anchor, area, placement.gap, side);
244    let fits = |side: Side| room(side) >= needed(size, side);
245    let roomier = |side: Side| {
246        if room(side.opposite()) > room(side) {
247            side.opposite()
248        } else {
249            side
250        }
251    };
252
253    let requested = placement.side;
254    let opposite = requested.opposite();
255    if fits(requested) {
256        return requested;
257    }
258    if fits(opposite) {
259        return opposite;
260    }
261    if requested.is_vertical() {
262        return roomier(requested);
263    }
264    [Side::Bottom, Side::Top]
265        .into_iter()
266        .find(|side| fits(*side))
267        .unwrap_or_else(|| roomier(Side::Bottom))
268}
269
270/// The panel's extent across `side`, the length that must fit beside it.
271fn needed(size: Size, side: Side) -> f32 {
272    if side.is_vertical() {
273        size.height
274    } else {
275        size.width
276    }
277}
278
279/// Space between the anchor and the edge of `area` on one side, less the gap.
280fn room(anchor: Rectangle, area: Rectangle, gap: f32, side: Side) -> f32 {
281    match side {
282        Side::Top => anchor.y - gap - area.y,
283        Side::Bottom => area.y + area.height - (anchor.y + anchor.height + gap),
284        Side::Left => anchor.x - gap - area.x,
285        Side::Right => area.x + area.width - (anchor.x + anchor.width + gap),
286    }
287}
288
289/// The tallest a panel may be with [`Anchored::fit_height`]: `None` when
290/// it fits where [`place`] puts it as it is, otherwise the room on the
291/// roomier of above and below, however little, so the panel scrolls rather
292/// than covering its anchor. A panel placed on the left or right is only
293/// limited once it fits beside the anchor on neither side.
294pub fn fitted_height(
295    anchor: Rectangle,
296    size: Size,
297    viewport: Rectangle,
298    placement: Placement,
299) -> Option<f32> {
300    let area = viewport.shrink(MARGIN);
301    let side = placement.side;
302    let beside = |side: Side| room(anchor, area, placement.gap, side) >= size.width;
303    if !side.is_vertical() && (beside(side) || beside(side.opposite())) {
304        return None;
305    }
306    let above = room(anchor, area, placement.gap, Side::Top);
307    let below = room(anchor, area, placement.gap, Side::Bottom);
308    if above >= size.height || below >= size.height {
309        return None;
310    }
311    Some(above.max(below).max(0.0))
312}
313
314/// Keeps `value` within `low..=high`, preferring `low` when the range is empty.
315fn clamp(value: f32, low: f32, high: f32) -> f32 {
316    value.min(high).max(low)
317}
318
319/// The floating surface shared by popovers, menus, lists and dialogs: the
320/// popover colour, a subtle border and a restrained shadow.
321pub fn surface_style(tokens: &Tokens) -> container::Style {
322    container::Style {
323        background: Some(Background::Color(tokens.popover)),
324        text_color: Some(tokens.foreground),
325        border: Border {
326            color: tokens.border,
327            width: 1.0,
328            radius: radius::MD.into(),
329        },
330        shadow: shadow(tokens),
331        snap: true,
332    }
333}
334
335/// The shadow under every floating surface, stronger on a dark page.
336pub fn shadow(tokens: &Tokens) -> Shadow {
337    Shadow {
338        color: fade(Color::BLACK, if tokens.is_dark { 0.5 } else { 0.1 }),
339        offset: Vector::new(0.0, 4.0),
340        blur_radius: 12.0,
341    }
342}
343
344type OnKey<'a, Message> = Box<dyn Fn(&keys::Event) -> Option<Message> + 'a>;
345
346/// How an open panel behaves. Shared with the widgets in this crate that
347/// float a panel of their own.
348pub(crate) struct Behaviour<'a, Message> {
349    pub(crate) placement: Placement,
350    pub(crate) point: Option<Point>,
351    pub(crate) match_width: bool,
352    pub(crate) fit_height: bool,
353    pub(crate) on_dismiss: Option<Message>,
354    pub(crate) dismiss_keys: Vec<Chord>,
355    pub(crate) dismiss_on_anchor_press: bool,
356    pub(crate) dismiss_on_blur: bool,
357    pub(crate) pass_through: bool,
358    /// The panel opens and closes itself through [`State::open`]: a
359    /// dismissal or a press the content captured closes it.
360    pub(crate) closes_itself: bool,
361    pub(crate) on_key: Option<OnKey<'a, Message>>,
362    pub(crate) on_anchor_press: Option<Message>,
363    pub(crate) on_focus: Option<OnFocus<'a, Message>>,
364    /// The component kind the anchor and panel report to icedwright.
365    #[cfg(feature = "icedwright")]
366    pub(crate) kind: &'static str,
367}
368
369type OnFocus<'a, Message> = Box<dyn Fn(bool) -> Message + 'a>;
370
371impl<Message> Default for Behaviour<'_, Message> {
372    fn default() -> Self {
373        Self {
374            placement: Placement::default(),
375            point: None,
376            match_width: false,
377            fit_height: false,
378            on_dismiss: None,
379            dismiss_keys: vec![Chord::named(Named::Escape)],
380            dismiss_on_anchor_press: false,
381            dismiss_on_blur: false,
382            pass_through: false,
383            closes_itself: false,
384            on_key: None,
385            on_anchor_press: None,
386            on_focus: None,
387            #[cfg(feature = "icedwright")]
388            kind: "iced_cube::anchored",
389        }
390    }
391}
392
393impl<Message> Behaviour<'_, Message> {
394    fn can_dismiss(&self) -> bool {
395        self.on_dismiss.is_some() || self.closes_itself
396    }
397
398    fn watches_focus(&self) -> bool {
399        self.on_key.is_some() || self.dismiss_on_blur || self.on_focus.is_some()
400    }
401
402    /// The message for a change of focus inside the anchor, if it changed
403    /// and anyone listens.
404    fn focus_message(&self, was: bool, is: bool) -> Option<Message> {
405        if was == is {
406            return None;
407        }
408        self.on_focus.as_ref().map(|on_focus| on_focus(is))
409    }
410}
411
412/// What an anchor remembers between events.
413#[derive(Debug, Default)]
414pub(crate) struct State {
415    focused: bool,
416    /// An outside press dismissed the panel, so the anchor gives up focus
417    /// on the next event, without a second dismissal.
418    unfocus: bool,
419    /// Whether a panel that [closes itself](Behaviour::closes_itself) is open.
420    pub(crate) open: bool,
421    /// The side such a panel opened on. It stays there while open, so a
422    /// list that shrinks as it is filtered does not jump across the anchor.
423    pub(crate) side: Option<Side>,
424    /// Links the anchor to its panel for icedwright, made on first use.
425    #[cfg(feature = "icedwright")]
426    key: Option<icedwright_probe::Key>,
427}
428
429#[cfg(feature = "icedwright")]
430impl State {
431    pub(crate) fn key(&mut self) -> icedwright_probe::Key {
432        self.key
433            .get_or_insert_with(icedwright_probe::Key::unique)
434            .clone()
435    }
436}
437
438/// An anchor with a panel floating next to it. Convert it into an
439/// [`Element`] to render.
440pub struct Anchored<'a, Message> {
441    anchor: Element<'a, Message>,
442    content: Option<Element<'a, Message>>,
443    behaviour: Behaviour<'a, Message>,
444}
445
446impl<Message> std::fmt::Debug for Anchored<'_, Message> {
447    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448        let behaviour = &self.behaviour;
449        f.debug_struct("Anchored")
450            .field("open", &self.content.is_some())
451            .field("placement", &behaviour.placement)
452            .field("point", &behaviour.point)
453            .field("match_width", &behaviour.match_width)
454            .field("fit_height", &behaviour.fit_height)
455            .field("dismissable", &behaviour.on_dismiss.is_some())
456            .field("dismiss_keys", &behaviour.dismiss_keys)
457            .field("pass_through", &behaviour.pass_through)
458            .finish_non_exhaustive()
459    }
460}
461
462/// Wraps `anchor`. Nothing floats until [`content`](Anchored::content) is set.
463pub fn anchored<'a, Message>(anchor: impl Into<Element<'a, Message>>) -> Anchored<'a, Message> {
464    Anchored {
465        anchor: anchor.into(),
466        content: None,
467        behaviour: Behaviour::default(),
468    }
469}
470
471impl<'a, Message> Anchored<'a, Message> {
472    /// The component kind the anchor and panel report to icedwright tests,
473    /// such as `"my_app::picker"` for a component built on this one. Does
474    /// nothing without the `icedwright` feature.
475    #[cfg(feature = "icedwright")]
476    pub fn kind(mut self, kind: &'static str) -> Self {
477        self.behaviour.kind = kind;
478        self
479    }
480
481    /// The component kind the anchor and panel report to icedwright tests,
482    /// such as `"my_app::picker"` for a component built on this one. Does
483    /// nothing without the `icedwright` feature.
484    #[cfg(not(feature = "icedwright"))]
485    pub fn kind(self, _kind: &'static str) -> Self {
486        self
487    }
488
489    /// The floating panel. `None` keeps it closed.
490    pub fn content(mut self, content: Option<Element<'a, Message>>) -> Self {
491        self.content = content;
492        self
493    }
494
495    pub fn placement(mut self, placement: Placement) -> Self {
496        self.behaviour.placement = placement;
497        self
498    }
499
500    /// Anchors the panel to a point, relative to the anchor's top left
501    /// corner, instead of to the anchor's edges.
502    pub fn at(mut self, point: Point) -> Self {
503        self.behaviour.point = Some(point);
504        self
505    }
506
507    /// Makes the panel exactly as wide as the anchor, as a list under a
508    /// field is.
509    pub fn match_width(mut self, match_width: bool) -> Self {
510        self.behaviour.match_width = match_width;
511        self
512    }
513
514    /// When the panel fits on no side of the anchor, limits its height to
515    /// the roomier of above and below instead of shifting it over the
516    /// anchor; see [`fitted_height`]. For content that scrolls, such as a
517    /// long menu.
518    pub fn fit_height(mut self, fit: bool) -> Self {
519        self.behaviour.fit_height = fit;
520        self
521    }
522
523    /// Sent once when the panel is dismissed; see the module docs.
524    pub fn on_dismiss(self, message: Message) -> Self {
525        self.on_dismiss_maybe(Some(message))
526    }
527
528    /// Like [`on_dismiss`](Self::on_dismiss); `None` makes the panel
529    /// undismissable, so presses outside it pass through.
530    pub fn on_dismiss_maybe(mut self, message: Option<Message>) -> Self {
531        self.behaviour.on_dismiss = message;
532        self
533    }
534
535    /// The chords that dismiss the panel when the content and
536    /// [`on_key`](Self::on_key) leave them alone. Defaults to Escape. Pass
537    /// the chords of a component keymap's close action, so unbinding them
538    /// there works.
539    pub fn dismiss_keys(mut self, chords: impl IntoIterator<Item = Chord>) -> Self {
540        self.behaviour.dismiss_keys = chords.into_iter().collect();
541        self
542    }
543
544    /// Also dismiss on presses on the anchor itself, for anchors that do
545    /// not toggle the panel, such as a context menu area. The press still
546    /// reaches the anchor.
547    pub fn dismiss_on_anchor_press(mut self, dismiss: bool) -> Self {
548        self.behaviour.dismiss_on_anchor_press = dismiss;
549        self
550    }
551
552    /// Also dismiss when a focused widget inside the anchor, such as a text
553    /// field, loses focus.
554    pub fn dismiss_on_blur(mut self, dismiss: bool) -> Self {
555        self.behaviour.dismiss_on_blur = dismiss;
556        self
557    }
558
559    /// Lets a press outside the panel reach the widgets underneath after
560    /// dismissing it, for panels that are not modal, such as a popover.
561    pub fn pass_through(mut self, pass_through: bool) -> Self {
562        self.behaviour.pass_through = pass_through;
563        self
564    }
565
566    /// Resolves key presses the content leaves, while the panel is open or
567    /// something in the anchor has focus. Returning a message sends it and
568    /// captures the key.
569    pub fn on_key(mut self, on_key: impl Fn(&keys::Event) -> Option<Message> + 'a) -> Self {
570        self.behaviour.on_key = Some(Box::new(on_key));
571        self
572    }
573
574    /// Sent with `true` when a widget inside the anchor, such as a text
575    /// field, gains focus, and with `false` when it loses it.
576    pub fn on_focus(mut self, on_focus: impl Fn(bool) -> Message + 'a) -> Self {
577        self.behaviour.on_focus = Some(Box::new(on_focus));
578        self
579    }
580
581    /// Sent when the pointer is pressed on the anchor, before the anchor
582    /// sees the press.
583    pub fn on_anchor_press_maybe(mut self, message: Option<Message>) -> Self {
584        self.behaviour.on_anchor_press = message;
585        self
586    }
587}
588
589impl<'a, Message: Clone + 'a> From<Anchored<'a, Message>> for Element<'a, Message> {
590    fn from(anchored: Anchored<'a, Message>) -> Self {
591        Element::new(anchored)
592    }
593}
594
595impl<Message: Clone> Widget<Message, Theme, Renderer> for Anchored<'_, Message> {
596    fn tag(&self) -> tree::Tag {
597        tree::Tag::of::<State>()
598    }
599
600    fn state(&self) -> tree::State {
601        tree::State::new(State::default())
602    }
603
604    fn size(&self) -> Size<Length> {
605        self.anchor.as_widget().size()
606    }
607
608    fn size_hint(&self) -> Size<Length> {
609        self.anchor.as_widget().size_hint()
610    }
611
612    fn children(&self) -> Vec<Tree> {
613        std::iter::once(&self.anchor)
614            .chain(&self.content)
615            .map(Tree::new)
616            .collect()
617    }
618
619    fn diff(&self, tree: &mut Tree) {
620        match &self.content {
621            Some(content) => tree.diff_children(&[&self.anchor, content]),
622            None => tree.diff_children(&[&self.anchor]),
623        }
624    }
625
626    fn layout(
627        &mut self,
628        tree: &mut Tree,
629        renderer: &Renderer,
630        limits: &layout::Limits,
631    ) -> layout::Node {
632        self.anchor
633            .as_widget_mut()
634            .layout(&mut tree.children[0], renderer, limits)
635    }
636
637    fn draw(
638        &self,
639        tree: &Tree,
640        renderer: &mut Renderer,
641        theme: &Theme,
642        style: &renderer::Style,
643        layout: Layout<'_>,
644        cursor: mouse::Cursor,
645        viewport: &Rectangle,
646    ) {
647        self.anchor.as_widget().draw(
648            &tree.children[0],
649            renderer,
650            theme,
651            style,
652            layout,
653            cursor,
654            viewport,
655        );
656    }
657
658    fn operate(
659        &mut self,
660        tree: &mut Tree,
661        layout: Layout<'_>,
662        renderer: &Renderer,
663        operation: &mut dyn Operation,
664    ) {
665        #[cfg(feature = "icedwright")]
666        {
667            let state = tree.state.downcast_mut::<State>();
668            let shown = self.content.is_some() && (!self.behaviour.closes_itself || state.open);
669            if shown {
670                let key = state.key();
671                let kind = self.behaviour.kind;
672                icedwright_probe::report(operation, layout.bounds(), || {
673                    icedwright_probe::Annotation::new()
674                        .owns(key)
675                        .component(kind)
676                });
677                let anchor = &mut self.anchor;
678                let child = &mut tree.children[0];
679                operation.traverse(&mut |operation| {
680                    anchor
681                        .as_widget_mut()
682                        .operate(child, layout, renderer, operation);
683                });
684                return;
685            }
686        }
687        self.anchor
688            .as_widget_mut()
689            .operate(&mut tree.children[0], layout, renderer, operation);
690    }
691
692    fn update(
693        &mut self,
694        tree: &mut Tree,
695        event: &Event,
696        layout: Layout<'_>,
697        cursor: mouse::Cursor,
698        renderer: &Renderer,
699        clipboard: &mut dyn Clipboard,
700        shell: &mut Shell<'_, Message>,
701        viewport: &Rectangle,
702    ) {
703        let Tree {
704            state, children, ..
705        } = tree;
706        let state = state.downcast_mut::<State>();
707        let Some(anchor_tree) = children.first_mut() else {
708            return;
709        };
710        let behaviour = &self.behaviour;
711
712        if state.unfocus {
713            state.unfocus = false;
714            if let Some(message) = behaviour.focus_message(state.focused, false) {
715                shell.publish(message);
716            }
717            state.focused = false;
718            self.anchor
719                .as_widget_mut()
720                .operate(anchor_tree, layout, renderer, &mut Unfocus);
721            shell.request_redraw();
722        }
723
724        if state.focused
725            && let Some(message) = key_message(behaviour, event)
726        {
727            shell.publish(message);
728            shell.capture_event();
729            return;
730        }
731
732        if is_press(event)
733            && cursor.is_over(layout.bounds())
734            && let Some(message) = &behaviour.on_anchor_press
735        {
736            shell.publish(message.clone());
737        }
738
739        self.anchor.as_widget_mut().update(
740            anchor_tree,
741            event,
742            layout,
743            cursor,
744            renderer,
745            clipboard,
746            shell,
747            viewport,
748        );
749
750        if !behaviour.watches_focus() {
751            return;
752        }
753        let mut focus = FindFocus::default();
754        self.anchor
755            .as_widget_mut()
756            .operate(anchor_tree, layout, renderer, &mut focus);
757        if state.focused
758            && !focus.0
759            && behaviour.dismiss_on_blur
760            && let Some(message) = &behaviour.on_dismiss
761        {
762            shell.publish(message.clone());
763        }
764        if let Some(message) = behaviour.focus_message(state.focused, focus.0) {
765            shell.publish(message);
766        }
767        state.focused = focus.0;
768    }
769
770    fn mouse_interaction(
771        &self,
772        tree: &Tree,
773        layout: Layout<'_>,
774        cursor: mouse::Cursor,
775        viewport: &Rectangle,
776        renderer: &Renderer,
777    ) -> mouse::Interaction {
778        self.anchor.as_widget().mouse_interaction(
779            &tree.children[0],
780            layout,
781            cursor,
782            viewport,
783            renderer,
784        )
785    }
786
787    fn overlay<'b>(
788        &'b mut self,
789        tree: &'b mut Tree,
790        layout: Layout<'b>,
791        renderer: &Renderer,
792        viewport: &Rectangle,
793        translation: Vector,
794    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
795        let Self {
796            anchor,
797            content,
798            behaviour,
799        } = self;
800        let Tree {
801            state, children, ..
802        } = tree;
803        let mut trees = children.iter_mut();
804        let anchor_tree = trees.next()?;
805        let trigger = layout.bounds() + translation;
806
807        // While the panel is open the anchor's own overlays, such as its
808        // tooltip, stay hidden.
809        let Some((content, tree)) = content.as_mut().zip(trees.next()) else {
810            return anchor.as_widget_mut().overlay(
811                anchor_tree,
812                layout,
813                renderer,
814                viewport,
815                translation,
816            );
817        };
818        Some(floating(
819            content,
820            tree,
821            state.downcast_mut::<State>(),
822            behaviour,
823            trigger,
824        ))
825    }
826}
827
828/// The overlay drawing a panel for `trigger`, the anchor's bounds in
829/// window coordinates.
830pub(crate) fn floating<'a, 'b, Message: Clone>(
831    content: &'b mut Element<'a, Message>,
832    tree: &'b mut Tree,
833    state: &'b mut State,
834    behaviour: &'b Behaviour<'a, Message>,
835    trigger: Rectangle,
836) -> overlay::Element<'b, Message, Theme, Renderer> {
837    let target = match behaviour.point {
838        Some(point) => Rectangle::new(
839            trigger.position() + Vector::new(point.x, point.y),
840            Size::ZERO,
841        ),
842        None => trigger,
843    };
844    overlay::Element::new(Box::new(Floating {
845        content,
846        tree,
847        state,
848        behaviour,
849        target,
850        trigger,
851    }))
852}
853
854/// The overlay drawing the panel. Its node covers the whole window so the
855/// panel's shadow is never clipped; the panel is its only child.
856struct Floating<'a, 'b, Message> {
857    content: &'b mut Element<'a, Message>,
858    tree: &'b mut Tree,
859    state: &'b mut State,
860    behaviour: &'b Behaviour<'a, Message>,
861    target: Rectangle,
862    trigger: Rectangle,
863}
864
865impl<Message: Clone> Floating<'_, '_, Message> {
866    fn dismiss(&mut self, shell: &mut Shell<'_, Message>) {
867        if self.behaviour.closes_itself {
868            self.state.open = false;
869            shell.request_redraw();
870        }
871        if self.behaviour.dismiss_on_blur {
872            self.state.unfocus = true;
873        }
874        if let Some(message) = &self.behaviour.on_dismiss {
875            shell.publish(message.clone());
876        }
877    }
878}
879
880/// The message [`Behaviour::on_key`] sends for a key press, if any.
881fn key_message<Message>(behaviour: &Behaviour<'_, Message>, event: &Event) -> Option<Message> {
882    let Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event else {
883        return None;
884    };
885    let on_key = behaviour.on_key.as_ref()?;
886    on_key(&keys::Event {
887        key: key.clone(),
888        modifiers: *modifiers,
889    })
890}
891
892fn is_dismiss_key<Message>(behaviour: &Behaviour<'_, Message>, event: &Event) -> bool {
893    let Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event else {
894        return false;
895    };
896    behaviour
897        .dismiss_keys
898        .iter()
899        .any(|chord| chord.matches(key, *modifiers))
900}
901
902fn is_press(event: &Event) -> bool {
903    matches!(
904        event,
905        Event::Mouse(mouse::Event::ButtonPressed(_))
906            | Event::Touch(touch::Event::FingerPressed { .. })
907    )
908}
909
910fn is_release(event: &Event) -> bool {
911    matches!(
912        event,
913        Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
914            | Event::Touch(touch::Event::FingerLifted { .. })
915    )
916}
917
918/// Where a mouse or touch press landed, if the event is one.
919fn press_position(event: &Event, cursor: mouse::Cursor) -> Option<Point> {
920    match event {
921        Event::Mouse(mouse::Event::ButtonPressed(_)) => cursor.position(),
922        Event::Touch(touch::Event::FingerPressed { position, .. }) => Some(*position),
923        _ => None,
924    }
925}
926
927fn is_pointer_input(event: &Event) -> bool {
928    matches!(
929        event,
930        Event::Mouse(
931            mouse::Event::ButtonPressed(_)
932                | mouse::Event::ButtonReleased(_)
933                | mouse::Event::WheelScrolled { .. }
934        ) | Event::Touch(_)
935    )
936}
937
938impl<Message: Clone> overlay::Overlay<Message, Theme, Renderer> for Floating<'_, '_, Message> {
939    fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node {
940        let viewport = Rectangle::with_size(bounds);
941        let room = viewport.shrink(MARGIN).size();
942        let room = Size::new(room.width.max(0.0), room.height.max(0.0));
943        let match_width = self.behaviour.match_width;
944        let trigger_width = self.trigger.width;
945        let limits = |height: f32| {
946            if match_width {
947                let width = trigger_width.min(room.width);
948                layout::Limits::new(Size::new(width, 0.0), Size::new(width, height))
949            } else {
950                layout::Limits::new(Size::ZERO, Size::new(room.width, height))
951            }
952        };
953        let placement = self.behaviour.placement;
954        let mut node =
955            self.content
956                .as_widget_mut()
957                .layout(self.tree, renderer, &limits(room.height));
958        let fitted = self
959            .behaviour
960            .fit_height
961            .then(|| fitted_height(self.target, node.size(), viewport, placement))
962            .flatten();
963        if let Some(height) = fitted {
964            node = self
965                .content
966                .as_widget_mut()
967                .layout(self.tree, renderer, &limits(height));
968        }
969        let size = node.size();
970        let side = match self.state.side {
971            Some(side) if self.behaviour.closes_itself => side,
972            _ => side_for(self.target, size, viewport, placement),
973        };
974        if self.behaviour.closes_itself {
975            self.state.side = Some(side);
976        }
977        let panel = place_on(self.target, size, viewport, placement, side);
978        layout::Node::with_children(bounds, vec![node.move_to(panel.position())])
979    }
980
981    fn draw(
982        &self,
983        renderer: &mut Renderer,
984        theme: &Theme,
985        style: &renderer::Style,
986        layout: Layout<'_>,
987        cursor: mouse::Cursor,
988    ) {
989        let Some(panel) = layout.children().next() else {
990            return;
991        };
992        self.content.as_widget().draw(
993            self.tree,
994            renderer,
995            theme,
996            style,
997            panel,
998            cursor,
999            &layout.bounds(),
1000        );
1001    }
1002
1003    fn operate(&mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
1004        let Some(panel) = layout.children().next() else {
1005            return;
1006        };
1007        #[cfg(feature = "icedwright")]
1008        {
1009            let key = self.state.key();
1010            let kind = self.behaviour.kind;
1011            icedwright_probe::report(operation, panel.bounds(), || {
1012                icedwright_probe::Annotation::new().key(key).component(kind)
1013            });
1014            let content = &mut self.content;
1015            let tree = &mut *self.tree;
1016            operation.traverse(&mut |operation| {
1017                content
1018                    .as_widget_mut()
1019                    .operate(tree, panel, renderer, operation);
1020            });
1021        }
1022        #[cfg(not(feature = "icedwright"))]
1023        self.content
1024            .as_widget_mut()
1025            .operate(self.tree, panel, renderer, operation);
1026    }
1027
1028    fn update(
1029        &mut self,
1030        event: &Event,
1031        layout: Layout<'_>,
1032        cursor: mouse::Cursor,
1033        renderer: &Renderer,
1034        clipboard: &mut dyn Clipboard,
1035        shell: &mut Shell<'_, Message>,
1036    ) {
1037        let Some(panel) = layout.children().next() else {
1038            return;
1039        };
1040
1041        self.content.as_widget_mut().update(
1042            self.tree,
1043            event,
1044            panel,
1045            cursor,
1046            renderer,
1047            clipboard,
1048            shell,
1049            &layout.bounds(),
1050        );
1051        if shell.is_event_captured() {
1052            // A row took the click, so the choice is made.
1053            if self.behaviour.closes_itself && is_release(event) {
1054                self.state.open = false;
1055                shell.request_redraw();
1056            }
1057            return;
1058        }
1059
1060        if let Some(message) = key_message(self.behaviour, event) {
1061            shell.publish(message);
1062            shell.capture_event();
1063            return;
1064        }
1065        if is_dismiss_key(self.behaviour, event) && self.behaviour.can_dismiss() {
1066            self.dismiss(shell);
1067            shell.capture_event();
1068            return;
1069        }
1070        if !is_pointer_input(event) {
1071            return;
1072        }
1073
1074        let bounds = panel.bounds();
1075        if cursor.is_over(bounds) {
1076            shell.capture_event();
1077            return;
1078        }
1079        let Some(position) = press_position(event, cursor) else {
1080            return;
1081        };
1082        if bounds.contains(position) {
1083            shell.capture_event();
1084            return;
1085        }
1086        let on_anchor = self.trigger.contains(position);
1087        if (on_anchor && !self.behaviour.dismiss_on_anchor_press) || !self.behaviour.can_dismiss() {
1088            return;
1089        }
1090        self.dismiss(shell);
1091        if !on_anchor && !self.behaviour.pass_through {
1092            shell.capture_event();
1093        }
1094    }
1095
1096    fn mouse_interaction(
1097        &self,
1098        layout: Layout<'_>,
1099        cursor: mouse::Cursor,
1100        renderer: &Renderer,
1101    ) -> mouse::Interaction {
1102        let Some(panel) = layout.children().next() else {
1103            return mouse::Interaction::None;
1104        };
1105        if !cursor.is_over(panel.bounds()) {
1106            return mouse::Interaction::None;
1107        }
1108        self.content
1109            .as_widget()
1110            .mouse_interaction(self.tree, panel, cursor, &layout.bounds(), renderer)
1111            .max(mouse::Interaction::Idle)
1112    }
1113
1114    fn overlay<'c>(
1115        &'c mut self,
1116        layout: Layout<'c>,
1117        renderer: &Renderer,
1118    ) -> Option<overlay::Element<'c, Message, Theme, Renderer>> {
1119        let panel = layout.children().next()?;
1120        let viewport = layout.bounds();
1121        self.content
1122            .as_widget_mut()
1123            .overlay(self.tree, panel, renderer, &viewport, Vector::ZERO)
1124    }
1125}
1126
1127/// Whether any focusable widget in a subtree has focus.
1128#[derive(Default)]
1129struct FindFocus(bool);
1130
1131impl Operation for FindFocus {
1132    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
1133        operate(self);
1134    }
1135
1136    fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) {
1137        self.0 |= state.is_focused();
1138    }
1139}
1140
1141/// Takes focus away from every widget in a subtree.
1142struct Unfocus;
1143
1144impl Operation for Unfocus {
1145    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
1146        operate(self);
1147    }
1148
1149    fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) {
1150        if state.is_focused() {
1151            state.unfocus();
1152        }
1153    }
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158    use super::*;
1159    use crate::theme::{dark, light};
1160    use iced::keyboard::{Key, Modifiers};
1161
1162    const VIEWPORT: Rectangle = Rectangle {
1163        x: 0.0,
1164        y: 0.0,
1165        width: 400.0,
1166        height: 300.0,
1167    };
1168
1169    fn anchor() -> Rectangle {
1170        Rectangle::new(Point::new(150.0, 100.0), Size::new(100.0, 40.0))
1171    }
1172
1173    const PANEL: Size = Size::new(60.0, 50.0);
1174
1175    fn at(side: Side, align: Align) -> Point {
1176        place(anchor(), PANEL, VIEWPORT, Placement::new(side, align)).position()
1177    }
1178
1179    #[test]
1180    fn defaults_to_bottom_centre_with_a_small_gap() {
1181        let placement = Placement::default();
1182        assert_eq!(placement.side, Side::Bottom);
1183        assert_eq!(placement.align, Align::Center);
1184        assert_eq!(placement.gap, GAP);
1185        assert_eq!(placement.offset, 0.0);
1186    }
1187
1188    #[test]
1189    fn each_side_sits_outside_the_anchor_with_the_gap() {
1190        assert_eq!(at(Side::Bottom, Align::Start), Point::new(150.0, 144.0));
1191        assert_eq!(at(Side::Top, Align::Start), Point::new(150.0, 46.0));
1192        assert_eq!(at(Side::Left, Align::Start), Point::new(86.0, 100.0));
1193        assert_eq!(at(Side::Right, Align::Start), Point::new(254.0, 100.0));
1194    }
1195
1196    #[test]
1197    fn alignment_moves_along_the_side() {
1198        assert_eq!(at(Side::Bottom, Align::Center).x, 170.0);
1199        assert_eq!(at(Side::Bottom, Align::End).x, 190.0);
1200        assert_eq!(at(Side::Right, Align::Center).y, 95.0);
1201        assert_eq!(at(Side::Right, Align::End).y, 90.0);
1202    }
1203
1204    #[test]
1205    fn offset_shifts_away_from_the_aligned_edge() {
1206        let placement = Placement::new(Side::Bottom, Align::Start).offset(5.0);
1207        let start = place(anchor(), PANEL, VIEWPORT, placement);
1208        assert_eq!(start.x, 155.0);
1209        let placement = Placement::new(Side::Bottom, Align::End).offset(5.0);
1210        let end = place(anchor(), PANEL, VIEWPORT, placement);
1211        assert_eq!(end.x, 185.0);
1212    }
1213
1214    #[test]
1215    fn flips_to_the_opposite_side_when_there_is_no_room() {
1216        let low = Rectangle::new(Point::new(150.0, 230.0), Size::new(100.0, 40.0));
1217        let panel = place(
1218            low,
1219            PANEL,
1220            VIEWPORT,
1221            Placement::new(Side::Bottom, Align::Start),
1222        );
1223        assert_eq!(panel.y, 230.0 - GAP - PANEL.height);
1224
1225        let left_edge = Rectangle::new(Point::new(20.0, 100.0), Size::new(40.0, 40.0));
1226        let panel = place(
1227            left_edge,
1228            PANEL,
1229            VIEWPORT,
1230            Placement::new(Side::Left, Align::Start),
1231        );
1232        assert_eq!(panel.x, 60.0 + GAP);
1233    }
1234
1235    #[test]
1236    fn stays_put_when_neither_side_fits_and_the_requested_one_is_larger() {
1237        let tall = Size::new(60.0, 290.0);
1238        let panel = place(
1239            anchor(),
1240            tall,
1241            VIEWPORT,
1242            Placement::new(Side::Bottom, Align::Start),
1243        );
1244        assert_eq!(panel.y, MARGIN, "shifted up to fit, pinned at the margin");
1245    }
1246
1247    #[test]
1248    fn fitted_height_keeps_a_tall_panel_off_its_anchor() {
1249        let below = Placement::new(Side::Bottom, Align::Start);
1250        assert_eq!(fitted_height(anchor(), PANEL, VIEWPORT, below), None);
1251        let tall = Size::new(60.0, 290.0);
1252        let room_below = VIEWPORT.height - MARGIN - (140.0 + GAP);
1253        assert_eq!(
1254            fitted_height(anchor(), tall, VIEWPORT, below),
1255            Some(room_below)
1256        );
1257        let panel = place(anchor(), Size::new(60.0, room_below), VIEWPORT, below);
1258        assert_eq!(panel.y, 140.0 + GAP, "stays below the anchor");
1259
1260        let low = Rectangle::new(Point::new(150.0, 200.0), Size::new(100.0, 40.0));
1261        let room_above = 200.0 - GAP - MARGIN;
1262        assert_eq!(fitted_height(low, tall, VIEWPORT, below), Some(room_above));
1263        let panel = place(low, Size::new(60.0, room_above), VIEWPORT, below);
1264        assert_eq!(panel.y + panel.height, 200.0 - GAP, "flips above it");
1265
1266        let beside = Placement::new(Side::Right, Align::Start);
1267        assert_eq!(fitted_height(anchor(), tall, VIEWPORT, beside), None);
1268    }
1269
1270    #[test]
1271    fn fitted_height_uses_the_roomier_side_however_little_room_it_has() {
1272        let below = Placement::new(Side::Bottom, Align::Start);
1273        let tall = Size::new(60.0, 290.0);
1274        let squeezed = Rectangle::new(Point::new(150.0, 100.0), Size::new(100.0, 120.0));
1275        let room_above = 100.0 - GAP - MARGIN;
1276        assert_eq!(
1277            fitted_height(squeezed, tall, VIEWPORT, below),
1278            Some(room_above)
1279        );
1280        let panel = place(squeezed, Size::new(60.0, room_above), VIEWPORT, below);
1281        assert_eq!(panel.y + panel.height, 100.0 - GAP, "clear of the anchor");
1282
1283        let filling = Rectangle::new(Point::new(0.0, 0.0), Size::new(400.0, 300.0));
1284        assert_eq!(fitted_height(filling, tall, VIEWPORT, below), Some(0.0));
1285    }
1286
1287    #[test]
1288    fn a_menu_low_in_the_window_opens_above_at_full_height() {
1289        let point = Rectangle::new(Point::new(100.0, 230.0), Size::ZERO);
1290        let menu = Size::new(180.0, 200.0);
1291        let placement = Placement::new(Side::Bottom, Align::Start).gap(0.0);
1292        assert_eq!(fitted_height(point, menu, VIEWPORT, placement), None);
1293        let panel = place(point, menu, VIEWPORT, placement);
1294        assert_eq!(panel.y + panel.height, 230.0, "flipped above the point");
1295    }
1296
1297    #[test]
1298    fn a_side_panel_that_fits_neither_side_moves_below_its_anchor() {
1299        let narrow = Rectangle::new(Point::new(0.0, 0.0), Size::new(320.0, 300.0));
1300        let row = Rectangle::new(Point::new(40.0, 100.0), Size::new(216.0, 32.0));
1301        let submenu = Size::new(224.0, 120.0);
1302        let placement = Placement::new(Side::Right, Align::Start).gap(4.0);
1303        let panel = place(row, submenu, narrow, placement);
1304        assert_eq!(panel.y, 132.0 + 4.0, "below the row, clear of its label");
1305        assert_eq!(panel.x, 40.0, "lined up with the row");
1306
1307        let low_row = Rectangle::new(Point::new(40.0, 200.0), Size::new(216.0, 32.0));
1308        let panel = place(low_row, submenu, narrow, placement);
1309        assert_eq!(panel.y + panel.height, 200.0 - 4.0, "above the row");
1310
1311        let wide = Rectangle::new(Point::new(0.0, 0.0), Size::new(600.0, 300.0));
1312        let panel = place(row, submenu, wide, placement);
1313        assert_eq!(panel.x, 256.0 + 4.0, "beside the row when it fits");
1314        assert_eq!(fitted_height(row, submenu, wide, placement), None);
1315    }
1316
1317    #[test]
1318    fn a_tall_side_panel_without_room_beside_scrolls_on_the_roomier_side() {
1319        let narrow = Rectangle::new(Point::new(0.0, 0.0), Size::new(320.0, 300.0));
1320        let row = Rectangle::new(Point::new(40.0, 160.0), Size::new(216.0, 32.0));
1321        let submenu = Size::new(224.0, 180.0);
1322        let placement = Placement::new(Side::Right, Align::Start).gap(4.0);
1323        assert_eq!(
1324            fitted_height(row, submenu, narrow, placement),
1325            Some(160.0 - 4.0 - MARGIN)
1326        );
1327        let fitted = Size::new(224.0, 160.0 - 4.0 - MARGIN);
1328        let panel = place(row, fitted, narrow, placement);
1329        assert_eq!(panel.y, MARGIN);
1330        assert_eq!(panel.y + panel.height, 160.0 - 4.0, "clear of the row");
1331    }
1332
1333    #[test]
1334    fn mirrors_the_alignment_when_it_would_overflow() {
1335        let right_edge = Rectangle::new(Point::new(360.0, 100.0), Size::new(30.0, 30.0));
1336        let panel = place(
1337            right_edge,
1338            PANEL,
1339            VIEWPORT,
1340            Placement::new(Side::Bottom, Align::Start),
1341        );
1342        assert_eq!(panel.x, 390.0 - PANEL.width);
1343    }
1344
1345    #[test]
1346    fn shifts_inside_the_margin_when_nothing_else_fits() {
1347        let corner = Rectangle::new(Point::new(0.0, 0.0), Size::new(10.0, 10.0));
1348        let panel = place(
1349            corner,
1350            PANEL,
1351            VIEWPORT,
1352            Placement::new(Side::Left, Align::Center),
1353        );
1354        assert_eq!(panel.x, 10.0 + GAP, "flipped to the right");
1355        assert_eq!(panel.y, MARGIN, "shifted down to the margin");
1356    }
1357
1358    #[test]
1359    fn a_list_near_the_bottom_keeps_the_margin() {
1360        let field = Rectangle::new(Point::new(20.0, 200.0), Size::new(200.0, 36.0));
1361        let list = Size::new(200.0, 80.0);
1362        let placement = Placement::new(Side::Bottom, Align::Start);
1363        let panel = place(field, list, VIEWPORT, placement);
1364        assert_eq!(panel.y, 200.0 - GAP - list.height, "flips above the field");
1365
1366        let wide = Size::new(420.0, 40.0);
1367        let panel = place(field, wide, VIEWPORT, placement);
1368        assert_eq!(panel.x, MARGIN, "clamped inside the window");
1369    }
1370
1371    #[test]
1372    fn a_point_anchor_opens_below_and_right_then_flips_near_edges() {
1373        let point = |x, y| Rectangle::new(Point::new(x, y), Size::ZERO);
1374        let placement = Placement::new(Side::Bottom, Align::Start).gap(0.0);
1375        assert_eq!(
1376            place(point(100.0, 100.0), PANEL, VIEWPORT, placement).position(),
1377            Point::new(100.0, 100.0)
1378        );
1379        assert_eq!(
1380            place(point(380.0, 280.0), PANEL, VIEWPORT, placement).position(),
1381            Point::new(320.0, 230.0)
1382        );
1383    }
1384
1385    #[test]
1386    fn a_panel_larger_than_the_window_is_pinned_top_left() {
1387        let huge = Size::new(1000.0, 1000.0);
1388        let panel = place(anchor(), huge, VIEWPORT, Placement::default());
1389        assert_eq!(panel.position(), Point::new(MARGIN, MARGIN));
1390        assert_eq!(panel.size(), huge);
1391    }
1392
1393    #[test]
1394    fn sides_and_alignments_mirror() {
1395        for side in Side::ALL {
1396            assert_eq!(side.opposite().opposite(), side);
1397            assert_ne!(side.opposite(), side);
1398        }
1399        assert_eq!(Align::Center.mirrored(), Align::Center);
1400        assert_eq!(Align::Start.mirrored(), Align::End);
1401    }
1402
1403    #[test]
1404    fn surface_uses_the_popover_colour_a_border_and_a_shadow() {
1405        for theme in [light(), dark()] {
1406            let tokens = Tokens::of(&theme);
1407            let style = surface_style(&tokens);
1408            assert_eq!(style.background, Some(Background::Color(tokens.popover)));
1409            assert_eq!(style.text_color, Some(tokens.foreground));
1410            assert_eq!(style.border.color, tokens.border);
1411            assert_eq!(style.border.width, 1.0);
1412            assert_eq!(style.border.radius, radius::MD.into());
1413            assert_eq!(style.shadow, shadow(&tokens));
1414            assert_eq!(style.shadow.offset, Vector::new(0.0, 4.0));
1415            assert_eq!(style.shadow.blur_radius, 12.0);
1416        }
1417        let light = shadow(&Tokens::of(&light())).color.a;
1418        let dark = shadow(&Tokens::of(&dark())).color.a;
1419        assert!((light - 0.1).abs() < 1e-6);
1420        assert!((dark - 0.5).abs() < 1e-6);
1421    }
1422
1423    #[test]
1424    fn builder_starts_closed_and_undismissable_with_escape_bound() {
1425        let anchored: Anchored<'_, ()> = anchored(iced::widget::text("Anchor"));
1426        let behaviour = &anchored.behaviour;
1427        assert!(anchored.content.is_none());
1428        assert!(behaviour.on_dismiss.is_none());
1429        assert!(behaviour.point.is_none());
1430        assert!(!behaviour.dismiss_on_anchor_press);
1431        assert!(!behaviour.dismiss_on_blur);
1432        assert!(!behaviour.pass_through);
1433        assert!(!behaviour.match_width);
1434        assert_eq!(behaviour.dismiss_keys, vec![Chord::named(Named::Escape)]);
1435        assert!(!behaviour.can_dismiss());
1436        assert!(!behaviour.watches_focus());
1437    }
1438
1439    #[test]
1440    fn builder_sets_every_option() {
1441        let anchored: Anchored<'_, u8> = anchored(iced::widget::text("Anchor"))
1442            .at(Point::new(3.0, 4.0))
1443            .match_width(true)
1444            .on_dismiss(1)
1445            .dismiss_keys([Chord::character('q')])
1446            .dismiss_on_anchor_press(true)
1447            .dismiss_on_blur(true)
1448            .pass_through(true)
1449            .on_anchor_press_maybe(Some(2))
1450            .on_key(|_| Some(3))
1451            .on_focus(|focused| if focused { 4 } else { 5 });
1452        let behaviour = &anchored.behaviour;
1453        assert_eq!(behaviour.focus_message(false, true), Some(4));
1454        assert_eq!(behaviour.focus_message(true, false), Some(5));
1455        assert_eq!(behaviour.focus_message(true, true), None);
1456        assert_eq!(behaviour.point, Some(Point::new(3.0, 4.0)));
1457        assert!(behaviour.match_width && behaviour.pass_through);
1458        assert!(behaviour.dismiss_on_anchor_press && behaviour.dismiss_on_blur);
1459        assert_eq!(behaviour.on_dismiss, Some(1));
1460        assert_eq!(behaviour.on_anchor_press, Some(2));
1461        assert_eq!(behaviour.dismiss_keys, vec![Chord::character('q')]);
1462        assert!(behaviour.can_dismiss() && behaviour.watches_focus());
1463    }
1464
1465    fn key_press(key: Key, modifiers: Modifiers) -> Event {
1466        Event::Keyboard(keyboard::Event::KeyPressed {
1467            key: key.clone(),
1468            modified_key: key,
1469            physical_key: keyboard::key::Physical::Unidentified(
1470                keyboard::key::NativeCode::Unidentified,
1471            ),
1472            location: keyboard::Location::Standard,
1473            modifiers,
1474            text: None,
1475            repeat: false,
1476        })
1477    }
1478
1479    #[test]
1480    fn keys_resolve_through_on_key_then_the_dismiss_chords() {
1481        let behaviour: Behaviour<'_, u8> = Behaviour {
1482            on_key: Some(Box::new(|key: &keys::Event| {
1483                (key.key == Key::Named(Named::ArrowDown)).then_some(7)
1484            })),
1485            ..Behaviour::default()
1486        };
1487        let down = key_press(Key::Named(Named::ArrowDown), Modifiers::empty());
1488        let escape = key_press(Key::Named(Named::Escape), Modifiers::empty());
1489        let shift_escape = key_press(Key::Named(Named::Escape), Modifiers::SHIFT);
1490        assert_eq!(key_message(&behaviour, &down), Some(7));
1491        assert_eq!(key_message(&behaviour, &escape), None);
1492        assert!(is_dismiss_key(&behaviour, &escape));
1493        assert!(!is_dismiss_key(&behaviour, &shift_escape));
1494        assert!(!is_dismiss_key(&behaviour, &down));
1495
1496        let unbound: Behaviour<'_, u8> = Behaviour {
1497            dismiss_keys: Vec::new(),
1498            ..Behaviour::default()
1499        };
1500        assert!(!is_dismiss_key(&unbound, &escape));
1501    }
1502
1503    #[test]
1504    fn press_position_only_reports_presses() {
1505        let cursor = mouse::Cursor::Available(Point::new(3.0, 4.0));
1506        let pressed = Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right));
1507        let released = Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left));
1508        assert_eq!(press_position(&pressed, cursor), Some(Point::new(3.0, 4.0)));
1509        assert_eq!(press_position(&released, cursor), None);
1510        assert_eq!(press_position(&pressed, mouse::Cursor::Unavailable), None);
1511        assert!(is_pointer_input(&released));
1512        assert!(is_release(&released));
1513        assert!(is_press(&pressed));
1514        assert!(!is_release(&pressed));
1515        assert!(!is_pointer_input(&Event::Mouse(mouse::Event::CursorLeft)));
1516    }
1517}