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