Skip to main content

gpui_component/
sheet.rs

1use gpui_base::TestSupportExt as _;
2use std::{rc::Rc, time::Duration};
3
4use gpui::{
5    Animation, AnimationExt as _, AnyElement, App, ClickEvent, DefiniteLength, DismissEvent, Edges,
6    EventEmitter, FocusHandle, InteractiveElement as _, IntoElement, ParentElement, Pixels,
7    RenderOnce, StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _, px,
8};
9use gpui_base::{ElementExt as _, Sheet as BaseSheet, TextSelectionScopeId, actions::Cancel};
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13use crate::{
14    ActiveTheme, IconName, Placement, Sizable, StyledExt as _, WindowExt as _,
15    button::{Button, ButtonVariants as _},
16    dialog::overlay_color,
17    h_flex,
18    scroll::ScrollableElement as _,
19    title_bar::TITLE_BAR_HEIGHT,
20    v_flex,
21};
22
23pub(crate) fn init(_: &mut App) {}
24
25/// The settings for sheets.
26#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
27pub struct SheetSettings {
28    /// The margin top for the sheet, default is [`TITLE_BAR_HEIGHT`].
29    pub margin_top: Pixels,
30}
31
32impl Default for SheetSettings {
33    fn default() -> Self {
34        Self {
35            margin_top: TITLE_BAR_HEIGHT,
36        }
37    }
38}
39
40/// Sheet component that slides in from the side of the window.
41#[derive(IntoElement)]
42pub struct Sheet {
43    pub(crate) focus_handle: FocusHandle,
44    pub(crate) placement: Placement,
45    pub(crate) size: DefiniteLength,
46    pub(crate) selection_scope: TextSelectionScopeId,
47    resizable: bool,
48    on_close: Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>,
49    title: Option<AnyElement>,
50    footer: Option<AnyElement>,
51    style: StyleRefinement,
52    children: Vec<AnyElement>,
53    overlay: bool,
54    overlay_closable: bool,
55}
56
57impl Sheet {
58    /// Creates a new Sheet.
59    pub fn new(_: &mut Window, cx: &mut App) -> Self {
60        Self {
61            focus_handle: cx.focus_handle(),
62            placement: Placement::Right,
63            size: DefiniteLength::Absolute(px(350.).into()),
64            selection_scope: TextSelectionScopeId::default(),
65            resizable: true,
66            title: None,
67            footer: None,
68            style: StyleRefinement::default(),
69            children: Vec::new(),
70            overlay: true,
71            overlay_closable: true,
72            on_close: Rc::new(|_, _, _| {}),
73        }
74    }
75
76    /// Sets the title of the sheet.
77    pub fn title(mut self, title: impl IntoElement) -> Self {
78        self.title = Some(title.into_any_element());
79        self
80    }
81
82    /// Set the footer of the sheet.
83    pub fn footer(mut self, footer: impl IntoElement) -> Self {
84        self.footer = Some(footer.into_any_element());
85        self
86    }
87
88    /// Sets the size of the sheet, default is 350px.
89    pub fn size(mut self, size: impl Into<DefiniteLength>) -> Self {
90        self.size = size.into();
91        self
92    }
93
94    /// Sets whether the sheet is resizable, default is `true`.
95    pub fn resizable(mut self, resizable: bool) -> Self {
96        self.resizable = resizable;
97        self
98    }
99
100    /// Set whether the sheet should have an overlay, default is `true`.
101    pub fn overlay(mut self, overlay: bool) -> Self {
102        self.overlay = overlay;
103        self
104    }
105
106    /// Set whether the sheet should be closable by clicking the overlay, default is `true`.
107    pub fn overlay_closable(mut self, overlay_closable: bool) -> Self {
108        self.overlay_closable = overlay_closable;
109        self
110    }
111
112    /// Listen to the close event of the sheet.
113    pub fn on_close(
114        mut self,
115        on_close: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
116    ) -> Self {
117        self.on_close = Rc::new(on_close);
118        self
119    }
120}
121
122impl EventEmitter<DismissEvent> for Sheet {}
123impl ParentElement for Sheet {
124    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
125        self.children.extend(elements);
126    }
127}
128impl Styled for Sheet {
129    fn style(&mut self) -> &mut gpui::StyleRefinement {
130        &mut self.style
131    }
132}
133
134impl RenderOnce for Sheet {
135    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
136        let placement = self.placement;
137        let selection_scope = self.selection_scope;
138        let frame_insets = crate::window_border::window_content_insets(window);
139        let safe_insets = crate::window_border::window_safe_insets(window);
140        let frame_insets = Edges {
141            top: frame_insets.top.max(safe_insets.top),
142            right: frame_insets.right.max(safe_insets.right),
143            bottom: frame_insets.bottom.max(safe_insets.bottom),
144            left: frame_insets.left.max(safe_insets.left),
145        };
146        let size = window.viewport_size()
147            - gpui::size(
148                frame_insets.left + frame_insets.right,
149                frame_insets.top + frame_insets.bottom,
150            );
151        let top = cx.theme().sheet.margin_top;
152        let base_size = window.text_style().font_size;
153        let rem_size = window.rem_size();
154        let mut paddings = Edges::all(px(16.));
155        if let Some(pl) = self.style.padding.left {
156            paddings.left = pl.to_pixels(base_size, rem_size);
157        }
158        if let Some(pr) = self.style.padding.right {
159            paddings.right = pr.to_pixels(base_size, rem_size);
160        }
161        if let Some(pt) = self.style.padding.top {
162            paddings.top = pt.to_pixels(base_size, rem_size);
163        }
164        if let Some(pb) = self.style.padding.bottom {
165            paddings.bottom = pb.to_pixels(base_size, rem_size);
166        }
167
168        let overlay = div()
169            .occlude()
170            .w(size.width)
171            .h(size.height)
172            .bg(overlay_color(self.overlay, cx));
173
174        let surface = v_flex()
175            .id("sheet-content")
176            .test_support()
177            .absolute()
178            .occlude()
179            .bg(cx.theme().tokens.background)
180            .border_color(cx.theme().border)
181            .shadow_xl()
182            .refine_style(&self.style)
183            .map(|this| {
184                // Set the size of the sheet.
185                if placement.is_horizontal() {
186                    this.w(self.size)
187                } else {
188                    this.h(self.size)
189                }
190            })
191            .map(|this| match self.placement {
192                Placement::Top => this.top(top).left_0().right_0().border_b_1(),
193                Placement::Right => this.top(top).right_0().bottom_0().border_l_1(),
194                Placement::Bottom => this.bottom_0().left_0().right_0().border_t_1(),
195                Placement::Left => this.top(top).left_0().bottom_0().border_r_1(),
196            })
197            .child(
198                // TitleBar
199                h_flex()
200                    .justify_between()
201                    .pl_4()
202                    .pr_3()
203                    .py_2()
204                    .w_full()
205                    .font_semibold()
206                    .child(self.title.unwrap_or(div().into_any_element()))
207                    .child(
208                        Button::new("close")
209                            .small()
210                            .ghost()
211                            .icon(IconName::Close)
212                            .on_click(|_, window, cx| {
213                                window.dispatch_action(Box::new(Cancel), cx);
214                            }),
215                    ),
216            )
217            .child(
218                div().flex_1().overflow_hidden().child(
219                    // Body
220                    v_flex()
221                        .size_full()
222                        .overflow_y_scrollbar()
223                        .pl(paddings.left)
224                        .pr(paddings.right)
225                        .children(self.children),
226                ),
227            )
228            .when_some(self.footer, |this, footer| {
229                // Footer
230                this.child(
231                    h_flex()
232                        .justify_between()
233                        .px_4()
234                        .py_3()
235                        .w_full()
236                        .child(footer),
237                )
238            })
239            .with_animation(
240                "slide",
241                Animation::new(Duration::from_secs_f64(0.15)),
242                move |this, delta| {
243                    let y = px(-100.) + delta * px(100.);
244                    this.map(|this| match placement {
245                        Placement::Top => this.top(top + y),
246                        Placement::Right => this.right(y),
247                        Placement::Bottom => this.bottom(y),
248                        Placement::Left => this.left(y),
249                    })
250                },
251            );
252        let surface = surface.text_selection_scope(selection_scope);
253
254        BaseSheet::new(cx)
255            .top(frame_insets.top)
256            .left(frame_insets.left)
257            .w(size.width)
258            .h(size.height)
259            .focus_handle(self.focus_handle)
260            .overlay_interactive(self.overlay)
261            .overlay_closable(self.overlay && self.overlay_closable)
262            .request_close(|window, cx| window.close_sheet(cx))
263            .on_close(move |event, window, cx| (self.on_close)(event, window, cx))
264            .overlay(overlay)
265            .surface(surface)
266    }
267}