Skip to main content

sui_widgets/composites/
dialogs.rs

1use crate::Button;
2use crate::ButtonAppearance;
3use crate::DefaultTheme;
4use crate::Progress;
5use crate::SemanticTone;
6use crate::animation::AnimationSpec;
7use crate::animation::Reveal;
8use crate::binding::Binding;
9use crate::composites::forms::set_focus_animation_target;
10use crate::composites::indicators::text_token_style;
11use crate::composites::popups::request_child_invalidation;
12use crate::draw::measure_text;
13use crate::frame::{draw_control_frame, draw_focus_ring, physical_pixels, stroke_border};
14use crate::paint_theme_shadow;
15use crate::text_align::paint_text;
16use std::cell::RefCell;
17use std::rc::Rc;
18use sui_core::Event;
19use sui_core::InvalidationKind;
20use sui_core::KeyState;
21use sui_core::Point;
22use sui_core::PointerButton;
23use sui_core::PointerEventKind;
24use sui_core::Rect;
25use sui_core::SemanticsAction;
26use sui_core::SemanticsNode;
27use sui_core::SemanticsRole;
28use sui_core::Size;
29use sui_core::Transform;
30use sui_core::Vector;
31use sui_core::WakeEvent;
32use sui_core::WidgetId;
33use sui_layout::Constraints;
34use sui_reactive::{Observable, Signal};
35use sui_runtime::ArrangeCtx;
36use sui_runtime::Command;
37use sui_runtime::EventCtx;
38use sui_runtime::FrameClock;
39use sui_runtime::LayerOptions;
40use sui_runtime::MeasureCtx;
41use sui_runtime::OVERLAY_DISMISS_REQUEST;
42use sui_runtime::OverlayDismissPolicy;
43use sui_runtime::OverlayFocusBehavior;
44use sui_runtime::OverlayKind;
45use sui_runtime::OverlayOptions;
46use sui_runtime::PaintBoundaryMode;
47use sui_runtime::PaintCtx;
48use sui_runtime::SemanticsCtx;
49use sui_runtime::SingleChild;
50use sui_runtime::StackSurfaceOptions;
51use sui_runtime::Widget;
52use sui_runtime::WidgetChildren;
53use sui_runtime::WidgetPod;
54use sui_runtime::WidgetPodMutVisitor;
55use sui_runtime::WidgetPodVisitor;
56use sui_scene::LayerCompositionMode;
57use sui_scene::LayerProperties;
58use sui_text::TextStyle;
59use sui_text::{TextAlign, TextMeasurement};
60
61/// A theme source shared between a surface and the action buttons it builds.
62/// Actions read the surface's current theme through it, so they follow
63/// `theme(...)` and `theme_when(...)` regardless of builder call order and
64/// keep following live theme switches.
65#[derive(Clone)]
66pub(super) struct SharedTheme(Rc<RefCell<SharedThemeSource>>);
67
68enum SharedThemeSource {
69    Fixed(Box<DefaultTheme>),
70    Live(Box<dyn Fn() -> DefaultTheme>),
71}
72
73impl SharedTheme {
74    pub(super) fn new() -> Self {
75        Self(Rc::new(RefCell::new(SharedThemeSource::Fixed(
76            Box::default(),
77        ))))
78    }
79
80    pub(super) fn set(&self, theme: DefaultTheme) {
81        *self.0.borrow_mut() = SharedThemeSource::Fixed(Box::new(theme));
82    }
83
84    pub(super) fn set_reader(&self, reader: impl Fn() -> DefaultTheme + 'static) {
85        *self.0.borrow_mut() = SharedThemeSource::Live(Box::new(reader));
86    }
87
88    pub(super) fn resolve(&self) -> DefaultTheme {
89        match &*self.0.borrow() {
90            SharedThemeSource::Fixed(theme) => **theme,
91            SharedThemeSource::Live(reader) => reader(),
92        }
93    }
94
95    /// A reader for child widgets that always resolves the current source.
96    pub(super) fn reader(&self) -> impl Fn() -> DefaultTheme + 'static {
97        let shared = self.clone();
98        move || shared.resolve()
99    }
100}
101
102#[derive(Debug, Clone)]
103pub(super) struct DialogFocusState {
104    pub(super) theme: DefaultTheme,
105    pub(super) frame: Rect,
106    pub(super) shown: bool,
107    pub(super) animation: Progress,
108}
109
110impl DialogFocusState {
111    pub(super) fn new() -> Self {
112        Self {
113            theme: DefaultTheme::default(),
114            frame: Rect::ZERO,
115            shown: false,
116            animation: Progress::new(0.0),
117        }
118    }
119}
120
121pub(super) struct DialogFocusSurface {
122    pub(super) state: Rc<RefCell<DialogFocusState>>,
123}
124
125impl DialogFocusSurface {
126    pub(super) fn new(state: Rc<RefCell<DialogFocusState>>) -> Self {
127        Self { state }
128    }
129}
130
131impl Widget for DialogFocusSurface {
132    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
133        let state = self.state.borrow();
134        if state.shown {
135            state.frame.size
136        } else {
137            Size::ZERO
138        }
139    }
140
141    fn paint(&self, ctx: &mut PaintCtx) {
142        let state = self.state.borrow();
143        if !state.shown {
144            return;
145        }
146        let progress = state.animation.get(ctx);
147        if progress <= Progress::EPSILON {
148            return;
149        }
150        let metrics = state.theme.metrics;
151        draw_focus_ring(
152            ctx,
153            ctx.bounds(),
154            metrics.corner_radius + 3.0,
155            metrics,
156            state
157                .theme
158                .palette
159                .focus_ring
160                .with_alpha(state.theme.palette.focus_ring.alpha * progress),
161        );
162    }
163
164    fn layer_options(&self) -> LayerOptions {
165        LayerOptions {
166            paint_boundary: PaintBoundaryMode::Explicit,
167            composition_mode: LayerCompositionMode::Normal,
168        }
169    }
170
171    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
172        let state = self.state.borrow();
173        state.shown.then_some(StackSurfaceOptions {
174            transient: true,
175            hit_test: false,
176            ..StackSurfaceOptions::default()
177        })
178    }
179}
180
181#[doc(alias = "Modal")]
182pub struct Dialog {
183    pub(super) theme: SharedTheme,
184    pub(super) title: String,
185    pub(super) description: Option<String>,
186    pub(super) shown: bool,
187    pub(super) open_binding: Binding<bool>,
188    pub(super) modal: bool,
189    pub(super) dismiss_on_scrim: bool,
190    pub(super) max_width: Option<f32>,
191    pub(super) header_action: Option<SingleChild>,
192    pub(super) body: SingleChild,
193    pub(super) actions: WidgetChildren,
194    pub(super) body_frame: Rect,
195    pub(super) dialog_frame: Rect,
196    pub(super) title_measurement: Option<TextMeasurement>,
197    pub(super) description_measurement: Option<TextMeasurement>,
198    pub(super) reveal: Reveal,
199    pub(super) focus_animation: Progress,
200    pub(super) focus_state: Rc<RefCell<DialogFocusState>>,
201    pub(super) focus_surface: SingleChild,
202    pub(super) entrance_started: bool,
203    pub(super) on_dismiss: Option<Box<dyn FnMut()>>,
204    pub(super) on_dismiss_with_ctx: Option<Box<dyn FnMut(&mut EventCtx)>>,
205    pub(super) overlay_kind: OverlayKind,
206    /// Laid out in flow at its content size; see [`Dialog::show_inline`].
207    pub(super) inline: bool,
208}
209
210impl Dialog {
211    pub fn new<W>(title: impl Into<String>, body: W) -> Self
212    where
213        W: Widget + 'static,
214    {
215        let focus_state = Rc::new(RefCell::new(DialogFocusState::new()));
216        Self {
217            theme: SharedTheme::new(),
218            title: title.into(),
219            description: None,
220            shown: true,
221            open_binding: Binding::new(true),
222            modal: true,
223            dismiss_on_scrim: false,
224            max_width: None,
225            header_action: None,
226            body: SingleChild::new(body),
227            actions: WidgetChildren::new(),
228            body_frame: Rect::ZERO,
229            dialog_frame: Rect::ZERO,
230            title_measurement: None,
231            description_measurement: None,
232            reveal: Reveal::new(0.0),
233            focus_animation: Progress::new(0.0),
234            focus_surface: SingleChild::new(DialogFocusSurface::new(Rc::clone(&focus_state))),
235            focus_state,
236            entrance_started: false,
237            on_dismiss: None,
238            on_dismiss_with_ctx: None,
239            overlay_kind: OverlayKind::Dialog,
240            inline: false,
241        }
242    }
243
244    /// Lays the dialog surface out in flow at its content size, without a
245    /// scrim, entrance animation, or dismissal, instead of centering it in the
246    /// window overlay stack. Widget galleries and documentation use this to
247    /// show a dialog beside other content.
248    pub fn show_inline(mut self) -> Self {
249        self.inline = true;
250        self.modal = false;
251        self.shown = true;
252        self.open_binding.set(true);
253        self.reveal = Reveal::new(1.0);
254        self.entrance_started = true;
255        self
256    }
257
258    pub fn theme(self, theme: DefaultTheme) -> Self {
259        self.theme.set(theme);
260        self
261    }
262
263    /// Resolve the theme on every layout and paint, including for the
264    /// dialog's built-in action buttons.
265    pub fn theme_when<F>(self, theme: F) -> Self
266    where
267        F: Fn() -> DefaultTheme + 'static,
268    {
269        self.theme.set_reader(theme);
270        self
271    }
272
273    pub(super) fn resolved_theme(&self) -> DefaultTheme {
274        self.theme.resolve()
275    }
276
277    pub fn description(mut self, description: impl Into<String>) -> Self {
278        self.description = Some(description.into());
279        self
280    }
281
282    /// Whether the dialog is open; it is open from the start. A dialog never
283    /// closes itself: when the user asks to close it, it calls
284    /// [`Self::on_dismiss`], and the app closes it.
285    pub fn open(mut self, open: bool) -> Self {
286        self.set_open(open);
287        self
288    }
289
290    /// [`Self::open`], read each time the dialog lays out.
291    pub fn open_when<F>(mut self, open: F) -> Self
292    where
293        F: Fn() -> bool + 'static,
294    {
295        self.open_binding.set_when(open);
296        self.sync_open();
297        self
298    }
299
300    /// [`Self::open`], following an observable and laying out again when it
301    /// changes.
302    pub fn open_from<O>(mut self, open: O) -> Self
303    where
304        O: Observable<bool> + 'static,
305    {
306        self.open_binding.set_from(open);
307        self.sync_open();
308        self
309    }
310
311    pub fn is_open(&self) -> bool {
312        self.shown
313    }
314
315    /// Open or close a built dialog, returning whether that changed it.
316    pub fn set_open(&mut self, open: bool) -> bool {
317        self.open_binding.set(open);
318        self.apply_open(open)
319    }
320
321    pub(super) fn sync_open(&mut self) {
322        if let Some(open) = self.open_binding.live() {
323            self.apply_open(open);
324        }
325    }
326
327    fn apply_open(&mut self, shown: bool) -> bool {
328        if self.shown == shown {
329            return false;
330        }
331        self.shown = shown;
332        if !shown {
333            self.reveal = Reveal::new(0.0);
334            self.focus_animation = Progress::new(0.0);
335            self.entrance_started = false;
336            let mut focus = self.focus_state.borrow_mut();
337            focus.shown = false;
338            focus.animation = Progress::new(0.0);
339        }
340        true
341    }
342
343    pub fn modal(mut self, modal: bool) -> Self {
344        self.modal = modal;
345        self
346    }
347
348    pub fn dismiss_on_scrim(mut self, dismiss_on_scrim: bool) -> Self {
349        self.dismiss_on_scrim = dismiss_on_scrim;
350        self
351    }
352
353    /// The widest the dialog grows; never narrower than the theme's
354    /// `dialog_min_width`.
355    pub fn max_width(mut self, max_width: f32) -> Self {
356        self.max_width = Some(max_width);
357        self
358    }
359
360    pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
361    where
362        F: FnMut() + 'static,
363    {
364        self.on_dismiss = Some(Box::new(on_dismiss));
365        self
366    }
367
368    /// [`Self::on_dismiss`], with the event context first.
369    pub fn on_dismiss_with_ctx<F>(mut self, on_dismiss: F) -> Self
370    where
371        F: FnMut(&mut EventCtx) + 'static,
372    {
373        self.on_dismiss_with_ctx = Some(Box::new(on_dismiss));
374        self
375    }
376
377    /// Place a compact control beside the title, such as a close button.
378    pub fn header_action<W: Widget + 'static>(mut self, action: W) -> Self {
379        self.header_action = Some(SingleChild::new(action));
380        self
381    }
382
383    /// Add a footer control or a composed action row outside the scrolling body.
384    pub fn action<W: Widget + 'static>(mut self, action: W) -> Self {
385        self.actions.push(action);
386        self
387    }
388
389    pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
390    where
391        F: FnMut() + 'static,
392    {
393        self.actions.push(
394            Button::primary(label.into())
395                .theme_when(self.theme.reader())
396                .min_width_from_theme(|theme| theme.metrics.dialog_action_min_width)
397                .on_press(on_press),
398        );
399        self
400    }
401
402    pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
403    where
404        F: FnMut() + 'static,
405    {
406        self.actions.push(
407            Button::new(label.into())
408                .theme_when(self.theme.reader())
409                .min_width_from_theme(|theme| theme.metrics.dialog_action_min_width)
410                .on_press(on_press),
411        );
412        self
413    }
414
415    pub(super) fn resolved_max_width(&self) -> f32 {
416        let metrics = self.resolved_theme().metrics;
417        self.max_width
418            .map_or(metrics.dialog_max_width, |max_width| {
419                max_width.max(metrics.dialog_min_width)
420            })
421    }
422
423    pub(super) fn title_style(&self) -> TextStyle {
424        let theme = self.resolved_theme();
425        text_token_style(&theme, theme.text.lg, theme.palette.text)
426    }
427
428    pub(super) fn dismiss(&mut self, ctx: &mut EventCtx) {
429        if self.inline {
430            return;
431        }
432        if let Some(on_dismiss) = &mut self.on_dismiss {
433            on_dismiss();
434        }
435        if let Some(on_dismiss) = &mut self.on_dismiss_with_ctx {
436            on_dismiss(ctx);
437        }
438    }
439
440    pub(super) fn ensure_entrance_started(&mut self, ctx: &mut MeasureCtx) {
441        if self.entrance_started {
442            return;
443        }
444        self.entrance_started = true;
445        let motion = self.resolved_theme().motion;
446        if let Some(until) = self
447            .reveal
448            .start(1.0, ctx.frame_time(), motion.entrance_spec())
449        {
450            ctx.track_motion(until, InvalidationKind::Effect);
451            if !self.modal {
452                ctx.track_motion(until, InvalidationKind::Transform);
453            }
454        }
455    }
456}
457
458impl Widget for Dialog {
459    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
460        self.sync_open();
461        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.shown {
462            self.dismiss(ctx);
463            ctx.request_semantics();
464            ctx.set_handled();
465        }
466    }
467
468    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
469        self.sync_open();
470        if !self.shown {
471            return;
472        }
473
474        match event {
475            Event::Pointer(pointer)
476                if pointer.kind == PointerEventKind::Down
477                    && pointer.button == Some(PointerButton::Primary)
478                    && self
479                        .dialog_frame
480                        .translate(ctx.bounds().origin.to_vector())
481                        .contains(pointer.position) =>
482            {
483                ctx.request_focus();
484                ctx.request_semantics();
485            }
486            Event::Pointer(pointer)
487                if pointer.kind == PointerEventKind::Down
488                    && pointer.button == Some(PointerButton::Primary)
489                    && !self
490                        .dialog_frame
491                        .translate(ctx.bounds().origin.to_vector())
492                        .contains(pointer.position) =>
493            {
494                if self.dismiss_on_scrim {
495                    self.dismiss(ctx);
496                }
497                if self.modal || self.dismiss_on_scrim {
498                    ctx.set_handled();
499                }
500                ctx.request_paint();
501                ctx.request_semantics();
502            }
503            Event::Keyboard(key)
504                if ctx.is_focused() && key.state == KeyState::Pressed && key.key == "Escape" =>
505            {
506                self.dismiss(ctx);
507                ctx.request_paint();
508                ctx.request_semantics();
509                ctx.set_handled();
510            }
511            _ => {}
512        }
513    }
514
515    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
516        self.open_binding.observe(|open| {
517            ctx.observe::<bool, _>(open);
518        });
519        self.sync_open();
520        if !self.shown {
521            self.dialog_frame = Rect::ZERO;
522            self.body_frame = Rect::ZERO;
523            self.reveal = Reveal::new(0.0);
524            self.focus_animation = Progress::new(0.0);
525            self.entrance_started = false;
526            let mut focus = self.focus_state.borrow_mut();
527            focus.shown = false;
528            focus.frame = Rect::ZERO;
529            focus.animation = Progress::new(0.0);
530            return Size::ZERO;
531        }
532        self.ensure_entrance_started(ctx);
533
534        let viewport = constraints.clamp(Size::new(
535            if constraints.max.width.is_finite() {
536                constraints.max.width
537            } else {
538                640.0
539            },
540            if constraints.max.height.is_finite() {
541                constraints.max.height
542            } else if self.inline {
543                f32::MAX / 4.0
544            } else {
545                420.0
546            },
547        ));
548        let theme = self.resolved_theme();
549        let metrics = theme.metrics;
550        let outer_margin = if self.inline {
551            0.0
552        } else {
553            metrics.dialog_outer_margin
554        };
555        let padding = metrics.dialog_padding;
556        let title_style = self.title_style();
557        let description_style = theme.placeholder_text_style();
558        self.title_measurement = Some(measure_text(ctx, &self.title, &title_style));
559        self.description_measurement = self
560            .description
561            .as_ref()
562            .map(|text| measure_text(ctx, text, &description_style));
563
564        let available_width = (viewport.width - outer_margin * 2.0).max(0.0);
565        let dialog_width = available_width
566            .min(self.resolved_max_width())
567            .max(metrics.dialog_min_width.min(available_width));
568        let content_width = (dialog_width - padding.left - padding.right).max(0.0);
569        let header_action_size = self.header_action.as_mut().map_or(Size::ZERO, |action| {
570            action.measure(
571                ctx,
572                Constraints::new(
573                    Size::ZERO,
574                    Size::new(content_width, metrics.touch_target_size),
575                ),
576            )
577        });
578        let mut footer_height: f32 = 0.0;
579        for button in self.actions.as_mut_slice().iter_mut() {
580            let button_size = button.measure(
581                ctx,
582                Constraints::new(Size::ZERO, Size::new(content_width, viewport.height)),
583            );
584            footer_height = footer_height.max(button_size.height);
585        }
586
587        let title_height = self
588            .title_measurement
589            .map(|measurement| measurement.height.max(title_style.line_height))
590            .unwrap_or(title_style.line_height)
591            .max(header_action_size.height);
592        let description_height = self
593            .description_measurement
594            .map(|measurement| measurement.height.max(description_style.line_height))
595            .unwrap_or(0.0);
596        let header_gap = if self.description.is_some() {
597            metrics.dialog_description_gap
598        } else {
599            0.0
600        };
601        let body_top =
602            padding.top + title_height + header_gap + description_height + metrics.dialog_body_gap;
603        let footer_gap = if self.actions.is_empty() {
604            0.0
605        } else {
606            metrics.dialog_footer_gap
607        };
608        let body_constraints = Constraints::new(
609            Size::ZERO,
610            Size::new(
611                (dialog_width - padding.left - padding.right).max(0.0),
612                (viewport.height
613                    - outer_margin * 2.0
614                    - body_top
615                    - footer_gap
616                    - footer_height
617                    - padding.bottom)
618                    .max(0.0),
619            ),
620        );
621        let body_size = self.body.measure(ctx, body_constraints);
622
623        let dialog_height =
624            body_top + body_size.height + footer_gap + footer_height + padding.bottom;
625        let (dialog_x, dialog_y) = if self.inline {
626            (0.0, 0.0)
627        } else {
628            (
629                ((viewport.width - dialog_width) * 0.5).max(outer_margin),
630                ((viewport.height - dialog_height) * 0.5).max(outer_margin),
631            )
632        };
633        self.dialog_frame = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);
634        self.body_frame = Rect::new(padding.left, body_top, body_size.width, body_size.height);
635        {
636            let mut focus = self.focus_state.borrow_mut();
637            focus.theme = theme;
638            focus.shown = true;
639            focus.frame = self.dialog_frame;
640            focus.animation = self.focus_animation;
641        }
642        self.focus_surface
643            .measure(ctx, Constraints::tight(self.dialog_frame.size));
644
645        if self.inline {
646            constraints.clamp(self.dialog_frame.size)
647        } else {
648            viewport
649        }
650    }
651
652    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
653        if !self.shown {
654            return;
655        }
656
657        let dialog = self.dialog_frame.translate(bounds.origin.to_vector());
658        self.focus_state.borrow_mut().frame = dialog;
659        self.focus_surface.arrange(ctx, dialog);
660        let title_line_height = self.title_style().line_height;
661        let theme = self.resolved_theme();
662        if let Some(action) = &mut self.header_action {
663            let size = action.child().measured_size();
664            let padding = theme.metrics.dialog_padding;
665            let title_height = self
666                .title_measurement
667                .map(|measurement| measurement.height.max(title_line_height))
668                .unwrap_or(title_line_height)
669                .max(size.height);
670            action.arrange(
671                ctx,
672                Rect::new(
673                    dialog.max_x() - padding.right - size.width,
674                    dialog.y() + padding.top + (title_height - size.height) * 0.5,
675                    size.width,
676                    size.height,
677                ),
678            );
679        }
680        self.body.arrange(
681            ctx,
682            Rect::new(
683                dialog.x() + self.body_frame.x(),
684                dialog.y() + self.body_frame.y(),
685                self.body_frame.width(),
686                self.body_frame.height(),
687            ),
688        );
689
690        if !self.actions.is_empty() {
691            let metrics = theme.metrics;
692            let padding = metrics.dialog_padding;
693            let action_gap = metrics.dialog_action_gap;
694            let footer_width = self
695                .actions
696                .as_slice()
697                .iter()
698                .map(|button| button.measured_size().width)
699                .sum::<f32>()
700                + (action_gap * self.actions.len().saturating_sub(1) as f32);
701            let footer_height = self
702                .actions
703                .as_slice()
704                .iter()
705                .map(|button| button.measured_size().height)
706                .fold(0.0, f32::max);
707            let mut x = dialog.x() + dialog.width() - padding.right - footer_width;
708            let y = dialog.y() + dialog.height() - padding.bottom - footer_height;
709            for button in self.actions.as_mut_slice().iter_mut() {
710                let size = button.measured_size();
711                button.arrange(ctx, Rect::new(x, y, size.width, size.height));
712                x += size.width + action_gap;
713            }
714        }
715    }
716
717    fn paint(&self, ctx: &mut PaintCtx) {
718        if !self.shown {
719            return;
720        }
721
722        let dialog = self.dialog_frame.translate(ctx.bounds().origin.to_vector());
723        let theme = self.resolved_theme();
724
725        if self.modal {
726            ctx.fill_bounds(theme.surfaces.overlay_scrim);
727        }
728
729        let metrics = theme.metrics;
730        let palette = theme.palette;
731        // Prominent elevation shadow behind the dialog surface, drawn over the
732        // (optional) modal backdrop and before the surface fill.
733        let surface_radius = metrics.corner_radius + 3.0;
734        paint_theme_shadow(
735            ctx,
736            dialog,
737            [surface_radius; 4],
738            &theme.shadows.box_shadow.xl,
739        );
740        draw_control_frame(
741            ctx,
742            dialog,
743            surface_radius,
744            metrics,
745            palette.surface_raised,
746            palette.border,
747            None,
748        );
749
750        let title_style = self.title_style();
751        let description_style = theme.placeholder_text_style();
752        let padding = metrics.dialog_padding;
753        let text_x = dialog.x() + padding.left;
754        let text_y = dialog.y() + padding.top;
755        let header_action_size = self
756            .header_action
757            .as_ref()
758            .map(|action| action.child().measured_size())
759            .unwrap_or(Size::ZERO);
760        let action_gap = if self.header_action.is_some() {
761            header_action_size.width + metrics.dialog_action_gap
762        } else {
763            0.0
764        };
765        let text_width = (dialog.width() - padding.left - padding.right - action_gap).max(0.0);
766        let title_height = self
767            .title_measurement
768            .map(|measurement| measurement.height.max(title_style.line_height))
769            .unwrap_or(title_style.line_height)
770            .max(header_action_size.height);
771        let title_slot = Rect::new(text_x, text_y, text_width, title_height);
772        ctx.push_clip_rect(title_slot);
773        paint_text(ctx, title_slot, &self.title, &title_style, TextAlign::Start);
774        ctx.pop_clip();
775        if let Some(description) = &self.description {
776            let description_height = self
777                .description_measurement
778                .map(|measurement| measurement.height.max(description_style.line_height))
779                .unwrap_or(description_style.line_height);
780            let description_slot = Rect::new(
781                text_x,
782                title_slot.max_y() + metrics.dialog_description_gap,
783                (dialog.width() - padding.left - padding.right).max(0.0),
784                description_height,
785            );
786            ctx.push_clip_rect(description_slot);
787            paint_text(
788                ctx,
789                description_slot,
790                description,
791                &description_style,
792                TextAlign::Start,
793            );
794            ctx.pop_clip();
795        }
796
797        if let Some(action) = &self.header_action {
798            action.paint(ctx);
799        }
800        self.body.paint(ctx);
801        for button in self.actions.as_slice() {
802            button.paint(ctx);
803        }
804        self.focus_surface.paint(ctx);
805    }
806
807    fn layer_options(&self) -> LayerOptions {
808        LayerOptions {
809            paint_boundary: PaintBoundaryMode::Explicit,
810            composition_mode: if self.shown && !self.inline {
811                if self.modal {
812                    LayerCompositionMode::Effect
813                } else {
814                    LayerCompositionMode::Overlay
815                }
816            } else {
817                LayerCompositionMode::Normal
818            },
819        }
820    }
821
822    fn layer_properties_at(&self, frame_time: f64) -> LayerProperties {
823        let reveal = self.reveal.at(frame_time);
824        let translation = if self.modal {
825            Vector::ZERO
826        } else {
827            Vector::new(
828                0.0,
829                self.resolved_theme().metrics.popover_reveal_offset
830                    * sui_runtime::motion_policy().entrance_offset(reveal),
831            )
832        };
833        LayerProperties::new(reveal, translation)
834    }
835
836    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
837        (self.shown && !self.inline).then_some(StackSurfaceOptions {
838            transient: true,
839            ..StackSurfaceOptions::default()
840        })
841    }
842
843    fn overlay_options(&self) -> Option<OverlayOptions> {
844        (self.shown && !self.inline).then_some(
845            OverlayOptions::new(self.overlay_kind)
846                .modal(self.modal)
847                .dismiss(OverlayDismissPolicy {
848                    escape: true,
849                    outside_pointer: self.dismiss_on_scrim,
850                })
851                .focus(OverlayFocusBehavior::CONTAINED),
852        )
853    }
854
855    fn semantics(&self, ctx: &mut SemanticsCtx) {
856        if !self.shown {
857            return;
858        }
859
860        let dialog = self.dialog_frame.translate(ctx.bounds().origin.to_vector());
861        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Dialog, dialog);
862        node.name = Some(self.title.clone());
863        node.description = self.description.clone();
864        node.state.focused = ctx.is_focused();
865        node.state.expanded = Some(self.shown);
866        node.state.modal = self.modal;
867        node.actions = vec![SemanticsAction::Focus, SemanticsAction::Collapse];
868        ctx.push(node);
869        if let Some(action) = &self.header_action {
870            action.semantics(ctx);
871        }
872        self.body.semantics(ctx);
873        for button in self.actions.as_slice() {
874            button.semantics(ctx);
875        }
876    }
877
878    fn accepts_focus(&self) -> bool {
879        true
880    }
881
882    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
883        let spec = self.resolved_theme().motion.focus_spec();
884        let focus_surface_id = self.focus_surface.child().id();
885        self.focus_animation
886            .animate_for(focused as u8 as f32, spec, ctx, focus_surface_id);
887        self.focus_state.borrow_mut().animation = self.focus_animation;
888        request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
889        ctx.request_semantics();
890    }
891
892    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
893        if self.shown {
894            if let Some(action) = &self.header_action {
895                action.visit_children(visitor);
896            }
897            self.body.visit_children(visitor);
898            self.actions.visit_children(visitor);
899            self.focus_surface.visit_children(visitor);
900        }
901    }
902
903    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
904        if self.shown {
905            if let Some(action) = &mut self.header_action {
906                action.visit_children_mut(visitor);
907            }
908            self.body.visit_children_mut(visitor);
909            self.actions.visit_children_mut(visitor);
910            self.focus_surface.visit_children_mut(visitor);
911        }
912    }
913}
914
915/// Modal presentation shell for application command search and execution.
916///
917/// Query state, ranking, and command execution remain application policies;
918/// this shell supplies the shared overlay lifecycle and desktop interaction
919/// behavior.
920pub struct CommandPalette {
921    pub(super) inner: Dialog,
922}
923
924impl CommandPalette {
925    pub fn new<W>(name: impl Into<String>, content: W) -> Self
926    where
927        W: Widget + 'static,
928    {
929        let mut inner = Dialog::new(name, content).dismiss_on_scrim(true);
930        inner.overlay_kind = OverlayKind::CommandPalette;
931        Self { inner }
932    }
933
934    pub fn theme(mut self, theme: DefaultTheme) -> Self {
935        self.inner = self.inner.theme(theme);
936        self
937    }
938
939    /// Resolve the theme on every layout and paint.
940    pub fn theme_when<F>(mut self, theme: F) -> Self
941    where
942        F: Fn() -> DefaultTheme + 'static,
943    {
944        self.inner = self.inner.theme_when(theme);
945        self
946    }
947
948    /// Whether the palette is open; see [`Dialog::open`].
949    pub fn open(mut self, open: bool) -> Self {
950        self.inner = self.inner.open(open);
951        self
952    }
953
954    /// [`Self::open`], read each time the palette lays out.
955    pub fn open_when<F>(mut self, open: F) -> Self
956    where
957        F: Fn() -> bool + 'static,
958    {
959        self.inner = self.inner.open_when(open);
960        self
961    }
962
963    /// [`Self::open`], following an observable.
964    pub fn open_from<O>(mut self, open: O) -> Self
965    where
966        O: Observable<bool> + 'static,
967    {
968        self.inner = self.inner.open_from(open);
969        self
970    }
971
972    pub fn is_open(&self) -> bool {
973        self.inner.is_open()
974    }
975
976    /// Open or close a built palette, returning whether that changed it.
977    pub fn set_open(&mut self, open: bool) -> bool {
978        self.inner.set_open(open)
979    }
980
981    pub fn description(mut self, description: impl Into<String>) -> Self {
982        self.inner = self.inner.description(description);
983        self
984    }
985
986    pub fn max_width(mut self, max_width: f32) -> Self {
987        self.inner = self.inner.max_width(max_width);
988        self
989    }
990
991    pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
992    where
993        F: FnMut() + 'static,
994    {
995        self.inner = self.inner.on_dismiss(on_dismiss);
996        self
997    }
998
999    /// [`Self::on_dismiss`], with the event context first.
1000    pub fn on_dismiss_with_ctx<F>(mut self, on_dismiss: F) -> Self
1001    where
1002        F: FnMut(&mut EventCtx) + 'static,
1003    {
1004        self.inner = self.inner.on_dismiss_with_ctx(on_dismiss);
1005        self
1006    }
1007}
1008
1009impl Widget for CommandPalette {
1010    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
1011        self.inner.command(ctx, command);
1012    }
1013
1014    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1015        self.inner.event(ctx, event);
1016    }
1017
1018    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1019        self.inner.measure(ctx, constraints)
1020    }
1021
1022    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1023        self.inner.arrange(ctx, bounds);
1024    }
1025
1026    fn paint(&self, ctx: &mut PaintCtx) {
1027        self.inner.paint(ctx);
1028    }
1029
1030    fn layer_options(&self) -> LayerOptions {
1031        self.inner.layer_options()
1032    }
1033
1034    fn layer_properties(&self) -> LayerProperties {
1035        self.inner.layer_properties()
1036    }
1037
1038    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
1039        self.inner.stack_surface_options()
1040    }
1041
1042    fn overlay_options(&self) -> Option<OverlayOptions> {
1043        self.inner.overlay_options()
1044    }
1045
1046    fn semantics(&self, ctx: &mut SemanticsCtx) {
1047        self.inner.semantics(ctx);
1048    }
1049
1050    fn accepts_focus(&self) -> bool {
1051        self.inner.accepts_focus()
1052    }
1053
1054    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1055        self.inner.focus_changed(ctx, focused);
1056    }
1057
1058    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1059        self.inner.visit_children(visitor);
1060    }
1061
1062    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1063        self.inner.visit_children_mut(visitor);
1064    }
1065}
1066
1067#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1068pub enum SideSheetPlacement {
1069    Left,
1070    #[default]
1071    Right,
1072    Bottom,
1073}
1074
1075/// Cloneable presentation state shared by a sheet and application controls.
1076#[derive(Clone, Debug)]
1077pub struct SheetState {
1078    pub(super) shown: Signal<bool>,
1079}
1080
1081impl SheetState {
1082    pub fn new(shown: bool) -> Self {
1083        Self {
1084            shown: Signal::named("SheetState", shown),
1085        }
1086    }
1087
1088    pub fn is_shown(&self) -> bool {
1089        self.shown.get()
1090    }
1091
1092    pub fn show(&self) -> bool {
1093        self.shown.set(true)
1094    }
1095
1096    pub fn hide(&self) -> bool {
1097        self.shown.set(false)
1098    }
1099
1100    pub fn toggle(&self) -> bool {
1101        self.shown.update(|shown| *shown = !*shown)
1102    }
1103}
1104
1105impl Default for SheetState {
1106    fn default() -> Self {
1107        Self::new(false)
1108    }
1109}
1110
1111/// An overlay panel anchored to a viewport edge.
1112///
1113/// `SideSheet` is suitable for responsive inspectors, conversation drawers,
1114/// and focused configuration flows. It shares SUI's dialog surface, spacing,
1115/// elevation, motion, focus, and semantic contracts while using a horizontal
1116/// reveal appropriate to a drawer.
1117#[doc(alias = "Drawer")]
1118pub struct SideSheet {
1119    pub(super) theme: SharedTheme,
1120    pub(super) title: String,
1121    pub(super) description: Option<String>,
1122    pub(super) shown: bool,
1123    pub(super) open_binding: Binding<bool>,
1124    pub(super) state: Option<SheetState>,
1125    pub(super) modal: bool,
1126    pub(super) dismiss_on_scrim: bool,
1127    pub(super) placement: SideSheetPlacement,
1128    pub(super) width: Option<f32>,
1129    pub(super) height: Option<f32>,
1130    pub(super) body: SingleChild,
1131    pub(super) header_action: Option<SingleChild>,
1132    pub(super) actions: WidgetChildren,
1133    pub(super) sheet_frame: Rect,
1134    pub(super) body_frame: Rect,
1135    pub(super) header_action_frame: Rect,
1136    pub(super) title_measurement: Option<TextMeasurement>,
1137    pub(super) description_measurement: Option<TextMeasurement>,
1138    pub(super) reveal: Progress,
1139    pub(super) focus_animation: Progress,
1140    pub(super) entrance_started: bool,
1141    pub(super) focus_requested: bool,
1142    pub(super) previous_focus: Option<WidgetId>,
1143    pub(super) on_dismiss: Option<Box<dyn FnMut()>>,
1144    pub(super) on_dismiss_with_ctx: Option<Box<dyn FnMut(&mut EventCtx)>>,
1145}
1146
1147impl SideSheet {
1148    pub fn new<W>(title: impl Into<String>, body: W) -> Self
1149    where
1150        W: Widget + 'static,
1151    {
1152        Self {
1153            theme: SharedTheme::new(),
1154            title: title.into(),
1155            description: None,
1156            shown: true,
1157            open_binding: Binding::new(true),
1158            state: None,
1159            modal: true,
1160            dismiss_on_scrim: true,
1161            placement: SideSheetPlacement::Right,
1162            width: None,
1163            height: None,
1164            body: SingleChild::new(body),
1165            header_action: None,
1166            actions: WidgetChildren::new(),
1167            sheet_frame: Rect::ZERO,
1168            body_frame: Rect::ZERO,
1169            header_action_frame: Rect::ZERO,
1170            title_measurement: None,
1171            description_measurement: None,
1172            reveal: Progress::new(0.0),
1173            focus_animation: Progress::new(0.0),
1174            entrance_started: false,
1175            focus_requested: false,
1176            previous_focus: None,
1177            on_dismiss: None,
1178            on_dismiss_with_ctx: None,
1179        }
1180    }
1181
1182    pub fn theme(self, theme: DefaultTheme) -> Self {
1183        self.theme.set(theme);
1184        self
1185    }
1186
1187    pub fn theme_when<F>(self, theme: F) -> Self
1188    where
1189        F: Fn() -> DefaultTheme + 'static,
1190    {
1191        self.theme.set_reader(theme);
1192        self
1193    }
1194
1195    pub fn description(mut self, description: impl Into<String>) -> Self {
1196        self.description = Some(description.into());
1197        self
1198    }
1199
1200    /// Whether the sheet is open; it is open from the start. When the user
1201    /// asks to close it, the sheet calls [`Self::on_dismiss`] and stays open
1202    /// until the app closes it, unless it follows a [`SheetState`], which it
1203    /// hides itself.
1204    pub fn open(mut self, open: bool) -> Self {
1205        self.set_open(open);
1206        self
1207    }
1208
1209    /// [`Self::open`], read each time the sheet lays out.
1210    pub fn open_when<F>(mut self, open: F) -> Self
1211    where
1212        F: Fn() -> bool + 'static,
1213    {
1214        self.state = None;
1215        self.open_binding.set_when(open);
1216        self.sync_open();
1217        self
1218    }
1219
1220    /// [`Self::open`], following an observable and laying out again when it
1221    /// changes.
1222    pub fn open_from<O>(mut self, open: O) -> Self
1223    where
1224        O: Observable<bool> + 'static,
1225    {
1226        self.state = None;
1227        self.open_binding.set_from(open);
1228        self.sync_open();
1229        self
1230    }
1231
1232    pub fn is_open(&self) -> bool {
1233        self.shown
1234    }
1235
1236    /// Read the open state from the sheet's [`SheetState`] or bound value.
1237    pub(super) fn sync_open(&mut self) {
1238        if let Some(state) = &self.state {
1239            self.shown = state.is_shown();
1240        } else if let Some(open) = self.open_binding.live() {
1241            self.shown = open;
1242        }
1243    }
1244
1245    /// Open or close a built sheet, returning whether that changed it.
1246    pub fn set_open(&mut self, shown: bool) -> bool {
1247        self.state = None;
1248        self.open_binding.set(shown);
1249        if self.shown == shown {
1250            return false;
1251        }
1252        self.shown = shown;
1253        if !self.shown {
1254            self.reveal = Progress::new(0.0);
1255            self.focus_animation = Progress::new(0.0);
1256            self.entrance_started = false;
1257            self.focus_requested = false;
1258            self.previous_focus = None;
1259        }
1260        true
1261    }
1262
1263    pub fn state(mut self, state: SheetState) -> Self {
1264        self.shown = state.is_shown();
1265        self.open_binding.set(self.shown);
1266        self.state = Some(state);
1267        self
1268    }
1269
1270    pub fn modal(mut self, modal: bool) -> Self {
1271        self.modal = modal;
1272        self
1273    }
1274
1275    pub fn dismiss_on_scrim(mut self, dismiss_on_scrim: bool) -> Self {
1276        self.dismiss_on_scrim = dismiss_on_scrim;
1277        self
1278    }
1279
1280    pub fn placement(mut self, placement: SideSheetPlacement) -> Self {
1281        self.placement = placement;
1282        self
1283    }
1284
1285    pub fn width(mut self, width: f32) -> Self {
1286        self.width = Some(width.max(0.0));
1287        self
1288    }
1289
1290    /// Set the panel height when placed at [`SideSheetPlacement::Bottom`].
1291    pub fn height(mut self, height: f32) -> Self {
1292        self.height = Some(height.max(0.0));
1293        self
1294    }
1295
1296    pub fn header_action<W>(mut self, action: W) -> Self
1297    where
1298        W: Widget + 'static,
1299    {
1300        self.header_action = Some(SingleChild::new(action));
1301        self
1302    }
1303
1304    pub fn action<W>(mut self, action: W) -> Self
1305    where
1306        W: Widget + 'static,
1307    {
1308        self.actions.push(action);
1309        self
1310    }
1311
1312    pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
1313    where
1314        F: FnMut() + 'static,
1315    {
1316        self.actions.push(
1317            Button::primary(label)
1318                .theme_when(self.theme.reader())
1319                .min_width_from_theme(|theme| theme.metrics.dialog_action_min_width)
1320                .on_press(on_press),
1321        );
1322        self
1323    }
1324
1325    pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
1326    where
1327        F: FnMut() + 'static,
1328    {
1329        self.actions.push(
1330            Button::new(label)
1331                .theme_when(self.theme.reader())
1332                .appearance(ButtonAppearance::Outline)
1333                .tone(SemanticTone::Neutral)
1334                .min_width_from_theme(|theme| theme.metrics.dialog_action_min_width)
1335                .on_press(on_press),
1336        );
1337        self
1338    }
1339
1340    pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
1341    where
1342        F: FnMut() + 'static,
1343    {
1344        self.on_dismiss = Some(Box::new(on_dismiss));
1345        self
1346    }
1347
1348    /// [`Self::on_dismiss`], with the event context first.
1349    pub fn on_dismiss_with_ctx<F>(mut self, on_dismiss: F) -> Self
1350    where
1351        F: FnMut(&mut EventCtx) + 'static,
1352    {
1353        self.on_dismiss_with_ctx = Some(Box::new(on_dismiss));
1354        self
1355    }
1356
1357    pub(super) fn resolved_theme(&self) -> DefaultTheme {
1358        self.theme.resolve()
1359    }
1360
1361    pub(super) fn resolved_width(&self, viewport_width: f32, theme: &DefaultTheme) -> f32 {
1362        self.width
1363            .unwrap_or(theme.metrics.dialog_max_width.min(420.0))
1364            .max(theme.metrics.dialog_min_width.min(viewport_width))
1365            .min(viewport_width)
1366            .max(0.0)
1367    }
1368
1369    pub(super) fn resolved_height(&self, viewport_height: f32, theme: &DefaultTheme) -> f32 {
1370        self.height
1371            .unwrap_or((viewport_height * 0.62).min(560.0))
1372            .max(theme.metrics.touch_target_size * 3.0)
1373            .min(viewport_height)
1374            .max(0.0)
1375    }
1376
1377    pub(super) fn title_style(theme: &DefaultTheme) -> TextStyle {
1378        text_token_style(theme, theme.text.lg, theme.palette.text)
1379    }
1380
1381    pub(super) fn dismiss(&mut self, ctx: &mut EventCtx) {
1382        if let Some(state) = &self.state {
1383            state.hide();
1384            self.shown = false;
1385            ctx.request_measure();
1386            ctx.request_paint();
1387        }
1388        if let Some(on_dismiss) = &mut self.on_dismiss {
1389            on_dismiss();
1390        }
1391        if let Some(on_dismiss) = &mut self.on_dismiss_with_ctx {
1392            on_dismiss(ctx);
1393        }
1394        if let Some(previous_focus) = self.previous_focus.take() {
1395            ctx.request_focus_for(previous_focus);
1396        }
1397    }
1398
1399    pub(super) fn contains_widget(&self, target: WidgetId) -> bool {
1400        struct Finder {
1401            target: WidgetId,
1402            found: bool,
1403        }
1404
1405        impl WidgetPodVisitor for Finder {
1406            fn visit(&mut self, child: &WidgetPod) {
1407                if self.found {
1408                    return;
1409                }
1410                if child.id() == self.target {
1411                    self.found = true;
1412                } else {
1413                    child.visit_children(self);
1414                }
1415            }
1416        }
1417
1418        fn inspect(pod: &WidgetPod, finder: &mut Finder) {
1419            if finder.found {
1420                return;
1421            }
1422            if pod.id() == finder.target {
1423                finder.found = true;
1424            } else {
1425                pod.visit_children(finder);
1426            }
1427        }
1428
1429        let mut finder = Finder {
1430            target,
1431            found: false,
1432        };
1433        inspect(self.body.child(), &mut finder);
1434        if let Some(action) = &self.header_action {
1435            inspect(action.child(), &mut finder);
1436        }
1437        for action in self.actions.as_slice() {
1438            inspect(action, &mut finder);
1439        }
1440        finder.found
1441    }
1442
1443    pub(super) fn ensure_entrance_started(&mut self, ctx: &mut MeasureCtx) {
1444        if self.entrance_started {
1445            return;
1446        }
1447        self.entrance_started = true;
1448        let motion = self.resolved_theme().motion;
1449        self.reveal.animate(
1450            1.0,
1451            AnimationSpec::tween(f64::from(motion.duration_slower), motion.easing_decelerate),
1452            ctx,
1453        );
1454        if !self.focus_requested {
1455            // Focus moves into the sheet on the next frame, once it is laid
1456            // out.
1457            ctx.request_animation_frame();
1458        }
1459    }
1460
1461    pub(super) fn reveal_offset(&self, clock: &impl FrameClock) -> Vector {
1462        // Reduced motion shows the sheet in place instead of sliding it in.
1463        let hidden = sui_runtime::motion_policy().entrance_offset(self.reveal.get(clock));
1464        let horizontal_distance = self.sheet_frame.width() * hidden;
1465        let vertical_distance = self.sheet_frame.height() * hidden;
1466        match self.placement {
1467            SideSheetPlacement::Left => Vector::new(-horizontal_distance, 0.0),
1468            SideSheetPlacement::Right => Vector::new(horizontal_distance, 0.0),
1469            SideSheetPlacement::Bottom => Vector::new(0.0, vertical_distance),
1470        }
1471    }
1472
1473    pub(super) fn presented_sheet(&self, origin: Point, clock: &impl FrameClock) -> Rect {
1474        self.sheet_frame
1475            .translate(origin.to_vector() + self.reveal_offset(clock))
1476    }
1477}
1478
1479impl Widget for SideSheet {
1480    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
1481        self.sync_open();
1482        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.is_open() {
1483            self.dismiss(ctx);
1484            ctx.set_handled();
1485        }
1486    }
1487
1488    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1489        self.sync_open();
1490        if !self.shown {
1491            return;
1492        }
1493        match event {
1494            Event::Wake(WakeEvent::AnimationFrame { .. }) if !self.focus_requested => {
1495                self.focus_requested = true;
1496                let current_focus = ctx.focused_widget_id();
1497                let focus_is_inside = current_focus.is_some_and(|focused| {
1498                    focused == ctx.widget_id() || self.contains_widget(focused)
1499                });
1500                if !focus_is_inside {
1501                    self.previous_focus = current_focus;
1502                    ctx.request_focus();
1503                }
1504                ctx.set_handled();
1505            }
1506            Event::Semantics(semantics)
1507                if semantics.target == ctx.widget_id()
1508                    && matches!(semantics.action, sui_core::SemanticsActionRequest::Collapse) =>
1509            {
1510                self.dismiss(ctx);
1511                ctx.request_semantics();
1512                ctx.set_handled();
1513            }
1514            Event::Pointer(pointer)
1515                if pointer.kind == PointerEventKind::Down
1516                    && pointer.button == Some(PointerButton::Primary) =>
1517            {
1518                if self
1519                    .presented_sheet(ctx.bounds().origin, ctx)
1520                    .contains(pointer.position)
1521                {
1522                    ctx.request_focus();
1523                    ctx.request_semantics();
1524                } else {
1525                    if self.dismiss_on_scrim {
1526                        self.dismiss(ctx);
1527                    }
1528                    if self.modal || self.dismiss_on_scrim {
1529                        ctx.set_handled();
1530                    }
1531                    ctx.request_semantics();
1532                }
1533            }
1534            Event::Keyboard(key) if key.state == KeyState::Pressed && key.key == "Escape" => {
1535                self.dismiss(ctx);
1536                ctx.request_semantics();
1537                ctx.set_handled();
1538            }
1539            _ => {}
1540        }
1541    }
1542
1543    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1544        if let Some(state) = &self.state {
1545            self.shown = ctx.observe(&state.shown);
1546        } else {
1547            self.open_binding.observe(|open| {
1548                ctx.observe::<bool, _>(open);
1549            });
1550            self.sync_open();
1551        }
1552        if !self.shown {
1553            self.sheet_frame = Rect::ZERO;
1554            self.body_frame = Rect::ZERO;
1555            self.header_action_frame = Rect::ZERO;
1556            self.reveal = Progress::new(0.0);
1557            self.focus_animation = Progress::new(0.0);
1558            self.entrance_started = false;
1559            self.focus_requested = false;
1560            self.previous_focus = None;
1561            return Size::ZERO;
1562        }
1563        self.ensure_entrance_started(ctx);
1564
1565        let viewport = constraints.clamp(Size::new(
1566            if constraints.max.width.is_finite() {
1567                constraints.max.width
1568            } else {
1569                960.0
1570            },
1571            if constraints.max.height.is_finite() {
1572                constraints.max.height
1573            } else {
1574                640.0
1575            },
1576        ));
1577        let theme = self.resolved_theme();
1578        let metrics = theme.metrics;
1579        let padding = metrics.dialog_padding;
1580        let (sheet_x, sheet_y, sheet_width, sheet_height) = match self.placement {
1581            SideSheetPlacement::Left => (
1582                0.0,
1583                0.0,
1584                self.resolved_width(viewport.width, &theme),
1585                viewport.height,
1586            ),
1587            SideSheetPlacement::Right => {
1588                let width = self.resolved_width(viewport.width, &theme);
1589                (viewport.width - width, 0.0, width, viewport.height)
1590            }
1591            SideSheetPlacement::Bottom => {
1592                let height = self.resolved_height(viewport.height, &theme);
1593                (0.0, viewport.height - height, viewport.width, height)
1594            }
1595        };
1596        self.sheet_frame = Rect::new(sheet_x, sheet_y, sheet_width, sheet_height);
1597
1598        let title_style = Self::title_style(&theme);
1599        let description_style = theme.placeholder_text_style();
1600        self.title_measurement = Some(measure_text(ctx, &self.title, &title_style));
1601        self.description_measurement = self
1602            .description
1603            .as_ref()
1604            .map(|description| measure_text(ctx, description, &description_style));
1605
1606        let header_action_size = if let Some(action) = &mut self.header_action {
1607            action.measure(
1608                ctx,
1609                Constraints::new(
1610                    Size::ZERO,
1611                    Size::new(
1612                        (sheet_width - padding.left - padding.right).max(0.0),
1613                        metrics.touch_target_size,
1614                    ),
1615                ),
1616            )
1617        } else {
1618            Size::ZERO
1619        };
1620        let title_height = self
1621            .title_measurement
1622            .map(|measurement| measurement.height.max(title_style.line_height))
1623            .unwrap_or(title_style.line_height)
1624            .max(header_action_size.height);
1625        let description_height = self
1626            .description_measurement
1627            .map(|measurement| measurement.height.max(description_style.line_height))
1628            .unwrap_or(0.0);
1629        let description_gap = if self.description.is_some() {
1630            metrics.dialog_description_gap
1631        } else {
1632            0.0
1633        };
1634        let body_top = padding.top
1635            + title_height
1636            + description_gap
1637            + description_height
1638            + metrics.dialog_body_gap;
1639
1640        let mut footer_height: f32 = 0.0;
1641        for action in self.actions.as_mut_slice() {
1642            footer_height = footer_height.max(
1643                action
1644                    .measure(
1645                        ctx,
1646                        Constraints::new(
1647                            Size::ZERO,
1648                            Size::new(sheet_width, metrics.touch_target_size),
1649                        ),
1650                    )
1651                    .height,
1652            );
1653        }
1654        let footer_gap = if self.actions.is_empty() {
1655            0.0
1656        } else {
1657            metrics.dialog_footer_gap
1658        };
1659        let body_height =
1660            (sheet_height - body_top - footer_gap - footer_height - padding.bottom).max(0.0);
1661        let body_width = (sheet_width - padding.left - padding.right).max(0.0);
1662        let _ = self.body.measure(
1663            ctx,
1664            Constraints::new(Size::ZERO, Size::new(body_width, body_height)),
1665        );
1666        self.body_frame = Rect::new(padding.left, body_top, body_width, body_height);
1667        self.header_action_frame = Rect::new(
1668            sheet_width - padding.right - header_action_size.width,
1669            padding.top,
1670            header_action_size.width,
1671            header_action_size.height,
1672        );
1673        viewport
1674    }
1675
1676    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1677        if !self.shown {
1678            return;
1679        }
1680        let sheet = self.sheet_frame.translate(bounds.origin.to_vector());
1681        self.body
1682            .arrange(ctx, self.body_frame.translate(sheet.origin.to_vector()));
1683        if let Some(action) = &mut self.header_action {
1684            action.arrange(
1685                ctx,
1686                self.header_action_frame.translate(sheet.origin.to_vector()),
1687            );
1688        }
1689        if !self.actions.is_empty() {
1690            let theme = self.resolved_theme();
1691            let metrics = theme.metrics;
1692            let padding = metrics.dialog_padding;
1693            let gap = metrics.dialog_action_gap;
1694            let total_width = self
1695                .actions
1696                .as_slice()
1697                .iter()
1698                .map(|action| action.measured_size().width)
1699                .sum::<f32>()
1700                + gap * self.actions.len().saturating_sub(1) as f32;
1701            let footer_height = self
1702                .actions
1703                .as_slice()
1704                .iter()
1705                .map(|action| action.measured_size().height)
1706                .fold(0.0, f32::max);
1707            let mut x = sheet.max_x() - padding.right - total_width;
1708            let y = sheet.max_y() - padding.bottom - footer_height;
1709            for action in self.actions.as_mut_slice() {
1710                let size = action.measured_size();
1711                action.arrange(ctx, Rect::new(x, y, size.width, size.height));
1712                x += size.width + gap;
1713            }
1714        }
1715    }
1716
1717    fn paint(&self, ctx: &mut PaintCtx) {
1718        if !self.shown {
1719            return;
1720        }
1721        let theme = self.resolved_theme();
1722        if self.modal {
1723            let scrim = theme
1724                .surfaces
1725                .overlay_scrim
1726                .with_alpha(theme.surfaces.overlay_scrim.alpha * self.reveal.get(ctx));
1727            ctx.fill_bounds(scrim);
1728        }
1729
1730        let reveal_offset = self.reveal_offset(ctx);
1731        ctx.push_transform(Transform::translation(reveal_offset.x, reveal_offset.y));
1732        let sheet = self.sheet_frame.translate(ctx.bounds().origin.to_vector());
1733        let metrics = theme.metrics;
1734        paint_theme_shadow(ctx, sheet, [0.0; 4], &theme.shadows.box_shadow.xl);
1735        ctx.fill_rect(sheet, theme.palette.surface_raised);
1736        let border_width = physical_pixels(ctx, metrics.border_width.max(1.0));
1737        let border = match self.placement {
1738            SideSheetPlacement::Left => Rect::new(
1739                sheet.max_x() - border_width,
1740                sheet.y(),
1741                border_width,
1742                sheet.height(),
1743            ),
1744            SideSheetPlacement::Right => {
1745                Rect::new(sheet.x(), sheet.y(), border_width, sheet.height())
1746            }
1747            SideSheetPlacement::Bottom => {
1748                Rect::new(sheet.x(), sheet.y(), sheet.width(), border_width)
1749            }
1750        };
1751        ctx.fill_rect(border, theme.palette.border);
1752        let focus = self.focus_animation.get(ctx);
1753        if focus > Progress::EPSILON {
1754            stroke_border(
1755                ctx,
1756                sheet,
1757                0.0,
1758                physical_pixels(ctx, theme.metrics.focus_ring_width),
1759                theme
1760                    .palette
1761                    .focus_ring
1762                    .with_alpha(theme.palette.focus_ring.alpha * focus),
1763            );
1764        }
1765
1766        let padding = metrics.dialog_padding;
1767        let title_style = Self::title_style(&theme);
1768        let action_width = if self.header_action.is_some() {
1769            self.header_action_frame.width() + metrics.dialog_action_gap
1770        } else {
1771            0.0
1772        };
1773        let title_height = self
1774            .title_measurement
1775            .map(|measurement| measurement.height.max(title_style.line_height))
1776            .unwrap_or(title_style.line_height)
1777            .max(self.header_action_frame.height());
1778        let title_slot = Rect::new(
1779            sheet.x() + padding.left,
1780            sheet.y() + padding.top,
1781            (sheet.width() - padding.left - padding.right - action_width).max(0.0),
1782            title_height,
1783        );
1784        paint_text(ctx, title_slot, &self.title, &title_style, TextAlign::Start);
1785        if let Some(description) = &self.description {
1786            let style = theme.placeholder_text_style();
1787            let height = self
1788                .description_measurement
1789                .map(|measurement| measurement.height.max(style.line_height))
1790                .unwrap_or(style.line_height);
1791            let slot = Rect::new(
1792                sheet.x() + padding.left,
1793                title_slot.max_y() + metrics.dialog_description_gap,
1794                (sheet.width() - padding.left - padding.right).max(0.0),
1795                height,
1796            );
1797            paint_text(ctx, slot, description, &style, TextAlign::Start);
1798        }
1799        self.body.paint(ctx);
1800        if let Some(action) = &self.header_action {
1801            action.paint(ctx);
1802        }
1803        self.actions.paint(ctx);
1804        ctx.pop_transform();
1805    }
1806
1807    fn layer_options(&self) -> LayerOptions {
1808        LayerOptions {
1809            paint_boundary: PaintBoundaryMode::Explicit,
1810            composition_mode: if self.shown {
1811                LayerCompositionMode::Overlay
1812            } else {
1813                LayerCompositionMode::Normal
1814            },
1815        }
1816    }
1817
1818    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
1819        self.shown.then_some(StackSurfaceOptions {
1820            transient: true,
1821            ..StackSurfaceOptions::default()
1822        })
1823    }
1824
1825    fn overlay_options(&self) -> Option<OverlayOptions> {
1826        self.is_open().then_some(
1827            OverlayOptions::new(OverlayKind::Sheet)
1828                .modal(self.modal)
1829                .dismiss(OverlayDismissPolicy {
1830                    escape: true,
1831                    outside_pointer: self.dismiss_on_scrim,
1832                })
1833                .focus(OverlayFocusBehavior::CONTAINED),
1834        )
1835    }
1836
1837    fn semantics(&self, ctx: &mut SemanticsCtx) {
1838        if !self.shown {
1839            return;
1840        }
1841        let mut node = SemanticsNode::new(
1842            ctx.widget_id(),
1843            SemanticsRole::Dialog,
1844            self.sheet_frame.translate(ctx.bounds().origin.to_vector()),
1845        );
1846        node.name = Some(self.title.clone());
1847        node.description = self.description.clone();
1848        node.state.focused = ctx.is_focused();
1849        node.state.expanded = Some(true);
1850        node.state.modal = self.modal;
1851        node.actions = vec![SemanticsAction::Focus, SemanticsAction::Collapse];
1852        ctx.push(node);
1853        self.body.semantics(ctx);
1854        if let Some(action) = &self.header_action {
1855            action.semantics(ctx);
1856        }
1857        self.actions.semantics(ctx);
1858    }
1859
1860    fn accepts_focus(&self) -> bool {
1861        self.shown
1862    }
1863
1864    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
1865        let theme = self.resolved_theme();
1866        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
1867        ctx.request_paint();
1868        ctx.request_semantics();
1869    }
1870
1871    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1872        if self.shown {
1873            self.body.visit_children(visitor);
1874            if let Some(action) = &self.header_action {
1875                action.visit_children(visitor);
1876            }
1877            self.actions.visit_children(visitor);
1878        }
1879    }
1880
1881    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1882        if self.shown {
1883            self.body.visit_children_mut(visitor);
1884            if let Some(action) = &mut self.header_action {
1885                action.visit_children_mut(visitor);
1886            }
1887            self.actions.visit_children_mut(visitor);
1888        }
1889    }
1890}
1891
1892/// A modal surface anchored to the bottom edge of its allocated viewport.
1893///
1894/// `BottomSheet` follows the same focus, dismissal, semantics, and action
1895/// contracts as [`SideSheet`], while exposing height-oriented configuration.
1896pub struct BottomSheet {
1897    pub(super) inner: SideSheet,
1898}
1899
1900impl BottomSheet {
1901    pub fn new<W>(title: impl Into<String>, body: W) -> Self
1902    where
1903        W: Widget + 'static,
1904    {
1905        Self {
1906            inner: SideSheet::new(title, body).placement(SideSheetPlacement::Bottom),
1907        }
1908    }
1909
1910    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1911        self.inner = self.inner.theme(theme);
1912        self
1913    }
1914
1915    pub fn theme_when<F>(mut self, theme: F) -> Self
1916    where
1917        F: Fn() -> DefaultTheme + 'static,
1918    {
1919        self.inner = self.inner.theme_when(theme);
1920        self
1921    }
1922
1923    pub fn description(mut self, description: impl Into<String>) -> Self {
1924        self.inner = self.inner.description(description);
1925        self
1926    }
1927
1928    /// Whether the sheet is open; see [`SideSheet::open`].
1929    pub fn open(mut self, open: bool) -> Self {
1930        self.inner = self.inner.open(open);
1931        self
1932    }
1933
1934    /// [`Self::open`], read each time the sheet lays out.
1935    pub fn open_when<F>(mut self, open: F) -> Self
1936    where
1937        F: Fn() -> bool + 'static,
1938    {
1939        self.inner = self.inner.open_when(open);
1940        self
1941    }
1942
1943    /// [`Self::open`], following an observable.
1944    pub fn open_from<O>(mut self, open: O) -> Self
1945    where
1946        O: Observable<bool> + 'static,
1947    {
1948        self.inner = self.inner.open_from(open);
1949        self
1950    }
1951
1952    pub fn is_open(&self) -> bool {
1953        self.inner.is_open()
1954    }
1955
1956    /// Open or close a built sheet, returning whether that changed it.
1957    pub fn set_open(&mut self, open: bool) -> bool {
1958        self.inner.set_open(open)
1959    }
1960
1961    pub fn state(mut self, state: SheetState) -> Self {
1962        self.inner = self.inner.state(state);
1963        self
1964    }
1965
1966    pub fn modal(mut self, modal: bool) -> Self {
1967        self.inner = self.inner.modal(modal);
1968        self
1969    }
1970
1971    pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
1972        self.inner = self.inner.dismiss_on_scrim(dismiss);
1973        self
1974    }
1975
1976    pub fn height(mut self, height: f32) -> Self {
1977        self.inner = self.inner.height(height);
1978        self
1979    }
1980
1981    pub fn header_action<W>(mut self, action: W) -> Self
1982    where
1983        W: Widget + 'static,
1984    {
1985        self.inner = self.inner.header_action(action);
1986        self
1987    }
1988
1989    pub fn action<W>(mut self, action: W) -> Self
1990    where
1991        W: Widget + 'static,
1992    {
1993        self.inner = self.inner.action(action);
1994        self
1995    }
1996
1997    pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
1998    where
1999        F: FnMut() + 'static,
2000    {
2001        self.inner = self.inner.primary_action(label, on_press);
2002        self
2003    }
2004
2005    pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
2006    where
2007        F: FnMut() + 'static,
2008    {
2009        self.inner = self.inner.secondary_action(label, on_press);
2010        self
2011    }
2012
2013    pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
2014    where
2015        F: FnMut() + 'static,
2016    {
2017        self.inner = self.inner.on_dismiss(on_dismiss);
2018        self
2019    }
2020
2021    /// [`Self::on_dismiss`], with the event context first.
2022    pub fn on_dismiss_with_ctx<F>(mut self, on_dismiss: F) -> Self
2023    where
2024        F: FnMut(&mut EventCtx) + 'static,
2025    {
2026        self.inner = self.inner.on_dismiss_with_ctx(on_dismiss);
2027        self
2028    }
2029}
2030
2031impl Widget for BottomSheet {
2032    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
2033        self.inner.command(ctx, command);
2034    }
2035
2036    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2037        self.inner.event(ctx, event);
2038    }
2039
2040    fn debug_name(&self) -> &'static str {
2041        "sui_widgets::BottomSheet"
2042    }
2043
2044    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2045        self.inner.measure(ctx, constraints)
2046    }
2047
2048    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2049        self.inner.arrange(ctx, bounds);
2050    }
2051
2052    fn paint(&self, ctx: &mut PaintCtx) {
2053        self.inner.paint(ctx);
2054    }
2055
2056    fn layer_options(&self) -> LayerOptions {
2057        self.inner.layer_options()
2058    }
2059
2060    fn layer_properties(&self) -> LayerProperties {
2061        self.inner.layer_properties()
2062    }
2063
2064    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
2065        self.inner.stack_surface_options()
2066    }
2067
2068    fn overlay_options(&self) -> Option<OverlayOptions> {
2069        self.inner.overlay_options()
2070    }
2071
2072    fn semantics(&self, ctx: &mut SemanticsCtx) {
2073        self.inner.semantics(ctx);
2074    }
2075
2076    fn accepts_focus(&self) -> bool {
2077        self.inner.accepts_focus()
2078    }
2079
2080    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2081        self.inner.focus_changed(ctx, focused);
2082    }
2083
2084    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2085        self.inner.visit_children(visitor);
2086    }
2087
2088    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2089        self.inner.visit_children_mut(visitor);
2090    }
2091}