Skip to main content

gpui_component/searchable_list/
state.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AnyElement, App, AppContext as _, Bounds, Context, ElementId, Entity, FocusHandle,
5    Focusable as _, IntoElement, Length, Pixels, StyleRefinement, Styled, Subscription, Window,
6    prelude::FluentBuilder as _,
7};
8
9use gpui_base::{DeferredPopover, Placement, Positioner};
10
11use crate::{IndexPath, Size, list::ListState, searchable_list::adapter::SearchableListAdapter};
12
13use super::delegate::{SearchableListDelegate, SearchableListItem};
14
15#[derive(Clone, Default)]
16pub(crate) struct MenuSide(Rc<Cell<Option<Placement>>>);
17
18impl MenuSide {
19    pub(crate) fn is_above(&self) -> bool {
20        self.0.get() == Some(Placement::Top)
21    }
22
23    pub(crate) fn reset(&self) {
24        self.0.set(None);
25    }
26}
27
28pub(crate) fn menu_popup(
29    menu_side: &MenuSide,
30    id: impl Into<ElementId>,
31    bounds: Bounds<Pixels>,
32    surface: impl IntoElement + Styled + 'static,
33    cx: &App,
34) -> Positioner {
35    let side = menu_side.0.clone();
36    crate::popover::dropdown_popup(id, bounds, surface, cx)
37        .when_some(side.get(), |popup, placement| popup.placement(placement))
38        .on_position(move |position| {
39            if side.get().is_none() {
40                side.set(position.placement);
41            }
42        })
43}
44
45/// Shared infrastructure for all searchable-list-based components (`SelectState`, `ComboBoxState`).
46///
47/// This struct is a plain nested value inside a GPUI entity — it has no entity context of its
48/// own and cannot call `cx.notify()` or `cx.emit()`. Callers are responsible for those after
49/// calling mutable methods.
50pub struct SearchableListState<D: SearchableListDelegate + 'static>
51where
52    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
53{
54    pub focus_handle: FocusHandle,
55    pub(crate) list: Entity<ListState<SearchableListAdapter<D>>>,
56    pub(crate) selection: Vec<(IndexPath, D::Item)>,
57    pub(crate) open: bool,
58    /// Held while the popup is open, so that a component dropped without
59    /// closing it first takes its registration with it.
60    pub(crate) deferred_context: Option<DeferredPopover>,
61    pub(crate) bounds: Bounds<Pixels>,
62
63    // Shared options
64    pub(crate) size: Size,
65    pub(crate) style: StyleRefinement,
66    pub(crate) cleanable: bool,
67    pub(crate) placeholder: Option<gpui::SharedString>,
68    pub(crate) search_placeholder: Option<gpui::SharedString>,
69    pub(crate) highlight_matches: bool,
70    pub(crate) menu_width: Length,
71    pub(crate) menu_max_h: Length,
72    pub(crate) menu_side: MenuSide,
73    pub(crate) scroll_bounce: Option<bool>,
74    pub(crate) disabled: bool,
75    pub(crate) appearance: bool,
76    pub(crate) empty: Option<Box<dyn Fn(&mut Window, &App) -> AnyElement + 'static>>,
77
78    pub(crate) _subscriptions: Vec<Subscription>,
79}
80
81#[allow(private_bounds)]
82impl<D: SearchableListDelegate + 'static> SearchableListState<D>
83where
84    <D::Item as SearchableListItem>::Value: PartialEq + Clone,
85{
86    /// Create a new `SearchableListState`, creating the list entity in the given parent context.
87    ///
88    /// `on_confirm`, `on_cancel`, and `on_render_empty` are forwarded to the underlying adapter.
89    /// `on_blur` is a function pointer invoked on the parent entity when focus leaves any of the
90    /// list's focus handles.
91    #[allow(clippy::too_many_arguments)]
92    pub fn new<P: 'static>(
93        delegate: D,
94        selected_indices: Vec<IndexPath>,
95        on_confirm: impl Fn(
96            Option<IndexPath>,
97            bool,
98            &mut Window,
99            &mut Context<ListState<SearchableListAdapter<D>>>,
100        ) + 'static,
101        on_cancel: impl Fn(
102            Option<IndexPath>,
103            &mut Window,
104            &mut Context<ListState<SearchableListAdapter<D>>>,
105        ) + 'static,
106        on_render_empty: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
107        on_blur: fn(&mut P, &mut Window, &mut Context<P>),
108        window: &mut Window,
109        cx: &mut Context<P>,
110    ) -> Self {
111        let focus_handle = cx.focus_handle();
112
113        let adapter = SearchableListAdapter::new(delegate, on_confirm, on_cancel, on_render_empty);
114        let list = cx.new(|cx| ListState::new(adapter, window, cx).reset_on_cancel(false));
115
116        let list_focus_handle = list.read(cx).focus_handle.clone();
117        let list_search_focus_handle = list.read(cx).query_input.focus_handle(cx);
118
119        let selection = {
120            let delegate = &list.read(cx).delegate().delegate;
121
122            selected_indices
123                .iter()
124                .copied()
125                .filter_map(|ix| delegate.item(ix).map(|i| (ix, i.clone())))
126                .collect::<Vec<_>>()
127        };
128
129        if let Some(cursor) = selected_indices.first().copied() {
130            list.update(cx, |l, cx| {
131                l.set_selected_index(Some(cursor), window, cx);
132            });
133        }
134
135        // Prime the adapter's snapshot so the very first render pass sees correct check state.
136        let initial_snapshot = selection.clone();
137        list.update(cx, |l, _| {
138            l.delegate_mut().update_selection_snapshot(initial_snapshot);
139        });
140
141        let _subscriptions = vec![
142            cx.on_blur(&list_focus_handle, window, on_blur),
143            cx.on_blur(&list_search_focus_handle, window, on_blur),
144            cx.on_blur(&focus_handle, window, on_blur),
145        ];
146
147        Self {
148            focus_handle,
149            list,
150            selection,
151            open: false,
152            deferred_context: None,
153            bounds: Bounds::default(),
154            size: Size::default(),
155            style: StyleRefinement::default(),
156            cleanable: false,
157            placeholder: None,
158            search_placeholder: None,
159            highlight_matches: false,
160            menu_width: Length::Auto,
161            menu_max_h: gpui::rems(20.).into(),
162            menu_side: MenuSide::default(),
163            scroll_bounce: None,
164            disabled: false,
165            appearance: true,
166            empty: None,
167            _subscriptions,
168        }
169    }
170
171    // MARK: Read-only accessors
172
173    pub fn selection(&self) -> &[(IndexPath, D::Item)] {
174        &self.selection
175    }
176
177    pub fn selected_values(&self) -> Vec<<D::Item as SearchableListItem>::Value> {
178        self.selection
179            .iter()
180            .map(|(_ix, i)| i.value().clone())
181            .collect()
182    }
183
184    pub fn is_open(&self) -> bool {
185        self.open
186    }
187
188    pub fn focus_handle(&self) -> &FocusHandle {
189        &self.focus_handle
190    }
191
192    /// Drop the search query, if there is one, so that a value lookup resolves
193    /// against every item rather than the filtered view.
194    ///
195    /// A delegate's `position` answers for the list as it is currently
196    /// displayed, which is what a click or a keyboard cursor needs. Projecting
197    /// an authoritative value in from outside is not a position in that view:
198    /// the value's item may be filtered out, and dropping it would let whatever
199    /// the user last typed decide which values can be selected at all.
200    ///
201    /// Search runs synchronously for a delegate holding its own items, so a
202    /// lookup right after this call sees the full set. One that fetches its
203    /// items cannot answer for a value it has not fetched, and this cannot make
204    /// it.
205    pub(crate) fn clear_query(&mut self, window: &mut Window, cx: &mut App) {
206        self.list.update(cx, |list, cx| {
207            if !list.query_input.read(cx).value().is_empty() {
208                list.set_query("", window, cx);
209            }
210        });
211    }
212
213    // MARK: Mutation (no cx — callers emit events and notify)
214
215    /// Add an index+item pair to the selection; no-op if already present.
216    pub(crate) fn add_by_item(&mut self, index: IndexPath, item: D::Item) {
217        if self.selection.iter().any(|(ix, _)| ix == &index) {
218            return;
219        }
220
221        self.selection.push((index, item));
222    }
223
224    /// Remove an index from the selection by index path.
225    pub(crate) fn remove_by_index(&mut self, index: &IndexPath) -> bool {
226        if let Some(pos) = self.selection.iter().position(|(ix, _)| ix == index) {
227            self.selection.remove(pos);
228
229            return true;
230        }
231
232        false
233    }
234
235    /// Add a single index to the selection by looking up the item in the list.
236    ///
237    /// Requires `cx` only to read the list entity; does not notify.
238    pub fn add_selected_index(&mut self, index: IndexPath, cx: &App) -> bool {
239        if self.selection.iter().any(|(ix, _)| ix == &index) {
240            return false;
241        }
242
243        let Some(item) = self.list.read(cx).delegate().delegate.item(index) else {
244            return false;
245        };
246
247        self.add_by_item(index, item.clone());
248
249        true
250    }
251
252    /// Remove a single index from the selection.
253    pub fn remove_selected_index(&mut self, index: IndexPath) -> bool {
254        self.remove_by_index(&index)
255    }
256
257    /// Replace the entire selection, looking up items from the list.
258    pub fn set_selected_indices(&mut self, indices: impl IntoIterator<Item = IndexPath>, cx: &App) {
259        let indices: Vec<IndexPath> = indices.into_iter().collect();
260
261        self.selection = indices
262            .into_iter()
263            .filter_map(|ix| {
264                self.list
265                    .read(cx)
266                    .delegate()
267                    .delegate
268                    .item(ix)
269                    .map(|i| (ix, i.clone()))
270            })
271            .collect();
272    }
273
274    /// Push the current selection into the adapter's snapshot so the next render pass sees
275    /// up-to-date check state. Call after every mutation that changes `self.selection`.
276    pub(crate) fn sync_snapshot<P: 'static>(&self, cx: &mut Context<P>) {
277        let snapshot = self.selection.clone();
278        self.list.update(cx, |l, _| {
279            l.delegate_mut().update_selection_snapshot(snapshot);
280        });
281    }
282}