Skip to main content

gpui_component/searchable_list/
delegate.rs

1use gpui::{AnyElement, App, IntoElement, SharedString, Task, Window};
2
3use crate::IndexPath;
4
5use super::change::SearchableListChange;
6
7/// An item that can appear in a searchable list (Select, ComboBox).
8pub trait SearchableListItem: Clone {
9    type Value: Clone + PartialEq;
10
11    /// Short display label shown in the dropdown row and in the trigger by default.
12    ///
13    /// This is also what assistive technology reads as the committed value, so
14    /// it has to stand on its own as text even when [`Self::display_title`]
15    /// draws something richer.
16    fn title(&self) -> SharedString;
17
18    /// Override the trigger display element (e.g. "Country (US)" instead of just "United States").
19    ///
20    /// Returns `None` to fall back to `title()`.
21    ///
22    /// This is presentation only. An element is not text, so the accessible
23    /// value keeps reporting [`Self::title`]; if the two would read
24    /// differently, put the meaning a listener needs in `title()`.
25    fn display_title(&self) -> Option<AnyElement> {
26        None
27    }
28
29    /// Render this item's row content inside the dropdown.
30    ///
31    /// Override to add icons, avatars, secondary text, etc.
32    /// The default renders `title()`.
33    fn render(&self, _: &mut Window, _: &mut App) -> impl IntoElement {
34        self.title()
35    }
36
37    /// Render this item's row content with the text matching `query`
38    /// highlighted. Used instead of [`Self::render`] when the component
39    /// enables `highlight_matches`.
40    ///
41    /// The default renders `title()` with every case-insensitive occurrence
42    /// of `query` highlighted. Override it together with `render` to keep a
43    /// custom row when highlighting is enabled.
44    fn render_highlighted(&self, query: &str, _: &mut Window, cx: &mut App) -> impl IntoElement {
45        crate::label::highlight_matches(self.title(), query, cx)
46    }
47
48    /// The value that identifies this item.
49    fn value(&self) -> &Self::Value;
50
51    /// Whether this item matches the search query.
52    ///
53    /// Defaults to case-insensitive substring match on `title()`.
54    fn matches(&self, query: &str) -> bool {
55        self.title().to_lowercase().contains(&query.to_lowercase())
56    }
57
58    /// Whether this item should be shown as non-interactive (grayed-out, unclickable).
59    fn disabled(&self) -> bool {
60        false
61    }
62}
63
64/// Provides data and search behaviour to a searchable list component.
65pub trait SearchableListDelegate: Sized + 'static {
66    type Item: SearchableListItem;
67
68    /// Number of sections (groups) in the list.  Defaults to 1.
69    fn sections_count(&self, _: &App) -> usize {
70        1
71    }
72
73    /// Optional header element for the given section index.
74    ///
75    /// Deprecated: override [`render_section_header`] instead (provides `Window` + `App` access).
76    #[deprecated]
77    fn section(&self, _section: usize) -> Option<AnyElement> {
78        None
79    }
80
81    /// Number of items in the given section.
82    fn items_count(&self, section: usize) -> usize;
83
84    /// Return a reference to the item at the given index path.
85    fn item(&self, ix: IndexPath) -> Option<&Self::Item>;
86
87    /// Find the index path of the item whose value equals `value`.
88    fn position<V>(&self, _value: &V) -> Option<IndexPath>
89    where
90        Self::Item: SearchableListItem<Value = V>,
91        V: PartialEq;
92
93    /// Called when the search query changes.
94    ///
95    /// Implementations should filter or fetch items and may return an async `Task`.
96    /// The `App` context allows spawning background work.
97    fn perform_search(&mut self, _query: &str, _window: &mut Window, _cx: &mut App) -> Task<()> {
98        Task::ready(())
99    }
100
101    // MARK: Rendering hooks
102
103    /// Override the row content for the item at `ix`.
104    ///
105    /// When `Some(_)` is returned, the adapter suppresses its default `SearchableListItemElement`
106    /// layout (including the automatic trailing check icon) — the returned element is rendered
107    /// as-is. Return `None` to fall back to the standard rendering.
108    ///
109    /// `checked` is `true` when the item is in the current selection (as determined by
110    /// `is_item_checked`), letting custom renderers show their own selection indicator.
111    ///
112    /// Replaces the `item_renderer` closure that was previously set on `SearchableListAdapter`.
113    fn render_item(
114        &self,
115        _ix: IndexPath,
116        _item: &Self::Item,
117        _checked: bool,
118        _window: &mut Window,
119        _cx: &mut App,
120    ) -> Option<AnyElement> {
121        None
122    }
123
124    /// Render the header element for the given section (full render access).
125    ///
126    /// When `Some(_)` is returned, it is rendered directly — the adapter's default div wrapper
127    /// (padding, muted colour) is bypassed. Return `None` to fall back to the deprecated
128    /// `section()` wrapped in the standard div (no visual change for existing delegates).
129    fn render_section_header(
130        &self,
131        _section: usize,
132        _window: &mut Window,
133        _cx: &mut App,
134    ) -> Option<AnyElement> {
135        None
136    }
137
138    // MARK: Item state hooks
139
140    /// Whether the item at `ix` should be rendered as interactive.
141    ///
142    /// Default: `!item.disabled()`.
143    fn is_item_enabled(&self, _ix: IndexPath, item: &Self::Item, _cx: &App) -> bool {
144        !item.disabled()
145    }
146
147    /// Whether the item at `ix` should show a checkmark.
148    ///
149    /// `current_selection` is the slice of currently selected `(IndexPath, Item)` pairs.
150    ///
151    /// Default: checks whether the item's value is present in `current_selection`.
152    fn is_item_checked(
153        &self,
154        _ix: IndexPath,
155        item: &Self::Item,
156        current_selection: &[(IndexPath, Self::Item)],
157        _cx: &App,
158    ) -> bool {
159        current_selection
160            .iter()
161            .any(|(_, selected_item)| selected_item.value() == item.value())
162    }
163
164    // MARK: Lifecycle / selection hooks
165
166    /// Called before a user-triggered selection change is committed.
167    ///
168    /// `selection` is the live selection vec — the delegate may freely mutate it: add items,
169    /// remove items, reorder, or leave it unchanged to effectively veto the operation.
170    ///
171    /// `changes` is the slice of atomic changes the mode-strategy computed (e.g. Single
172    /// replacement deselects all then selects one; Multi toggles the clicked item). The delegate
173    /// is not required to apply them — they are informational. The default implementation applies
174    /// every change in order.
175    ///
176    /// No `cx` is available: this hook runs synchronously during the item-click handler while
177    /// the list entity is mutably borrowed. Side effects that need cx belong in `on_confirm`.
178    fn on_will_change(
179        &mut self,
180        selection: &mut Vec<(IndexPath, Self::Item)>,
181        changes: &[SearchableListChange],
182    ) {
183        for change in changes {
184            match change {
185                SearchableListChange::Select { index } => {
186                    let Some(item) = self.item(*index) else {
187                        continue;
188                    };
189
190                    if !selection
191                        .iter()
192                        .any(|(_, selected_item)| selected_item.value() == item.value())
193                    {
194                        selection.push((*index, item.clone()));
195                    }
196                }
197                SearchableListChange::Deselect { index } => {
198                    if let Some(item) = self.item(*index) {
199                        let has_value = selection
200                            .iter()
201                            .any(|(_, selected_item)| selected_item.value() == item.value());
202
203                        if has_value {
204                            selection
205                                .retain(|(_, selected_item)| selected_item.value() != item.value());
206                            continue;
207                        }
208                    }
209
210                    selection.retain(|(selected_ix, _)| selected_ix != index);
211                }
212            }
213        }
214    }
215
216    /// Called when the dropdown/popover is committed (Escape, `close_on_select`, or explicit
217    /// confirm). `final_selection` is the selection after the last committed change.
218    fn on_confirm(&mut self, _final_selection: &[(IndexPath, Self::Item)]) {}
219}