Skip to main content

gpui_material_components/overlay/
sheet.rs

1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4    AnyElement, App, AppContext, Context, DragMoveEvent, Edges, ElementId, Entity, Hsla,
5    InteractiveElement, IntoElement, MouseButton, ParentElement, Pixels, Render, RenderOnce, Role,
6    SharedString, Size, StatefulInteractiveElement, Styled, Window, anchored, div, point,
7    prelude::FluentBuilder, px, radians,
8};
9use gpui_base::TestSupportExt as _;
10use gpui_material_foundation::{
11    DragCapture, Scrim, Surface, animate, color, isolated_scroll, window_material_theme,
12};
13use gpui_material_theme::{
14    ColorRole, CornerRole, CornerShape, Direction, Elevation, MotionKind, MotionSpec, MotionSpeed,
15    TypeRole,
16};
17
18use crate::{Button, ButtonVariant, Divider, Icon, IconButton, IconName, ScaffoldInsets, Text};
19
20use super::bottom_sheet::{
21    BottomHandle, BottomSheetLayout, BottomSheetState, BottomSheetThresholds, BottomSheetValue,
22};
23
24use super::dialog::{
25    DialogCloseReason, DialogProperties, DialogState, ModalClosed, ModalDismissRequest,
26    ModalSession, exiting_panel, modal_backdrop,
27};
28
29#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
30pub enum SheetEdge {
31    #[default]
32    Bottom,
33    Start,
34    End,
35}
36
37#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
38pub enum SheetMode {
39    #[default]
40    Standard,
41    Modal,
42}
43
44/// Placement of a side sheet relative to its window edge or layout slot.
45#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
46pub enum SheetPlacement {
47    #[default]
48    Docked,
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    pub top: Pixels,
56    pub bottom: Pixels,
57    pub start: Pixels,
58    pub end: Pixels,
59}
60
61impl Default for SheetMargins {
62    fn default() -> Self {
63        Self {
64            top: px(16.),
65            bottom: px(16.),
66            start: px(16.),
67            end: px(16.),
68        }
69    }
70}
71
72impl SheetMargins {
73    fn fit(self, viewport: Size<Pixels>, rtl: bool) -> Edges<Pixels> {
74        let (start, end) =
75            fit_margins(self.start, self.end, (viewport.width - px(48.)).max(px(0.)));
76        let (top, bottom) = fit_margins(
77            self.top,
78            self.bottom,
79            (viewport.height - px(48.)).max(px(0.)),
80        );
81        let (left, right) = if rtl { (end, start) } else { (start, end) };
82        Edges {
83            top,
84            bottom,
85            left,
86            right,
87        }
88    }
89}
90
91fn fit_margins(a: Pixels, b: Pixels, available: Pixels) -> (Pixels, Pixels) {
92    let sanitize = |margin: Pixels| {
93        if f32::from(margin).is_finite() {
94            margin.clamp(px(0.), available)
95        } else {
96            px(0.)
97        }
98    };
99    let (a, b) = (sanitize(a), sanitize(b));
100    if a + b > available {
101        let factor = available / (a + b);
102        (a * factor, b * factor)
103    } else {
104        (a, b)
105    }
106}
107
108/// Optional local colors for the sheet and its adornments.
109#[derive(Clone, Copy, Debug, Default)]
110pub struct SheetColors {
111    pub container: Option<Hsla>,
112    pub content: Option<Hsla>,
113    pub header: Option<Hsla>,
114    pub divider: Option<Hsla>,
115    pub scrim: Option<Hsla>,
116}
117
118/// Activation for a close control supplied by the caller.
119#[derive(Clone)]
120pub struct SheetClose(CloseAction);
121
122#[derive(Clone)]
123enum CloseAction {
124    Modal(ModalSession),
125    Standard(Option<ModalDismissRequest>, Option<ModalClosed>),
126}
127
128impl SheetClose {
129    /// Requests dismissal from the sheet's Close action.
130    pub fn activate(&self, window: &mut Window, cx: &mut App) {
131        self.request(window, cx);
132    }
133
134    pub(super) fn request(&self, window: &mut Window, cx: &mut App) -> bool {
135        let reason = DialogCloseReason::Cancel;
136        match &self.0 {
137            CloseAction::Modal(session) => session.dismiss(reason, window, cx),
138            CloseAction::Standard(request, Some(closed))
139                if request
140                    .as_ref()
141                    .is_none_or(|request| request(reason, window, cx)) =>
142            {
143                closed(reason, window, cx);
144                true
145            }
146            CloseAction::Standard(_, _) => false,
147        }
148    }
149}
150
151type CloseSlot = Box<dyn FnOnce(SheetClose) -> AnyElement>;
152
153type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
154
155struct SheetDrag;
156
157impl Render for SheetDrag {
158    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
159        div()
160    }
161}
162
163#[derive(Default)]
164struct Gesture {
165    origin: Option<Pixels>,
166    capture: Option<DragCapture>,
167    offset: Pixels,
168}
169
170fn drag_handle(
171    id: &ElementId,
172    gesture: Rc<RefCell<Gesture>>,
173    travel: Pixels,
174    expanded: bool,
175    change: Change,
176    window: &mut Window,
177    cx: &mut App,
178) -> AnyElement {
179    let tint = color(
180        window_material_theme(window, cx)
181            .colors
182            .color(ColorRole::OnSurfaceVariant),
183    );
184    let focus = window
185        .use_keyed_state((id.clone(), "drag-focus"), cx, |_, cx| cx.focus_handle())
186        .read(cx)
187        .clone();
188    let down = gesture.clone();
189    let start = gesture.clone();
190    let release = gesture.clone();
191    let outside = gesture.clone();
192    let moving = gesture.clone();
193    let cancel = gesture;
194    let drag_focus = focus.clone();
195    let release_change = change.clone();
196    let settle = move |gesture: &RefCell<Gesture>,
197                       y: Pixels,
198                       change: &Change,
199                       window: &mut Window,
200                       cx: &mut App| {
201        let active = std::mem::take(&mut *gesture.borrow_mut());
202        window.refresh();
203        if active.capture.is_none() {
204            return;
205        }
206        if let Some(origin) = active.origin {
207            let distance = y - origin;
208            if distance.abs() >= px(32.) && expanded == (distance > px(0.)) {
209                change(!expanded, window, cx);
210            }
211        }
212    };
213    div()
214        .id("drag-handle")
215        .test_support()
216        .track_focus(&focus)
217        .w_full()
218        .h(px(48.))
219        .flex_none()
220        .flex()
221        .items_center()
222        .justify_center()
223        .cursor_ns_resize()
224        .child(drag_handle_mark(tint))
225        .on_mouse_down(MouseButton::Left, move |event, _, _| {
226            down.borrow_mut().origin = Some(event.position.y);
227        })
228        .on_drag(SheetDrag, move |_, _, window, cx| {
229            drag_focus.focus(window, cx);
230            let weak = Rc::downgrade(&start);
231            start.borrow_mut().capture = Some(DragCapture::watch(window, cx, move |_, _| {
232                if let Some(state) = weak.upgrade() {
233                    *state.borrow_mut() = Gesture::default();
234                }
235            }));
236            cx.stop_propagation();
237            cx.new(|_| SheetDrag)
238        })
239        .on_drag_move(move |event: &DragMoveEvent<SheetDrag>, window, _| {
240            let mut state = moving.borrow_mut();
241            if state.capture.is_some()
242                && let Some(origin) = state.origin
243            {
244                let offset = event.event.position.y - origin;
245                state.offset = if expanded {
246                    offset.clamp(px(0.), travel)
247                } else {
248                    offset.clamp(-travel, px(0.))
249                };
250                window.refresh();
251            }
252        })
253        .on_mouse_up(MouseButton::Left, move |event, window, cx| {
254            settle(&release, event.position.y, &release_change, window, cx);
255        })
256        .on_mouse_up_out(MouseButton::Left, move |event, window, cx| {
257            settle(&outside, event.position.y, &change, window, cx);
258        })
259        .capture_key_down(move |event, window, cx| {
260            if event.keystroke.key == "escape"
261                && let Some(capture) = std::mem::take(&mut *cancel.borrow_mut()).capture
262            {
263                capture.cancel(window, cx);
264                window.refresh();
265                cx.stop_propagation();
266            }
267        })
268        .into_any_element()
269}
270
271fn drag_handle_mark(tint: gpui::Hsla) -> gpui::Div {
272    div().w(px(32.)).h(px(4.)).rounded_full().bg(tint)
273}
274
275enum SheetBinding {
276    Immediate(Entity<DialogState>),
277    Retained(Entity<BottomSheetState>),
278}
279
280/// A docked or modal Material sheet. Standard sheets take part in parent layout.
281/// The caller owns the bottom sheet's expanded value and handles changes.
282#[derive(IntoElement)]
283pub struct Sheet {
284    id: ElementId,
285    state: SheetBinding,
286    title: SharedString,
287    content: AnyElement,
288    edge: SheetEdge,
289    mode: SheetMode,
290    extent: Pixels,
291    expansion: Option<(bool, Change)>,
292    placement: SheetPlacement,
293    margins: SheetMargins,
294    header: Option<AnyElement>,
295    back: Option<AnyElement>,
296    close_content: Option<CloseSlot>,
297    close_label: SharedString,
298    show_close: bool,
299    footer: Option<AnyElement>,
300    footer_divider: bool,
301    edge_divider: bool,
302    properties: DialogProperties,
303    on_dismiss_request: Option<ModalDismissRequest>,
304    on_close: Option<ModalClosed>,
305    layer: usize,
306    shape: Option<CornerShape>,
307    container_role: Option<ColorRole>,
308    content_role: Option<ColorRole>,
309    colors: SheetColors,
310    tonal_elevation: Elevation,
311    shadow_elevation: Option<Elevation>,
312    scrim_opacity: f32,
313    presence: Option<gpui_base::motion::PresenceSample>,
314    layout_size: Option<Size<Pixels>>,
315    peek_height: Option<Pixels>,
316    max_width: Pixels,
317    drag_enabled: bool,
318    show_handle: bool,
319    handle_content: Option<AnyElement>,
320    handle_label: SharedString,
321    thresholds: BottomSheetThresholds,
322    content_insets: ScaffoldInsets,
323}
324
325impl Sheet {
326    pub fn new(
327        id: impl Into<ElementId>,
328        state: &Entity<DialogState>,
329        title: impl Into<SharedString>,
330        content: impl IntoElement,
331    ) -> Self {
332        Self::with_state(
333            id.into(),
334            SheetBinding::Immediate(state.clone()),
335            title.into(),
336            content.into_any_element(),
337        )
338    }
339
340    /// Creates a bottom sheet with retained stops and state-owned visibility.
341    pub fn bottom(
342        id: impl Into<ElementId>,
343        state: &Entity<BottomSheetState>,
344        title: impl Into<SharedString>,
345        content: impl IntoElement,
346    ) -> Self {
347        Self::with_state(
348            id.into(),
349            SheetBinding::Retained(state.clone()),
350            title.into(),
351            content.into_any_element(),
352        )
353    }
354
355    fn with_state(
356        id: ElementId,
357        state: SheetBinding,
358        title: SharedString,
359        content: AnyElement,
360    ) -> Self {
361        Self {
362            id,
363            state,
364            title,
365            content,
366            edge: SheetEdge::Bottom,
367            mode: SheetMode::Standard,
368            extent: px(320.),
369            expansion: None,
370            placement: SheetPlacement::Docked,
371            margins: SheetMargins::default(),
372            header: None,
373            back: None,
374            close_content: None,
375            close_label: "Close".into(),
376            show_close: true,
377            footer: None,
378            footer_divider: false,
379            edge_divider: false,
380            properties: DialogProperties::default(),
381            on_dismiss_request: None,
382            on_close: None,
383            layer: 0,
384            shape: None,
385            container_role: None,
386            content_role: None,
387            colors: SheetColors::default(),
388            tonal_elevation: Elevation::Level0,
389            shadow_elevation: None,
390            scrim_opacity: 0.32,
391            presence: None,
392            layout_size: None,
393            peek_height: None,
394            max_width: px(640.),
395            drag_enabled: true,
396            show_handle: true,
397            handle_content: None,
398            handle_label: "Resize bottom sheet".into(),
399            thresholds: BottomSheetThresholds::default(),
400            content_insets: ScaffoldInsets::default(),
401        }
402    }
403
404    pub(crate) fn in_scaffold(mut self, size: Size<Pixels>) -> Self {
405        self.edge = SheetEdge::Bottom;
406        self.mode = SheetMode::Standard;
407        self.layout_size = Some(size);
408        self
409    }
410
411    /// Sets the retained bottom sheet's partial height. It fits the expanded extent.
412    pub fn peek_height(mut self, height: Pixels) -> Self {
413        if f32::from(height).is_finite() {
414            self.peek_height = Some(height.max(px(48.)));
415        }
416        self
417    }
418
419    /// Sets the bottom sheet's maximum width in logical pixels.
420    pub fn max_width(mut self, width: Pixels) -> Self {
421        if f32::from(width).is_finite() && width > px(0.) {
422            self.max_width = width;
423        }
424        self
425    }
426
427    pub fn drag_enabled(mut self, enabled: bool) -> Self {
428        self.drag_enabled = enabled;
429        self
430    }
431
432    pub fn drag_thresholds(mut self, thresholds: BottomSheetThresholds) -> Self {
433        self.thresholds = thresholds.normalized();
434        self
435    }
436
437    /// Replaces the grip decoration of the retained sheet's resize control.
438    pub fn handle_content(mut self, content: impl IntoElement) -> Self {
439        self.handle_content = Some(content.into_any_element());
440        self
441    }
442
443    /// Names the resize action for keyboard and assistive technology.
444    pub fn handle_label(mut self, label: impl Into<SharedString>) -> Self {
445        self.handle_label = label.into();
446        self
447    }
448
449    /// Uses a text height action in place of the grip when multiple stops are available.
450    pub fn show_handle(mut self, show: bool) -> Self {
451        self.show_handle = show;
452        self
453    }
454
455    /// Sets logical padding within the bottom sheet's scrolling content.
456    pub fn content_insets(mut self, insets: ScaffoldInsets) -> Self {
457        self.content_insets = insets.normalized();
458        self
459    }
460
461    pub fn edge(mut self, edge: SheetEdge) -> Self {
462        if matches!(self.state, SheetBinding::Immediate(_)) {
463            self.edge = edge;
464        }
465        self
466    }
467
468    pub fn mode(mut self, mode: SheetMode) -> Self {
469        self.mode = mode;
470        self
471    }
472
473    /// Sets expanded height for a bottom sheet, or width for a side sheet.
474    pub fn extent(mut self, extent: Pixels) -> Self {
475        self.extent = extent.max(px(48.));
476        self
477    }
478
479    /// Enables a keyboard-operable expand and collapse action on a bottom sheet.
480    pub fn expandable(
481        mut self,
482        expanded: bool,
483        on_change: impl Fn(bool, &mut Window, &mut App) + 'static,
484    ) -> Self {
485        self.expansion = Some((expanded, Rc::new(on_change)));
486        self
487    }
488
489    pub fn placement(mut self, placement: SheetPlacement) -> Self {
490        self.placement = placement;
491        self
492    }
493
494    pub fn margins(mut self, margins: SheetMargins) -> Self {
495        self.margins = margins;
496        self
497    }
498
499    /// Replaces the visible heading while preserving the accessible sheet name.
500    pub fn header_content(mut self, heading: impl IntoElement) -> Self {
501        self.header = Some(heading.into_any_element());
502        self
503    }
504
505    /// Adds a named back action. Navigation ownership remains with the caller.
506    pub fn back(
507        mut self,
508        label: impl Into<SharedString>,
509        on_back: impl Fn(&mut Window, &mut App) + 'static,
510    ) -> Self {
511        self.back = Some(
512            IconButton::new(
513                "back",
514                label,
515                Icon::new(IconName::ArrowForward)
516                    .rotate(radians(std::f32::consts::PI))
517                    .mirror_in_rtl(true),
518            )
519            .on_activate(on_back)
520            .into_any_element(),
521        );
522        self
523    }
524
525    pub fn back_content(mut self, back: impl IntoElement) -> Self {
526        self.back = Some(back.into_any_element());
527        self
528    }
529
530    pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
531        self.close_label = label.into();
532        self
533    }
534
535    pub fn show_close(mut self, show: bool) -> Self {
536        self.show_close = show;
537        self
538    }
539
540    /// Builds a custom close control. Connect its activation to the supplied action.
541    pub fn close_content<E: IntoElement>(
542        mut self,
543        close: impl FnOnce(SheetClose) -> E + 'static,
544    ) -> Self {
545        self.close_content = Some(Box::new(move |action| close(action).into_any_element()));
546        self
547    }
548
549    pub fn footer(mut self, actions: impl IntoElement) -> Self {
550        self.footer = Some(actions.into_any_element());
551        self
552    }
553
554    pub fn footer_divider(mut self, visible: bool) -> Self {
555        self.footer_divider = visible;
556        self
557    }
558
559    /// Adds a divider between a docked Standard side sheet and its adjacent content.
560    pub fn edge_divider(mut self, visible: bool) -> Self {
561        self.edge_divider = visible;
562        self
563    }
564
565    pub fn properties(mut self, properties: DialogProperties) -> Self {
566        self.properties = properties;
567        self
568    }
569
570    /// Return false to veto a user-initiated close.
571    pub fn on_dismiss_request(
572        mut self,
573        request: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
574    ) -> Self {
575        self.on_dismiss_request = Some(Rc::new(request));
576        self
577    }
578
579    /// Receives accepted modal closes or requests to remove a Standard sheet.
580    pub fn on_close(
581        mut self,
582        close: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
583    ) -> Self {
584        self.on_close = Some(Rc::new(close));
585        self
586    }
587
588    /// Sets the stacking layer of a nested modal sheet.
589    pub fn layer(mut self, layer: usize) -> Self {
590        self.layer = layer;
591        self
592    }
593
594    pub fn shape(mut self, shape: CornerShape) -> Self {
595        self.shape = Some(shape);
596        self
597    }
598
599    pub fn container_role(mut self, role: ColorRole) -> Self {
600        self.container_role = Some(role);
601        self
602    }
603
604    pub fn content_role(mut self, role: ColorRole) -> Self {
605        self.content_role = Some(role);
606        self
607    }
608
609    pub fn colors(mut self, colors: SheetColors) -> Self {
610        self.colors = colors;
611        self
612    }
613
614    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
615        self.tonal_elevation = elevation;
616        self
617    }
618
619    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
620        self.shadow_elevation = Some(elevation);
621        self
622    }
623
624    /// Reuses the enclosing component's sampled presence.
625    pub(crate) fn sampled_presence(mut self, presence: gpui_base::motion::PresenceSample) -> Self {
626        self.presence = Some(presence);
627        self
628    }
629
630    pub fn scrim_opacity(mut self, opacity: f32) -> Self {
631        self.scrim_opacity = if opacity.is_nan() {
632            0.32
633        } else {
634            opacity.clamp(0., 1.)
635        };
636        self
637    }
638}
639
640impl RenderOnce for Sheet {
641    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
642        let modal = self.mode == SheetMode::Modal;
643        let viewport = window.viewport_size();
644        let available = self.layout_size.unwrap_or(viewport);
645        let bottom = self.edge == SheetEdge::Bottom;
646        let bottom_width = available.width.min(self.max_width);
647        let bottom_left = (viewport.width - bottom_width) / 2.;
648        let (dialog, retained) = match &self.state {
649            SheetBinding::Immediate(dialog) => (dialog.clone(), None),
650            SheetBinding::Retained(state) => (state.read(cx).dialog.clone(), Some(state.clone())),
651        };
652        let bottom_state = retained.as_ref().filter(|_| bottom);
653        let mut on_dismiss_request = self.on_dismiss_request;
654        let mut on_close = self.on_close;
655        let retained_layout = bottom_state.map(|state| {
656            let expanded = self.extent.min(available.height);
657            let partial = self
658                .peek_height
659                .unwrap_or_else(|| {
660                    if modal {
661                        available.height / 2.
662                    } else {
663                        px(56.)
664                    }
665                })
666                .min(expanded);
667            let layout = BottomSheetLayout {
668                available,
669                expanded,
670                partial,
671                mode: self.mode,
672                drag_enabled: self.drag_enabled && self.show_handle,
673            };
674            let height = state.update(cx, |state, cx| {
675                state.configure(layout, window, cx);
676                state.visible_height()
677            });
678            let state = state.downgrade();
679            let request = on_dismiss_request.take();
680            on_dismiss_request = Some(Rc::new(move |reason, window, cx| {
681                request
682                    .as_ref()
683                    .is_none_or(|request| request(reason, window, cx))
684                    && state
685                        .update(cx, |state, cx| state.accept_user_close(window, cx))
686                        .unwrap_or(false)
687            }));
688            if !modal && on_close.is_none() {
689                on_close = Some(Rc::new(|_, _, _| {}));
690            }
691            (height, partial.max(px(1.)))
692        });
693        let open = !modal || dialog.read(cx).is_open();
694        let presence = (modal && retained_layout.is_none()).then(|| {
695            self.presence
696                .unwrap_or_else(|| crate::motion::presence(&self.id, open, 240, window, cx))
697        });
698        let hidden = bottom_state.is_some_and(|state| {
699            let state = state.read(cx);
700            state.target_value() == BottomSheetValue::Hidden && state.visible_height() <= px(0.)
701        });
702        if hidden || presence.is_some_and(|presence| !presence.should_render()) {
703            return div().into_any_element();
704        }
705        let visibility = if let Some((height, peek)) = retained_layout {
706            (height / peek).clamp(0., 1.)
707        } else {
708            presence.map_or(1., |presence| presence.progress)
709        };
710        let theme = window_material_theme(window, cx).clone();
711        let left = match self.edge {
712            SheetEdge::Start => theme.layout.direction == Direction::Ltr,
713            SheetEdge::End => theme.layout.direction == Direction::Rtl,
714            SheetEdge::Bottom => false,
715        };
716        let detached = !bottom && self.placement == SheetPlacement::Detached;
717        let rtl = theme.layout.direction == Direction::Rtl;
718        let margins = if detached {
719            self.margins.fit(viewport, rtl)
720        } else {
721            Edges::default()
722        };
723        let available_width = (viewport.width - margins.left - margins.right).max(px(0.));
724        let target = if bottom {
725            self.extent.min(available.height)
726        } else {
727            self.extent.min(px(400.)).min(available_width)
728        };
729        let extent = if !bottom && !modal {
730            px(animate(
731                (self.id.clone(), "side-sheet-width"),
732                f32::from(target),
733                theme.motion.spec(
734                    MotionKind::Spatial,
735                    MotionSpeed::Default,
736                    cx.reduce_motion(),
737                ),
738                window,
739                cx,
740            ))
741            .clamp(px(0.), available_width)
742        } else {
743            target
744        };
745
746        let expanded = !bottom
747            || self
748                .expansion
749                .as_ref()
750                .is_none_or(|(expanded, _)| *expanded);
751        let focus = dialog.read(cx).focus.clone();
752        let scroll = dialog.read(cx).scroll.clone();
753        let session = modal
754            .then(|| ModalSession::new(&dialog, on_dismiss_request.clone(), on_close.clone(), cx));
755        let gesture = window
756            .use_keyed_state((self.id.clone(), "drag"), cx, |_, _| {
757                Rc::new(RefCell::new(Gesture::default()))
758            })
759            .read(cx)
760            .clone();
761        // The 48dp handle and 48dp header actions must remain operable at rest.
762        let collapsed = px(48. + 8. + 48. + 16.).min(extent);
763        let travel = extent - collapsed;
764        let height = if let Some((height, _)) = retained_layout {
765            height
766        } else if self.expansion.is_some() && bottom {
767            let drag = gesture.borrow();
768            let tracked = drag.capture.is_some();
769            let target = if expanded { extent } else { collapsed } - drag.offset;
770            let policy = if tracked {
771                MotionSpec::Instant
772            } else {
773                theme.motion.spec(
774                    MotionKind::Spatial,
775                    MotionSpeed::Default,
776                    cx.reduce_motion(),
777                )
778            };
779            px(animate(
780                (self.id.clone(), "sheet-height"),
781                f32::from(target),
782                policy,
783                window,
784                cx,
785            ))
786            .clamp(collapsed, extent)
787        } else {
788            extent
789        };
790        let offscreen = if retained_layout.is_some() {
791            px(0.)
792        } else {
793            -(if bottom { height } else { extent }) * (1. - visibility)
794        };
795        let handle = self
796            .expansion
797            .as_ref()
798            .filter(|_| bottom && retained_layout.is_none())
799            .map(|(expanded, change)| {
800                if open {
801                    drag_handle(
802                        &self.id,
803                        gesture,
804                        travel,
805                        *expanded,
806                        change.clone(),
807                        window,
808                        cx,
809                    )
810                } else {
811                    let tint = color(theme.colors.color(ColorRole::OnSurfaceVariant));
812                    div()
813                        .w_full()
814                        .h(px(48.))
815                        .flex_none()
816                        .flex()
817                        .items_center()
818                        .justify_center()
819                        .child(drag_handle_mark(tint))
820                        .into_any_element()
821                }
822            });
823        let show_default_close = (modal || on_close.is_some())
824            && bottom_state.is_none_or(|state| {
825                state
826                    .read(cx)
827                    .available_values()
828                    .contains(&BottomSheetValue::Hidden)
829            });
830        let close_action = SheetClose(match session.clone() {
831            Some(session) => CloseAction::Modal(session),
832            None => CloseAction::Standard(on_dismiss_request, on_close),
833        });
834        let handle = if let Some(state) = bottom_state
835            .filter(|state| self.show_handle || state.read(cx).available_values().len() > 1)
836        {
837            Some(
838                BottomHandle {
839                    id: self.id.clone(),
840                    state: state.clone(),
841                    close: close_action.clone(),
842                    decoration: self.handle_content,
843                    label: self.handle_label,
844                    grip: self.show_handle,
845                    thresholds: self.thresholds,
846                    tint: color(theme.colors.color(ColorRole::OnSurfaceVariant)),
847                    active: open,
848                }
849                .render(window, cx),
850            )
851        } else {
852            handle
853        };
854        let show_chrome = retained_layout.is_none() || handle.is_none() || height >= px(120.);
855        let body_insets = self.content_insets.resolve(theme.layout.direction);
856        let close = self
857            .show_close
858            .then(|| match self.close_content {
859                Some(content) => Some(content(close_action)),
860                None if show_default_close && bottom => Some(
861                    Button::new("close", self.close_label)
862                        .variant(ButtonVariant::Text)
863                        .on_activate(move |window, cx| close_action.activate(window, cx))
864                        .into_any_element(),
865                ),
866                None if show_default_close => Some(
867                    IconButton::new("close", self.close_label, Icon::new(IconName::Close))
868                        .on_activate(move |window, cx| close_action.activate(window, cx))
869                        .into_any_element(),
870                ),
871                None => None,
872            })
873            .flatten();
874        let container_role = self.container_role.unwrap_or(if !bottom && !modal {
875            ColorRole::Surface
876        } else {
877            ColorRole::SurfaceContainerLow
878        });
879        let shade = |role| color(theme.colors.color(role));
880        let content = self.colors.content.or_else(|| self.content_role.map(shade));
881        let side_color = shade(ColorRole::OnSurfaceVariant);
882        let default_title = if bottom {
883            Text::new(self.title.clone())
884                .id("sheet-heading")
885                .role(TypeRole::TitleMedium)
886        } else {
887            Text::new(self.title.clone())
888                .id("sheet-heading")
889                .role(TypeRole::TitleMedium)
890                .wrap()
891        };
892        let header = div()
893            .id("sheet-header")
894            .test_support()
895            .flex()
896            .flex_none()
897            .items_center()
898            .justify_between()
899            .flex_wrap()
900            .gap(if bottom { px(8.) } else { px(12.) })
901            .when(!bottom && rtl, Styled::flex_row_reverse)
902            .children(self.back)
903            .child(
904                div()
905                    .flex_1()
906                    .min_w(px(56.))
907                    .max_w_full()
908                    .when_some(
909                        self.colors.header.or((!bottom).then_some(side_color)),
910                        Styled::text_color,
911                    )
912                    .child(
913                        self.header
914                            .unwrap_or_else(|| default_title.into_any_element()),
915                    ),
916            )
917            .when_some(
918                self.expansion.filter(|_| bottom),
919                |header, (expanded, change)| {
920                    header.child(
921                        Button::new("expand", if expanded { "Collapse" } else { "Expand" })
922                            .variant(ButtonVariant::Text)
923                            .on_activate(move |window, cx| {
924                                if open {
925                                    change(!expanded, window, cx);
926                                }
927                            }),
928                    )
929                },
930            )
931            .children(close);
932        let divider = |divider: Divider| match self.colors.divider {
933            Some(color) => divider.color_override(color),
934            None => divider,
935        };
936        let footer = self.footer.map(|footer| {
937            div()
938                .id("sheet-footer")
939                .test_support()
940                .flex()
941                .flex_col()
942                .flex_none()
943                .min_h(px(72.))
944                .when(self.footer_divider, |footer| {
945                    footer.child(
946                        div()
947                            .id("sheet-footer-divider")
948                            .test_support()
949                            .child(divider(Divider::horizontal())),
950                    )
951                })
952                .child(
953                    div()
954                        .pt(px(16.))
955                        .flex_1()
956                        .flex()
957                        .items_center()
958                        .when(rtl, Styled::justify_end)
959                        .child(footer),
960                )
961        });
962        let shape = self.shape.unwrap_or_else(|| {
963            if bottom {
964                CornerRole::ExtraLargeTop.shape()
965            } else if detached {
966                CornerRole::Large.shape()
967            } else if modal {
968                if self.edge == SheetEdge::Start {
969                    CornerRole::LargeEnd.shape()
970                } else {
971                    CornerRole::LargeStart.shape()
972                }
973            } else {
974                CornerRole::None.shape()
975            }
976        });
977        let elevation = self
978            .shadow_elevation
979            .unwrap_or(if bottom || modal || detached {
980                Elevation::Level1
981            } else {
982                Elevation::Level0
983            });
984        let surface = Surface::new(container_role)
985            .shape(shape)
986            .shadow_elevation(elevation)
987            .tonal_elevation(self.tonal_elevation)
988            .when_some(content, Surface::content_color)
989            .when_some(self.colors.container, Surface::container_color)
990            .flex()
991            .flex_col()
992            .gap(px(8.))
993            .px(if bottom { px(16.) } else { px(24.) })
994            .pb(if bottom { px(16.) } else { px(24.) })
995            .when(handle.is_none(), |surface| surface.pt(px(16.)))
996            .children(handle)
997            .when_else(
998                bottom,
999                |surface| surface.w_full().h(height).overflow_hidden(),
1000                |surface| surface.h_full().flex_1().min_w_0().overflow_hidden(),
1001            )
1002            .children(show_chrome.then_some(header))
1003            .when(show_chrome && (expanded || height > collapsed), |surface| {
1004                surface.child(
1005                    isolated_scroll("sheet-content", &scroll)
1006                        .test_support()
1007                        .flex_1()
1008                        .child(if self.content_insets == ScaffoldInsets::default() {
1009                            self.content
1010                        } else {
1011                            div()
1012                                .pt(body_insets.top)
1013                                .pr(body_insets.right)
1014                                .pb(body_insets.bottom)
1015                                .pl(body_insets.left)
1016                                .child(self.content)
1017                                .into_any_element()
1018                        }),
1019                )
1020            })
1021            .children(footer.filter(|_| retained_layout.is_none() || height >= px(192.)));
1022        let edge_separator = (!bottom && !modal && !detached && self.edge_divider).then(|| {
1023            div()
1024                .id("sheet-edge-divider")
1025                .test_support()
1026                .h_full()
1027                .flex_none()
1028                .child(divider(Divider::vertical()))
1029        });
1030        let panel = div()
1031            .id(self.id.clone())
1032            .test_support()
1033            .when(open, |panel| {
1034                panel
1035                    .role(if modal { Role::Dialog } else { Role::Group })
1036                    .aria_label(self.title)
1037                    .when(modal, |panel| {
1038                        panel.a11y_synthetic_children(|tree| tree.parent_node().set_modal())
1039                    })
1040                    .occlude()
1041            })
1042            .when(bottom && !modal, |panel| {
1043                panel.w_full().max_w(bottom_width).mx_auto()
1044            })
1045            .when(!bottom, |panel| {
1046                panel
1047                    .flex()
1048                    .w_full()
1049                    .min_w_0()
1050                    .when(left, Styled::flex_row_reverse)
1051                    .when(!modal, Styled::h_full)
1052            })
1053            .when(modal, |panel| {
1054                panel.absolute().when_else(
1055                    bottom,
1056                    |panel| panel.bottom(offscreen).left(bottom_left).w(bottom_width),
1057                    |panel| {
1058                        panel
1059                            .w(extent)
1060                            .top(margins.top)
1061                            .h((viewport.height - margins.top - margins.bottom).max(px(0.)))
1062                            .when_else(
1063                                left,
1064                                |panel| panel.left(margins.left + offscreen),
1065                                |panel| panel.right(margins.right + offscreen),
1066                            )
1067                    },
1068                )
1069            })
1070            .children(edge_separator)
1071            .child(surface);
1072        if !modal {
1073            return if bottom {
1074                panel.into_any_element()
1075            } else {
1076                div()
1077                    .w(extent + margins.left + margins.right)
1078                    .max_w_full()
1079                    .min_w_0()
1080                    .h_full()
1081                    .pt(margins.top)
1082                    .pb(margins.bottom)
1083                    .pl(margins.left)
1084                    .pr(margins.right)
1085                    .child(panel)
1086                    .into_any_element()
1087            };
1088        }
1089
1090        let layer = 9usize.saturating_add(self.layer);
1091        let scrim = Scrim::new((self.id.clone(), "scrim"))
1092            .opacity(self.scrim_opacity * visibility)
1093            .when_some(self.colors.scrim, Scrim::color);
1094        if let Some(session) = session.filter(|_| open) {
1095            let properties = self.properties;
1096            let outside = session.clone();
1097            // Scope Base's host and focus trap IDs to this sheet, including
1098            // when nested sheets render as siblings.
1099            gpui::deferred(
1100                div().id((self.id, "sheet-root")).child(
1101                    gpui_base::Sheet::new(cx)
1102                        .focus_handle(focus)
1103                        .overlay_interactive(false)
1104                        .overlay(modal_backdrop(scrim, move |window, cx| {
1105                            if properties.dismiss_on_outside_click {
1106                                outside.dismiss(DialogCloseReason::OutsideClick, window, cx);
1107                            }
1108                        }))
1109                        .surface(div().absolute().inset_0().overflow_hidden().child(panel))
1110                        .request_close(move |window, cx| {
1111                            cx.stop_propagation();
1112                            if properties.dismiss_on_escape {
1113                                session.dismiss(DialogCloseReason::Escape, window, cx);
1114                            }
1115                        }),
1116                ),
1117            )
1118            .with_priority(layer)
1119            .into_any_element()
1120        } else {
1121            gpui::deferred(
1122                anchored().position(point(px(0.), px(0.))).child(
1123                    div()
1124                        .id((self.id.clone(), "sheet-exit"))
1125                        .absolute()
1126                        .top_0()
1127                        .left_0()
1128                        .w(viewport.width)
1129                        .h(viewport.height)
1130                        .overflow_hidden()
1131                        .child(scrim)
1132                        .child(exiting_panel(panel, &self.id, &dialog, window, cx)),
1133                ),
1134            )
1135            .with_priority(layer)
1136            .into_any_element()
1137        }
1138    }
1139}