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    /// Search for an input showing this list under its field. The rows only
317    /// help type the text, so unlike a search box, nothing gets highlighted.
318    pub(crate) fn search_from_input(
319        &mut self,
320        query: String,
321        window: &mut Window,
322        cx: &mut Context<Self>,
323    ) {
324        self.search(query, false, window, cx);
325    }
326
327    /// Drop the search in flight, with whatever its delegate task still had to do.
328    pub(crate) fn cancel_search(&mut self) {
329        self._search_task = Task::ready(());
330    }
331
332    pub(crate) fn has_items(&self, cx: &App) -> bool {
333        (0..self.delegate.sections_count(cx).max(1))
334            .any(|section| self.delegate.items_count(section, cx) > 0)
335    }
336
337    /// Whether the selection still points at a row: results that arrive after
338    /// it was made may have fewer.
339    pub(crate) fn selected_item_exists(&self, cx: &App) -> bool {
340        self.selected_index
341            .is_some_and(|ix| ix.row < self.delegate.items_count(ix.section, cx))
342    }
343
344    /// Select the first row, even before the rows have been laid out.
345    pub(crate) fn select_first_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
346        let section = (0..self.delegate.sections_count(cx).max(1))
347            .find(|section| self.delegate.items_count(*section, cx) > 0);
348        if let Some(section) = section {
349            self.select_item(IndexPath::default().section(section), window, cx);
350        }
351    }
352
353    /// Like `on_action_select_prev`, but above the first row is nothing
354    /// instead of the last row.
355    pub(crate) fn select_prev_or_none(&mut self, window: &mut Window, cx: &mut Context<Self>) {
356        let Some(selected) = self.selected_index else {
357            return;
358        };
359        let prev = self.rows_cache.prev(Some(selected));
360        let wrapped = self.rows_cache.position_of(&prev) >= self.rows_cache.position_of(&selected);
361        if wrapped {
362            self._set_selected_index(None, window, cx);
363            cx.notify();
364        } else {
365            self.select_item(prev, window, cx);
366        }
367    }
368
369    fn start_search(&mut self, query: String, window: &mut Window, cx: &mut Context<Self>) {
370        self.search(query, true, window, cx);
371    }
372
373    /// Search with `query`, highlighting the first row when `highlight_first`
374    /// and there are rows, and nothing otherwise.
375    fn search(
376        &mut self,
377        query: String,
378        highlight_first: bool,
379        window: &mut Window,
380        cx: &mut Context<Self>,
381    ) {
382        self.set_searching(true, window, cx);
383        let search = self.delegate.perform_search(&query, window, cx);
384
385        if highlight_first && self.rows_cache.len() > 0 {
386            self._set_selected_index(Some(IndexPath::default()), window, cx);
387        } else {
388            self._set_selected_index(None, window, cx);
389        }
390
391        self._search_task = cx.spawn_in(window, async move |this, window| {
392            search.await;
393
394            _ = this.update_in(window, |this, _, _| {
395                this.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
396                this.last_query = Some(query);
397            });
398
399            // Always wait 100ms to avoid flicker
400            window
401                .background_executor()
402                .timer(Duration::from_millis(100))
403                .await;
404            _ = this.update_in(window, |this, window, cx| {
405                this.set_searching(false, window, cx);
406            });
407        });
408    }
409
410    fn set_searching(&mut self, searching: bool, window: &mut Window, cx: &mut Context<Self>) {
411        self.query_input
412            .update(cx, |input, cx| input.set_loading(searching, window, cx));
413    }
414
415    /// Dispatch delegate's `load_more` method when the
416    /// visible range is near the end.
417    fn load_more_if_need(
418        &mut self,
419        entities_count: usize,
420        visible_end: usize,
421        window: &mut Window,
422        cx: &mut Context<Self>,
423    ) {
424        // FIXME: Here need void sections items count.
425
426        let threshold = self.delegate.load_more_threshold();
427        // Securely handle subtract logic to prevent attempt
428        // to subtract with overflow
429        if visible_end >= entities_count.saturating_sub(threshold) {
430            if !self.delegate.has_more(cx) {
431                return;
432            }
433
434            self._load_more_task = cx.spawn_in(window, async move |view, cx| {
435                _ = view.update_in(cx, |view, window, cx| {
436                    view.delegate.load_more(window, cx);
437                });
438            });
439        }
440    }
441
442    pub(crate) fn reset_on_cancel(mut self, reset: bool) -> Self {
443        self.reset_on_cancel = reset;
444        self
445    }
446
447    pub(crate) fn on_action_cancel(
448        &mut self,
449        _: &Cancel,
450        window: &mut Window,
451        cx: &mut Context<Self>,
452    ) {
453        cx.propagate();
454        if self.reset_on_cancel {
455            self._set_selected_index(None, window, cx);
456        }
457
458        self.delegate.cancel(window, cx);
459        cx.emit(ListEvent::Cancel);
460        cx.notify();
461    }
462
463    pub(crate) fn on_action_confirm(
464        &mut self,
465        confirm: &Confirm,
466        window: &mut Window,
467        cx: &mut Context<Self>,
468    ) {
469        if self.rows_cache.len() == 0 {
470            return;
471        }
472
473        let Some(ix) = self.selected_index else {
474            return;
475        };
476
477        self.delegate
478            .set_selected_index(self.selected_index, window, cx);
479        self.delegate.confirm(confirm.secondary, window, cx);
480        cx.emit(ListEvent::Confirm(ix));
481        cx.notify();
482    }
483
484    fn select_item(&mut self, ix: IndexPath, window: &mut Window, cx: &mut Context<Self>) {
485        if !self.selectable {
486            return;
487        }
488
489        self.selected_index = Some(ix);
490        self.delegate.set_selected_index(Some(ix), window, cx);
491        self.scroll_to_selected_item(window, cx);
492        cx.emit(ListEvent::Select(ix));
493        cx.notify();
494    }
495
496    pub(crate) fn on_action_select_prev(
497        &mut self,
498        _: &SelectUp,
499        window: &mut Window,
500        cx: &mut Context<Self>,
501    ) {
502        if self.rows_cache.len() == 0 {
503            return;
504        }
505
506        let prev_ix = self.rows_cache.prev(self.selected_index);
507        self.select_item(prev_ix, window, cx);
508    }
509
510    pub(crate) fn on_action_select_next(
511        &mut self,
512        _: &SelectDown,
513        window: &mut Window,
514        cx: &mut Context<Self>,
515    ) {
516        if self.rows_cache.len() == 0 {
517            return;
518        }
519
520        let next_ix = self.rows_cache.next(self.selected_index);
521        self.select_item(next_ix, window, cx);
522    }
523
524    fn prepare_items_if_needed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
525        let sections_count = self.delegate.sections_count(cx).max(1);
526        let mut measured_size = MeasuredEntrySize::default();
527
528        // Measure the item_height and section header/footer height.
529        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
530        // Use the fallback for this measurement without overwriting the caller's configured index.
531        let requested = self.item_to_measure_index;
532        let item_to_measure = if requested.section < sections_count
533            && requested.row < self.delegate.items_count(requested.section, cx)
534        {
535            Some(requested)
536        } else {
537            (0..sections_count)
538                .find(|section| self.delegate.items_count(*section, cx) > 0)
539                .map(|section| IndexPath::default().section(section))
540        };
541        if let Some(index) = item_to_measure {
542            measured_size.item_size = self
543                .render_list_item(index, window, cx)
544                .into_any_element()
545                .layout_as_root(available_space, window, cx);
546        }
547
548        if let Some(mut el) = self
549            .delegate
550            .render_section_header(0, window, cx)
551            .map(|r| r.into_any_element())
552        {
553            measured_size.section_header_size = el.layout_as_root(available_space, window, cx);
554        }
555        if let Some(mut el) = self
556            .delegate
557            .render_section_footer(0, window, cx)
558            .map(|r| r.into_any_element())
559        {
560            measured_size.section_footer_size = el.layout_as_root(available_space, window, cx);
561        }
562
563        self.rows_cache
564            .prepare_if_needed(sections_count, measured_size, cx, |section_ix, cx| {
565                self.delegate.items_count(section_ix, cx)
566            });
567    }
568
569    fn render_list_item(
570        &mut self,
571        ix: IndexPath,
572        window: &mut Window,
573        cx: &mut Context<Self>,
574    ) -> impl IntoElement {
575        let selectable = self.selectable;
576        let selected = self.selected_index.map(|s| s.eq_row(ix)).unwrap_or(false);
577        let mouse_right_clicked = self
578            .mouse_right_clicked_index
579            .map(|s| s.eq_row(ix))
580            .unwrap_or(false);
581        let id = SharedString::from(format!("list-item-{}", ix));
582
583        let total_items = self.rows_cache.items_count();
584
585        div()
586            .id(id)
587            .role(Role::ListItem)
588            .aria_position_in_set(ix.row + 1)
589            .aria_size_of_set(total_items)
590            .aria_selected(selected)
591            .w_full()
592            .relative()
593            .overflow_hidden()
594            .children(self.delegate.render_item(ix, window, cx).map(|item| {
595                item.selected(selected)
596                    .secondary_selected(mouse_right_clicked)
597            }))
598            .when(selectable, |this| {
599                this.on_click(cx.listener(move |this, e: &ClickEvent, window, cx| {
600                    this.set_right_clicked_index(None, window, cx);
601                    this.selected_index = Some(ix);
602                    this.on_action_confirm(
603                        &Confirm {
604                            secondary: e.modifiers().secondary(cx),
605                        },
606                        window,
607                        cx,
608                    );
609                }))
610                .on_mouse_down(
611                    MouseButton::Right,
612                    cx.listener(move |this, _, window, cx| {
613                        this.set_right_clicked_index(Some(ix), window, cx);
614                        cx.notify();
615                    }),
616                )
617            })
618    }
619
620    fn render_items(
621        &mut self,
622        items_count: usize,
623        entities_count: usize,
624        window: &mut Window,
625        cx: &mut Context<Self>,
626    ) -> impl IntoElement {
627        let rows_cache = self.rows_cache.clone();
628        let scrollbar_visible = self.options.scrollbar_visible;
629        let scroll_handle = self.scroll_handle.clone();
630        let record_items_height = self.options.record_items_height;
631        let held_items_height = self.held_items_height.clone();
632        let items_min_height = self
633            .options
634            .hold_items_height
635            .then(|| held_items_height.get())
636            .flatten();
637        let item_to_measure_index = rows_cache
638            .position_of(&self.item_to_measure_index)
639            .or_else(|| rows_cache.first_entry_position())
640            .unwrap_or(0);
641
642        v_flex()
643            .flex_grow_1()
644            .relative()
645            .size_full()
646            .when_some(self.options.max_height, |this, h| this.max_h(h))
647            .when_some(items_min_height, |this, h| this.min_h(h))
648            .when(record_items_height, |this| {
649                this.on_prepaint(move |bounds, _, _| {
650                    if held_items_height.get().is_none() && bounds.size.height > px(0.) {
651                        held_items_height.set(Some(bounds.size.height));
652                    }
653                })
654            })
655            .overflow_hidden()
656            .when(items_count == 0, |this| {
657                this.child(self.delegate.render_empty(window, cx))
658            })
659            .when(items_count > 0, {
660                |this| {
661                    this.child(
662                        v_virtual_list(
663                            cx.entity(),
664                            "virtual-list",
665                            rows_cache.entries_sizes.clone(),
666                            move |list, visible_range: Range<usize>, window, cx| {
667                                list.load_more_if_need(
668                                    entities_count,
669                                    visible_range.end,
670                                    window,
671                                    cx,
672                                );
673
674                                // NOTE: Here the v_virtual_list would not able to have gap_y,
675                                // because the section header, footer is always have rendered as a empty child item,
676                                // even the delegate give a None result.
677
678                                visible_range
679                                    .map(|ix| {
680                                        let Some(entry) = rows_cache.get(ix) else {
681                                            return div();
682                                        };
683
684                                        div().children(match entry {
685                                            RowEntry::Entry(index) => Some(
686                                                list.render_list_item(index, window, cx)
687                                                    .into_any_element(),
688                                            ),
689                                            RowEntry::SectionHeader(section_ix) => list
690                                                .delegate_mut()
691                                                .render_section_header(section_ix, window, cx)
692                                                .map(|r| r.into_any_element()),
693                                            RowEntry::SectionFooter(section_ix) => list
694                                                .delegate_mut()
695                                                .render_section_footer(section_ix, window, cx)
696                                                .map(|r| r.into_any_element()),
697                                        })
698                                    })
699                                    .collect::<Vec<_>>()
700                            },
701                        )
702                        .with_item_to_measure_index(item_to_measure_index)
703                        .paddings(self.options.paddings.clone())
704                        .when(self.options.max_height.is_some(), |this| {
705                            this.with_sizing_behavior(ListSizingBehavior::Infer)
706                        })
707                        .track_scroll(&scroll_handle)
708                        .map(|list| {
709                            gpui_base::ScrollBounce::new("list-scroll-bounce", &scroll_handle, list)
710                                .when_some(self.options.scroll_bounce, |bounce, on| {
711                                    bounce.enabled(on)
712                                })
713                        })
714                        .into_any_element(),
715                    )
716                }
717            })
718            .when(scrollbar_visible, |this| {
719                this.child(Scrollbar::vertical(&scroll_handle).viewport_from_layout())
720            })
721    }
722}
723
724impl<D> Focusable for ListState<D>
725where
726    D: ListDelegate,
727{
728    fn focus_handle(&self, cx: &App) -> FocusHandle {
729        if self.searchable {
730            self.query_input.focus_handle(cx)
731        } else {
732            self.focus_handle.clone()
733        }
734    }
735}
736impl<D> EventEmitter<ListEvent> for ListState<D> where D: ListDelegate {}
737impl<D> Render for ListState<D>
738where
739    D: ListDelegate,
740{
741    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
742        self.prepare_items_if_needed(window, cx);
743
744        // Scroll to the selected item if it is set.
745        if let Some((ix, strategy)) = self.deferred_scroll_to_index.take() {
746            if let Some(item_ix) = self.rows_cache.position_of(&ix) {
747                self.scroll_handle.scroll_to_item(item_ix, strategy);
748            }
749        }
750
751        let loading = self.delegate().loading(cx);
752        let query_input = if self.searchable {
753            // sync placeholder
754            if let Some(placeholder) = &self.options.search_placeholder {
755                self.query_input.update(cx, |input, cx| {
756                    input.set_placeholder(placeholder.clone(), window, cx);
757                });
758            }
759            Some(self.query_input.clone())
760        } else {
761            None
762        };
763
764        let loading_view = if loading {
765            Some(self.delegate.render_loading(window, cx).into_any_element())
766        } else {
767            None
768        };
769        let initial_view = if let Some(input) = &query_input {
770            if input.read(cx).value().is_empty() {
771                self.delegate.render_initial(window, cx)
772            } else {
773                None
774            }
775        } else {
776            None
777        };
778        let items_count = self.rows_cache.items_count();
779        let entities_count = self.rows_cache.len();
780        let mouse_right_clicked_index = self.mouse_right_clicked_index;
781
782        v_flex()
783            .key_context("List")
784            .id("list-state")
785            .track_focus(&self.focus_handle)
786            .role(Role::List)
787            .size_full()
788            .relative()
789            .overflow_hidden()
790            .when_some(query_input, |this, input| {
791                this.child(
792                    div()
793                        .map(|this| match self.options.size {
794                            Size::Small => this.px_1p5(),
795                            _ => this.px_2(),
796                        })
797                        .border_b_1()
798                        .border_color(cx.theme().border)
799                        .child(
800                            Input::new(&input)
801                                .with_size(self.options.size)
802                                .prefix(
803                                    Icon::new(IconName::Search)
804                                        .text_color(cx.theme().muted_foreground),
805                                )
806                                .cleanable(true)
807                                .p_0()
808                                .appearance(false),
809                        ),
810                )
811            })
812            .when(!loading, |this| {
813                this.on_action(cx.listener(Self::on_action_cancel))
814                    .on_action(cx.listener(Self::on_action_confirm))
815                    .on_action(cx.listener(Self::on_action_select_next))
816                    .on_action(cx.listener(Self::on_action_select_prev))
817                    .map(|this| {
818                        if let Some(view) = initial_view {
819                            this.child(view)
820                        } else {
821                            this.child(self.render_items(items_count, entities_count, window, cx))
822                        }
823                    })
824                    // Click out to cancel right clicked row
825                    .when(mouse_right_clicked_index.is_some(), |this| {
826                        this.on_mouse_down_out(cx.listener(|this, _, window, cx| {
827                            this.set_right_clicked_index(None, window, cx);
828                            cx.notify();
829                        }))
830                    })
831            })
832            .children(loading_view)
833    }
834}
835
836/// The List element.
837#[derive(IntoElement)]
838pub struct List<D: ListDelegate + 'static> {
839    state: Entity<ListState<D>>,
840    style: StyleRefinement,
841    options: ListOptions,
842}
843
844impl<D> List<D>
845where
846    D: ListDelegate + 'static,
847{
848    /// Create a new List element with the given ListState entity.
849    pub fn new(state: &Entity<ListState<D>>) -> Self {
850        Self {
851            state: state.clone(),
852            style: StyleRefinement::default(),
853            options: ListOptions::default(),
854        }
855    }
856
857    /// Set whether the scrollbar is visible, default is `true`.
858    pub fn scrollbar_visible(mut self, visible: bool) -> Self {
859        self.options.scrollbar_visible = visible;
860        self
861    }
862
863    /// Bounce at the vertical boundaries. On by default on iOS, Android and
864    /// macOS, off elsewhere; reduced motion disables displacement.
865    pub fn scroll_bounce(mut self, enabled: bool) -> Self {
866        self.options.scroll_bounce = Some(enabled);
867        self
868    }
869
870    /// Sets the placeholder text for the search input.
871    pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
872        self.options.search_placeholder = Some(placeholder.into());
873        self
874    }
875
876    /// Record the items area height on its first paint and, while `hold` is
877    /// true, keep the area at least that tall, so a search that filters items
878    /// does not shrink (and move) a popup menu opened above its trigger.
879    ///
880    /// Reset with [`ListState::reset_held_items_height`].
881    pub(crate) fn hold_items_height(mut self, hold: bool) -> Self {
882        self.options.record_items_height = true;
883        self.options.hold_items_height = hold;
884        self
885    }
886}
887
888impl<D> Styled for List<D>
889where
890    D: ListDelegate + 'static,
891{
892    fn style(&mut self) -> &mut StyleRefinement {
893        &mut self.style
894    }
895}
896
897impl<D> Sizable for List<D>
898where
899    D: ListDelegate + 'static,
900{
901    fn with_size(mut self, size: impl Into<Size>) -> Self {
902        self.options.size = size.into();
903        self
904    }
905}
906
907impl<D> RenderOnce for List<D>
908where
909    D: ListDelegate + 'static,
910{
911    fn render(mut self, _: &mut Window, cx: &mut App) -> impl IntoElement {
912        // Take paddings, max_height to options, and clear them from style,
913        // because they would be applied to the inner virtual list.
914        self.options.paddings = self.style.padding.clone();
915        self.options.max_height = self.style.max_size.height;
916        self.style.padding = EdgesRefinement::default();
917        self.style.max_size.height = None;
918
919        self.state.update(cx, |state, _| {
920            state.options = self.options;
921        });
922
923        div()
924            .id("list")
925            .size_full()
926            .refine_style(&self.style)
927            .child(self.state.clone())
928    }
929}
930
931#[cfg(test)]
932mod measurement_tests {
933    use super::*;
934    use crate::list::ListItem;
935    use gpui::{Element, TestAppContext};
936
937    struct Delegate {
938        counts: Vec<usize>,
939    }
940
941    impl ListDelegate for Delegate {
942        type Item = ListItem;
943        fn sections_count(&self, _: &App) -> usize {
944            self.counts.len()
945        }
946        fn items_count(&self, section: usize, _: &App) -> usize {
947            self.counts[section]
948        }
949        fn set_selected_index(
950            &mut self,
951            _: Option<IndexPath>,
952            _: &mut Window,
953            _: &mut Context<ListState<Self>>,
954        ) {
955        }
956        fn render_item(
957            &mut self,
958            index: IndexPath,
959            _: &mut Window,
960            _: &mut Context<ListState<Self>>,
961        ) -> Option<ListItem> {
962            (index.row < *self.counts.get(index.section)?)
963                .then(|| ListItem::new(index.row).h(px(if index.row == 0 { 36. } else { 48. })))
964        }
965    }
966
967    struct BounceList(Entity<ListState<Delegate>>);
968
969    impl Render for BounceList {
970        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
971            div()
972                .w(px(240.))
973                .h(px(200.))
974                .child(List::new(&self.0).scroll_bounce(true).size_full())
975        }
976    }
977
978    #[gpui::test]
979    fn scroll_bounce_list_accepts_a_reverse_wheel_during_return(cx: &mut TestAppContext) {
980        cx.update(crate::init);
981        let (view, cx) = cx.add_window_view(|window, cx| {
982            BounceList(cx.new(|cx| ListState::new(Delegate { counts: vec![40] }, window, cx)))
983        });
984        cx.update(|window, cx| window.draw(cx).clear(cx));
985        let state = view.read_with(cx, |view, _| view.0.clone());
986        let wheel = |cx: &mut gpui::VisualTestContext, dy| {
987            cx.simulate_event(gpui::ScrollEvent {
988                position: gpui::point(px(100.), px(100.)),
989                delta: gpui::ScrollDelta::Lines(gpui::point(0., dy)),
990                ..Default::default()
991            });
992        };
993        for (dy, phase) in [
994            (-10000., gpui::TouchPhase::Started),
995            (0., gpui::TouchPhase::Ended),
996        ] {
997            cx.simulate_event(gpui::ScrollEvent {
998                position: gpui::point(px(100.), px(100.)),
999                delta: gpui::ScrollDelta::Pixels(gpui::point(px(0.), px(dy))),
1000                touch_phase: phase,
1001                ..Default::default()
1002            });
1003        }
1004        cx.update(|window, cx| window.draw(cx).clear(cx));
1005        let end = state.read_with(cx, |state, _| state.scroll_handle.offset().y);
1006        assert!(end < px(0.));
1007        cx.executor()
1008            .advance_clock(std::time::Duration::from_millis(200));
1009        cx.update(|window, cx| window.draw(cx).clear(cx));
1010        wheel(cx, 2.);
1011        assert!(state.read_with(cx, |state, _| state.scroll_handle.offset().y) > end);
1012    }
1013
1014    struct HeightProbe {
1015        list: Entity<ListState<Delegate>>,
1016        hold: bool,
1017        height: std::rc::Rc<std::cell::Cell<Pixels>>,
1018    }
1019
1020    impl Render for HeightProbe {
1021        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1022            let height = self.height.clone();
1023            div().w(px(240.)).child(
1024                div()
1025                    .on_prepaint(move |bounds, _, _| height.set(bounds.size.height))
1026                    .child(
1027                        List::new(&self.list)
1028                            .max_h(px(200.))
1029                            .hold_items_height(self.hold),
1030                    ),
1031            )
1032        }
1033    }
1034
1035    #[gpui::test]
1036    fn hold_items_height_keeps_the_list_height_when_items_shrink(cx: &mut TestAppContext) {
1037        cx.update(crate::init);
1038        for (hold, expected_short) in [(false, px(36.)), (true, px(200.))] {
1039            let height = std::rc::Rc::new(std::cell::Cell::new(px(0.)));
1040            let (view, cx) = cx.add_window_view({
1041                let height = height.clone();
1042                move |window, cx| HeightProbe {
1043                    list: cx.new(|cx| ListState::new(Delegate { counts: vec![40] }, window, cx)),
1044                    hold: false,
1045                    height,
1046                }
1047            });
1048            cx.update(|window, cx| window.draw(cx).clear(cx));
1049            assert_eq!(height.get(), px(200.), "a long list stops at max_h");
1050
1051            view.update(cx, |view, cx| {
1052                view.hold = hold;
1053                view.list.update(cx, |list, cx| {
1054                    list.delegate.counts = vec![1];
1055                    cx.notify();
1056                })
1057            });
1058            cx.update(|window, cx| window.draw(cx).clear(cx));
1059            assert_eq!(height.get(), expected_short);
1060
1061            if hold {
1062                view.update(cx, |view, cx| {
1063                    view.list.update(cx, |list, cx| {
1064                        list.reset_held_items_height();
1065                        cx.notify();
1066                    })
1067                });
1068                cx.update(|window, cx| window.draw(cx).clear(cx));
1069                assert_eq!(height.get(), px(36.), "reset releases the held height");
1070            }
1071        }
1072    }
1073
1074    #[gpui::test]
1075    fn measures_an_existing_row_when_the_requested_item_is_absent(cx: &mut TestAppContext) {
1076        cx.update(crate::init);
1077        let window = cx.add_empty_window();
1078        window.draw(
1079            gpui::point(px(0.), px(0.)),
1080            size(px(300.), px(300.)),
1081            |window, cx| {
1082                let list = cx.new(|cx| ListState::new(Delegate { counts: vec![0, 2] }, window, cx));
1083                list.update(cx, |list, cx| {
1084                    for (requested, expected_height) in [
1085                        (IndexPath::default(), 36.),
1086                        (IndexPath::new(1).section(1), 48.),
1087                        (IndexPath::new(99).section(1), 36.),
1088                        (IndexPath::new(0).section(99), 36.),
1089                    ] {
1090                        list.set_item_to_measure_index(requested, window, cx);
1091                        list.prepare_items_if_needed(window, cx);
1092                        let position = list
1093                            .rows_cache
1094                            .position_of(&IndexPath::new(0).section(1))
1095                            .unwrap();
1096                        assert_eq!(
1097                            list.rows_cache.entries_sizes[position].height,
1098                            px(expected_height)
1099                        );
1100                        assert_eq!(list.item_to_measure_index, requested);
1101                    }
1102                    let requested = IndexPath::new(1).section(1);
1103                    list.set_item_to_measure_index(requested, window, cx);
1104                    // Filtering removes the requested row, then all rows, before restoring it.
1105                    for (counts, expected_height) in [
1106                        (vec![0, 2], Some(48.)),
1107                        (vec![0, 1], Some(36.)),
1108                        (vec![0, 0], None),
1109                        (vec![0, 2], Some(48.)),
1110                    ] {
1111                        list.delegate.counts = counts;
1112                        list.prepare_items_if_needed(window, cx);
1113                        if let Some(height) = expected_height {
1114                            let position = list
1115                                .rows_cache
1116                                .position_of(&IndexPath::new(0).section(1))
1117                                .unwrap();
1118                            assert_eq!(list.rows_cache.entries_sizes[position].height, px(height));
1119                        } else {
1120                            assert_eq!(list.rows_cache.items_count(), 0);
1121                            assert!(list.rows_cache.entries_sizes.is_empty());
1122                        }
1123                        assert_eq!(list.item_to_measure_index, requested);
1124                    }
1125                });
1126                div()
1127            },
1128        );
1129    }
1130
1131    #[gpui::test]
1132    fn list_state_has_list_role(cx: &mut TestAppContext) {
1133        cx.update(crate::init);
1134        let window = cx.add_empty_window();
1135        window.draw(
1136            gpui::point(px(0.), px(0.)),
1137            size(px(300.), px(300.)),
1138            |window, cx| {
1139                let list = cx.new(|cx| ListState::new(Delegate { counts: vec![2] }, window, cx));
1140                list.update(cx, |list, cx| {
1141                    let element = list.render(window, cx).into_element();
1142                    assert_eq!(element.a11y_role(), Some(Role::List));
1143                });
1144                div()
1145            },
1146        );
1147    }
1148}