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        let had_drag = self.release_drag(window, cx);
241        let prev_target = self.target;
242        let prev_current = self.current;
243        let prev_height = self.height;
244        let was_animating = self.motion.is_animating();
245        self.target = value;
246        let mut dialog_changed = false;
247        if synchronize_focus
248            && self
249                .layout
250                .is_some_and(|layout| layout.mode == SheetMode::Modal)
251        {
252            let want_open = value != BottomSheetValue::Hidden;
253            if self.dialog.read(cx).is_open() != want_open {
254                dialog_changed = true;
255                self.dialog.update(cx, |dialog, cx| match value {
256                    BottomSheetValue::Hidden => dialog.close(window, cx),
257                    _ => dialog.open(window, cx),
258                });
259            }
260        }
261        self.move_to_target(animate, cx);
262        let changed = had_drag
263            || dialog_changed
264            || prev_target != self.target
265            || prev_current != self.current
266            || prev_height != self.height
267            || was_animating
268            || self.motion.is_animating();
269        if changed {
270            cx.notify();
271            window.refresh();
272        }
273        true
274    }
275
276    fn move_to_target(&mut self, animate: bool, cx: &App) {
277        let target = self
278            .layout
279            .map_or(px(0.), |layout| layout.height(self.target));
280        let now = cx.background_executor().now();
281        if !animate || cx.reduce_motion() {
282            self.height = target;
283            self.current = self.target;
284            self.motion.snap_to(f32::from(target));
285        } else {
286            self.motion
287                .animate_to(f32::from(target), SETTLE, Easing::EaseOut, now, false);
288            self.height = px(self.motion.value());
289            if !self.motion.is_animating() {
290                self.current = self.target;
291            }
292        }
293    }
294
295    pub(super) fn configure(
296        &mut self,
297        layout: BottomSheetLayout,
298        window: &mut Window,
299        cx: &mut Context<Self>,
300    ) {
301        let before = (
302            self.height,
303            self.current,
304            self.target,
305            self.is_animating(),
306            self.offset(),
307        );
308        if self.layout != Some(layout) {
309            let old = self.layout.replace(layout);
310            self.pressed = None;
311            if self.drag.is_some() {
312                self.release_drag(window, cx);
313                self.target = self.current;
314            }
315            let moving = self.motion.is_animating();
316            self.height = if moving {
317                self.height.clamp(px(0.), layout.expanded)
318            } else {
319                layout.height(self.current)
320            };
321            self.motion.snap_to(f32::from(self.height));
322            self.move_to_target(moving, cx);
323            if old.is_none_or(|old| old.mode != layout.mode) {
324                self.dialog.update(cx, |dialog, cx| {
325                    if layout.mode == SheetMode::Modal && self.target != BottomSheetValue::Hidden {
326                        dialog.open(window, cx);
327                    } else {
328                        dialog.close(window, cx);
329                    }
330                });
331            }
332        }
333        if self.motion.is_animating() {
334            let now = cx.background_executor().now();
335            let (height, running) = self.motion.sample(now, cx.reduce_motion());
336            self.height = px(height);
337            if running {
338                if window.is_visible() {
339                    window.request_animation_frame();
340                }
341            } else {
342                self.current = self.target;
343            }
344        }
345        let after = (
346            self.height,
347            self.current,
348            self.target,
349            self.is_animating(),
350            self.offset(),
351        );
352        if before != after {
353            // Deliver the notification after GPUI leaves the draw phase.
354            let state = cx.weak_entity();
355            cx.defer(move |cx| {
356                let _ = state.update(cx, |_, cx| cx.notify());
357            });
358        }
359    }
360
361    fn release_drag(&mut self, window: &mut Window, cx: &mut App) -> bool {
362        self.pressed = None;
363        if let Some(drag) = self.drag.take() {
364            drag.capture.cancel(window, cx);
365            true
366        } else {
367            false
368        }
369    }
370
371    fn cancel_drag(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
372        if self.release_drag(window, cx) {
373            self.target = self.current;
374            self.move_to_target(true, cx);
375            cx.notify();
376            window.refresh();
377            true
378        } else {
379            false
380        }
381    }
382
383    fn begin_drag(&mut self, y: Pixels, window: &mut Window, cx: &mut Context<Self>) {
384        if self.layout.is_none_or(|layout| !layout.drag_enabled) {
385            return;
386        }
387        let origin = self.pressed.take().unwrap_or(y);
388        if self.drag.is_some() || self.enabled.len() < 2 {
389            return;
390        }
391        let was_animating = self.motion.is_animating();
392        self.motion.snap_to(f32::from(self.height));
393        if was_animating
394            && self.current == BottomSheetValue::Hidden
395            && self.target != BottomSheetValue::Hidden
396        {
397            self.current = self.target;
398        }
399        self.target = self.current;
400        let state = cx.weak_entity();
401        let capture = DragCapture::watch(window, cx, {
402            let state = state.clone();
403            move |window, cx| {
404                let _ = state.update(cx, |state, cx| state.cancel_drag(window, cx));
405            }
406        });
407        let window_id = window.window_handle().window_id();
408        let escape = cx.intercept_keystrokes(move |event, window, cx| {
409            if event.keystroke.key == "escape"
410                && window.window_handle().window_id() == window_id
411                && state
412                    .update(cx, |state, cx| state.cancel_drag(window, cx))
413                    .unwrap_or(false)
414            {
415                cx.stop_propagation();
416            }
417        });
418        let activation = cx.observe_window_activation(window, |state, window, cx| {
419            if !window.is_window_active() {
420                state.cancel_drag(window, cx);
421            }
422        });
423        self.drag = Some(SheetDrag {
424            origin,
425            start_height: self.height,
426            last_position: origin,
427            last_motion: cx.background_executor().now(),
428            velocity: px(0.),
429            capture,
430            _escape: escape,
431            _activation: activation,
432        });
433    }
434
435    fn drag_to(&mut self, y: Pixels, cx: &mut Context<Self>) -> Option<bool> {
436        let (Some(drag), Some(layout)) = (&mut self.drag, self.layout) else {
437            return None;
438        };
439        let now = cx.background_executor().now();
440        if y != drag.last_position {
441            let elapsed = now
442                .saturating_duration_since(drag.last_motion)
443                .as_secs_f32();
444            if elapsed > 0. {
445                drag.velocity = (drag.last_position - y) / elapsed;
446            }
447            drag.last_position = y;
448            drag.last_motion = now;
449        }
450        let low = layout.height(self.enabled[0]);
451        let high = layout.height(*self.enabled.last().expect("an available stop"));
452        let next = (drag.start_height + drag.origin - y).clamp(low, high);
453        let changed = self.height != next || self.motion.is_animating();
454        self.height = next;
455        self.motion.snap_to(f32::from(self.height));
456        if changed {
457            cx.notify();
458        }
459        Some(changed)
460    }
461
462    fn finish_drag(
463        &mut self,
464        position: Pixels,
465        thresholds: BottomSheetThresholds,
466        window: &mut Window,
467        cx: &mut Context<Self>,
468    ) -> Option<BottomSheetValue> {
469        self.drag_to(position, cx)?;
470        let drag = self.drag.as_ref().expect("the active drag");
471        let velocity = if cx
472            .background_executor()
473            .now()
474            .saturating_duration_since(drag.last_motion)
475            <= VELOCITY_AGE
476        {
477            drag.velocity
478        } else {
479            px(0.)
480        };
481        let target = self.settle_target(velocity, thresholds);
482        self.release_drag(window, cx);
483        Some(target)
484    }
485
486    fn settle_target(
487        &self,
488        velocity: Pixels,
489        thresholds: BottomSheetThresholds,
490    ) -> BottomSheetValue {
491        let layout = self.layout.expect("a laid out drag");
492        let start = layout.height(self.current);
493        let displacement = self.height - start;
494        let fling = velocity != px(0.) && velocity.abs() >= thresholds.velocity;
495        if !fling && displacement == px(0.) {
496            return self.current;
497        }
498        let positive = if fling {
499            velocity > px(0.)
500        } else {
501            displacement > px(0.)
502        };
503        let mut stops = self.enabled.iter().copied().filter(|value| {
504            let height = layout.height(*value);
505            if positive {
506                height > start
507            } else {
508                height < start
509            }
510        });
511        if fling {
512            return if positive {
513                stops.next()
514            } else {
515                stops.next_back()
516            }
517            .unwrap_or(self.current);
518        }
519        let mut crossed = stops.filter(|value| {
520            let distance = (layout.height(*value) - start).abs();
521            displacement.abs() >= thresholds.position.min(distance / 2.)
522        });
523        if positive {
524            crossed.next_back()
525        } else {
526            crossed.next()
527        }
528        .unwrap_or(self.current)
529    }
530
531    fn destination(&self, key: Option<&str>) -> Option<BottomSheetValue> {
532        let current = self
533            .enabled
534            .iter()
535            .position(|value| *value == self.target)?;
536        match key {
537            None => self.enabled.get((current + 1) % self.enabled.len()),
538            Some("up") => self.enabled.get(current + 1),
539            Some("down") => current
540                .checked_sub(1)
541                .and_then(|index| self.enabled.get(index)),
542            Some("home") => self.enabled.first(),
543            Some("end") => self.enabled.last(),
544            _ => None,
545        }
546        .copied()
547        .filter(|value| *value != self.target)
548    }
549}
550
551#[derive(Clone)]
552struct Driver {
553    state: WeakEntity<BottomSheetState>,
554    close: SheetClose,
555    thresholds: BottomSheetThresholds,
556}
557
558impl Driver {
559    fn navigate(&self, key: Option<&str>, window: &mut Window, cx: &mut App) -> bool {
560        let Some(state) = self.state.upgrade() else {
561            return false;
562        };
563        if let Some(target) = state.read(cx).destination(key) {
564            self.request(target, window, cx);
565            true
566        } else {
567            false
568        }
569    }
570
571    fn request(&self, target: BottomSheetValue, window: &mut Window, cx: &mut App) -> bool {
572        if target == BottomSheetValue::Hidden {
573            self.close.request(window, cx)
574        } else {
575            self.state
576                .update(cx, |state, cx| state.animate_to(target, window, cx))
577                .unwrap_or(false)
578        }
579    }
580
581    fn release(&self, y: Pixels, window: &mut Window, cx: &mut App) {
582        let target = self
583            .state
584            .update(cx, |state, cx| {
585                state.finish_drag(y, self.thresholds, window, cx)
586            })
587            .ok()
588            .flatten();
589        if let Some(target) = target {
590            if !self.request(target, window, cx) {
591                let _ = self.state.update(cx, |state, cx| {
592                    state.target = state.current;
593                    state.move_to_target(true, cx);
594                    cx.notify();
595                    window.refresh();
596                });
597            }
598            cx.stop_propagation();
599        }
600    }
601}
602
603struct DragPayload;
604
605impl Render for DragPayload {
606    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
607        div()
608    }
609}
610
611pub(super) struct BottomHandle {
612    pub(super) id: ElementId,
613    pub(super) state: Entity<BottomSheetState>,
614    pub(super) close: SheetClose,
615    pub(super) decoration: Option<AnyElement>,
616    pub(super) label: SharedString,
617    pub(super) grip: bool,
618    pub(super) thresholds: BottomSheetThresholds,
619    pub(super) tint: Hsla,
620    pub(super) active: bool,
621}
622
623impl BottomHandle {
624    pub(super) fn render(self, window: &mut Window, cx: &mut App) -> AnyElement {
625        let model = self.state.read(cx);
626        let enabled = self.active && model.available_values().len() > 1;
627        let draggable =
628            enabled && self.grip && model.layout.is_some_and(|layout| layout.drag_enabled);
629        let focus = window
630            .use_keyed_state((self.id.clone(), "bottom-handle"), cx, |_, cx| {
631                cx.focus_handle()
632            })
633            .read(cx)
634            .clone();
635        let driver = Driver {
636            state: self.state.downgrade(),
637            close: self.close,
638            thresholds: self.thresholds,
639        };
640        let decoration = if self.grip {
641            self.decoration.unwrap_or_else(|| {
642                div()
643                    .w(px(32.))
644                    .h(px(4.))
645                    .rounded_full()
646                    .bg(self.tint)
647                    .into_any_element()
648            })
649        } else {
650            crate::Text::new("Change sheet height")
651                .id("sheet-height-label")
652                .into_any_element()
653        };
654        let grip = div()
655            .id("bottom-sheet-resize")
656            .test_support()
657            .w_full()
658            .h(px(48.))
659            .flex()
660            .flex_none()
661            .items_center()
662            .justify_center()
663            .child(decoration);
664        if !enabled {
665            return grip.into_any_element();
666        }
667        let keyboard = driver.clone();
668        let accessibility = driver.clone();
669        let activate = driver.clone();
670        grip.role(Role::Button)
671            .aria_label(self.label)
672            .track_focus(&focus)
673            .tab_stop(true)
674            .on_click(move |_, window, cx| {
675                activate.navigate(None, window, cx);
676            })
677            .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| {
678                accessibility.navigate(None, window, cx);
679            })
680            .on_key_down(move |event, window, cx| {
681                if keyboard.navigate(Some(&event.keystroke.key), window, cx) {
682                    cx.stop_propagation();
683                }
684            })
685            .when(draggable, |grip| {
686                let pressed = driver.state.clone();
687                let start = driver.state.clone();
688                let moving = driver.state.clone();
689                let outside = driver.clone();
690                grip.cursor_ns_resize()
691                    .on_mouse_down(MouseButton::Left, move |event, _, cx| {
692                        let _ =
693                            pressed.update(cx, |state, _| state.pressed = Some(event.position.y));
694                    })
695                    .on_drag(DragPayload, move |_, _, window, cx| {
696                        focus.focus(window, cx);
697                        let y = window.mouse_position().y;
698                        let _ = start.update(cx, |state, cx| {
699                            state.begin_drag(y, window, cx);
700                            state.drag_to(y, cx);
701                        });
702                        cx.stop_propagation();
703                        cx.new(|_| DragPayload)
704                    })
705                    .on_drag_move(move |event: &DragMoveEvent<DragPayload>, window, cx| {
706                        if let Ok(Some(changed)) =
707                            moving.update(cx, |state, cx| state.drag_to(event.event.position.y, cx))
708                        {
709                            if changed {
710                                window.refresh();
711                            }
712                            cx.stop_propagation();
713                        }
714                    })
715                    .on_mouse_up(MouseButton::Left, move |event, window, cx| {
716                        driver.release(event.position.y, window, cx)
717                    })
718                    .on_mouse_up_out(MouseButton::Left, move |event, window, cx| {
719                        outside.release(event.position.y, window, cx)
720                    })
721            })
722            .into_any_element()
723    }
724}