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