ui/scroll.rs
1//! What gpui's own scroll handles leave to the app: a container that scrolls
2//! the way it was asked to, a bar to show the position, and a rule for which
3//! pane a wheel belongs to.
4//!
5//! [`pane`] is the container — an axis given at construction, the way
6//! SwiftUI's `ScrollView` takes one, because gpui's is a style field that
7//! defaults to unset and gets guessed at. Read its docs before reaching for
8//! `div().overflow_y_scroll()`; the guess is a real bug and not a small one.
9//!
10//! gpui scrolls that pane perfectly well and draws nothing while it does, so a
11//! bezel app has no way to show how far down it is. That is [`scrollbar`]: an
12//! overlay the caller lays over its own pane, because a wrapper that swallowed
13//! the content would have to re-implement layout for it. Nesting two panes is
14//! [`claim_wheel`]'s business.
15//!
16//! ```ignore
17//! div().relative() // the bar is absolute in here
18//! .child(
19//! scroll::pane("pane", Axes::Vertical)
20//! .size_full()
21//! .track_scroll(&self.scroll) // gpui's handle, the app's field
22//! .child(content),
23//! )
24//! .child(scroll::scrollbar("pane-bar", &self.scroll, &self.scroll_bar))
25//! ```
26//!
27//! The bar must span the container it reports on — its track *is* the viewport,
28//! in the coordinates [`thumb`] answers in.
29//!
30//! The geometry is transcribed from zed's own scrollbar (`thumb_ranges` in
31//! `crates/ui/src/components/scrollbar.rs`), which is 1722 lines of settings
32//! system around the fifteen that matter. Two of gpui's conventions are easy to
33//! get backwards and both are load-bearing here: `max_offset` is the *overflow*
34//! (content minus viewport, not content), and `offset` is **negative** as you
35//! scroll down.
36//!
37//! [`transient`] is the same bar, shown only while its content moves.
38//! [`Overlay`] manages its own state and supports either axis. Its default is
39//! [`Visibility::Scrolling`]; [`set_visibility`] updates all default overlays,
40//! including Markdown code blocks and tables. [`Viewport`] also owns the handle.
41
42mod overlay;
43pub use overlay::{Overlay, Viewport, Visibility, set_visibility, visibility};
44
45use std::{cell::Cell, ops::Range, rc::Rc, time::Duration};
46
47use gpui::{
48 Animation, AnimationExt, App, Axis, Bounds, Div, DragMoveEvent, ElementId, Empty, MouseButton,
49 Pixels, Point, ScrollHandle, SharedString, Stateful, Window, canvas, div, point, prelude::*,
50 px,
51};
52
53use motion::Painter;
54use theme::ink;
55use web_time::Instant;
56
57/// Shortest a thumb may get, however long the document — below this it stops
58/// being something a pointer can catch.
59pub const MIN_THUMB: Pixels = px(25.0);
60/// Space between the overlay track and the viewport edges, along the axis the
61/// bar runs.
62const INSET: f32 = 4.0;
63const BAR_INSET: Pixels = px(INSET);
64/// Width of the strip the thumb sits in.
65const TRACK: f32 = 10.0;
66/// Room a bar is centred in across its axis when the caller reserves none.
67const CHANNEL: f32 = 2.0 * INSET + TRACK;
68/// Width of the thumb itself, centred in the track.
69const THUMB: f32 = 6.0;
70/// Length of one [`rail`] mark, and its thickness.
71const MARK: f32 = 16.0;
72const MARK_THICK: f32 = 2.0;
73/// Between two marks. The track's width, so a rail and a bar on the same pane
74/// are cut to one rhythm.
75const MARK_GAP: f32 = TRACK;
76/// How far the rail stands off the edge it is pinned to.
77const RAIL_INSET: f32 = 12.0;
78/// What a rail needs beside the content before it will paint at all.
79const RAIL_ROOM: f32 = RAIL_INSET + MARK;
80
81// ---------------------------------------------------------------------------
82// Pane — a scroll container whose axis is an argument, not a modifier
83// ---------------------------------------------------------------------------
84
85/// Which way a [`pane`] scrolls. SwiftUI's `Axis.Set`, which gpui's [`Axis`]
86/// has no spelling for: a pane that scrolls both ways is not one of two
87/// directions.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub enum Axes {
90 Vertical,
91 Horizontal,
92 Both,
93}
94
95impl Axes {
96 pub fn vertical(self) -> bool {
97 matches!(self, Axes::Vertical | Axes::Both)
98 }
99
100 pub fn horizontal(self) -> bool {
101 matches!(self, Axes::Horizontal | Axes::Both)
102 }
103
104 /// The gpui axis this is, where it is only one.
105 pub fn axis(self) -> Option<Axis> {
106 match self {
107 Axes::Vertical => Some(Axis::Vertical),
108 Axes::Horizontal => Some(Axis::Horizontal),
109 Axes::Both => None,
110 }
111 }
112}
113
114/// A scroll container, with the axis as an argument rather than a modifier you
115/// can forget.
116///
117/// ```ignore
118/// scroll::pane("log", Axes::Vertical)
119/// .size_full()
120/// .track_scroll(&self.scroll)
121/// .child(content)
122/// ```
123///
124/// Returns an element for the caller to fill, the way [`crate::stack::row`]
125/// does — it takes no children and lays nothing out, so the pane stays the
126/// app's and only its scroll behaviour is decided here. The id is gpui's
127/// requirement, not ours: a scroll container has state to track.
128///
129/// # Why this exists rather than `div().overflow_y_scroll()`
130///
131/// gpui makes scrollability a late-bound style field with no default, and then
132/// has to guess what to do when a gesture's axis is not one the container
133/// scrolls: it **remaps the delta onto whichever axis the container can
134/// scroll**. A sideways swipe over a vertical list scrolls it down; a downward
135/// swipe over a wide table pans it sideways. `restrict_scroll_to_axis` turns
136/// that off, but it is opt-in per element, so every pane that forgets it is
137/// wrong and nothing says so.
138///
139/// SwiftUI has no such case to guess at — `ScrollView(.vertical)` takes its
140/// axis at construction, so there is no container whose axis is unstated. This
141/// is that: ask for an axis, get a pane that answers only to it.
142///
143/// A horizontal pane also contains a sideways gesture ([`contain_sideways`]),
144/// because the pane it is nested in usually belongs to a consumer and is not
145/// ours to restrict.
146///
147/// `Axes::Both` inherits gpui's dominant-axis lock — a diagonal gesture moves
148/// one axis, not two. gpui exposes no builder for `allow_concurrent_scroll`.
149pub fn pane(id: impl Into<ElementId>, axes: Axes) -> Stateful<Div> {
150 scrolls(div().id(id), axes)
151}
152
153/// [`pane`], keeping the wheel it can act on: the pane a consumer nests inside
154/// another and never wires a handle to.
155///
156/// [`claim_wheel`] asks the caller for a [`ScrollHandle`] and a [`ClaimState`],
157/// because the caller usually has the handle already — it is scrolling the pane
158/// from elsewhere. A bounded box inside someone else's page has neither, and a
159/// pane that is only ever read by the wheel that moves it should not make a
160/// consumer hold two fields to stop it dragging the page behind it. Both live
161/// in keyed element state here, so the pane is still one call.
162///
163/// ```ignore
164/// scroll::claiming_pane("output", Axes::Vertical, window, cx).child(text)
165/// ```
166///
167/// The chaining is [`claim_wheel`]'s: at its ends the pane hands the wheel back
168/// to the page.
169pub fn claiming_pane(
170 id: impl Into<ElementId>,
171 axes: Axes,
172 window: &mut Window,
173 cx: &mut App,
174) -> Stateful<Div> {
175 let id = id.into();
176 let held = window.use_keyed_state(id.clone(), cx, |_, _| Claiming::default());
177 let (handle, state) = {
178 let held = held.read(cx);
179 (held.handle.clone(), held.state.clone())
180 };
181 claim_wheel(pane(id, axes).track_scroll(&handle), &handle, axes, &state)
182}
183
184/// What [`claiming_pane`] keeps between frames: the handle it reads its own
185/// travel off, and where that travel stood before the wheel being dispatched.
186#[derive(Default)]
187struct Claiming {
188 handle: ScrollHandle,
189 state: ClaimState,
190}
191
192/// [`pane`]'s answer applied to an element that already exists — a container
193/// that scrolls only at some widths, or one another builder handed back.
194///
195/// ```ignore
196/// strip.when(compact, |strip| scroll::scrolls(strip, Axes::Horizontal))
197/// ```
198pub fn scrolls<E: gpui::StatefulInteractiveElement>(el: E, axes: Axes) -> E {
199 let el = match axes {
200 Axes::Vertical => el.overflow_y_scroll(),
201 Axes::Horizontal => el.overflow_x_scroll(),
202 Axes::Both => el.overflow_scroll(),
203 }
204 .restrict_scroll_to_axis();
205 match axes.horizontal() {
206 true => contain_sideways(el),
207 false => el,
208 }
209}
210
211/// Keep a sideways gesture inside the pane it started in.
212///
213/// The other half of [`pane`], and the half [`Axes::Vertical`] does not want:
214/// a vertical pane at its end should hand the wheel to the page behind it
215/// ([`claim_wheel`] is that chaining), but a sideways gesture reaching a
216/// vertical ancestor is never right — unless that ancestor is restricted too,
217/// it will remap the delta and scroll down.
218///
219/// Applied by [`pane`] for the axes that need it. Public because a consumer
220/// wrapping bezel's content in a scroller of its own has the same problem and
221/// the same fix.
222///
223/// Registered before the element's own handler and so run after it — gpui
224/// bubbles the list backwards — which is why the pane has already moved by the
225/// time the event stops here.
226pub fn contain_sideways<E: gpui::InteractiveElement>(el: E) -> E {
227 contain_wheel(el, Axes::Horizontal)
228}
229
230/// Keep every wheel inside the pane it landed on — `overscroll-behavior:
231/// contain`, where [`claim_wheel`] is the chaining kind.
232///
233/// For a box with a cap on it, where the content is a program's output rather
234/// than a document: it is a window onto something, and a wheel over a window
235/// belongs to what is inside it. Chaining asks the pane to prove it moved,
236/// which it reads off a handle carrying the previous frame's layout — under a
237/// pane whose content is still arriving that reads as "did not move", and the
238/// page takes the wheel while the box is still scrolling (user report,
239/// DEV-13).
240///
241/// The page is still reachable: move the pointer off the box.
242pub fn contain_wheel<E: gpui::InteractiveElement>(el: E, axes: Axes) -> E {
243 el.on_scroll_wheel(move |event, window, cx| {
244 let delta = event.delta.pixel_delta(window.line_height());
245 // The dominant axis, not "any horizontal component": a trackpad puts a
246 // little of both into every gesture, and a mostly-vertical one still
247 // belongs to the page.
248 let sideways = delta.x.abs() > delta.y.abs();
249 if (sideways && axes.horizontal()) || (!sideways && axes.vertical()) {
250 cx.stop_propagation();
251 }
252 })
253}
254
255/// The strip a thumb sits in, placed along `axis` and named for `id`.
256///
257/// A press on the bar belongs to the bar. Hitboxes in gpui are paint-order
258/// only, so without `block_mouse_except_scroll` the content under the strip
259/// takes the press as well; the wheel still passes, which is what a bar laid
260/// over a pane has to let through.
261fn track(id: &SharedString, place: Place, axis: Axis) -> Stateful<Div> {
262 let debug_id = id.clone();
263 let el = div()
264 .debug_selector(move || format!("{debug_id}-track"))
265 .id(SharedString::from(format!("{id}-track")))
266 .block_mouse_except_scroll()
267 .absolute()
268 .flex();
269 match axis {
270 Axis::Vertical => el
271 .top(BAR_INSET)
272 .right(place.near())
273 .bottom(BAR_INSET + place.end)
274 .w(px(TRACK))
275 .justify_center(),
276 Axis::Horizontal => el
277 .left(BAR_INSET)
278 .right(BAR_INSET + place.end)
279 .bottom(place.near())
280 .h(px(TRACK))
281 .items_center(),
282 }
283}
284
285/// Where the thumb sits in a track of `viewport` length, as a range from the
286/// track's start — or `None` when there is nothing to scroll.
287///
288/// `None` also covers a viewport of zero (the frame before layout has run) and
289/// a thumb that would not fit, which is zed's third guard: with a viewport
290/// shorter than [`MIN_THUMB`] a bar would be all thumb and no travel.
291pub fn thumb(
292 viewport: Pixels,
293 max_offset: Pixels,
294 offset: Pixels,
295 min: Pixels,
296) -> Option<Range<Pixels>> {
297 if viewport <= px(0.0) || max_offset <= px(0.0) {
298 return None;
299 }
300 let content = viewport + max_offset;
301 let size = min.max(viewport * (viewport / content));
302 if size > viewport {
303 return None;
304 }
305 // Negative going down, and never past either end — a wheel can overshoot.
306 let travelled = offset.clamp(-max_offset, px(0.0)).abs();
307 let start = (travelled / max_offset) * (viewport - size);
308 Some(start..start + size)
309}
310
311pub(crate) fn thumb_in_track(
312 viewport: Pixels,
313 max_offset: Pixels,
314 offset: Pixels,
315 track: Pixels,
316) -> Option<Range<Pixels>> {
317 if track <= px(0.) {
318 return None;
319 }
320 let scale = track / viewport;
321 let range = thumb(viewport, max_offset, offset, MIN_THUMB / scale)?;
322 Some(range.start * scale..range.end * scale)
323}
324
325/// The inverse: the scroll offset that puts the thumb's top at `top`.
326///
327/// Negative, because that is the direction gpui counts in, and clamped to the
328/// scrollable range so a drag past either end simply stops.
329pub fn offset_for_thumb(top: Pixels, viewport: Pixels, max_offset: Pixels, size: Pixels) -> Pixels {
330 let travel = viewport - size;
331 if travel <= px(0.0) || max_offset <= px(0.0) {
332 return px(0.0);
333 }
334 -(max_offset * (top / travel).clamp(0.0, 1.0))
335}
336
337/// The drag payload. Carries the bar's id because, unlike a split, an app has
338/// several of these on screen at once and `on_drag_move` filters by type alone
339/// — without the id every bar in the window would answer one thumb's gesture.
340#[derive(Clone)]
341pub struct ScrollbarDrag(pub SharedString);
342
343/// Where in the thumb a drag was grabbed.
344///
345/// Shaped like gpui's `ScrollHandle` — an `Rc` cell the view holds one field of
346/// and the bar clones — for the same reason: both mutate through `&self`, so
347/// the bar carries its whole gesture without the view wiring a single listener.
348/// Without it the thumb would jump its middle to the pointer on every press.
349#[derive(Clone)]
350pub struct ScrollbarState {
351 grab: Rc<Cell<Option<Pixels>>>,
352 /// A drag runs in event-dispatch context, where the window cannot resolve
353 /// which view is asking — so the bar carries its own.
354 painter: Painter,
355}
356
357impl ScrollbarState {
358 pub fn new(painter: Painter) -> Self {
359 Self {
360 grab: Rc::new(Cell::new(None)),
361 painter,
362 }
363 }
364
365 fn begin(&self, handle: &ScrollHandle, event: &gpui::MouseDownEvent, end_inset: Pixels) {
366 let viewport = handle.bounds().size.height;
367 if let Some(range) = thumb_in_track(
368 viewport,
369 handle.max_offset().y,
370 handle.offset().y,
371 viewport - 2. * BAR_INSET - end_inset,
372 ) {
373 self.grab.set(Some(
374 (event.position.y - handle.bounds().top() - BAR_INSET - range.start)
375 .clamp(px(0.), range.end - range.start),
376 ));
377 }
378 }
379
380 /// Whether a thumb drag is in flight.
381 pub fn dragging(&self) -> bool {
382 self.grab.get().is_some()
383 }
384
385 /// One drag move of the thumb: filter the gesture to this bar's track, then
386 /// translate the pointer into a scroll offset.
387 fn drag(
388 &self,
389 track_id: &SharedString,
390 handle: &ScrollHandle,
391 event: &DragMoveEvent<ScrollbarDrag>,
392 end_inset: Pixels,
393 cx: &mut App,
394 ) {
395 // Another bar's thumb: `on_drag_move` filters by payload type, and
396 // every bar in the window shares this one.
397 if event.drag(cx).0 != *track_id {
398 return;
399 }
400 let viewport = handle.bounds().size.height;
401 let max_offset = handle.max_offset().y;
402 let Some(range) = thumb_in_track(
403 viewport,
404 max_offset,
405 handle.offset().y,
406 viewport - 2. * BAR_INSET - end_inset,
407 ) else {
408 return;
409 };
410 let size = range.end - range.start;
411 let pointer = event.event.position.y - event.bounds.top();
412 // First move of this drag: the offset has not shifted yet, so the
413 // thumb is still where the press landed on it and the grab is
414 // simply the difference. Held for the rest of the gesture — read it
415 // again later and it would answer "wherever the pointer is now",
416 // which is a thumb that never moves.
417 let grab = self.grab.get().unwrap_or_else(|| {
418 let grab = (pointer - range.start).clamp(px(0.0), size);
419 self.grab.set(Some(grab));
420 grab
421 });
422 let offset = offset_for_thumb(
423 pointer - grab,
424 viewport - 2. * BAR_INSET - end_inset,
425 max_offset,
426 size,
427 );
428 handle.set_offset(point(handle.offset().x, offset));
429 self.painter.notify(cx);
430 }
431}
432
433/// Where a bar sits in the pane it reports on. [`Overlay`] builds one; the free
434/// bars take the default.
435#[derive(Clone, Copy)]
436struct Place {
437 /// Shortens the track at its far end.
438 end: Pixels,
439 /// Room reserved across the axis, which the track is centred in.
440 channel: Pixels,
441}
442
443impl Default for Place {
444 fn default() -> Self {
445 Self {
446 end: px(0.),
447 channel: px(CHANNEL),
448 }
449 }
450}
451
452impl Place {
453 /// Gap between the near edge of the pane and the near side of the track.
454 fn near(self) -> Pixels {
455 ((self.channel - px(TRACK)) * 0.5).max(px(0.))
456 }
457}
458
459/// The bar: an overlay strip along the right edge of whatever it is laid over,
460/// showing nothing at all when the content fits.
461///
462/// Overlay rather than a gutter, so a bar arriving or leaving never reflows the
463/// content beneath it.
464///
465/// Its geometry comes from the handle as the *last* frame left it, which is all
466/// a render pass can see; the canvas at the end asks for one more frame when
467/// layout disagrees, so the bar is right on the frame after it first appears
468/// rather than whenever something else happens to repaint.
469///
470/// No `&Theme`, unlike most of this crate — a scrollbar is a neutral overlay
471/// rather than a toned surface, so the thumb is [`ink`], which already follows
472/// the appearance on its own. A parameter it ignored would be worse than none.
473pub fn scrollbar(
474 id: impl Into<SharedString>,
475 handle: &ScrollHandle,
476 state: &ScrollbarState,
477) -> gpui::AnyElement {
478 scrollbar_placed(id.into(), handle, state, Place::default())
479}
480
481fn scrollbar_placed(
482 id: SharedString,
483 handle: &ScrollHandle,
484 state: &ScrollbarState,
485 place: Place,
486) -> gpui::AnyElement {
487 let end_inset = place.end;
488 let viewport = handle.bounds().size.height;
489 let max_offset = handle.max_offset().y;
490 let Some(range) = thumb_in_track(
491 viewport,
492 max_offset,
493 handle.offset().y,
494 viewport - 2. * BAR_INSET - end_inset,
495 ) else {
496 return Empty.into_any_element();
497 };
498 let size = range.end - range.start;
499 let dragging = state.dragging();
500
501 let track_id = id.clone();
502 let drag_handle = handle.clone();
503 let drag_state = state.clone();
504 let release_state = state.clone();
505 let press_state = state.clone();
506 let press_handle = handle.clone();
507 let released = move |_: &gpui::MouseUpEvent, _: &mut Window, _: &mut App| {
508 release_state.grab.set(None);
509 };
510
511 let thumb_debug_id = id.clone();
512 track(&id, place, Axis::Vertical)
513 .on_drag_move(move |event, _, cx| {
514 drag_state.drag(&track_id, &drag_handle, event, end_inset, cx);
515 })
516 // Both, because a release can land anywhere on screen; a grab left set
517 // would make the next press continue the last gesture.
518 .on_mouse_up(MouseButton::Left, released.clone())
519 .on_mouse_up_out(MouseButton::Left, released)
520 .child(
521 div()
522 .debug_selector(move || format!("{thumb_debug_id}-thumb"))
523 .id(SharedString::from(format!("{id}-thumb")))
524 .absolute()
525 .top(range.start)
526 .h(size)
527 .w(px(THUMB))
528 .rounded_full()
529 .bg(if dragging { ink(0.38) } else { ink(0.2) })
530 .hover(|s| s.bg(ink(0.32)))
531 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
532 press_state.begin(&press_handle, event, end_inset);
533 press_state.painter.notify(cx);
534 })
535 .on_drag(ScrollbarDrag(id.clone()), |_, _, _, cx| cx.new(|_| Empty)),
536 )
537 .child(
538 canvas(
539 move |bounds, window, _| {
540 // Laid out taller or shorter than the geometry above was
541 // computed from: that geometry came from last frame's
542 // handle. Ask for the frame that will paint it right.
543 // Self-limiting — once they agree, nothing is requested.
544 if (bounds.size.height + 2. * BAR_INSET + end_inset - viewport).abs() > px(0.5)
545 {
546 window.request_animation_frame();
547 }
548 },
549 |_, _, _, _| {},
550 )
551 .absolute()
552 .size_full(),
553 )
554 .into_any_element()
555}
556
557/// Whether `room` beside the content is enough for a rail to paint in. A
558/// hand-rolled rail asks this to land on the same floor as [`rail`].
559pub fn rail_fits(room: Pixels) -> bool {
560 room >= px(RAIL_ROOM)
561}
562
563/// A mark per item, the one at the top of the viewport lit — for a pane whose
564/// content comes in countable pieces (a transcript's turns) rather than as one
565/// continuous document, where how far down you are matters less than which
566/// piece you are on. A press jumps to that piece.
567///
568/// `count` addresses the **direct children** of the `track_scroll` element,
569/// which is what gpui indexes: a pane whose pieces sit nested inside a wrapper
570/// reports one child, and every mark would scroll to the same place.
571///
572/// Absolute, so the caller's container holds the position: pin it with
573/// `.relative()` on whichever box the rail belongs to the edge of.
574///
575/// `room` is the clear space beside the content, which only the caller can
576/// measure; under what [`rail_fits`] accepts the rail paints nothing.
577pub fn rail(
578 id: impl Into<SharedString>,
579 handle: &ScrollHandle,
580 count: usize,
581 room: Pixels,
582) -> gpui::AnyElement {
583 if count == 0 || !rail_fits(room) {
584 return Empty.into_any_element();
585 }
586 let id = id.into();
587 let at = handle.top_item();
588 div()
589 .absolute()
590 .top_0()
591 .bottom_0()
592 .left(px(RAIL_INSET))
593 .flex()
594 .flex_col()
595 .items_center()
596 .justify_center()
597 .gap(px(MARK_GAP))
598 .overflow_hidden()
599 .children((0..count).map(|ix| {
600 let handle = handle.clone();
601 div()
602 .id(SharedString::from(format!("{id}-{ix}")))
603 .w(px(MARK))
604 .h(px(MARK_THICK))
605 .rounded_full()
606 .bg(if ix == at { ink(0.6) } else { ink(0.2) })
607 .cursor_pointer()
608 .hover(|mark| mark.bg(ink(0.32)))
609 .on_click(move |_, window, _| {
610 handle.scroll_to_item(ix);
611 window.refresh();
612 })
613 }))
614 .into_any_element()
615}
616
617// ---------------------------------------------------------------------------
618// Transient — the same bar, only while the content moves
619// ---------------------------------------------------------------------------
620
621/// How long the thumb stays after the last scroll before fading — the idle
622/// window *is* the fade, because the fork's `Animation` has no delay.
623pub const TRANSIENT_IDLE: Duration = Duration::from_millis(1000);
624
625/// The show-and-fade state behind [`transient`]: the last frame's scroll
626/// state (a change is activity), a generation counter (a fresh animation id
627/// restarts the fade — `AnimationElement` pins its clock to the id it first
628/// laid out with), and the hover flag that holds the thumb up while the
629/// pointer is on the strip.
630#[derive(Clone)]
631pub struct TransientState {
632 cell: Rc<Cell<(Pixels, Pixels, u64, bool)>>,
633 bar: ScrollbarState,
634}
635
636impl TransientState {
637 pub fn new(painter: Painter) -> Self {
638 Self {
639 cell: Rc::new(Cell::new(Default::default())),
640 bar: ScrollbarState::new(painter),
641 }
642 }
643}
644
645/// The same bar as [`scrollbar`], but it only earns its place while the
646/// content moves: activity raises the thumb, and it fades out over
647/// [`TRANSIENT_IDLE`] once the scrolling stops. Hovering the strip or
648/// dragging the thumb holds it up. With `reduce_motion` there is nothing to
649/// animate, so it renders as the always-on bar.
650pub fn transient(
651 id: impl Into<SharedString>,
652 handle: &ScrollHandle,
653 state: &TransientState,
654 reduce_motion: bool,
655) -> gpui::AnyElement {
656 transient_placed(id.into(), handle, state, reduce_motion, Place::default())
657}
658
659fn transient_placed(
660 id: SharedString,
661 handle: &ScrollHandle,
662 state: &TransientState,
663 reduce_motion: bool,
664 place: Place,
665) -> gpui::AnyElement {
666 let end_inset = place.end;
667 let viewport = handle.bounds().size.height;
668 let max_offset = handle.max_offset().y;
669 let Some(range) = thumb_in_track(
670 viewport,
671 max_offset,
672 handle.offset().y,
673 viewport - 2. * BAR_INSET - end_inset,
674 ) else {
675 return Empty.into_any_element();
676 };
677 let size = range.end - range.start;
678
679 // Any change in the scroll state is activity: bump the generation so the
680 // fade restarts under a fresh animation id. The half-pixel slack keeps a
681 // sub-pixel layout jitter from re-showing a settled bar.
682 let mut cell = state.cell.get();
683 if (handle.offset().y - cell.0).abs() > px(0.5) || (max_offset - cell.1).abs() > px(0.5) {
684 cell.0 = handle.offset().y;
685 cell.1 = max_offset;
686 cell.2 += 1;
687 state.cell.set(cell);
688 }
689 let generation = cell.2;
690 let dragging = state.bar.dragging();
691
692 let track_id = id.clone();
693 let drag_handle = handle.clone();
694 let drag_state = state.clone();
695 let release_state = state.clone();
696 let press_state = state.clone();
697 let press_handle = handle.clone();
698 let released = move |_: &gpui::MouseUpEvent, _: &mut Window, _: &mut App| {
699 release_state.bar.grab.set(None);
700 };
701
702 let thumb_debug_id = id.clone();
703 let track = track(&id, place, Axis::Vertical)
704 .on_drag_move(move |event, _, cx| {
705 drag_state
706 .bar
707 .drag(&track_id, &drag_handle, event, end_inset, cx);
708 })
709 // Both, because a release can land anywhere on screen; a grab left set
710 // would make the next press continue the last gesture.
711 .on_mouse_up(MouseButton::Left, released.clone())
712 .on_mouse_up_out(MouseButton::Left, released)
713 .map(|track| {
714 if reduce_motion {
715 track
716 } else {
717 // The thumb's stand-in at rest: hovering the strip raises it,
718 // and leaving starts its fade.
719 let hover_state = state.clone();
720 let hover_painter = state.bar.painter;
721 track.on_hover(move |hovered: &bool, _, cx: &mut App| {
722 let mut cell = hover_state.cell.get();
723 if cell.3 == *hovered {
724 return;
725 }
726 cell.3 = *hovered;
727 cell.2 += 1;
728 hover_state.cell.set(cell);
729 hover_painter.notify(cx);
730 })
731 }
732 });
733
734 let thumb = div()
735 .debug_selector(move || format!("{thumb_debug_id}-thumb"))
736 .id(SharedString::from(format!("{id}-thumb")))
737 .absolute()
738 .top(range.start)
739 .h(size)
740 .w(px(THUMB))
741 .rounded_full()
742 .bg(if dragging { ink(0.38) } else { ink(0.2) })
743 .hover(|s| s.bg(ink(0.32)))
744 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
745 press_state.bar.begin(&press_handle, event, end_inset);
746 press_state.bar.painter.notify(cx);
747 })
748 .on_drag(ScrollbarDrag(id.clone()), |_, _, _, cx| cx.new(|_| Empty));
749
750 let thumb: gpui::AnyElement = if reduce_motion {
751 thumb.into_any_element()
752 } else {
753 // The thumb's presence is the animation: progress 0 is fully up, and
754 // progress 1 — a full idle window later — is hidden, so no frame is
755 // requested once the fade completes.
756 let anim = state.clone();
757 thumb
758 .with_animation(
759 ElementId::from(format!("{id}-fade-{generation}")),
760 Animation::new(TRANSIENT_IDLE),
761 move |el, p| {
762 let cell = anim.cell.get();
763 if cell.3 || anim.bar.dragging() {
764 el
765 } else if p < 1.0 {
766 el.opacity(1.0 - p)
767 } else {
768 el.hidden()
769 }
770 },
771 )
772 .into_any_element()
773 };
774
775 track
776 .child(thumb)
777 .child(
778 canvas(
779 move |bounds, window, _| {
780 // Laid out taller or shorter than the geometry above was
781 // computed from: that geometry came from last frame's
782 // handle. Ask for the frame that will paint it right.
783 // Self-limiting — once they agree, nothing is requested.
784 if (bounds.size.height + 2. * BAR_INSET + end_inset - viewport).abs() > px(0.5)
785 {
786 window.request_animation_frame();
787 }
788 },
789 |_, _, _, _| {},
790 )
791 .absolute()
792 .size_full(),
793 )
794 .into_any_element()
795}
796
797// ---------------------------------------------------------------------------
798// Nesting — which pane a wheel belongs to
799// ---------------------------------------------------------------------------
800
801/// Where a [`claim_wheel`] pane was before the wheel that is being dispatched.
802///
803/// Shaped like [`ScrollbarState`] and [`FollowState`], and owned by the view
804/// for the same reason: an element rebuilt every render cannot remember
805/// anything, and this has to outlive the frame it was written in.
806#[derive(Clone)]
807pub struct ClaimState(Rc<Cell<Point<Pixels>>>);
808
809impl Default for ClaimState {
810 fn default() -> Self {
811 Self::new()
812 }
813}
814
815impl ClaimState {
816 pub fn new() -> Self {
817 Self(Rc::new(Cell::new(point(px(0.0), px(0.0)))))
818 }
819}
820
821/// Let a pane keep the wheel it can act on, instead of passing it to the pane
822/// behind as well.
823///
824/// gpui's scroll listener neither stops propagation nor asks whether an
825/// ancestor scrolls too, so a wheel over a nested pane moves *both* — an output
826/// box inside a transcript scrolls itself and drags the transcript with it
827/// (user report). Every scrolling ancestor under the pointer does this, so the
828/// deeper the nesting the further the page jumps.
829///
830/// The question it asks is whether the pane *moved*, not whether it had room
831/// to. This listener runs after the element's own — gpui registers that one
832/// later and the bubble phase runs the list backwards — so `handle` already
833/// holds the post-scroll offset, and `state` is where it stood before. "Had
834/// room" is the same answer one notch too late, and gets the notch that lands
835/// exactly on the end wrong: the pane finishes its travel *and* the page jumps
836/// a full notch behind it.
837///
838/// Chained at the ends, not sealed: a pane with nowhere left to go hands the
839/// wheel to the page, so reaching the end of a short inner list does not strand
840/// it there and make the pointer move. A pane whose content fits never claims
841/// anything, for the same reason. For `overscroll-behavior: contain` — a pane
842/// that never lets a wheel past — stop unconditionally instead.
843///
844/// ```ignore
845/// scroll::claim_wheel(
846/// scroll::pane("output", Axes::Vertical).track_scroll(&self.scroll),
847/// &self.scroll,
848/// Axes::Vertical,
849/// &self.claim,
850/// )
851/// ```
852///
853/// `axes` is what the pane scrolls, and must be what [`pane`] was given: an
854/// axis left out here is one whose movement goes unnoticed, so the wheel is
855/// handed on and the ancestor moves too.
856pub fn claim_wheel<E: gpui::StatefulInteractiveElement>(
857 el: E,
858 handle: &ScrollHandle,
859 axes: Axes,
860 state: &ClaimState,
861) -> E {
862 let handle = handle.clone();
863 let state = state.0.clone();
864 // Where the pane stands as the frame is built, which is where it stands
865 // before anything this frame's listeners are handed. The listener writes it
866 // too: a wheel the pane could not act on produces no `notify` and so no
867 // render, and the reading below has to stay true across that gap.
868 state.set(travel(&handle, axes));
869 el.on_scroll_wheel(move |_, _, cx| {
870 let now = travel(&handle, axes);
871 if now != state.get() {
872 state.set(now);
873 cx.stop_propagation();
874 }
875 })
876}
877
878/// How far `handle` has visibly travelled along each of `axes`. Negative, as
879/// gpui counts it; an axis the pane does not scroll reads zero forever, so it
880/// can never be mistaken for movement.
881///
882/// Clamped here because gpui's scroll listener is not: it adds the raw delta
883/// and leaves the clamp to the next `paint`, so a pane held at its end keeps
884/// accumulating offset it will never show. Compared raw, every notch past the
885/// end reads as movement and the pane never lets go of the wheel.
886fn travel(handle: &ScrollHandle, axes: Axes) -> Point<Pixels> {
887 let (offset, max) = (handle.offset(), handle.max_offset());
888 let seen = |offset: Pixels, max: Pixels| offset.clamp(-max.max(px(0.0)), px(0.0));
889 point(
890 match axes.horizontal() {
891 true => seen(offset.x, max.x),
892 false => px(0.0),
893 },
894 match axes.vertical() {
895 true => seen(offset.y, max.y),
896 false => px(0.0),
897 },
898 )
899}
900
901// ---------------------------------------------------------------------------
902// Follow — a view pinned to the bottom of content that grows under it
903// ---------------------------------------------------------------------------
904
905/// How close to the bottom still counts as following. A wheel lands on
906/// fractional offsets and a re-layout can move the end by a hair; without slack
907/// a view would unpin itself for a rounding error nobody asked for.
908pub const FOLLOW_SLACK: Pixels = px(4.0);
909
910/// Whether `offset` is at the end of the scrollable range, within `slack`.
911///
912/// Both of gpui's conventions bite here, so: `max_offset` is the *overflow* and
913/// `offset` is **negative** going down, which makes the distance still to go
914/// `max_offset - |offset|`. Content that fits is always "at the bottom" — there
915/// is nowhere else to be, and answering `false` would unpin an empty log.
916pub fn at_bottom(max_offset: Pixels, offset: Pixels, slack: Pixels) -> bool {
917 if max_offset <= px(0.0) {
918 return true;
919 }
920 let travelled = offset.clamp(-max_offset, px(0.0)).abs();
921 max_offset - travelled <= slack
922}
923
924/// Whether a [`follow`] view is still pinned, and the overflow it last saw.
925///
926/// Shaped like [`ScrollbarState`] and for the same reason: it mutates through
927/// `&self`, so the element carries the whole behaviour without the view wiring
928/// a listener. Starts pinned — a transcript or a log opens on its newest line.
929#[derive(Clone)]
930pub struct FollowState(Rc<Cell<(bool, Pixels)>>);
931
932impl Default for FollowState {
933 fn default() -> Self {
934 Self(Rc::new(Cell::new((true, px(0.0)))))
935 }
936}
937
938impl FollowState {
939 pub fn new() -> Self {
940 Self::default()
941 }
942
943 /// Whether the view is following. An app shows its "jump to latest" affordance
944 /// on `!following()`, which is the only reason this is public.
945 pub fn following(&self) -> bool {
946 self.0.get().0
947 }
948
949 /// Re-pin. What that "jump to latest" button calls; the next frame does the
950 /// scrolling.
951 pub fn follow(&self) {
952 let (_, last) = self.0.get();
953 self.0.set((true, last));
954 }
955}
956
957/// Keep `handle` pinned to the bottom of its content while the user leaves it
958/// there, and get out of the way the moment they scroll up.
959///
960/// Drop it in beside [`scrollbar`], over the same container:
961///
962/// ```ignore
963/// div().relative()
964/// .child(scroll::pane("log", Axes::Vertical).size_full().track_scroll(&self.scroll).child(rows))
965/// .child(scroll::follow(&self.scroll, &self.follow))
966/// .child(scroll::scrollbar("log-bar", &self.scroll, &self.bar))
967/// ```
968///
969/// **Telling appended content from a user scroll is the whole problem**, and
970/// neither is an event this can subscribe to — both surface as the same handle
971/// reading differently than last frame. The overflow is what separates them: if
972/// it changed, the content grew and the pin is left as the user last set it; if
973/// it did not, the offset moved because the *user* moved it, and being at the
974/// end is what re-pins. So scrolling up releases, and scrolling back down
975/// re-attaches, with no gesture to hook.
976///
977/// The correction lands a frame late — the scrolling div was laid out with the
978/// old offset before this runs — which is why it asks for that frame. At a
979/// streaming cadence it is invisible, and it converges rather than spinning:
980/// once pinned and at the end, nothing is requested.
981pub fn follow(handle: &ScrollHandle, state: &FollowState) -> gpui::AnyElement {
982 let handle = handle.clone();
983 let state = state.clone();
984 canvas(
985 move |_, window, _| {
986 let max_offset = handle.max_offset().y;
987 let offset = handle.offset().y;
988 let (was_pinned, last_max) = state.0.get();
989
990 let pinned = if (max_offset - last_max).abs() > px(0.5) {
991 was_pinned
992 } else {
993 at_bottom(max_offset, offset, FOLLOW_SLACK)
994 };
995
996 if pinned && (offset + max_offset).abs() > px(0.5) {
997 handle.set_offset(point(handle.offset().x, -max_offset));
998 window.request_animation_frame();
999 }
1000 state.0.set((pinned, max_offset));
1001 },
1002 |_, _, _, _| {},
1003 )
1004 .absolute()
1005 .size_full()
1006 .into_any_element()
1007}
1008
1009// ---------------------------------------------------------------------------
1010// Drift — a pane that keeps moving while a drag is held at its edge
1011// ---------------------------------------------------------------------------
1012
1013/// How close to an edge a held drag starts the pane moving. Read off
1014/// `../desktop`'s board (2026-05): a third of a column, wide enough to reach
1015/// while aiming at a card and narrow enough to leave the middle still.
1016pub const DRIFT_EDGE: Pixels = px(96.0);
1017
1018/// How fast a pane travels with the pointer at the very edge, in pixels a
1019/// second. The same board's 22px per frame, said in a unit that does not
1020/// double on a 120Hz display.
1021pub const DRIFT_SPEED: f32 = 1320.0;
1022
1023/// The most one frame may travel, however late it ran. A frame dropped while
1024/// the pointer rests at an edge costs a pause, not a jump to the far end.
1025const DRIFT_STEP: Duration = Duration::from_millis(50);
1026
1027/// How far a pane should travel in a second, for a pointer at `pointer`
1028/// between edges `start` and `end`.
1029///
1030/// Signed the way gpui's offset is: positive travels back toward the start,
1031/// because the offset goes negative as a pane scrolls on. Zero everywhere but
1032/// within [`DRIFT_EDGE`] of an edge, where it ramps with proximity — easing
1033/// toward the edge eases the scroll — and holds at full speed once the pointer
1034/// is past it, so a card carried off the side of a board keeps it coming
1035/// instead of stopping dead at the boundary.
1036///
1037/// The ramp is capped at half the pane, so one narrower than two edges has a
1038/// still middle rather than a midpoint where the direction flips at half speed.
1039pub fn drift_velocity(pointer: Pixels, start: Pixels, end: Pixels) -> f32 {
1040 let edge = DRIFT_EDGE.as_f32().min((end - start).as_f32() / 2.0);
1041 if edge <= 0.0 {
1042 return 0.0;
1043 }
1044 let (from_start, from_end) = ((pointer - start).as_f32(), (end - pointer).as_f32());
1045 // The nearer edge, which is what decides the direction — and what keeps
1046 // the two ramps from summing where they overlap.
1047 let near = from_start.min(from_end);
1048 if near >= edge {
1049 return 0.0;
1050 }
1051 let ramp = 1.0 - near.max(0.0) / edge;
1052 match from_start < from_end {
1053 true => DRIFT_SPEED * ramp,
1054 false => -DRIFT_SPEED * ramp,
1055 }
1056}
1057
1058/// What lies past a drifting pane's edge, and so whether a pointer that has
1059/// crossed it is still aiming at the pane.
1060#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1061pub enum Beyond {
1062 /// Nothing the drag could be meant for — a board that fills the window.
1063 /// The pane holds at full speed for as long as the pointer is out there.
1064 Nothing,
1065 /// Another surface. The pane stops the moment the pointer leaves it,
1066 /// whichever edge it left by.
1067 Neighbour,
1068}
1069
1070/// How fast a pane of `bounds` drifts with the pointer at `pointer`, one
1071/// [`drift_velocity`] per axis [`Axes`] names.
1072///
1073/// Across an axis the pointer must be within the pane: without that, every
1074/// lane of a board would drift together on a drag that is only near one of
1075/// them. Along it, `beyond` decides.
1076pub fn pane_velocity(
1077 bounds: Bounds<Pixels>,
1078 pointer: Point<Pixels>,
1079 axes: Axes,
1080 beyond: Beyond,
1081) -> Point<f32> {
1082 if beyond == Beyond::Neighbour && !bounds.contains(&pointer) {
1083 return point(0.0, 0.0);
1084 }
1085 let mut velocity = point(0.0, 0.0);
1086 if axes.horizontal() && (bounds.top()..=bounds.bottom()).contains(&pointer.y) {
1087 velocity.x = drift_velocity(pointer.x, bounds.left(), bounds.right());
1088 }
1089 if axes.vertical() && (bounds.left()..=bounds.right()).contains(&pointer.x) {
1090 velocity.y = drift_velocity(pointer.y, bounds.top(), bounds.bottom());
1091 }
1092 velocity
1093}
1094
1095/// What one drifting pane remembers between frames.
1096#[derive(Clone, Copy, Default)]
1097struct Drift {
1098 /// Where the pointer was last seen carrying something this pane follows.
1099 aim: Option<Point<Pixels>>,
1100 /// When it last moved, and `None` whenever it is not moving — so a pane
1101 /// picking the gesture back up starts its clock rather than travelling the
1102 /// gap it stood still for.
1103 since: Option<Instant>,
1104}
1105
1106/// Where a drift was last aimed, and when it last moved.
1107///
1108/// Shaped like [`ScrollbarState`] and owned by the view for the same reason:
1109/// the element is rebuilt every frame and cannot remember where the pointer
1110/// was. One per pane — two panes sharing one would take turns reading each
1111/// other's clock.
1112#[derive(Clone, Default)]
1113pub struct DriftState(Rc<Cell<Drift>>);
1114
1115impl DriftState {
1116 pub fn new() -> Self {
1117 Self::default()
1118 }
1119
1120 /// Where the pointer is. Call it from the drag-move listener of the
1121 /// payload this pane should follow — that listener is typed, which is what
1122 /// keeps a board from drifting under somebody dragging a scrollbar thumb:
1123 ///
1124 /// ```ignore
1125 /// .on_drag_move(cx.listener(|this, event: &DragMoveEvent<CardDrag>, _, _| {
1126 /// this.drift.aim(event.event.position);
1127 /// }))
1128 /// ```
1129 ///
1130 /// Aimed rather than continuous: gpui reports a drag only while it moves,
1131 /// and a pointer parked at an edge is the case the whole thing exists for.
1132 pub fn aim(&self, pointer: Point<Pixels>) {
1133 let drift = self.0.get();
1134 self.0.set(Drift {
1135 aim: Some(pointer),
1136 ..drift
1137 });
1138 }
1139}
1140
1141/// Move `handle` while a drag is held near its edge, for as long as it is held
1142/// there.
1143///
1144/// Drop it in beside [`scrollbar`], over the same container, and feed it from
1145/// the drag-move listener — see [`DriftState::aim`]:
1146///
1147/// ```ignore
1148/// div().relative()
1149/// .child(scroll::pane("board", Axes::Horizontal).size_full().track_scroll(&self.scroll).child(lanes))
1150/// .child(scroll::drift(&self.scroll, &self.drift, Axes::Horizontal, Beyond::Nothing))
1151/// ```
1152///
1153/// Without it a board is only as wide as the window: a card cannot be carried
1154/// to a lane that is off screen, because reaching for one means letting go.
1155///
1156/// **The gesture ending is not an event this subscribes to.** gpui hands a
1157/// drop to whatever was under the pointer, and a release over nothing is not
1158/// delivered at all, so either would leave a pane drifting on a gesture that
1159/// is over. The drag going away is the signal instead, and it arrives however
1160/// the drag ended.
1161///
1162/// `beyond` is what the pane's edge gives onto, and decides whether a pointer
1163/// carried past it still drives the pane — see [`Beyond`] and
1164/// [`pane_velocity`].
1165///
1166/// Not motion in the [`motion`] sense and not reduced with it: nothing here
1167/// animates a property, the pane is being scrolled by a gesture the same way a
1168/// wheel scrolls it, and a reader who cannot reach the far lane has no gesture
1169/// left to make.
1170pub fn drift(
1171 handle: &ScrollHandle,
1172 state: &DriftState,
1173 axes: Axes,
1174 beyond: Beyond,
1175) -> gpui::AnyElement {
1176 let handle = handle.clone();
1177 let state = state.clone();
1178 canvas(
1179 move |_, window, cx: &mut App| {
1180 let drift = state.0.get();
1181 // Nothing aimed here, or the gesture that aimed it has ended.
1182 let Some(pointer) = drift.aim.filter(|_| cx.has_active_drag()) else {
1183 state.0.set(Drift::default());
1184 return;
1185 };
1186
1187 let velocity = pane_velocity(handle.bounds(), pointer, axes, beyond);
1188 // Aimed here but nowhere near an edge, or gone off to a
1189 // neighbour. The clock stops with it, so a drag wandering back to
1190 // the edge a second later starts a fresh drift rather than
1191 // travelling the second it stood still.
1192 if velocity.x == 0.0 && velocity.y == 0.0 {
1193 state.0.set(Drift {
1194 aim: Some(pointer),
1195 since: None,
1196 });
1197 return;
1198 }
1199
1200 let now = cx.background_executor().now();
1201 state.0.set(Drift {
1202 aim: Some(pointer),
1203 since: Some(now),
1204 });
1205 // The first frame of a drift is the one that starts the clock;
1206 // there is no interval yet to travel over.
1207 let Some(last) = drift.since else {
1208 window.request_animation_frame();
1209 return;
1210 };
1211
1212 let step = (now - last).min(DRIFT_STEP).as_secs_f32();
1213 let (offset, max) = (handle.offset(), handle.max_offset());
1214 let moved = point(
1215 (offset.x + px(velocity.x * step)).clamp(-max.x, px(0.0)),
1216 (offset.y + px(velocity.y * step)).clamp(-max.y, px(0.0)),
1217 );
1218 if moved == offset {
1219 // Held at an end that has nowhere left to go. Asking for
1220 // another frame here would spin at the display's rate for as
1221 // long as the drag is held; the next pointer move draws one
1222 // anyway, and that is the soonest this could have anything to
1223 // do.
1224 return;
1225 }
1226 handle.set_offset(moved);
1227 window.request_animation_frame();
1228 },
1229 |_, _, _, _| {},
1230 )
1231 .absolute()
1232 .size_full()
1233 .into_any_element()
1234}