Skip to main content

gpui_material_components/overlay/
bottom_sheet.rs

1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4    AnyElement, App, AppContext, Context, DragMoveEvent, ElementId, Entity, Hsla,
5    InteractiveElement, IntoElement, MouseButton, ParentElement, Pixels, Render, Role,
6    SharedString, Size, StatefulInteractiveElement, Styled, Subscription, WeakEntity, Window, div,
7    prelude::FluentBuilder, px,
8};
9use gpui_base::TestSupportExt as _;
10use gpui_material_foundation::DragCapture;
11use web_time::Instant;
12
13use super::{DialogState, SheetClose, SheetMode};
14
15/// Settled values for a retained bottom sheet.
16#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
17pub enum BottomSheetValue {
18    #[default]
19    Hidden,
20    PartiallyExpanded,
21    Expanded,
22}
23
24impl BottomSheetValue {
25    const ORDERED: [Self; 3] = [Self::Hidden, Self::PartiallyExpanded, Self::Expanded];
26}
27
28/// Thresholds for settling a released sheet drag.
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub struct BottomSheetThresholds {
31    /// Distance in logical pixels.
32    pub position: Pixels,
33    /// Speed in logical pixels per second.
34    pub velocity: Pixels,
35}
36
37impl Default for BottomSheetThresholds {
38    fn default() -> Self {
39        Self {
40            position: px(56.),
41            velocity: px(125.),
42        }
43    }
44}
45
46impl BottomSheetThresholds {
47    pub(super) fn normalized(self) -> Self {
48        let fallback = Self::default();
49        let nonnegative = |value: Pixels, default| {
50            if f32::from(value).is_finite() && value >= px(0.) {
51                value
52            } else {
53                default
54            }
55        };
56        Self {
57            position: nonnegative(self.position, fallback.position),
58            velocity: nonnegative(self.velocity, fallback.velocity),
59        }
60    }
61}
62
63#[derive(Clone, Copy, Debug, PartialEq)]
64pub(super) struct BottomSheetLayout {
65    pub(super) available: Size<Pixels>,
66    pub(super) expanded: Pixels,
67    pub(super) partial: Pixels,
68    pub(super) mode: SheetMode,
69    pub(super) drag_enabled: bool,
70}
71
72impl BottomSheetLayout {
73    fn height(self, value: BottomSheetValue) -> Pixels {
74        match value {
75            BottomSheetValue::Hidden => px(0.),
76            BottomSheetValue::PartiallyExpanded => self.partial,
77            BottomSheetValue::Expanded => self.expanded,
78        }
79    }
80}
81
82struct HeightMotion {
83    from: Pixels,
84    to: Pixels,
85    started: Instant,
86}
87
88const SETTLE: Duration = Duration::from_millis(240);
89const VELOCITY_AGE: Duration = Duration::from_millis(120);
90
91struct SheetDrag {
92    origin: Pixels,
93    start_height: Pixels,
94    last_position: Pixels,
95    last_motion: Instant,
96    velocity: Pixels,
97    capture: DragCapture,
98    _escape: Subscription,
99    _activation: Subscription,
100}
101
102/// Retained position, available stops and transitions of a bottom sheet.
103pub struct BottomSheetState {
104    pub(super) dialog: Entity<DialogState>,
105    current: BottomSheetValue,
106    target: BottomSheetValue,
107    enabled: Vec<BottomSheetValue>,
108    confirm: Option<Rc<dyn Fn(BottomSheetValue) -> bool>>,
109    layout: Option<BottomSheetLayout>,
110    height: Pixels,
111    motion: Option<HeightMotion>,
112    pressed: Option<Pixels>,
113    drag: Option<SheetDrag>,
114}
115
116impl BottomSheetState {
117    pub fn new(initial: BottomSheetValue, cx: &mut Context<Self>) -> Self {
118        Self {
119            dialog: cx.new(DialogState::new),
120            current: initial,
121            target: initial,
122            enabled: BottomSheetValue::ORDERED.to_vec(),
123            confirm: None,
124            layout: None,
125            height: px(0.),
126            motion: None,
127            pressed: None,
128            drag: None,
129        }
130    }
131
132    /// Configures available stops. An empty set retains the initial stop.
133    pub fn enabled_values(mut self, values: impl IntoIterator<Item = BottomSheetValue>) -> Self {
134        let values = values.into_iter().collect::<Vec<_>>();
135        self.enabled = BottomSheetValue::ORDERED
136            .into_iter()
137            .filter(|value| values.contains(value))
138            .collect();
139        if self.enabled.is_empty() {
140            self.enabled.push(self.current);
141        }
142        if !self.enabled.contains(&self.current) {
143            self.current = self.enabled[0];
144            self.target = self.current;
145        }
146        self
147    }
148
149    /// Vetoes a requested destination before it changes visibility or focus.
150    pub fn confirm_value_change(
151        mut self,
152        confirm: impl Fn(BottomSheetValue) -> bool + 'static,
153    ) -> Self {
154        self.confirm = Some(Rc::new(confirm));
155        self
156    }
157
158    pub fn available_values(&self) -> &[BottomSheetValue] {
159        &self.enabled
160    }
161
162    pub fn current_value(&self) -> BottomSheetValue {
163        self.current
164    }
165
166    pub fn target_value(&self) -> BottomSheetValue {
167        self.target
168    }
169
170    pub fn is_animating(&self) -> bool {
171        self.motion.is_some()
172    }
173
174    pub fn visible_height(&self) -> Pixels {
175        self.height
176    }
177
178    /// Downward distance from the expanded stop in the sheet's layout.
179    pub fn offset(&self) -> Pixels {
180        self.layout
181            .map_or(px(0.), |layout| layout.expanded - self.height)
182    }
183
184    pub fn show(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
185        let value = if self.enabled.contains(&BottomSheetValue::PartiallyExpanded) {
186            BottomSheetValue::PartiallyExpanded
187        } else {
188            BottomSheetValue::Expanded
189        };
190        self.animate_to(value, window, cx)
191    }
192
193    pub fn expand(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
194        self.animate_to(BottomSheetValue::Expanded, window, cx)
195    }
196
197    pub fn partial_expand(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
198        self.animate_to(BottomSheetValue::PartiallyExpanded, window, cx)
199    }
200
201    pub fn hide(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
202        self.animate_to(BottomSheetValue::Hidden, window, cx)
203    }
204
205    pub fn animate_to(
206        &mut self,
207        value: BottomSheetValue,
208        window: &mut Window,
209        cx: &mut Context<Self>,
210    ) -> bool {
211        self.request(value, true, true, window, cx)
212    }
213
214    pub fn snap_to(
215        &mut self,
216        value: BottomSheetValue,
217        window: &mut Window,
218        cx: &mut Context<Self>,
219    ) -> bool {
220        self.request(value, false, true, window, cx)
221    }
222
223    pub(super) fn accept_user_close(
224        &mut self,
225        window: &mut Window,
226        cx: &mut Context<Self>,
227    ) -> bool {
228        (self.target != BottomSheetValue::Hidden || self.drag.is_some())
229            && self.request(BottomSheetValue::Hidden, true, false, window, cx)
230    }
231
232    fn request(
233        &mut self,
234        value: BottomSheetValue,
235        animate: bool,
236        synchronize_focus: bool,
237        window: &mut Window,
238        cx: &mut Context<Self>,
239    ) -> bool {
240        if !self.enabled.contains(&value)
241            || (value != self.target
242                && self.confirm.as_ref().is_some_and(|confirm| !confirm(value)))
243        {
244            return false;
245        }
246        self.release_drag(window, cx);
247        self.target = value;
248        if synchronize_focus
249            && self
250                .layout
251                .is_some_and(|layout| layout.mode == SheetMode::Modal)
252        {
253            self.dialog.update(cx, |dialog, cx| match value {
254                BottomSheetValue::Hidden => dialog.close(window, cx),
255                _ => dialog.open(window, cx),
256            });
257        }
258        self.move_to_target(animate, cx);
259        cx.notify();
260        window.refresh();
261        true
262    }
263
264    fn move_to_target(&mut self, animate: bool, cx: &App) {
265        let target = self
266            .layout
267            .map_or(px(0.), |layout| layout.height(self.target));
268        if !animate || cx.reduce_motion() || self.height == target {
269            self.height = target;
270            self.current = self.target;
271            self.motion = None;
272        } else {
273            self.motion = Some(HeightMotion {
274                from: self.height,
275                to: target,
276                started: cx.background_executor().now(),
277            });
278        }
279    }
280
281    pub(super) fn configure(
282        &mut self,
283        layout: BottomSheetLayout,
284        window: &mut Window,
285        cx: &mut Context<Self>,
286    ) {
287        let before = (
288            self.height,
289            self.current,
290            self.target,
291            self.is_animating(),
292            self.offset(),
293        );
294        if self.layout != Some(layout) {
295            let old = self.layout.replace(layout);
296            self.pressed = None;
297            if self.drag.is_some() {
298                self.release_drag(window, cx);
299                self.target = self.current;
300            }
301            self.height = if self.motion.is_some() {
302                self.height.clamp(px(0.), layout.expanded)
303            } else {
304                layout.height(self.current)
305            };
306            let moving = self.motion.is_some();
307            self.move_to_target(moving, cx);
308            if old.is_none_or(|old| old.mode != layout.mode) {
309                self.dialog.update(cx, |dialog, cx| {
310                    if layout.mode == SheetMode::Modal && self.target != BottomSheetValue::Hidden {
311                        dialog.open(window, cx);
312                    } else {
313                        dialog.close(window, cx);
314                    }
315                });
316            }
317        }
318        if let Some(motion) = &self.motion {
319            let elapsed = cx
320                .background_executor()
321                .now()
322                .saturating_duration_since(motion.started);
323            if cx.reduce_motion() || elapsed >= SETTLE {
324                self.height = motion.to;
325                self.current = self.target;
326                self.motion = None;
327            } else {
328                let t = elapsed.as_secs_f32() / SETTLE.as_secs_f32();
329                self.height = motion.from + (motion.to - motion.from) * (1. - (1. - t).powi(3));
330                window.request_animation_frame();
331            }
332        }
333        let after = (
334            self.height,
335            self.current,
336            self.target,
337            self.is_animating(),
338            self.offset(),
339        );
340        if before != after {
341            // Deliver the notification after GPUI leaves the draw phase.
342            let state = cx.weak_entity();
343            cx.defer(move |cx| {
344                let _ = state.update(cx, |_, cx| cx.notify());
345            });
346        }
347    }
348
349    fn release_drag(&mut self, window: &mut Window, cx: &mut App) -> bool {
350        self.pressed = None;
351        if let Some(drag) = self.drag.take() {
352            drag.capture.cancel(window, cx);
353            true
354        } else {
355            false
356        }
357    }
358
359    fn cancel_drag(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
360        if self.release_drag(window, cx) {
361            self.target = self.current;
362            self.move_to_target(true, cx);
363            cx.notify();
364            window.refresh();
365            true
366        } else {
367            false
368        }
369    }
370
371    fn begin_drag(&mut self, y: Pixels, window: &mut Window, cx: &mut Context<Self>) {
372        if self.layout.is_none_or(|layout| !layout.drag_enabled) {
373            return;
374        }
375        let origin = self.pressed.take().unwrap_or(y);
376        if self.drag.is_some() || self.enabled.len() < 2 {
377            return;
378        }
379        if self.motion.take().is_some()
380            && self.current == BottomSheetValue::Hidden
381            && self.target != BottomSheetValue::Hidden
382        {
383            self.current = self.target;
384        }
385        self.target = self.current;
386        let state = cx.weak_entity();
387        let capture = DragCapture::watch(window, cx, {
388            let state = state.clone();
389            move |window, cx| {
390                let _ = state.update(cx, |state, cx| state.cancel_drag(window, cx));
391            }
392        });
393        let window_id = window.window_handle().window_id();
394        let escape = cx.intercept_keystrokes(move |event, window, cx| {
395            if event.keystroke.key == "escape"
396                && window.window_handle().window_id() == window_id
397                && state
398                    .update(cx, |state, cx| state.cancel_drag(window, cx))
399                    .unwrap_or(false)
400            {
401                cx.stop_propagation();
402            }
403        });
404        let activation = cx.observe_window_activation(window, |state, window, cx| {
405            if !window.is_window_active() {
406                state.cancel_drag(window, cx);
407            }
408        });
409        self.drag = Some(SheetDrag {
410            origin,
411            start_height: self.height,
412            last_position: origin,
413            last_motion: cx.background_executor().now(),
414            velocity: px(0.),
415            capture,
416            _escape: escape,
417            _activation: activation,
418        });
419    }
420
421    fn drag_to(&mut self, y: Pixels, cx: &mut Context<Self>) -> bool {
422        let (Some(drag), Some(layout)) = (&mut self.drag, self.layout) else {
423            return false;
424        };
425        let now = cx.background_executor().now();
426        if y != drag.last_position {
427            let elapsed = now
428                .saturating_duration_since(drag.last_motion)
429                .as_secs_f32();
430            if elapsed > 0. {
431                drag.velocity = (drag.last_position - y) / elapsed;
432            }
433            drag.last_position = y;
434            drag.last_motion = now;
435        }
436        let low = layout.height(self.enabled[0]);
437        let high = layout.height(*self.enabled.last().expect("an available stop"));
438        self.height = (drag.start_height + drag.origin - y).clamp(low, high);
439        cx.notify();
440        true
441    }
442
443    fn finish_drag(
444        &mut self,
445        position: Pixels,
446        thresholds: BottomSheetThresholds,
447        window: &mut Window,
448        cx: &mut Context<Self>,
449    ) -> Option<BottomSheetValue> {
450        if !self.drag_to(position, cx) {
451            return None;
452        }
453        let drag = self.drag.as_ref().expect("the active drag");
454        let velocity = if cx
455            .background_executor()
456            .now()
457            .saturating_duration_since(drag.last_motion)
458            <= VELOCITY_AGE
459        {
460            drag.velocity
461        } else {
462            px(0.)
463        };
464        let target = self.settle_target(velocity, thresholds);
465        self.release_drag(window, cx);
466        Some(target)
467    }
468
469    fn settle_target(
470        &self,
471        velocity: Pixels,
472        thresholds: BottomSheetThresholds,
473    ) -> BottomSheetValue {
474        let layout = self.layout.expect("a laid out drag");
475        let start = layout.height(self.current);
476        let displacement = self.height - start;
477        let fling = velocity != px(0.) && velocity.abs() >= thresholds.velocity;
478        if !fling && displacement == px(0.) {
479            return self.current;
480        }
481        let positive = if fling {
482            velocity > px(0.)
483        } else {
484            displacement > px(0.)
485        };
486        let mut stops = self.enabled.iter().copied().filter(|value| {
487            let height = layout.height(*value);
488            if positive {
489                height > start
490            } else {
491                height < start
492            }
493        });
494        if fling {
495            return if positive {
496                stops.next()
497            } else {
498                stops.next_back()
499            }
500            .unwrap_or(self.current);
501        }
502        let mut crossed = stops.filter(|value| {
503            let distance = (layout.height(*value) - start).abs();
504            displacement.abs() >= thresholds.position.min(distance / 2.)
505        });
506        if positive {
507            crossed.next_back()
508        } else {
509            crossed.next()
510        }
511        .unwrap_or(self.current)
512    }
513
514    fn destination(&self, key: Option<&str>) -> Option<BottomSheetValue> {
515        let current = self
516            .enabled
517            .iter()
518            .position(|value| *value == self.target)?;
519        match key {
520            None => self.enabled.get((current + 1) % self.enabled.len()),
521            Some("up") => self.enabled.get(current + 1),
522            Some("down") => current
523                .checked_sub(1)
524                .and_then(|index| self.enabled.get(index)),
525            Some("home") => self.enabled.first(),
526            Some("end") => self.enabled.last(),
527            _ => None,
528        }
529        .copied()
530        .filter(|value| *value != self.target)
531    }
532}
533
534#[derive(Clone)]
535struct Driver {
536    state: WeakEntity<BottomSheetState>,
537    close: SheetClose,
538    thresholds: BottomSheetThresholds,
539}
540
541impl Driver {
542    fn navigate(&self, key: Option<&str>, window: &mut Window, cx: &mut App) -> bool {
543        let Some(state) = self.state.upgrade() else {
544            return false;
545        };
546        if let Some(target) = state.read(cx).destination(key) {
547            self.request(target, window, cx);
548            true
549        } else {
550            false
551        }
552    }
553
554    fn request(&self, target: BottomSheetValue, window: &mut Window, cx: &mut App) -> bool {
555        if target == BottomSheetValue::Hidden {
556            self.close.request(window, cx)
557        } else {
558            self.state
559                .update(cx, |state, cx| state.animate_to(target, window, cx))
560                .unwrap_or(false)
561        }
562    }
563
564    fn release(&self, y: Pixels, window: &mut Window, cx: &mut App) {
565        let target = self
566            .state
567            .update(cx, |state, cx| {
568                state.finish_drag(y, self.thresholds, window, cx)
569            })
570            .ok()
571            .flatten();
572        if let Some(target) = target {
573            if !self.request(target, window, cx) {
574                let _ = self.state.update(cx, |state, cx| {
575                    state.target = state.current;
576                    state.move_to_target(true, cx);
577                    cx.notify();
578                    window.refresh();
579                });
580            }
581            cx.stop_propagation();
582        }
583    }
584}
585
586struct DragPayload;
587
588impl Render for DragPayload {
589    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
590        div()
591    }
592}
593
594pub(super) struct BottomHandle {
595    pub(super) id: ElementId,
596    pub(super) state: Entity<BottomSheetState>,
597    pub(super) close: SheetClose,
598    pub(super) decoration: Option<AnyElement>,
599    pub(super) label: SharedString,
600    pub(super) grip: bool,
601    pub(super) thresholds: BottomSheetThresholds,
602    pub(super) tint: Hsla,
603    pub(super) active: bool,
604}
605
606impl BottomHandle {
607    pub(super) fn render(self, window: &mut Window, cx: &mut App) -> AnyElement {
608        let model = self.state.read(cx);
609        let enabled = self.active && model.available_values().len() > 1;
610        let draggable =
611            enabled && self.grip && model.layout.is_some_and(|layout| layout.drag_enabled);
612        let focus = window
613            .use_keyed_state((self.id.clone(), "bottom-handle"), cx, |_, cx| {
614                cx.focus_handle()
615            })
616            .read(cx)
617            .clone();
618        let driver = Driver {
619            state: self.state.downgrade(),
620            close: self.close,
621            thresholds: self.thresholds,
622        };
623        let decoration = if self.grip {
624            self.decoration.unwrap_or_else(|| {
625                div()
626                    .w(px(32.))
627                    .h(px(4.))
628                    .rounded_full()
629                    .bg(self.tint)
630                    .into_any_element()
631            })
632        } else {
633            crate::Text::new("Change sheet height")
634                .id("sheet-height-label")
635                .into_any_element()
636        };
637        let grip = div()
638            .id("bottom-sheet-resize")
639            .test_support()
640            .w_full()
641            .h(px(48.))
642            .flex()
643            .flex_none()
644            .items_center()
645            .justify_center()
646            .child(decoration);
647        if !enabled {
648            return grip.into_any_element();
649        }
650        let keyboard = driver.clone();
651        let accessibility = driver.clone();
652        let activate = driver.clone();
653        grip.role(Role::Button)
654            .aria_label(self.label)
655            .track_focus(&focus)
656            .tab_stop(true)
657            .on_click(move |_, window, cx| {
658                activate.navigate(None, window, cx);
659            })
660            .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| {
661                accessibility.navigate(None, window, cx);
662            })
663            .on_key_down(move |event, window, cx| {
664                if keyboard.navigate(Some(&event.keystroke.key), window, cx) {
665                    cx.stop_propagation();
666                }
667            })
668            .when(draggable, |grip| {
669                let pressed = driver.state.clone();
670                let start = driver.state.clone();
671                let moving = driver.state.clone();
672                let outside = driver.clone();
673                grip.cursor_ns_resize()
674                    .on_mouse_down(MouseButton::Left, move |event, _, cx| {
675                        let _ =
676                            pressed.update(cx, |state, _| state.pressed = Some(event.position.y));
677                    })
678                    .on_drag(DragPayload, move |_, _, window, cx| {
679                        focus.focus(window, cx);
680                        let y = window.mouse_position().y;
681                        let _ = start.update(cx, |state, cx| {
682                            state.begin_drag(y, window, cx);
683                            state.drag_to(y, cx);
684                        });
685                        cx.stop_propagation();
686                        cx.new(|_| DragPayload)
687                    })
688                    .on_drag_move(move |event: &DragMoveEvent<DragPayload>, window, cx| {
689                        if moving
690                            .update(cx, |state, cx| state.drag_to(event.event.position.y, cx))
691                            .unwrap_or(false)
692                        {
693                            window.refresh();
694                            cx.stop_propagation();
695                        }
696                    })
697                    .on_mouse_up(MouseButton::Left, move |event, window, cx| {
698                        driver.release(event.position.y, window, cx)
699                    })
700                    .on_mouse_up_out(MouseButton::Left, move |event, window, cx| {
701                        outside.release(event.position.y, window, cx)
702                    })
703            })
704            .into_any_element()
705    }
706}