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    fn clear_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
210        let mut changed = self.active.take().is_some() | self.active_index.take().is_some();
211        self.input.update(cx, |input, cx| {
212            if input.value() != self.committed {
213                input.set_value(self.committed.clone(), window, cx);
214                changed = true;
215            }
216        });
217        changed
218    }
219
220    pub(super) fn reset_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
221        if self.clear_draft(window, cx) {
222            cx.notify();
223        }
224    }
225
226    pub(super) fn request_open(
227        &mut self,
228        open: bool,
229        opening: Option<Opening>,
230        window: &mut Window,
231        cx: &mut Context<Self>,
232    ) {
233        if self.open == open {
234            return;
235        }
236        self.opening = opening;
237        let visibility = self.visibility.upgrade();
238        if visibility
239            .as_ref()
240            .is_none_or(|policy| policy.controlled.is_none())
241        {
242            self.open = open;
243            if !open {
244                self.clear_draft(window, cx);
245            }
246        }
247        if let Some(visibility) = visibility
248            && (visibility.change.is_some() || !open && visibility.dismiss.is_some())
249        {
250            window.defer(cx, move |window, cx| {
251                if let Some(change) = &visibility.change {
252                    change(open, window, cx);
253                }
254                if !open && let Some(dismiss) = &visibility.dismiss {
255                    dismiss(window, cx);
256                }
257            });
258        }
259        cx.notify();
260    }
261
262    pub(super) fn present(
263        &mut self,
264        visibility: &Rc<Visibility>,
265        primary_enabled: bool,
266        secondary_enabled: bool,
267        primary: Opening,
268        window: &mut Window,
269        cx: &mut Context<Self>,
270    ) {
271        self.primary_enabled = primary_enabled;
272        self.open = visibility.controlled.unwrap_or(self.open);
273        self.visibility = Rc::downgrade(visibility);
274        let opening = self.opening.take();
275        if self.presented_open == self.open {
276            if !self.open {
277                self.active = None;
278                self.active_index = None;
279            }
280            return;
281        }
282        self.presented_open = self.open;
283        self.focus_epoch = self.focus_epoch.wrapping_add(1);
284        let epoch = self.focus_epoch;
285        if self.open {
286            let editor = self.input.read(cx).focus_handle(cx);
287            let (focus, restore) = match opening.unwrap_or(primary) {
288                Opening::Editor => (editor.clone(), None),
289                Opening::PopupFromPrimary => (self.popup_focus.clone(), Some(editor)),
290                Opening::PopupFromSecondary => {
291                    (self.popup_focus.clone(), Some(self.secondary_focus.clone()))
292                }
293            };
294            self.restore_focus = restore;
295            if !focus.is_focused(window) {
296                let state = cx.weak_entity();
297                window.on_next_frame(move |window, cx| {
298                    if state
299                        .upgrade()
300                        .is_some_and(|state| state.read(cx).focus_epoch == epoch)
301                    {
302                        focus.focus(window, cx);
303                    }
304                });
305            }
306        } else {
307            self.reset_draft(window, cx);
308            if let Some(mut restore) = self.restore_focus.take()
309                && self.popup_focus.contains_focused(window, cx)
310            {
311                if !secondary_enabled && restore == self.secondary_focus {
312                    restore = self.input.read(cx).focus_handle(cx);
313                }
314                let popup = self.popup_focus.clone();
315                let state = cx.weak_entity();
316                window.defer(cx, move |window, cx| {
317                    if state
318                        .upgrade()
319                        .is_some_and(|state| state.read(cx).focus_epoch == epoch)
320                        && popup.contains_focused(window, cx)
321                    {
322                        restore.focus(window, cx);
323                    }
324                });
325            }
326        }
327    }
328
329    fn active_position(&self, choices: &[DropdownOption]) -> Option<usize> {
330        let id = self.active.as_ref()?;
331        self.active_index
332            .filter(|&index| choices.get(index).is_some_and(|choice| &choice.id == id))
333            .or_else(|| choices.iter().position(|choice| &choice.id == id))
334    }
335
336    pub(super) fn reconcile_options(
337        &mut self,
338        source: &Rc<[DropdownOption]>,
339        query: Option<SharedString>,
340    ) -> (Rc<[DropdownOption]>, Option<ElementId>, Option<ElementId>) {
341        if self.options.reconcile(source, query) {
342            self.active_index = self.active_position(&self.options.visible);
343            if self.active_index.is_none() {
344                self.active = None;
345            }
346        }
347        (
348            self.options.visible.clone(),
349            self.active.clone(),
350            self.selected.clone(),
351        )
352    }
353
354    pub(super) fn sync_presented_list(
355        &mut self,
356        options: &Rc<[DropdownOption]>,
357        active: Option<&ElementId>,
358        metrics: (Pixels, f32, Pixels, gpui_material_theme::Typography, u64),
359    ) {
360        if !Rc::ptr_eq(&self.presented, options) {
361            let old_top = self.scroll.logical_scroll_top();
362            let old_id = self.presented.get(old_top.item_ix).map(|option| &option.id);
363            let anchor = if active.is_some() && Rc::ptr_eq(options, &self.options.visible) {
364                self.active_position(options)
365            } else {
366                active
367                    .or(old_id)
368                    .and_then(|id| options.iter().position(|option| &option.id == id))
369            };
370            self.scroll.reset(options.len());
371            if let Some(index) = anchor {
372                self.scroll.scroll_to(ListOffset {
373                    item_ix: index,
374                    offset_in_item: if active.is_some() {
375                        px(0.)
376                    } else {
377                        old_top.offset_in_item
378                    },
379                });
380            }
381            self.presented = options.clone();
382        } else if self.metrics.as_ref() != Some(&metrics) {
383            let anchor = self.scroll.logical_scroll_top();
384            self.scroll.remeasure();
385            self.scroll.scroll_to(anchor);
386        }
387        self.metrics = Some(metrics);
388    }
389
390    pub(super) fn navigate(&mut self, backwards: bool, cx: &mut Context<Self>) {
391        let choices = &self.options.visible;
392        let index = self.active_position(choices);
393        let next = index.map_or_else(
394            || {
395                if backwards {
396                    choices.len().saturating_sub(1)
397                } else {
398                    0
399                }
400            },
401            |index| {
402                if backwards {
403                    index
404                        .checked_sub(1)
405                        .unwrap_or(choices.len().saturating_sub(1))
406                } else {
407                    (index + 1) % choices.len()
408                }
409            },
410        );
411        if let Some(choice) = choices.get(next) {
412            self.active = Some(choice.id.clone());
413            self.active_index = Some(next);
414        } else {
415            self.active = None;
416            self.active_index = None;
417        }
418        if self.scroll.bounds_for_item(next).is_some() {
419            self.scroll.scroll_to_reveal_item(next);
420        } else {
421            self.scroll.scroll_to(ListOffset {
422                item_ix: next,
423                offset_in_item: px(0.),
424            });
425        }
426        cx.notify();
427    }
428
429    pub(super) fn pending(&self) -> Option<DropdownOption> {
430        let choices = &self.options.visible;
431        let index = self.active_position(choices).unwrap_or(0);
432        choices.get(index).cloned()
433    }
434}