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    /// Creates dropdown state with an internal single-line editor initialized to `value`.
103    pub fn new(
104        value: impl Into<SharedString>,
105        editable: bool,
106        window: &mut Window,
107        cx: &mut Context<Self>,
108    ) -> Self {
109        let value = value.into();
110        let input = cx.new(|cx| TextFieldState::new(window, cx).default_value(value));
111        Self::with_editor(&input, editable, window, cx)
112    }
113
114    /// Uses a caller-retained single-line editor and its current value.
115    pub fn with_editor(
116        input: &Entity<TextFieldState>,
117        editable: bool,
118        window: &mut Window,
119        cx: &mut Context<Self>,
120    ) -> Self {
121        let committed = input.read(cx).value();
122        input.update(cx, |input, cx| input.set_readonly(!editable, cx));
123        let subscription = cx.subscribe_in(input, window, |state, input, event, window, cx| {
124            if !state.editable || !matches!(event, TextFieldEvent::Change) {
125                return;
126            }
127            if input.update(cx, |input, cx| {
128                input.marked_text_range(window, cx).is_some()
129            }) {
130                return;
131            }
132            if input.read(cx).value() != state.committed {
133                state.active = None;
134                state.active_index = None;
135                if state.primary_enabled {
136                    state.request_open(true, Some(Opening::Editor), window, cx);
137                }
138            }
139            cx.notify();
140        });
141        Self {
142            input: input.clone(),
143            committed,
144            editable,
145            open: false,
146            presented_open: false,
147            visibility: Weak::new(),
148            primary_enabled: true,
149            opening: None,
150            popup_focus: cx.focus_handle(),
151            secondary_focus: cx.focus_handle(),
152            restore_focus: None,
153            focus_epoch: 0,
154            active: None,
155            active_index: None,
156            selected: None,
157            scroll: ListState::new(0, ListAlignment::Top, px(280.)),
158            presented: Rc::default(),
159            metrics: None,
160            options: OptionSnapshot::default(),
161            _input: subscription,
162        }
163    }
164
165    /// Synchronizes the label and dismisses an internally controlled list.
166    pub fn set_value(
167        &mut self,
168        value: impl Into<SharedString>,
169        window: &mut Window,
170        cx: &mut Context<Self>,
171    ) {
172        let value = value.into();
173        if self.committed != value {
174            self.selected = None;
175        }
176        self.committed = value;
177        if self
178            .visibility
179            .upgrade()
180            .is_none_or(|policy| policy.controlled.is_none())
181        {
182            self.open = false;
183        }
184        self.reset_draft(window, cx);
185    }
186
187    /// Returns `true` if the dropdown popup menu is currently open.
188    pub fn is_open(&self) -> bool {
189        self.open
190    }
191
192    /// Returns the ID of the last committed dropdown option, if any.
193    pub fn selected_option_id(&self) -> Option<&ElementId> {
194        self.selected.as_ref()
195    }
196
197    /// The retained variable-height list position, including while closed.
198    pub fn scroll_state(&self) -> &ListState {
199        &self.scroll
200    }
201
202    /// Uses a caller-owned list position. The dropdown owns its item count.
203    pub fn set_scroll_state(&mut self, scroll: &ListState, cx: &mut Context<Self>) {
204        let anchor = scroll.logical_scroll_top();
205        scroll.reset(self.presented.len());
206        scroll.scroll_to(anchor);
207        self.scroll = scroll.clone();
208        self.metrics = None;
209        cx.notify();
210    }
211
212    fn clear_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
213        let mut changed = self.active.take().is_some() | self.active_index.take().is_some();
214        self.input.update(cx, |input, cx| {
215            if input.value() != self.committed {
216                input.set_value(self.committed.clone(), window, cx);
217                changed = true;
218            }
219        });
220        changed
221    }
222
223    pub(super) fn reset_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
224        if self.clear_draft(window, cx) {
225            cx.notify();
226        }
227    }
228
229    pub(super) fn request_open(
230        &mut self,
231        open: bool,
232        opening: Option<Opening>,
233        window: &mut Window,
234        cx: &mut Context<Self>,
235    ) {
236        if self.open == open {
237            return;
238        }
239        self.opening = opening;
240        let visibility = self.visibility.upgrade();
241        if visibility
242            .as_ref()
243            .is_none_or(|policy| policy.controlled.is_none())
244        {
245            self.open = open;
246            if !open {
247                self.clear_draft(window, cx);
248            }
249        }
250        if let Some(visibility) = visibility
251            && (visibility.change.is_some() || !open && visibility.dismiss.is_some())
252        {
253            window.defer(cx, move |window, cx| {
254                if let Some(change) = &visibility.change {
255                    change(open, window, cx);
256                }
257                if !open && let Some(dismiss) = &visibility.dismiss {
258                    dismiss(window, cx);
259                }
260            });
261        }
262        cx.notify();
263    }
264
265    pub(super) fn present(
266        &mut self,
267        visibility: &Rc<Visibility>,
268        primary_enabled: bool,
269        secondary_enabled: bool,
270        primary: Opening,
271        window: &mut Window,
272        cx: &mut Context<Self>,
273    ) {
274        self.primary_enabled = primary_enabled;
275        self.open = visibility.controlled.unwrap_or(self.open);
276        self.visibility = Rc::downgrade(visibility);
277        let opening = self.opening.take();
278        if self.presented_open == self.open {
279            if !self.open {
280                self.active = None;
281                self.active_index = None;
282            }
283            return;
284        }
285        self.presented_open = self.open;
286        self.focus_epoch = self.focus_epoch.wrapping_add(1);
287        let epoch = self.focus_epoch;
288        if self.open {
289            let editor = self.input.read(cx).focus_handle(cx);
290            let (focus, restore) = match opening.unwrap_or(primary) {
291                Opening::Editor => (editor.clone(), None),
292                Opening::PopupFromPrimary => (self.popup_focus.clone(), Some(editor)),
293                Opening::PopupFromSecondary => {
294                    (self.popup_focus.clone(), Some(self.secondary_focus.clone()))
295                }
296            };
297            self.restore_focus = restore;
298            if !focus.is_focused(window) {
299                let state = cx.weak_entity();
300                window.on_next_frame(move |window, cx| {
301                    if state
302                        .upgrade()
303                        .is_some_and(|state| state.read(cx).focus_epoch == epoch)
304                    {
305                        focus.focus(window, cx);
306                    }
307                });
308            }
309        } else {
310            self.reset_draft(window, cx);
311            if let Some(mut restore) = self.restore_focus.take()
312                && self.popup_focus.contains_focused(window, cx)
313            {
314                if !secondary_enabled && restore == self.secondary_focus {
315                    restore = self.input.read(cx).focus_handle(cx);
316                }
317                let popup = self.popup_focus.clone();
318                let state = cx.weak_entity();
319                window.defer(cx, move |window, cx| {
320                    if state
321                        .upgrade()
322                        .is_some_and(|state| state.read(cx).focus_epoch == epoch)
323                        && popup.contains_focused(window, cx)
324                    {
325                        restore.focus(window, cx);
326                    }
327                });
328            }
329        }
330    }
331
332    fn active_position(&self, choices: &[DropdownOption]) -> Option<usize> {
333        let id = self.active.as_ref()?;
334        self.active_index
335            .filter(|&index| choices.get(index).is_some_and(|choice| &choice.id == id))
336            .or_else(|| choices.iter().position(|choice| &choice.id == id))
337    }
338
339    pub(super) fn reconcile_options(
340        &mut self,
341        source: &Rc<[DropdownOption]>,
342        query: Option<SharedString>,
343    ) -> (Rc<[DropdownOption]>, Option<ElementId>, Option<ElementId>) {
344        if self.options.reconcile(source, query) {
345            self.active_index = self.active_position(&self.options.visible);
346            if self.active_index.is_none() {
347                self.active = None;
348            }
349        }
350        (
351            self.options.visible.clone(),
352            self.active.clone(),
353            self.selected.clone(),
354        )
355    }
356
357    pub(super) fn sync_presented_list(
358        &mut self,
359        options: &Rc<[DropdownOption]>,
360        active: Option<&ElementId>,
361        metrics: (Pixels, f32, Pixels, gpui_material_theme::Typography, u64),
362    ) {
363        if !Rc::ptr_eq(&self.presented, options) {
364            let old_top = self.scroll.logical_scroll_top();
365            let old_id = self.presented.get(old_top.item_ix).map(|option| &option.id);
366            let anchor = if active.is_some() && Rc::ptr_eq(options, &self.options.visible) {
367                self.active_position(options)
368            } else {
369                active
370                    .or(old_id)
371                    .and_then(|id| options.iter().position(|option| &option.id == id))
372            };
373            self.scroll.reset(options.len());
374            if let Some(index) = anchor {
375                self.scroll.scroll_to(ListOffset {
376                    item_ix: index,
377                    offset_in_item: if active.is_some() {
378                        px(0.)
379                    } else {
380                        old_top.offset_in_item
381                    },
382                });
383            }
384            self.presented = options.clone();
385        } else if self.metrics.as_ref() != Some(&metrics) {
386            let anchor = self.scroll.logical_scroll_top();
387            self.scroll.remeasure();
388            self.scroll.scroll_to(anchor);
389        }
390        self.metrics = Some(metrics);
391    }
392
393    pub(super) fn navigate(&mut self, backwards: bool, cx: &mut Context<Self>) {
394        let choices = &self.options.visible;
395        let index = self.active_position(choices);
396        let next = index.map_or_else(
397            || {
398                if backwards {
399                    choices.len().saturating_sub(1)
400                } else {
401                    0
402                }
403            },
404            |index| {
405                if backwards {
406                    index
407                        .checked_sub(1)
408                        .unwrap_or(choices.len().saturating_sub(1))
409                } else {
410                    (index + 1) % choices.len()
411                }
412            },
413        );
414        if let Some(choice) = choices.get(next) {
415            self.active = Some(choice.id.clone());
416            self.active_index = Some(next);
417        } else {
418            self.active = None;
419            self.active_index = None;
420        }
421        if self.scroll.bounds_for_item(next).is_some() {
422            self.scroll.scroll_to_reveal_item(next);
423        } else {
424            self.scroll.scroll_to(ListOffset {
425                item_ix: next,
426                offset_in_item: px(0.),
427            });
428        }
429        cx.notify();
430    }
431
432    pub(super) fn pending(&self) -> Option<DropdownOption> {
433        let choices = &self.options.visible;
434        let index = self.active_position(choices).unwrap_or(0);
435        choices.get(index).cloned()
436    }
437}