Skip to main content

gpui_deck/
drawer.rs

1//! A modal surface with an edge-aligned drag handle and optional snap heights.
2
3use gpui::{
4    AnyElement, App, AppContext as _, Context, ElementId, Entity, EventEmitter, FocusHandle,
5    InteractiveElement as _, IntoElement, MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement,
6    Pixels, Point, RenderOnce, SharedString, StyleRefinement, Styled, Subscription, Window, canvas,
7    div, prelude::FluentBuilder as _, px,
8};
9
10use crate::{
11    Dialog, DialogEvent, DialogPopup, DialogState, ElementExt as _, Placement, StyledExt as _,
12    TestSupportExt as _,
13};
14
15/// Retained pointer geometry around the existing modal lifecycle.
16///
17/// DialogState remains the sole owner of open state, focus trapping, initial
18/// focus and restoration. Only presses on the dedicated handle start dragging;
19/// scrolling and editing inside the body retain their normal native behavior.
20pub struct DrawerState {
21    dialog: Entity<DialogState>,
22    drag_start: Option<Pixels>,
23    offset: Pixels,
24    extent: Pixels,
25    side: Placement,
26    snap_points: Vec<f32>,
27    snap_index: usize,
28    _subscriptions: Vec<Subscription>,
29}
30
31impl DrawerState {
32    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
33        Self::with_dialog(cx.new(DialogState::new), window, cx)
34    }
35
36    /// Adopts an existing modal state, including its configured initial focus.
37    /// Mount that state in this Drawer only, not in a second Dialog as well.
38    pub fn with_dialog(
39        dialog: Entity<DialogState>,
40        window: &mut Window,
41        cx: &mut Context<Self>,
42    ) -> Self {
43        let subscriptions = vec![
44            cx.observe(&dialog, |_, _, cx| cx.notify()),
45            cx.subscribe(&dialog, |state, _, event: &DialogEvent, cx| {
46                if matches!(event, DialogEvent::Closed(_)) {
47                    state.drag_start = None;
48                    state.offset = px(0.);
49                }
50                cx.emit(*event);
51                cx.notify();
52            }),
53            cx.observe_window_activation(window, |state, window, cx| {
54                if !window.is_window_active() {
55                    state.cancel_drag(window, cx);
56                }
57            }),
58        ];
59        Self {
60            dialog,
61            drag_start: None,
62            offset: px(0.),
63            extent: px(0.),
64            side: Placement::Bottom,
65            snap_points: Vec::new(),
66            snap_index: 0,
67            _subscriptions: subscriptions,
68        }
69    }
70
71    pub fn dialog(&self) -> &Entity<DialogState> {
72        &self.dialog
73    }
74
75    /// Sets the physical window edge before mounting. The default is bottom.
76    pub fn side(mut self, side: Placement) -> Self {
77        assert!(
78            side.is_vertical() || self.snap_points.is_empty(),
79            "snap points require a vertical drawer"
80        );
81        self.side = side;
82        self
83    }
84
85    /// Sets increasing fractions of the window height for a top or bottom
86    /// drawer. The first fraction is its initial height.
87    pub fn snap_points(mut self, points: impl IntoIterator<Item = f32>) -> Self {
88        let points: Vec<_> = points.into_iter().collect();
89        assert!(
90            self.side.is_vertical(),
91            "snap points require a vertical drawer"
92        );
93        assert!(
94            !points.is_empty()
95                && points.iter().all(|&p| p > 0. && p <= 1.)
96                && points.windows(2).all(|pair| pair[0] < pair[1]),
97            "snap points must increase strictly from above zero through at most one"
98        );
99        self.snap_points = points;
100        self.snap_index = 0;
101        self
102    }
103
104    /// Index of the current resting height, retained when the drawer closes.
105    pub fn snap_index(&self) -> Option<usize> {
106        (!self.snap_points.is_empty()).then_some(self.snap_index)
107    }
108
109    /// Changes the resting height, for example from an accessible size button.
110    /// Returns false for an index outside the configured points.
111    pub fn set_snap_index(
112        &mut self,
113        index: usize,
114        window: &mut Window,
115        cx: &mut Context<Self>,
116    ) -> bool {
117        if index >= self.snap_points.len() {
118            return false;
119        }
120        self.cancel_drag(window, cx);
121        if self.snap_index != index {
122            self.snap_index = index;
123            cx.notify();
124            window.refresh();
125        }
126        true
127    }
128
129    pub fn is_open(&self, cx: &App) -> bool {
130        self.dialog.read(cx).is_open()
131    }
132
133    pub fn focus_handle(&self, cx: &App) -> FocusHandle {
134        self.dialog.read(cx).focus_handle().clone()
135    }
136
137    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
138        self.cancel_drag(window, cx);
139        self.dialog.update(cx, |dialog, cx| dialog.open(window, cx));
140    }
141
142    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
143        self.cancel_drag(window, cx);
144        self.dialog
145            .update(cx, |dialog, cx| dialog.close(window, cx));
146    }
147
148    pub fn is_dragging(&self) -> bool {
149        self.drag_start.is_some()
150    }
151
152    pub fn drag_offset(&self) -> Pixels {
153        self.offset
154    }
155
156    fn outward_position(&self, position: Point<Pixels>) -> Pixels {
157        match self.side {
158            Placement::Top => -position.y,
159            Placement::Bottom => position.y,
160            Placement::Left => -position.x,
161            Placement::Right => position.x,
162        }
163    }
164
165    fn snap_height(&self, window: &Window) -> Option<Pixels> {
166        self.snap_points
167            .get(self.snap_index)
168            .map(|fraction| window.viewport_size().height * *fraction)
169    }
170
171    fn start_drag(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
172        if self.is_open(cx) {
173            self.drag_start = Some(self.outward_position(position));
174            self.offset = px(0.);
175            cx.notify();
176        }
177    }
178
179    fn drag_to(&mut self, position: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
180        if let Some(start) = self.drag_start {
181            let distance = self.outward_position(position) - start;
182            self.offset = if let Some(rest) = self.snap_height(window) {
183                let tallest =
184                    window.viewport_size().height * self.snap_points[self.snap_points.len() - 1];
185                distance.clamp(rest - tallest, rest)
186            } else {
187                distance.clamp(px(0.), self.extent)
188            };
189            cx.notify();
190            window.refresh();
191        }
192    }
193
194    fn finish_drag(
195        &mut self,
196        position: Point<Pixels>,
197        window: &mut Window,
198        cx: &mut Context<Self>,
199    ) {
200        if self.drag_start.is_none() {
201            return;
202        }
203        self.drag_to(position, window, cx);
204        let dismiss = if let Some(rest) = self.snap_height(window) {
205            let height = rest - self.offset;
206            let viewport = window.viewport_size().height;
207            // The closed position and each snap height are neighboring stops.
208            if viewport > px(0.) && height < viewport * self.snap_points[0] / 2. {
209                true
210            } else {
211                self.snap_index = (0..self.snap_points.len())
212                    .min_by_key(|&index| (height - viewport * self.snap_points[index]).abs())
213                    .unwrap();
214                false
215            }
216        } else {
217            self.extent > px(0.) && self.offset >= self.extent / 3.
218        };
219        self.cancel_drag(window, cx);
220        if dismiss {
221            self.dialog
222                .update(cx, |dialog, cx| dialog.close(window, cx));
223        }
224    }
225
226    fn cancel_drag(&mut self, window: &mut Window, cx: &mut Context<Self>) {
227        if self.drag_start.take().is_some() || self.offset != px(0.) {
228            self.offset = px(0.);
229            cx.notify();
230            window.refresh();
231        }
232    }
233}
234
235impl EventEmitter<DialogEvent> for DrawerState {}
236
237/// An edge-aligned modal whose panel follows outward pointer movement.
238///
239/// [`Styled`] controls the panel, and normal children form its body. Supply a
240/// visible, noninteractive grip with [`Self::handle`]; its entire bounds become
241/// the drag target. Native mouse capture keeps tracking outside that target.
242/// Without snap points, releasing past one third of the panel extent closes
243/// the modal. Vertical snap points settle at the nearest height, including
244/// closed. Keyboard users keep Dialog's Escape and focus
245/// trap, and may use a regular `DialogClose` with [`DrawerState::dialog`].
246///
247/// Placement and clipping are structural. The application owns colors, panel
248/// dimensions, a backdrop, content scrolling and the handle's appearance.
249#[derive(IntoElement)]
250pub struct Drawer {
251    id: ElementId,
252    state: Entity<DrawerState>,
253    style: StyleRefinement,
254    children: Vec<AnyElement>,
255    handle: Option<AnyElement>,
256    backdrop: Option<AnyElement>,
257    label: Option<SharedString>,
258    description: Option<SharedString>,
259    escape: bool,
260    backdrop_closable: bool,
261}
262
263impl Drawer {
264    pub fn new(id: impl Into<ElementId>, state: &Entity<DrawerState>) -> Self {
265        Self {
266            id: id.into(),
267            state: state.clone(),
268            style: StyleRefinement::default(),
269            children: Vec::new(),
270            handle: None,
271            backdrop: None,
272            label: None,
273            description: None,
274            escape: true,
275            backdrop_closable: true,
276        }
277    }
278
279    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
280        self.label = Some(label.into());
281        self
282    }
283
284    pub fn accessibility_description(mut self, description: impl Into<SharedString>) -> Self {
285        self.description = Some(description.into());
286        self
287    }
288
289    pub fn handle(mut self, handle: impl IntoElement) -> Self {
290        self.handle = Some(handle.into_any_element());
291        self
292    }
293
294    pub fn backdrop(mut self, backdrop: impl IntoElement) -> Self {
295        self.backdrop = Some(backdrop.into_any_element());
296        self
297    }
298
299    pub fn close_on_escape(mut self, close: bool) -> Self {
300        self.escape = close;
301        self
302    }
303
304    pub fn close_on_backdrop_press(mut self, close: bool) -> Self {
305        self.backdrop_closable = close;
306        self
307    }
308}
309
310impl Styled for Drawer {
311    fn style(&mut self) -> &mut StyleRefinement {
312        &mut self.style
313    }
314}
315
316impl ParentElement for Drawer {
317    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
318        self.children.extend(children);
319    }
320}
321
322impl RenderOnce for Drawer {
323    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
324        let model = self.state.read(cx);
325        let dialog = model.dialog.clone();
326        let side = model.side;
327        let snap_height = model.snap_height(window);
328        let offset = model.offset;
329        let drag = self.state.clone();
330        let geometry = self.state.clone();
331        let movement = self.state.clone();
332        let release = self.state;
333        let panel = DialogPopup::new()
334            .relative()
335            .flex()
336            .when(side.is_vertical(), |panel| panel.flex_col().w_full())
337            .when(side.is_horizontal(), |panel| panel.h_full())
338            .max_w_full()
339            .max_h_full()
340            .refine_style(&self.style)
341            .on_prepaint(move |bounds, _, cx| {
342                geometry.update(cx, |state, _| {
343                    state.extent = if side.is_vertical() {
344                        bounds.size.height
345                    } else {
346                        bounds.size.width
347                    }
348                });
349            });
350        let panel = match (side, snap_height) {
351            (_, Some(height)) => panel
352                .min_h_0()
353                .max_h_full()
354                .h((height - offset).max(px(0.)))
355                .overflow_hidden(),
356            (Placement::Bottom, None) => panel.top(offset),
357            (Placement::Top, None) => panel.top(-offset),
358            (Placement::Left, None) => panel.left(-offset),
359            (Placement::Right, None) => panel.left(offset),
360        };
361        let handle = self.handle.map(|handle| {
362            div()
363                .id((self.id, "handle"))
364                .test_support()
365                .flex_shrink_0()
366                .when(side == Placement::Top, |handle| handle.mt_auto())
367                .on_mouse_down(MouseButton::Left, move |event, _, cx| {
368                    cx.stop_propagation();
369                    drag.update(cx, |state, cx| state.start_drag(event.position, cx));
370                })
371                .child(handle)
372        });
373        let panel = match side {
374            Placement::Bottom => panel.children(handle).children(self.children),
375            // Keep the grip at the panel's lower edge when its body overflows.
376            Placement::Top => panel
377                .when(handle.is_some(), |panel| panel.justify_end())
378                .children(self.children)
379                .children(handle),
380            Placement::Left | Placement::Right => {
381                let body = div()
382                    .min_w_0()
383                    .min_h_0()
384                    .flex_1()
385                    .flex()
386                    .flex_col()
387                    .children(self.children);
388                if side == Placement::Left {
389                    panel.child(body).children(handle)
390                } else {
391                    panel.children(handle).child(body)
392                }
393            }
394        }
395        .child(
396            canvas(
397                |_, _, _| {},
398                move |_, _, window, _| {
399                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
400                        if phase.capture() && movement.read(cx).is_dragging() {
401                            movement.update(cx, |state, cx| {
402                                if event.dragging() {
403                                    state.drag_to(event.position, window, cx);
404                                } else {
405                                    state.cancel_drag(window, cx);
406                                }
407                            });
408                            cx.stop_propagation();
409                        }
410                    });
411                    window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
412                        if phase.capture()
413                            && event.button == MouseButton::Left
414                            && release.read(cx).is_dragging()
415                        {
416                            release.update(cx, |state, cx| {
417                                state.finish_drag(event.position, window, cx);
418                            });
419                            cx.stop_propagation();
420                        }
421                    });
422                },
423            )
424            .absolute()
425            .inset_0()
426            .size_full(),
427        );
428        let dialog = Dialog::new(&dialog);
429        match side {
430            Placement::Bottom => dialog.items_end(),
431            Placement::Top => dialog.items_start(),
432            Placement::Left => dialog.justify_start(),
433            Placement::Right => dialog.justify_end(),
434        }
435        .overflow_hidden()
436        .close_on_escape(self.escape)
437        .close_on_backdrop_press(self.backdrop_closable)
438        .when_some(self.label, |this, label| this.accessibility_label(label))
439        .when_some(self.description, |this, description| {
440            this.accessibility_description(description)
441        })
442        .when_some(self.backdrop, |this, backdrop| this.backdrop(backdrop))
443        .popup(panel)
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use gpui::{Modifiers, Render, TestAppContext, VisualTestContext, point, size};
450
451    use super::*;
452
453    struct Harness {
454        state: Entity<DrawerState>,
455        trigger: FocusHandle,
456        _subscription: Subscription,
457    }
458
459    impl Render for Harness {
460        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
461            let side = self.state.read(cx).side;
462            div()
463                .size_full()
464                .child(
465                    crate::Button::new("open")
466                        .track_focus(&self.trigger)
467                        .child("Open"),
468                )
469                .child(
470                    Drawer::new("drawer", &self.state)
471                        .accessibility_label("Session review")
472                        .h(px(240.))
473                        .w(px(320.))
474                        .backdrop(div().size_full())
475                        .handle(
476                            div()
477                                .debug_selector(|| "drawer-grip".into())
478                                .when(side.is_vertical(), |grip| grip.h(px(30.)).w_full())
479                                .when(side.is_horizontal(), |grip| grip.w(px(30.)).h_full()),
480                        )
481                        .child(
482                            crate::Button::new("body-action")
483                                .debug_selector(|| "body-action".into())
484                                .flex_shrink_0()
485                                .h(px(40.))
486                                .child("Body action"),
487                        ),
488                )
489        }
490    }
491
492    fn open_drawer(
493        cx: &mut TestAppContext,
494        configure: impl FnOnce(DrawerState) -> DrawerState + 'static,
495    ) -> (&mut VisualTestContext, Entity<Harness>) {
496        let (root, cx) = cx.add_window_view(move |window, cx| {
497            let view = cx.new(|cx| {
498                let state = cx.new(|cx| configure(DrawerState::new(window, cx)));
499                Harness {
500                    _subscription: cx.observe(&state, |_, _, cx| cx.notify()),
501                    state,
502                    trigger: cx.focus_handle(),
503                }
504            });
505            crate::Root::new(view, window, cx)
506        });
507        let view = root
508            .read_with(cx, |root, _| root.view().clone())
509            .downcast::<Harness>()
510            .unwrap();
511        cx.update(|window, cx| {
512            window.activate_window();
513            view.read(cx).trigger.clone().focus(window, cx);
514            let state = view.read(cx).state.clone();
515            state.update(cx, |state, cx| state.open(window, cx));
516            window.draw(cx).clear(cx);
517        });
518        (cx, view)
519    }
520
521    #[gpui::test]
522    fn only_handle_drag_dismisses_after_threshold_and_returns_modal_focus(cx: &mut TestAppContext) {
523        cx.update(crate::init);
524        let (cx, view) = open_drawer(cx, |state| state);
525        let handle = cx.debug_bounds("drawer-grip").unwrap().center();
526        let short = point(handle.x, handle.y + px(30.));
527        cx.simulate_mouse_down(handle, MouseButton::Left, Modifiers::default());
528        cx.simulate_mouse_move(short, MouseButton::Left, Modifiers::default());
529        cx.update(|window, cx| window.draw(cx).clear(cx));
530        cx.simulate_mouse_up(short, MouseButton::Left, Modifiers::default());
531        cx.update(|window, cx| {
532            let state = view.read(cx).state.read(cx);
533            assert!(state.is_open(cx));
534            assert_eq!(state.drag_offset(), px(0.));
535            window.draw(cx).clear(cx);
536        });
537        let body = cx.debug_bounds("body-action").unwrap().center();
538        let end = point(handle.x, handle.y + px(120.));
539        cx.simulate_mouse_down(body, MouseButton::Left, Modifiers::default());
540        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
541        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
542        cx.update(|window, cx| {
543            assert!(view.read(cx).state.read(cx).is_open(cx));
544            window.draw(cx).clear(cx);
545        });
546        cx.simulate_mouse_down(handle, MouseButton::Left, Modifiers::default());
547        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
548        cx.update(|window, cx| window.draw(cx).clear(cx));
549        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
550        cx.update(|window, cx| {
551            assert!(!view.read(cx).state.read(cx).is_open(cx));
552            assert!(!view.read(cx).state.read(cx).is_dragging());
553            assert!(view.read(cx).trigger.is_focused(window));
554        });
555        cx.simulate_resize(gpui::size(px(260.), px(180.)));
556        cx.update(|window, cx| {
557            let state = view.read(cx).state.clone();
558            state.update(cx, |state, cx| state.open(window, cx));
559            window.draw(cx).clear(cx);
560            assert!(
561                state.read(cx).extent <= window.viewport_size().height,
562                "the drawer must fit the viewport so its grip stays reachable"
563            );
564        });
565        assert!(cx.debug_bounds("drawer-grip").unwrap().top() >= px(0.));
566    }
567
568    #[gpui::test]
569    fn outward_drags_on_each_edge_close_only_along_that_axis(cx: &mut TestAppContext) {
570        cx.update(crate::init);
571        for (side, delta) in [
572            (Placement::Top, point(px(0.), px(-120.))),
573            (Placement::Left, point(px(-120.), px(0.))),
574            (Placement::Right, point(px(120.), px(0.))),
575        ] {
576            let (cx, view) = open_drawer(cx, move |state| state.side(side));
577            cx.simulate_resize(size(px(400.), px(400.)));
578            cx.update(|window, cx| window.draw(cx).clear(cx));
579            let grip = cx.debug_bounds("drawer-grip").unwrap();
580            match side {
581                Placement::Top => assert_eq!(grip.bottom(), px(240.)),
582                Placement::Left => assert_eq!(grip.right(), px(320.)),
583                Placement::Right => assert_eq!(grip.left(), px(80.)),
584                Placement::Bottom => unreachable!(),
585            }
586            let start = grip.center();
587            let across = start + point(delta.y, delta.x);
588            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
589            cx.simulate_mouse_up(across, MouseButton::Left, Modifiers::default());
590            cx.update(|_, cx| assert!(view.read(cx).state.read(cx).is_open(cx)));
591            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
592            cx.simulate_mouse_move(start + delta, MouseButton::Left, Modifiers::default());
593            cx.update(|window, cx| window.draw(cx).clear(cx));
594            cx.simulate_mouse_up(start + delta, MouseButton::Left, Modifiers::default());
595            cx.update(|window, cx| {
596                assert!(!view.read(cx).state.read(cx).is_open(cx));
597                assert!(view.read(cx).trigger.is_focused(window));
598            });
599        }
600    }
601
602    #[gpui::test]
603    fn snap_heights_follow_the_grip_resize_and_close_at_the_lowest_stop(cx: &mut TestAppContext) {
604        cx.update(crate::init);
605        for side in [Placement::Bottom, Placement::Top] {
606            let (cx, view) = open_drawer(cx, move |state| state.side(side).snap_points([0.4, 0.8]));
607            let state = view.read_with(cx, |view, _| view.state.clone());
608            cx.simulate_resize(size(px(360.), px(100.)));
609            cx.update(|window, cx| window.draw(cx).clear(cx));
610            let grip = cx.debug_bounds("drawer-grip").unwrap();
611            match side {
612                Placement::Bottom => assert_eq!(grip.top(), px(60.)),
613                Placement::Top => assert_eq!(grip.bottom(), px(40.)),
614                _ => unreachable!(),
615            }
616            cx.simulate_resize(size(px(360.), px(400.)));
617            cx.update(|window, cx| {
618                window.draw(cx).clear(cx);
619                assert_eq!(state.read(cx).extent, px(160.));
620            });
621            let sign = if side == Placement::Bottom { 1. } else { -1. };
622            let start = cx.debug_bounds("drawer-grip").unwrap().center();
623            let end = start - point(px(0.), px(120.) * sign);
624            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
625            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
626            cx.update(|window, cx| {
627                window.draw(cx).clear(cx);
628                assert_eq!(state.read(cx).extent, px(280.));
629            });
630            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
631            cx.simulate_resize(size(px(360.), px(300.)));
632            cx.update(|window, cx| {
633                window.draw(cx).clear(cx);
634                assert_eq!(state.read(cx).snap_index(), Some(1));
635                assert_eq!(state.read(cx).extent, px(240.));
636                state.update(cx, |state, cx| {
637                    assert!(!state.set_snap_index(2, window, cx));
638                    assert!(state.set_snap_index(0, window, cx));
639                });
640                window.draw(cx).clear(cx);
641                assert_eq!(state.read(cx).extent, px(120.));
642            });
643            let start = cx.debug_bounds("drawer-grip").unwrap().center();
644            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
645            cx.simulate_mouse_up(
646                start + point(px(0.), px(80.) * sign),
647                MouseButton::Left,
648                Modifiers::default(),
649            );
650            cx.update(|_, cx| assert!(!state.read(cx).is_open(cx)));
651        }
652    }
653}