Skip to main content

ui/scroll/
overlay.rs

1//! Stateful overlays for either scroll axis.
2
3use super::{self as scroll, ScrollbarState, TransientState};
4use gpui::{
5    self, Animation, AnimationExt, AnyElement, App, Axis, Div, DragMoveEvent, Empty, Global,
6    IntoElement, MouseButton, Pixels, RenderOnce, ScrollHandle, SharedString, Stateful, Window,
7    canvas, div, point, prelude::*, px,
8};
9use motion::Painter;
10use std::{cell::Cell, rc::Rc};
11use theme::ink;
12
13/// Visibility for overflowing panes; content that fits never draws a bar.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum Visibility {
16    #[default]
17    Scrolling,
18    Always,
19    Never,
20}
21impl Global for Visibility {}
22
23pub fn visibility(cx: &App) -> Visibility {
24    cx.try_global::<Visibility>().copied().unwrap_or_default()
25}
26
27/// Set the default for overlays, including those inside Markdown blocks.
28pub fn set_visibility(value: Visibility, cx: &mut App) {
29    cx.set_global(value);
30    cx.refresh_windows();
31}
32
33#[derive(IntoElement)]
34pub struct Overlay {
35    id: SharedString,
36    handle: ScrollHandle,
37    axis: Axis,
38    visibility: Option<Visibility>,
39    place: scroll::Place,
40}
41
42impl Overlay {
43    /// Mount beside the scroller in a relative wrapper of the same size.
44    pub fn new(id: impl Into<SharedString>, handle: &ScrollHandle, axis: Axis) -> Self {
45        Self {
46            id: id.into(),
47            handle: handle.clone(),
48            axis,
49            visibility: None,
50            place: scroll::Place::default(),
51        }
52    }
53
54    /// Shorten the track to clear an overlaid footer without resizing content.
55    pub fn end_inset(mut self, inset: Pixels) -> Self {
56        self.place.end = inset.max(px(0.));
57        self
58    }
59
60    /// Centre the bar in `room` reserved across its axis rather than in the
61    /// default strip at the edge. Pass the padding the pane holds beside its
62    /// content and the thumb runs down the middle of it.
63    pub fn channel(mut self, room: Pixels) -> Self {
64        self.place.channel = room.max(px(0.));
65        self
66    }
67
68    /// Override the default for an individual pane, such as a sidebar.
69    pub fn visibility(mut self, visibility: Visibility) -> Self {
70        self.visibility = Some(visibility);
71        self
72    }
73}
74
75/// An intrinsically sized scroll container with its own handle and overlay.
76#[derive(IntoElement)]
77pub struct Viewport {
78    id: SharedString,
79    content: Stateful<Div>,
80    axis: Axis,
81    fill: bool,
82    handle: Option<ScrollHandle>,
83}
84
85impl Viewport {
86    pub fn new(id: impl Into<SharedString>, content: Stateful<Div>, axis: Axis) -> Self {
87        Self {
88            id: id.into(),
89            content,
90            axis,
91            fill: false,
92            handle: None,
93        }
94    }
95
96    /// Fill the remaining space in a flex container instead of sizing to content.
97    pub fn fill(mut self) -> Self {
98        self.fill = true;
99        self
100    }
101
102    /// Scroll it from outside — what a caller needs to ask
103    /// [`gpui::ScrollHandle::scroll_to_item`] for one of its children. Left
104    /// unset, the viewport keeps a handle of its own that nothing else can
105    /// reach.
106    pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
107        self.handle = Some(handle.clone());
108        self
109    }
110}
111
112impl RenderOnce for Viewport {
113    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
114        let handle = match self.handle {
115            Some(handle) => handle,
116            None => window
117                .use_keyed_state(
118                    SharedString::from(format!("{}-handle", self.id)),
119                    cx,
120                    |_, _| ScrollHandle::new(),
121                )
122                .read(cx)
123                .clone(),
124        };
125        let axes = match self.axis {
126            Axis::Vertical => scroll::Axes::Vertical,
127            Axis::Horizontal => scroll::Axes::Horizontal,
128        };
129        div()
130            .relative()
131            .w_full()
132            .min_w_0()
133            .when(self.fill, |el| el.flex_1().min_h_0().flex().flex_col())
134            .child(scroll::scrolls(self.content, axes).track_scroll(&handle))
135            .child(Overlay::new(self.id, &handle, self.axis))
136    }
137}
138
139struct State {
140    steady: ScrollbarState,
141    transient: TransientState,
142    horizontal: Rc<Cell<Horizontal>>,
143}
144
145#[derive(Clone, Copy, Default)]
146struct Horizontal {
147    offset: Pixels,
148    max: Pixels,
149    generation: usize,
150    hovered: bool,
151    grab: Option<Pixels>,
152}
153
154impl RenderOnce for Overlay {
155    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
156        let mode = self.visibility.unwrap_or_else(|| visibility(cx));
157        if mode == Visibility::Never {
158            return Empty.into_any_element();
159        }
160        let state = window.use_keyed_state(
161            SharedString::from(format!("{}-state", self.id)),
162            cx,
163            |_, cx| State {
164                steady: ScrollbarState::new(Painter::of(cx)),
165                transient: TransientState::new(Painter::of(cx)),
166                horizontal: Rc::default(),
167            },
168        );
169        let held = state.read(cx);
170        let always = mode == Visibility::Always || cx.reduce_motion();
171        let inner = match self.axis {
172            Axis::Vertical if always => {
173                scroll::scrollbar_placed(self.id, &self.handle, &held.steady, self.place)
174            }
175            Axis::Vertical => {
176                scroll::transient_placed(self.id, &self.handle, &held.transient, false, self.place)
177            }
178            Axis::Horizontal => horizontal(
179                self.id,
180                &self.handle,
181                held.horizontal.clone(),
182                always,
183                self.place,
184            ),
185        };
186        let handle = self.handle;
187        let before = (handle.bounds(), handle.max_offset(), handle.offset());
188        // Handles receive new geometry during layout, after this render pass.
189        div()
190            .absolute()
191            .inset_0()
192            .child(inner)
193            .child(
194                canvas(
195                    move |_, window, _| {
196                        if before != (handle.bounds(), handle.max_offset(), handle.offset()) {
197                            window.request_animation_frame();
198                        }
199                    },
200                    |_, _, _, _| {},
201                )
202                .absolute()
203                .size_full(),
204            )
205            .into_any_element()
206    }
207}
208
209#[derive(Clone)]
210struct HorizontalDrag(SharedString);
211
212fn horizontal(
213    id: SharedString,
214    handle: &ScrollHandle,
215    state: Rc<Cell<Horizontal>>,
216    always: bool,
217    place: scroll::Place,
218) -> AnyElement {
219    let end_inset = place.end;
220    let viewport = handle.bounds().size.width;
221    let max = handle.max_offset().x;
222    let Some(range) = scroll::thumb_in_track(
223        viewport,
224        max,
225        handle.offset().x,
226        viewport - 2. * scroll::BAR_INSET - end_inset,
227    ) else {
228        return Empty.into_any_element();
229    };
230    let size = range.end - range.start;
231    let mut held = state.get();
232    if (held.offset - handle.offset().x).abs() > px(0.5) || (held.max - max).abs() > px(0.5) {
233        held.offset = handle.offset().x;
234        held.max = max;
235        held.generation += 1;
236        state.set(held);
237    }
238    let drag_id = id.clone();
239    let drag_handle = handle.clone();
240    let drag_state = state.clone();
241    let release_state = state.clone();
242    let release = move |_: &gpui::MouseUpEvent, window: &mut Window, _: &mut App| {
243        let mut held = release_state.get();
244        held.grab = None;
245        held.generation += 1;
246        release_state.set(held);
247        window.refresh();
248    };
249    let hover_state = state.clone();
250    let track = scroll::track(&id, place, Axis::Horizontal)
251        .on_hover(move |hovered, window, _| {
252            let mut held = hover_state.get();
253            held.hovered = *hovered;
254            held.generation += 1;
255            hover_state.set(held);
256            window.refresh();
257        })
258        .on_drag_move(move |event: &DragMoveEvent<HorizontalDrag>, window, cx| {
259            if event.drag(cx).0 != drag_id {
260                return;
261            }
262            let viewport = drag_handle.bounds().size.width;
263            let max = drag_handle.max_offset().x;
264            let Some(range) = scroll::thumb_in_track(
265                viewport,
266                max,
267                drag_handle.offset().x,
268                viewport - 2. * scroll::BAR_INSET - end_inset,
269            ) else {
270                return;
271            };
272            let pointer = event.event.position.x - event.bounds.left();
273            let mut held = drag_state.get();
274            let grab = *held
275                .grab
276                .get_or_insert((pointer - range.start).clamp(px(0.), range.end - range.start));
277            drag_state.set(held);
278            let x = scroll::offset_for_thumb(
279                pointer - grab,
280                viewport - 2. * scroll::BAR_INSET - end_inset,
281                max,
282                range.end - range.start,
283            );
284            drag_handle.set_offset(point(x, drag_handle.offset().y));
285            window.refresh();
286        })
287        .on_mouse_up(MouseButton::Left, release.clone())
288        .on_mouse_up_out(MouseButton::Left, release);
289    let thumb_debug_id = id.clone();
290    let press_state = state.clone();
291    let press_handle = handle.clone();
292    let thumb = div()
293        .debug_selector(move || format!("{thumb_debug_id}-thumb"))
294        .id(SharedString::from(format!("{id}-thumb")))
295        .absolute()
296        .left(range.start)
297        .w(size)
298        .h(px(scroll::THUMB))
299        .rounded_full()
300        .bg(ink(0.2))
301        .hover(|s| s.bg(ink(0.32)))
302        .on_mouse_down(MouseButton::Left, move |event, window, _| {
303            let mut held = press_state.get();
304            held.grab = Some(
305                (event.position.x - press_handle.bounds().left() - scroll::BAR_INSET - range.start)
306                    .clamp(px(0.), size),
307            );
308            press_state.set(held);
309            window.refresh();
310        })
311        .on_drag(HorizontalDrag(id.clone()), |_, _, _, cx| cx.new(|_| Empty));
312    let thumb = if always {
313        thumb.into_any_element()
314    } else {
315        thumb
316            .with_animation(
317                SharedString::from(format!("{id}-fade-{}", held.generation)),
318                Animation::new(scroll::TRANSIENT_IDLE),
319                move |el, p| {
320                    let held = state.get();
321                    if held.hovered || held.grab.is_some() {
322                        el
323                    } else if p < 1. {
324                        el.opacity(1. - p)
325                    } else {
326                        el.hidden()
327                    }
328                },
329            )
330            .into_any_element()
331    };
332    track.child(thumb).into_any_element()
333}