Skip to main content

gpui_component/list/
list.rs

1use instant::Duration;
2use std::{cell::Cell, ops::Range, rc::Rc};
3
4use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
5use crate::input::InputState;
6use crate::list::cache::{MeasuredEntrySize, RowEntry, RowsCache};
7use crate::{
8    ActiveTheme, IconName, Size,
9    input::{Input, InputEvent},
10    scroll::Scrollbar,
11    v_flex,
12};
13use crate::{ElementExt as _, Icon, IndexPath, Selectable, Sizable, StyledExt};
14use crate::{VirtualListScrollHandle, list::ListDelegate, v_virtual_list};
15use gpui::{
16    App, AvailableSpace, ClickEvent, Context, DefiniteLength, EdgesRefinement, EventEmitter,
17    ListSizingBehavior, Pixels, RenderOnce, Role, ScrollStrategy, SharedString,
18    StatefulInteractiveElement, StyleRefinement, Subscription, px, size,
19};
20use gpui::{
21    AppContext, Entity, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyBinding,
22    Length, MouseButton, ParentElement, Render, Styled, Task, Window, div, prelude::FluentBuilder,
23};
24use rust_i18n::t;
25
26pub(crate) fn init(cx: &mut App) {
27    let context: Option<&str> = Some("List");
28    cx.bind_keys([
29        KeyBinding::new("escape", Cancel, context),
30        KeyBinding::new("enter", Confirm { secondary: false }, context),
31        KeyBinding::new(
32            if cx.platform_info().is_mac() {
33                "cmd-enter"
34            } else {
35                "ctrl-enter"
36            },
37            Confirm { secondary: true },
38            context,
39        ),
40        KeyBinding::new("up", SelectUp, context),
41        KeyBinding::new("down", SelectDown, context),
42    ]);
43}
44
45#[derive(Clone)]
46pub enum ListEvent {
47    /// Move to select item.
48    Select(IndexPath),
49    /// Click on item or pressed Enter.
50    Confirm(IndexPath),
51    /// Pressed ESC to deselect the item.
52    Cancel,
53}
54
55struct ListOptions {
56    scroll_bounce: Option<bool>,
57    size: Size,
58    scrollbar_visible: bool,
59    search_placeholder: Option<SharedString>,
60    max_height: Option<Length>,
61    record_items_height: bool,
62    hold_items_height: bool,
63    paddings: EdgesRefinement<DefiniteLength>,
64}
65
66impl Default for ListOptions {
67    fn default() -> Self {
68        Self {
69            scroll_bounce: None,
70            size: Size::default(),
71            scrollbar_visible: true,
72            max_height: None,
73            record_items_height: false,
74            hold_items_height: false,
75            search_placeholder: None,
76            paddings: EdgesRefinement::default(),
77        }
78    }
79}
80
81/// The state for List.
82///
83/// List required all items has the same height.
84pub struct ListState<D: ListDelegate> {
85    pub(crate) focus_handle: FocusHandle,
86    pub(crate) query_input: Entity<InputState>,
87    options: ListOptions,
88    delegate: D,
89    last_query: Option<String>,
90    scroll_handle: VirtualListScrollHandle,
91    rows_cache: RowsCache,
92    selected_index: Option<IndexPath>,
93    item_to_measure_index: IndexPath,
94    deferred_scroll_to_index: Option<(IndexPath, ScrollStrategy)>,
95    mouse_right_clicked_index: Option<IndexPath>,
96    reset_on_cancel: bool,
97    /// Items height recorded on the first paint while `hold_items_height` is on.
98    held_items_height: Rc<Cell<Option<Pixels>>>,
99    searchable: bool,
100    selectable: bool,
101    _search_task: Task<()>,
102    _load_more_task: Task<()>,
103    _query_input_subscription: Subscription,
104}
105
106impl<D> ListState<D>
107where
108    D: ListDelegate,
109{
110    pub fn new(delegate: D, window: &mut Window, cx: &mut Context<Self>) -> Self {
111        let query_input =
112            cx.new(|cx| InputState::new(window, cx).placeholder(t!("List.search_placeholder")));
113
114        let _query_input_subscription =
115            cx.subscribe_in(&query_input, window, Self::on_query_input_event);
116
117        Self {
118            focus_handle: cx.focus_handle(),
119            options: ListOptions::default(),
120            delegate,
121            rows_cache: RowsCache::default(),
122            query_input,
123            last_query: None,
124            selected_index: None,
125            selectable: true,
126            searchable: false,
127            item_to_measure_index: IndexPath::default(),
128            deferred_scroll_to_index: None,
129            mouse_right_clicked_index: None,
130            scroll_handle: VirtualListScrollHandle::new(),
131            reset_on_cancel: true,
132            held_items_height: Rc::default(),
133            _search_task: Task::ready(()),
134            _load_more_task: Task::ready(()),
135            _query_input_subscription,
136        }
137    }
138
139    /// Forget the items height held by [`List::hold_items_height`], so the
140    /// next paint records it again. Call it when a popup menu is closed.
141    pub(crate) fn reset_held_items_height(&self) {
142        self.held_items_height.set(None);
143    }
144
145    /// Sets whether the list is searchable, default is `false`.
146    ///
147    /// When `true`, there will be a search input at the top of the list.
148    pub fn searchable(mut self, searchable: bool) -> Self {
149        self.searchable = searchable;
150        self
151    }
152
153    pub fn set_searchable(&mut self, searchable: bool, cx: &mut Context<Self>) {
154        if self.searchable != searchable {
155            self.searchable = searchable;
156            cx.notify();
157        }
158    }
159
160    /// Sets whether the list is selectable, default is true.
161    pub fn selectable(mut self, selectable: bool) -> Self {
162        self.selectable = selectable;
163        self
164    }
165
166    /// Sets whether the list is selectable, default is true.
167    pub fn set_selectable(&mut self, selectable: bool, cx: &mut Context<Self>) {
168        self.selectable = selectable;
169        cx.notify();
170    }
171
172    pub fn delegate(&self) -> &D {
173        &self.delegate
174    }
175
176    pub fn delegate_mut(&mut self) -> &mut D {
177        &mut self.delegate
178    }
179
180    /// Focus the list, if the list is searchable, focus the search input.
181    pub fn focus(&mut self, window: &mut Window, cx: &mut App) {
182        self.focus_handle(cx).focus(window, cx);
183    }
184
185    /// Return true if either the list or the search input is focused.
186    pub(crate) fn is_focused(&self, window: &Window, cx: &App) -> bool {
187        self.focus_handle.is_focused(window) || self.query_input.focus_handle(cx).is_focused(window)
188    }
189
190    /// Set the selected index of the list,
191    /// this will also scroll to the selected item.
192    pub(crate) fn _set_selected_index(
193        &mut self,
194        ix: Option<IndexPath>,
195        window: &mut Window,
196        cx: &mut Context<Self>,
197    ) {
198        if !self.selectable {
199            return;
200        }
201
202        self.selected_index = ix;
203        self.delegate.set_selected_index(ix, window, cx);
204        self.scroll_to_selected_item(window, cx);
205    }
206
207    /// Set the selected index of the list,
208    /// this method will not scroll to the selected item.
209    pub fn set_selected_index(
210        &mut self,
211        ix: Option<IndexPath>,
212        window: &mut Window,
213        cx: &mut Context<Self>,
214    ) {
215        self.selected_index = ix;
216        self.delegate.set_selected_index(ix, window, cx);
217    }
218
219    pub fn selected_index(&self) -> Option<IndexPath> {
220        self.selected_index
221    }
222
223    /// Set the index of the item that has been right clicked.
224    pub fn set_right_clicked_index(
225        &mut self,
226        ix: Option<IndexPath>,
227        window: &mut Window,
228        cx: &mut Context<Self>,
229    ) {
230        self.mouse_right_clicked_index = ix;
231        self.delegate.set_right_clicked_index(ix, window, cx);
232    }
233
234    /// Returns the index of the item that has been right clicked.
235    pub fn right_clicked_index(&self) -> Option<IndexPath> {
236        self.mouse_right_clicked_index
237    }
238
239    /// Set the query text of the search input, this will trigger a search.
240    pub fn set_query(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
241        let query = query.to_string();
242        self.query_input.update(cx, |input, cx| {
243            input.set_value(query.clone(), window, cx);
244        });
245
246        // `set_value` does not emit `InputEvent::Change`, so start the search here.
247        self.start_search(query.trim().to_string(), window, cx);
248    }
249
250    /// Set a specific list item for measurement.
251    ///
252    /// If the item is absent, measure the first item in the first non-empty section.
253    pub fn set_item_to_measure_index(
254        &mut self,
255        ix: IndexPath,
256        _: &mut Window,
257        cx: &mut Context<Self>,
258    ) {
259        self.item_to_measure_index = ix;
260        cx.notify();
261    }
262
263    /// Scroll to the item at the given index.
264    pub fn scroll_to_item(
265        &mut self,
266        ix: IndexPath,
267        strategy: ScrollStrategy,
268        _: &mut Window,
269        cx: &mut Context<Self>,
270    ) {
271        if ix.section == 0 && ix.row == 0 {
272            // If the item is the first item, scroll to the top.
273            let mut offset = self.scroll_handle.base_handle().offset();
274            offset.y = px(0.);
275            self.scroll_handle.base_handle().set_offset(offset);
276            cx.notify();
277            return;
278        }
279        self.deferred_scroll_to_index = Some((ix, strategy));
280        cx.notify();
281    }
282
283    /// Get scroll handle
284    pub fn scroll_handle(&self) -> &VirtualListScrollHandle {
285        &self.scroll_handle
286    }
287
288    pub fn scroll_to_selected_item(&mut self, _: &mut Window, cx: &mut Context<Self>) {
289        if let Some(ix) = self.selected_index {
290            self.deferred_scroll_to_index = Some((ix, ScrollStrategy::Top));
291            cx.notify();
292        }
293    }
294
295    fn on_query_input_event(
296        &mut self,
297        state: &Entity<InputState>,
298        event: &InputEvent,
299        window: &mut Window,
300        cx: &mut Context<Self>,
301    ) {
302        match event {
303            InputEvent::Change => {
304                let text = state.read(cx).value();
305                let text = text.trim().to_string();
306                if Some(&text) == self.last_query.as_ref() {
307                    return;
308                }
309
310                self.start_search(text, window, cx);
311            }
312            _ => {}
313        }
314    }
315
316    fn start_search(&mut self, query: String, window: &mut Window, cx: &mut Context<Self>) {
317        self.set_searching(true, window, cx);
318        let search = self.delegate.perform_search(&query, window, cx);
319
320        if self.rows_cache.len() > 0 {
321            self._set_selected_index(Some(IndexPath::default()), window, cx);
322        } else {
323            self._set_selected_index(None, window, cx);
324        }
325
326        self._search_task = cx.spawn_in(window, async move |this, window| {
327            search.await;
328
329            _ = this.update_in(window, |this, _, _| {
330                this.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
331                this.last_query = Some(query);
332            });
333
334            // Always wait 100ms to avoid flicker
335            window
336                .background_executor()
337                .timer(Duration::from_millis(100))
338                .await;
339            _ = this.update_in(window, |this, window, cx| {
340                this.set_searching(false, window, cx);
341            });
342        });
343    }
344
345    fn set_searching(&mut self, searching: bool, window: &mut Window, cx: &mut Context<Self>) {
346        self.query_input
347            .update(cx, |input, cx| input.set_loading(searching, window, cx));
348    }
349
350    /// Dispatch delegate's `load_more` method when the
351    /// visible range is near the end.
352    fn load_more_if_need(
353        &mut self,
354        entities_count: usize,
355        visible_end: usize,
356        window: &mut Window,
357        cx: &mut Context<Self>,
358    ) {
359        // FIXME: Here need void sections items count.
360
361        let threshold = self.delegate.load_more_threshold();
362        // Securely handle subtract logic to prevent attempt
363        // to subtract with overflow
364        if visible_end >= entities_count.saturating_sub(threshold) {
365            if !self.delegate.has_more(cx) {
366                return;
367            }
368
369            self._load_more_task = cx.spawn_in(window, async move |view, cx| {
370                _ = view.update_in(cx, |view, window, cx| {
371                    view.delegate.load_more(window, cx);
372                });
373            });
374        }
375    }
376
377    pub(crate) fn reset_on_cancel(mut self, reset: bool) -> Self {
378        self.reset_on_cancel = reset;
379        self
380    }
381
382    fn on_action_cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
383        cx.propagate();
384        if self.reset_on_cancel {
385            self._set_selected_index(None, window, cx);
386        }
387
388        self.delegate.cancel(window, cx);
389        cx.emit(ListEvent::Cancel);
390        cx.notify();
391    }
392
393    fn on_action_confirm(
394        &mut self,
395        confirm: &Confirm,
396        window: &mut Window,
397        cx: &mut Context<Self>,
398    ) {
399        if self.rows_cache.len() == 0 {
400            return;
401        }
402
403        let Some(ix) = self.selected_index else {
404            return;
405        };
406
407        self.delegate
408            .set_selected_index(self.selected_index, window, cx);
409        self.delegate.confirm(confirm.secondary, window, cx);
410        cx.emit(ListEvent::Confirm(ix));
411        cx.notify();
412    }
413
414    fn select_item(&mut self, ix: IndexPath, window: &mut Window, cx: &mut Context<Self>) {
415        if !self.selectable {
416            return;
417        }
418
419        self.selected_index = Some(ix);
420        self.delegate.set_selected_index(Some(ix), window, cx);
421        self.scroll_to_selected_item(window, cx);
422        cx.emit(ListEvent::Select(ix));
423        cx.notify();
424    }
425
426    pub(crate) fn on_action_select_prev(
427        &mut self,
428        _: &SelectUp,
429        window: &mut Window,
430        cx: &mut Context<Self>,
431    ) {
432        if self.rows_cache.len() == 0 {
433            return;
434        }
435
436        let prev_ix = self.rows_cache.prev(self.selected_index);
437        self.select_item(prev_ix, window, cx);
438    }
439
440    pub(crate) fn on_action_select_next(
441        &mut self,
442        _: &SelectDown,
443        window: &mut Window,
444        cx: &mut Context<Self>,
445    ) {
446        if self.rows_cache.len() == 0 {
447            return;
448        }
449
450        let next_ix = self.rows_cache.next(self.selected_index);
451        self.select_item(next_ix, window, cx);
452    }
453
454    fn prepare_items_if_needed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
455        let sections_count = self.delegate.sections_count(cx).max(1);
456        let mut measured_size = MeasuredEntrySize::default();
457
458        // Measure the item_height and section header/footer height.
459        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
460        // Use the fallback for this measurement without overwriting the caller's configured index.
461        let requested = self.item_to_measure_index;
462        let item_to_measure = if requested.section < sections_count
463            && requested.row < self.delegate.items_count(requested.section, cx)
464        {
465            Some(requested)
466        } else {
467            (0..sections_count)
468                .find(|section| self.delegate.items_count(*section, cx) > 0)
469                .map(|section| IndexPath::default().section(section))
470        };
471        if let Some(index) = item_to_measure {
472            measured_size.item_size = self
473                .render_list_item(index, window, cx)
474                .into_any_element()
475                .layout_as_root(available_space, window, cx);
476        }
477
478        if let Some(mut el) = self
479            .delegate
480            .render_section_header(0, window, cx)
481            .map(|r| r.into_any_element())
482        {
483            measured_size.section_header_size = el.layout_as_root(available_space, window, cx);
484        }
485        if let Some(mut el) = self
486            .delegate
487            .render_section_footer(0, window, cx)
488            .map(|r| r.into_any_element())
489        {
490            measured_size.section_footer_size = el.layout_as_root(available_space, window, cx);
491        }
492
493        self.rows_cache
494            .prepare_if_needed(sections_count, measured_size, cx, |section_ix, cx| {
495                self.delegate.items_count(section_ix, cx)
496            });
497    }
498
499    fn render_list_item(
500        &mut self,
501        ix: IndexPath,
502        window: &mut Window,
503        cx: &mut Context<Self>,
504    ) -> impl IntoElement {
505        let selectable = self.selectable;
506        let selected = self.selected_index.map(|s| s.eq_row(ix)).unwrap_or(false);
507        let mouse_right_clicked = self
508            .mouse_right_clicked_index
509            .map(|s| s.eq_row(ix))
510            .unwrap_or(false);
511        let id = SharedString::from(format!("list-item-{}", ix));
512
513        let total_items = self.rows_cache.items_count();
514
515        div()
516            .id(id)
517            .role(Role::ListItem)
518            .aria_position_in_set(ix.row + 1)
519            .aria_size_of_set(total_items)
520            .aria_selected(selected)
521            .w_full()
522            .relative()
523            .overflow_hidden()
524            .children(self.delegate.render_item(ix, window, cx).map(|item| {
525                item.selected(selected)
526                    .secondary_selected(mouse_right_clicked)
527            }))
528            .when(selectable, |this| {
529                this.on_click(cx.listener(move |this, e: &ClickEvent, window, cx| {
530                    this.set_right_clicked_index(None, window, cx);
531                    this.selected_index = Some(ix);
532                    this.on_action_confirm(
533                        &Confirm {
534                            secondary: e.modifiers().secondary(cx),
535                        },
536                        window,
537                        cx,
538                    );
539                }))
540                .on_mouse_down(
541                    MouseButton::Right,
542                    cx.listener(move |this, _, window, cx| {
543                        this.set_right_clicked_index(Some(ix), window, cx);
544                        cx.notify();
545                    }),
546                )
547            })
548    }
549
550    fn render_items(
551        &mut self,
552        items_count: usize,
553        entities_count: usize,
554        window: &mut Window,
555        cx: &mut Context<Self>,
556    ) -> impl IntoElement {
557        let rows_cache = self.rows_cache.clone();
558        let scrollbar_visible = self.options.scrollbar_visible;
559        let scroll_handle = self.scroll_handle.clone();
560        let record_items_height = self.options.record_items_height;
561        let held_items_height = self.held_items_height.clone();
562        let items_min_height = self
563            .options
564            .hold_items_height
565            .then(|| held_items_height.get())
566            .flatten();
567        let item_to_measure_index = rows_cache
568            .position_of(&self.item_to_measure_index)
569            .or_else(|| rows_cache.first_entry_position())
570            .unwrap_or(0);
571
572        v_flex()
573            .flex_grow_1()
574            .relative()
575            .size_full()
576            .when_some(self.options.max_height, |this, h| this.max_h(h))
577            .when_some(items_min_height, |this, h| this.min_h(h))
578            .when(record_items_height, |this| {
579                this.on_prepaint(move |bounds, _, _| {
580                    if held_items_height.get().is_none() && bounds.size.height > px(0.) {
581                        held_items_height.set(Some(bounds.size.height));
582                    }
583                })
584            })
585            .overflow_hidden()
586            .when(items_count == 0, |this| {
587                this.child(self.delegate.render_empty(window, cx))
588            })
589            .when(items_count > 0, {
590                |this| {
591                    this.child(
592                        v_virtual_list(
593                            cx.entity(),
594                            "virtual-list",
595                            rows_cache.entries_sizes.clone(),
596                            move |list, visible_range: Range<usize>, window, cx| {
597                                list.load_more_if_need(
598                                    entities_count,
599                                    visible_range.end,
600                                    window,
601                                    cx,
602                                );
603
604                                // NOTE: Here the v_virtual_list would not able to have gap_y,
605                                // because the section header, footer is always have rendered as a empty child item,
606                                // even the delegate give a None result.
607
608                                visible_range
609                                    .map(|ix| {
610                                        let Some(entry) = rows_cache.get(ix) else {
611                                            return div();
612                                        };
613
614                                        div().children(match entry {
615                                            RowEntry::Entry(index) => Some(
616                                                list.render_list_item(index, window, cx)
617                                                    .into_any_element(),
618                                            ),
619                                            RowEntry::SectionHeader(section_ix) => list
620                                                .delegate_mut()
621                                                .render_section_header(section_ix, window, cx)
622                                                .map(|r| r.into_any_element()),
623                                            RowEntry::SectionFooter(section_ix) => list
624                                                .delegate_mut()
625                                                .render_section_footer(section_ix, window, cx)
626                                                .map(|r| r.into_any_element()),
627                                        })
628                                    })
629                                    .collect::<Vec<_>>()
630                            },
631                        )
632                        .with_item_to_measure_index(item_to_measure_index)
633                        .paddings(self.options.paddings.clone())
634                        .when(self.options.max_height.is_some(), |this| {
635                            this.with_sizing_behavior(ListSizingBehavior::Infer)
636                        })
637                        .track_scroll(&scroll_handle)
638                        .map(|list| {
639                            gpui_base::ScrollBounce::new("list-scroll-bounce", &scroll_handle, list)
640                                .when_some(self.options.scroll_bounce, |bounce, on| {
641                                    bounce.enabled(on)
642                                })
643                        })
644                        .into_any_element(),
645                    )
646                }
647            })
648            .when(scrollbar_visible, |this| {
649                this.child(Scrollbar::vertical(&scroll_handle).viewport_from_layout())
650            })
651    }
652}
653
654impl<D> Focusable for ListState<D>
655where
656    D: ListDelegate,
657{
658    fn focus_handle(&self, cx: &App) -> FocusHandle {
659        if self.searchable {
660            self.query_input.focus_handle(cx)
661        } else {
662            self.focus_handle.clone()
663        }
664    }
665}
666impl<D> EventEmitter<ListEvent> for ListState<D> where D: ListDelegate {}
667impl<D> Render for ListState<D>
668where
669    D: ListDelegate,
670{
671    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
672        self.prepare_items_if_needed(window, cx);
673
674        // Scroll to the selected item if it is set.
675        if let Some((ix, strategy)) = self.deferred_scroll_to_index.take() {
676            if let Some(item_ix) = self.rows_cache.position_of(&ix) {
677                self.scroll_handle.scroll_to_item(item_ix, strategy);
678            }
679        }
680
681        let loading = self.delegate().loading(cx);
682        let query_input = if self.searchable {
683            // sync placeholder
684            if let Some(placeholder) = &self.options.search_placeholder {
685                self.query_input.update(cx, |input, cx| {
686                    input.set_placeholder(placeholder.clone(), window, cx);
687                });
688            }
689            Some(self.query_input.clone())
690        } else {
691            None
692        };
693
694        let loading_view = if loading {
695            Some(self.delegate.render_loading(window, cx).into_any_element())
696        } else {
697            None
698        };
699        let initial_view = if let Some(input) = &query_input {
700            if input.read(cx).value().is_empty() {
701                self.delegate.render_initial(window, cx)
702            } else {
703                None
704            }
705        } else {
706            None
707        };
708        let items_count = self.rows_cache.items_count();
709        let entities_count = self.rows_cache.len();
710        let mouse_right_clicked_index = self.mouse_right_clicked_index;
711
712        v_flex()
713            .key_context("List")
714            .id("list-state")
715            .track_focus(&self.focus_handle)
716            .role(Role::List)
717            .size_full()
718            .relative()
719            .overflow_hidden()
720            .when_some(query_input, |this, input| {
721                this.child(
722                    div()
723                        .map(|this| match self.options.size {
724                            Size::Small => this.px_1p5(),
725                            _ => this.px_2(),
726                        })
727                        .border_b_1()
728                        .border_color(cx.theme().border)
729                        .child(
730                            Input::new(&input)
731                                .with_size(self.options.size)
732                                .prefix(
733                                    Icon::new(IconName::Search)
734                                        .text_color(cx.theme().muted_foreground),
735                                )
736                                .cleanable(true)
737                                .p_0()
738                                .appearance(false),
739                        ),
740                )
741            })
742            .when(!loading, |this| {
743                this.on_action(cx.listener(Self::on_action_cancel))
744                    .on_action(cx.listener(Self::on_action_confirm))
745                    .on_action(cx.listener(Self::on_action_select_next))
746                    .on_action(cx.listener(Self::on_action_select_prev))
747                    .map(|this| {
748                        if let Some(view) = initial_view {
749                            this.child(view)
750                        } else {
751                            this.child(self.render_items(items_count, entities_count, window, cx))
752                        }
753                    })
754                    // Click out to cancel right clicked row
755                    .when(mouse_right_clicked_index.is_some(), |this| {
756                        this.on_mouse_down_out(cx.listener(|this, _, window, cx| {
757                            this.set_right_clicked_index(None, window, cx);
758                            cx.notify();
759                        }))
760                    })
761            })
762            .children(loading_view)
763    }
764}
765
766/// The List element.
767#[derive(IntoElement)]
768pub struct List<D: ListDelegate + 'static> {
769    state: Entity<ListState<D>>,
770    style: StyleRefinement,
771    options: ListOptions,
772}
773
774impl<D> List<D>
775where
776    D: ListDelegate + 'static,
777{
778    /// Create a new List element with the given ListState entity.
779    pub fn new(state: &Entity<ListState<D>>) -> Self {
780        Self {
781            state: state.clone(),
782            style: StyleRefinement::default(),
783            options: ListOptions::default(),
784        }
785    }
786
787    /// Set whether the scrollbar is visible, default is `true`.
788    pub fn scrollbar_visible(mut self, visible: bool) -> Self {
789        self.options.scrollbar_visible = visible;
790        self
791    }
792
793    /// Bounce at the vertical boundaries. On by default on iOS, Android and
794    /// macOS, off elsewhere; reduced motion disables displacement.
795    pub fn scroll_bounce(mut self, enabled: bool) -> Self {
796        self.options.scroll_bounce = Some(enabled);
797        self
798    }
799
800    /// Sets the placeholder text for the search input.
801    pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
802        self.options.search_placeholder = Some(placeholder.into());
803        self
804    }
805
806    /// Record the items area height on its first paint and, while `hold` is
807    /// true, keep the area at least that tall, so a search that filters items
808    /// does not shrink (and move) a popup menu opened above its trigger.
809    ///
810    /// Reset with [`ListState::reset_held_items_height`].
811    pub(crate) fn hold_items_height(mut self, hold: bool) -> Self {
812        self.options.record_items_height = true;
813        self.options.hold_items_height = hold;
814        self
815    }
816}
817
818impl<D> Styled for List<D>
819where
820    D: ListDelegate + 'static,
821{
822    fn style(&mut self) -> &mut StyleRefinement {
823        &mut self.style
824    }
825}
826
827impl<D> Sizable for List<D>
828where
829    D: ListDelegate + 'static,
830{
831    fn with_size(mut self, size: impl Into<Size>) -> Self {
832        self.options.size = size.into();
833        self
834    }
835}
836
837impl<D> RenderOnce for List<D>
838where
839    D: ListDelegate + 'static,
840{
841    fn render(mut self, _: &mut Window, cx: &mut App) -> impl IntoElement {
842        // Take paddings, max_height to options, and clear them from style,
843        // because they would be applied to the inner virtual list.
844        self.options.paddings = self.style.padding.clone();
845        self.options.max_height = self.style.max_size.height;
846        self.style.padding = EdgesRefinement::default();
847        self.style.max_size.height = None;
848
849        self.state.update(cx, |state, _| {
850            state.options = self.options;
851        });
852
853        div()
854            .id("list")
855            .size_full()
856            .refine_style(&self.style)
857            .child(self.state.clone())
858    }
859}
860
861#[cfg(test)]
862mod measurement_tests {
863    use super::*;
864    use crate::list::ListItem;
865    use gpui::{Element, TestAppContext};
866
867    struct Delegate {
868        counts: Vec<usize>,
869    }
870
871    impl ListDelegate for Delegate {
872        type Item = ListItem;
873        fn sections_count(&self, _: &App) -> usize {
874            self.counts.len()
875        }
876        fn items_count(&self, section: usize, _: &App) -> usize {
877            self.counts[section]
878        }
879        fn set_selected_index(
880            &mut self,
881            _: Option<IndexPath>,
882            _: &mut Window,
883            _: &mut Context<ListState<Self>>,
884        ) {
885        }
886        fn render_item(
887            &mut self,
888            index: IndexPath,
889            _: &mut Window,
890            _: &mut Context<ListState<Self>>,
891        ) -> Option<ListItem> {
892            (index.row < *self.counts.get(index.section)?)
893                .then(|| ListItem::new(index.row).h(px(if index.row == 0 { 36. } else { 48. })))
894        }
895    }
896
897    struct BounceList(Entity<ListState<Delegate>>);
898
899    impl Render for BounceList {
900        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
901            div()
902                .w(px(240.))
903                .h(px(200.))
904                .child(List::new(&self.0).scroll_bounce(true).size_full())
905        }
906    }
907
908    #[gpui::test]
909    fn scroll_bounce_list_accepts_a_reverse_wheel_during_return(cx: &mut TestAppContext) {
910        cx.update(crate::init);
911        let (view, cx) = cx.add_window_view(|window, cx| {
912            BounceList(cx.new(|cx| ListState::new(Delegate { counts: vec![40] }, window, cx)))
913        });
914        cx.update(|window, cx| window.draw(cx).clear(cx));
915        let state = view.read_with(cx, |view, _| view.0.clone());
916        let wheel = |cx: &mut gpui::VisualTestContext, dy| {
917            cx.simulate_event(gpui::ScrollEvent {
918                position: gpui::point(px(100.), px(100.)),
919                delta: gpui::ScrollDelta::Lines(gpui::point(0., dy)),
920                ..Default::default()
921            });
922        };
923        for (dy, phase) in [
924            (-10000., gpui::TouchPhase::Started),
925            (0., gpui::TouchPhase::Ended),
926        ] {
927            cx.simulate_event(gpui::ScrollEvent {
928                position: gpui::point(px(100.), px(100.)),
929                delta: gpui::ScrollDelta::Pixels(gpui::point(px(0.), px(dy))),
930                touch_phase: phase,
931                ..Default::default()
932            });
933        }
934        cx.update(|window, cx| window.draw(cx).clear(cx));
935        let end = state.read_with(cx, |state, _| state.scroll_handle.offset().y);
936        assert!(end < px(0.));
937        cx.executor()
938            .advance_clock(std::time::Duration::from_millis(200));
939        cx.update(|window, cx| window.draw(cx).clear(cx));
940        wheel(cx, 2.);
941        assert!(state.read_with(cx, |state, _| state.scroll_handle.offset().y) > end);
942    }
943
944    struct HeightProbe {
945        list: Entity<ListState<Delegate>>,
946        hold: bool,
947        height: std::rc::Rc<std::cell::Cell<Pixels>>,
948    }
949
950    impl Render for HeightProbe {
951        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
952            let height = self.height.clone();
953            div().w(px(240.)).child(
954                div()
955                    .on_prepaint(move |bounds, _, _| height.set(bounds.size.height))
956                    .child(
957                        List::new(&self.list)
958                            .max_h(px(200.))
959                            .hold_items_height(self.hold),
960                    ),
961            )
962        }
963    }
964
965    #[gpui::test]
966    fn hold_items_height_keeps_the_list_height_when_items_shrink(cx: &mut TestAppContext) {
967        cx.update(crate::init);
968        for (hold, expected_short) in [(false, px(36.)), (true, px(200.))] {
969            let height = std::rc::Rc::new(std::cell::Cell::new(px(0.)));
970            let (view, cx) = cx.add_window_view({
971                let height = height.clone();
972                move |window, cx| HeightProbe {
973                    list: cx.new(|cx| ListState::new(Delegate { counts: vec![40] }, window, cx)),
974                    hold: false,
975                    height,
976                }
977            });
978            cx.update(|window, cx| window.draw(cx).clear(cx));
979            assert_eq!(height.get(), px(200.), "a long list stops at max_h");
980
981            view.update(cx, |view, cx| {
982                view.hold = hold;
983                view.list.update(cx, |list, cx| {
984                    list.delegate.counts = vec![1];
985                    cx.notify();
986                })
987            });
988            cx.update(|window, cx| window.draw(cx).clear(cx));
989            assert_eq!(height.get(), expected_short);
990
991            if hold {
992                view.update(cx, |view, cx| {
993                    view.list.update(cx, |list, cx| {
994                        list.reset_held_items_height();
995                        cx.notify();
996                    })
997                });
998                cx.update(|window, cx| window.draw(cx).clear(cx));
999                assert_eq!(height.get(), px(36.), "reset releases the held height");
1000            }
1001        }
1002    }
1003
1004    #[gpui::test]
1005    fn measures_an_existing_row_when_the_requested_item_is_absent(cx: &mut TestAppContext) {
1006        cx.update(crate::init);
1007        let window = cx.add_empty_window();
1008        window.draw(
1009            gpui::point(px(0.), px(0.)),
1010            size(px(300.), px(300.)),
1011            |window, cx| {
1012                let list = cx.new(|cx| ListState::new(Delegate { counts: vec![0, 2] }, window, cx));
1013                list.update(cx, |list, cx| {
1014                    for (requested, expected_height) in [
1015                        (IndexPath::default(), 36.),
1016                        (IndexPath::new(1).section(1), 48.),
1017                        (IndexPath::new(99).section(1), 36.),
1018                        (IndexPath::new(0).section(99), 36.),
1019                    ] {
1020                        list.set_item_to_measure_index(requested, window, cx);
1021                        list.prepare_items_if_needed(window, cx);
1022                        let position = list
1023                            .rows_cache
1024                            .position_of(&IndexPath::new(0).section(1))
1025                            .unwrap();
1026                        assert_eq!(
1027                            list.rows_cache.entries_sizes[position].height,
1028                            px(expected_height)
1029                        );
1030                        assert_eq!(list.item_to_measure_index, requested);
1031                    }
1032                    let requested = IndexPath::new(1).section(1);
1033                    list.set_item_to_measure_index(requested, window, cx);
1034                    // Filtering removes the requested row, then all rows, before restoring it.
1035                    for (counts, expected_height) in [
1036                        (vec![0, 2], Some(48.)),
1037                        (vec![0, 1], Some(36.)),
1038                        (vec![0, 0], None),
1039                        (vec![0, 2], Some(48.)),
1040                    ] {
1041                        list.delegate.counts = counts;
1042                        list.prepare_items_if_needed(window, cx);
1043                        if let Some(height) = expected_height {
1044                            let position = list
1045                                .rows_cache
1046                                .position_of(&IndexPath::new(0).section(1))
1047                                .unwrap();
1048                            assert_eq!(list.rows_cache.entries_sizes[position].height, px(height));
1049                        } else {
1050                            assert_eq!(list.rows_cache.items_count(), 0);
1051                            assert!(list.rows_cache.entries_sizes.is_empty());
1052                        }
1053                        assert_eq!(list.item_to_measure_index, requested);
1054                    }
1055                });
1056                div()
1057            },
1058        );
1059    }
1060
1061    #[gpui::test]
1062    fn list_state_has_list_role(cx: &mut TestAppContext) {
1063        cx.update(crate::init);
1064        let window = cx.add_empty_window();
1065        window.draw(
1066            gpui::point(px(0.), px(0.)),
1067            size(px(300.), px(300.)),
1068            |window, cx| {
1069                let list = cx.new(|cx| ListState::new(Delegate { counts: vec![2] }, window, cx));
1070                list.update(cx, |list, cx| {
1071                    let element = list.render(window, cx).into_element();
1072                    assert_eq!(element.a11y_role(), Some(Role::List));
1073                });
1074                div()
1075            },
1076        );
1077    }
1078}