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#[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
77pub 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, Pixels, gpui_material_theme::Typography, u64)>,
97 options: OptionSnapshot,
98 _input: Subscription,
99}
100
101impl ExposedDropdownState {
102 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 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 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 pub fn is_open(&self) -> bool {
189 self.open
190 }
191
192 pub fn selected_option_id(&self) -> Option<&ElementId> {
194 self.selected.as_ref()
195 }
196
197 pub fn scroll_state(&self) -> &ListState {
199 &self.scroll
200 }
201
202 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 #[allow(clippy::too_many_arguments)]
266 pub(super) fn present(
267 &mut self,
268 visibility: &Rc<Visibility>,
269 disabled: bool,
270 primary_enabled: bool,
271 secondary_enabled: bool,
272 primary: Opening,
273 window: &mut Window,
274 cx: &mut Context<Self>,
275 ) {
276 self.primary_enabled = primary_enabled;
277 self.open = if disabled {
278 false
279 } else {
280 visibility.controlled.unwrap_or(self.open)
281 };
282 self.visibility = Rc::downgrade(visibility);
283 let opening = self.opening.take();
284 if self.presented_open == self.open {
285 if !self.open {
286 self.active = None;
287 self.active_index = None;
288 }
289 return;
290 }
291 self.presented_open = self.open;
292 self.focus_epoch = self.focus_epoch.wrapping_add(1);
293 let epoch = self.focus_epoch;
294 if self.open {
295 let editor = self.input.read(cx).focus_handle(cx);
296 let (focus, restore) = match opening.unwrap_or(primary) {
297 Opening::Editor => (editor.clone(), None),
298 Opening::PopupFromPrimary => (self.popup_focus.clone(), Some(editor)),
299 Opening::PopupFromSecondary => {
300 (self.popup_focus.clone(), Some(self.secondary_focus.clone()))
301 }
302 };
303 self.restore_focus = restore;
304 if !focus.is_focused(window) {
305 let state = cx.weak_entity();
306 window.on_next_frame(move |window, cx| {
307 if state
308 .upgrade()
309 .is_some_and(|state| state.read(cx).focus_epoch == epoch)
310 {
311 focus.focus(window, cx);
312 }
313 });
314 }
315 } else {
316 self.reset_draft(window, cx);
317 if !disabled
318 && let Some(mut restore) = self.restore_focus.take()
319 && self.popup_focus.contains_focused(window, cx)
320 {
321 if !secondary_enabled && restore == self.secondary_focus {
322 restore = self.input.read(cx).focus_handle(cx);
323 }
324 let popup = self.popup_focus.clone();
325 let state = cx.weak_entity();
326 window.defer(cx, move |window, cx| {
327 if state
328 .upgrade()
329 .is_some_and(|state| state.read(cx).focus_epoch == epoch)
330 && popup.contains_focused(window, cx)
331 {
332 restore.focus(window, cx);
333 }
334 });
335 } else if disabled {
336 self.restore_focus = None;
337 }
338 }
339 }
340
341 fn active_position(&self, choices: &[DropdownOption]) -> Option<usize> {
342 let id = self.active.as_ref()?;
343 self.active_index
344 .filter(|&index| choices.get(index).is_some_and(|choice| &choice.id == id))
345 .or_else(|| choices.iter().position(|choice| &choice.id == id))
346 }
347
348 pub(super) fn reconcile_options(
349 &mut self,
350 source: &Rc<[DropdownOption]>,
351 query: Option<SharedString>,
352 ) -> (Rc<[DropdownOption]>, Option<ElementId>, Option<ElementId>) {
353 if self.options.reconcile(source, query) {
354 self.active_index = self.active_position(&self.options.visible);
355 if self.active_index.is_none() {
356 self.active = None;
357 }
358 }
359 (
360 self.options.visible.clone(),
361 self.active.clone(),
362 self.selected.clone(),
363 )
364 }
365
366 pub(super) fn sync_presented_list(
367 &mut self,
368 options: &Rc<[DropdownOption]>,
369 active: Option<&ElementId>,
370 metrics: (Pixels, Pixels, gpui_material_theme::Typography, u64),
371 ) {
372 if !Rc::ptr_eq(&self.presented, options) {
373 let old_top = self.scroll.logical_scroll_top();
374 let old_id = self.presented.get(old_top.item_ix).map(|option| &option.id);
375 let anchor = if active.is_some() && Rc::ptr_eq(options, &self.options.visible) {
376 self.active_position(options)
377 } else {
378 active
379 .or(old_id)
380 .and_then(|id| options.iter().position(|option| &option.id == id))
381 };
382 self.scroll.reset(options.len());
383 if let Some(index) = anchor {
384 self.scroll.scroll_to(ListOffset {
385 item_ix: index,
386 offset_in_item: if active.is_some() {
387 px(0.)
388 } else {
389 old_top.offset_in_item
390 },
391 });
392 }
393 self.presented = options.clone();
394 } else if self.metrics.as_ref() != Some(&metrics) {
395 let anchor = self.scroll.logical_scroll_top();
396 self.scroll.remeasure();
397 self.scroll.scroll_to(anchor);
398 }
399 self.metrics = Some(metrics);
400 }
401
402 pub(super) fn navigate(&mut self, backwards: bool, cx: &mut Context<Self>) {
403 let choices = &self.options.visible;
404 if choices.is_empty() {
405 self.active = None;
406 self.active_index = None;
407 cx.notify();
408 return;
409 }
410 let index = self.active_position(choices);
411 let next = index.map_or_else(
412 || {
413 if backwards {
414 choices.len().saturating_sub(1)
415 } else {
416 0
417 }
418 },
419 |index| {
420 if backwards {
421 index
422 .checked_sub(1)
423 .unwrap_or(choices.len().saturating_sub(1))
424 } else {
425 (index + 1) % choices.len()
426 }
427 },
428 );
429 self.focus_option_at(next, cx);
430 }
431
432 pub(super) fn navigate_edge(&mut self, to_end: bool, cx: &mut Context<Self>) {
433 let choices = &self.options.visible;
434 if choices.is_empty() {
435 self.active = None;
436 self.active_index = None;
437 cx.notify();
438 return;
439 }
440 let next = if to_end { choices.len() - 1 } else { 0 };
441 self.focus_option_at(next, cx);
442 }
443
444 fn focus_option_at(&mut self, index: usize, cx: &mut Context<Self>) {
445 if let Some(choice) = self.options.visible.get(index) {
446 self.active = Some(choice.id.clone());
447 self.active_index = Some(index);
448 } else {
449 self.active = None;
450 self.active_index = None;
451 }
452 if self.scroll.bounds_for_item(index).is_some() {
453 self.scroll.scroll_to_reveal_item(index);
454 } else {
455 self.scroll.scroll_to(ListOffset {
456 item_ix: index,
457 offset_in_item: px(0.),
458 });
459 }
460 cx.notify();
461 }
462
463 pub(super) fn pending(&self) -> Option<DropdownOption> {
464 let choices = &self.options.visible;
465 let index = self.active_position(choices).unwrap_or(0);
466 choices.get(index).cloned()
467 }
468}