| 1 | use gpui::{ |
| 2 | AnyElement, App, Bounds, ClickEvent, Context, DismissEvent, Edges, ElementId, Entity, |
| 3 | EventEmitter, FocusHandle, Focusable, Hsla, InteractiveElement, IntoElement, Length, |
| 4 | MouseDownEvent, ParentElement, Pixels, Render, RenderOnce, SharedString, |
| 5 | StatefulInteractiveElement, StyleRefinement, Styled, Window, deferred, div, |
| 6 | prelude::FluentBuilder, px, rems, |
| 7 | }; |
| 8 | |
| 9 | use rust_i18n::t; |
| 10 | |
| 11 | pub use crate::select::Caret; |
| 12 | |
| 13 | use crate::ThemeStyled as _; |
| 14 | use crate::{ |
| 15 | ActiveTheme, Disableable, ElementExt as _, Icon, IconName, IndexPath, Sizable, Size, |
| 16 | StyleSized, StyledExt, h_flex, |
| 17 | input::{clear_button, input_style}, |
| 18 | list::{List, ListState}, |
| 19 | searchable_list::{ |
| 20 | SearchableListAdapter, SearchableListChange, SearchableListDelegate, SearchableListItem, |
| 21 | SearchableListState, |
| 22 | }, |
| 23 | sizing::DROPDOWN_LIST_PADDING, |
| 24 | v_flex, |
| 25 | }; |
| 26 | use gpui_base::{Combobox as BaseCombobox, GlobalState}; |
| 27 | |
| 28 | // MARK: ComboboxTriggerContext |
| 29 | |
| 30 | /// Context passed to the `render_trigger` closure on [`Combobox`]. |
| 31 | /// |
| 32 | /// The fields are private and reached through the methods below, so that a new |
| 33 | /// one can be added without breaking the trigger renderers. |
| 34 | pub struct ComboboxTriggerContext<'a, D: SearchableListDelegate + 'static> { |
| 35 | selection: &'a [(IndexPath, D::Item)], |
| 36 | placeholder: Option<&'a SharedString>, |
| 37 | open: bool, |
| 38 | disabled: bool, |
| 39 | size: Size, |
| 40 | } |
| 41 | |
| 42 | impl<'a, D: SearchableListDelegate + 'static> ComboboxTriggerContext<'a, D> { |
| 43 | /// The items currently selected, empty when the combobox has no value. |
| 44 | pub fn selection(&self) -> &'a [(IndexPath, D::Item)] { |
| 45 | self.selection |
| 46 | } |
| 47 | |
| 48 | pub fn placeholder(&self) -> Option<&'a SharedString> { |
| 49 | self.placeholder |
| 50 | } |
| 51 | |
| 52 | /// Whether the dropdown list is showing. |
| 53 | pub fn is_open(&self) -> bool { |
| 54 | self.open |
| 55 | } |
| 56 | |
| 57 | pub fn is_disabled(&self) -> bool { |
| 58 | self.disabled |
| 59 | } |
| 60 | |
| 61 | pub fn size(&self) -> Size { |
| 62 | self.size |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | // MARK: ComboboxChange |
| 67 | |
| 68 | /// Back-compat alias — new code should use [`SearchableListChange`] directly. |
| 69 | pub type ComboboxChange = SearchableListChange; |
| 70 | |
| 71 | // MARK: ComboboxOptions |
| 72 | |
| 73 | struct ComboboxOptions { |
| 74 | style: StyleRefinement, |
| 75 | size: Size, |
| 76 | cleanable: bool, |
| 77 | placeholder: Option<SharedString>, |
| 78 | search_placeholder: Option<SharedString>, |
| 79 | menu_width: Length, |
| 80 | menu_max_h: Length, |
| 81 | disabled: bool, |
| 82 | appearance: bool, |
| 83 | focus_ring_enabled: bool, |
| 84 | trigger_icon: Option<Icon>, |
| 85 | check_icon: Option<Icon>, |
| 86 | } |
| 87 | |
| 88 | impl Default for ComboboxOptions { |
| 89 | fn default() -> Self { |
| 90 | Self { |
| 91 | style: StyleRefinement::default(), |
| 92 | size: Size::default(), |
| 93 | cleanable: false, |
| 94 | placeholder: None, |
| 95 | search_placeholder: None, |
| 96 | menu_width: Length::Auto, |
| 97 | menu_max_h: rems(20.).into(), |
| 98 | disabled: false, |
| 99 | appearance: true, |
| 100 | focus_ring_enabled: true, |
| 101 | trigger_icon: None, |
| 102 | check_icon: None, |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // MARK: ComboboxState |
| 108 | |
| 109 | /// State of the [`Combobox`] component. |
| 110 | pub struct ComboboxState<D: SearchableListDelegate + 'static> |
| 111 | where |
| 112 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 113 | { |
| 114 | pub(crate) state: SearchableListState<D>, |
| 115 | |
| 116 | // Combobox-specific fields |
| 117 | multiple: bool, |
| 118 | searchable: bool, |
| 119 | trigger_icon: Option<Icon>, |
| 120 | check_icon: Option<Icon>, |
| 121 | render_trigger: Option< |
| 122 | Box<dyn Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> AnyElement + 'static>, |
| 123 | >, |
| 124 | footer: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>>, |
| 125 | focus_ring_enabled: bool, |
| 126 | } |
| 127 | |
| 128 | /// Events emitted by [`ComboboxState`]. |
| 129 | pub enum ComboboxEvent<D: SearchableListDelegate + 'static> |
| 130 | where |
| 131 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 132 | { |
| 133 | /// Emitted on every toggle (item added or removed). |
| 134 | Change(Vec<<D::Item as SearchableListItem>::Value>), |
| 135 | /// Emitted when the popover closes. |
| 136 | Confirm(Vec<<D::Item as SearchableListItem>::Value>), |
| 137 | } |
| 138 | |
| 139 | impl<D> ComboboxState<D> |
| 140 | where |
| 141 | D: SearchableListDelegate + 'static, |
| 142 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 143 | { |
| 144 | /// Create a new `Combobox` state. |
| 145 | pub fn new( |
| 146 | delegate: D, |
| 147 | selected_indices: Vec<IndexPath>, |
| 148 | window: &mut Window, |
| 149 | cx: &mut Context<Self>, |
| 150 | ) -> Self { |
| 151 | let weak = cx.entity().downgrade(); |
| 152 | let weak_confirm = weak.clone(); |
| 153 | let weak_cancel = weak.clone(); |
| 154 | let weak_empty = weak; |
| 155 | |
| 156 | let state = SearchableListState::new( |
| 157 | delegate, |
| 158 | selected_indices, |
| 159 | move |selected_index, _secondary, window, cx| { |
| 160 | cx.defer_in(window, { |
| 161 | let weak_confirm = weak_confirm.clone(); |
| 162 | move |list_state, window, cx| { |
| 163 | let Some(index) = selected_index else { |
| 164 | return; |
| 165 | }; |
| 166 | |
| 167 | let Some(item) = list_state.delegate().delegate.item(index).cloned() else { |
| 168 | return; |
| 169 | }; |
| 170 | |
| 171 | let ix = index; |
| 172 | |
| 173 | let Some(weak) = weak_confirm.upgrade() else { |
| 174 | return; |
| 175 | }; |
| 176 | |
| 177 | let (multiple, mut selection) = { |
| 178 | let s = weak.read(cx); |
| 179 | (s.multiple, s.state.selection.clone()) |
| 180 | }; |
| 181 | |
| 182 | let changes = Self::selection_changes(multiple, &selection, ix, &item); |
| 183 | |
| 184 | let before_indices: Vec<IndexPath> = |
| 185 | selection.iter().map(|(ix, _)| *ix).collect(); |
| 186 | |
| 187 | // on_will_change is called directly — entity-handle access would |
| 188 | // re-enter the ListState lock that defer_in holds for this callback. |
| 189 | list_state |
| 190 | .delegate_mut() |
| 191 | .delegate |
| 192 | .on_will_change(&mut selection, &changes); |
| 193 | |
| 194 | let after_indices: Vec<IndexPath> = |
| 195 | selection.iter().map(|(ix, _)| *ix).collect(); |
| 196 | let changed = before_indices != after_indices; |
| 197 | let should_close = changed && !multiple; |
| 198 | |
| 199 | let new_selection = weak_confirm.update(cx, |this, cx| { |
| 200 | this.state.selection = selection; |
| 201 | |
| 202 | if changed { |
| 203 | cx.emit(ComboboxEvent::Change(this.selected_values())); |
| 204 | cx.notify(); |
| 205 | } |
| 206 | |
| 207 | if should_close { |
| 208 | cx.emit(ComboboxEvent::Confirm(this.selected_values())); |
| 209 | this.set_open(false, cx); |
| 210 | this.focus(window, cx); |
| 211 | } |
| 212 | |
| 213 | this.state.selection.clone() |
| 214 | }); |
| 215 | |
| 216 | // Sync snapshot and fire on_confirm directly — same re-entrancy guard. |
| 217 | if let Ok(new_selection) = new_selection { |
| 218 | list_state |
| 219 | .delegate_mut() |
| 220 | .update_selection_snapshot(new_selection.clone()); |
| 221 | |
| 222 | if should_close { |
| 223 | list_state |
| 224 | .delegate_mut() |
| 225 | .delegate |
| 226 | .on_confirm(&new_selection); |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | }); |
| 231 | }, |
| 232 | // on_cancel — close and emit Confirm with current values |
| 233 | move |_final_selected_index, window, cx| { |
| 234 | cx.defer_in(window, { |
| 235 | let weak_cancel = weak_cancel.clone(); |
| 236 | move |_list_state, window, cx| { |
| 237 | _ = weak_cancel.update(cx, |this, cx| { |
| 238 | // Cancel propagates to the BaseCombobox, which may already |
| 239 | // have confirmed and closed before this deferred callback. |
| 240 | if !this.state.open { |
| 241 | return; |
| 242 | } |
| 243 | cx.emit(ComboboxEvent::Confirm(this.selected_values())); |
| 244 | this.set_open(false, cx); |
| 245 | this.focus(window, cx); |
| 246 | }); |
| 247 | } |
| 248 | }); |
| 249 | }, |
| 250 | // on_render_empty |
| 251 | move |window, cx| { |
| 252 | if let Some(empty) = weak_empty |
| 253 | .upgrade() |
| 254 | .and_then(|e| e.read(cx).state.empty.as_ref().map(|f| f(window, cx))) |
| 255 | { |
| 256 | empty |
| 257 | } else { |
| 258 | h_flex() |
| 259 | .justify_center() |
| 260 | .py_6() |
| 261 | .text_color(cx.theme().muted_foreground.opacity(0.6)) |
| 262 | .child(Icon::new(IconName::Inbox).size(px(28.))) |
| 263 | .into_any_element() |
| 264 | } |
| 265 | }, |
| 266 | Self::on_blur, |
| 267 | window, |
| 268 | cx, |
| 269 | ); |
| 270 | |
| 271 | Self { |
| 272 | state, |
| 273 | multiple: false, |
| 274 | searchable: false, |
| 275 | trigger_icon: None, |
| 276 | check_icon: None, |
| 277 | render_trigger: None, |
| 278 | footer: None, |
| 279 | focus_ring_enabled: true, |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | /// Enable multi-select mode. |
| 284 | /// |
| 285 | /// When `true`, clicking an item toggles it in the selection and the popover stays open. |
| 286 | /// When `false` (default), clicking an item replaces the selection and closes the popover. |
| 287 | pub fn multiple(mut self, multiple: bool) -> Self { |
| 288 | self.multiple = multiple; |
| 289 | self |
| 290 | } |
| 291 | |
| 292 | /// Enable or disable the search input at the top of the dropdown. |
| 293 | pub fn searchable(mut self, searchable: bool) -> Self { |
| 294 | self.searchable = searchable; |
| 295 | self |
| 296 | } |
| 297 | |
| 298 | /// Return the currently selected values. |
| 299 | pub fn selected_values(&self) -> Vec<<D::Item as SearchableListItem>::Value> { |
| 300 | self.state.selected_values() |
| 301 | } |
| 302 | |
| 303 | /// Return the first selected value, or `None` when nothing is selected. |
| 304 | /// |
| 305 | /// Convenience for single-select mode (`.multiple(false)`). |
| 306 | pub fn selected_value(&self) -> Option<<D::Item as SearchableListItem>::Value> { |
| 307 | self.state.selected_values().into_iter().next() |
| 308 | } |
| 309 | |
| 310 | /// Return the currently selected `(IndexPath, Item)` pairs. |
| 311 | pub fn selection(&self) -> &[(IndexPath, D::Item)] { |
| 312 | self.state.selection() |
| 313 | } |
| 314 | |
| 315 | /// Replace the entire selection set by item values. |
| 316 | /// |
| 317 | /// Values are resolved through the current delegate. Values that cannot be resolved are |
| 318 | /// ignored. This updates the committed selection and snapshot without emitting a |
| 319 | /// [`ComboboxEvent`]. |
| 320 | pub fn set_selected_values( |
| 321 | &mut self, |
| 322 | values: &[<D::Item as SearchableListItem>::Value], |
| 323 | window: &mut Window, |
| 324 | cx: &mut Context<Self>, |
| 325 | ) { |
| 326 | self.state.clear_query(window, cx); |
| 327 | |
| 328 | let selected_indices = { |
| 329 | let list = self.state.list.read(cx); |
| 330 | let delegate = &list.delegate().delegate; |
| 331 | |
| 332 | values |
| 333 | .iter() |
| 334 | .filter_map(|value| delegate.position(value)) |
| 335 | .collect::<Vec<_>>() |
| 336 | }; |
| 337 | |
| 338 | self.set_selected_indices(selected_indices, window, cx); |
| 339 | } |
| 340 | |
| 341 | /// Replace the entire selection set. |
| 342 | pub fn set_selected_indices( |
| 343 | &mut self, |
| 344 | indices: impl IntoIterator<Item = IndexPath>, |
| 345 | _window: &mut Window, |
| 346 | cx: &mut Context<Self>, |
| 347 | ) { |
| 348 | self.state.set_selected_indices(indices, cx); |
| 349 | self.state.sync_snapshot(cx); |
| 350 | cx.notify(); |
| 351 | } |
| 352 | |
| 353 | /// Add a single index to the selection, if not already present, returning whether it was added. |
| 354 | pub fn add_selected_index(&mut self, index: IndexPath, cx: &mut Context<Self>) -> bool { |
| 355 | let added = self.state.add_selected_index(index, cx); |
| 356 | |
| 357 | if added { |
| 358 | self.state.sync_snapshot(cx); |
| 359 | cx.notify(); |
| 360 | } |
| 361 | |
| 362 | added |
| 363 | } |
| 364 | |
| 365 | /// Remove a single index from the selection, returning whether it was removed. |
| 366 | pub fn remove_selected_index(&mut self, index: IndexPath, cx: &mut Context<Self>) -> bool { |
| 367 | let removed = self.state.remove_selected_index(index); |
| 368 | |
| 369 | if removed { |
| 370 | self.state.sync_snapshot(cx); |
| 371 | } |
| 372 | |
| 373 | removed |
| 374 | } |
| 375 | |
| 376 | /// Clear all selected values. |
| 377 | pub fn clear_selection(&mut self, cx: &mut Context<Self>) { |
| 378 | self.state.selection.clear(); |
| 379 | self.state.sync_snapshot(cx); |
| 380 | cx.emit(ComboboxEvent::Change(self.selected_values())); |
| 381 | cx.notify(); |
| 382 | } |
| 383 | |
| 384 | /// Replace the underlying delegate (item data source). |
| 385 | pub fn set_items(&mut self, items: D, _: &mut Window, cx: &mut Context<Self>) { |
| 386 | self.state.list.update(cx, |list, _| { |
| 387 | list.delegate_mut().delegate = items; |
| 388 | }); |
| 389 | } |
| 390 | |
| 391 | /// Focus the trigger. |
| 392 | pub fn focus(&self, window: &mut Window, cx: &mut App) { |
| 393 | self.state.focus_handle.focus(window, cx); |
| 394 | } |
| 395 | |
| 396 | /// Returns the search query. |
| 397 | pub fn query(&self, cx: &App) -> SharedString { |
| 398 | self.state.list.read(cx).query_input.read(cx).value() |
| 399 | } |
| 400 | |
| 401 | /// Sets the search query and updates the filtered items. |
| 402 | pub fn set_query(&self, query: impl Into<SharedString>, window: &mut Window, cx: &mut App) { |
| 403 | let query = query.into(); |
| 404 | self.state.list.update(cx, |list, cx| { |
| 405 | list.set_query(query.as_ref(), window, cx); |
| 406 | }); |
| 407 | } |
| 408 | |
| 409 | fn selection_changes( |
| 410 | multiple: bool, |
| 411 | selection: &[(IndexPath, D::Item)], |
| 412 | ix: IndexPath, |
| 413 | item: &D::Item, |
| 414 | ) -> Vec<SearchableListChange> { |
| 415 | let is_selected = selection |
| 416 | .iter() |
| 417 | .any(|(_, selected_item)| selected_item.value() == item.value()); |
| 418 | |
| 419 | if multiple { |
| 420 | if is_selected { |
| 421 | vec![SearchableListChange::Deselect { index: ix }] |
| 422 | } else { |
| 423 | vec![SearchableListChange::Select { index: ix }] |
| 424 | } |
| 425 | } else { |
| 426 | let mut changes: Vec<SearchableListChange> = selection |
| 427 | .iter() |
| 428 | .map(|(cur_ix, _)| SearchableListChange::Deselect { index: *cur_ix }) |
| 429 | .collect(); |
| 430 | changes.push(SearchableListChange::Select { index: ix }); |
| 431 | changes |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | /// Process an item click: single-select replaces the selection and closes; multi-select toggles. |
| 436 | /// |
| 437 | /// Calls `delegate.on_will_change` before committing and `delegate.on_confirm` when closing. |
| 438 | #[allow(dead_code)] |
| 439 | pub(crate) fn handle_item_select( |
| 440 | &mut self, |
| 441 | ix: IndexPath, |
| 442 | window: &mut Window, |
| 443 | cx: &mut Context<Self>, |
| 444 | ) { |
| 445 | let Some(item) = self |
| 446 | .state |
| 447 | .list |
| 448 | .read(cx) |
| 449 | .delegate() |
| 450 | .delegate |
| 451 | .item(ix) |
| 452 | .cloned() |
| 453 | else { |
| 454 | return; |
| 455 | }; |
| 456 | |
| 457 | let changes = Self::selection_changes(self.multiple, &self.state.selection, ix, &item); |
| 458 | |
| 459 | let mut selection = self.state.selection.clone(); |
| 460 | let before_indices: Vec<IndexPath> = selection.iter().map(|(ix, _)| *ix).collect(); |
| 461 | |
| 462 | self.state.list.update(cx, |list, _cx| { |
| 463 | list.delegate_mut() |
| 464 | .delegate |
| 465 | .on_will_change(&mut selection, &changes); |
| 466 | }); |
| 467 | |
| 468 | let after_indices: Vec<IndexPath> = selection.iter().map(|(ix, _)| *ix).collect(); |
| 469 | let changed = before_indices != after_indices; |
| 470 | let should_close = changed && !self.multiple; |
| 471 | |
| 472 | self.state.selection = selection; |
| 473 | self.state.sync_snapshot(cx); |
| 474 | |
| 475 | if changed { |
| 476 | cx.emit(ComboboxEvent::Change(self.selected_values())); |
| 477 | cx.notify(); |
| 478 | } |
| 479 | |
| 480 | if should_close { |
| 481 | let final_selection = self.state.selection.clone(); |
| 482 | self.state.list.update(cx, |list, _cx| { |
| 483 | list.delegate_mut().delegate.on_confirm(&final_selection); |
| 484 | }); |
| 485 | |
| 486 | cx.emit(ComboboxEvent::Confirm(self.selected_values())); |
| 487 | self.set_open(false, cx); |
| 488 | self.focus(window, cx); |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 493 | if self.state.list.read(cx).is_focused(window, cx) |
| 494 | || self.state.focus_handle.is_focused(window) |
| 495 | { |
| 496 | return; |
| 497 | } |
| 498 | |
| 499 | self.set_open(false, cx); |
| 500 | cx.notify(); |
| 501 | } |
| 502 | |
| 503 | fn toggle_menu(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) { |
| 504 | cx.stop_propagation(); |
| 505 | |
| 506 | self.set_open(!self.state.open, cx); |
| 507 | |
| 508 | if self.state.open { |
| 509 | self.state.list.focus_handle(cx).focus(window, cx); |
| 510 | } else { |
| 511 | cx.emit(ComboboxEvent::Confirm(self.selected_values())); |
| 512 | self.focus(window, cx); |
| 513 | } |
| 514 | |
| 515 | cx.notify(); |
| 516 | } |
| 517 | |
| 518 | /// Close the menu when a press lands outside the popup. |
| 519 | /// |
| 520 | /// A press on the trigger is left to propagate: swallowing it here would keep nested |
| 521 | /// controls (a tag remove button, the clear button) from ever seeing the press, and |
| 522 | /// `toggle_menu` closes the menu on release anyway. |
| 523 | fn dismiss(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) { |
| 524 | if !self.state.open || self.state.bounds.contains(&event.position) { |
| 525 | return; |
| 526 | } |
| 527 | |
| 528 | cx.stop_propagation(); |
| 529 | cx.emit(ComboboxEvent::Confirm(self.selected_values())); |
| 530 | |
| 531 | self.set_open(false, cx); |
| 532 | self.focus(window, cx); |
| 533 | cx.notify(); |
| 534 | } |
| 535 | |
| 536 | fn set_open(&mut self, open: bool, cx: &mut Context<Self>) { |
| 537 | self.state.open = open; |
| 538 | self.state.deferred_context = open.then(|| GlobalState::register_deferred_popover(cx)); |
| 539 | |
| 540 | cx.notify(); |
| 541 | } |
| 542 | |
| 543 | fn clean(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) { |
| 544 | cx.stop_propagation(); |
| 545 | self.clear_selection(cx); |
| 546 | } |
| 547 | |
| 548 | fn default_trigger_body(&self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement { |
| 549 | let placeholder_text = self |
| 550 | .state |
| 551 | .placeholder |
| 552 | .clone() |
| 553 | .unwrap_or_else(|| t!("Combobox.placeholder").into()); |
| 554 | |
| 555 | if self.state.selection.is_empty() { |
| 556 | return div() |
| 557 | .text_color(cx.theme().muted_foreground) |
| 558 | .child(placeholder_text) |
| 559 | .into_any_element(); |
| 560 | } |
| 561 | |
| 562 | if self.multiple { |
| 563 | let items: Vec<SharedString> = self |
| 564 | .state |
| 565 | .selection |
| 566 | .iter() |
| 567 | .map(|(_, i)| i.title()) |
| 568 | .collect(); |
| 569 | |
| 570 | div() |
| 571 | .w_full() |
| 572 | .overflow_hidden() |
| 573 | .whitespace_nowrap() |
| 574 | .truncate() |
| 575 | .child(items.join(", ")) |
| 576 | .into_any_element() |
| 577 | } else { |
| 578 | let title = self |
| 579 | .state |
| 580 | .selection |
| 581 | .first() |
| 582 | .map(|(_, i)| i.title()) |
| 583 | .unwrap_or_default(); |
| 584 | |
| 585 | div() |
| 586 | .w_full() |
| 587 | .overflow_hidden() |
| 588 | .whitespace_nowrap() |
| 589 | .truncate() |
| 590 | .child(title) |
| 591 | .into_any_element() |
| 592 | } |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | impl<D> Render for ComboboxState<D> |
| 597 | where |
| 598 | D: SearchableListDelegate + 'static, |
| 599 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 600 | { |
| 601 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 602 | let searchable = self.searchable; |
| 603 | let is_focused = self.state.focus_handle.is_focused(window); |
| 604 | let show_clean = self.state.cleanable && !self.state.selection.is_empty(); |
| 605 | let bounds = self.state.bounds; |
| 606 | let allow_open = !self.state.disabled; |
| 607 | let outline_visible = self.state.open || (is_focused && !self.state.disabled); |
| 608 | let disabled = self.state.disabled; |
| 609 | |
| 610 | let (bg, fg) = input_style(disabled, cx); |
| 611 | |
| 612 | self.state.list.update(cx, |list, cx| { |
| 613 | list.set_searchable(searchable, cx); |
| 614 | list.delegate_mut().size = self.state.size; |
| 615 | list.delegate_mut().check_icon = self.check_icon.clone(); |
| 616 | }); |
| 617 | |
| 618 | let selection = &self.state.selection; |
| 619 | let placeholder = self.state.placeholder.as_ref(); |
| 620 | let open = self.state.open; |
| 621 | let size = self.state.size; |
| 622 | let has_custom_trigger = self.render_trigger.is_some(); |
| 623 | |
| 624 | let trigger_body = if let Some(render_trigger) = &self.render_trigger { |
| 625 | let trigger = ComboboxTriggerContext { |
| 626 | selection, |
| 627 | placeholder, |
| 628 | open, |
| 629 | disabled, |
| 630 | size, |
| 631 | }; |
| 632 | |
| 633 | render_trigger(&trigger, window, cx) |
| 634 | } else { |
| 635 | self.default_trigger_body(window, cx) |
| 636 | }; |
| 637 | |
| 638 | let trailing: AnyElement = if has_custom_trigger { |
| 639 | div().into_any_element() |
| 640 | } else if show_clean { |
| 641 | clear_button(cx) |
| 642 | .map(|this| { |
| 643 | if disabled { |
| 644 | this.disabled(true) |
| 645 | } else { |
| 646 | this.on_click(cx.listener(Self::clean)) |
| 647 | } |
| 648 | }) |
| 649 | .into_any_element() |
| 650 | } else if let Some(icon) = self.trigger_icon.clone() { |
| 651 | icon.xsmall() |
| 652 | .text_color(cx.theme().muted_foreground) |
| 653 | .into_any_element() |
| 654 | } else { |
| 655 | Caret::new(size) |
| 656 | .text_color(cx.theme().muted_foreground) |
| 657 | .into_any_element() |
| 658 | }; |
| 659 | |
| 660 | let toggle_handler: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>> = |
| 661 | if allow_open { |
| 662 | Some(Box::new(cx.listener(Self::toggle_menu))) |
| 663 | } else { |
| 664 | None |
| 665 | }; |
| 666 | |
| 667 | let footer_el = self.footer.as_ref().map(|f| f(window, cx)); |
| 668 | |
| 669 | let dismiss_handler: Box<dyn Fn(&MouseDownEvent, &mut Window, &mut App) + 'static> = |
| 670 | Box::new(cx.listener(Self::dismiss)); |
| 671 | |
| 672 | div().size_full().relative().child( |
| 673 | div() |
| 674 | .relative() |
| 675 | .on_prepaint({ |
| 676 | let state = cx.entity(); |
| 677 | move |bounds, _, cx| state.update(cx, |r, _| r.state.bounds = bounds) |
| 678 | }) |
| 679 | .child(render_trigger_container( |
| 680 | disabled, |
| 681 | self.state.appearance, |
| 682 | self.focus_ring_enabled, |
| 683 | self.state.size, |
| 684 | &self.state.style, |
| 685 | bg, |
| 686 | fg, |
| 687 | outline_visible, |
| 688 | allow_open, |
| 689 | trigger_body, |
| 690 | trailing, |
| 691 | toggle_handler, |
| 692 | window, |
| 693 | cx, |
| 694 | )) |
| 695 | .when(self.state.open, |this| { |
| 696 | this.child( |
| 697 | deferred(render_popup_shell( |
| 698 | ("combobox-popup", cx.entity_id()), |
| 699 | &self.state.list, |
| 700 | self.state.menu_width, |
| 701 | self.state.search_placeholder.clone(), |
| 702 | self.state.size, |
| 703 | self.state.menu_max_h, |
| 704 | bounds, |
| 705 | footer_el, |
| 706 | dismiss_handler, |
| 707 | window, |
| 708 | cx, |
| 709 | )) |
| 710 | .with_priority(gpui_base::POPUP_PRIORITY), |
| 711 | ) |
| 712 | }), |
| 713 | ) |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | impl<D> EventEmitter<ComboboxEvent<D>> for ComboboxState<D> |
| 718 | where |
| 719 | D: SearchableListDelegate + 'static, |
| 720 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 721 | { |
| 722 | } |
| 723 | impl<D> EventEmitter<DismissEvent> for ComboboxState<D> |
| 724 | where |
| 725 | D: SearchableListDelegate + 'static, |
| 726 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 727 | { |
| 728 | } |
| 729 | |
| 730 | impl<D> Focusable for ComboboxState<D> |
| 731 | where |
| 732 | D: SearchableListDelegate + 'static, |
| 733 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 734 | { |
| 735 | fn focus_handle(&self, cx: &App) -> FocusHandle { |
| 736 | if self.state.open { |
| 737 | self.state.list.focus_handle(cx) |
| 738 | } else { |
| 739 | self.state.focus_handle.clone() |
| 740 | } |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | // MARK: Combobox element |
| 745 | |
| 746 | /// A combo box with support for single and multi-select. |
| 747 | /// |
| 748 | /// Clicking an item toggles it in the selection; the dropdown stays open until the user |
| 749 | /// presses Escape or clicks outside. |
| 750 | #[derive(IntoElement)] |
| 751 | pub struct Combobox<D: SearchableListDelegate + 'static> |
| 752 | where |
| 753 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 754 | { |
| 755 | id: ElementId, |
| 756 | state: Entity<ComboboxState<D>>, |
| 757 | options: ComboboxOptions, |
| 758 | render_trigger: Option< |
| 759 | Box<dyn Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> AnyElement + 'static>, |
| 760 | >, |
| 761 | footer: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>>, |
| 762 | empty: Option<Box<dyn Fn(&mut Window, &App) -> AnyElement + 'static>>, |
| 763 | } |
| 764 | |
| 765 | impl<D> Combobox<D> |
| 766 | where |
| 767 | D: SearchableListDelegate + 'static, |
| 768 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 769 | { |
| 770 | pub fn new(state: &Entity<ComboboxState<D>>) -> Self { |
| 771 | Self { |
| 772 | id: ("multi-combo-box", state.entity_id()).into(), |
| 773 | state: state.clone(), |
| 774 | options: ComboboxOptions::default(), |
| 775 | render_trigger: None, |
| 776 | footer: None, |
| 777 | empty: None, |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | /// Set the width of the dropdown menu. |
| 782 | pub fn menu_width(mut self, width: impl Into<Length>) -> Self { |
| 783 | self.options.menu_width = width.into(); |
| 784 | self |
| 785 | } |
| 786 | |
| 787 | /// Set the maximum height of the dropdown menu. |
| 788 | pub fn menu_max_h(mut self, max_h: impl Into<Length>) -> Self { |
| 789 | self.options.menu_max_h = max_h.into(); |
| 790 | self |
| 791 | } |
| 792 | |
| 793 | /// Set the placeholder text shown when no items are selected. |
| 794 | pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { |
| 795 | self.options.placeholder = Some(placeholder.into()); |
| 796 | self |
| 797 | } |
| 798 | |
| 799 | /// Override the trigger chevron icon. |
| 800 | pub fn icon(mut self, icon: impl Into<Icon>) -> Self { |
| 801 | self.options.trigger_icon = Some(icon.into()); |
| 802 | self |
| 803 | } |
| 804 | |
| 805 | /// Override the trailing check icon shown next to selected items. |
| 806 | pub fn check_icon(mut self, icon: impl Into<Icon>) -> Self { |
| 807 | self.options.check_icon = Some(icon.into()); |
| 808 | self |
| 809 | } |
| 810 | |
| 811 | /// Set the placeholder text for the search input. |
| 812 | pub fn search_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { |
| 813 | self.options.search_placeholder = Some(placeholder.into()); |
| 814 | self |
| 815 | } |
| 816 | |
| 817 | /// Show a clear button when at least one item is selected. |
| 818 | pub fn cleanable(mut self, cleanable: bool) -> Self { |
| 819 | self.options.cleanable = cleanable; |
| 820 | self |
| 821 | } |
| 822 | |
| 823 | /// Set the disabled state. |
| 824 | pub fn disabled(mut self, disabled: bool) -> Self { |
| 825 | self.options.disabled = disabled; |
| 826 | self |
| 827 | } |
| 828 | |
| 829 | /// Set a custom closure that renders the empty-state element. |
| 830 | pub fn empty<E: IntoElement + 'static>( |
| 831 | mut self, |
| 832 | builder: impl Fn(&mut Window, &App) -> E + 'static, |
| 833 | ) -> Self { |
| 834 | self.empty = Some(Box::new(move |window, cx| { |
| 835 | builder(window, cx).into_any_element() |
| 836 | })); |
| 837 | self |
| 838 | } |
| 839 | |
| 840 | /// Control whether the trigger shows a border and background. |
| 841 | pub fn appearance(mut self, appearance: bool) -> Self { |
| 842 | self.options.appearance = appearance; |
| 843 | self |
| 844 | } |
| 845 | |
| 846 | /// Override the entire trigger element. |
| 847 | pub fn render_trigger<E: IntoElement + 'static>( |
| 848 | mut self, |
| 849 | f: impl Fn(&ComboboxTriggerContext<D>, &mut Window, &mut App) -> E + 'static, |
| 850 | ) -> Self { |
| 851 | self.render_trigger = Some(Box::new(move |trigger, window, cx| { |
| 852 | f(trigger, window, cx).into_any_element() |
| 853 | })); |
| 854 | self |
| 855 | } |
| 856 | |
| 857 | /// Render an element below a separator at the bottom of the dropdown. |
| 858 | pub fn footer<E: IntoElement + 'static>( |
| 859 | mut self, |
| 860 | f: impl Fn(&mut Window, &mut App) -> E + 'static, |
| 861 | ) -> Self { |
| 862 | self.footer = Some(Box::new(move |window, cx| f(window, cx).into_any_element())); |
| 863 | self |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | impl<D> Sizable for Combobox<D> |
| 868 | where |
| 869 | D: SearchableListDelegate + 'static, |
| 870 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 871 | { |
| 872 | fn with_size(mut self, size: impl Into<Size>) -> Self { |
| 873 | self.options.size = size.into(); |
| 874 | self |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | impl<D> crate::FocusableExt for Combobox<D> |
| 879 | where |
| 880 | D: SearchableListDelegate + 'static, |
| 881 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 882 | { |
| 883 | fn focus_ring(mut self, enabled: bool) -> Self { |
| 884 | self.options.focus_ring_enabled = enabled; |
| 885 | self |
| 886 | } |
| 887 | |
| 888 | fn is_focus_ring_enabled(&self) -> bool { |
| 889 | self.options.focus_ring_enabled |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | impl<D> Styled for Combobox<D> |
| 894 | where |
| 895 | D: SearchableListDelegate + 'static, |
| 896 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 897 | { |
| 898 | fn style(&mut self) -> &mut StyleRefinement { |
| 899 | &mut self.options.style |
| 900 | } |
| 901 | } |
| 902 | |
| 903 | impl<D> RenderOnce for Combobox<D> |
| 904 | where |
| 905 | D: SearchableListDelegate + 'static, |
| 906 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 907 | { |
| 908 | fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { |
| 909 | let disabled = self.options.disabled; |
| 910 | let focus_handle = self.state.read(cx).state.focus_handle.clone(); |
| 911 | let render_trigger = self.render_trigger; |
| 912 | let footer = self.footer; |
| 913 | let empty = self.empty; |
| 914 | let opts = self.options; |
| 915 | |
| 916 | self.state.update(cx, |this, _| { |
| 917 | this.state.style = opts.style; |
| 918 | this.state.size = opts.size; |
| 919 | this.state.cleanable = opts.cleanable; |
| 920 | this.state.placeholder = opts.placeholder; |
| 921 | this.state.search_placeholder = opts.search_placeholder; |
| 922 | this.state.menu_width = opts.menu_width; |
| 923 | this.state.menu_max_h = opts.menu_max_h; |
| 924 | this.state.disabled = opts.disabled; |
| 925 | this.state.appearance = opts.appearance; |
| 926 | this.focus_ring_enabled = opts.focus_ring_enabled; |
| 927 | this.trigger_icon = opts.trigger_icon; |
| 928 | this.check_icon = opts.check_icon; |
| 929 | this.render_trigger = render_trigger; |
| 930 | this.footer = footer; |
| 931 | |
| 932 | if let Some(empty) = empty { |
| 933 | this.state.empty = Some(empty); |
| 934 | } |
| 935 | }); |
| 936 | |
| 937 | let is_open = self.state.read(cx).state.open; |
| 938 | let content_focus_handle = self.state.read(cx).state.list.focus_handle(cx); |
| 939 | let open_state = self.state.clone(); |
| 940 | let confirm_state = self.state.clone(); |
| 941 | |
| 942 | BaseCombobox::new(self.id) |
| 943 | .open(is_open) |
| 944 | .disabled(disabled) |
| 945 | .focus_handle(&focus_handle) |
| 946 | .content_focus_handle(&content_focus_handle) |
| 947 | .on_open_change(move |open, _, cx| { |
| 948 | open_state.update(cx, |state, cx| state.set_open(open, cx)); |
| 949 | }) |
| 950 | // This combobox commits its pending selection when the popup |
| 951 | // closes, so it listens for dismissal rather than Confirm. |
| 952 | .on_dismiss(move |_, cx| { |
| 953 | confirm_state.update(cx, |state, cx| { |
| 954 | cx.emit(ComboboxEvent::Confirm(state.selected_values())); |
| 955 | }); |
| 956 | }) |
| 957 | .size_full() |
| 958 | .child(self.state) |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | // MARK: Rendering helpers |
| 963 | |
| 964 | /// Renders the styled trigger container. |
| 965 | #[allow(clippy::too_many_arguments)] |
| 966 | fn render_trigger_container( |
| 967 | disabled: bool, |
| 968 | appearance: bool, |
| 969 | focus_ring_enabled: bool, |
| 970 | size: Size, |
| 971 | style: &StyleRefinement, |
| 972 | bg: Hsla, |
| 973 | fg: Hsla, |
| 974 | outline_visible: bool, |
| 975 | allow_open: bool, |
| 976 | trigger_body: AnyElement, |
| 977 | trailing: AnyElement, |
| 978 | toggle_handler: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>, |
| 979 | window: &Window, |
| 980 | cx: &mut App, |
| 981 | ) -> impl IntoElement { |
| 982 | div() |
| 983 | .id("input") |
| 984 | .relative() |
| 985 | .flex() |
| 986 | .items_center() |
| 987 | .justify_between() |
| 988 | .border_1() |
| 989 | .border_color(cx.theme().transparent) |
| 990 | .when(appearance, |this| { |
| 991 | this.bg(bg) |
| 992 | .text_color(fg) |
| 993 | .when(disabled, |this| this.opacity(0.5)) |
| 994 | .border_color(cx.theme().input) |
| 995 | .rounded(cx.theme().radius) |
| 996 | }) |
| 997 | .input_size(size) |
| 998 | .input_text_size(size) |
| 999 | .refine_style(style) |
| 1000 | .when(outline_visible && appearance, |this| { |
| 1001 | this.border_1().border_color(cx.theme().ring) |
| 1002 | }) |
| 1003 | .when( |
| 1004 | outline_visible && appearance && focus_ring_enabled, |
| 1005 | |this| this.focus_ring_style(window, cx), |
| 1006 | ) |
| 1007 | .when(allow_open, |this| { |
| 1008 | this.when_some(toggle_handler, |this, handler| this.on_click(handler)) |
| 1009 | }) |
| 1010 | .child( |
| 1011 | h_flex() |
| 1012 | .id("inner") |
| 1013 | .w_full() |
| 1014 | .min_w_0() |
| 1015 | .overflow_hidden() |
| 1016 | .whitespace_nowrap() |
| 1017 | .items_center() |
| 1018 | .justify_between() |
| 1019 | .gap_1() |
| 1020 | .child( |
| 1021 | div() |
| 1022 | .flex_1() |
| 1023 | .min_w_0() |
| 1024 | .overflow_hidden() |
| 1025 | .whitespace_nowrap() |
| 1026 | .child(trigger_body), |
| 1027 | ) |
| 1028 | .child(trailing), |
| 1029 | ) |
| 1030 | } |
| 1031 | |
| 1032 | /// Renders the deferred anchored popup shell containing the searchable list and optional footer. |
| 1033 | #[allow(clippy::too_many_arguments)] |
| 1034 | fn render_popup_shell<D: SearchableListDelegate + 'static>( |
| 1035 | id: impl Into<ElementId>, |
| 1036 | list: &Entity<ListState<SearchableListAdapter<D>>>, |
| 1037 | menu_width: Length, |
| 1038 | search_placeholder: Option<SharedString>, |
| 1039 | size: Size, |
| 1040 | menu_max_h: Length, |
| 1041 | bounds: Bounds<Pixels>, |
| 1042 | footer_el: Option<AnyElement>, |
| 1043 | dismiss_handler: Box<dyn Fn(&MouseDownEvent, &mut Window, &mut App) + 'static>, |
| 1044 | window: &Window, |
| 1045 | cx: &mut App, |
| 1046 | ) -> AnyElement { |
| 1047 | let has_footer = footer_el.is_some(); |
| 1048 | |
| 1049 | crate::popover::dropdown_popup( |
| 1050 | id, |
| 1051 | bounds, |
| 1052 | v_flex() |
| 1053 | .occlude() |
| 1054 | .map(|this| match menu_width { |
| 1055 | Length::Auto => this.w(bounds.size.width), |
| 1056 | Length::Definite(w) => this.w(w), |
| 1057 | }) |
| 1058 | .popover_style(window, cx) |
| 1059 | .child( |
| 1060 | List::new(list) |
| 1061 | .when_some(search_placeholder, |this, placeholder| { |
| 1062 | this.search_placeholder(placeholder) |
| 1063 | }) |
| 1064 | .with_size(size) |
| 1065 | .max_h(menu_max_h) |
| 1066 | .paddings(Edges::all(DROPDOWN_LIST_PADDING)), |
| 1067 | ) |
| 1068 | .when(has_footer, |this| { |
| 1069 | this.child( |
| 1070 | div() |
| 1071 | .border_t_1() |
| 1072 | .border_color(cx.theme().border) |
| 1073 | .p_1() |
| 1074 | .when_some(footer_el, |this, el| this.child(el)), |
| 1075 | ) |
| 1076 | }) |
| 1077 | .on_mouse_down_out(dismiss_handler), |
| 1078 | cx, |
| 1079 | ) |
| 1080 | .into_any_element() |
| 1081 | } |
| 1082 | |
| 1083 | // MARK: Tests |
| 1084 | |
| 1085 | #[cfg(test)] |
| 1086 | mod tests { |
| 1087 | use std::{cell::Cell, rc::Rc}; |
| 1088 | |
| 1089 | use gpui::{ |
| 1090 | AppContext as _, Bounds, Context, Entity, Modifiers, MouseButton, MouseDownEvent, Pixels, |
| 1091 | Point, Subscription, TestAppContext, point, px, size, |
| 1092 | }; |
| 1093 | |
| 1094 | use crate::{ |
| 1095 | IndexPath, |
| 1096 | combobox::{Combobox, ComboboxEvent, ComboboxState}, |
| 1097 | searchable_list::{ |
| 1098 | SearchableListChange, SearchableListDelegate, SearchableListItem, SearchableListState, |
| 1099 | SearchableVec, |
| 1100 | }, |
| 1101 | }; |
| 1102 | |
| 1103 | struct TestComboboxEventCollector { |
| 1104 | event_count: Rc<Cell<usize>>, |
| 1105 | _subscription: Subscription, |
| 1106 | } |
| 1107 | |
| 1108 | impl TestComboboxEventCollector { |
| 1109 | fn new( |
| 1110 | state: &Entity<ComboboxState<SearchableVec<&'static str>>>, |
| 1111 | cx: &mut Context<Self>, |
| 1112 | ) -> Self { |
| 1113 | let event_count = Rc::new(Cell::new(0)); |
| 1114 | let event_count_for_subscription = event_count.clone(); |
| 1115 | let _subscription = cx.subscribe( |
| 1116 | state, |
| 1117 | move |_, _, _: &ComboboxEvent<SearchableVec<&'static str>>, _| { |
| 1118 | event_count_for_subscription.set(event_count_for_subscription.get() + 1); |
| 1119 | }, |
| 1120 | ); |
| 1121 | |
| 1122 | Self { |
| 1123 | event_count, |
| 1124 | _subscription, |
| 1125 | } |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | #[gpui::test] |
| 1130 | fn test_combo_box_builder(cx: &mut TestAppContext) { |
| 1131 | cx.update(crate::init); |
| 1132 | let cx = cx.add_empty_window(); |
| 1133 | cx.update(|window, cx| { |
| 1134 | let items = SearchableVec::new(vec!["Rust", "Go", "C++"]); |
| 1135 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true)); |
| 1136 | |
| 1137 | let _cb = Combobox::new(&state) |
| 1138 | .placeholder("Select language") |
| 1139 | .search_placeholder("Search...") |
| 1140 | .menu_width(gpui::px(300.)) |
| 1141 | .menu_max_h(gpui::rems(15.)) |
| 1142 | .cleanable(true) |
| 1143 | .disabled(false) |
| 1144 | .appearance(true); |
| 1145 | }); |
| 1146 | } |
| 1147 | |
| 1148 | #[gpui::test] |
| 1149 | fn test_combo_box_search_filters_items(cx: &mut TestAppContext) { |
| 1150 | cx.update(crate::init); |
| 1151 | let cx = cx.add_empty_window(); |
| 1152 | cx.update(|window, cx| { |
| 1153 | let items = SearchableVec::new(vec!["Rust", "Go", "C++"]); |
| 1154 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true)); |
| 1155 | |
| 1156 | let count_before = state |
| 1157 | .read(cx) |
| 1158 | .state |
| 1159 | .list |
| 1160 | .read(cx) |
| 1161 | .delegate() |
| 1162 | .delegate |
| 1163 | .items_count(0); |
| 1164 | assert_eq!(count_before, 3); |
| 1165 | |
| 1166 | state.update(cx, |s, cx| { |
| 1167 | s.state.list.update(cx, |list, cx| { |
| 1168 | let _ = list |
| 1169 | .delegate_mut() |
| 1170 | .delegate |
| 1171 | .perform_search("Rust", window, cx); |
| 1172 | }); |
| 1173 | }); |
| 1174 | |
| 1175 | let count_after = state |
| 1176 | .read(cx) |
| 1177 | .state |
| 1178 | .list |
| 1179 | .read(cx) |
| 1180 | .delegate() |
| 1181 | .delegate |
| 1182 | .items_count(0); |
| 1183 | assert_eq!(count_after, 1); |
| 1184 | }); |
| 1185 | } |
| 1186 | |
| 1187 | #[gpui::test] |
| 1188 | fn test_combo_box_set_query_updates_text_and_filters_items(cx: &mut TestAppContext) { |
| 1189 | cx.update(crate::init); |
| 1190 | let cx = cx.add_empty_window(); |
| 1191 | cx.update(|window, cx| { |
| 1192 | let items = SearchableVec::new(vec!["Rust", "Go", "C++"]); |
| 1193 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).searchable(true)); |
| 1194 | |
| 1195 | state.update(cx, |state, cx| state.set_query(" Rust ", window, cx)); |
| 1196 | |
| 1197 | assert_eq!(state.read(cx).query(cx).as_ref(), " Rust "); |
| 1198 | assert_eq!( |
| 1199 | state |
| 1200 | .read(cx) |
| 1201 | .state |
| 1202 | .list |
| 1203 | .read(cx) |
| 1204 | .delegate() |
| 1205 | .delegate |
| 1206 | .items_count(0), |
| 1207 | 1, |
| 1208 | ); |
| 1209 | }); |
| 1210 | } |
| 1211 | |
| 1212 | #[gpui::test] |
| 1213 | fn test_multi_combo_box_builder(cx: &mut TestAppContext) { |
| 1214 | cx.update(crate::init); |
| 1215 | let cx = cx.add_empty_window(); |
| 1216 | cx.update(|window, cx| { |
| 1217 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1218 | let state = cx.new(|cx| { |
| 1219 | ComboboxState::new(items, vec![IndexPath::new(0)], window, cx) |
| 1220 | .multiple(true) |
| 1221 | .searchable(true) |
| 1222 | }); |
| 1223 | |
| 1224 | let _cb = Combobox::new(&state) |
| 1225 | .placeholder("Select frameworks") |
| 1226 | .search_placeholder("Search...") |
| 1227 | .menu_width(gpui::px(300.)) |
| 1228 | .cleanable(true) |
| 1229 | .disabled(false); |
| 1230 | |
| 1231 | assert_eq!(state.read(cx).selected_values(), vec!["React"]); |
| 1232 | }); |
| 1233 | } |
| 1234 | |
| 1235 | #[gpui::test] |
| 1236 | fn test_combo_box_set_selected_values_uses_current_delegate(cx: &mut TestAppContext) { |
| 1237 | cx.update(crate::init); |
| 1238 | let cx = cx.add_empty_window(); |
| 1239 | cx.update(|window, cx| { |
| 1240 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1241 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true)); |
| 1242 | |
| 1243 | state.update(cx, |state, cx| { |
| 1244 | state.set_selected_values(&["Vue", "Missing"], window, cx); |
| 1245 | |
| 1246 | assert_eq!(state.selected_values(), vec!["Vue"]); |
| 1247 | assert_eq!( |
| 1248 | state |
| 1249 | .selection() |
| 1250 | .iter() |
| 1251 | .map(|(index, _)| *index) |
| 1252 | .collect::<Vec<_>>(), |
| 1253 | vec![IndexPath::new(1)], |
| 1254 | ); |
| 1255 | assert_eq!( |
| 1256 | state |
| 1257 | .state |
| 1258 | .list |
| 1259 | .read(cx) |
| 1260 | .delegate() |
| 1261 | .selection_snapshot |
| 1262 | .as_slice(), |
| 1263 | state.selection(), |
| 1264 | ); |
| 1265 | |
| 1266 | state.set_items(SearchableVec::new(vec!["Vue", "Rust", "Go"]), window, cx); |
| 1267 | state.set_selected_values(&["Go", "Vue"], window, cx); |
| 1268 | |
| 1269 | assert_eq!(state.selected_values(), vec!["Go", "Vue"]); |
| 1270 | assert_eq!( |
| 1271 | state |
| 1272 | .selection() |
| 1273 | .iter() |
| 1274 | .map(|(index, _)| *index) |
| 1275 | .collect::<Vec<_>>(), |
| 1276 | vec![IndexPath::new(2), IndexPath::new(0)], |
| 1277 | ); |
| 1278 | assert_eq!( |
| 1279 | state |
| 1280 | .state |
| 1281 | .list |
| 1282 | .read(cx) |
| 1283 | .delegate() |
| 1284 | .selection_snapshot |
| 1285 | .as_slice(), |
| 1286 | state.selection(), |
| 1287 | ); |
| 1288 | |
| 1289 | state.set_selected_values(&[], window, cx); |
| 1290 | |
| 1291 | assert!(state.selection().is_empty()); |
| 1292 | assert!( |
| 1293 | state |
| 1294 | .state |
| 1295 | .list |
| 1296 | .read(cx) |
| 1297 | .delegate() |
| 1298 | .selection_snapshot |
| 1299 | .is_empty() |
| 1300 | ); |
| 1301 | }); |
| 1302 | }); |
| 1303 | } |
| 1304 | |
| 1305 | /// A value projected in from outside is not a position in the filtered view, |
| 1306 | /// so an active search must not decide which values can be selected. |
| 1307 | #[gpui::test] |
| 1308 | fn test_combo_box_set_selected_values_keeps_values_hidden_by_the_search( |
| 1309 | cx: &mut TestAppContext, |
| 1310 | ) { |
| 1311 | cx.update(crate::init); |
| 1312 | let cx = cx.add_empty_window(); |
| 1313 | cx.update(|window, cx| { |
| 1314 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1315 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true)); |
| 1316 | |
| 1317 | state.update(cx, |state, cx| { |
| 1318 | state.set_selected_values(&["React", "Vue"], window, cx); |
| 1319 | state.state.list.update(cx, |list, cx| { |
| 1320 | list.set_query("Angular", window, cx); |
| 1321 | }); |
| 1322 | |
| 1323 | state.set_selected_values(&["React", "Vue", "Angular"], window, cx); |
| 1324 | |
| 1325 | assert_eq!( |
| 1326 | state.selected_values(), |
| 1327 | vec!["React", "Vue", "Angular"], |
| 1328 | "a value the search had hidden must survive being reapplied" |
| 1329 | ); |
| 1330 | assert_eq!( |
| 1331 | state |
| 1332 | .selection() |
| 1333 | .iter() |
| 1334 | .map(|(index, _)| *index) |
| 1335 | .collect::<Vec<_>>(), |
| 1336 | vec![IndexPath::new(0), IndexPath::new(1), IndexPath::new(2)], |
| 1337 | "clearing the query puts every selected item back in view" |
| 1338 | ); |
| 1339 | }); |
| 1340 | }); |
| 1341 | } |
| 1342 | |
| 1343 | #[gpui::test] |
| 1344 | fn test_combo_box_set_selected_values_does_not_emit_events(cx: &mut TestAppContext) { |
| 1345 | cx.update(crate::init); |
| 1346 | let cx = cx.add_empty_window(); |
| 1347 | let state = cx.update(|window, cx| { |
| 1348 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1349 | cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true)) |
| 1350 | }); |
| 1351 | let collector = cx.update(|_, cx| cx.new(|cx| TestComboboxEventCollector::new(&state, cx))); |
| 1352 | |
| 1353 | cx.update(|window, cx| { |
| 1354 | state.update(cx, |state, cx| { |
| 1355 | state.set_selected_values(&["React", "Vue"], window, cx); |
| 1356 | }); |
| 1357 | }); |
| 1358 | |
| 1359 | cx.update(|_, cx| { |
| 1360 | assert_eq!(collector.read(cx).event_count.get(), 0); |
| 1361 | }); |
| 1362 | } |
| 1363 | |
| 1364 | #[gpui::test] |
| 1365 | fn test_combo_box_initial_selection_seeds_cursor(cx: &mut TestAppContext) { |
| 1366 | cx.update(crate::init); |
| 1367 | let cx = cx.add_empty_window(); |
| 1368 | cx.update(|window, cx| { |
| 1369 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1370 | let state = cx.new(|cx| { |
| 1371 | ComboboxState::new(items, vec![IndexPath::new(1)], window, cx).multiple(true) |
| 1372 | }); |
| 1373 | |
| 1374 | let state_ref = state.read(cx); |
| 1375 | assert_eq!( |
| 1376 | state_ref.state.list.read(cx).selected_index(), |
| 1377 | Some(IndexPath::new(1)), |
| 1378 | "initial selected_indices should seed ListState.selected_index, not just the snapshot", |
| 1379 | ); |
| 1380 | assert_eq!(state_ref.selected_values(), vec!["Vue"]); |
| 1381 | }); |
| 1382 | } |
| 1383 | |
| 1384 | #[gpui::test] |
| 1385 | fn test_multi_combo_box_toggle(cx: &mut TestAppContext) { |
| 1386 | cx.update(crate::init); |
| 1387 | let cx = cx.add_empty_window(); |
| 1388 | cx.update(|window, cx| { |
| 1389 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1390 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true)); |
| 1391 | |
| 1392 | state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx)); |
| 1393 | assert_eq!(state.read(cx).selected_values(), &["React"]); |
| 1394 | |
| 1395 | state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(1), cx)); |
| 1396 | assert_eq!(state.read(cx).selected_values(), &["React", "Vue"]); |
| 1397 | |
| 1398 | state.update(cx, |s, cx| s.remove_selected_index(IndexPath::new(0), cx)); |
| 1399 | assert_eq!(state.read(cx).selected_values(), &["Vue"]); |
| 1400 | }); |
| 1401 | } |
| 1402 | |
| 1403 | #[gpui::test] |
| 1404 | fn test_multi_combo_box_search_selection_uses_value_identity(cx: &mut TestAppContext) { |
| 1405 | cx.update(crate::init); |
| 1406 | let cx = cx.add_empty_window(); |
| 1407 | cx.update(|window, cx| { |
| 1408 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1409 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true)); |
| 1410 | |
| 1411 | state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx)); |
| 1412 | assert_eq!(state.read(cx).selected_values(), &["React"]); |
| 1413 | |
| 1414 | state.update(cx, |s, cx| { |
| 1415 | s.state.list.update(cx, |list, cx| { |
| 1416 | let _ = list |
| 1417 | .delegate_mut() |
| 1418 | .delegate |
| 1419 | .perform_search("Vue", window, cx); |
| 1420 | }); |
| 1421 | }); |
| 1422 | |
| 1423 | state.read_with(cx, |s, cx| { |
| 1424 | let selection = s.state.selection.clone(); |
| 1425 | let list = s.state.list.read(cx); |
| 1426 | let delegate = &list.delegate().delegate; |
| 1427 | let ix = IndexPath::new(0); |
| 1428 | let item = delegate.item(ix).expect("filtered item exists"); |
| 1429 | |
| 1430 | assert_eq!(item.value(), &"Vue"); |
| 1431 | assert!( |
| 1432 | !delegate.is_item_checked(ix, item, &selection, cx), |
| 1433 | "filtered row 0 should not inherit React's checked state", |
| 1434 | ); |
| 1435 | }); |
| 1436 | |
| 1437 | state.update(cx, |s, cx| { |
| 1438 | s.handle_item_select(IndexPath::new(0), window, cx); |
| 1439 | }); |
| 1440 | assert_eq!(state.read(cx).selected_values(), &["React", "Vue"]); |
| 1441 | }); |
| 1442 | } |
| 1443 | |
| 1444 | #[gpui::test] |
| 1445 | fn test_multi_combo_box_search_deselects_by_value(cx: &mut TestAppContext) { |
| 1446 | cx.update(crate::init); |
| 1447 | let cx = cx.add_empty_window(); |
| 1448 | cx.update(|window, cx| { |
| 1449 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1450 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true)); |
| 1451 | |
| 1452 | state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx)); |
| 1453 | |
| 1454 | state.update(cx, |s, cx| { |
| 1455 | s.state.list.update(cx, |list, cx| { |
| 1456 | let _ = list |
| 1457 | .delegate_mut() |
| 1458 | .delegate |
| 1459 | .perform_search("React", window, cx); |
| 1460 | }); |
| 1461 | }); |
| 1462 | |
| 1463 | state.update(cx, |s, cx| { |
| 1464 | s.handle_item_select(IndexPath::new(0), window, cx); |
| 1465 | }); |
| 1466 | assert!(state.read(cx).selected_values().is_empty()); |
| 1467 | }); |
| 1468 | } |
| 1469 | |
| 1470 | #[gpui::test] |
| 1471 | fn test_searchable_list_default_change_uses_value_identity(cx: &mut TestAppContext) { |
| 1472 | cx.update(crate::init); |
| 1473 | let cx = cx.add_empty_window(); |
| 1474 | cx.update(|window, cx| { |
| 1475 | let mut delegate = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1476 | let mut selection = vec![(IndexPath::new(1), "Vue")]; |
| 1477 | |
| 1478 | let _ = delegate.perform_search("Vue", window, cx); |
| 1479 | delegate.on_will_change( |
| 1480 | &mut selection, |
| 1481 | &[SearchableListChange::Deselect { |
| 1482 | index: IndexPath::new(0), |
| 1483 | }], |
| 1484 | ); |
| 1485 | assert!(selection.is_empty()); |
| 1486 | |
| 1487 | delegate.on_will_change( |
| 1488 | &mut selection, |
| 1489 | &[SearchableListChange::Select { |
| 1490 | index: IndexPath::new(0), |
| 1491 | }], |
| 1492 | ); |
| 1493 | assert_eq!(selection, vec![(IndexPath::new(0), "Vue")]); |
| 1494 | }); |
| 1495 | } |
| 1496 | |
| 1497 | #[gpui::test] |
| 1498 | fn test_multi_combo_box_clear(cx: &mut TestAppContext) { |
| 1499 | cx.update(crate::init); |
| 1500 | let cx = cx.add_empty_window(); |
| 1501 | cx.update(|window, cx| { |
| 1502 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1503 | let state = cx.new(|cx| { |
| 1504 | ComboboxState::new( |
| 1505 | items, |
| 1506 | vec![IndexPath::new(0), IndexPath::new(1)], |
| 1507 | window, |
| 1508 | cx, |
| 1509 | ) |
| 1510 | .multiple(true) |
| 1511 | }); |
| 1512 | |
| 1513 | assert_eq!(state.read(cx).selected_values().len(), 2); |
| 1514 | state.update(cx, |s, cx| s.clear_selection(cx)); |
| 1515 | assert!(state.read(cx).selected_values().is_empty()); |
| 1516 | }); |
| 1517 | } |
| 1518 | |
| 1519 | #[gpui::test] |
| 1520 | fn test_single_combo_box_mode(cx: &mut TestAppContext) { |
| 1521 | cx.update(crate::init); |
| 1522 | let cx = cx.add_empty_window(); |
| 1523 | cx.update(|window, cx| { |
| 1524 | let items = SearchableVec::new(vec!["Rust", "Go", "C++"]); |
| 1525 | let state = cx.new(|cx| ComboboxState::new(items, vec![], window, cx)); |
| 1526 | |
| 1527 | // Default mode is Single. |
| 1528 | state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx)); |
| 1529 | assert_eq!(state.read(cx).selected_values(), &["Rust"]); |
| 1530 | |
| 1531 | state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(1), cx)); |
| 1532 | assert_eq!(state.read(cx).selected_values(), &["Rust", "Go"]); |
| 1533 | }); |
| 1534 | } |
| 1535 | |
| 1536 | // Delegate that vetoes all selections via on_will_change by ignoring the changes. |
| 1537 | struct VetoDelegate(SearchableVec<&'static str>); |
| 1538 | |
| 1539 | impl SearchableListDelegate for VetoDelegate { |
| 1540 | type Item = &'static str; |
| 1541 | |
| 1542 | fn items_count(&self, section: usize) -> usize { |
| 1543 | self.0.items_count(section) |
| 1544 | } |
| 1545 | |
| 1546 | fn item(&self, ix: IndexPath) -> Option<&&'static str> { |
| 1547 | self.0.item(ix) |
| 1548 | } |
| 1549 | |
| 1550 | fn position<V>(&self, value: &V) -> Option<IndexPath> |
| 1551 | where |
| 1552 | &'static str: SearchableListItem<Value = V>, |
| 1553 | V: PartialEq, |
| 1554 | { |
| 1555 | self.0.position(value) |
| 1556 | } |
| 1557 | |
| 1558 | fn on_will_change( |
| 1559 | &mut self, |
| 1560 | _selection: &mut Vec<(IndexPath, &'static str)>, |
| 1561 | _changes: &[SearchableListChange], |
| 1562 | ) { |
| 1563 | // Leave selection unchanged — acts as a veto. |
| 1564 | } |
| 1565 | } |
| 1566 | |
| 1567 | #[gpui::test] |
| 1568 | fn test_on_will_change_veto(cx: &mut TestAppContext) { |
| 1569 | cx.update(crate::init); |
| 1570 | let cx = cx.add_empty_window(); |
| 1571 | cx.update(|window, cx| { |
| 1572 | let delegate = VetoDelegate(SearchableVec::new(vec!["Rust", "Go", "C++"])); |
| 1573 | let state = cx.new(|cx| ComboboxState::new(delegate, vec![], window, cx)); |
| 1574 | |
| 1575 | // Pre-select an item directly so we can verify veto prevents changes. |
| 1576 | state.update(cx, |s, cx| s.add_selected_index(IndexPath::new(0), cx)); |
| 1577 | assert_eq!(state.read(cx).selected_values(), &["Rust"]); |
| 1578 | |
| 1579 | // Simulate a click on index 1 via handle_item_select; on_will_change vetoes it. |
| 1580 | state.update(cx, |s, cx| { |
| 1581 | s.handle_item_select(IndexPath::new(1), window, cx); |
| 1582 | }); |
| 1583 | |
| 1584 | // Selection must remain unchanged because on_will_change left it unmodified. |
| 1585 | assert_eq!(state.read(cx).selected_values(), &["Rust"]); |
| 1586 | }); |
| 1587 | } |
| 1588 | |
| 1589 | fn left_press(position: Point<Pixels>) -> MouseDownEvent { |
| 1590 | MouseDownEvent { |
| 1591 | button: MouseButton::Left, |
| 1592 | position, |
| 1593 | modifiers: Modifiers::default(), |
| 1594 | click_count: 1, |
| 1595 | first_mouse: false, |
| 1596 | } |
| 1597 | } |
| 1598 | |
| 1599 | #[gpui::test] |
| 1600 | fn test_combo_box_dismiss_ignores_press_on_trigger(cx: &mut TestAppContext) { |
| 1601 | cx.update(crate::init); |
| 1602 | let cx = cx.add_empty_window(); |
| 1603 | let state = cx.update(|window, cx| { |
| 1604 | let items = SearchableVec::new(vec!["React", "Vue", "Angular"]); |
| 1605 | cx.new(|cx| ComboboxState::new(items, vec![], window, cx).multiple(true)) |
| 1606 | }); |
| 1607 | let collector = cx.update(|_, cx| cx.new(|cx| TestComboboxEventCollector::new(&state, cx))); |
| 1608 | |
| 1609 | cx.update(|window, cx| { |
| 1610 | state.update(cx, |state, cx| { |
| 1611 | state.state.bounds = Bounds { |
| 1612 | origin: point(px(10.), px(10.)), |
| 1613 | size: size(px(200.), px(32.)), |
| 1614 | }; |
| 1615 | state.set_open(true, cx); |
| 1616 | state.dismiss(&left_press(point(px(20.), px(20.))), window, cx); |
| 1617 | }); |
| 1618 | }); |
| 1619 | |
| 1620 | cx.update(|_, cx| { |
| 1621 | assert!( |
| 1622 | state.read(cx).state.open, |
| 1623 | "a press on the trigger must reach nested controls, so the menu stays open \ |
| 1624 | and `toggle_menu` closes it on release instead", |
| 1625 | ); |
| 1626 | assert_eq!(collector.read(cx).event_count.get(), 0); |
| 1627 | }); |
| 1628 | |
| 1629 | cx.update(|window, cx| { |
| 1630 | state.update(cx, |state, cx| { |
| 1631 | state.dismiss(&left_press(point(px(20.), px(200.))), window, cx); |
| 1632 | }); |
| 1633 | }); |
| 1634 | |
| 1635 | cx.update(|_, cx| { |
| 1636 | assert!(!state.read(cx).state.open); |
| 1637 | assert_eq!( |
| 1638 | collector.read(cx).event_count.get(), |
| 1639 | 1, |
| 1640 | "dismissing from outside the trigger emits Confirm", |
| 1641 | ); |
| 1642 | }); |
| 1643 | } |
| 1644 | |
| 1645 | // Suppress unused import warning for SearchableListState in test module. |
| 1646 | #[allow(unused)] |
| 1647 | fn _uses_state<D: SearchableListDelegate + 'static>(_: &SearchableListState<D>) |
| 1648 | where |
| 1649 | <D::Item as SearchableListItem>::Value: PartialEq + Clone, |
| 1650 | { |
| 1651 | } |
| 1652 | } |