A bottom sheet with a grab handle and centered content.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::drawer::Drawer;
const BASE_GOAL: i32 = 350;
const STEP: i32 = 10;
#[derive(Default)]
pub struct GoalView {
open: bool,
/// Change from the default goal, so `Default` starts at `BASE_GOAL`.
adjustment: i32,
}
impl Render for GoalView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let goal = BASE_GOAL + self.adjustment;
Drawer::new("goal", self.open)
.trigger(Button::new("goal-trigger", "Open drawer").variant(ButtonVariant::Outline))
.title("Move goal")
.description("Set your daily activity goal.")
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.child(
div()
.flex()
.items_center()
.justify_center()
.gap_6()
.child(
Button::new("goal-less", "−")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.disabled(goal <= 200)
.on_click(cx.listener(|this, _, _, cx| {
this.adjustment -= STEP;
cx.notify();
})),
)
.child(
div()
.flex()
.flex_col()
.items_center()
.child(
div()
.text_size(px(48.0))
.font_weight(FontWeight::BOLD)
.line_height(px(52.0))
.child(goal.to_string()),
)
.child(
div()
.text_xs()
.text_color(theme.muted_foreground)
.child("CALORIES/DAY"),
),
)
.child(
Button::new("goal-more", "+")
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm)
.disabled(goal >= 500)
.on_click(cx.listener(|this, _, _, cx| {
this.adjustment += STEP;
cx.notify();
})),
),
)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("goal-cancel", "Cancel")
.variant(ButtonVariant::Outline)
.on_click(cx.listener(|this, _, _, cx| {
this.open = false;
cx.notify();
})),
)
.child(Button::new("goal-submit", "Submit").on_click(cx.listener(
|this, _, _, cx| {
this.open = false;
cx.notify();
},
))),
)
}
}Installation
Copies src/ui/drawer.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/drawer.rs.src/ui/drawer.rs use std::{rc::Rc, sync::Arc}; use gpui::{div, prelude::*, px, AnyElement, App, ElementId, FontWeight, SharedString, Window}; use crate::theme::ActiveTheme; use crate::ui::dialog::{Modal, ModalPlacement, ModalTransition}; /// Content stays readable on wide windows, as in shadcn's `max-w-sm` drawer body. const CONTENT_WIDTH: f32 = 384.0; type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// The window edge a [`Drawer`] slides in from. #[derive(Clone, Copy, Default, PartialEq)] pub enum DrawerSide { Top, #[default] Bottom, Left, Right, } /// A sheet that slides up from the bottom (or another edge, see `side`) with a grab handle, /// rounded inner corners and centered content. /// The parent owns `open`. Drag-to-dismiss is not implemented: close with the scrim, Escape or /// a footer button. #[derive(IntoElement)] pub struct Drawer { id: ElementId, open: bool, trigger: Option<AnyElement>, title: Option<SharedString>, description: Option<SharedString>, children: Vec<AnyElement>, footer: Option<AnyElement>, side: DrawerSide, modal: bool, close_on_outside_click: bool, on_open_change: Option<OpenChangeHandler>, } impl Drawer { pub fn new(id: impl Into<ElementId>, open: bool) -> Self { Self { id: id.into(), open, trigger: None, title: None, description: None, children: Vec::new(), footer: None, side: DrawerSide::default(), modal: true, close_on_outside_click: true, on_open_change: None, } } /// Clicking this element asks the parent to open the drawer. pub fn trigger(mut self, trigger: impl IntoElement) -> Self { self.trigger = Some(trigger.into_any_element()); self } pub fn title(mut self, title: impl Into<SharedString>) -> Self { self.title = Some(title.into()); self } pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } pub fn footer(mut self, footer: impl IntoElement) -> Self { self.footer = Some(footer.into_any_element()); self } /// The window edge the drawer slides in from. Only a bottom drawer shows the grab handle; /// left and right drawers fill the window's height at up to 384px wide. pub fn side(mut self, side: DrawerSide) -> Self { self.side = side; self } /// `false` leaves the page behind undimmed and clickable while the drawer is open. A click /// outside still closes it unless `close_on_outside_click(false)`. pub fn modal(mut self, modal: bool) -> Self { self.modal = modal; self } /// `false` keeps the drawer open when the user clicks outside it; Escape and your own buttons /// still close it. Pair it with `modal(false)` to let people work on the page meanwhile. pub fn close_on_outside_click(mut self, close: bool) -> Self { self.close_on_outside_click = close; self } /// Receives the *next* open value. pub fn on_open_change( mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static, ) -> Self { self.on_open_change = Some(Rc::new(handler)); self } } impl ParentElement for Drawer { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for Drawer { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let viewport = window.viewport_size(); // Callers often reset the side as they close (`open_on: None`), so keep sliding out // on the side the drawer opened on. let opened_side = window.use_keyed_state( ElementId::NamedChild(Arc::new(self.id.clone()), "side".into()), cx, |_, _| self.side, ); let side = if self.open { opened_side.update(cx, |side, _| *side = self.side); self.side } else { *opened_side.read(cx) }; let theme = cx.theme(); let corner = theme.radius * 1.25; let vertical = matches!(side, DrawerSide::Left | DrawerSide::Right); // Side drawers follow shadcn's w-3/4 sm:max-w-sm. let side_width = (viewport.width * 0.75).min(px(CONTENT_WIDTH)); let content_width = if vertical { side_width } else { px(CONTENT_WIDTH) }; let panel = div() .relative() .flex() .flex_col() .items_center() .border_color(theme.border) .bg(theme.background) .text_color(theme.foreground) .map(|this| match side { DrawerSide::Bottom => this .w(viewport.width) .max_h(viewport.height * 0.8) .rounded_tl(corner) .rounded_tr(corner) .border_t_1() .border_l_1() .border_r_1() .child(div().mt_4().w(px(100.0)).h(px(8.0)).rounded_full().bg(theme.muted)), DrawerSide::Top => this .w(viewport.width) .max_h(viewport.height * 0.8) .rounded_bl(corner) .rounded_br(corner) .border_b_1() .border_l_1() .border_r_1(), DrawerSide::Left => this .w(side_width) .h(viewport.height) .rounded_tr(corner) .rounded_br(corner) .border_r_1(), DrawerSide::Right => this .w(side_width) .h(viewport.height) .rounded_tl(corner) .rounded_bl(corner) .border_l_1(), }) .child( div() .w(content_width) .flex() .flex_col() .when(vertical, |this| this.flex_1()) .when(self.title.is_some() || self.description.is_some(), |this| { this.child( div() .flex() .flex_col() .when(!vertical, |this| this.items_center()) .gap(px(6.0)) .p_4() .when_some(self.title, |this, title| { this.child(div().font_weight(FontWeight::SEMIBOLD).child(title)) }) .when_some(self.description, |this, description| { this.child( div().text_sm().text_color(theme.muted_foreground).child(description), ) }), ) }) .child(div().px_4().children(self.children)) .when_some(self.footer, |this, footer| { this.child( div() .flex() .gap_2() .p_4() // Side drawers pin the footer to the bottom edge, like a sheet. .map(|this| if vertical { this.mt_auto().flex_col() } else { this.justify_center() }) .child(footer), ) }), ); let placement = match side { DrawerSide::Top => ModalPlacement::Top, DrawerSide::Bottom => ModalPlacement::Bottom, DrawerSide::Left => ModalPlacement::Left, DrawerSide::Right => ModalPlacement::Right, }; // The modal slides the panel in from `side` on vaul's curve, and back out before unmounting. Modal::new(self.id, self.open) .placement(placement) .transition(ModalTransition::DRAWER) .modal(self.modal) .close_on_outside_click(self.close_on_outside_click) .when_some(self.trigger, |this, trigger| this.trigger(trigger)) .when_some(self.on_open_change, |this, handler| { this.on_open_change(move |open, window, cx| handler(open, window, cx)) }) .panel(panel) } }Register the module
// src/ui/mod.rs pub mod drawer;
Usage
use crate::ui::drawer::*;Examples
Position
side sets the window edge the drawer slides in from: Top, Bottom (the default), Left or Right.
use gpui::{div, prelude::*, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::drawer::{Drawer, DrawerSide};
#[derive(Default)]
pub struct DrawerPosition {
/// The side the drawer is open on, or `None` when closed.
open_on: Option<DrawerSide>,
}
impl Render for DrawerPosition {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let sides = [
("Top", DrawerSide::Top),
("Right", DrawerSide::Right),
("Bottom", DrawerSide::Bottom),
("Left", DrawerSide::Left),
];
let label = sides
.iter()
.find(|(_, side)| Some(*side) == self.open_on)
.map_or("", |(label, _)| *label)
.to_lowercase();
div()
.flex()
.gap_2()
.children(sides.into_iter().map(|(label, side)| {
Button::new(("drawer-position", side as usize), label)
.variant(ButtonVariant::Outline)
.on_click(cx.listener(move |this, _, _, cx| {
this.open_on = Some(side);
cx.notify();
}))
}))
.child(
Drawer::new("drawer-position", self.open_on.is_some())
.side(self.open_on.unwrap_or_default())
.title("Move goal")
.description(format!("This drawer slides in from the {label}."))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
if !open {
this.open_on = None;
}
cx.notify();
}))
.footer(
Button::new("drawer-position-close", "Close")
.variant(ButtonVariant::Outline)
.on_click(cx.listener(|this, _, _, cx| {
this.open_on = None;
cx.notify();
})),
),
)
}
}Nested
A drawer can open another from its content. The parent stays mounted behind the front one and ignores close requests until the nested drawer is gone.
use gpui::{div, prelude::*, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::drawer::Drawer;
#[derive(Default)]
pub struct DrawerNested {
open: bool,
nested_open: bool,
}
impl Render for DrawerNested {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let nested = Drawer::new("drawer-nested-inner", self.nested_open)
.title("Notification settings")
.description("Pick how often we email you.")
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.nested_open = *open;
cx.notify();
}))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child("Close this drawer to return to your account settings."),
)
.footer(
Button::new("drawer-nested-done", "Done").on_click(cx.listener(|this, _, _, cx| {
this.nested_open = false;
cx.notify();
})),
);
Drawer::new("drawer-nested", self.open)
.trigger(Button::new("drawer-nested-trigger", "Open Drawer").variant(ButtonVariant::Outline))
.title("Account settings")
.description("Manage your profile and preferences.")
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
// A click on the nested drawer lands outside this one; it shouldn't close both.
if !*open && this.nested_open {
return;
}
this.open = *open;
cx.notify();
}))
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child("Notification preferences open in a second drawer on top of this one."),
)
.child(nested)
.footer(
div()
.flex()
.gap_2()
.child(
Button::new("drawer-nested-close", "Close")
.variant(ButtonVariant::Outline)
.on_click(cx.listener(|this, _, _, cx| {
this.open = false;
cx.notify();
})),
)
.child(Button::new("drawer-nested-open", "Notifications").on_click(cx.listener(
|this, _, _, cx| {
this.nested_open = true;
cx.notify();
},
))),
)
}
}Non Modal
modal(false) drops the scrim so the page stays usable while the drawer is open, and close_on_outside_click(false) keeps it open while you click around. Try the counter.
use gpui::{div, prelude::*, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::drawer::Drawer;
#[derive(Default)]
pub struct DrawerNonModal {
open: bool,
clicks: usize,
}
impl Render for DrawerNonModal {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.gap_2()
.child(
Drawer::new("drawer-non-modal", self.open)
.trigger(Button::new("drawer-non-modal-trigger", "Open Drawer").variant(ButtonVariant::Outline))
.title("Non-modal drawer")
.description("The page behind stays interactive. Press Escape or Close to dismiss.")
.modal(false)
.close_on_outside_click(false)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.footer(
Button::new("drawer-non-modal-close", "Close")
.variant(ButtonVariant::Outline)
.on_click(cx.listener(|this, _, _, cx| {
this.open = false;
cx.notify();
})),
),
)
.child(
Button::new("drawer-non-modal-count", format!("Clicked {} times", self.clicks))
.variant(ButtonVariant::Secondary)
.on_click(cx.listener(|this, _, _, cx| {
this.clicks += 1;
cx.notify();
})),
)
}
}Responsive
Show a Dialog in wide windows and a Drawer in narrow ones by checking the viewport width when rendering. Resize the window to switch between them.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dialog::Dialog;
use crate::ui::drawer::Drawer;
use crate::ui::field::Field;
use crate::ui::input::TextInput;
/// Tailwind's `md` breakpoint, which shadcn's example switches on.
const DESKTOP_WIDTH: f32 = 768.0;
const TITLE: &str = "Edit profile";
const DESCRIPTION: &str = "Make changes to your profile here. Click save when you're done.";
#[derive(Default)]
pub struct DrawerResponsive {
open: bool,
}
impl Render for DrawerResponsive {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let name = window.use_keyed_state("drawer-responsive-name", cx, |_, cx| {
TextInput::new(cx).default_value("Pedro Duarte")
});
let username = window.use_keyed_state("drawer-responsive-username", cx, |_, cx| {
TextInput::new(cx).default_value("@peduarte")
});
let form = div()
.flex()
.flex_col()
.gap_4()
.child(Field::new().label("Name").child(name))
.child(Field::new().label("Username").child(username));
let trigger = Button::new("drawer-responsive-trigger", "Edit Profile").variant(ButtonVariant::Outline);
let save = Button::new("drawer-responsive-save", "Save changes").on_click(cx.listener(|this, _, _, cx| {
this.open = false;
cx.notify();
}));
let on_open_change = cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
});
if window.viewport_size().width >= px(DESKTOP_WIDTH) {
Dialog::new("drawer-responsive-dialog", self.open)
.trigger(trigger)
.title(TITLE)
.description(DESCRIPTION)
.on_open_change(on_open_change)
.child(form)
.footer(save)
.into_any_element()
} else {
Drawer::new("drawer-responsive-drawer", self.open)
.trigger(trigger)
.title(TITLE)
.description(DESCRIPTION)
.on_open_change(on_open_change)
.child(form)
.footer(save)
.into_any_element()
}
}
}API Reference
DrawerSide
The window edge a [Drawer] slides in from.
DrawerSide::TopDrawerSide::BottomDrawerSide::LeftDrawerSide::RightDrawer
A sheet that slides up from the bottom (or another edge, see side) with a grab handle, rounded inner corners and centered content. The parent owns open. Drag-to-dismiss is not implemented: close with the scrim, Escape or a footer button.
Drawer::new(id: impl Into<ElementId>, open: bool) -> Self.trigger(trigger: impl IntoElement)Clicking this element asks the parent to open the drawer.
.title(title: impl Into<SharedString>).description(description: impl Into<SharedString>).footer(footer: impl IntoElement).side(side: DrawerSide)The window edge the drawer slides in from. Only a bottom drawer shows the grab handle; left and right drawers fill the window's height at up to 384px wide.
.modal(modal: bool)false leaves the page behind undimmed and clickable while the drawer is open. A click outside still closes it unless close_on_outside_click(false).
.close_on_outside_click(close: bool)false keeps the drawer open when the user clicks outside it; Escape and your own buttons still close it. Pair it with modal(false) to let people work on the page meanwhile.
.on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.