Skip to main content

gpui_material_components/overlay/
sheet.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, Edges, ElementId, Entity, Hsla, IntoElement, Pixels, SharedString, Size,
5    Window, px, radians,
6};
7use gpui_material_theme::{ColorRole, CornerShape, Elevation};
8
9use crate::{Icon, IconButton, IconName, ScaffoldInsets};
10
11use super::bottom_sheet::{BottomSheetState, BottomSheetThresholds};
12use super::dialog::{
13    DialogCloseReason, DialogProperties, DialogState, ModalClosed, ModalDismissRequest,
14    ModalSession,
15};
16
17mod gesture;
18mod render;
19
20/// Edge of the window or layout container to which a [`Sheet`] attaches.
21#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
22pub enum SheetEdge {
23    /// Attach to the bottom edge.
24    #[default]
25    Bottom,
26    /// Attach to the logical start edge (left in LTR, right in RTL).
27    Start,
28    /// Attach to the logical end edge (right in LTR, left in RTL).
29    End,
30}
31
32/// Interaction mode of a [`Sheet`].
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
34pub enum SheetMode {
35    /// Non-blocking docked sheet that participates in parent layout.
36    #[default]
37    Standard,
38    /// Blocking overlay sheet presented above a scrim with modal focus trapping.
39    Modal,
40}
41
42/// Placement of a side sheet relative to its window edge or layout slot.
43#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
44pub enum SheetPlacement {
45    /// Flush against the window or container edge.
46    #[default]
47    Docked,
48    /// Inset from the edges using [`SheetMargins`] with rounded corners on all sides.
49    Detached,
50}
51
52/// Logical detached margins in pixels. The default is 16 px on each side.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct SheetMargins {
55    /// Top inset in logical pixels.
56    pub top: Pixels,
57    /// Bottom inset in logical pixels.
58    pub bottom: Pixels,
59    /// Logical start inset in logical pixels.
60    pub start: Pixels,
61    /// Logical end inset in logical pixels.
62    pub end: Pixels,
63}
64
65impl Default for SheetMargins {
66    fn default() -> Self {
67        Self {
68            top: px(16.),
69            bottom: px(16.),
70            start: px(16.),
71            end: px(16.),
72        }
73    }
74}
75
76impl SheetMargins {
77    fn fit(self, viewport: Size<Pixels>, rtl: bool) -> Edges<Pixels> {
78        let (start, end) =
79            fit_margins(self.start, self.end, (viewport.width - px(48.)).max(px(0.)));
80        let (top, bottom) = fit_margins(
81            self.top,
82            self.bottom,
83            (viewport.height - px(48.)).max(px(0.)),
84        );
85        let (left, right) = if rtl { (end, start) } else { (start, end) };
86        Edges {
87            top,
88            bottom,
89            left,
90            right,
91        }
92    }
93}
94
95fn fit_margins(a: Pixels, b: Pixels, available: Pixels) -> (Pixels, Pixels) {
96    let sanitize = |margin: Pixels| {
97        if f32::from(margin).is_finite() {
98            margin.clamp(px(0.), available)
99        } else {
100            px(0.)
101        }
102    };
103    let (a, b) = (sanitize(a), sanitize(b));
104    if a + b > available {
105        let factor = available / (a + b);
106        (a * factor, b * factor)
107    } else {
108        (a, b)
109    }
110}
111
112/// Optional local colors for the sheet and its adornments.
113#[derive(Clone, Copy, Debug, Default)]
114pub struct SheetColors {
115    /// Background color override for the sheet container.
116    pub container: Option<Hsla>,
117    /// Foreground color override for the sheet body content.
118    pub content: Option<Hsla>,
119    /// Foreground color override for the sheet header title.
120    pub header: Option<Hsla>,
121    /// Color override for header, footer, and edge dividers.
122    pub divider: Option<Hsla>,
123    /// Color override for the modal backdrop scrim.
124    pub scrim: Option<Hsla>,
125}
126
127/// Activation for a close control supplied by the caller.
128#[derive(Clone)]
129pub struct SheetClose(CloseAction);
130
131#[derive(Clone)]
132enum CloseAction {
133    Modal(ModalSession),
134    Standard(Option<ModalDismissRequest>, Option<ModalClosed>),
135}
136
137impl SheetClose {
138    /// Requests dismissal from the sheet's Close action.
139    pub fn activate(&self, window: &mut Window, cx: &mut App) {
140        self.request(window, cx);
141    }
142
143    pub(super) fn request(&self, window: &mut Window, cx: &mut App) -> bool {
144        let reason = DialogCloseReason::Cancel;
145        match &self.0 {
146            CloseAction::Modal(session) => session.dismiss(reason, window, cx),
147            CloseAction::Standard(request, Some(closed))
148                if request
149                    .as_ref()
150                    .is_none_or(|request| request(reason, window, cx)) =>
151            {
152                closed(reason, window, cx);
153                true
154            }
155            CloseAction::Standard(_, _) => false,
156        }
157    }
158}
159
160type CloseSlot = Box<dyn FnOnce(SheetClose) -> AnyElement>;
161
162type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
163
164enum SheetBinding {
165    Immediate(Entity<DialogState>),
166    Retained(Entity<BottomSheetState>),
167}
168
169/// A docked or modal Material sheet. Standard sheets take part in parent layout.
170/// The caller owns the bottom sheet's expanded value and handles changes.
171#[derive(IntoElement)]
172pub struct Sheet {
173    id: ElementId,
174    state: SheetBinding,
175    title: SharedString,
176    content: AnyElement,
177    edge: SheetEdge,
178    mode: SheetMode,
179    extent: Pixels,
180    expansion: Option<(bool, Change)>,
181    placement: SheetPlacement,
182    margins: SheetMargins,
183    header: Option<AnyElement>,
184    show_header: bool,
185    back: Option<AnyElement>,
186    close_content: Option<CloseSlot>,
187    close_label: SharedString,
188    show_close: bool,
189    footer: Option<AnyElement>,
190    footer_divider: bool,
191    edge_divider: bool,
192    properties: DialogProperties,
193    on_dismiss_request: Option<ModalDismissRequest>,
194    on_close: Option<ModalClosed>,
195    layer: usize,
196    shape: Option<CornerShape>,
197    container_role: Option<ColorRole>,
198    content_role: Option<ColorRole>,
199    colors: SheetColors,
200    tonal_elevation: Elevation,
201    shadow_elevation: Option<Elevation>,
202    scrim_opacity: f32,
203    presence: Option<gpui_base::motion::PresenceSample>,
204    layout_size: Option<Size<Pixels>>,
205    peek_height: Option<Pixels>,
206    max_width: Option<Pixels>,
207    drag_enabled: bool,
208    show_handle: bool,
209    handle_content: Option<AnyElement>,
210    handle_label: SharedString,
211    thresholds: BottomSheetThresholds,
212    content_insets: ScaffoldInsets,
213}
214
215impl Sheet {
216    /// Creates a sheet bound to a [`DialogState`] with the given accessible title and body content.
217    pub fn new(
218        id: impl Into<ElementId>,
219        state: &Entity<DialogState>,
220        title: impl Into<SharedString>,
221        content: impl IntoElement,
222    ) -> Self {
223        Self::with_state(
224            id.into(),
225            SheetBinding::Immediate(state.clone()),
226            title.into(),
227            content.into_any_element(),
228        )
229    }
230
231    /// Creates a bottom sheet with retained stops and state-owned visibility.
232    pub fn bottom(
233        id: impl Into<ElementId>,
234        state: &Entity<BottomSheetState>,
235        title: impl Into<SharedString>,
236        content: impl IntoElement,
237    ) -> Self {
238        Self::with_state(
239            id.into(),
240            SheetBinding::Retained(state.clone()),
241            title.into(),
242            content.into_any_element(),
243        )
244    }
245
246    fn with_state(
247        id: ElementId,
248        state: SheetBinding,
249        title: SharedString,
250        content: AnyElement,
251    ) -> Self {
252        Self {
253            id,
254            state,
255            title,
256            content,
257            edge: SheetEdge::Bottom,
258            mode: SheetMode::Standard,
259            extent: px(320.),
260            expansion: None,
261            placement: SheetPlacement::Docked,
262            margins: SheetMargins::default(),
263            header: None,
264            show_header: true,
265            back: None,
266            close_content: None,
267            close_label: "Close".into(),
268            show_close: true,
269            footer: None,
270            footer_divider: false,
271            edge_divider: false,
272            properties: DialogProperties::default(),
273            on_dismiss_request: None,
274            on_close: None,
275            layer: 0,
276            shape: None,
277            container_role: None,
278            content_role: None,
279            colors: SheetColors::default(),
280            tonal_elevation: Elevation::Level0,
281            shadow_elevation: None,
282            scrim_opacity: 0.32,
283            presence: None,
284            layout_size: None,
285            peek_height: None,
286            max_width: None,
287            drag_enabled: true,
288            show_handle: true,
289            handle_content: None,
290            handle_label: "Resize bottom sheet".into(),
291            thresholds: BottomSheetThresholds::default(),
292            content_insets: ScaffoldInsets::default(),
293        }
294    }
295
296    #[cfg_attr(not(feature = "navigation"), allow(dead_code))]
297    pub(crate) fn in_scaffold(mut self, size: Size<Pixels>) -> Self {
298        self.edge = SheetEdge::Bottom;
299        self.mode = SheetMode::Standard;
300        self.layout_size = Some(size);
301        self
302    }
303
304    /// Sets the retained bottom sheet's partial height. It fits the expanded extent.
305    pub fn peek_height(mut self, height: Pixels) -> Self {
306        if f32::from(height).is_finite() {
307            self.peek_height = Some(height.max(px(48.)));
308        }
309        self
310    }
311
312    /// Sets the maximum width in logical pixels (defaults to 640 dp for bottom sheets and 400 dp for side sheets).
313    pub fn max_width(mut self, width: Pixels) -> Self {
314        if f32::from(width).is_finite() && width > px(0.) {
315            self.max_width = Some(width);
316        }
317        self
318    }
319
320    /// Enables or disables pointer drag resizing on a retained bottom sheet (default `true`).
321    pub fn drag_enabled(mut self, enabled: bool) -> Self {
322        self.drag_enabled = enabled;
323        self
324    }
325
326    /// Sets the distance and velocity thresholds used when settling a released drag.
327    pub fn drag_thresholds(mut self, thresholds: BottomSheetThresholds) -> Self {
328        self.thresholds = thresholds.normalized();
329        self
330    }
331
332    /// Replaces the grip decoration of the retained sheet's resize control.
333    pub fn handle_content(mut self, content: impl IntoElement) -> Self {
334        self.handle_content = Some(content.into_any_element());
335        self
336    }
337
338    /// Names the resize action for keyboard and assistive technology.
339    pub fn handle_label(mut self, label: impl Into<SharedString>) -> Self {
340        self.handle_label = label.into();
341        self
342    }
343
344    /// Uses a text height action in place of the grip when multiple stops are available.
345    pub fn show_handle(mut self, show: bool) -> Self {
346        self.show_handle = show;
347        self
348    }
349
350    /// Sets logical padding within the bottom sheet's scrolling content.
351    pub fn content_insets(mut self, insets: ScaffoldInsets) -> Self {
352        self.content_insets = insets.normalized();
353        self
354    }
355
356    /// Sets which edge the sheet attaches to (default [`SheetEdge::Bottom`]). Ignored for retained bottom sheets.
357    pub fn edge(mut self, edge: SheetEdge) -> Self {
358        if matches!(self.state, SheetBinding::Immediate(_)) {
359            self.edge = edge;
360        }
361        self
362    }
363
364    /// Sets whether the sheet is standard (docked) or modal (default [`SheetMode::Standard`]).
365    pub fn mode(mut self, mode: SheetMode) -> Self {
366        self.mode = mode;
367        self
368    }
369
370    /// Sets expanded height for a bottom sheet, or width for a side sheet.
371    pub fn extent(mut self, extent: Pixels) -> Self {
372        self.extent = extent.max(px(48.));
373        self
374    }
375
376    /// Enables a keyboard-operable expand and collapse action on a bottom sheet.
377    pub fn expandable(
378        mut self,
379        expanded: bool,
380        on_change: impl Fn(bool, &mut Window, &mut App) + 'static,
381    ) -> Self {
382        self.expansion = Some((expanded, Rc::new(on_change)));
383        self
384    }
385
386    /// Sets whether a side sheet is docked to the edge or detached with margins (default [`SheetPlacement::Docked`]).
387    pub fn placement(mut self, placement: SheetPlacement) -> Self {
388        self.placement = placement;
389        self
390    }
391
392    /// Sets the logical inset margins used when [`SheetPlacement::Detached`] is active.
393    pub fn margins(mut self, margins: SheetMargins) -> Self {
394        self.margins = margins;
395        self
396    }
397
398    /// Replaces the visible heading while preserving the accessible sheet name.
399    pub fn header_content(mut self, heading: impl IntoElement) -> Self {
400        self.header = Some(heading.into_any_element());
401        self
402    }
403
404    /// Shows or hides the visible header row while keeping the constructor's name as the accessible label.
405    pub fn show_header(mut self, show: bool) -> Self {
406        self.show_header = show;
407        self
408    }
409
410    /// Adds a named back action. Navigation ownership remains with the caller.
411    pub fn back(
412        mut self,
413        label: impl Into<SharedString>,
414        on_back: impl Fn(&mut Window, &mut App) + 'static,
415    ) -> Self {
416        self.back = Some(
417            IconButton::new(
418                "back",
419                label,
420                Icon::new(IconName::ArrowForward)
421                    .rotate(radians(std::f32::consts::PI))
422                    .mirror_in_rtl(true),
423            )
424            .on_activate(on_back)
425            .into_any_element(),
426        );
427        self
428    }
429
430    /// Replaces the leading back button with custom content.
431    pub fn back_content(mut self, back: impl IntoElement) -> Self {
432        self.back = Some(back.into_any_element());
433        self
434    }
435
436    /// Overrides the accessible label of the default close button (default `"Close"`).
437    pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
438        self.close_label = label.into();
439        self
440    }
441
442    /// Shows or hides the default close button in the sheet header (default `true`).
443    pub fn show_close(mut self, show: bool) -> Self {
444        self.show_close = show;
445        self
446    }
447
448    /// Builds a custom close control. Connect its activation to the supplied action.
449    pub fn close_content<E: IntoElement>(
450        mut self,
451        close: impl FnOnce(SheetClose) -> E + 'static,
452    ) -> Self {
453        self.close_content = Some(Box::new(move |action| close(action).into_any_element()));
454        self
455    }
456
457    /// Adds a fixed footer slot at the bottom of the sheet.
458    pub fn footer(mut self, actions: impl IntoElement) -> Self {
459        self.footer = Some(actions.into_any_element());
460        self
461    }
462
463    /// Shows or hides a horizontal divider above the sheet footer (default `false`).
464    pub fn footer_divider(mut self, visible: bool) -> Self {
465        self.footer_divider = visible;
466        self
467    }
468
469    /// Adds a divider between a docked Standard side sheet and its adjacent content.
470    pub fn edge_divider(mut self, visible: bool) -> Self {
471        self.edge_divider = visible;
472        self
473    }
474
475    /// Configures Escape and outside-click dismissal behavior for modal sheets.
476    pub fn properties(mut self, properties: DialogProperties) -> Self {
477        self.properties = properties;
478        self
479    }
480
481    /// Return false to veto a user-initiated close.
482    pub fn on_dismiss_request(
483        mut self,
484        request: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
485    ) -> Self {
486        self.on_dismiss_request = Some(Rc::new(request));
487        self
488    }
489
490    /// Receives accepted modal closes or requests to remove a Standard sheet.
491    pub fn on_close(
492        mut self,
493        close: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
494    ) -> Self {
495        self.on_close = Some(Rc::new(close));
496        self
497    }
498
499    /// Sets the stacking layer of a nested modal sheet.
500    pub fn layer(mut self, layer: usize) -> Self {
501        self.layer = layer;
502        self
503    }
504
505    /// Overrides the corner shape of the sheet container.
506    pub fn shape(mut self, shape: CornerShape) -> Self {
507        self.shape = Some(shape);
508        self
509    }
510
511    /// Overrides the theme [`ColorRole`] used for the sheet container background.
512    pub fn container_role(mut self, role: ColorRole) -> Self {
513        self.container_role = Some(role);
514        self
515    }
516
517    /// Overrides the theme [`ColorRole`] used for the sheet foreground content.
518    pub fn content_role(mut self, role: ColorRole) -> Self {
519        self.content_role = Some(role);
520        self
521    }
522
523    /// Overrides the sheet's container, content, header, divider, and scrim colors.
524    pub fn colors(mut self, colors: SheetColors) -> Self {
525        self.colors = colors;
526        self
527    }
528
529    /// Sets the tonal elevation applied to the sheet surface.
530    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
531        self.tonal_elevation = elevation;
532        self
533    }
534
535    /// Overrides the shadow elevation cast by the sheet surface.
536    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
537        self.shadow_elevation = Some(elevation);
538        self
539    }
540
541    /// Reuses the enclosing component's sampled presence.
542    #[cfg_attr(not(feature = "navigation"), allow(dead_code))]
543    pub(crate) fn sampled_presence(mut self, presence: gpui_base::motion::PresenceSample) -> Self {
544        self.presence = Some(presence);
545        self
546    }
547
548    /// Sets the modal backdrop scrim opacity, clamped to 0–1. `NaN` falls back to the default (`0.32`).
549    pub fn scrim_opacity(mut self, opacity: f32) -> Self {
550        self.scrim_opacity = if opacity.is_nan() {
551            0.32
552        } else {
553            opacity.clamp(0., 1.)
554        };
555        self
556    }
557}