Skip to main content

sui_widgets/composites/
dialogs.rs

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