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