Skip to main content

fc_ui/capabilities/scroll/
uniform_virtual_list.rs

1use std::cell::{Cell, RefCell};
2use std::cmp;
3use std::collections::HashMap;
4use std::ops::Range;
5use std::rc::Rc;
6
7use crate::capabilities::foundation::util::{AxisExt, PixelsExt};
8use crate::capabilities::scroll::scroll_container::{PhysicsScrollState, ScrollDirection};
9use gpui::{
10    div, point, px, size, Along, AnyElement, App, AvailableSpace, Axis, Bounds, Context, Div,
11    Edges, Element, ElementId, Entity, GlobalElementId, Hitbox, InteractiveElement, IntoElement,
12    ListSizingBehavior, Pixels, Point, Render, ScrollStrategy, Size, Stateful,
13    StatefulInteractiveElement, StyleRefinement, Styled, Window,
14};
15use smallvec::SmallVec;
16
17/// A `scroll_to` request recorded during element construction and applied in
18/// `prepaint`, once the viewport size for the frame is known.
19#[derive(Clone, Copy)]
20struct PendingScroll {
21    index: usize,
22    strategy: ScrollStrategy,
23}
24
25/// Largest legal scroll distance, mirroring GPUI's `Interactivity::clamp_scroll_position`.
26///
27/// The list layer must use the same formula as the scroll container it wraps.
28/// If the two disagree, the list paints a frame from an offset GPUI is about to
29/// reject, producing a visible jump on the next frame.
30///
31/// Callers must pass padding already snapped to the device-pixel grid
32/// (`Window::pixel_snap`), matching upstream's `clamp_scroll_position` after
33/// the phantom-scrollbar fix: layout snaps authored padding, so the recomputed
34/// value must be snapped too or a fitting container looks scrollable by a
35/// sub-pixel amount.
36fn scroll_max(
37    content_size: Size<Pixels>,
38    padding: Edges<Pixels>,
39    bounds_size: Size<Pixels>,
40) -> Size<Pixels> {
41    fn round_to_two_decimals(pixels: Pixels) -> Pixels {
42        const ROUNDING_FACTOR: f32 = 100.0;
43        (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
44    }
45
46    let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
47    (content_size + padding_size - bounds_size)
48        .map(round_to_two_decimals)
49        .max(&Size::default())
50}
51
52fn clamp_scroll_offset(offset: Point<Pixels>, scroll_max: Size<Pixels>) -> Point<Pixels> {
53    point(
54        offset.x.clamp(-scroll_max.width, px(0.)),
55        offset.y.clamp(-scroll_max.height, px(0.)),
56    )
57}
58
59/// Resolves a [`ScrollStrategy`] to a scroll distance along the list axis.
60///
61/// All arguments are extents along that axis, in the list's content coordinate
62/// space where `0` is the start of the first item. The result is clamped into
63/// `0..=max_scroll`, so items near either end resolve to the closest legal
64/// position and different strategies may legitimately agree there.
65fn scroll_target_for_strategy(
66    item_start: Pixels,
67    item_extent: Pixels,
68    viewport_extent: Pixels,
69    max_scroll: Pixels,
70    strategy: ScrollStrategy,
71) -> Pixels {
72    let target = match strategy {
73        ScrollStrategy::Top => item_start,
74        ScrollStrategy::Center => item_start + item_extent / 2.0 - viewport_extent / 2.0,
75        ScrollStrategy::Bottom => item_start + item_extent - viewport_extent,
76    };
77    target.max(px(0.)).min(max_scroll.max(px(0.)))
78}
79
80/// Resolve against the last completed layout. Deriving the viewport from the
81/// content and maximum offset preserves the padding already encoded by GPUI.
82fn target_from_laid_out_handle(
83    handle: &gpui::ScrollHandle,
84    axis: Axis,
85    content_extent: Pixels,
86    item_start: Pixels,
87    item_extent: Pixels,
88    strategy: ScrollStrategy,
89) -> Option<Pixels> {
90    if handle.bounds().size.along(axis) <= px(0.) {
91        return None;
92    }
93
94    let content_extent = content_extent.max(px(0.));
95    let max_scroll = handle
96        .max_offset()
97        .along(axis)
98        .max(px(0.))
99        .min(content_extent);
100    let viewport_extent = (content_extent - max_scroll).max(px(0.));
101    Some(scroll_target_for_strategy(
102        item_start,
103        item_extent,
104        viewport_extent,
105        max_scroll,
106        strategy,
107    ))
108}
109
110fn set_scroll_target(handle: &gpui::ScrollHandle, axis: Axis, target: Pixels) {
111    let offset = handle.offset().apply_along(axis, |_| -target);
112    handle.set_offset(offset);
113}
114
115pub struct UniformVirtualList {
116    id: ElementId,
117    axis: Axis,
118    item_count: usize,
119    item_extent: Pixels,
120    overscan: usize,
121    base: Stateful<Div>,
122    scroll_handle: gpui::ScrollHandle,
123    sizing_behavior: ListSizingBehavior,
124    renderer: Box<
125        dyn for<'a> Fn(Range<usize>, &'a mut Window, &'a mut App) -> SmallVec<[AnyElement; 64]>,
126    >,
127    on_visible_range: Option<Box<dyn Fn(Range<usize>, &mut Window, &mut App)>>,
128    near_end_threshold: Option<(f32, Rc<RefCell<bool>>, Box<dyn Fn(&mut Window, &mut App)>)>,
129    physics_state: Option<PhysicsScrollState>,
130    pending_scroll: Cell<Option<PendingScroll>>,
131}
132
133impl Styled for UniformVirtualList {
134    fn style(&mut self) -> &mut StyleRefinement {
135        self.base.style()
136    }
137}
138
139impl UniformVirtualList {
140    pub fn new<R: IntoElement + 'static>(
141        id: impl Into<ElementId>,
142        axis: Axis,
143        item_count: usize,
144        item_extent: Pixels,
145        renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
146    ) -> Self {
147        let id = id.into();
148        let renderer_boxed = move |range: Range<usize>, window: &mut Window, cx: &mut App| {
149            renderer(range, window, cx)
150                .into_iter()
151                .map(|r| r.into_any_element())
152                .collect::<SmallVec<[AnyElement; 64]>>()
153        };
154
155        Self {
156            id: id.clone(),
157            axis,
158            item_count,
159            item_extent,
160            overscan: 5,
161            base: div().id(id).size_full().overflow_scroll(),
162            scroll_handle: gpui::ScrollHandle::new(),
163            sizing_behavior: ListSizingBehavior::Auto,
164            renderer: Box::new(renderer_boxed),
165            on_visible_range: None,
166            near_end_threshold: None,
167            physics_state: None,
168            pending_scroll: Cell::new(None),
169        }
170    }
171
172    pub fn overscan(mut self, items: usize) -> Self {
173        self.overscan = items;
174        self
175    }
176
177    pub fn track_scroll(mut self, handle: &gpui::ScrollHandle) -> Self {
178        self.base = self.base.track_scroll(handle);
179        self.scroll_handle = handle.clone();
180        self
181    }
182
183    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
184        self.sizing_behavior = behavior;
185        self
186    }
187
188    pub fn on_visible_range(
189        mut self,
190        f: impl 'static + Fn(Range<usize>, &mut Window, &mut App),
191    ) -> Self {
192        self.on_visible_range = Some(Box::new(f));
193        self
194    }
195
196    pub fn on_near_end(
197        mut self,
198        threshold: f32,
199        f: impl 'static + Fn(&mut Window, &mut App),
200    ) -> Self {
201        self.near_end_threshold = Some((
202            threshold.clamp(0.0, 1.0),
203            Rc::new(RefCell::new(false)),
204            Box::new(f),
205        ));
206        self
207    }
208
209    /// Scroll `index` into view according to `strategy`.
210    ///
211    /// The item is always aligned to the strategy's position, even when it is
212    /// already visible, and any in-flight animated scroll is cancelled: the
213    /// latest command wins.
214    ///
215    /// When this handle has layout metrics, its offset is updated immediately.
216    /// The request is also resolved during the next `prepaint` so first-layout
217    /// calls and viewport changes use the current frame's exact geometry.
218    pub fn scroll_to(&self, index: usize, strategy: ScrollStrategy) {
219        if let Some(physics) = self.physics_state.as_ref() {
220            physics.stop();
221        }
222        self.pending_scroll
223            .set(Some(PendingScroll { index, strategy }));
224
225        if let Some(target) = self.immediate_target(index, strategy) {
226            set_scroll_target(&self.scroll_handle, self.axis, target);
227        }
228    }
229
230    /// Best-effort target from the last completed layout's metrics. Returns
231    /// `None` on the first frame for strategies that need the viewport;
232    /// `prepaint` resolves the request with exact geometry in that case.
233    fn immediate_target(&self, index: usize, strategy: ScrollStrategy) -> Option<Pixels> {
234        let index = index.min(self.item_count.saturating_sub(1));
235        let item_start = self.item_extent * index as f32;
236        target_from_laid_out_handle(
237            &self.scroll_handle,
238            self.axis,
239            self.item_extent * self.item_count as f32,
240            item_start,
241            self.item_extent,
242            strategy,
243        )
244        .or(match strategy {
245            ScrollStrategy::Top => Some(item_start),
246            ScrollStrategy::Center | ScrollStrategy::Bottom => None,
247        })
248    }
249
250    pub fn with_physics(mut self, state: &PhysicsScrollState) -> Self {
251        let physics_c = state.clone();
252        let handle_c = self.scroll_handle.clone();
253        let dir = if self.axis.is_vertical() {
254            ScrollDirection::Vertical
255        } else {
256            ScrollDirection::Horizontal
257        };
258        self.base = self.base.on_scroll_wheel(move |event, window, _cx| {
259            physics_c.handle_scroll_event(&handle_c, dir, event, window);
260        });
261        self.physics_state = Some(state.clone());
262        self
263    }
264
265    /// Scroll to `index` immediately, animating when physics is configured.
266    pub fn scroll_to_animated(&self, index: usize, window: &Window) {
267        // `Top` always resolves, with or without layout metrics.
268        let target = self
269            .immediate_target(index, ScrollStrategy::Top)
270            .expect("ScrollStrategy::Top always resolves");
271
272        if let Some(physics) = self.physics_state.as_ref() {
273            self.pending_scroll.set(None);
274            if self.axis.is_vertical() {
275                physics.scroll_to_y_animated(target.as_f32(), &self.scroll_handle, window);
276            } else {
277                physics.scroll_to_x_animated(target.as_f32(), &self.scroll_handle, window);
278            }
279        } else {
280            self.scroll_to(index, ScrollStrategy::Top);
281        }
282    }
283
284    /// Consume a pending `scroll_to` and return the offset the frame should use.
285    fn apply_pending_scroll(
286        &self,
287        offset: Point<Pixels>,
288        viewport_extent: Pixels,
289        max_scroll: Size<Pixels>,
290    ) -> Point<Pixels> {
291        let Some(pending) = self.pending_scroll.take() else {
292            return offset;
293        };
294        let index = pending.index.min(self.item_count.saturating_sub(1));
295        let target = scroll_target_for_strategy(
296            self.item_extent * index as f32,
297            self.item_extent,
298            viewport_extent,
299            max_scroll.along(self.axis),
300            pending.strategy,
301        );
302        offset.apply_along(self.axis, |_| -target)
303    }
304}
305
306pub struct UniformFrameState {
307    items: SmallVec<[AnyElement; 32]>,
308}
309
310impl IntoElement for UniformVirtualList {
311    type Element = Self;
312    fn into_element(self) -> Self::Element {
313        self
314    }
315}
316
317impl Element for UniformVirtualList {
318    type RequestLayoutState = UniformFrameState;
319    type PrepaintState = Option<Hitbox>;
320
321    fn id(&self) -> Option<ElementId> {
322        Some(self.id.clone())
323    }
324
325    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
326        None
327    }
328
329    fn request_layout(
330        &mut self,
331        global_id: Option<&GlobalElementId>,
332        inspector_id: Option<&gpui::InspectorElementId>,
333        window: &mut Window,
334        cx: &mut App,
335    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
336        let axis = self.axis;
337        let item_count = self.item_count;
338        let item_extent = self.item_extent;
339        let behavior = self.sizing_behavior;
340
341        let layout_id = self.base.interactivity().request_layout(
342            global_id,
343            inspector_id,
344            window,
345            cx,
346            move |style, window: &mut Window, cx: &mut App| match behavior {
347                ListSizingBehavior::Infer => {
348                    window.request_measured_layout(style, move |_k, available, _, _| {
349                        let mut sz = Size::default();
350                        if axis.is_horizontal() {
351                            sz.width = match available.width {
352                                AvailableSpace::Definite(w) => w,
353                                _ => px(item_count as f32 * item_extent.as_f32()),
354                            };
355                            sz.height = match available.height {
356                                AvailableSpace::Definite(h) => h,
357                                _ => px(0.),
358                            };
359                        } else {
360                            sz.width = match available.width {
361                                AvailableSpace::Definite(w) => w,
362                                _ => px(0.),
363                            };
364                            sz.height = match available.height {
365                                AvailableSpace::Definite(h) => h,
366                                _ => px(item_count as f32 * item_extent.as_f32()),
367                            };
368                        }
369                        sz
370                    })
371                }
372                ListSizingBehavior::Auto => window.request_layout(style, None, cx),
373            },
374        );
375
376        (
377            layout_id,
378            UniformFrameState {
379                items: SmallVec::new(),
380            },
381        )
382    }
383
384    fn prepaint(
385        &mut self,
386        global_id: Option<&GlobalElementId>,
387        inspector_id: Option<&gpui::InspectorElementId>,
388        bounds: Bounds<Pixels>,
389        layout: &mut Self::RequestLayoutState,
390        window: &mut Window,
391        cx: &mut App,
392    ) -> Self::PrepaintState {
393        let style = self
394            .base
395            .interactivity()
396            .compute_style(global_id, None, window, cx);
397        let border = style.border_widths.to_pixels(window.rem_size());
398        // Layout snaps authored padding to the device-pixel grid, so every
399        // recomputation of it (content bounds, scroll max) must snap too.
400        let padding = style
401            .padding
402            .to_pixels(bounds.size.into(), window.rem_size())
403            .map(|edge| window.pixel_snap(*edge));
404
405        let content_bounds = Bounds::from_corners(
406            bounds.origin + point(border.left + padding.left, border.top + padding.top),
407            bounds.bottom_right()
408                - point(border.right + padding.right, border.bottom + padding.bottom),
409        );
410
411        let viewport_len = content_bounds.size.along(self.axis);
412        let extent = self.item_extent;
413        let total = px(self.item_count as f32 * extent.as_f32());
414
415        let content_size = if self.axis.is_horizontal() {
416            size(total, content_bounds.size.height)
417        } else {
418            size(content_bounds.size.width, total)
419        };
420        let max_scroll = scroll_max(content_size, padding, bounds.size);
421
422        // Resolve any pending `scroll_to` and clamp before the visible range is
423        // derived, so this frame's range, this frame's item positions and the
424        // offset GPUI will settle on all agree.
425        let offset =
426            self.apply_pending_scroll(self.scroll_handle.offset(), viewport_len, max_scroll);
427        let offset = clamp_scroll_offset(offset, max_scroll);
428        self.scroll_handle.set_offset(offset);
429
430        let base = -offset.along(self.axis);
431        let first = if extent.as_f32() > 0.0 {
432            (base.as_f32() / extent.as_f32()).floor().max(0.0) as usize
433        } else {
434            0
435        };
436        let last = if extent.as_f32() > 0.0 {
437            ((base + viewport_len).as_f32() / extent.as_f32())
438                .ceil()
439                .max(0.0) as usize
440        } else {
441            0
442        };
443
444        let start = first.saturating_sub(self.overscan);
445        let mut end = cmp::min(last + self.overscan, self.item_count);
446        if end == 0 {
447            end = cmp::min(self.item_count, self.overscan);
448        }
449
450        let visible = start..end;
451
452        if let Some(cb) = &self.on_visible_range {
453            cb(visible.clone(), window, cx);
454        }
455
456        if let Some((threshold, fired, cb)) = &self.near_end_threshold {
457            let progress = if self.item_count == 0 {
458                0.0
459            } else {
460                visible.end as f32 / self.item_count as f32
461            };
462            let mut was_fired = fired.borrow_mut();
463            if progress >= *threshold && !*was_fired {
464                *was_fired = true;
465                cb(window, cx);
466            }
467            if progress < *threshold {
468                *was_fired = false;
469            }
470        }
471
472        let items = (self.renderer)(visible.clone(), window, cx);
473
474        self.base.interactivity().prepaint(
475            global_id,
476            inspector_id,
477            bounds,
478            content_size,
479            window,
480            cx,
481            |_style, _, hitbox, window, cx| {
482                let available = match self.axis {
483                    Axis::Horizontal => size(
484                        AvailableSpace::Definite(extent),
485                        AvailableSpace::Definite(content_bounds.size.height),
486                    ),
487                    Axis::Vertical => size(
488                        AvailableSpace::Definite(content_bounds.size.width),
489                        AvailableSpace::Definite(extent),
490                    ),
491                };
492
493                for (mut item, ix) in items.into_iter().zip(visible) {
494                    let item_origin = match self.axis {
495                        Axis::Horizontal => {
496                            content_bounds.origin
497                                + point(px(ix as f32 * extent.as_f32()) + offset.x, offset.y)
498                        }
499                        Axis::Vertical => {
500                            content_bounds.origin
501                                + point(offset.x, px(ix as f32 * extent.as_f32()) + offset.y)
502                        }
503                    };
504                    item.layout_as_root(available, window, cx);
505                    item.prepaint_at(item_origin, window, cx);
506                    layout.items.push(item);
507                }
508
509                hitbox
510            },
511        )
512    }
513
514    fn paint(
515        &mut self,
516        global_id: Option<&GlobalElementId>,
517        inspector_id: Option<&gpui::InspectorElementId>,
518        bounds: Bounds<Pixels>,
519        layout: &mut Self::RequestLayoutState,
520        hitbox: &mut Self::PrepaintState,
521        window: &mut Window,
522        cx: &mut App,
523    ) {
524        self.base.interactivity().paint(
525            global_id,
526            inspector_id,
527            bounds,
528            hitbox.as_ref(),
529            window,
530            cx,
531            |_, window, cx| {
532                for item in &mut layout.items {
533                    item.paint(window, cx);
534                }
535            },
536        )
537    }
538}
539
540pub trait ItemExtentProvider {
541    /// Return an item's extent. The list snapshots each value once during
542    /// construction; non-finite and negative values are treated as zero.
543    fn extent(&self, index: usize) -> Pixels;
544}
545
546const CHUNK_SIZE: usize = 1024;
547
548/// Per-item layout budget used when measuring variable-height items.
549/// Unrelated to CHUNK_SIZE (an item-count granularity): decoupled so the two
550/// can be tuned independently.
551const ITEM_LAYOUT_BUDGET: Pixels = px(1024.0);
552
553struct ChunkedExtents<P: ItemExtentProvider> {
554    provider: P,
555    item_count: usize,
556    item_extents: Vec<Pixels>,
557    chunk_totals: Vec<Pixels>,
558    chunk_offsets: Vec<Pixels>,
559    intra_prefix: HashMap<usize, Rc<Vec<Pixels>>>,
560}
561
562impl<P: ItemExtentProvider> ChunkedExtents<P> {
563    fn new(provider: P, item_count: usize) -> Self {
564        let chunk_count = item_count.div_ceil(CHUNK_SIZE);
565        Self {
566            provider,
567            item_count,
568            item_extents: Vec::new(),
569            chunk_totals: vec![px(0.0); chunk_count],
570            chunk_offsets: vec![px(0.0); chunk_count + 1],
571            intra_prefix: HashMap::new(),
572        }
573    }
574
575    fn initialize_totals(&mut self) {
576        if self.item_count == 0 {
577            return;
578        }
579        if self.item_extents.is_empty() {
580            self.item_extents = (0..self.item_count)
581                .map(|index| Self::sanitize_extent(self.provider.extent(index)))
582                .collect();
583        }
584
585        let chunk_count = self.chunk_totals.len();
586        for c in 0..chunk_count {
587            let start = c * CHUNK_SIZE;
588            let end = ((c + 1) * CHUNK_SIZE).min(self.item_count);
589            let sum = self.item_extents[start..end]
590                .iter()
591                .map(|extent| extent.as_f32())
592                .sum();
593            self.chunk_totals[c] = px(sum);
594        }
595        let mut accum = 0.0;
596        self.chunk_offsets[0] = px(0.0);
597        for c in 0..chunk_count {
598            accum += self.chunk_totals[c].as_f32();
599            self.chunk_offsets[c + 1] = px(accum);
600        }
601    }
602
603    fn sanitize_extent(extent: Pixels) -> Pixels {
604        let value = extent.as_f32();
605        if value.is_finite() && value >= 0.0 {
606            extent
607        } else {
608            px(0.0)
609        }
610    }
611
612    fn total_extent(&self) -> Pixels {
613        if self.chunk_offsets.is_empty() {
614            return px(0.0);
615        }
616        *self.chunk_offsets.last().unwrap()
617    }
618
619    fn ensure_intra_prefix(&mut self, chunk_index: usize) -> Rc<Vec<Pixels>> {
620        if let Some(v) = self.intra_prefix.get(&chunk_index) {
621            return v.clone();
622        }
623        let start = chunk_index * CHUNK_SIZE;
624        let end = ((chunk_index + 1) * CHUNK_SIZE).min(self.item_count);
625        let mut origins = Vec::with_capacity(end - start);
626        let mut sum = 0.0;
627        for extent in &self.item_extents[start..end] {
628            origins.push(px(sum));
629            sum += extent.as_f32();
630        }
631        let rc = Rc::new(origins);
632        self.intra_prefix.insert(chunk_index, rc.clone());
633        rc
634    }
635
636    fn find_index_for_offset(&mut self, offset: Pixels) -> usize {
637        if self.item_count == 0 {
638            return 0;
639        }
640        let target = offset.as_f32();
641        let mut lo = 0usize;
642        let mut hi = self.chunk_offsets.len() - 1;
643        while lo < hi {
644            let mid = (lo + hi) / 2;
645            if self.chunk_offsets[mid].as_f32() <= target {
646                lo = mid + 1;
647            } else {
648                hi = mid;
649            }
650        }
651        let chunk = lo
652            .saturating_sub(1)
653            .min(self.chunk_totals.len().saturating_sub(1));
654        let chunk_base = self.chunk_offsets[chunk].as_f32();
655        let within = target - chunk_base;
656        let intra = self.ensure_intra_prefix(chunk);
657        let mut lo_i = 0usize;
658        let mut hi_i = intra.len();
659        while lo_i < hi_i {
660            let mid = (lo_i + hi_i) / 2;
661            if intra[mid].as_f32() <= within {
662                lo_i = mid + 1;
663            } else {
664                hi_i = mid;
665            }
666        }
667        let idx_in_chunk = lo_i.saturating_sub(1).min(intra.len().saturating_sub(1));
668        (chunk * CHUNK_SIZE + idx_in_chunk).min(self.item_count.saturating_sub(1))
669    }
670
671    fn item_origin(&mut self, index: usize) -> Pixels {
672        if self.item_count == 0 {
673            return px(0.0);
674        }
675        let chunk = index / CHUNK_SIZE;
676        let intra_ix = index % CHUNK_SIZE;
677        let intra = self.ensure_intra_prefix(chunk);
678        self.chunk_offsets[chunk] + intra[intra_ix]
679    }
680}
681
682pub struct VariableVirtualList<P: ItemExtentProvider> {
683    id: ElementId,
684    axis: Axis,
685    overscan: usize,
686    base: Stateful<Div>,
687    scroll_handle: gpui::ScrollHandle,
688    sizing_behavior: ListSizingBehavior,
689    engine: ChunkedExtents<P>,
690    renderer: Box<
691        dyn for<'a> Fn(Range<usize>, &'a mut Window, &'a mut App) -> SmallVec<[AnyElement; 64]>,
692    >,
693    on_visible_range: Option<Box<dyn Fn(Range<usize>, &mut Window, &mut App)>>,
694    near_end_threshold: Option<(f32, Rc<RefCell<bool>>, Box<dyn Fn(&mut Window, &mut App)>)>,
695    physics_state: Option<PhysicsScrollState>,
696    pending_scroll: Cell<Option<PendingScroll>>,
697}
698
699impl<P: ItemExtentProvider> Styled for VariableVirtualList<P> {
700    fn style(&mut self) -> &mut StyleRefinement {
701        self.base.style()
702    }
703}
704
705impl<P: ItemExtentProvider + 'static> VariableVirtualList<P> {
706    pub fn new<R: IntoElement + 'static>(
707        id: impl Into<ElementId>,
708        axis: Axis,
709        item_count: usize,
710        provider: P,
711        renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
712    ) -> Self {
713        let id = id.into();
714        let renderer_boxed = move |range: Range<usize>, window: &mut Window, cx: &mut App| {
715            renderer(range, window, cx)
716                .into_iter()
717                .map(|r| r.into_any_element())
718                .collect::<SmallVec<[AnyElement; 64]>>()
719        };
720
721        let mut engine = ChunkedExtents::new(provider, item_count);
722        engine.initialize_totals();
723
724        Self {
725            id: id.clone(),
726            axis,
727            overscan: 5,
728            base: div().id(id).size_full().overflow_scroll(),
729            scroll_handle: gpui::ScrollHandle::new(),
730            sizing_behavior: ListSizingBehavior::Auto,
731            engine,
732            renderer: Box::new(renderer_boxed),
733            on_visible_range: None,
734            near_end_threshold: None,
735            physics_state: None,
736            pending_scroll: Cell::new(None),
737        }
738    }
739
740    pub fn overscan(mut self, items: usize) -> Self {
741        self.overscan = items;
742        self
743    }
744    pub fn track_scroll(mut self, handle: &gpui::ScrollHandle) -> Self {
745        self.base = self.base.track_scroll(handle);
746        self.scroll_handle = handle.clone();
747        self
748    }
749    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
750        self.sizing_behavior = behavior;
751        self
752    }
753
754    pub fn on_visible_range(
755        mut self,
756        f: impl 'static + Fn(Range<usize>, &mut Window, &mut App),
757    ) -> Self {
758        self.on_visible_range = Some(Box::new(f));
759        self
760    }
761
762    pub fn on_near_end(
763        mut self,
764        threshold: f32,
765        f: impl 'static + Fn(&mut Window, &mut App),
766    ) -> Self {
767        self.near_end_threshold = Some((
768            threshold.clamp(0.0, 1.0),
769            Rc::new(RefCell::new(false)),
770            Box::new(f),
771        ));
772        self
773    }
774
775    /// Scroll `index` into view according to `strategy`.
776    ///
777    /// The item is always aligned to the strategy's position, even when it is
778    /// already visible, and any in-flight animated scroll is cancelled: the
779    /// latest command wins.
780    ///
781    /// When this handle has layout metrics, its offset is updated immediately.
782    /// The request is also resolved during the next `prepaint` so first-layout
783    /// calls and viewport changes use the current frame's exact geometry.
784    pub fn scroll_to(&mut self, index: usize, strategy: ScrollStrategy) {
785        if let Some(physics) = self.physics_state.as_ref() {
786            physics.stop();
787        }
788        self.pending_scroll
789            .set(Some(PendingScroll { index, strategy }));
790
791        if let Some(target) = self.immediate_target(index, strategy) {
792            set_scroll_target(&self.scroll_handle, self.axis, target);
793        }
794    }
795
796    /// Best-effort target from the last completed layout's metrics. Returns
797    /// `None` for empty lists and, on the first frame, for strategies that
798    /// need the viewport; `prepaint` resolves those with exact geometry.
799    fn immediate_target(&mut self, index: usize, strategy: ScrollStrategy) -> Option<Pixels> {
800        if self.engine.item_count == 0 {
801            return None;
802        }
803        let index = index.min(self.engine.item_count - 1);
804        let item_start = self.engine.item_origin(index);
805        target_from_laid_out_handle(
806            &self.scroll_handle,
807            self.axis,
808            self.engine.total_extent(),
809            item_start,
810            self.engine.item_extents[index],
811            strategy,
812        )
813        .or(match strategy {
814            ScrollStrategy::Top => Some(item_start),
815            ScrollStrategy::Center | ScrollStrategy::Bottom => None,
816        })
817    }
818
819    pub fn with_physics(mut self, state: &PhysicsScrollState) -> Self {
820        let physics_c = state.clone();
821        let handle_c = self.scroll_handle.clone();
822        let dir = if self.axis.is_vertical() {
823            ScrollDirection::Vertical
824        } else {
825            ScrollDirection::Horizontal
826        };
827        self.base = self.base.on_scroll_wheel(move |event, window, _cx| {
828            physics_c.handle_scroll_event(&handle_c, dir, event, window);
829        });
830        self.physics_state = Some(state.clone());
831        self
832    }
833
834    /// Scroll to `index` immediately, animating when physics is configured.
835    pub fn scroll_to_animated(&mut self, index: usize, window: &Window) {
836        if self.engine.item_count == 0 {
837            return;
838        }
839        // `Top` always resolves, with or without layout metrics.
840        let target = self
841            .immediate_target(index, ScrollStrategy::Top)
842            .expect("ScrollStrategy::Top always resolves");
843
844        if let Some(physics) = self.physics_state.as_ref() {
845            self.pending_scroll.set(None);
846            if self.axis.is_vertical() {
847                physics.scroll_to_y_animated(target.as_f32(), &self.scroll_handle, window);
848            } else {
849                physics.scroll_to_x_animated(target.as_f32(), &self.scroll_handle, window);
850            }
851        } else {
852            self.scroll_to(index, ScrollStrategy::Top);
853        }
854    }
855
856    /// Consume a pending `scroll_to` and return the offset the frame should use.
857    fn apply_pending_scroll(
858        &mut self,
859        offset: Point<Pixels>,
860        viewport_extent: Pixels,
861        max_scroll: Size<Pixels>,
862    ) -> Point<Pixels> {
863        let Some(pending) = self.pending_scroll.take() else {
864            return offset;
865        };
866        if self.engine.item_count == 0 {
867            return offset;
868        }
869        let index = pending.index.min(self.engine.item_count - 1);
870        let target = scroll_target_for_strategy(
871            self.engine.item_origin(index),
872            self.engine.item_extents[index],
873            viewport_extent,
874            max_scroll.along(self.axis),
875            pending.strategy,
876        );
877        offset.apply_along(self.axis, |_| -target)
878    }
879}
880
881pub struct VariableFrameState {
882    items: SmallVec<[AnyElement; 32]>,
883}
884
885impl<P: ItemExtentProvider + 'static> IntoElement for VariableVirtualList<P> {
886    type Element = Self;
887    fn into_element(self) -> Self::Element {
888        self
889    }
890}
891
892impl<P: ItemExtentProvider + 'static> Element for VariableVirtualList<P> {
893    type RequestLayoutState = VariableFrameState;
894    type PrepaintState = Option<Hitbox>;
895
896    fn id(&self) -> Option<ElementId> {
897        Some(self.id.clone())
898    }
899    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
900        None
901    }
902
903    fn request_layout(
904        &mut self,
905        global_id: Option<&GlobalElementId>,
906        inspector_id: Option<&gpui::InspectorElementId>,
907        window: &mut Window,
908        cx: &mut App,
909    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
910        let axis = self.axis;
911        let behavior = self.sizing_behavior;
912        let engine_total = self.engine.total_extent();
913
914        let layout_id = self.base.interactivity().request_layout(
915            global_id,
916            inspector_id,
917            window,
918            cx,
919            move |style, window: &mut Window, cx: &mut App| match behavior {
920                ListSizingBehavior::Infer => {
921                    window.request_measured_layout(style, move |_k, available, _, _| {
922                        let mut sz = Size::default();
923                        if axis.is_horizontal() {
924                            sz.width = match available.width {
925                                AvailableSpace::Definite(w) => w,
926                                _ => engine_total,
927                            };
928                            sz.height = match available.height {
929                                AvailableSpace::Definite(h) => h,
930                                _ => px(0.),
931                            };
932                        } else {
933                            sz.width = match available.width {
934                                AvailableSpace::Definite(w) => w,
935                                _ => px(0.),
936                            };
937                            sz.height = match available.height {
938                                AvailableSpace::Definite(h) => h,
939                                _ => engine_total,
940                            };
941                        }
942                        sz
943                    })
944                }
945                ListSizingBehavior::Auto => window.request_layout(style, None, cx),
946            },
947        );
948        (
949            layout_id,
950            VariableFrameState {
951                items: SmallVec::new(),
952            },
953        )
954    }
955
956    fn prepaint(
957        &mut self,
958        global_id: Option<&GlobalElementId>,
959        inspector_id: Option<&gpui::InspectorElementId>,
960        bounds: Bounds<Pixels>,
961        layout: &mut Self::RequestLayoutState,
962        window: &mut Window,
963        cx: &mut App,
964    ) -> Self::PrepaintState {
965        let style = self
966            .base
967            .interactivity()
968            .compute_style(global_id, None, window, cx);
969        let border = style.border_widths.to_pixels(window.rem_size());
970        // Layout snaps authored padding to the device-pixel grid, so every
971        // recomputation of it (content bounds, scroll max) must snap too.
972        let padding = style
973            .padding
974            .to_pixels(bounds.size.into(), window.rem_size())
975            .map(|edge| window.pixel_snap(*edge));
976
977        let content_bounds = Bounds::from_corners(
978            bounds.origin + point(border.left + padding.left, border.top + padding.top),
979            bounds.bottom_right()
980                - point(border.right + padding.right, border.bottom + padding.bottom),
981        );
982
983        let viewport_len = content_bounds.size.along(self.axis);
984        let total = self.engine.total_extent();
985
986        let content_size = if self.axis.is_horizontal() {
987            size(total, content_bounds.size.height)
988        } else {
989            size(content_bounds.size.width, total)
990        };
991        let max_scroll = scroll_max(content_size, padding, bounds.size);
992
993        // Resolve any pending `scroll_to` and clamp before the visible range is
994        // derived, so this frame's range, this frame's item positions and the
995        // offset GPUI will settle on all agree.
996        let offset =
997            self.apply_pending_scroll(self.scroll_handle.offset(), viewport_len, max_scroll);
998        let offset = clamp_scroll_offset(offset, max_scroll);
999        self.scroll_handle.set_offset(offset);
1000
1001        let start_px = -offset.along(self.axis);
1002        let end_px = start_px + viewport_len;
1003
1004        let mut start_ix = self.engine.find_index_for_offset(start_px.max(px(0.)));
1005        start_ix = start_ix.saturating_sub(self.overscan);
1006
1007        let mut end_ix = self.engine.find_index_for_offset(end_px.max(px(0.)));
1008        end_ix = (end_ix + 1 + self.overscan).min(self.engine.item_count);
1009
1010        let visible = start_ix..end_ix;
1011
1012        if let Some(cb) = &self.on_visible_range {
1013            cb(visible.clone(), window, cx);
1014        }
1015        if let Some((threshold, fired, cb)) = &self.near_end_threshold {
1016            let progress = if self.engine.item_count == 0 {
1017                0.0
1018            } else {
1019                visible.end as f32 / self.engine.item_count as f32
1020            };
1021            let mut was_fired = fired.borrow_mut();
1022            if progress >= *threshold && !*was_fired {
1023                *was_fired = true;
1024                cb(window, cx);
1025            }
1026            if progress < *threshold {
1027                *was_fired = false;
1028            }
1029        }
1030
1031        let items = (self.renderer)(visible.clone(), window, cx);
1032
1033        self.base.interactivity().prepaint(
1034            global_id,
1035            inspector_id,
1036            bounds,
1037            content_size,
1038            window,
1039            cx,
1040            |_style, _, hitbox, window, cx| {
1041                for (mut item, ix) in items.into_iter().zip(visible) {
1042                    let origin_along = self.engine.item_origin(ix);
1043                    let item_origin = match self.axis {
1044                        Axis::Horizontal => {
1045                            content_bounds.origin + point(origin_along + offset.x, offset.y)
1046                        }
1047                        Axis::Vertical => {
1048                            content_bounds.origin + point(offset.x, origin_along + offset.y)
1049                        }
1050                    };
1051
1052                    let available = match self.axis {
1053                        Axis::Horizontal => size(
1054                            AvailableSpace::Definite(ITEM_LAYOUT_BUDGET),
1055                            AvailableSpace::Definite(content_bounds.size.height),
1056                        ),
1057                        Axis::Vertical => size(
1058                            AvailableSpace::Definite(content_bounds.size.width),
1059                            AvailableSpace::Definite(ITEM_LAYOUT_BUDGET),
1060                        ),
1061                    };
1062
1063                    item.layout_as_root(available, window, cx);
1064                    item.prepaint_at(item_origin, window, cx);
1065                    layout.items.push(item);
1066                }
1067                hitbox
1068            },
1069        )
1070    }
1071
1072    fn paint(
1073        &mut self,
1074        global_id: Option<&GlobalElementId>,
1075        inspector_id: Option<&gpui::InspectorElementId>,
1076        bounds: Bounds<Pixels>,
1077        layout: &mut Self::RequestLayoutState,
1078        hitbox: &mut Self::PrepaintState,
1079        window: &mut Window,
1080        cx: &mut App,
1081    ) {
1082        self.base.interactivity().paint(
1083            global_id,
1084            inspector_id,
1085            bounds,
1086            hitbox.as_ref(),
1087            window,
1088            cx,
1089            |_, window, cx| {
1090                for item in &mut layout.items {
1091                    item.paint(window, cx);
1092                }
1093            },
1094        )
1095    }
1096}
1097
1098pub fn vlist_uniform<R: IntoElement + 'static>(
1099    id: impl Into<ElementId>,
1100    item_count: usize,
1101    item_extent: Pixels,
1102    renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
1103) -> UniformVirtualList {
1104    UniformVirtualList::new(id, Axis::Vertical, item_count, item_extent, renderer)
1105}
1106
1107pub fn hlist_uniform<R: IntoElement + 'static>(
1108    id: impl Into<ElementId>,
1109    item_count: usize,
1110    item_extent: Pixels,
1111    renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
1112) -> UniformVirtualList {
1113    UniformVirtualList::new(id, Axis::Horizontal, item_count, item_extent, renderer)
1114}
1115
1116pub fn vlist_variable<R: IntoElement + 'static, P: ItemExtentProvider + 'static>(
1117    id: impl Into<ElementId>,
1118    item_count: usize,
1119    provider: P,
1120    renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
1121) -> VariableVirtualList<P> {
1122    VariableVirtualList::new(id, Axis::Vertical, item_count, provider, renderer)
1123}
1124
1125pub fn hlist_variable<R: IntoElement + 'static, P: ItemExtentProvider + 'static>(
1126    id: impl Into<ElementId>,
1127    item_count: usize,
1128    provider: P,
1129    renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
1130) -> VariableVirtualList<P> {
1131    VariableVirtualList::new(id, Axis::Horizontal, item_count, provider, renderer)
1132}
1133
1134pub fn vlist_uniform_view<R, V>(
1135    view: Entity<V>,
1136    id: impl Into<ElementId>,
1137    item_count: usize,
1138    item_extent: Pixels,
1139    f: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
1140) -> UniformVirtualList
1141where
1142    R: IntoElement,
1143    V: Render,
1144{
1145    let id: ElementId = id.into();
1146    let render_range = move |visible_range: Range<usize>, window: &mut Window, cx: &mut App| {
1147        view.update(cx, |this, cx| {
1148            f(this, visible_range, window, cx)
1149                .into_iter()
1150                .map(|component| component.into_any_element())
1151                .collect::<SmallVec<[AnyElement; 64]>>()
1152        })
1153    };
1154
1155    UniformVirtualList::new(
1156        id,
1157        Axis::Vertical,
1158        item_count,
1159        item_extent,
1160        move |range, window, cx| {
1161            render_range(range, window, cx)
1162                .into_iter()
1163                .collect::<Vec<_>>()
1164        },
1165    )
1166}
1167
1168#[cfg(test)]
1169mod tests {
1170    use super::{scroll_target_for_strategy, ChunkedExtents, ItemExtentProvider};
1171    use gpui::{px, Pixels, ScrollStrategy};
1172    use std::{cell::Cell, rc::Rc};
1173
1174    struct CountingProvider {
1175        calls: Rc<Cell<usize>>,
1176        extents: Vec<f32>,
1177    }
1178
1179    impl ItemExtentProvider for CountingProvider {
1180        fn extent(&self, index: usize) -> Pixels {
1181            self.calls.set(self.calls.get() + 1);
1182            px(self.extents[index])
1183        }
1184    }
1185
1186    #[test]
1187    fn variable_extents_are_snapshotted_once_and_sanitized() {
1188        let calls = Rc::new(Cell::new(0));
1189        let mut extents = ChunkedExtents::new(
1190            CountingProvider {
1191                calls: calls.clone(),
1192                extents: vec![10.0, f32::NAN, -5.0, 20.0],
1193            },
1194            4,
1195        );
1196
1197        extents.initialize_totals();
1198        let prefix = extents.ensure_intra_prefix(0);
1199
1200        assert_eq!(calls.get(), 4);
1201        assert_eq!(extents.total_extent(), px(30.0));
1202        assert_eq!(
1203            prefix.as_ref(),
1204            &vec![px(0.0), px(10.0), px(10.0), px(10.0)]
1205        );
1206    }
1207
1208    #[test]
1209    fn strategies_resolve_to_distinct_middle_positions() {
1210        let item_start = px(200.);
1211        let item_extent = px(20.);
1212        let viewport_extent = px(100.);
1213        let max_scroll = px(300.);
1214
1215        assert_eq!(
1216            scroll_target_for_strategy(
1217                item_start,
1218                item_extent,
1219                viewport_extent,
1220                max_scroll,
1221                ScrollStrategy::Top,
1222            ),
1223            px(200.)
1224        );
1225        assert_eq!(
1226            scroll_target_for_strategy(
1227                item_start,
1228                item_extent,
1229                viewport_extent,
1230                max_scroll,
1231                ScrollStrategy::Center,
1232            ),
1233            px(160.)
1234        );
1235        assert_eq!(
1236            scroll_target_for_strategy(
1237                item_start,
1238                item_extent,
1239                viewport_extent,
1240                max_scroll,
1241                ScrollStrategy::Bottom,
1242            ),
1243            px(120.)
1244        );
1245    }
1246
1247    #[test]
1248    fn strategy_targets_clamp_at_both_ends() {
1249        assert_eq!(
1250            scroll_target_for_strategy(px(0.), px(20.), px(100.), px(300.), ScrollStrategy::Bottom,),
1251            px(0.)
1252        );
1253        assert_eq!(
1254            scroll_target_for_strategy(px(380.), px(20.), px(100.), px(300.), ScrollStrategy::Top,),
1255            px(300.)
1256        );
1257    }
1258}