Skip to main content

fc_ui/capabilities/scroll/
scroll_container.rs

1//! Scroll containers, lists, and physics-backed scrolling.
2
3use crate::capabilities::layout::{Align, VStack};
4use crate::capabilities::motion::animations::{easings, lerp_f32};
5use crate::capabilities::motion::scroll_physics::ScrollPhysics;
6use crate::capabilities::scroll::scrollbar::{Scrollbar, ScrollbarAxis, ScrollbarState};
7use gpui::*;
8use std::cell::RefCell;
9use std::panic::Location;
10use std::rc::Rc;
11use std::sync::atomic::AtomicUsize;
12
13static SCROLL_CONTAINER_COUNTER: AtomicUsize = AtomicUsize::new(0);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum ScrollDirection {
17    Vertical,
18    Horizontal,
19    Both,
20}
21
22const PIXELS_PER_LINE: f32 = 20.0;
23
24#[derive(Clone)]
25pub struct PhysicsScrollState {
26    inner: Rc<RefCell<PhysicsScrollInner>>,
27}
28
29struct PhysicsScrollInner {
30    physics_y: ScrollPhysics,
31    physics_x: ScrollPhysics,
32    scroll_target: Option<ScrollAnimTarget>,
33    animating: bool,
34    generation: u64,
35}
36
37struct ScrollAnimTarget {
38    start_y: f32,
39    end_y: f32,
40    start_x: f32,
41    end_x: f32,
42    progress: f32,
43    animate_y: bool,
44    animate_x: bool,
45}
46
47impl Default for PhysicsScrollState {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl PhysicsScrollState {
54    pub fn new() -> Self {
55        Self {
56            inner: Rc::new(RefCell::new(PhysicsScrollInner {
57                physics_y: ScrollPhysics::new(),
58                physics_x: ScrollPhysics::new(),
59                scroll_target: None,
60                animating: false,
61                generation: 0,
62            })),
63        }
64    }
65
66    pub fn with_deceleration(self, deceleration: f32) -> Self {
67        let mut inner = self.inner.borrow_mut();
68        inner.physics_y = inner.physics_y.clone().with_deceleration(deceleration);
69        inner.physics_x = inner.physics_x.clone().with_deceleration(deceleration);
70        drop(inner);
71        self
72    }
73
74    pub fn momentum(self, enabled: bool) -> Self {
75        let mut inner = self.inner.borrow_mut();
76        inner.physics_y = inner.physics_y.clone().momentum(enabled);
77        inner.physics_x = inner.physics_x.clone().momentum(enabled);
78        drop(inner);
79        self
80    }
81
82    pub fn overscroll(self, enabled: bool) -> Self {
83        let mut inner = self.inner.borrow_mut();
84        inner.physics_y = inner.physics_y.clone().overscroll(enabled);
85        inner.physics_x = inner.physics_x.clone().overscroll(enabled);
86        drop(inner);
87        self
88    }
89
90    pub fn scroll_to_y_animated(&self, target: f32, handle: &ScrollHandle, window: &Window) {
91        let mut inner = self.inner.borrow_mut();
92        let current = -f32::from(handle.offset().y);
93        inner.physics_y.set_position(current);
94        inner.physics_x.set_position(-f32::from(handle.offset().x));
95        inner.physics_y.stop();
96        inner.scroll_target = Some(ScrollAnimTarget {
97            start_y: current,
98            end_y: target,
99            start_x: 0.0,
100            end_x: 0.0,
101            progress: 0.0,
102            animate_y: true,
103            animate_x: false,
104        });
105        inner.animating = true;
106        inner.generation += 1;
107        let gen = inner.generation;
108        drop(inner);
109        drive_physics_frame(self.clone(), handle.clone(), gen, window);
110    }
111
112    pub fn scroll_to_x_animated(&self, target: f32, handle: &ScrollHandle, window: &Window) {
113        let mut inner = self.inner.borrow_mut();
114        let current = -f32::from(handle.offset().x);
115        inner.physics_y.set_position(-f32::from(handle.offset().y));
116        inner.physics_x.set_position(current);
117        inner.physics_x.stop();
118        inner.scroll_target = Some(ScrollAnimTarget {
119            start_y: 0.0,
120            end_y: 0.0,
121            start_x: current,
122            end_x: target,
123            progress: 0.0,
124            animate_y: false,
125            animate_x: true,
126        });
127        inner.animating = true;
128        inner.generation += 1;
129        let gen = inner.generation;
130        drop(inner);
131        drive_physics_frame(self.clone(), handle.clone(), gen, window);
132    }
133
134    pub fn handle_scroll_event(
135        &self,
136        handle: &ScrollHandle,
137        direction: ScrollDirection,
138        event: &ScrollWheelEvent,
139        window: &Window,
140    ) {
141        let (delta_x, delta_y) = match &event.delta {
142            ScrollDelta::Lines(d) => (d.x * PIXELS_PER_LINE, d.y * PIXELS_PER_LINE),
143            ScrollDelta::Pixels(d) => (f32::from(d.x), f32::from(d.y)),
144        };
145
146        let mut inner = self.inner.borrow_mut();
147        inner.scroll_target = None;
148        inner.generation += 1;
149        let gen = inner.generation;
150
151        let max_offset = handle.max_offset();
152        inner
153            .physics_y
154            .set_bounds(0.0, f32::from(max_offset.height).max(0.0));
155        inner
156            .physics_x
157            .set_bounds(0.0, f32::from(max_offset.width).max(0.0));
158
159        match direction {
160            ScrollDirection::Vertical => inner.physics_y.apply_delta(-delta_y),
161            ScrollDirection::Horizontal => inner.physics_x.apply_delta(-delta_x),
162            ScrollDirection::Both => {
163                inner.physics_y.apply_delta(-delta_y);
164                inner.physics_x.apply_delta(-delta_x);
165            }
166        }
167
168        let offset = handle.offset();
169        inner.physics_y.set_position(-f32::from(offset.y));
170        inner.physics_x.set_position(-f32::from(offset.x));
171
172        inner.animating = true;
173        drop(inner);
174
175        drive_physics_frame(self.clone(), handle.clone(), gen, window);
176    }
177
178    pub fn is_animating(&self) -> bool {
179        self.inner.borrow().animating
180    }
181
182    pub fn stop(&self) {
183        let mut inner = self.inner.borrow_mut();
184        inner.physics_y.stop();
185        inner.physics_x.stop();
186        inner.scroll_target = None;
187        inner.animating = false;
188    }
189}
190
191fn drive_physics_frame(
192    state: PhysicsScrollState,
193    handle: ScrollHandle,
194    generation: u64,
195    window: &Window,
196) {
197    let state_c = state.clone();
198    let handle_c = handle.clone();
199    window.on_next_frame(move |window, _cx| {
200        let mut inner = state_c.inner.borrow_mut();
201        if inner.generation != generation || !inner.animating {
202            return;
203        }
204
205        let dt = 1.0 / 60.0;
206        let active;
207
208        let target_result = if let Some(ref mut target) = inner.scroll_target {
209            target.progress = (target.progress + dt * 3.33).min(1.0);
210            let t = easings::ease_out_cubic(target.progress);
211            let y_pos = if target.animate_y {
212                Some(lerp_f32(target.start_y, target.end_y, t))
213            } else {
214                None
215            };
216            let x_pos = if target.animate_x {
217                Some(lerp_f32(target.start_x, target.end_x, t))
218            } else {
219                None
220            };
221            let done = target.progress >= 1.0;
222            Some((y_pos, x_pos, done))
223        } else {
224            None
225        };
226
227        if let Some((y_pos, x_pos, done)) = target_result {
228            if let Some(y) = y_pos {
229                inner.physics_y.set_position(y);
230            }
231            if let Some(x) = x_pos {
232                inner.physics_x.set_position(x);
233            }
234            if done {
235                inner.scroll_target = None;
236                active = false;
237            } else {
238                active = true;
239            }
240        } else {
241            active = inner.physics_y.tick(dt) | inner.physics_x.tick(dt);
242        }
243
244        let mut offset = handle_c.offset();
245        let max_offset = handle_c.max_offset();
246        let y_managed = inner.physics_y.is_moving()
247            || inner.physics_y.is_overscrolled()
248            || inner.scroll_target.as_ref().is_some_and(|t| t.animate_y);
249        let x_managed = inner.physics_x.is_moving()
250            || inner.physics_x.is_overscrolled()
251            || inner.scroll_target.as_ref().is_some_and(|t| t.animate_x);
252
253        // A live overshoot is the bounce animation: physics pulls it back into
254        // range. Anything else must settle inside the current scroll range so
255        // the handle cannot drift past it.
256        if y_managed {
257            let position = inner.physics_y.position();
258            offset.y = if inner.physics_y.is_overscrolled() {
259                px(-position)
260            } else {
261                px(-position).clamp(-max_offset.height, px(0.))
262            };
263        }
264        if x_managed {
265            let position = inner.physics_x.position();
266            offset.x = if inner.physics_x.is_overscrolled() {
267                px(-position)
268            } else {
269                px(-position).clamp(-max_offset.width, px(0.))
270            };
271        }
272        handle_c.set_offset(offset);
273
274        if active {
275            drop(inner);
276            window.refresh();
277            drive_physics_frame(state_c.clone(), handle_c.clone(), generation, window);
278        } else {
279            inner.animating = false;
280        }
281    });
282}
283
284pub struct ScrollContainer {
285    base: Div,
286    direction: ScrollDirection,
287    scroll_handle: Option<ScrollHandle>,
288    auto_size: bool,
289    smooth_scroll: bool,
290    custom_id: Option<ElementId>,
291    auto_id: ElementId,
292    show_scrollbar: bool,
293    horizontal_top: bool,
294    scrollbar_state: ScrollbarState,
295    physics_state: Option<PhysicsScrollState>,
296}
297
298impl ScrollContainer {
299    #[track_caller]
300    pub fn new(direction: ScrollDirection) -> Self {
301        let location = Location::caller();
302        let auto_id = ElementId::Name(
303            format!(
304                "scroll-container:{}:{}:{}:{}",
305                location.file(),
306                location.line(),
307                location.column(),
308                SCROLL_CONTAINER_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
309            )
310            .into(),
311        );
312
313        Self {
314            base: div(),
315            direction,
316            scroll_handle: None,
317            auto_size: false,
318            smooth_scroll: true,
319            custom_id: None,
320            auto_id,
321            show_scrollbar: false,
322            horizontal_top: false,
323            scrollbar_state: ScrollbarState::default(),
324            physics_state: None,
325        }
326    }
327
328    #[track_caller]
329    pub fn vertical() -> Self {
330        Self::new(ScrollDirection::Vertical)
331    }
332
333    #[track_caller]
334    pub fn horizontal() -> Self {
335        Self::new(ScrollDirection::Horizontal)
336    }
337
338    #[track_caller]
339    pub fn both() -> Self {
340        Self::new(ScrollDirection::Both)
341    }
342
343    pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
344        self.scroll_handle = Some(handle.clone());
345        self
346    }
347
348    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
349        self.custom_id = Some(id.into());
350        self
351    }
352
353    #[deprecated(note = "no-op")]
354    pub fn no_auto_size(mut self) -> Self {
355        self.auto_size = false;
356        self
357    }
358
359    /// Smooth scrolling reduces vibrating effect during scroll by allowing concurrent scroll in both axes
360    pub fn smooth(mut self) -> Self {
361        self.smooth_scroll = true;
362        self
363    }
364
365    pub fn no_smooth(mut self) -> Self {
366        self.smooth_scroll = false;
367        self
368    }
369
370    pub fn flex_grow(mut self) -> Self {
371        self.base = self.base.flex_1();
372        self
373    }
374
375    pub fn with_scrollbar(mut self) -> Self {
376        self.show_scrollbar = true;
377        self
378    }
379
380    pub fn horizontal_bar_top(mut self) -> Self {
381        self.horizontal_top = true;
382        self
383    }
384
385    pub fn horizontal_bar_bottom(mut self) -> Self {
386        self.horizontal_top = false;
387        self
388    }
389
390    pub fn with_physics(mut self, state: &PhysicsScrollState) -> Self {
391        self.physics_state = Some(state.clone());
392        self
393    }
394
395    pub fn momentum(mut self, enabled: bool) -> Self {
396        let state = self
397            .physics_state
398            .get_or_insert_with(PhysicsScrollState::new);
399        {
400            let mut inner = state.inner.borrow_mut();
401            inner.physics_y = inner.physics_y.clone().momentum(enabled);
402            inner.physics_x = inner.physics_x.clone().momentum(enabled);
403        }
404        self
405    }
406
407    pub fn overscroll_bounce(mut self, enabled: bool) -> Self {
408        let state = self
409            .physics_state
410            .get_or_insert_with(PhysicsScrollState::new);
411        {
412            let mut inner = state.inner.borrow_mut();
413            inner.physics_y = inner.physics_y.clone().overscroll(enabled);
414            inner.physics_x = inner.physics_x.clone().overscroll(enabled);
415        }
416        self
417    }
418}
419
420impl ParentElement for ScrollContainer {
421    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
422        self.base.extend(elements);
423    }
424}
425
426impl Styled for ScrollContainer {
427    fn style(&mut self) -> &mut StyleRefinement {
428        self.base.style()
429    }
430}
431
432impl InteractiveElement for ScrollContainer {
433    fn interactivity(&mut self) -> &mut Interactivity {
434        self.base.interactivity()
435    }
436}
437
438impl StatefulInteractiveElement for ScrollContainer {}
439
440impl IntoElement for ScrollContainer {
441    type Element = Stateful<Div>;
442
443    fn into_element(self) -> Self::Element {
444        let id_to_use = self.custom_id.clone().unwrap_or(self.auto_id.clone());
445        let handle = self.scroll_handle.clone().unwrap_or_default();
446
447        if !self.show_scrollbar {
448            let mut scrollable = self.base.id(id_to_use);
449
450            if let Some(handle) = &self.scroll_handle {
451                scrollable = scrollable.track_scroll(handle);
452            }
453
454            scrollable = match self.direction {
455                ScrollDirection::Vertical => scrollable.overflow_y_scroll(),
456                ScrollDirection::Horizontal => scrollable.overflow_x_scroll(),
457                ScrollDirection::Both => scrollable.overflow_scroll(),
458            };
459
460            // With smooth scrolling disabled, GPUI's built-in wheel handling
461            // applies the delta directly, skipping the physics simulation.
462            if self.smooth_scroll {
463                if let Some(ref physics) = self.physics_state {
464                    let physics_c = physics.clone();
465                    let handle_c = handle.clone();
466                    let dir = self.direction;
467                    scrollable = scrollable.on_scroll_wheel(move |event, window, _cx| {
468                        physics_c.handle_scroll_event(&handle_c, dir, event, window);
469                    });
470                }
471            }
472
473            scrollable
474        } else {
475            let scrollbar_state = self.scrollbar_state.clone();
476            scrollbar_state.init_visible();
477
478            let axis = match self.direction {
479                ScrollDirection::Vertical => ScrollbarAxis::Vertical,
480                ScrollDirection::Horizontal => ScrollbarAxis::Horizontal,
481                ScrollDirection::Both => ScrollbarAxis::Both,
482            };
483            let mut scrollbar = Scrollbar::both(&scrollbar_state, &handle).axis(axis);
484            if self.horizontal_top {
485                scrollbar = scrollbar.horizontal_top();
486            }
487
488            let mut scrollable = self.base.id(id_to_use.clone()).track_scroll(&handle);
489
490            scrollable = match self.direction {
491                ScrollDirection::Vertical => scrollable.overflow_y_scroll(),
492                ScrollDirection::Horizontal => scrollable.overflow_x_scroll(),
493                ScrollDirection::Both => scrollable.overflow_scroll(),
494            };
495
496            scrollable = scrollable.relative().size_full();
497
498            // With smooth scrolling disabled, GPUI's built-in wheel handling
499            // applies the delta directly, skipping the physics simulation.
500            if self.smooth_scroll {
501                if let Some(ref physics) = self.physics_state {
502                    let physics_c = physics.clone();
503                    let handle_c = handle.clone();
504                    let dir = self.direction;
505                    scrollable = scrollable.on_scroll_wheel(move |event, window, _cx| {
506                        physics_c.handle_scroll_event(&handle_c, dir, event, window);
507                    });
508                }
509            }
510
511            let wrapper = div()
512                .id(ElementId::Name(format!("{}-wrapper", id_to_use).into()))
513                .relative()
514                .size_full()
515                .child(scrollable)
516                .child(scrollbar);
517
518            wrapper
519        }
520    }
521}
522
523pub struct ScrollList {
524    scroll_container: ScrollContainer,
525    stack: VStack,
526}
527
528impl Default for ScrollList {
529    fn default() -> Self {
530        Self::new()
531    }
532}
533
534impl ScrollList {
535    pub fn new() -> Self {
536        Self {
537            scroll_container: ScrollContainer::vertical().flex_grow(),
538            stack: VStack::new(),
539        }
540    }
541
542    pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self {
543        self.stack = self.stack.spacing(spacing);
544        self
545    }
546
547    pub fn align(mut self, align: Align) -> Self {
548        self.stack = self.stack.align(align);
549        self
550    }
551
552    pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
553        self.scroll_container = self.scroll_container.track_scroll(handle);
554        self
555    }
556
557    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
558        self.scroll_container = self.scroll_container.id(id);
559        self
560    }
561
562    pub fn no_flex_grow(mut self) -> Self {
563        let id = SharedString::from(format!(
564            "scroll-list-{}",
565            SCROLL_CONTAINER_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
566        ));
567        self.scroll_container = ScrollContainer::vertical().id(id);
568        self
569    }
570
571    pub fn momentum(mut self, enabled: bool) -> Self {
572        self.scroll_container = self.scroll_container.momentum(enabled);
573        self
574    }
575
576    pub fn overscroll_bounce(mut self, enabled: bool) -> Self {
577        self.scroll_container = self.scroll_container.overscroll_bounce(enabled);
578        self
579    }
580
581    pub fn with_physics(mut self, state: &PhysicsScrollState) -> Self {
582        self.scroll_container = self.scroll_container.with_physics(state);
583        self
584    }
585}
586
587impl ParentElement for ScrollList {
588    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
589        self.stack.extend(elements);
590    }
591}
592
593impl Styled for ScrollList {
594    fn style(&mut self) -> &mut StyleRefinement {
595        self.scroll_container.style()
596    }
597}
598
599impl InteractiveElement for ScrollList {
600    fn interactivity(&mut self) -> &mut Interactivity {
601        self.scroll_container.interactivity()
602    }
603}
604
605impl StatefulInteractiveElement for ScrollList {}
606
607impl IntoElement for ScrollList {
608    type Element = Stateful<Div>;
609
610    fn into_element(self) -> Self::Element {
611        let mut scroll_container = self.scroll_container;
612        scroll_container = scroll_container.child(self.stack);
613        scroll_container.into_element()
614    }
615}