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