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
548struct ChunkedExtents<P: ItemExtentProvider> {
549    provider: P,
550    item_count: usize,
551    item_extents: Vec<Pixels>,
552    chunk_totals: Vec<Pixels>,
553    chunk_offsets: Vec<Pixels>,
554    intra_prefix: HashMap<usize, Rc<Vec<Pixels>>>,
555}
556
557impl<P: ItemExtentProvider> ChunkedExtents<P> {
558    fn new(provider: P, item_count: usize) -> Self {
559        let chunk_count = (item_count + CHUNK_SIZE - 1) / CHUNK_SIZE;
560        Self {
561            provider,
562            item_count,
563            item_extents: Vec::new(),
564            chunk_totals: vec![px(0.0); chunk_count],
565            chunk_offsets: vec![px(0.0); chunk_count + 1],
566            intra_prefix: HashMap::new(),
567        }
568    }
569
570    fn initialize_totals(&mut self) {
571        if self.item_count == 0 {
572            return;
573        }
574        if self.item_extents.is_empty() {
575            self.item_extents = (0..self.item_count)
576                .map(|index| Self::sanitize_extent(self.provider.extent(index)))
577                .collect();
578        }
579
580        let chunk_count = self.chunk_totals.len();
581        for c in 0..chunk_count {
582            let start = c * CHUNK_SIZE;
583            let end = ((c + 1) * CHUNK_SIZE).min(self.item_count);
584            let sum = self.item_extents[start..end]
585                .iter()
586                .map(|extent| extent.as_f32())
587                .sum();
588            self.chunk_totals[c] = px(sum);
589        }
590        let mut accum = 0.0;
591        self.chunk_offsets[0] = px(0.0);
592        for c in 0..chunk_count {
593            accum += self.chunk_totals[c].as_f32();
594            self.chunk_offsets[c + 1] = px(accum);
595        }
596    }
597
598    fn sanitize_extent(extent: Pixels) -> Pixels {
599        let value = extent.as_f32();
600        if value.is_finite() && value >= 0.0 {
601            extent
602        } else {
603            px(0.0)
604        }
605    }
606
607    fn total_extent(&self) -> Pixels {
608        if self.chunk_offsets.is_empty() {
609            return px(0.0);
610        }
611        *self.chunk_offsets.last().unwrap()
612    }
613
614    fn ensure_intra_prefix(&mut self, chunk_index: usize) -> Rc<Vec<Pixels>> {
615        if let Some(v) = self.intra_prefix.get(&chunk_index) {
616            return v.clone();
617        }
618        let start = chunk_index * CHUNK_SIZE;
619        let end = ((chunk_index + 1) * CHUNK_SIZE).min(self.item_count);
620        let mut origins = Vec::with_capacity(end - start);
621        let mut sum = 0.0;
622        for extent in &self.item_extents[start..end] {
623            origins.push(px(sum));
624            sum += extent.as_f32();
625        }
626        let rc = Rc::new(origins);
627        self.intra_prefix.insert(chunk_index, rc.clone());
628        rc
629    }
630
631    fn find_index_for_offset(&mut self, offset: Pixels) -> usize {
632        if self.item_count == 0 {
633            return 0;
634        }
635        let target = offset.as_f32();
636        let mut lo = 0usize;
637        let mut hi = self.chunk_offsets.len() - 1;
638        while lo < hi {
639            let mid = (lo + hi) / 2;
640            if self.chunk_offsets[mid].as_f32() <= target {
641                lo = mid + 1;
642            } else {
643                hi = mid;
644            }
645        }
646        let chunk = lo
647            .saturating_sub(1)
648            .min(self.chunk_totals.len().saturating_sub(1));
649        let chunk_base = self.chunk_offsets[chunk].as_f32();
650        let within = target - chunk_base;
651        let intra = self.ensure_intra_prefix(chunk);
652        let mut lo_i = 0usize;
653        let mut hi_i = intra.len();
654        while lo_i < hi_i {
655            let mid = (lo_i + hi_i) / 2;
656            if intra[mid].as_f32() <= within {
657                lo_i = mid + 1;
658            } else {
659                hi_i = mid;
660            }
661        }
662        let idx_in_chunk = lo_i.saturating_sub(1).min(intra.len().saturating_sub(1));
663        (chunk * CHUNK_SIZE + idx_in_chunk).min(self.item_count.saturating_sub(1))
664    }
665
666    fn item_origin(&mut self, index: usize) -> Pixels {
667        if self.item_count == 0 {
668            return px(0.0);
669        }
670        let chunk = index / CHUNK_SIZE;
671        let intra_ix = index % CHUNK_SIZE;
672        let intra = self.ensure_intra_prefix(chunk);
673        self.chunk_offsets[chunk] + intra[intra_ix]
674    }
675}
676
677pub struct VariableVirtualList<P: ItemExtentProvider> {
678    id: ElementId,
679    axis: Axis,
680    overscan: usize,
681    base: Stateful<Div>,
682    scroll_handle: gpui::ScrollHandle,
683    sizing_behavior: ListSizingBehavior,
684    engine: ChunkedExtents<P>,
685    renderer: Box<
686        dyn for<'a> Fn(Range<usize>, &'a mut Window, &'a mut App) -> SmallVec<[AnyElement; 64]>,
687    >,
688    on_visible_range: Option<Box<dyn Fn(Range<usize>, &mut Window, &mut App)>>,
689    near_end_threshold: Option<(f32, Rc<RefCell<bool>>, Box<dyn Fn(&mut Window, &mut App)>)>,
690    physics_state: Option<PhysicsScrollState>,
691    pending_scroll: Cell<Option<PendingScroll>>,
692}
693
694impl<P: ItemExtentProvider> Styled for VariableVirtualList<P> {
695    fn style(&mut self) -> &mut StyleRefinement {
696        self.base.style()
697    }
698}
699
700impl<P: ItemExtentProvider + 'static> VariableVirtualList<P> {
701    pub fn new<R: IntoElement + 'static>(
702        id: impl Into<ElementId>,
703        axis: Axis,
704        item_count: usize,
705        provider: P,
706        renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
707    ) -> Self {
708        let id = id.into();
709        let renderer_boxed = move |range: Range<usize>, window: &mut Window, cx: &mut App| {
710            renderer(range, window, cx)
711                .into_iter()
712                .map(|r| r.into_any_element())
713                .collect::<SmallVec<[AnyElement; 64]>>()
714        };
715
716        let mut engine = ChunkedExtents::new(provider, item_count);
717        engine.initialize_totals();
718
719        Self {
720            id: id.clone(),
721            axis,
722            overscan: 5,
723            base: div().id(id).size_full().overflow_scroll(),
724            scroll_handle: gpui::ScrollHandle::new(),
725            sizing_behavior: ListSizingBehavior::Auto,
726            engine,
727            renderer: Box::new(renderer_boxed),
728            on_visible_range: None,
729            near_end_threshold: None,
730            physics_state: None,
731            pending_scroll: Cell::new(None),
732        }
733    }
734
735    pub fn overscan(mut self, items: usize) -> Self {
736        self.overscan = items;
737        self
738    }
739    pub fn track_scroll(mut self, handle: &gpui::ScrollHandle) -> Self {
740        self.base = self.base.track_scroll(handle);
741        self.scroll_handle = handle.clone();
742        self
743    }
744    pub fn with_sizing_behavior(mut self, behavior: ListSizingBehavior) -> Self {
745        self.sizing_behavior = behavior;
746        self
747    }
748
749    pub fn on_visible_range(
750        mut self,
751        f: impl 'static + Fn(Range<usize>, &mut Window, &mut App),
752    ) -> Self {
753        self.on_visible_range = Some(Box::new(f));
754        self
755    }
756
757    pub fn on_near_end(
758        mut self,
759        threshold: f32,
760        f: impl 'static + Fn(&mut Window, &mut App),
761    ) -> Self {
762        self.near_end_threshold = Some((
763            threshold.clamp(0.0, 1.0),
764            Rc::new(RefCell::new(false)),
765            Box::new(f),
766        ));
767        self
768    }
769
770    /// Scroll `index` into view according to `strategy`.
771    ///
772    /// The item is always aligned to the strategy's position, even when it is
773    /// already visible, and any in-flight animated scroll is cancelled: the
774    /// latest command wins.
775    ///
776    /// When this handle has layout metrics, its offset is updated immediately.
777    /// The request is also resolved during the next `prepaint` so first-layout
778    /// calls and viewport changes use the current frame's exact geometry.
779    pub fn scroll_to(&mut self, index: usize, strategy: ScrollStrategy) {
780        if let Some(physics) = self.physics_state.as_ref() {
781            physics.stop();
782        }
783        self.pending_scroll
784            .set(Some(PendingScroll { index, strategy }));
785
786        if let Some(target) = self.immediate_target(index, strategy) {
787            set_scroll_target(&self.scroll_handle, self.axis, target);
788        }
789    }
790
791    /// Best-effort target from the last completed layout's metrics. Returns
792    /// `None` for empty lists and, on the first frame, for strategies that
793    /// need the viewport; `prepaint` resolves those with exact geometry.
794    fn immediate_target(&mut self, index: usize, strategy: ScrollStrategy) -> Option<Pixels> {
795        if self.engine.item_count == 0 {
796            return None;
797        }
798        let index = index.min(self.engine.item_count - 1);
799        let item_start = self.engine.item_origin(index);
800        target_from_laid_out_handle(
801            &self.scroll_handle,
802            self.axis,
803            self.engine.total_extent(),
804            item_start,
805            self.engine.item_extents[index],
806            strategy,
807        )
808        .or(match strategy {
809            ScrollStrategy::Top => Some(item_start),
810            ScrollStrategy::Center | ScrollStrategy::Bottom => None,
811        })
812    }
813
814    pub fn with_physics(mut self, state: &PhysicsScrollState) -> Self {
815        let physics_c = state.clone();
816        let handle_c = self.scroll_handle.clone();
817        let dir = if self.axis.is_vertical() {
818            ScrollDirection::Vertical
819        } else {
820            ScrollDirection::Horizontal
821        };
822        self.base = self.base.on_scroll_wheel(move |event, window, _cx| {
823            physics_c.handle_scroll_event(&handle_c, dir, event, window);
824        });
825        self.physics_state = Some(state.clone());
826        self
827    }
828
829    /// Scroll to `index` immediately, animating when physics is configured.
830    pub fn scroll_to_animated(&mut self, index: usize, window: &Window) {
831        if self.engine.item_count == 0 {
832            return;
833        }
834        // `Top` always resolves, with or without layout metrics.
835        let target = self
836            .immediate_target(index, ScrollStrategy::Top)
837            .expect("ScrollStrategy::Top always resolves");
838
839        if let Some(physics) = self.physics_state.as_ref() {
840            self.pending_scroll.set(None);
841            if self.axis.is_vertical() {
842                physics.scroll_to_y_animated(target.as_f32(), &self.scroll_handle, window);
843            } else {
844                physics.scroll_to_x_animated(target.as_f32(), &self.scroll_handle, window);
845            }
846        } else {
847            self.scroll_to(index, ScrollStrategy::Top);
848        }
849    }
850
851    /// Consume a pending `scroll_to` and return the offset the frame should use.
852    fn apply_pending_scroll(
853        &mut self,
854        offset: Point<Pixels>,
855        viewport_extent: Pixels,
856        max_scroll: Size<Pixels>,
857    ) -> Point<Pixels> {
858        let Some(pending) = self.pending_scroll.take() else {
859            return offset;
860        };
861        if self.engine.item_count == 0 {
862            return offset;
863        }
864        let index = pending.index.min(self.engine.item_count - 1);
865        let target = scroll_target_for_strategy(
866            self.engine.item_origin(index),
867            self.engine.item_extents[index],
868            viewport_extent,
869            max_scroll.along(self.axis),
870            pending.strategy,
871        );
872        offset.apply_along(self.axis, |_| -target)
873    }
874}
875
876pub struct VariableFrameState {
877    items: SmallVec<[AnyElement; 32]>,
878}
879
880impl<P: ItemExtentProvider + 'static> IntoElement for VariableVirtualList<P> {
881    type Element = Self;
882    fn into_element(self) -> Self::Element {
883        self
884    }
885}
886
887impl<P: ItemExtentProvider + 'static> Element for VariableVirtualList<P> {
888    type RequestLayoutState = VariableFrameState;
889    type PrepaintState = Option<Hitbox>;
890
891    fn id(&self) -> Option<ElementId> {
892        Some(self.id.clone())
893    }
894    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
895        None
896    }
897
898    fn request_layout(
899        &mut self,
900        global_id: Option<&GlobalElementId>,
901        inspector_id: Option<&gpui::InspectorElementId>,
902        window: &mut Window,
903        cx: &mut App,
904    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
905        let axis = self.axis;
906        let behavior = self.sizing_behavior;
907        let engine_total = self.engine.total_extent();
908
909        let layout_id = self.base.interactivity().request_layout(
910            global_id,
911            inspector_id,
912            window,
913            cx,
914            move |style, window: &mut Window, cx: &mut App| match behavior {
915                ListSizingBehavior::Infer => {
916                    window.request_measured_layout(style, move |_k, available, _, _| {
917                        let mut sz = Size::default();
918                        if axis.is_horizontal() {
919                            sz.width = match available.width {
920                                AvailableSpace::Definite(w) => w,
921                                _ => engine_total,
922                            };
923                            sz.height = match available.height {
924                                AvailableSpace::Definite(h) => h,
925                                _ => px(0.),
926                            };
927                        } else {
928                            sz.width = match available.width {
929                                AvailableSpace::Definite(w) => w,
930                                _ => px(0.),
931                            };
932                            sz.height = match available.height {
933                                AvailableSpace::Definite(h) => h,
934                                _ => engine_total,
935                            };
936                        }
937                        sz
938                    })
939                }
940                ListSizingBehavior::Auto => window.request_layout(style, None, cx),
941            },
942        );
943        (
944            layout_id,
945            VariableFrameState {
946                items: SmallVec::new(),
947            },
948        )
949    }
950
951    fn prepaint(
952        &mut self,
953        global_id: Option<&GlobalElementId>,
954        inspector_id: Option<&gpui::InspectorElementId>,
955        bounds: Bounds<Pixels>,
956        layout: &mut Self::RequestLayoutState,
957        window: &mut Window,
958        cx: &mut App,
959    ) -> Self::PrepaintState {
960        let style = self
961            .base
962            .interactivity()
963            .compute_style(global_id, None, window, cx);
964        let border = style.border_widths.to_pixels(window.rem_size());
965        // Layout snaps authored padding to the device-pixel grid, so every
966        // recomputation of it (content bounds, scroll max) must snap too.
967        let padding = style
968            .padding
969            .to_pixels(bounds.size.into(), window.rem_size())
970            .map(|edge| window.pixel_snap(*edge));
971
972        let content_bounds = Bounds::from_corners(
973            bounds.origin + point(border.left + padding.left, border.top + padding.top),
974            bounds.bottom_right()
975                - point(border.right + padding.right, border.bottom + padding.bottom),
976        );
977
978        let viewport_len = content_bounds.size.along(self.axis);
979        let total = self.engine.total_extent();
980
981        let content_size = if self.axis.is_horizontal() {
982            size(total, content_bounds.size.height)
983        } else {
984            size(content_bounds.size.width, total)
985        };
986        let max_scroll = scroll_max(content_size, padding, bounds.size);
987
988        // Resolve any pending `scroll_to` and clamp before the visible range is
989        // derived, so this frame's range, this frame's item positions and the
990        // offset GPUI will settle on all agree.
991        let offset =
992            self.apply_pending_scroll(self.scroll_handle.offset(), viewport_len, max_scroll);
993        let offset = clamp_scroll_offset(offset, max_scroll);
994        self.scroll_handle.set_offset(offset);
995
996        let start_px = -offset.along(self.axis);
997        let end_px = start_px + viewport_len;
998
999        let mut start_ix = self.engine.find_index_for_offset(start_px.max(px(0.)));
1000        start_ix = start_ix.saturating_sub(self.overscan);
1001
1002        let mut end_ix = self.engine.find_index_for_offset(end_px.max(px(0.)));
1003        end_ix = (end_ix + 1 + self.overscan).min(self.engine.item_count);
1004
1005        let visible = start_ix..end_ix;
1006
1007        if let Some(cb) = &self.on_visible_range {
1008            cb(visible.clone(), window, cx);
1009        }
1010        if let Some((threshold, fired, cb)) = &self.near_end_threshold {
1011            let progress = if self.engine.item_count == 0 {
1012                0.0
1013            } else {
1014                visible.end as f32 / self.engine.item_count as f32
1015            };
1016            let mut was_fired = fired.borrow_mut();
1017            if progress >= *threshold && !*was_fired {
1018                *was_fired = true;
1019                cb(window, cx);
1020            }
1021            if progress < *threshold {
1022                *was_fired = false;
1023            }
1024        }
1025
1026        let items = (self.renderer)(visible.clone(), window, cx);
1027
1028        self.base.interactivity().prepaint(
1029            global_id,
1030            inspector_id,
1031            bounds,
1032            content_size,
1033            window,
1034            cx,
1035            |_style, _, hitbox, window, cx| {
1036                for (mut item, ix) in items.into_iter().zip(visible) {
1037                    let origin_along = self.engine.item_origin(ix);
1038                    let item_origin = match self.axis {
1039                        Axis::Horizontal => {
1040                            content_bounds.origin + point(origin_along + offset.x, offset.y)
1041                        }
1042                        Axis::Vertical => {
1043                            content_bounds.origin + point(offset.x, origin_along + offset.y)
1044                        }
1045                    };
1046
1047                    let available = match self.axis {
1048                        Axis::Horizontal => size(
1049                            AvailableSpace::Definite(px(CHUNK_SIZE as f32)),
1050                            AvailableSpace::Definite(content_bounds.size.height),
1051                        ),
1052                        Axis::Vertical => size(
1053                            AvailableSpace::Definite(content_bounds.size.width),
1054                            AvailableSpace::Definite(px(CHUNK_SIZE as f32)),
1055                        ),
1056                    };
1057
1058                    item.layout_as_root(available, window, cx);
1059                    item.prepaint_at(item_origin, window, cx);
1060                    layout.items.push(item);
1061                }
1062                hitbox
1063            },
1064        )
1065    }
1066
1067    fn paint(
1068        &mut self,
1069        global_id: Option<&GlobalElementId>,
1070        inspector_id: Option<&gpui::InspectorElementId>,
1071        bounds: Bounds<Pixels>,
1072        layout: &mut Self::RequestLayoutState,
1073        hitbox: &mut Self::PrepaintState,
1074        window: &mut Window,
1075        cx: &mut App,
1076    ) {
1077        self.base.interactivity().paint(
1078            global_id,
1079            inspector_id,
1080            bounds,
1081            hitbox.as_ref(),
1082            window,
1083            cx,
1084            |_, window, cx| {
1085                for item in &mut layout.items {
1086                    item.paint(window, cx);
1087                }
1088            },
1089        )
1090    }
1091}
1092
1093pub fn vlist_uniform<R: IntoElement + 'static>(
1094    id: impl Into<ElementId>,
1095    item_count: usize,
1096    item_extent: Pixels,
1097    renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
1098) -> UniformVirtualList {
1099    UniformVirtualList::new(id, Axis::Vertical, item_count, item_extent, renderer)
1100}
1101
1102pub fn hlist_uniform<R: IntoElement + 'static>(
1103    id: impl Into<ElementId>,
1104    item_count: usize,
1105    item_extent: Pixels,
1106    renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
1107) -> UniformVirtualList {
1108    UniformVirtualList::new(id, Axis::Horizontal, item_count, item_extent, renderer)
1109}
1110
1111pub fn vlist_variable<R: IntoElement + 'static, P: ItemExtentProvider + 'static>(
1112    id: impl Into<ElementId>,
1113    item_count: usize,
1114    provider: P,
1115    renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
1116) -> VariableVirtualList<P> {
1117    VariableVirtualList::new(id, Axis::Vertical, item_count, provider, renderer)
1118}
1119
1120pub fn hlist_variable<R: IntoElement + 'static, P: ItemExtentProvider + 'static>(
1121    id: impl Into<ElementId>,
1122    item_count: usize,
1123    provider: P,
1124    renderer: impl 'static + Fn(Range<usize>, &mut Window, &mut App) -> Vec<R>,
1125) -> VariableVirtualList<P> {
1126    VariableVirtualList::new(id, Axis::Horizontal, item_count, provider, renderer)
1127}
1128
1129pub fn vlist_uniform_view<R, V>(
1130    view: Entity<V>,
1131    id: impl Into<ElementId>,
1132    item_count: usize,
1133    item_extent: Pixels,
1134    f: impl 'static + Fn(&mut V, Range<usize>, &mut Window, &mut Context<V>) -> Vec<R>,
1135) -> UniformVirtualList
1136where
1137    R: IntoElement,
1138    V: Render,
1139{
1140    let id: ElementId = id.into();
1141    let render_range = move |visible_range: Range<usize>, window: &mut Window, cx: &mut App| {
1142        view.update(cx, |this, cx| {
1143            f(this, visible_range, window, cx)
1144                .into_iter()
1145                .map(|component| component.into_any_element())
1146                .collect::<SmallVec<[AnyElement; 64]>>()
1147        })
1148    };
1149
1150    UniformVirtualList::new(
1151        id,
1152        Axis::Vertical,
1153        item_count,
1154        item_extent,
1155        move |range, window, cx| {
1156            render_range(range, window, cx)
1157                .into_iter()
1158                .collect::<Vec<_>>()
1159        },
1160    )
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165    use super::{scroll_target_for_strategy, ChunkedExtents, ItemExtentProvider};
1166    use gpui::{px, Pixels, ScrollStrategy};
1167    use std::{cell::Cell, rc::Rc};
1168
1169    struct CountingProvider {
1170        calls: Rc<Cell<usize>>,
1171        extents: Vec<f32>,
1172    }
1173
1174    impl ItemExtentProvider for CountingProvider {
1175        fn extent(&self, index: usize) -> Pixels {
1176            self.calls.set(self.calls.get() + 1);
1177            px(self.extents[index])
1178        }
1179    }
1180
1181    #[test]
1182    fn variable_extents_are_snapshotted_once_and_sanitized() {
1183        let calls = Rc::new(Cell::new(0));
1184        let mut extents = ChunkedExtents::new(
1185            CountingProvider {
1186                calls: calls.clone(),
1187                extents: vec![10.0, f32::NAN, -5.0, 20.0],
1188            },
1189            4,
1190        );
1191
1192        extents.initialize_totals();
1193        let prefix = extents.ensure_intra_prefix(0);
1194
1195        assert_eq!(calls.get(), 4);
1196        assert_eq!(extents.total_extent(), px(30.0));
1197        assert_eq!(
1198            prefix.as_ref(),
1199            &vec![px(0.0), px(10.0), px(10.0), px(10.0)]
1200        );
1201    }
1202
1203    #[test]
1204    fn strategies_resolve_to_distinct_middle_positions() {
1205        let item_start = px(200.);
1206        let item_extent = px(20.);
1207        let viewport_extent = px(100.);
1208        let max_scroll = px(300.);
1209
1210        assert_eq!(
1211            scroll_target_for_strategy(
1212                item_start,
1213                item_extent,
1214                viewport_extent,
1215                max_scroll,
1216                ScrollStrategy::Top,
1217            ),
1218            px(200.)
1219        );
1220        assert_eq!(
1221            scroll_target_for_strategy(
1222                item_start,
1223                item_extent,
1224                viewport_extent,
1225                max_scroll,
1226                ScrollStrategy::Center,
1227            ),
1228            px(160.)
1229        );
1230        assert_eq!(
1231            scroll_target_for_strategy(
1232                item_start,
1233                item_extent,
1234                viewport_extent,
1235                max_scroll,
1236                ScrollStrategy::Bottom,
1237            ),
1238            px(120.)
1239        );
1240    }
1241
1242    #[test]
1243    fn strategy_targets_clamp_at_both_ends() {
1244        assert_eq!(
1245            scroll_target_for_strategy(px(0.), px(20.), px(100.), px(300.), ScrollStrategy::Bottom,),
1246            px(0.)
1247        );
1248        assert_eq!(
1249            scroll_target_for_strategy(px(380.), px(20.), px(100.), px(300.), ScrollStrategy::Top,),
1250            px(300.)
1251        );
1252    }
1253}