Skip to main content

gpui_material_components/overlay/
sheet.rs

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