1use std::{cell::Cell, rc::Rc, time::Duration};
2
3use gpui::{
4 AccessibleAction, AnyElement, App, BackgroundExecutor, Context, Div, ElementId, Entity,
5 FocusHandle, Hsla, InteractiveElement, IntoElement, MouseButton, ParentElement, RenderOnce,
6 Role, ScrollEvent, SharedString, Stateful, StatefulInteractiveElement, Styled, Task,
7 TouchPhase, Window,
8 accesskit::{ActionData, Orientation},
9 canvas, div,
10 prelude::FluentBuilder as _,
11 px,
12};
13use gpui_base::TestSupportExt;
14use gpui_material_components::Text;
15use gpui_material_foundation::{
16 InteractionFeedback, InteractionSource, InteractionState, InteractionTracker, Shape, animate,
17 color, current_material_theme,
18};
19use gpui_material_theme::{
20 ColorRole, CornerRole, CornerShape, MaterialTheme, MotionKind, MotionSpec, MotionSpeed,
21 TypeRole,
22};
23
24const HEIGHT: f32 = 200.;
25const ROW_HEIGHT: f32 = HEIGHT / 3.;
26const PRECISE_SCROLL_SETTLE: Duration = Duration::from_millis(120);
27const ANIMATED_ROWS: usize = 3;
29
30struct SettleTimer {
31 _task: Task<()>,
32 bump: Box<dyn Fn(&BackgroundExecutor)>,
33}
34
35pub struct ScrollFieldState {
37 item_count: usize,
38 position: Position,
39 target: usize,
40 motion: Option<Motion>,
41 gesture_start: Option<usize>,
42 settle: Option<SettleTimer>,
43 focus: FocusHandle,
44}
45
46#[derive(Clone, Copy, PartialEq)]
47struct Position {
48 index: usize,
49 fraction: f32,
50}
51
52impl Position {
53 fn at(index: usize) -> Self {
54 Self {
55 index,
56 fraction: 0.,
57 }
58 }
59
60 fn shift(self, rows: f32, item_count: usize) -> Self {
61 let offset = self.fraction + rows;
62 let shift = offset.round();
63 Self {
64 index: wrap(self.index, shift as isize, item_count),
65 fraction: offset - shift,
66 }
67 }
68
69 fn offset_from(self, target: usize) -> f32 {
70 let distance = self.index.abs_diff(target).min(ANIMATED_ROWS) as f32;
71 self.fraction
72 + if self.index < target {
73 -distance
74 } else {
75 distance
76 }
77 }
78}
79
80fn wrap(index: usize, rows: isize, count: usize) -> usize {
81 let step = rows.unsigned_abs() % count;
82 if rows < 0 {
83 index
84 .checked_sub(step)
85 .unwrap_or_else(|| count - (step - index))
86 } else if step >= count - index {
87 step - (count - index)
88 } else {
89 index + step
90 }
91}
92
93#[derive(Clone, Copy)]
94struct Motion {
95 start: f32,
96 restart: bool,
97 origin: ScrollOrigin,
98}
99
100#[derive(Clone, Copy, PartialEq, Eq)]
101enum ScrollOrigin {
102 Application,
103 Interaction,
104}
105
106impl ScrollFieldState {
107 pub fn new(item_count: usize, index: usize, cx: &mut Context<Self>) -> Self {
109 let index = index.min(item_count.saturating_sub(1));
110 Self {
111 item_count,
112 position: Position::at(index),
113 target: index,
114 motion: None,
115 gesture_start: None,
116 settle: None,
117 focus: cx.focus_handle(),
118 }
119 }
120
121 pub fn item_count(&self) -> usize {
123 self.item_count
124 }
125
126 pub fn set_item_count(&mut self, count: usize, cx: &mut Context<Self>) {
128 if self.item_count != count {
129 self.item_count = count;
130 self.scroll_to_option(self.target, cx);
131 }
132 }
133
134 pub fn selected_option(&self) -> Option<usize> {
136 (self.item_count > 0).then_some(self.position.index)
137 }
138
139 pub fn target_option(&self) -> Option<usize> {
141 (self.item_count > 0).then_some(self.target)
142 }
143
144 pub fn is_scroll_in_progress(&self) -> bool {
146 self.motion.is_some() || self.gesture_start.is_some()
147 }
148
149 pub fn focus_handle(&self) -> &FocusHandle {
151 &self.focus
152 }
153
154 pub fn scroll_to_option(&mut self, index: usize, cx: &mut Context<Self>) {
156 let target = index.min(self.item_count.saturating_sub(1));
157 let position = Position::at(target);
158 if self.target == target
159 && self.position == position
160 && self.gesture_start.is_none()
161 && self.settle.is_none()
162 && self.motion.is_none()
163 {
164 return;
165 }
166 self.target = target;
167 self.gesture_start = None;
168 self.settle = None;
169 self.motion = None;
170 self.position = position;
171 cx.notify();
172 }
173
174 pub fn animate_scroll_to_option(&mut self, index: usize, cx: &mut Context<Self>) {
176 self.animate_to(index, ScrollOrigin::Application, cx);
177 }
178
179 fn animate_to(&mut self, index: usize, origin: ScrollOrigin, cx: &mut Context<Self>) {
180 let index = index.min(self.item_count.saturating_sub(1));
181 if self.item_count > 0 && (self.target != index || self.gesture_start.is_some()) {
182 self.snap(index, self.position.offset_from(index), origin, cx);
183 }
184 }
185
186 fn snap(&mut self, index: usize, start: f32, origin: ScrollOrigin, cx: &mut Context<Self>) {
187 if start == 0. || cx.reduce_motion() {
188 self.scroll_to_option(index, cx);
189 } else {
190 self.target = index;
191 self.gesture_start = None;
192 self.settle = None;
193 self.motion = Some(Motion {
194 start,
195 restart: true,
196 origin,
197 });
198 cx.notify();
199 }
200 }
201
202 fn sample(&mut self, offset: f32, cx: &mut Context<Self>) {
203 let position = Position::at(self.target).shift(offset, self.item_count);
204 let changed = self.position.index != position.index || offset == 0.;
205 self.position = position;
206 self.motion = self.motion.filter(|_| offset != 0.).map(|mut motion| {
207 motion.restart = false;
208 motion
209 });
210 if changed {
211 cx.notify();
212 }
213 }
214
215 fn step(&mut self, delta: isize, cx: &mut Context<Self>) {
216 if self.item_count < 2 {
217 return;
218 }
219 let index = wrap(self.target, delta, self.item_count);
220 let (origin, destination) = if delta > 0 {
221 (self.position.index, index)
222 } else {
223 (index, self.position.index)
224 };
225 let distance = if destination >= origin {
226 destination - origin
227 } else {
228 self.item_count - (origin - destination)
229 };
230 let start =
231 self.position.fraction - delta.signum() as f32 * distance.min(ANIMATED_ROWS) as f32;
232 self.snap(index, start, ScrollOrigin::Interaction, cx);
233 }
234
235 fn select_row(&mut self, row: isize, cx: &mut Context<Self>) {
236 if self.item_count > 0 {
237 let index = wrap(self.position.index, row, self.item_count);
238 self.snap(
239 index,
240 self.position.fraction - row as f32,
241 ScrollOrigin::Interaction,
242 cx,
243 );
244 }
245 }
246
247 fn scroll(&mut self, event: &ScrollEvent, window: &mut Window, cx: &mut Context<Self>) -> bool {
248 if self.item_count < 2 {
249 return false;
250 }
251 let delta = event.delta.pixel_delta(px(ROW_HEIGHT));
252 let x = f32::from(delta.x);
253 let y = f32::from(delta.y);
254 let vertical = y.is_finite() && x.abs() <= y.abs() && y != 0.;
255 if !event.delta.precise() {
256 if vertical {
257 self.step(if y < 0. { 1 } else { -1 }, cx);
258 }
259 return vertical;
260 }
261 if event.touch_phase == TouchPhase::Cancelled {
262 return self.finish_gesture(true, cx);
263 }
264 if vertical {
265 self.gesture_start.get_or_insert(self.position.index);
266 self.motion = None;
267 self.position = self.position.shift(-y / ROW_HEIGHT, self.item_count);
268 self.target = self.position.index;
269 cx.notify();
270 }
271 if event.touch_phase == TouchPhase::Ended {
272 return self.finish_gesture(false, cx);
273 }
274 if vertical {
275 if let Some(settle) = &self.settle {
279 (settle.bump)(cx.background_executor());
280 } else {
281 let origin = cx.background_executor().now();
282 let last_offset = Rc::new(Cell::new(Duration::ZERO));
283 let bump_offset = last_offset.clone();
284 let bump = Box::new(move |executor: &BackgroundExecutor| {
285 bump_offset.set(executor.now().saturating_duration_since(origin));
286 });
287 let state = cx.weak_entity();
288 let task = window.spawn(cx, async move |cx| {
289 let mut wait = PRECISE_SCROLL_SETTLE;
290 loop {
291 let Ok(timer) = cx.update(|_, cx| cx.background_executor().timer(wait))
292 else {
293 return;
294 };
295 timer.await;
296 let next_wait = cx.update(|_, cx| {
297 let elapsed = cx
298 .background_executor()
299 .now()
300 .saturating_duration_since(origin);
301 let deadline = last_offset.get() + PRECISE_SCROLL_SETTLE;
302 if elapsed < deadline {
303 Some(deadline - elapsed)
304 } else {
305 let _ =
306 state.update(cx, |state, cx| state.finish_gesture(false, cx));
307 None
308 }
309 });
310 match next_wait {
311 Ok(Some(remaining)) => wait = remaining,
312 _ => return,
313 }
314 }
315 });
316 self.settle = Some(SettleTimer { _task: task, bump });
317 }
318 }
319 vertical
320 }
321
322 fn finish_gesture(&mut self, cancelled: bool, cx: &mut Context<Self>) -> bool {
323 let Some(start) = self.gesture_start else {
324 return false;
325 };
326 let index = if cancelled {
327 start
328 } else {
329 self.position.index
330 };
331 self.snap(
332 index,
333 self.position.offset_from(index),
334 ScrollOrigin::Interaction,
335 cx,
336 );
337 true
338 }
339
340 fn has_pending_interaction(&self) -> bool {
341 self.gesture_start.is_some()
342 || self
343 .motion
344 .is_some_and(|motion| motion.origin == ScrollOrigin::Interaction)
345 }
346}
347
348#[derive(Clone, Copy, Debug, Default, PartialEq)]
350pub struct ScrollFieldColors {
351 pub container: Option<Hsla>,
353 pub content: Option<Hsla>,
355 pub selected_content: Option<Hsla>,
357 pub disabled_container: Option<Hsla>,
359 pub disabled_content: Option<Hsla>,
361 pub disabled_selected_content: Option<Hsla>,
363}
364
365impl ScrollFieldColors {
366 fn resolve(self, enabled: bool, theme: &MaterialTheme) -> (Hsla, Hsla, Hsla) {
367 let container = color(theme.colors.color(ColorRole::SurfaceContainerLowest));
368 let selected = color(theme.colors.color(ColorRole::OnSurface));
369 if enabled {
370 (
371 self.container.unwrap_or(container),
372 self.content
373 .unwrap_or_else(|| color(theme.colors.color(ColorRole::Outline))),
374 self.selected_content.unwrap_or(selected),
375 )
376 } else {
377 (
378 self.disabled_container
379 .unwrap_or_else(|| container.opacity(0.38)),
380 self.disabled_content
381 .unwrap_or_else(|| selected.opacity(0.38)),
382 self.disabled_selected_content
383 .unwrap_or_else(|| selected.opacity(0.38)),
384 )
385 }
386 }
387}
388
389type ItemContent = Box<dyn Fn(usize, bool, bool) -> AnyElement>;
390type ValueDescription = Box<dyn Fn(usize) -> SharedString>;
391
392#[derive(IntoElement)]
395pub struct ScrollField {
396 id: ElementId,
397 name: SharedString,
398 state: Entity<ScrollFieldState>,
399 disabled: bool,
400 colors: ScrollFieldColors,
401 time_field_shape: Option<CornerShape>,
402 numeric_offset: usize,
403 source: Option<Entity<InteractionSource>>,
404 item: Option<ItemContent>,
405 description: Option<ValueDescription>,
406}
407
408impl ScrollField {
409 pub fn new(
411 id: impl Into<ElementId>,
412 name: impl Into<SharedString>,
413 state: &Entity<ScrollFieldState>,
414 ) -> Self {
415 Self {
416 id: id.into(),
417 name: name.into(),
418 state: state.clone(),
419 disabled: false,
420 colors: ScrollFieldColors::default(),
421 time_field_shape: None,
422 numeric_offset: 0,
423 source: None,
424 item: None,
425 description: None,
426 }
427 }
428
429 pub fn disabled(mut self, disabled: bool) -> Self {
431 self.disabled = disabled;
432 self
433 }
434
435 pub fn colors(mut self, colors: ScrollFieldColors) -> Self {
437 self.colors = colors;
438 self
439 }
440
441 pub(super) fn time_field(mut self, shape: Option<CornerShape>, numeric_offset: usize) -> Self {
442 self.time_field_shape = shape;
443 self.numeric_offset = numeric_offset;
444 self
445 }
446
447 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
449 self.source = Some(source.clone());
450 self
451 }
452
453 pub fn item_content<E: IntoElement>(
455 mut self,
456 item: impl Fn(usize, bool, bool) -> E + 'static,
457 ) -> Self {
458 self.item = Some(Box::new(move |index, selected, enabled| {
459 item(index, selected, enabled).into_any_element()
460 }));
461 self
462 }
463
464 pub fn value_description<S: Into<SharedString>>(
466 mut self,
467 description: impl Fn(usize) -> S + 'static,
468 ) -> Self {
469 self.description = Some(Box::new(move |index| description(index).into()));
470 self
471 }
472}
473
474impl RenderOnce for ScrollField {
475 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
476 let theme = current_material_theme(window, cx);
477 let corner = self
478 .time_field_shape
479 .unwrap_or_else(|| CornerRole::Large.shape());
480 let direction = theme.layout.direction;
481 let [tl, tr, br, bl] = corner.radii(HEIGHT, HEIGHT, direction).map(px);
482 let ring = color(theme.colors.color(ColorRole::Secondary));
483 let motion_spec =
484 theme
485 .motion
486 .spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion());
487 if self.disabled && self.state.read(cx).has_pending_interaction() {
488 self.state
489 .update(cx, |state, cx| state.scroll_to_option(state.target, cx));
490 }
491 let motion = self.state.read(cx).motion;
492 if let Some(motion) = motion {
493 let key = (self.id.clone(), "scroll-position");
494 if motion.restart {
495 animate(key.clone(), motion.start, MotionSpec::Instant, window, cx);
496 }
497 let offset = animate(key, 0., motion_spec, window, cx);
498 self.state.update(cx, |state, cx| state.sample(offset, cx));
499 }
500 let state = self.state.read(cx);
501 let count = state.item_count;
502 let position = state.position;
503 let target = state.target;
504 let focus = state.focus.clone();
505 let enabled = !self.disabled && count > 0;
506 let (container, content, selected_content) = self.colors.resolve(enabled, &theme);
507 let feedback = window
508 .use_keyed_state((self.id.clone(), "scroll-field-feedback"), cx, |_, _| {
509 Rc::new(Cell::new(InteractionState::default()))
510 })
511 .read(cx)
512 .clone();
513 let input = Input {
514 tracker: self
515 .source
516 .as_ref()
517 .map(|source| InteractionSource::track(source, &self.id, window, cx)),
518 state: self.state,
519 feedback,
520 numeric_offset: self.numeric_offset,
521 };
522 let mut interaction = input.feedback.get();
523 if !enabled || !window.is_window_active() {
524 interaction = InteractionState::default();
525 }
526 interaction.disabled = !enabled;
527 input.update_feedback(interaction, window, cx);
528 let feedback = InteractionFeedback::new(input.feedback.get(), selected_content, ring);
529 let label = (count > 0).then(|| {
530 self.description
531 .as_ref()
532 .map_or_else(|| target.to_string().into(), |describe| describe(target))
533 });
534 let rows = (-2_isize..=2)
535 .filter(|row| count > 1 || (count == 1 && *row == 0))
536 .map(|row| {
537 let index = wrap(position.index, row, count);
538 let selected = row == 0;
539 let visual = self.item.as_ref().map_or_else(
540 || {
541 Text::new(super::format_two_digits(index))
542 .role(if selected {
543 TypeRole::DisplayLarge
544 } else {
545 TypeRole::DisplayMedium
546 })
547 .emphasized(selected)
548 .into_any_element()
549 },
550 |item| item(index, selected, enabled),
551 );
552 let input = input.state.clone();
553 div()
554 .absolute()
555 .top(px((1. + row as f32 - position.fraction) * ROW_HEIGHT))
556 .h(px(ROW_HEIGHT))
557 .w_full()
558 .flex()
559 .items_center()
560 .justify_center()
561 .text_color(if selected { selected_content } else { content })
562 .id(("scroll-field-row", (row + 2) as usize))
563 .role(Role::Group)
564 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
565 .when(enabled, |row_element| {
566 row_element.on_click(move |_, window, cx| {
567 input.update(cx, |state, cx| {
568 state.focus.focus(window, cx);
569 state.select_row(row, cx);
570 });
571 })
572 })
573 .child(visual)
574 .test_support()
575 });
576 let field = div()
577 .id(self.id)
578 .relative()
579 .w_full()
580 .min_w_0()
581 .h(px(HEIGHT))
582 .flex_none()
583 .overflow_hidden()
584 .rounded_tl(tl)
585 .rounded_tr(tr)
586 .rounded_br(br)
587 .rounded_bl(bl)
588 .bg(container)
589 .role(Role::Slider)
590 .aria_label(self.name)
591 .aria_orientation(Orientation::Vertical)
592 .when_some(label, |field, label| {
593 field
594 .aria_value(label)
595 .aria_numeric_value(target as f64 + self.numeric_offset as f64)
596 .aria_min_numeric_value(self.numeric_offset as f64)
597 .aria_max_numeric_value((count - 1) as f64 + self.numeric_offset as f64)
598 .aria_numeric_value_step(1.)
599 })
600 .when(!enabled, |field| {
601 field.a11y_synthetic_children(|tree| tree.parent_node().set_disabled())
602 })
603 .children(rows)
604 .child(
605 canvas(
606 |_, _, _| (),
607 move |bounds, _, window, cx| {
608 if let Some(shape) = Shape::rounded(bounds, corner, direction) {
609 feedback.paint(
610 &shape,
611 None,
612 cx.background_executor().now(),
613 cx.reduce_motion(),
614 window,
615 );
616 }
617 },
618 )
619 .absolute()
620 .inset_0(),
621 );
622 field
623 .when(enabled, |field| input.bind(field))
624 .test_support()
625 .when(enabled || focus.is_focused(window), |field| {
626 field.track_focus(&focus.tab_stop(enabled))
627 })
628 }
629}
630
631#[derive(Clone)]
632struct Input {
633 state: Entity<ScrollFieldState>,
634 feedback: Rc<Cell<InteractionState>>,
635 numeric_offset: usize,
636 tracker: Option<InteractionTracker>,
637}
638
639impl Input {
640 fn update_feedback(&self, mut feedback: InteractionState, window: &mut Window, cx: &mut App) {
641 let state = self.state.read(cx);
642 feedback.focus_visible = !feedback.disabled
643 && state.focus.is_focused(window)
644 && window.last_input_was_keyboard();
645 feedback.dragged = !feedback.disabled && state.gesture_start.is_some();
646 if self.feedback.replace(feedback) != feedback {
647 window.refresh();
648 }
649 if let Some(tracker) = &self.tracker {
650 tracker.record(feedback, cx);
651 }
652 }
653
654 fn bind(&self, field: Stateful<Div>) -> Stateful<Div> {
655 let scroll = self.clone();
656 let hover = self.clone();
657 let press = self.clone();
658 let release = self.clone();
659 let release_out = self.clone();
660 let keyboard = self.state.clone();
661 let increment = self.state.clone();
662 let decrement = self.state.clone();
663 let set_value = self.state.clone();
664 let numeric_offset = self.numeric_offset as f64;
665 field
666 .on_scroll(move |event, window, cx| {
667 if scroll
668 .state
669 .update(cx, |state, cx| state.scroll(event, window, cx))
670 {
671 scroll.update_feedback(scroll.feedback.get(), window, cx);
672 cx.stop_propagation();
673 }
674 })
675 .on_hover(move |hovered, window, cx| {
676 let mut feedback = hover.feedback.get();
677 feedback.hovered = *hovered;
678 hover.update_feedback(feedback, window, cx);
679 })
680 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
681 press.pointer(true, window, cx)
682 })
683 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
684 release.pointer(false, window, cx)
685 })
686 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
687 release_out.pointer(false, window, cx)
688 })
689 .on_key_down(move |event, _, cx| {
690 match event.keystroke.key.as_str() {
691 "up" => keyboard.update(cx, |state, cx| state.step(-1, cx)),
692 "down" => keyboard.update(cx, |state, cx| state.step(1, cx)),
693 "home" => keyboard.update(cx, |state, cx| {
694 state.animate_to(0, ScrollOrigin::Interaction, cx)
695 }),
696 "end" => keyboard.update(cx, |state, cx| {
697 state.animate_to(
698 state.item_count.saturating_sub(1),
699 ScrollOrigin::Interaction,
700 cx,
701 )
702 }),
703 _ => return,
704 }
705 cx.stop_propagation();
706 })
707 .on_a11y_action(AccessibleAction::Increment, move |_, _, cx| {
708 increment.update(cx, |state, cx| state.step(1, cx))
709 })
710 .on_a11y_action(AccessibleAction::Decrement, move |_, _, cx| {
711 decrement.update(cx, |state, cx| state.step(-1, cx))
712 })
713 .on_a11y_action(AccessibleAction::SetValue, move |data, _, cx| {
714 let value = match data {
715 Some(ActionData::NumericValue(value)) => Some(*value),
716 Some(ActionData::Value(value)) => value.trim().parse::<f64>().ok(),
717 _ => None,
718 };
719 if let Some(value) = value.filter(|value| value.is_finite()) {
720 set_value.update(cx, |state, cx| {
721 state.animate_to(
722 (value - numeric_offset).round() as usize,
723 ScrollOrigin::Interaction,
724 cx,
725 )
726 });
727 }
728 })
729 }
730
731 fn pointer(&self, pressed: bool, window: &mut Window, cx: &mut App) {
732 let mut feedback = self.feedback.get();
733 feedback.pressed = pressed;
734 self.update_feedback(feedback, window, cx);
735 }
736}