1use std::{rc::Rc, time::Duration};
2
3use gpui::{App, AppContext, Context, Entity, Pixels, Size, Subscription, Window, px};
4use gpui_base::motion::Easing;
5use gpui_material_foundation::{DragCapture, RetargetTransition};
6use web_time::Instant;
7
8use super::super::{DialogState, SheetMode};
9
10#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
12pub enum BottomSheetValue {
13 #[default]
15 Hidden,
16 PartiallyExpanded,
18 Expanded,
20}
21
22impl BottomSheetValue {
23 const ORDERED: [Self; 3] = [Self::Hidden, Self::PartiallyExpanded, Self::Expanded];
24}
25
26#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct BottomSheetThresholds {
29 pub position: Pixels,
31 pub velocity: Pixels,
33}
34
35impl Default for BottomSheetThresholds {
36 fn default() -> Self {
37 Self {
38 position: px(56.),
39 velocity: px(125.),
40 }
41 }
42}
43
44impl BottomSheetThresholds {
45 pub(in crate::overlay) fn normalized(self) -> Self {
46 let fallback = Self::default();
47 let nonnegative = |value: Pixels, default| {
48 if f32::from(value).is_finite() && value >= px(0.) {
49 value
50 } else {
51 default
52 }
53 };
54 Self {
55 position: nonnegative(self.position, fallback.position),
56 velocity: nonnegative(self.velocity, fallback.velocity),
57 }
58 }
59}
60
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub(in crate::overlay) struct BottomSheetLayout {
63 pub(in crate::overlay) available: Size<Pixels>,
64 pub(in crate::overlay) expanded: Pixels,
65 pub(in crate::overlay) partial: Pixels,
66 pub(in crate::overlay) mode: SheetMode,
67 pub(in crate::overlay) drag_enabled: bool,
68}
69
70impl BottomSheetLayout {
71 fn height(self, value: BottomSheetValue) -> Pixels {
72 match value {
73 BottomSheetValue::Hidden => px(0.),
74 BottomSheetValue::PartiallyExpanded => self.partial,
75 BottomSheetValue::Expanded => self.expanded,
76 }
77 }
78}
79
80const SETTLE: Duration = Duration::from_millis(240);
81const VELOCITY_AGE: Duration = Duration::from_millis(120);
82
83struct SheetDrag {
84 origin: Pixels,
85 start_height: Pixels,
86 last_position: Pixels,
87 last_motion: Instant,
88 velocity: Pixels,
89 capture: DragCapture,
90 _escape: Subscription,
91 _activation: Subscription,
92}
93
94pub struct BottomSheetState {
96 pub(in crate::overlay) dialog: Entity<DialogState>,
97 pub(super) current: BottomSheetValue,
98 pub(super) target: BottomSheetValue,
99 enabled: Vec<BottomSheetValue>,
100 confirm: Option<Rc<dyn Fn(BottomSheetValue) -> bool>>,
101 pub(super) layout: Option<BottomSheetLayout>,
102 height: Pixels,
103 motion: RetargetTransition,
104 pub(super) pressed: Option<Pixels>,
105 drag: Option<SheetDrag>,
106}
107
108impl BottomSheetState {
109 pub fn new(initial: BottomSheetValue, cx: &mut Context<Self>) -> Self {
111 Self {
112 dialog: cx.new(DialogState::new),
113 current: initial,
114 target: initial,
115 enabled: BottomSheetValue::ORDERED.to_vec(),
116 confirm: None,
117 layout: None,
118 height: px(0.),
119 motion: RetargetTransition::settled(0.),
120 pressed: None,
121 drag: None,
122 }
123 }
124
125 pub fn enabled_values(mut self, values: impl IntoIterator<Item = BottomSheetValue>) -> Self {
127 let values = values.into_iter().collect::<Vec<_>>();
128 self.enabled = BottomSheetValue::ORDERED
129 .into_iter()
130 .filter(|value| values.contains(value))
131 .collect();
132 if self.enabled.is_empty() {
133 self.enabled.push(self.current);
134 }
135 if !self.enabled.contains(&self.current) {
136 self.current = self.enabled[0];
137 self.target = self.current;
138 }
139 self
140 }
141
142 pub fn confirm_value_change(
144 mut self,
145 confirm: impl Fn(BottomSheetValue) -> bool + 'static,
146 ) -> Self {
147 self.confirm = Some(Rc::new(confirm));
148 self
149 }
150
151 pub fn available_values(&self) -> &[BottomSheetValue] {
153 &self.enabled
154 }
155
156 pub fn current_value(&self) -> BottomSheetValue {
158 self.current
159 }
160
161 pub fn target_value(&self) -> BottomSheetValue {
163 self.target
164 }
165
166 pub fn is_animating(&self) -> bool {
168 self.motion.is_animating()
169 }
170
171 pub fn visible_height(&self) -> Pixels {
173 self.height
174 }
175
176 pub fn offset(&self) -> Pixels {
178 self.layout
179 .map_or(px(0.), |layout| layout.expanded - self.height)
180 }
181
182 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 {
195 self.animate_to(BottomSheetValue::Expanded, window, cx)
196 }
197
198 pub fn partial_expand(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
200 self.animate_to(BottomSheetValue::PartiallyExpanded, window, cx)
201 }
202
203 pub fn hide(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
205 self.animate_to(BottomSheetValue::Hidden, window, cx)
206 }
207
208 pub fn animate_to(
210 &mut self,
211 value: BottomSheetValue,
212 window: &mut Window,
213 cx: &mut Context<Self>,
214 ) -> bool {
215 self.request(value, true, true, window, cx)
216 }
217
218 pub fn snap_to(
220 &mut self,
221 value: BottomSheetValue,
222 window: &mut Window,
223 cx: &mut Context<Self>,
224 ) -> bool {
225 self.request(value, false, true, window, cx)
226 }
227
228 pub(in crate::overlay) fn accept_user_close(
229 &mut self,
230 window: &mut Window,
231 cx: &mut Context<Self>,
232 ) -> bool {
233 (self.target != BottomSheetValue::Hidden || self.drag.is_some())
234 && self.request(BottomSheetValue::Hidden, true, false, window, cx)
235 }
236
237 fn request(
238 &mut self,
239 value: BottomSheetValue,
240 animate: bool,
241 synchronize_focus: bool,
242 window: &mut Window,
243 cx: &mut Context<Self>,
244 ) -> bool {
245 if !self.enabled.contains(&value)
246 || (value != self.target
247 && self.confirm.as_ref().is_some_and(|confirm| !confirm(value)))
248 {
249 return false;
250 }
251 let had_drag = self.release_drag(window, cx);
252 let prev_target = self.target;
253 let prev_current = self.current;
254 let prev_height = self.height;
255 let was_animating = self.motion.is_animating();
256 self.target = value;
257 let mut dialog_changed = false;
258 if synchronize_focus
259 && self
260 .layout
261 .is_some_and(|layout| layout.mode == SheetMode::Modal)
262 {
263 let want_open = value != BottomSheetValue::Hidden;
264 if self.dialog.read(cx).is_open() != want_open {
265 dialog_changed = true;
266 self.dialog.update(cx, |dialog, cx| match value {
267 BottomSheetValue::Hidden => dialog.close(window, cx),
268 _ => dialog.open(window, cx),
269 });
270 }
271 }
272 self.move_to_target(animate, cx);
273 let changed = had_drag
274 || dialog_changed
275 || prev_target != self.target
276 || prev_current != self.current
277 || prev_height != self.height
278 || was_animating
279 || self.motion.is_animating();
280 if changed {
281 cx.notify();
282 window.refresh();
283 }
284 true
285 }
286
287 pub(super) fn move_to_target(&mut self, animate: bool, cx: &App) {
288 let target = self
289 .layout
290 .map_or(px(0.), |layout| layout.height(self.target));
291 let now = cx.background_executor().now();
292 if !animate || cx.reduce_motion() {
293 self.height = target;
294 self.current = self.target;
295 self.motion.snap_to(f32::from(target));
296 } else {
297 self.motion
298 .animate_to(f32::from(target), SETTLE, Easing::EaseOut, now, false);
299 self.height = px(self.motion.value());
300 if !self.motion.is_animating() {
301 self.current = self.target;
302 }
303 }
304 }
305
306 pub(in crate::overlay) fn configure(
307 &mut self,
308 layout: BottomSheetLayout,
309 window: &mut Window,
310 cx: &mut Context<Self>,
311 ) {
312 let before = (
313 self.height,
314 self.current,
315 self.target,
316 self.is_animating(),
317 self.offset(),
318 );
319 if self.layout != Some(layout) {
320 let old = self.layout.replace(layout);
321 self.pressed = None;
322 if self.drag.is_some() {
323 self.release_drag(window, cx);
324 self.target = self.current;
325 }
326 let moving = self.motion.is_animating();
327 self.height = if moving {
328 self.height.clamp(px(0.), layout.expanded)
329 } else {
330 layout.height(self.current)
331 };
332 self.motion.snap_to(f32::from(self.height));
333 self.move_to_target(moving, cx);
334 if old.is_none_or(|old| old.mode != layout.mode) {
335 let dialog = self.dialog.downgrade();
336 let want_open =
337 layout.mode == SheetMode::Modal && self.target != BottomSheetValue::Hidden;
338 window.defer(cx, move |window, cx| {
340 let _ = dialog.update(cx, |dialog, cx| {
341 if want_open {
342 dialog.open(window, cx);
343 } else {
344 dialog.close(window, cx);
345 }
346 });
347 });
348 }
349 }
350 if self.motion.is_animating() {
351 let now = cx.background_executor().now();
352 let (height, running) = self.motion.sample(now, cx.reduce_motion());
353 self.height = px(height);
354 if running {
355 if window.is_visible() {
356 window.request_animation_frame();
357 }
358 } else {
359 self.current = self.target;
360 }
361 }
362 let after = (
363 self.height,
364 self.current,
365 self.target,
366 self.is_animating(),
367 self.offset(),
368 );
369 if before != after {
370 let state = cx.weak_entity();
372 window.defer(cx, move |_, cx| {
373 let _ = state.update(cx, |_, cx| cx.notify());
374 });
375 }
376 }
377
378 fn release_drag(&mut self, window: &mut Window, cx: &mut App) -> bool {
379 self.pressed = None;
380 if let Some(drag) = self.drag.take() {
381 drag.capture.cancel(window, cx);
382 true
383 } else {
384 false
385 }
386 }
387
388 fn cancel_drag(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
389 if self.release_drag(window, cx) {
390 self.target = self.current;
391 self.move_to_target(true, cx);
392 cx.notify();
393 window.refresh();
394 true
395 } else {
396 false
397 }
398 }
399
400 pub(super) fn begin_drag(&mut self, y: Pixels, window: &mut Window, cx: &mut Context<Self>) {
401 if !f32::from(y).is_finite() || self.layout.is_none_or(|layout| !layout.drag_enabled) {
402 return;
403 }
404 let origin = self.pressed.take().unwrap_or(y);
405 if self.drag.is_some() || self.enabled.len() < 2 {
406 return;
407 }
408 let was_animating = self.motion.is_animating();
409 self.motion.snap_to(f32::from(self.height));
410 if was_animating
411 && self.current == BottomSheetValue::Hidden
412 && self.target != BottomSheetValue::Hidden
413 {
414 self.current = self.target;
415 }
416 self.target = self.current;
417 let state = cx.weak_entity();
418 let capture = DragCapture::watch(window, cx, {
419 let state = state.clone();
420 move |window, cx| {
421 let _ = state.update(cx, |state, cx| state.cancel_drag(window, cx));
422 }
423 });
424 let window_id = window.window_handle().window_id();
425 let escape = cx.intercept_keystrokes(move |event, window, cx| {
426 if event.keystroke.key == "escape"
427 && window.window_handle().window_id() == window_id
428 && state
429 .update(cx, |state, cx| state.cancel_drag(window, cx))
430 .unwrap_or(false)
431 {
432 cx.stop_propagation();
433 }
434 });
435 let activation = cx.observe_window_activation(window, |state, window, cx| {
436 if !window.is_window_active() {
437 state.cancel_drag(window, cx);
438 }
439 });
440 self.drag = Some(SheetDrag {
441 origin,
442 start_height: self.height,
443 last_position: origin,
444 last_motion: cx.background_executor().now(),
445 velocity: px(0.),
446 capture,
447 _escape: escape,
448 _activation: activation,
449 });
450 }
451
452 pub(super) fn drag_to(&mut self, y: Pixels, cx: &mut Context<Self>) -> Option<bool> {
453 if !f32::from(y).is_finite() {
454 return None;
455 }
456 let (Some(drag), Some(layout)) = (&mut self.drag, self.layout) else {
457 return None;
458 };
459 let now = cx.background_executor().now();
460 if y != drag.last_position {
461 let elapsed = now
462 .saturating_duration_since(drag.last_motion)
463 .as_secs_f32();
464 if elapsed > 0. {
465 let velocity = (drag.last_position - y) / elapsed;
466 if f32::from(velocity).is_finite() {
467 drag.velocity = velocity;
468 }
469 }
470 drag.last_position = y;
471 drag.last_motion = now;
472 }
473 let low = layout.height(self.enabled[0]);
474 let high = layout.height(*self.enabled.last().expect("an available stop"));
475 let next = (drag.start_height + drag.origin - y).clamp(low, high);
476 let changed = self.height != next || self.motion.is_animating();
477 self.height = next;
478 self.motion.snap_to(f32::from(self.height));
479 if changed {
480 cx.notify();
481 }
482 Some(changed)
483 }
484
485 pub(super) fn finish_drag(
486 &mut self,
487 position: Pixels,
488 thresholds: BottomSheetThresholds,
489 window: &mut Window,
490 cx: &mut Context<Self>,
491 ) -> Option<BottomSheetValue> {
492 self.drag_to(position, cx)?;
493 let drag = self.drag.as_ref().expect("the active drag");
494 let velocity = if cx
495 .background_executor()
496 .now()
497 .saturating_duration_since(drag.last_motion)
498 <= VELOCITY_AGE
499 {
500 drag.velocity
501 } else {
502 px(0.)
503 };
504 let target = self.settle_target(velocity, thresholds);
505 self.release_drag(window, cx);
506 Some(target)
507 }
508
509 fn settle_target(
510 &self,
511 velocity: Pixels,
512 thresholds: BottomSheetThresholds,
513 ) -> BottomSheetValue {
514 let layout = self.layout.expect("a laid out drag");
515 let start = layout.height(self.current);
516 let displacement = self.height - start;
517 let fling = velocity != px(0.) && velocity.abs() >= thresholds.velocity;
518 if !fling && displacement == px(0.) {
519 return self.current;
520 }
521 let positive = if fling {
522 velocity > px(0.)
523 } else {
524 displacement > px(0.)
525 };
526 let mut stops = self.enabled.iter().copied().filter(|value| {
527 let height = layout.height(*value);
528 if positive {
529 height > start
530 } else {
531 height < start
532 }
533 });
534 if fling {
535 return if positive {
536 stops.next()
537 } else {
538 stops.next_back()
539 }
540 .unwrap_or(self.current);
541 }
542 let mut crossed = stops.filter(|value| {
543 let distance = (layout.height(*value) - start).abs();
544 displacement.abs() >= thresholds.position.min(distance / 2.)
545 });
546 if positive {
547 crossed.next_back()
548 } else {
549 crossed.next()
550 }
551 .unwrap_or(self.current)
552 }
553
554 pub(super) fn destination(&self, key: Option<&str>) -> Option<BottomSheetValue> {
555 let current = self
556 .enabled
557 .iter()
558 .position(|value| *value == self.target)?;
559 match key {
560 None => self.enabled.get((current + 1) % self.enabled.len()),
561 Some("up") => self.enabled.get(current + 1),
562 Some("down") => current
563 .checked_sub(1)
564 .and_then(|index| self.enabled.get(index)),
565 Some("home") => self.enabled.first(),
566 Some("end") => self.enabled.last(),
567 _ => None,
568 }
569 .copied()
570 .filter(|value| *value != self.target)
571 }
572}
573
574#[cfg(test)]
575mod tests {
576 use super::*;
577
578 #[test]
579 fn thresholds_sanitize_non_finite_and_negative_values() {
580 let defaults = BottomSheetThresholds::default();
581 assert_eq!(
582 BottomSheetThresholds {
583 position: px(f32::NAN),
584 velocity: px(-10.),
585 }
586 .normalized(),
587 defaults
588 );
589 assert_eq!(
590 BottomSheetThresholds {
591 position: px(24.),
592 velocity: px(0.),
593 }
594 .normalized(),
595 BottomSheetThresholds {
596 position: px(24.),
597 velocity: px(0.),
598 }
599 );
600 }
601}