Skip to main content

gpui_material_components/input/exposed_dropdown/
state.rs

1use std::rc::{Rc, Weak};
2
3use gpui::{
4    AppContext, Context, ElementId, Entity, EntityInputHandler, FocusHandle, Focusable,
5    ListAlignment, ListOffset, ListState, Pixels, SharedString, Subscription, Window, px,
6};
7
8use super::{
9    super::{TextFieldEvent, TextFieldState},
10    Dismiss, DropdownOption, OpenChange,
11};
12
13#[derive(Default)]
14pub(super) struct Visibility {
15    pub(super) controlled: Option<bool>,
16    pub(super) change: Option<OpenChange>,
17    pub(super) dismiss: Option<Dismiss>,
18}
19
20#[derive(Clone, Copy)]
21pub(super) enum Opening {
22    Editor,
23    PopupFromPrimary,
24    PopupFromSecondary,
25}
26
27/// Retains the filtered model independently of the visible rows. Comparisons
28/// use stable IDs and labels; only a changed collection or query is filtered.
29#[derive(Default)]
30pub(super) struct OptionSnapshot {
31    pub(super) source: Rc<[DropdownOption]>,
32    query: Option<SharedString>,
33    pub(super) visible: Rc<[DropdownOption]>,
34}
35
36impl OptionSnapshot {
37    pub(super) fn reconcile(
38        &mut self,
39        source: &Rc<[DropdownOption]>,
40        query: Option<SharedString>,
41    ) -> bool {
42        let source_unchanged =
43            Rc::ptr_eq(&self.source, source) || self.source.as_ref() == source.as_ref();
44        if !Rc::ptr_eq(&self.source, source) {
45            self.source = source.clone();
46        }
47        if source_unchanged && self.query == query {
48            return false;
49        }
50        self.visible = if let Some(query) = &query {
51            let query_lower = query.to_lowercase();
52            self.source
53                .iter()
54                .filter(|option| contains_ignore_case(&option.label, query, &query_lower))
55                .cloned()
56                .collect()
57        } else {
58            self.source.clone()
59        };
60        self.query = query;
61        true
62    }
63}
64
65pub(super) fn contains_ignore_case(haystack: &str, needle_raw: &str, needle_lower: &str) -> bool {
66    if haystack.is_ascii() && needle_raw.is_ascii() {
67        needle_raw.is_empty()
68            || haystack
69                .as_bytes()
70                .windows(needle_raw.len())
71                .any(|window| window.eq_ignore_ascii_case(needle_raw.as_bytes()))
72    } else {
73        haystack.to_lowercase().contains(needle_lower)
74    }
75}
76
77/// Keeps the editable query and pending keyboard choice across renders.
78pub struct ExposedDropdownState {
79    pub(super) input: Entity<TextFieldState>,
80    pub(super) committed: SharedString,
81    pub(super) editable: bool,
82    pub(super) open: bool,
83    presented_open: bool,
84    visibility: Weak<Visibility>,
85    primary_enabled: bool,
86    opening: Option<Opening>,
87    pub(super) popup_focus: FocusHandle,
88    pub(super) secondary_focus: FocusHandle,
89    pub(super) restore_focus: Option<FocusHandle>,
90    focus_epoch: u64,
91    pub(super) active: Option<ElementId>,
92    active_index: Option<usize>,
93    pub(super) selected: Option<ElementId>,
94    pub(super) scroll: ListState,
95    presented: Rc<[DropdownOption]>,
96    metrics: Option<(Pixels, f32, Pixels, gpui_material_theme::Typography, u64)>,
97    options: OptionSnapshot,
98    _input: Subscription,
99}
100
101impl ExposedDropdownState {
102    pub fn new(
103        value: impl Into<SharedString>,
104        editable: bool,
105        window: &mut Window,
106        cx: &mut Context<Self>,
107    ) -> Self {
108        let value = value.into();
109        let input = cx.new(|cx| TextFieldState::new(window, cx).default_value(value));
110        Self::with_editor(&input, editable, window, cx)
111    }
112
113    /// Uses a caller-retained single-line editor and its current value.
114    pub fn with_editor(
115        input: &Entity<TextFieldState>,
116        editable: bool,
117        window: &mut Window,
118        cx: &mut Context<Self>,
119    ) -> Self {
120        let committed = input.read(cx).value();
121        input.update(cx, |input, cx| input.set_readonly(!editable, cx));
122        let subscription = cx.subscribe_in(input, window, |state, input, event, window, cx| {
123            if !state.editable || !matches!(event, TextFieldEvent::Change) {
124                return;
125            }
126            if input.update(cx, |input, cx| {
127                input.marked_text_range(window, cx).is_some()
128            }) {
129                return;
130            }
131            if input.read(cx).value() != state.committed {
132                state.active = None;
133                state.active_index = None;
134                if state.primary_enabled {
135                    state.request_open(true, Some(Opening::Editor), window, cx);
136                }
137            }
138            cx.notify();
139        });
140        Self {
141            input: input.clone(),
142            committed,
143            editable,
144            open: false,
145            presented_open: false,
146            visibility: Weak::new(),
147            primary_enabled: true,
148            opening: None,
149            popup_focus: cx.focus_handle(),
150            secondary_focus: cx.focus_handle(),
151            restore_focus: None,
152            focus_epoch: 0,
153            active: None,
154            active_index: None,
155            selected: None,
156            scroll: ListState::new(0, ListAlignment::Top, px(280.)),
157            presented: Rc::default(),
158            metrics: None,
159            options: OptionSnapshot::default(),
160            _input: subscription,
161        }
162    }
163
164    /// Synchronizes the label and dismisses an internally controlled list.
165    pub fn set_value(
166        &mut self,
167        value: impl Into<SharedString>,
168        window: &mut Window,
169        cx: &mut Context<Self>,
170    ) {
171        let value = value.into();
172        if self.committed != value {
173            self.selected = None;
174        }
175        self.committed = value;
176        if self
177            .visibility
178            .upgrade()
179            .is_none_or(|policy| policy.controlled.is_none())
180        {
181            self.open = false;
182        }
183        self.reset_draft(window, cx);
184    }
185
186    pub fn is_open(&self) -> bool {
187        self.open
188    }
189
190    pub fn selected_option_id(&self) -> Option<&ElementId> {
191        self.selected.as_ref()
192    }
193
194    /// The retained variable-height list position, including while closed.
195    pub fn scroll_state(&self) -> &ListState {
196        &self.scroll
197    }
198
199    /// Uses a caller-owned list position. The dropdown owns its item count.
200    pub fn set_scroll_state(&mut self, scroll: &ListState, cx: &mut Context<Self>) {
201        let anchor = scroll.logical_scroll_top();
202        scroll.reset(self.presented.len());
203        scroll.scroll_to(anchor);
204        self.scroll = scroll.clone();
205        self.metrics = None;
206        cx.notify();
207    }
208
209    pub(super) fn reset_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
210        self.active = None;
211        self.active_index = None;
212        self.input.update(cx, |input, cx| {
213            if input.value() != self.committed {
214                input.set_value(self.committed.clone(), window, cx);
215            }
216        });
217        cx.notify();
218    }
219
220    pub(super) fn request_open(
221        &mut self,
222        open: bool,
223        opening: Option<Opening>,
224        window: &mut Window,
225        cx: &mut Context<Self>,
226    ) {
227        if self.open == open {
228            return;
229        }
230        self.opening = opening;
231        let visibility = self.visibility.upgrade();
232        if visibility
233            .as_ref()
234            .is_none_or(|policy| policy.controlled.is_none())
235        {
236            self.open = open;
237            if !open {
238                self.reset_draft(window, cx);
239            }
240        }
241        if let Some(visibility) = visibility
242            && (visibility.change.is_some() || !open && visibility.dismiss.is_some())
243        {
244            window.defer(cx, move |window, cx| {
245                if let Some(change) = &visibility.change {
246                    change(open, window, cx);
247                }
248                if !open && let Some(dismiss) = &visibility.dismiss {
249                    dismiss(window, cx);
250                }
251            });
252        }
253        cx.notify();
254    }
255
256    pub(super) fn present(
257        &mut self,
258        visibility: &Rc<Visibility>,
259        primary_enabled: bool,
260        secondary_enabled: bool,
261        primary: Opening,
262        window: &mut Window,
263        cx: &mut Context<Self>,
264    ) {
265        self.primary_enabled = primary_enabled;
266        self.open = visibility.controlled.unwrap_or(self.open);
267        self.visibility = Rc::downgrade(visibility);
268        let opening = self.opening.take();
269        if self.presented_open == self.open {
270            if !self.open {
271                self.active = None;
272                self.active_index = None;
273            }
274            return;
275        }
276        self.presented_open = self.open;
277        self.focus_epoch = self.focus_epoch.wrapping_add(1);
278        let epoch = self.focus_epoch;
279        if self.open {
280            let editor = self.input.read(cx).focus_handle(cx);
281            let (focus, restore) = match opening.unwrap_or(primary) {
282                Opening::Editor => (editor.clone(), None),
283                Opening::PopupFromPrimary => (self.popup_focus.clone(), Some(editor)),
284                Opening::PopupFromSecondary => {
285                    (self.popup_focus.clone(), Some(self.secondary_focus.clone()))
286                }
287            };
288            self.restore_focus = restore;
289            if !focus.is_focused(window) {
290                let state = cx.weak_entity();
291                window.on_next_frame(move |window, cx| {
292                    if state
293                        .upgrade()
294                        .is_some_and(|state| state.read(cx).focus_epoch == epoch)
295                    {
296                        focus.focus(window, cx);
297                    }
298                });
299            }
300        } else {
301            self.reset_draft(window, cx);
302            if let Some(mut restore) = self.restore_focus.take()
303                && self.popup_focus.contains_focused(window, cx)
304            {
305                if !secondary_enabled && restore == self.secondary_focus {
306                    restore = self.input.read(cx).focus_handle(cx);
307                }
308                let popup = self.popup_focus.clone();
309                let state = cx.weak_entity();
310                window.defer(cx, move |window, cx| {
311                    if state
312                        .upgrade()
313                        .is_some_and(|state| state.read(cx).focus_epoch == epoch)
314                        && popup.contains_focused(window, cx)
315                    {
316                        restore.focus(window, cx);
317                    }
318                });
319            }
320        }
321    }
322
323    fn active_position(&self, choices: &[DropdownOption]) -> Option<usize> {
324        let id = self.active.as_ref()?;
325        self.active_index
326            .filter(|&index| choices.get(index).is_some_and(|choice| &choice.id == id))
327            .or_else(|| choices.iter().position(|choice| &choice.id == id))
328    }
329
330    pub(super) fn reconcile_options(
331        &mut self,
332        source: &Rc<[DropdownOption]>,
333        query: Option<SharedString>,
334    ) -> (Rc<[DropdownOption]>, Option<ElementId>, Option<ElementId>) {
335        if self.options.reconcile(source, query) {
336            self.active_index = self.active_position(&self.options.visible);
337            if self.active_index.is_none() {
338                self.active = None;
339            }
340        }
341        (
342            self.options.visible.clone(),
343            self.active.clone(),
344            self.selected.clone(),
345        )
346    }
347
348    pub(super) fn sync_presented_list(
349        &mut self,
350        options: &Rc<[DropdownOption]>,
351        active: Option<&ElementId>,
352        metrics: (Pixels, f32, Pixels, gpui_material_theme::Typography, u64),
353    ) {
354        if !Rc::ptr_eq(&self.presented, options) {
355            let old_top = self.scroll.logical_scroll_top();
356            let old_id = self.presented.get(old_top.item_ix).map(|option| &option.id);
357            let anchor = if active.is_some() && Rc::ptr_eq(options, &self.options.visible) {
358                self.active_position(options)
359            } else {
360                active
361                    .or(old_id)
362                    .and_then(|id| options.iter().position(|option| &option.id == id))
363            };
364            self.scroll.reset(options.len());
365            if let Some(index) = anchor {
366                self.scroll.scroll_to(ListOffset {
367                    item_ix: index,
368                    offset_in_item: if active.is_some() {
369                        px(0.)
370                    } else {
371                        old_top.offset_in_item
372                    },
373                });
374            }
375            self.presented = options.clone();
376        } else if self.metrics.as_ref() != Some(&metrics) {
377            let anchor = self.scroll.logical_scroll_top();
378            self.scroll.remeasure();
379            self.scroll.scroll_to(anchor);
380        }
381        self.metrics = Some(metrics);
382    }
383
384    pub(super) fn navigate(&mut self, backwards: bool, cx: &mut Context<Self>) {
385        let choices = &self.options.visible;
386        let index = self.active_position(choices);
387        let next = index.map_or_else(
388            || {
389                if backwards {
390                    choices.len().saturating_sub(1)
391                } else {
392                    0
393                }
394            },
395            |index| {
396                if backwards {
397                    index
398                        .checked_sub(1)
399                        .unwrap_or(choices.len().saturating_sub(1))
400                } else {
401                    (index + 1) % choices.len()
402                }
403            },
404        );
405        if let Some(choice) = choices.get(next) {
406            self.active = Some(choice.id.clone());
407            self.active_index = Some(next);
408        } else {
409            self.active = None;
410            self.active_index = None;
411        }
412        if self.scroll.bounds_for_item(next).is_some() {
413            self.scroll.scroll_to_reveal_item(next);
414        } else {
415            self.scroll.scroll_to(ListOffset {
416                item_ix: next,
417                offset_in_item: px(0.),
418            });
419        }
420        cx.notify();
421    }
422
423    pub(super) fn pending(&self) -> Option<DropdownOption> {
424        let choices = &self.options.visible;
425        let index = self.active_position(choices).unwrap_or(0);
426        choices.get(index).cloned()
427    }
428}