Skip to main content

iced_cube/overlay/
dialog.rs

1//! A modal window over a dimmed scrim, with a title, a description, body
2//! content and a footer of actions.
3//!
4//! The app owns whether the dialog is open. [`dialog`] wraps the app's
5//! content (the base) and, while open, draws a scrim over it that blocks
6//! every click and key press from reaching the base.
7//!
8//! ```no_run
9//! use iced::Element;
10//! use iced::widget::center;
11//! use iced_cube::button;
12//! use iced_cube::overlay::dialog::dialog;
13//!
14//! #[derive(Debug, Clone)]
15//! enum Message {
16//!     Open,
17//!     Close,
18//! }
19//!
20//! struct App {
21//!     open: bool,
22//! }
23//!
24//! impl App {
25//!     fn update(&mut self, message: Message) {
26//!         self.open = matches!(message, Message::Open);
27//!     }
28//!
29//!     fn view(&self) -> Element<'_, Message> {
30//!         dialog(center(button("Open").on_press(Message::Open)))
31//!             .open(self.open)
32//!             .title("Share link")
33//!             .description("Anyone with the link can view this document.")
34//!             .action(button("Done").on_press(Message::Close))
35//!             .on_dismiss(Message::Close)
36//!             .into()
37//!     }
38//! }
39//! ```
40//!
41//! The dialog handles its own keys through a [`Keymap`], so an app needs no
42//! subscription for it: Escape dismisses, Enter sends the
43//! [`on_confirm`](Dialog::on_confirm) message, and Tab and Shift+Tab move
44//! focus through everything focusable inside the dialog without leaving
45//! it, scrolling the body to show it. That is every text field and this
46//! library's buttons, icon buttons, switches, checkboxes, radios, toggles
47//! and selects, including the footer actions and the close button, in the
48//! order they are laid out. A focused control rings and Space or Enter
49//! works it; a focused select opens on Space, Enter or ArrowDown. Opening
50//! the dialog focuses its first text field, if it has one.
51//!
52//! Escape first closes whatever is open inside the dialog, such as a
53//! select's list, a combobox's suggestions or a menu. The next Escape
54//! dismisses the dialog, even while a text field has focus.
55//!
56//! While it is open the dialog captures every key press, after the content
57//! inside it has had its turn, so app-wide shortcuts from
58//! [`keys::subscription`] never reach the components underneath. Let
59//! chosen chords through with [`Dialog::pass_through`].
60//!
61//! The dialog never grows taller than the window. The title, description
62//! and actions stay in view and the body scrolls when it does not fit.
63//! Group a long body with [`section`] and lay sections side by side with
64//! [`columns`].
65
66use std::any::Any;
67
68use iced::advanced::layout::{self, Layout};
69use iced::advanced::widget::operation::scrollable::AbsoluteOffset;
70use iced::advanced::widget::operation::{Focusable, Scrollable};
71use iced::advanced::widget::{Operation, Tree, Widget, tree};
72use iced::advanced::{Clipboard, Shell, overlay, renderer};
73use iced::keyboard::key::Named;
74use iced::widget::{self, center, column, container, mouse_area, row, stack, text};
75use iced::{
76    Alignment, Background, Border, Color, Element, Event, Length, Padding, Point, Rectangle,
77    Renderer, Size as Bounds, Theme, Vector, keyboard, mouse,
78};
79
80use crate::focus;
81use crate::keys::{self, Chord, Keymap};
82use crate::overlay::anchored;
83use crate::primitives::button::{self, Size as ButtonSize};
84use crate::primitives::icon_button::icon_button;
85use crate::primitives::scroll_area::scroll_area;
86use crate::solid::solid;
87use crate::theme::{Tokens, fade, heading, radius, space, supporting, text_size};
88
89/// The default widget id of the dialog surface, which scopes focus.
90pub const DEFAULT_ID: widget::Id = widget::Id::new("iced-cube-dialog");
91
92/// The widget id of the close button, for clicking it in tests.
93pub const CLOSE_BUTTON_ID: widget::Id = widget::Id::new("iced-cube-dialog-close");
94
95/// Maximum width of the dialog surface. It shrinks to fit smaller windows.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
97pub enum Size {
98    Sm,
99    #[default]
100    Md,
101    Lg,
102}
103
104impl Size {
105    pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];
106
107    /// The maximum width in logical pixels.
108    pub const fn width(self) -> f32 {
109        match self {
110            Size::Sm => 384.0,
111            Size::Md => 512.0,
112            Size::Lg => 640.0,
113        }
114    }
115}
116
117/// What a dialog keyboard shortcut does.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119pub enum Action {
120    Close,
121    Confirm,
122    FocusNext,
123    FocusPrevious,
124}
125
126/// The direction focus moves in.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128pub enum Direction {
129    Next,
130    Previous,
131}
132
133/// What an [`Action`] does to an open dialog.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
135pub enum Effect {
136    /// Emit the `on_dismiss` message.
137    Dismiss,
138    /// Emit the `on_confirm` message.
139    Confirm,
140    /// Move focus to another field or control inside the dialog.
141    Focus(Direction),
142}
143
144impl Action {
145    /// The effect of this action on an open dialog, or `None` when Close
146    /// has nothing to do because Escape does not dismiss the dialog.
147    pub fn effect(self, dismiss_on_escape: bool) -> Option<Effect> {
148        match self {
149            Action::Close => dismiss_on_escape.then_some(Effect::Dismiss),
150            Action::Confirm => Some(Effect::Confirm),
151            Action::FocusNext => Some(Effect::Focus(Direction::Next)),
152            Action::FocusPrevious => Some(Effect::Focus(Direction::Previous)),
153        }
154    }
155}
156
157impl keys::Action for Action {
158    const ALL: &'static [Self] = &[
159        Action::Close,
160        Action::Confirm,
161        Action::FocusNext,
162        Action::FocusPrevious,
163    ];
164
165    fn defaults() -> Keymap<Self> {
166        default_keymap()
167    }
168
169    fn name(self) -> &'static str {
170        match self {
171            Action::Close => "Close",
172            Action::Confirm => "Confirm",
173            Action::FocusNext => "FocusNext",
174            Action::FocusPrevious => "FocusPrevious",
175        }
176    }
177
178    fn description(self) -> &'static str {
179        match self {
180            Action::Close => "Dismisses the dialog, unless Escape dismissal is turned off.",
181            Action::Confirm => {
182                "Sends the dialog's confirm message. An alert dialog's destructive action only runs on Enter when it opts in."
183            }
184            Action::FocusNext => {
185                "Focuses the next field, button or control in the dialog, wrapping from the last to the first."
186            }
187            Action::FocusPrevious => {
188                "Focuses the previous field, button or control in the dialog, wrapping from the first to the last."
189            }
190        }
191    }
192}
193
194/// The default dialog shortcuts:
195///
196/// | Keys | Action |
197/// | --- | --- |
198/// | `Escape` | [`Action::Close`] |
199/// | `Enter` | [`Action::Confirm`] |
200/// | `Tab` | [`Action::FocusNext`] |
201/// | `Shift+Tab` | [`Action::FocusPrevious`] |
202///
203/// The dialog resolves these itself while it is open, after the content
204/// inside it, so a menu, select or combobox list in the dialog closes on
205/// Escape before the dialog does, and a field that submits on Enter or a
206/// focused button keeps it. A focused text field does not hold up Close:
207/// the press that takes focus off it also dismisses the dialog. Enter does
208/// nothing in a dialog without [`Dialog::on_confirm`], or in an alert
209/// dialog without [`AlertDialog::confirm_on_enter`].
210pub fn default_keymap() -> Keymap<Action> {
211    Keymap::new()
212        .bind(Chord::named(Named::Escape), Action::Close)
213        .bind(Chord::named(Named::Enter), Action::Confirm)
214        .bind(Chord::named(Named::Tab), Action::FocusNext)
215        .bind(Chord::named(Named::Tab).shift(), Action::FocusPrevious)
216}
217
218/// A dialog builder. Convert it into an [`Element`] to render.
219pub struct Dialog<'a, Message> {
220    base: Element<'a, Message>,
221    open: bool,
222    title: Option<text::Fragment<'a>>,
223    description: Option<text::Fragment<'a>>,
224    body: Option<Element<'a, Message>>,
225    actions: Vec<Element<'a, Message>>,
226    on_dismiss: Option<Message>,
227    on_confirm: Option<Message>,
228    dismiss_on_escape: bool,
229    dismiss_on_scrim: bool,
230    close_button: bool,
231    width: f32,
232    max_height: f32,
233    id: widget::Id,
234    keymap: Keymap<Action>,
235    pass_through: Vec<Chord>,
236    /// Built from an [`AlertDialog`], so icedwright reports an alert dialog.
237    #[cfg(feature = "icedwright")]
238    alert: bool,
239}
240
241impl<Message> std::fmt::Debug for Dialog<'_, Message> {
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        f.debug_struct("Dialog")
244            .field("open", &self.open)
245            .field("title", &self.title)
246            .field("description", &self.description)
247            .field("actions", &self.actions.len())
248            .field("dismiss_on_escape", &self.dismiss_on_escape)
249            .field("dismiss_on_scrim", &self.dismiss_on_scrim)
250            .field("close_button", &self.close_button)
251            .field("width", &self.width)
252            .field("max_height", &self.max_height)
253            .field("id", &self.id)
254            .field("pass_through", &self.pass_through)
255            .finish_non_exhaustive()
256    }
257}
258
259/// Wraps `base`, the content the dialog opens over. The dialog is closed
260/// until [`open`](Dialog::open) is `true`.
261pub fn dialog<'a, Message>(base: impl Into<Element<'a, Message>>) -> Dialog<'a, Message> {
262    Dialog {
263        base: base.into(),
264        open: false,
265        title: None,
266        description: None,
267        body: None,
268        actions: Vec::new(),
269        on_dismiss: None,
270        on_confirm: None,
271        dismiss_on_escape: true,
272        dismiss_on_scrim: true,
273        close_button: true,
274        width: Size::default().width(),
275        max_height: f32::INFINITY,
276        id: DEFAULT_ID,
277        keymap: default_keymap(),
278        pass_through: Vec::new(),
279        #[cfg(feature = "icedwright")]
280        alert: false,
281    }
282}
283
284impl<'a, Message> Dialog<'a, Message> {
285    pub fn open(mut self, open: bool) -> Self {
286        self.open = open;
287        self
288    }
289
290    pub fn title(mut self, title: impl text::IntoFragment<'a>) -> Self {
291        self.title = Some(title.into_fragment());
292        self
293    }
294
295    /// A line of muted text under the title.
296    pub fn description(mut self, description: impl text::IntoFragment<'a>) -> Self {
297        self.description = Some(description.into_fragment());
298        self
299    }
300
301    /// Content between the header and the footer, such as a form. It
302    /// scrolls when the dialog would not otherwise fit the window.
303    pub fn body(mut self, body: impl Into<Element<'a, Message>>) -> Self {
304        self.body = Some(body.into());
305        self
306    }
307
308    /// Adds a button or other element to the footer, which lines them up
309    /// on the right. Add the main action last.
310    pub fn action(mut self, action: impl Into<Element<'a, Message>>) -> Self {
311        self.actions.push(action.into());
312        self
313    }
314
315    /// The message emitted when Escape, a click on the scrim or the close
316    /// button dismisses the dialog. Without it, only the footer actions
317    /// can close the dialog and the close button renders disabled.
318    pub fn on_dismiss(mut self, message: Message) -> Self {
319        self.on_dismiss = Some(message);
320        self
321    }
322
323    /// Whether Escape dismisses the dialog. Defaults to `true`.
324    pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
325        self.dismiss_on_escape = dismiss;
326        self
327    }
328
329    /// The message [`Action::Confirm`] (Enter) emits, usually the same as
330    /// the main footer action. Without it Enter does nothing. A field
331    /// inside the dialog that submits on Enter keeps the key.
332    pub fn on_confirm(mut self, message: Message) -> Self {
333        self.on_confirm = Some(message);
334        self
335    }
336
337    /// Whether a click on the scrim dismisses the dialog. Defaults to
338    /// `true`; turn it off for confirmations that need an explicit answer.
339    pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
340        self.dismiss_on_scrim = dismiss;
341        self
342    }
343
344    /// Whether to show a close button in the top right corner. Defaults to
345    /// `true`.
346    pub fn close_button(mut self, show: bool) -> Self {
347        self.close_button = show;
348        self
349    }
350
351    /// Sets the maximum width from a [`Size`].
352    pub fn size(mut self, size: Size) -> Self {
353        self.width = size.width();
354        self
355    }
356
357    /// Sets the maximum width in logical pixels.
358    pub fn width(mut self, width: f32) -> Self {
359        self.width = width;
360        self
361    }
362
363    /// Sets the maximum height in logical pixels. The dialog is never
364    /// taller than the window less the scrim's padding, whatever this is.
365    pub fn max_height(mut self, height: f32) -> Self {
366        self.max_height = height;
367        self
368    }
369
370    /// Sets the surface's widget id, which scopes focus. Give nested
371    /// dialogs different ids.
372    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
373        self.id = id.into();
374        self
375    }
376
377    /// Replaces the default shortcuts.
378    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
379        self.keymap = keymap;
380        self
381    }
382
383    /// Chords the open dialog lets through to the app, such as the shortcut
384    /// that toggles it. Every other key press stops at the dialog.
385    pub fn pass_through(mut self, chords: impl IntoIterator<Item = Chord>) -> Self {
386        self.pass_through = chords.into_iter().collect();
387        self
388    }
389
390    pub fn is_open(&self) -> bool {
391        self.open
392    }
393}
394
395impl<'a, Message: Clone + 'a> From<Dialog<'a, Message>> for Element<'a, Message> {
396    fn from(dialog: Dialog<'a, Message>) -> Self {
397        let Dialog {
398            base,
399            open,
400            title,
401            description,
402            body,
403            actions,
404            on_dismiss,
405            on_confirm,
406            dismiss_on_escape,
407            dismiss_on_scrim,
408            close_button,
409            width,
410            max_height,
411            id,
412            keymap,
413            pass_through,
414            #[cfg(feature = "icedwright")]
415            alert,
416        } = dialog;
417
418        let guarded = Element::new(Guard {
419            content: base,
420            blocked: open,
421        });
422
423        // The base is always the first child, so it keeps its widget state
424        // when the dialog opens and closes.
425        let mut layers = stack![guarded].width(Length::Fill).height(Length::Fill);
426
427        if open {
428            #[cfg(feature = "icedwright")]
429            let name = title.clone();
430            #[cfg(feature = "icedwright")]
431            let about = description.clone();
432            let surface = surface(
433                title,
434                description,
435                body,
436                actions,
437                close_button.then(|| on_dismiss.clone()),
438                Bounds::new(width, max_height),
439                id.clone(),
440            );
441            #[cfg(feature = "icedwright")]
442            let surface = annotate_surface(surface, alert, name, about);
443            let scrim = center(solid(surface))
444                .padding(space::LG)
445                .style(|theme| scrim_style(&Tokens::of(theme)));
446            let layer: Element<'a, Message> = match on_dismiss.clone().filter(|_| dismiss_on_scrim)
447            {
448                Some(message) => solid(mouse_area(scrim).on_press(message)),
449                None => solid(scrim),
450            };
451            #[cfg(feature = "icedwright")]
452            let layer: Element<'a, Message> = icedwright_probe::semantic(layer)
453                .role(icedwright_probe::role::Scrim)
454                .component("iced_cube::dialog")
455                .into();
456            layers = layers.push(layer);
457        }
458
459        Element::new(Scope {
460            content: layers.into(),
461            open,
462            surface: id,
463            keymap,
464            pass_through,
465            on_escape: on_dismiss.filter(|_| dismiss_on_escape),
466            on_confirm,
467        })
468    }
469}
470
471/// Reports the surface as a modal dialog named by its title.
472#[cfg(feature = "icedwright")]
473fn annotate_surface<'a, Message: 'a>(
474    surface: Element<'a, Message>,
475    alert: bool,
476    title: Option<text::Fragment<'a>>,
477    description: Option<text::Fragment<'a>>,
478) -> Element<'a, Message> {
479    use icedwright_probe::{Semantic, role, semantic};
480
481    fn finish<'a, Message: 'a, R: role::RoleKind>(
482        mut annotated: Semantic<'a, Message, Theme, iced::Renderer, R>,
483        title: Option<text::Fragment<'a>>,
484        description: Option<text::Fragment<'a>>,
485    ) -> Element<'a, Message> {
486        annotated = annotated.modal(true).component("iced_cube::dialog");
487        if let Some(title) = title {
488            annotated = annotated.name(title);
489        }
490        if let Some(description) = description {
491            annotated = annotated.description(description);
492        }
493        annotated.into()
494    }
495
496    if alert {
497        finish(
498            semantic(surface).role(role::AlertDialog),
499            title,
500            description,
501        )
502    } else {
503        finish(semantic(surface).role(role::Dialog), title, description)
504    }
505}
506
507fn surface<'a, Message: Clone + 'a>(
508    title: Option<text::Fragment<'a>>,
509    description: Option<text::Fragment<'a>>,
510    body: Option<Element<'a, Message>>,
511    actions: Vec<Element<'a, Message>>,
512    close: Option<Option<Message>>,
513    max: Bounds,
514    id: widget::Id,
515) -> Element<'a, Message> {
516    let mut header = column![].spacing(space::XS);
517    if let Some(title) = title {
518        header = header.push(heading(title, text_size::LG));
519    }
520    if let Some(description) = description {
521        header = header.push(supporting(description));
522    }
523    // Keeps long titles clear of the close button.
524    if close.is_some() {
525        header = header.padding(Padding::ZERO.right(space::XL));
526    }
527
528    let mut parts: Vec<Element<'a, Message>> = vec![header.into()];
529    let mut flexible = None;
530    if let Some(body) = body {
531        flexible = Some(parts.len());
532        parts.push(scroll_area(body).width(Length::Fill).into());
533    }
534    if !actions.is_empty() {
535        parts.push(
536            container(row(actions).spacing(space::SM))
537                .width(Length::Fill)
538                .align_x(Alignment::End)
539                .into(),
540        );
541    }
542    let content = Element::new(Pinned {
543        children: parts,
544        flexible,
545        spacing: space::LG,
546    });
547
548    let mut layers = stack![container(content).padding(space::XL)];
549    if let Some(on_press) = close {
550        layers = layers.push(
551            container(
552                icon_button(crate::lucide!(X))
553                    .label("Close")
554                    .tooltip(None)
555                    .size(ButtonSize::Sm)
556                    .id(CLOSE_BUTTON_ID)
557                    .on_press_maybe(on_press),
558            )
559            .padding(space::MD)
560            .width(Length::Fill)
561            .align_x(Alignment::End),
562        );
563    }
564
565    container(layers)
566        .id(id)
567        .width(Length::Fill)
568        .max_width(max.width)
569        .max_height(max.height)
570        .style(|theme| surface_style(&Tokens::of(theme)))
571        .into()
572}
573
574/// The height left for the flexible child of a [`Pinned`] layout once the
575/// other children and the gaps between `count` children are placed.
576fn room(available: f32, fixed: f32, spacing: f32, count: usize) -> f32 {
577    let gaps = spacing * count.saturating_sub(1) as f32;
578    (available - fixed - gaps).max(0.0)
579}
580
581/// Lays its children out top to bottom like a column, but the flexible
582/// child only gets the height the others leave. The dialog's header and
583/// footer stay in view while its body, a scroll area, shrinks.
584struct Pinned<'a, Message> {
585    children: Vec<Element<'a, Message>>,
586    flexible: Option<usize>,
587    spacing: f32,
588}
589
590impl<Message> Widget<Message, Theme, Renderer> for Pinned<'_, Message> {
591    fn size(&self) -> Bounds<Length> {
592        Bounds::new(Length::Fill, Length::Shrink)
593    }
594
595    fn children(&self) -> Vec<Tree> {
596        self.children.iter().map(Tree::new).collect()
597    }
598
599    fn diff(&self, tree: &mut Tree) {
600        tree.diff_children(&self.children);
601    }
602
603    fn layout(
604        &mut self,
605        tree: &mut Tree,
606        renderer: &Renderer,
607        limits: &layout::Limits,
608    ) -> layout::Node {
609        let max = limits.max();
610        let loose = layout::Limits::new(Bounds::ZERO, max);
611        let mut nodes: Vec<Option<layout::Node>> = self
612            .children
613            .iter_mut()
614            .zip(&mut tree.children)
615            .enumerate()
616            .map(|(index, (child, tree))| {
617                (self.flexible != Some(index))
618                    .then(|| child.as_widget_mut().layout(tree, renderer, &loose))
619            })
620            .collect();
621
622        if let Some(index) = self.flexible {
623            let fixed = nodes.iter().flatten().map(|node| node.size().height).sum();
624            let height = room(max.height, fixed, self.spacing, self.children.len());
625            let limits = layout::Limits::new(Bounds::ZERO, Bounds::new(max.width, height));
626            if let (Some(child), Some(tree), Some(slot)) = (
627                self.children.get_mut(index),
628                tree.children.get_mut(index),
629                nodes.get_mut(index),
630            ) {
631                *slot = Some(child.as_widget_mut().layout(tree, renderer, &limits));
632            }
633        }
634
635        let (nodes, size) = stack_vertically(nodes.into_iter().flatten(), self.spacing);
636        layout::Node::with_children(limits.resolve(Length::Fill, Length::Shrink, size), nodes)
637    }
638
639    fn draw(
640        &self,
641        tree: &Tree,
642        renderer: &mut Renderer,
643        theme: &Theme,
644        style: &renderer::Style,
645        layout: Layout<'_>,
646        cursor: mouse::Cursor,
647        viewport: &Rectangle,
648    ) {
649        for ((child, tree), layout) in self
650            .children
651            .iter()
652            .zip(&tree.children)
653            .zip(layout.children())
654        {
655            child
656                .as_widget()
657                .draw(tree, renderer, theme, style, layout, cursor, viewport);
658        }
659    }
660
661    fn operate(
662        &mut self,
663        tree: &mut Tree,
664        layout: Layout<'_>,
665        renderer: &Renderer,
666        operation: &mut dyn Operation,
667    ) {
668        operate_all(&mut self.children, tree, layout, renderer, operation);
669    }
670
671    fn update(
672        &mut self,
673        tree: &mut Tree,
674        event: &Event,
675        layout: Layout<'_>,
676        cursor: mouse::Cursor,
677        renderer: &Renderer,
678        clipboard: &mut dyn Clipboard,
679        shell: &mut Shell<'_, Message>,
680        viewport: &Rectangle,
681    ) {
682        for ((child, tree), layout) in self
683            .children
684            .iter_mut()
685            .zip(&mut tree.children)
686            .zip(layout.children())
687        {
688            child.as_widget_mut().update(
689                tree, event, layout, cursor, renderer, clipboard, shell, viewport,
690            );
691        }
692    }
693
694    fn mouse_interaction(
695        &self,
696        tree: &Tree,
697        layout: Layout<'_>,
698        cursor: mouse::Cursor,
699        viewport: &Rectangle,
700        renderer: &Renderer,
701    ) -> mouse::Interaction {
702        interaction_of_all(&self.children, tree, layout, cursor, viewport, renderer)
703    }
704
705    fn overlay<'b>(
706        &'b mut self,
707        tree: &'b mut Tree,
708        layout: Layout<'b>,
709        renderer: &Renderer,
710        viewport: &Rectangle,
711        translation: Vector,
712    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
713        overlay::from_children(
714            &mut self.children,
715            tree,
716            layout,
717            renderer,
718            viewport,
719            translation,
720        )
721    }
722}
723
724/// Places `nodes` one under another with `spacing` between them, and
725/// returns them with the size they cover.
726fn stack_vertically(
727    nodes: impl IntoIterator<Item = layout::Node>,
728    spacing: f32,
729) -> (Vec<layout::Node>, Bounds) {
730    let mut y = 0.0;
731    let mut width: f32 = 0.0;
732    let placed: Vec<layout::Node> = nodes
733        .into_iter()
734        .map(|node| {
735            let size = node.size();
736            let node = node.move_to(Point::new(0.0, y));
737            y += size.height + spacing;
738            width = width.max(size.width);
739            node
740        })
741        .collect();
742    let height = if placed.is_empty() { 0.0 } else { y - spacing };
743    (placed, Bounds::new(width, height))
744}
745
746fn operate_all<Message>(
747    children: &mut [Element<'_, Message>],
748    tree: &mut Tree,
749    layout: Layout<'_>,
750    renderer: &Renderer,
751    operation: &mut dyn Operation,
752) {
753    operation.container(None, layout.bounds());
754    operation.traverse(&mut |operation| {
755        for ((child, tree), layout) in children
756            .iter_mut()
757            .zip(&mut tree.children)
758            .zip(layout.children())
759        {
760            child
761                .as_widget_mut()
762                .operate(tree, layout, renderer, operation);
763        }
764    });
765}
766
767fn interaction_of_all<Message>(
768    children: &[Element<'_, Message>],
769    tree: &Tree,
770    layout: Layout<'_>,
771    cursor: mouse::Cursor,
772    viewport: &Rectangle,
773    renderer: &Renderer,
774) -> mouse::Interaction {
775    children
776        .iter()
777        .zip(&tree.children)
778        .zip(layout.children())
779        .map(|((child, tree), layout)| {
780            child
781                .as_widget()
782                .mouse_interaction(tree, layout, cursor, viewport, renderer)
783        })
784        .max()
785        .unwrap_or_default()
786}
787
788/// The dialog surface: the floating surface every overlay shares, with a
789/// larger radius.
790pub fn surface_style(tokens: &Tokens) -> container::Style {
791    let style = anchored::surface_style(tokens);
792    container::Style {
793        border: Border {
794            radius: radius::LG.into(),
795            ..style.border
796        },
797        ..style
798    }
799}
800
801/// The scrim: black at half opacity in light themes and more in dark ones,
802/// where half would barely show.
803pub fn scrim_style(tokens: &Tokens) -> container::Style {
804    container::Style {
805        background: Some(Background::Color(fade(
806            Color::BLACK,
807            if tokens.is_dark { 0.7 } else { 0.5 },
808        ))),
809        ..container::Style::default()
810    }
811}
812
813/// Draws the base content, and while `blocked` keeps input and hover state
814/// away from it.
815struct Guard<'a, Message> {
816    content: Element<'a, Message>,
817    blocked: bool,
818}
819
820impl<Message> Widget<Message, Theme, Renderer> for Guard<'_, Message> {
821    fn size(&self) -> Bounds<Length> {
822        self.content.as_widget().size()
823    }
824
825    fn size_hint(&self) -> Bounds<Length> {
826        self.content.as_widget().size_hint()
827    }
828
829    fn tag(&self) -> tree::Tag {
830        self.content.as_widget().tag()
831    }
832
833    fn state(&self) -> tree::State {
834        self.content.as_widget().state()
835    }
836
837    fn children(&self) -> Vec<Tree> {
838        self.content.as_widget().children()
839    }
840
841    fn diff(&self, tree: &mut Tree) {
842        self.content.as_widget().diff(tree);
843    }
844
845    fn layout(
846        &mut self,
847        tree: &mut Tree,
848        renderer: &Renderer,
849        limits: &layout::Limits,
850    ) -> layout::Node {
851        self.content.as_widget_mut().layout(tree, renderer, limits)
852    }
853
854    fn draw(
855        &self,
856        tree: &Tree,
857        renderer: &mut Renderer,
858        theme: &Theme,
859        style: &renderer::Style,
860        layout: Layout<'_>,
861        cursor: mouse::Cursor,
862        viewport: &Rectangle,
863    ) {
864        let cursor = if self.blocked {
865            mouse::Cursor::Unavailable
866        } else {
867            cursor
868        };
869        self.content
870            .as_widget()
871            .draw(tree, renderer, theme, style, layout, cursor, viewport);
872    }
873
874    fn operate(
875        &mut self,
876        tree: &mut Tree,
877        layout: Layout<'_>,
878        renderer: &Renderer,
879        operation: &mut dyn Operation,
880    ) {
881        self.content
882            .as_widget_mut()
883            .operate(tree, layout, renderer, operation);
884    }
885
886    fn update(
887        &mut self,
888        tree: &mut Tree,
889        event: &Event,
890        layout: Layout<'_>,
891        cursor: mouse::Cursor,
892        renderer: &Renderer,
893        clipboard: &mut dyn Clipboard,
894        shell: &mut Shell<'_, Message>,
895        viewport: &Rectangle,
896    ) {
897        if !self.blocked {
898            self.content.as_widget_mut().update(
899                tree, event, layout, cursor, renderer, clipboard, shell, viewport,
900            );
901            return;
902        }
903        // Window events still arrive so animations underneath keep running.
904        if !matches!(event, Event::Window(_)) {
905            return;
906        }
907        self.content.as_widget_mut().update(
908            tree,
909            event,
910            layout,
911            mouse::Cursor::Unavailable,
912            renderer,
913            clipboard,
914            shell,
915            viewport,
916        );
917    }
918
919    fn mouse_interaction(
920        &self,
921        tree: &Tree,
922        layout: Layout<'_>,
923        cursor: mouse::Cursor,
924        viewport: &Rectangle,
925        renderer: &Renderer,
926    ) -> mouse::Interaction {
927        if self.blocked {
928            return mouse::Interaction::None;
929        }
930        self.content
931            .as_widget()
932            .mouse_interaction(tree, layout, cursor, viewport, renderer)
933    }
934
935    fn overlay<'b>(
936        &'b mut self,
937        tree: &'b mut Tree,
938        layout: Layout<'b>,
939        renderer: &Renderer,
940        viewport: &Rectangle,
941        translation: Vector,
942    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
943        if self.blocked {
944            return None;
945        }
946        self.content
947            .as_widget_mut()
948            .overlay(tree, layout, renderer, viewport, translation)
949    }
950}
951
952/// Resolves the dialog's keymap, keeps focus inside the surface and
953/// captures every other key press while the dialog is open.
954struct Scope<'a, Message> {
955    content: Element<'a, Message>,
956    open: bool,
957    surface: widget::Id,
958    keymap: Keymap<Action>,
959    pass_through: Vec<Chord>,
960    on_escape: Option<Message>,
961    on_confirm: Option<Message>,
962}
963
964/// The key and modifiers of a key press or release.
965fn key_of(event: &Event) -> Option<(&keyboard::Key, keyboard::Modifiers, bool)> {
966    match event {
967        Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) => {
968            Some((key, *modifiers, true))
969        }
970        Event::Keyboard(keyboard::Event::KeyReleased { key, modifiers, .. }) => {
971            Some((key, *modifiers, false))
972        }
973        _ => None,
974    }
975}
976
977/// Whether focus has moved into the dialog since it opened.
978#[derive(Debug, Default)]
979struct ScopeState {
980    entered: bool,
981}
982
983/// Whether a Close press the content captured still dismisses the dialog:
984/// it does when all the content did was take focus off a field inside.
985fn dismisses_anyway(focused_before: bool, focused_after: bool) -> bool {
986    focused_before && !focused_after
987}
988
989impl<Message> Scope<'_, Message> {
990    /// Whether `event` is a press of a Close chord that would dismiss.
991    fn is_dismissal(&self, event: &Event) -> bool {
992        let Some((key, modifiers, true)) = key_of(event) else {
993            return false;
994        };
995        self.open
996            && self.on_escape.is_some()
997            && !self
998                .pass_through
999                .iter()
1000                .any(|chord| chord.matches(key, modifiers))
1001            && self.keymap.resolve(key, modifiers) == Some(Action::Close)
1002    }
1003
1004    fn has_focus_inside(
1005        &mut self,
1006        tree: &mut Tree,
1007        layout: Layout<'_>,
1008        renderer: &Renderer,
1009    ) -> bool {
1010        let mut survey = Survey::new(self.surface.clone());
1011        self.content
1012            .as_widget_mut()
1013            .operate(tree, layout, renderer, &mut survey);
1014        survey.has_focus_inside()
1015    }
1016
1017    fn move_focus(
1018        &mut self,
1019        tree: &mut Tree,
1020        layout: Layout<'_>,
1021        renderer: &Renderer,
1022        movement: Movement,
1023    ) {
1024        let mut survey = Survey::new(self.surface.clone());
1025        self.content
1026            .as_widget_mut()
1027            .operate(tree, layout, renderer, &mut survey);
1028
1029        let mut apply = Apply {
1030            target: target(&survey.slots, movement),
1031            index: 0,
1032            focused: None,
1033        };
1034        self.content
1035            .as_widget_mut()
1036            .operate(tree, layout, renderer, &mut apply);
1037
1038        let Some(focused) = apply.focused else {
1039            return;
1040        };
1041        let mut reveal = Reveal {
1042            scope: Survey::new(self.surface.clone()),
1043            target: focused,
1044        };
1045        self.content
1046            .as_widget_mut()
1047            .operate(tree, layout, renderer, &mut reveal);
1048    }
1049}
1050
1051impl<Message: Clone> Widget<Message, Theme, Renderer> for Scope<'_, Message> {
1052    fn size(&self) -> Bounds<Length> {
1053        self.content.as_widget().size()
1054    }
1055
1056    fn size_hint(&self) -> Bounds<Length> {
1057        self.content.as_widget().size_hint()
1058    }
1059
1060    fn tag(&self) -> tree::Tag {
1061        tree::Tag::of::<ScopeState>()
1062    }
1063
1064    fn state(&self) -> tree::State {
1065        tree::State::new(ScopeState::default())
1066    }
1067
1068    fn children(&self) -> Vec<Tree> {
1069        vec![Tree::new(&self.content)]
1070    }
1071
1072    fn diff(&self, tree: &mut Tree) {
1073        tree.diff_children(std::slice::from_ref(&self.content));
1074    }
1075
1076    fn layout(
1077        &mut self,
1078        tree: &mut Tree,
1079        renderer: &Renderer,
1080        limits: &layout::Limits,
1081    ) -> layout::Node {
1082        self.content
1083            .as_widget_mut()
1084            .layout(&mut tree.children[0], renderer, limits)
1085    }
1086
1087    fn draw(
1088        &self,
1089        tree: &Tree,
1090        renderer: &mut Renderer,
1091        theme: &Theme,
1092        style: &renderer::Style,
1093        layout: Layout<'_>,
1094        cursor: mouse::Cursor,
1095        viewport: &Rectangle,
1096    ) {
1097        self.content.as_widget().draw(
1098            &tree.children[0],
1099            renderer,
1100            theme,
1101            style,
1102            layout,
1103            cursor,
1104            viewport,
1105        );
1106    }
1107
1108    fn operate(
1109        &mut self,
1110        tree: &mut Tree,
1111        layout: Layout<'_>,
1112        renderer: &Renderer,
1113        operation: &mut dyn Operation,
1114    ) {
1115        self.content
1116            .as_widget_mut()
1117            .operate(&mut tree.children[0], layout, renderer, operation);
1118    }
1119
1120    fn update(
1121        &mut self,
1122        tree: &mut Tree,
1123        event: &Event,
1124        layout: Layout<'_>,
1125        cursor: mouse::Cursor,
1126        renderer: &Renderer,
1127        clipboard: &mut dyn Clipboard,
1128        shell: &mut Shell<'_, Message>,
1129        viewport: &Rectangle,
1130    ) {
1131        let state = tree.state.downcast_mut::<ScopeState>();
1132        let entering = self.open && !state.entered;
1133        state.entered = self.open;
1134
1135        let content = &mut tree.children[0];
1136        if entering {
1137            self.move_focus(content, layout, renderer, Movement::First);
1138            shell.request_redraw();
1139        }
1140
1141        // A field drops focus on Escape and keeps the key, which would
1142        // otherwise take a second press to dismiss. Open lists and menus
1143        // float in overlays, which see the key first and never pass it on.
1144        let dismissal = self.is_dismissal(event);
1145        let focused_before = dismissal && self.has_focus_inside(content, layout, renderer);
1146
1147        self.content.as_widget_mut().update(
1148            content, event, layout, cursor, renderer, clipboard, shell, viewport,
1149        );
1150        if !self.open {
1151            return;
1152        }
1153        if shell.is_event_captured() {
1154            if !dismissal {
1155                return;
1156            }
1157            let focused_after = self.has_focus_inside(content, layout, renderer);
1158            if let Some(message) = self
1159                .on_escape
1160                .clone()
1161                .filter(|_| dismisses_anyway(focused_before, focused_after))
1162            {
1163                shell.publish(message);
1164            }
1165            return;
1166        }
1167
1168        let Some((key, modifiers, pressed)) = key_of(event) else {
1169            return;
1170        };
1171        if self
1172            .pass_through
1173            .iter()
1174            .any(|chord| chord.matches(key, modifiers))
1175        {
1176            return;
1177        }
1178        shell.capture_event();
1179        if !pressed {
1180            return;
1181        }
1182        let Some(effect) = self
1183            .keymap
1184            .resolve(key, modifiers)
1185            .and_then(|action| action.effect(self.on_escape.is_some()))
1186        else {
1187            return;
1188        };
1189
1190        match effect {
1191            Effect::Dismiss => {
1192                let Some(message) = self.on_escape.clone() else {
1193                    return;
1194                };
1195                shell.publish(message);
1196            }
1197            Effect::Confirm => {
1198                let Some(message) = self.on_confirm.clone() else {
1199                    return;
1200                };
1201                shell.publish(message);
1202            }
1203            Effect::Focus(direction) => {
1204                self.move_focus(content, layout, renderer, Movement::from(direction));
1205                shell.request_redraw();
1206            }
1207        }
1208    }
1209
1210    fn mouse_interaction(
1211        &self,
1212        tree: &Tree,
1213        layout: Layout<'_>,
1214        cursor: mouse::Cursor,
1215        viewport: &Rectangle,
1216        renderer: &Renderer,
1217    ) -> mouse::Interaction {
1218        self.content.as_widget().mouse_interaction(
1219            &tree.children[0],
1220            layout,
1221            cursor,
1222            viewport,
1223            renderer,
1224        )
1225    }
1226
1227    fn overlay<'b>(
1228        &'b mut self,
1229        tree: &'b mut Tree,
1230        layout: Layout<'b>,
1231        renderer: &Renderer,
1232        viewport: &Rectangle,
1233        translation: Vector,
1234    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1235        self.content.as_widget_mut().overlay(
1236            &mut tree.children[0],
1237            layout,
1238            renderer,
1239            viewport,
1240            translation,
1241        )
1242    }
1243}
1244
1245/// Where focus goes inside the dialog.
1246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1247enum Movement {
1248    First,
1249    Next,
1250    Previous,
1251}
1252
1253impl From<Direction> for Movement {
1254    fn from(direction: Direction) -> Self {
1255        match direction {
1256            Direction::Next => Movement::Next,
1257            Direction::Previous => Movement::Previous,
1258        }
1259    }
1260}
1261
1262/// A focusable widget, in tree order.
1263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1264struct Slot {
1265    inside: bool,
1266    focused: bool,
1267    /// A button or other control, which Tab reaches but opening does not.
1268    control: bool,
1269}
1270
1271/// The index of the slot to focus. Only slots inside the dialog are
1272/// candidates, and focus wraps at either end. Opening focuses the first
1273/// text field, never a control. Every other slot loses focus.
1274fn target(slots: &[Slot], movement: Movement) -> Option<usize> {
1275    let inside: Vec<usize> = (0..slots.len()).filter(|&i| slots[i].inside).collect();
1276    if movement == Movement::First {
1277        return inside.into_iter().find(|&i| !slots[i].control);
1278    }
1279    let (first, last) = (inside.first().copied()?, inside.last().copied()?);
1280    let current = inside.iter().position(|&i| slots[i].focused);
1281    let count = inside.len();
1282
1283    match (movement, current) {
1284        (Movement::First, _) | (Movement::Next, None) => Some(first),
1285        (Movement::Previous, None) => Some(last),
1286        (Movement::Next, Some(at)) => inside.get((at + 1) % count).copied(),
1287        (Movement::Previous, Some(at)) => inside.get((at + count - 1) % count).copied(),
1288    }
1289}
1290
1291/// Records every focusable widget and whether it sits inside the surface.
1292struct Survey {
1293    scope: widget::Id,
1294    entering: bool,
1295    depth: usize,
1296    /// The next focusable is a control, marked just before it.
1297    control: bool,
1298    slots: Vec<Slot>,
1299}
1300
1301impl Survey {
1302    fn new(scope: widget::Id) -> Self {
1303        Self {
1304            scope,
1305            entering: false,
1306            depth: 0,
1307            control: false,
1308            slots: Vec::new(),
1309        }
1310    }
1311
1312    fn has_focus_inside(&self) -> bool {
1313        self.slots.iter().any(|slot| slot.inside && slot.focused)
1314    }
1315}
1316
1317impl Operation for Survey {
1318    fn container(&mut self, id: Option<&widget::Id>, _bounds: Rectangle) {
1319        if id == Some(&self.scope) {
1320            self.entering = true;
1321        }
1322    }
1323
1324    // A container reports itself and then traverses its children, so the
1325    // traversal right after the scope's container is the inside of it.
1326    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
1327        let entered = std::mem::take(&mut self.entering);
1328        self.depth += usize::from(entered);
1329        operate(self);
1330        self.depth -= usize::from(entered);
1331    }
1332
1333    fn custom(&mut self, _id: Option<&widget::Id>, _bounds: Rectangle, state: &mut dyn Any) {
1334        if state.is::<focus::Control>() {
1335            self.control = true;
1336        }
1337    }
1338
1339    fn focusable(
1340        &mut self,
1341        _id: Option<&widget::Id>,
1342        _bounds: Rectangle,
1343        state: &mut dyn Focusable,
1344    ) {
1345        self.slots.push(Slot {
1346            inside: self.depth > 0,
1347            focused: state.is_focused(),
1348            control: std::mem::take(&mut self.control),
1349        });
1350    }
1351}
1352
1353/// Focuses the target slot and unfocuses every other one, and records the
1354/// bounds of the one it focused.
1355struct Apply {
1356    target: Option<usize>,
1357    index: usize,
1358    focused: Option<Rectangle>,
1359}
1360
1361impl Operation for Apply {
1362    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
1363        operate(self);
1364    }
1365
1366    fn focusable(
1367        &mut self,
1368        _id: Option<&widget::Id>,
1369        bounds: Rectangle,
1370        state: &mut dyn Focusable,
1371    ) {
1372        let is_target = self.target == Some(self.index);
1373        if is_target {
1374            self.focused = Some(bounds);
1375        }
1376        if is_target && !state.is_focused() {
1377            state.focus();
1378        } else if !is_target && state.is_focused() {
1379            state.unfocus();
1380        }
1381        self.index += 1;
1382    }
1383}
1384
1385/// Room kept above or below a field scrolled into view, so its focus ring
1386/// shows too.
1387const REVEAL_MARGIN: f32 = space::XS;
1388
1389/// The scroll offset that brings `target` fully into a scroll area's
1390/// `viewport`, or `None` when it is already in view or not inside the
1391/// area's `content`. Bounds are in the content's unscrolled coordinates,
1392/// as operations report them.
1393fn reveal(viewport: Rectangle, content: Rectangle, offset: f32, target: Rectangle) -> Option<f32> {
1394    if !content.intersects(&target) {
1395        return None;
1396    }
1397    let top = (target.y - content.y - REVEAL_MARGIN).max(0.0);
1398    let bottom = target.y + target.height - content.y + REVEAL_MARGIN;
1399    if top < offset {
1400        return Some(top);
1401    }
1402    if bottom > offset + viewport.height {
1403        return Some((bottom - viewport.height).min(top));
1404    }
1405    None
1406}
1407
1408/// Scrolls the scroll areas inside the dialog so the focused field shows.
1409struct Reveal {
1410    scope: Survey,
1411    target: Rectangle,
1412}
1413
1414impl Operation for Reveal {
1415    fn container(&mut self, id: Option<&widget::Id>, bounds: Rectangle) {
1416        self.scope.container(id, bounds);
1417    }
1418
1419    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
1420        let entered = std::mem::take(&mut self.scope.entering);
1421        self.scope.depth += usize::from(entered);
1422        operate(self);
1423        self.scope.depth -= usize::from(entered);
1424    }
1425
1426    fn scrollable(
1427        &mut self,
1428        _id: Option<&widget::Id>,
1429        bounds: Rectangle,
1430        content_bounds: Rectangle,
1431        translation: Vector,
1432        state: &mut dyn Scrollable,
1433    ) {
1434        if self.scope.depth == 0 {
1435            return;
1436        }
1437        let Some(y) = reveal(bounds, content_bounds, translation.y, self.target) else {
1438            return;
1439        };
1440        state.scroll_to(AbsoluteOffset {
1441            x: None,
1442            y: Some(y),
1443        });
1444    }
1445}
1446
1447/// A confirmation that needs an explicit answer: a clicked scrim does
1448/// nothing unless [`dismiss_on_scrim`](Self::dismiss_on_scrim) is on,
1449/// there is no close button, and the footer holds Cancel and a
1450/// destructive action.
1451///
1452/// Keyboard users reach both buttons with Tab and Shift+Tab, which ring
1453/// the focused one, and press it with Enter or Space. Nothing is focused
1454/// when the dialog opens, so a stray Enter does nothing unless
1455/// [`confirm_on_enter`](Self::confirm_on_enter) is on; Escape cancels.
1456pub struct AlertDialog<'a, Message> {
1457    base: Element<'a, Message>,
1458    open: bool,
1459    title: text::Fragment<'a>,
1460    description: text::Fragment<'a>,
1461    cancel: text::Fragment<'a>,
1462    confirm: text::Fragment<'a>,
1463    on_cancel: Option<Message>,
1464    on_confirm: Option<Message>,
1465    confirm_on_enter: bool,
1466    dismiss_on_escape: bool,
1467    dismiss_on_scrim: bool,
1468    size: Size,
1469    keymap: Keymap<Action>,
1470}
1471
1472impl<Message> std::fmt::Debug for AlertDialog<'_, Message> {
1473    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1474        f.debug_struct("AlertDialog")
1475            .field("open", &self.open)
1476            .field("title", &self.title)
1477            .field("description", &self.description)
1478            .field("cancel", &self.cancel)
1479            .field("confirm", &self.confirm)
1480            .field("confirm_on_enter", &self.confirm_on_enter)
1481            .field("dismiss_on_escape", &self.dismiss_on_escape)
1482            .field("dismiss_on_scrim", &self.dismiss_on_scrim)
1483            .field("size", &self.size)
1484            .finish_non_exhaustive()
1485    }
1486}
1487
1488/// Wraps `base` in a confirmation dialog. The buttons read "Cancel" and
1489/// "Continue" until you change them.
1490pub fn alert_dialog<'a, Message>(
1491    base: impl Into<Element<'a, Message>>,
1492    title: impl text::IntoFragment<'a>,
1493    description: impl text::IntoFragment<'a>,
1494) -> AlertDialog<'a, Message> {
1495    AlertDialog {
1496        base: base.into(),
1497        open: false,
1498        title: title.into_fragment(),
1499        description: description.into_fragment(),
1500        cancel: "Cancel".into(),
1501        confirm: "Continue".into(),
1502        on_cancel: None,
1503        on_confirm: None,
1504        confirm_on_enter: false,
1505        dismiss_on_escape: true,
1506        dismiss_on_scrim: false,
1507        size: Size::default(),
1508        keymap: default_keymap(),
1509    }
1510}
1511
1512impl<'a, Message> AlertDialog<'a, Message> {
1513    pub fn open(mut self, open: bool) -> Self {
1514        self.open = open;
1515        self
1516    }
1517
1518    /// The label of the cancel button.
1519    pub fn cancel(mut self, label: impl text::IntoFragment<'a>) -> Self {
1520        self.cancel = label.into_fragment();
1521        self
1522    }
1523
1524    /// The label of the destructive button, such as "Delete".
1525    pub fn confirm(mut self, label: impl text::IntoFragment<'a>) -> Self {
1526        self.confirm = label.into_fragment();
1527        self
1528    }
1529
1530    /// Emitted by the cancel button and by Escape.
1531    pub fn on_cancel(mut self, message: Message) -> Self {
1532        self.on_cancel = Some(message);
1533        self
1534    }
1535
1536    /// Emitted by the destructive button, and by Enter when
1537    /// [`confirm_on_enter`](Self::confirm_on_enter) is on.
1538    pub fn on_confirm(mut self, message: Message) -> Self {
1539        self.on_confirm = Some(message);
1540        self
1541    }
1542
1543    /// Whether Enter ([`Action::Confirm`]) runs the destructive action
1544    /// while no button is focused. Defaults to `false`, so a stray Enter
1545    /// never destroys anything; keyboard users Tab to the button and press
1546    /// Enter or Space instead.
1547    pub fn confirm_on_enter(mut self, confirm: bool) -> Self {
1548        self.confirm_on_enter = confirm;
1549        self
1550    }
1551
1552    /// Whether Escape cancels. Defaults to `true`.
1553    pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
1554        self.dismiss_on_escape = dismiss;
1555        self
1556    }
1557
1558    /// Whether a click on the scrim cancels, sending the
1559    /// [`on_cancel`](Self::on_cancel) message. Defaults to `false`.
1560    pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
1561        self.dismiss_on_scrim = dismiss;
1562        self
1563    }
1564
1565    pub fn size(mut self, size: Size) -> Self {
1566        self.size = size;
1567        self
1568    }
1569
1570    /// Replaces the default shortcuts.
1571    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
1572        self.keymap = keymap;
1573        self
1574    }
1575}
1576
1577impl<'a, Message: Clone + 'a> From<AlertDialog<'a, Message>> for Dialog<'a, Message> {
1578    fn from(alert: AlertDialog<'a, Message>) -> Self {
1579        let mut dialog = dialog(alert.base)
1580            .open(alert.open)
1581            .title(alert.title)
1582            .description(alert.description)
1583            .action(
1584                button::button(alert.cancel)
1585                    .variant(button::Variant::Outline)
1586                    .on_press_maybe(alert.on_cancel.clone()),
1587            )
1588            .action(
1589                button::button(alert.confirm)
1590                    .variant(button::Variant::Destructive)
1591                    .on_press_maybe(alert.on_confirm.clone()),
1592            )
1593            .dismiss_on_escape(alert.dismiss_on_escape)
1594            .dismiss_on_scrim(alert.dismiss_on_scrim)
1595            .close_button(false)
1596            .size(alert.size)
1597            .keymap(alert.keymap);
1598        #[cfg(feature = "icedwright")]
1599        {
1600            dialog.alert = true;
1601        }
1602        if let Some(message) = alert.on_cancel {
1603            dialog = dialog.on_dismiss(message);
1604        }
1605        let Some(message) = alert.on_confirm.filter(|_| alert.confirm_on_enter) else {
1606            return dialog;
1607        };
1608        dialog.on_confirm(message)
1609    }
1610}
1611
1612impl<'a, Message: Clone + 'a> From<AlertDialog<'a, Message>> for Element<'a, Message> {
1613    fn from(alert: AlertDialog<'a, Message>) -> Self {
1614        Dialog::from(alert).into()
1615    }
1616}
1617
1618/// A headed group of content in a dialog body. Convert it into an
1619/// [`Element`] to render.
1620pub struct Section<'a, Message> {
1621    title: text::Fragment<'a>,
1622    description: Option<text::Fragment<'a>>,
1623    body: Element<'a, Message>,
1624}
1625
1626impl<Message> std::fmt::Debug for Section<'_, Message> {
1627    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1628        f.debug_struct("Section")
1629            .field("title", &self.title)
1630            .field("description", &self.description)
1631            .finish_non_exhaustive()
1632    }
1633}
1634
1635/// Puts `title` over `body`, in the dialog's heading style one step
1636/// smaller than the dialog's own title.
1637pub fn section<'a, Message>(
1638    title: impl text::IntoFragment<'a>,
1639    body: impl Into<Element<'a, Message>>,
1640) -> Section<'a, Message> {
1641    Section {
1642        title: title.into_fragment(),
1643        description: None,
1644        body: body.into(),
1645    }
1646}
1647
1648impl<'a, Message> Section<'a, Message> {
1649    /// A line of muted text under the title.
1650    pub fn description(mut self, description: impl text::IntoFragment<'a>) -> Self {
1651        self.description = Some(description.into_fragment());
1652        self
1653    }
1654}
1655
1656/// Text size of a section title.
1657pub const SECTION_TITLE_SIZE: f32 = text_size::MD;
1658
1659impl<'a, Message: 'a> From<Section<'a, Message>> for Element<'a, Message> {
1660    fn from(section: Section<'a, Message>) -> Self {
1661        let mut header = column![heading(section.title, SECTION_TITLE_SIZE)].spacing(space::XS);
1662        if let Some(description) = section.description {
1663            header = header.push(supporting(description));
1664        }
1665        column![header, section.body]
1666            .spacing(space::MD)
1667            .width(Length::Fill)
1668            .into()
1669    }
1670}
1671
1672/// The width below which [`columns`] stacks its children in one column.
1673pub const BREAKPOINT: f32 = 400.0;
1674
1675/// How many columns fit in `width`, and how wide each one is.
1676pub fn cells(width: f32, breakpoint: f32, spacing: f32) -> (usize, f32) {
1677    if !width.is_finite() || width < breakpoint {
1678        return (1, width);
1679    }
1680    (2, ((width - spacing) / 2.0).max(0.0))
1681}
1682
1683/// Two columns that fall back to one in a narrow space. Convert it into an
1684/// [`Element`] to render.
1685pub struct Columns<'a, Message> {
1686    children: Vec<Element<'a, Message>>,
1687    breakpoint: f32,
1688    spacing: f32,
1689}
1690
1691impl<Message> std::fmt::Debug for Columns<'_, Message> {
1692    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1693        f.debug_struct("Columns")
1694            .field("children", &self.children.len())
1695            .field("breakpoint", &self.breakpoint)
1696            .field("spacing", &self.spacing)
1697            .finish()
1698    }
1699}
1700
1701/// Lays `children` out in two equal columns, filling each row left to
1702/// right. Where there is less room than the [`breakpoint`](Columns::breakpoint)
1703/// they stack in a single column instead.
1704pub fn columns<'a, Message>(
1705    children: impl IntoIterator<Item = Element<'a, Message>>,
1706) -> Columns<'a, Message> {
1707    Columns {
1708        children: children.into_iter().collect(),
1709        breakpoint: BREAKPOINT,
1710        spacing: space::XL,
1711    }
1712}
1713
1714impl<'a, Message> Columns<'a, Message> {
1715    /// Adds a child.
1716    pub fn push(mut self, child: impl Into<Element<'a, Message>>) -> Self {
1717        self.children.push(child.into());
1718        self
1719    }
1720
1721    /// The narrowest width, in logical pixels, that still gets two columns.
1722    /// Defaults to [`BREAKPOINT`].
1723    pub fn breakpoint(mut self, width: f32) -> Self {
1724        self.breakpoint = width;
1725        self
1726    }
1727
1728    /// The gap between the columns and between the rows. Defaults to 24.
1729    pub fn spacing(mut self, spacing: f32) -> Self {
1730        self.spacing = spacing;
1731        self
1732    }
1733}
1734
1735impl<'a, Message: 'a> From<Columns<'a, Message>> for Element<'a, Message> {
1736    fn from(columns: Columns<'a, Message>) -> Self {
1737        Element::new(columns)
1738    }
1739}
1740
1741impl<Message> Widget<Message, Theme, Renderer> for Columns<'_, Message> {
1742    fn size(&self) -> Bounds<Length> {
1743        Bounds::new(Length::Fill, Length::Shrink)
1744    }
1745
1746    fn children(&self) -> Vec<Tree> {
1747        self.children.iter().map(Tree::new).collect()
1748    }
1749
1750    fn diff(&self, tree: &mut Tree) {
1751        tree.diff_children(&self.children);
1752    }
1753
1754    fn layout(
1755        &mut self,
1756        tree: &mut Tree,
1757        renderer: &Renderer,
1758        limits: &layout::Limits,
1759    ) -> layout::Node {
1760        let max = limits.max();
1761        let (count, cell) = cells(max.width, self.breakpoint, self.spacing);
1762        let cell_limits = layout::Limits::new(Bounds::ZERO, Bounds::new(cell, max.height));
1763
1764        let mut nodes = Vec::with_capacity(self.children.len());
1765        let mut y = 0.0;
1766        let mut width: f32 = 0.0;
1767        for (children, trees) in self
1768            .children
1769            .chunks_mut(count)
1770            .zip(tree.children.chunks_mut(count))
1771        {
1772            let mut height: f32 = 0.0;
1773            for (column, (child, tree)) in children.iter_mut().zip(trees).enumerate() {
1774                let node = child.as_widget_mut().layout(tree, renderer, &cell_limits);
1775                let x = column as f32 * (cell + self.spacing);
1776                let size = node.size();
1777                height = height.max(size.height);
1778                width = width.max(x + size.width);
1779                nodes.push(node.move_to(Point::new(x, y)));
1780            }
1781            y += height + self.spacing;
1782        }
1783        let height = if nodes.is_empty() {
1784            0.0
1785        } else {
1786            y - self.spacing
1787        };
1788
1789        let intrinsic = Bounds::new(width, height);
1790        let size = if max.width.is_finite() {
1791            limits.resolve(Length::Fill, Length::Shrink, intrinsic)
1792        } else {
1793            intrinsic
1794        };
1795        layout::Node::with_children(size, nodes)
1796    }
1797
1798    fn draw(
1799        &self,
1800        tree: &Tree,
1801        renderer: &mut Renderer,
1802        theme: &Theme,
1803        style: &renderer::Style,
1804        layout: Layout<'_>,
1805        cursor: mouse::Cursor,
1806        viewport: &Rectangle,
1807    ) {
1808        for ((child, tree), layout) in self
1809            .children
1810            .iter()
1811            .zip(&tree.children)
1812            .zip(layout.children())
1813        {
1814            child
1815                .as_widget()
1816                .draw(tree, renderer, theme, style, layout, cursor, viewport);
1817        }
1818    }
1819
1820    fn operate(
1821        &mut self,
1822        tree: &mut Tree,
1823        layout: Layout<'_>,
1824        renderer: &Renderer,
1825        operation: &mut dyn Operation,
1826    ) {
1827        operate_all(&mut self.children, tree, layout, renderer, operation);
1828    }
1829
1830    fn update(
1831        &mut self,
1832        tree: &mut Tree,
1833        event: &Event,
1834        layout: Layout<'_>,
1835        cursor: mouse::Cursor,
1836        renderer: &Renderer,
1837        clipboard: &mut dyn Clipboard,
1838        shell: &mut Shell<'_, Message>,
1839        viewport: &Rectangle,
1840    ) {
1841        for ((child, tree), layout) in self
1842            .children
1843            .iter_mut()
1844            .zip(&mut tree.children)
1845            .zip(layout.children())
1846        {
1847            child.as_widget_mut().update(
1848                tree, event, layout, cursor, renderer, clipboard, shell, viewport,
1849            );
1850        }
1851    }
1852
1853    fn mouse_interaction(
1854        &self,
1855        tree: &Tree,
1856        layout: Layout<'_>,
1857        cursor: mouse::Cursor,
1858        viewport: &Rectangle,
1859        renderer: &Renderer,
1860    ) -> mouse::Interaction {
1861        interaction_of_all(&self.children, tree, layout, cursor, viewport, renderer)
1862    }
1863
1864    fn overlay<'b>(
1865        &'b mut self,
1866        tree: &'b mut Tree,
1867        layout: Layout<'b>,
1868        renderer: &Renderer,
1869        viewport: &Rectangle,
1870        translation: Vector,
1871    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1872        overlay::from_children(
1873            &mut self.children,
1874            tree,
1875            layout,
1876            renderer,
1877            viewport,
1878            translation,
1879        )
1880    }
1881}
1882
1883#[cfg(test)]
1884mod tests {
1885    use super::*;
1886    use crate::theme::{dark, light};
1887
1888    fn slots(layout: &[(bool, bool)]) -> Vec<Slot> {
1889        layout
1890            .iter()
1891            .map(|&(inside, focused)| Slot {
1892                inside,
1893                focused,
1894                control: false,
1895            })
1896            .collect()
1897    }
1898
1899    #[test]
1900    fn a_captured_close_still_dismisses_when_it_only_unfocused_a_field() {
1901        assert!(dismisses_anyway(true, false));
1902        assert!(!dismisses_anyway(true, true), "something else used the key");
1903        assert!(!dismisses_anyway(false, false));
1904        assert!(!dismisses_anyway(false, true));
1905    }
1906
1907    #[test]
1908    fn the_survey_marks_controls_and_finds_focus_inside() {
1909        let mut survey = Survey::new(DEFAULT_ID);
1910        let mut field = focus::State::default();
1911        let mut control = focus::State::default();
1912        let bounds = Rectangle::with_size(Bounds::new(10.0, 10.0));
1913        survey.container(Some(&DEFAULT_ID), bounds);
1914        survey.traverse(&mut |operation| {
1915            operation.focusable(None, bounds, &mut field);
1916            focus::report(operation, None, bounds, &mut control);
1917        });
1918        assert_eq!(
1919            survey
1920                .slots
1921                .iter()
1922                .map(|slot| slot.control)
1923                .collect::<Vec<_>>(),
1924            vec![false, true]
1925        );
1926        assert!(survey.slots.iter().all(|slot| slot.inside));
1927        assert!(!survey.has_focus_inside());
1928
1929        let mut outside = Survey::new(DEFAULT_ID);
1930        Focusable::focus(&mut field);
1931        outside.focusable(None, bounds, &mut field);
1932        assert!(!outside.has_focus_inside(), "focus outside the surface");
1933    }
1934
1935    #[test]
1936    fn builder_defaults() {
1937        let d: Dialog<'_, ()> = dialog(text("Base"));
1938        assert!(!d.is_open());
1939        assert!(d.dismiss_on_escape);
1940        assert!(d.dismiss_on_scrim);
1941        assert!(d.close_button);
1942        assert!(d.on_dismiss.is_none());
1943        assert_eq!(d.width, Size::Md.width());
1944        assert_eq!(d.max_height, f32::INFINITY);
1945        assert_eq!(d.id, DEFAULT_ID);
1946        assert_eq!(d.keymap, default_keymap());
1947        assert!(d.pass_through.is_empty());
1948    }
1949
1950    #[test]
1951    fn builder_sets_every_option() {
1952        let d = dialog::<u8>(text("Base"))
1953            .open(true)
1954            .title("Title")
1955            .description("Description")
1956            .body(text("Body"))
1957            .action(text("One"))
1958            .action(text("Two"))
1959            .on_dismiss(1)
1960            .dismiss_on_escape(false)
1961            .dismiss_on_scrim(false)
1962            .close_button(false)
1963            .size(Size::Lg)
1964            .max_height(420.0)
1965            .id("custom")
1966            .keymap(Keymap::new())
1967            .pass_through([Chord::character('k').command()]);
1968        assert_eq!(d.pass_through, vec![Chord::character('k').command()]);
1969        assert!(d.is_open());
1970        assert_eq!(d.title.as_deref(), Some("Title"));
1971        assert_eq!(d.description.as_deref(), Some("Description"));
1972        assert!(d.body.is_some());
1973        assert_eq!(d.actions.len(), 2);
1974        assert_eq!(d.on_dismiss, Some(1));
1975        assert!(!d.dismiss_on_escape && !d.dismiss_on_scrim && !d.close_button);
1976        assert_eq!(d.width, 640.0);
1977        assert_eq!(d.max_height, 420.0);
1978        assert_eq!(d.id, widget::Id::new("custom"));
1979        assert!(d.keymap.is_empty());
1980        assert_eq!(dialog::<u8>(text("Base")).width(300.0).width, 300.0);
1981    }
1982
1983    #[test]
1984    fn sizes_grow_monotonically() {
1985        let widths = Size::ALL.map(Size::width);
1986        assert!(widths.windows(2).all(|w| w[0] < w[1]));
1987        assert_eq!(Size::default(), Size::Md);
1988    }
1989
1990    #[test]
1991    fn alert_dialog_needs_an_explicit_answer() {
1992        let alert = alert_dialog::<u8>(text("Base"), "Delete file?", "This cannot be undone.")
1993            .open(true)
1994            .confirm("Delete")
1995            .on_cancel(1)
1996            .on_confirm(2);
1997        assert_eq!(alert.cancel.as_ref(), "Cancel");
1998        assert_eq!(alert.confirm.as_ref(), "Delete");
1999
2000        let d = Dialog::from(alert);
2001        assert!(d.is_open());
2002        assert!(!d.dismiss_on_scrim);
2003        assert!(!d.close_button);
2004        assert!(d.dismiss_on_escape);
2005        assert_eq!(d.on_dismiss, Some(1));
2006        assert_eq!(d.on_confirm, None, "Enter does not destroy by default");
2007        assert_eq!(d.actions.len(), 2);
2008    }
2009
2010    #[test]
2011    fn alert_dialog_can_cancel_on_the_scrim() {
2012        let alert = alert_dialog::<u8>(text("Base"), "Discard draft?", "It has not been saved.");
2013        assert!(!alert.dismiss_on_scrim);
2014
2015        let d = Dialog::from(alert.on_cancel(1).dismiss_on_scrim(true));
2016        assert!(d.dismiss_on_scrim);
2017        assert_eq!(d.on_dismiss, Some(1), "the scrim sends on_cancel");
2018    }
2019
2020    #[test]
2021    fn the_body_gets_what_the_header_footer_and_gaps_leave() {
2022        assert_eq!(room(600.0, 100.0, 16.0, 3), 600.0 - 100.0 - 32.0);
2023        assert_eq!(room(600.0, 100.0, 16.0, 1), 500.0);
2024        assert_eq!(room(100.0, 200.0, 16.0, 3), 0.0, "never negative");
2025        assert_eq!(room(f32::INFINITY, 50.0, 16.0, 2), f32::INFINITY);
2026        assert_eq!(room(100.0, 0.0, 16.0, 0), 100.0);
2027    }
2028
2029    #[test]
2030    fn stacking_places_nodes_under_each_other() {
2031        let nodes = [Bounds::new(40.0, 10.0), Bounds::new(80.0, 20.0)]
2032            .map(layout::Node::new)
2033            .to_vec();
2034        let (placed, size) = stack_vertically(nodes, 5.0);
2035        assert_eq!(size, Bounds::new(80.0, 35.0));
2036        assert_eq!(placed[1].bounds().y, 15.0);
2037        assert_eq!(stack_vertically([], 5.0).1, Bounds::ZERO);
2038    }
2039
2040    #[test]
2041    fn reveal_scrolls_a_hidden_field_into_view() {
2042        let viewport = Rectangle::new(Point::new(0.0, 100.0), Bounds::new(300.0, 200.0));
2043        let content = Rectangle::new(Point::new(0.0, 100.0), Bounds::new(300.0, 800.0));
2044        let field = |y: f32| Rectangle::new(Point::new(0.0, 100.0 + y), Bounds::new(300.0, 40.0));
2045
2046        assert_eq!(reveal(viewport, content, 0.0, field(50.0)), None, "in view");
2047        assert_eq!(
2048            reveal(viewport, content, 0.0, field(400.0)),
2049            Some(400.0 + 40.0 + REVEAL_MARGIN - 200.0),
2050            "below: its bottom lines up with the bottom"
2051        );
2052        assert_eq!(
2053            reveal(viewport, content, 300.0, field(100.0)),
2054            Some(100.0 - REVEAL_MARGIN),
2055            "above: its top lines up with the top"
2056        );
2057        let tall = Rectangle::new(Point::new(0.0, 500.0), Bounds::new(300.0, 300.0));
2058        assert_eq!(
2059            reveal(viewport, content, 0.0, tall),
2060            Some(400.0 - REVEAL_MARGIN),
2061            "a field taller than the view shows its top"
2062        );
2063        let elsewhere = Rectangle::new(Point::new(0.0, 1000.0), Bounds::new(300.0, 40.0));
2064        assert_eq!(reveal(viewport, content, 0.0, elsewhere), None);
2065    }
2066
2067    #[test]
2068    fn columns_fall_back_to_one_below_the_breakpoint() {
2069        assert_eq!(cells(464.0, BREAKPOINT, 24.0), (2, 220.0));
2070        assert_eq!(cells(BREAKPOINT, BREAKPOINT, 24.0), (2, 188.0));
2071        assert_eq!(
2072            cells(BREAKPOINT - 1.0, BREAKPOINT, 24.0),
2073            (1, BREAKPOINT - 1.0)
2074        );
2075        assert_eq!(cells(280.0, 200.0, 0.0), (2, 140.0));
2076        assert_eq!(cells(f32::INFINITY, BREAKPOINT, 24.0).0, 1);
2077    }
2078
2079    #[test]
2080    fn columns_and_sections_builders() {
2081        let c = columns::<()>([text("A").into()])
2082            .push(text("B"))
2083            .breakpoint(320.0)
2084            .spacing(8.0);
2085        assert_eq!(c.children.len(), 2);
2086        assert_eq!(c.breakpoint, 320.0);
2087        assert_eq!(c.spacing, 8.0);
2088        let d = columns::<()>([]);
2089        assert_eq!((d.breakpoint, d.spacing), (BREAKPOINT, space::XL));
2090
2091        let s = section::<()>("Event", text("Body")).description("When and where");
2092        assert_eq!(s.title.as_ref(), "Event");
2093        assert_eq!(s.description.as_deref(), Some("When and where"));
2094        const { assert!(SECTION_TITLE_SIZE < text_size::LG) };
2095    }
2096
2097    #[test]
2098    fn alert_dialog_confirms_on_enter_only_when_asked() {
2099        let alert = alert_dialog::<u8>(text("Base"), "Delete file?", "This cannot be undone.")
2100            .on_confirm(2)
2101            .confirm_on_enter(true);
2102        assert_eq!(Dialog::from(alert).on_confirm, Some(2));
2103    }
2104
2105    #[test]
2106    fn alert_dialog_without_cancel_has_no_dismiss() {
2107        let d = Dialog::from(
2108            alert_dialog::<u8>(text("Base"), "Title", "Description").dismiss_on_escape(false),
2109        );
2110        assert!(d.on_dismiss.is_none());
2111        assert!(d.on_confirm.is_none());
2112        assert!(!d.dismiss_on_escape);
2113    }
2114
2115    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
2116        let chord: Chord = chord.parse().ok()?;
2117        keymap.resolve(chord.key(), chord.modifiers())
2118    }
2119
2120    #[test]
2121    fn default_keymap_and_overrides() {
2122        let keymap = default_keymap();
2123        assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
2124        assert_eq!(press(&keymap, "Enter"), Some(Action::Confirm));
2125        assert_eq!(press(&keymap, "Shift+Enter"), None);
2126        assert_eq!(press(&keymap, "Tab"), Some(Action::FocusNext));
2127        assert_eq!(press(&keymap, "Shift+Tab"), Some(Action::FocusPrevious));
2128        assert_eq!(press(&keymap, "Ctrl+Tab"), None);
2129
2130        let custom = keymap
2131            .unbind(&Chord::named(Named::Escape))
2132            .bind(Chord::character('w').command(), Action::Close);
2133        assert_eq!(press(&custom, "Escape"), None);
2134        assert_eq!(press(&custom, "Mod+W"), Some(Action::Close));
2135        assert!(
2136            custom
2137                .unbind_action(&Action::Close)
2138                .chords(&Action::Close)
2139                .is_empty()
2140        );
2141    }
2142
2143    #[test]
2144    fn close_only_dismisses_when_escape_is_allowed() {
2145        assert_eq!(Action::Close.effect(true), Some(Effect::Dismiss));
2146        assert_eq!(Action::Close.effect(false), None);
2147        for allowed in [true, false] {
2148            assert_eq!(Action::Confirm.effect(allowed), Some(Effect::Confirm));
2149            assert_eq!(
2150                Action::FocusNext.effect(allowed),
2151                Some(Effect::Focus(Direction::Next))
2152            );
2153            assert_eq!(
2154                Action::FocusPrevious.effect(allowed),
2155                Some(Effect::Focus(Direction::Previous))
2156            );
2157        }
2158    }
2159
2160    #[test]
2161    fn every_action_has_a_name_and_a_sentence() {
2162        use keys::Action as _;
2163        for action in Action::ALL {
2164            assert!(!action.name().is_empty());
2165            assert!(action.description().ends_with('.'));
2166        }
2167    }
2168
2169    #[test]
2170    fn first_focuses_the_first_field_inside() {
2171        let layout = slots(&[(false, true), (true, false), (true, false)]);
2172        assert_eq!(target(&layout, Movement::First), Some(1));
2173    }
2174
2175    #[test]
2176    fn opening_skips_controls_but_tab_reaches_them() {
2177        let mut layout = slots(&[(true, false), (true, false)]);
2178        for slot in &mut layout {
2179            slot.control = true;
2180        }
2181        assert_eq!(target(&layout, Movement::First), None);
2182        assert_eq!(target(&layout, Movement::Next), Some(0));
2183        assert_eq!(target(&layout, Movement::Previous), Some(1));
2184
2185        layout[1].control = false;
2186        assert_eq!(target(&layout, Movement::First), Some(1));
2187    }
2188
2189    #[test]
2190    fn next_and_previous_wrap_inside_the_dialog() {
2191        let last = slots(&[(false, false), (true, false), (true, true), (false, false)]);
2192        assert_eq!(target(&last, Movement::Next), Some(1));
2193        assert_eq!(target(&last, Movement::Previous), Some(1));
2194
2195        let first = slots(&[(true, true), (true, false), (true, false)]);
2196        assert_eq!(target(&first, Movement::Previous), Some(2));
2197        assert_eq!(target(&first, Movement::Next), Some(1));
2198    }
2199
2200    #[test]
2201    fn focus_outside_moves_to_either_end_inside() {
2202        let layout = slots(&[(false, true), (true, false), (true, false), (false, false)]);
2203        assert_eq!(target(&layout, Movement::Next), Some(1));
2204        assert_eq!(target(&layout, Movement::Previous), Some(2));
2205    }
2206
2207    #[test]
2208    fn nothing_to_focus_without_fields_inside() {
2209        let layout = slots(&[(false, true), (false, false)]);
2210        for movement in [Movement::First, Movement::Next, Movement::Previous] {
2211            assert_eq!(target(&layout, movement), None);
2212        }
2213        assert_eq!(target(&[], Movement::Next), None);
2214    }
2215
2216    #[test]
2217    fn a_single_field_keeps_focus() {
2218        let layout = slots(&[(true, true)]);
2219        assert_eq!(target(&layout, Movement::Next), Some(0));
2220        assert_eq!(target(&layout, Movement::Previous), Some(0));
2221    }
2222
2223    #[test]
2224    fn surface_uses_the_shared_floating_style() {
2225        for theme in [light(), dark()] {
2226            let tokens = Tokens::of(&theme);
2227            let style = surface_style(&tokens);
2228            let shared = anchored::surface_style(&tokens);
2229            assert_eq!(style.background, Some(Background::Color(tokens.popover)));
2230            assert_eq!(style.text_color, Some(tokens.foreground));
2231            assert_eq!(style.border.color, tokens.border);
2232            assert_eq!(style.border.width, 1.0);
2233            assert_eq!(style.border.radius, radius::LG.into());
2234            assert_eq!(style.shadow, shared.shadow);
2235        }
2236    }
2237
2238    #[test]
2239    fn dark_theme_has_a_stronger_shadow_and_scrim() {
2240        let light = Tokens::of(&light());
2241        let dark = Tokens::of(&dark());
2242        assert!(surface_style(&dark).shadow.color.a > surface_style(&light).shadow.color.a);
2243
2244        let alpha = |tokens: &Tokens| match scrim_style(tokens).background {
2245            Some(Background::Color(colour)) => colour.a,
2246            _ => 0.0,
2247        };
2248        assert!((alpha(&light) - 0.5).abs() < 1e-6);
2249        assert!((alpha(&dark) - 0.7).abs() < 1e-6);
2250    }
2251}