1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, Axis, ElementId, FocusHandle, InteractiveElement, IntoElement, ParentElement,
5 Pixels, RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement, Styled,
6 Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{current_material_theme, move_roving_focus};
10use gpui_material_theme::Direction;
11
12use crate::SemanticTone;
13use crate::action::Activate;
14use crate::button_style::finite_length;
15
16use super::{Chip, ChipVariant};
17
18type SelectionChange = Rc<dyn Fn(Vec<SharedString>, &mut Window, &mut App)>;
19
20#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
22pub enum ChipGroupSelection {
23 Single,
25 SingleRequired,
27 #[default]
29 Multiple,
30}
31
32impl ChipGroupSelection {
33 pub(crate) fn next(
34 self,
35 selection: &[SharedString],
36 id: &SharedString,
37 ) -> Option<Vec<SharedString>> {
38 let contains = selection.iter().any(|value| value == id);
39 match self {
40 Self::SingleRequired if contains && selection.len() == 1 => None,
41 Self::Single if contains => Some(Vec::new()),
42 Self::Single | Self::SingleRequired => Some(vec![id.clone()]),
43 Self::Multiple if contains => Some(
44 selection
45 .iter()
46 .filter(|value| *value != id)
47 .cloned()
48 .collect(),
49 ),
50 Self::Multiple => {
51 let mut next = selection.to_vec();
52 next.push(id.clone());
53 Some(next)
54 }
55 }
56 }
57}
58
59pub struct ChipGroupItem {
61 id: SharedString,
62 label: SharedString,
63 leading: Option<AnyElement>,
64 avatar: Option<AnyElement>,
65 trailing: Option<AnyElement>,
66 disabled: bool,
67 tonal: Option<bool>,
68 elevated: Option<bool>,
69 tone: SemanticTone,
70 remove: Option<(SharedString, Activate)>,
71}
72
73impl ChipGroupItem {
74 pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
75 Self {
76 id: id.into(),
77 label: label.into(),
78 leading: None,
79 avatar: None,
80 trailing: None,
81 disabled: false,
82 tonal: None,
83 elevated: None,
84 tone: SemanticTone::Default,
85 remove: None,
86 }
87 }
88
89 pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
90 self.leading = Some(icon.into_any_element());
91 self
92 }
93
94 pub fn avatar(mut self, avatar: impl IntoElement) -> Self {
95 self.avatar = Some(avatar.into_any_element());
96 self
97 }
98
99 pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
100 self.trailing = Some(trailing.into_any_element());
101 self
102 }
103
104 pub fn disabled(mut self, disabled: bool) -> Self {
105 self.disabled = disabled;
106 self
107 }
108
109 pub fn tonal(mut self, tonal: bool) -> Self {
110 self.tonal = Some(tonal);
111 self
112 }
113
114 pub fn elevated(mut self, elevated: bool) -> Self {
115 self.elevated = Some(elevated);
116 self
117 }
118
119 pub fn tone(mut self, tone: SemanticTone) -> Self {
120 self.tone = tone;
121 self
122 }
123
124 pub fn on_remove(
126 mut self,
127 label: impl Into<SharedString>,
128 handler: impl Fn(&mut Window, &mut App) + 'static,
129 ) -> Self {
130 self.remove = Some((label.into(), Rc::new(handler)));
131 self
132 }
133}
134
135#[derive(IntoElement)]
138pub struct ChipGroup {
139 id: ElementId,
140 name: SharedString,
141 items: Vec<ChipGroupItem>,
142 selection_mode: ChipGroupSelection,
143 selected: Vec<SharedString>,
144 on_change: Option<SelectionChange>,
145 variant: ChipVariant,
146 tonal: bool,
147 elevated: bool,
148 disabled: bool,
149 scrollable: bool,
150 scroll_handle: Option<ScrollHandle>,
151 spacing: Pixels,
152 row_spacing: Pixels,
153}
154
155impl ChipGroup {
156 pub fn new(
157 id: impl Into<ElementId>,
158 name: impl Into<SharedString>,
159 items: impl IntoIterator<Item = ChipGroupItem>,
160 ) -> Self {
161 Self {
162 id: id.into(),
163 name: name.into(),
164 items: items.into_iter().collect(),
165 selection_mode: ChipGroupSelection::default(),
166 selected: Vec::new(),
167 on_change: None,
168 variant: ChipVariant::Filter,
169 tonal: false,
170 elevated: false,
171 disabled: false,
172 scrollable: false,
173 scroll_handle: None,
174 spacing: px(8.),
175 row_spacing: px(8.),
176 }
177 }
178
179 pub fn selection(
181 mut self,
182 mode: ChipGroupSelection,
183 selected: impl IntoIterator<Item = SharedString>,
184 ) -> Self {
185 self.selection_mode = mode;
186 self.selected = selected.into_iter().collect();
187 self
188 }
189
190 pub fn on_change(
192 mut self,
193 handler: impl Fn(Vec<SharedString>, &mut Window, &mut App) + 'static,
194 ) -> Self {
195 self.on_change = Some(Rc::new(handler));
196 self
197 }
198
199 pub fn single_select(
201 mut self,
202 selected: impl Into<SharedString>,
203 on_select: impl Fn(SharedString, &mut Window, &mut App) + 'static,
204 ) -> Self {
205 self.selection_mode = ChipGroupSelection::SingleRequired;
206 self.selected = vec![selected.into()];
207 self.on_change = Some(Rc::new(move |next, window, cx| {
208 if let Some(id) = next.into_iter().next() {
209 on_select(id, window, cx);
210 }
211 }));
212 self
213 }
214
215 pub fn variant(mut self, variant: ChipVariant) -> Self {
217 self.variant = variant;
218 self
219 }
220
221 pub fn tonal(mut self, tonal: bool) -> Self {
223 self.tonal = tonal;
224 self
225 }
226
227 pub fn elevated(mut self, elevated: bool) -> Self {
229 self.elevated = elevated;
230 self
231 }
232
233 pub fn disabled(mut self, disabled: bool) -> Self {
235 self.disabled = disabled;
236 self
237 }
238
239 pub fn scrollable(mut self, scrollable: bool) -> Self {
242 self.scrollable = scrollable;
243 self
244 }
245
246 pub fn scroll_handle(mut self, handle: &ScrollHandle) -> Self {
248 self.scroll_handle = Some(handle.clone());
249 self
250 }
251
252 pub fn spacing(mut self, spacing: Pixels) -> Self {
254 self.spacing = finite_length(spacing);
255 self
256 }
257
258 pub fn row_spacing(mut self, row_spacing: Pixels) -> Self {
260 self.row_spacing = finite_length(row_spacing);
261 self
262 }
263}
264
265impl RenderOnce for ChipGroup {
266 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
267 let direction = current_material_theme(window, cx).layout.direction;
268 let focus_handles: Vec<FocusHandle> = self
269 .items
270 .iter()
271 .map(|item| {
272 let scope_id = ElementId::from((self.id.clone(), "chip-focus"));
273 window.with_id(scope_id, |window| {
274 window
275 .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
276 .read(cx)
277 .clone()
278 })
279 })
280 .collect();
281
282 let group_disabled = self.disabled;
283 let group_tonal = self.tonal;
284 let group_elevated = self.elevated;
285
286 let focused_index = self
287 .items
288 .iter()
289 .zip(&focus_handles)
290 .position(|(item, focus)| {
291 !(group_disabled || item.disabled) && focus.is_focused(window)
292 });
293 let selected_index = self.items.iter().position(|item| {
294 !(group_disabled || item.disabled) && self.selected.iter().any(|id| id == &item.id)
295 });
296 let first_enabled = self
297 .items
298 .iter()
299 .position(|item| !(group_disabled || item.disabled));
300 let tab_stop = focused_index.or(selected_index).or(first_enabled);
301
302 let nav_entries: Vec<(FocusHandle, bool)> = self
303 .items
304 .iter()
305 .zip(&focus_handles)
306 .map(|(item, focus)| (focus.clone(), !(group_disabled || item.disabled)))
307 .collect();
308
309 let scroll_handle = self.scrollable.then(|| {
310 self.scroll_handle.clone().unwrap_or_else(|| {
311 window
312 .use_keyed_state((self.id.clone(), "chip-group-scroll"), cx, |_, _| {
313 ScrollHandle::new()
314 })
315 .read(cx)
316 .clone()
317 })
318 });
319
320 let selection: Rc<[SharedString]> = Rc::from(self.selected.as_slice());
321 let mode = self.selection_mode;
322 let variant = self.variant;
323 let group_id = self.id.clone();
324
325 let chips: Vec<AnyElement> = self
326 .items
327 .into_iter()
328 .enumerate()
329 .map(|(ix, item)| {
330 let focus = focus_handles[ix].clone();
331 let is_selected = selection.iter().any(|id| id == &item.id);
332 let item_id = item.id.clone();
333 let chip_id = ElementId::from((group_id.clone(), item_id.clone()));
334
335 let restore = item.remove.as_ref().and_then(|_| {
336 ((ix + 1)..nav_entries.len())
337 .find(|&next| nav_entries[next].1)
338 .or_else(|| (0..ix).rev().find(|&prev| nav_entries[prev].1))
339 .map(|target| nav_entries[target].0.clone())
340 });
341
342 let mut chip = Chip::new(chip_id, item.label)
343 .variant(variant)
344 .selected(is_selected)
345 .disabled(group_disabled || item.disabled)
346 .tonal(item.tonal.unwrap_or(group_tonal))
347 .elevated(item.elevated.unwrap_or(group_elevated))
348 .tone(item.tone)
349 .track_focus(&focus)
350 .tab_stop(Some(ix) == tab_stop);
351
352 if let Some(leading) = item.leading {
353 chip = chip.leading_icon(leading);
354 }
355 if let Some(avatar) = item.avatar {
356 chip = chip.avatar(avatar);
357 }
358 if let Some(trailing) = item.trailing {
359 chip = chip.trailing(trailing);
360 }
361 if let Some((remove_label, remove_handler)) = item.remove {
362 chip = chip.on_remove(remove_label, restore, move |window, cx| {
363 remove_handler(window, cx);
364 });
365 }
366 if let Some(on_change) = self.on_change.clone() {
367 let selection = selection.clone();
368 let target_id = item_id.clone();
369 if matches!(variant, ChipVariant::Filter | ChipVariant::Input) {
370 chip = chip.on_change(move |_, window, cx| {
371 if let Some(next) = mode.next(&selection, &target_id) {
372 on_change(next, window, cx);
373 }
374 });
375 } else {
376 chip = chip.on_activate(move |window, cx| {
377 if let Some(next) = mode.next(&selection, &target_id) {
378 on_change(next, window, cx);
379 }
380 });
381 }
382 }
383 chip.into_any_element()
384 })
385 .collect();
386
387 let mut container = div()
388 .id(self.id)
389 .test_support()
390 .role(Role::ListBox)
391 .aria_label(self.name)
392 .flex()
393 .flex_row()
394 .items_center()
395 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
396 .on_key_down(move |event, window, cx| {
397 let key = event.keystroke.key.as_str();
398 match key {
399 "home" => {
400 if let Some((focus, _)) = nav_entries.iter().find(|(_, enabled)| *enabled) {
401 focus.focus(window, cx);
402 cx.stop_propagation();
403 }
404 }
405 "end" => {
406 if let Some((focus, _)) =
407 nav_entries.iter().rev().find(|(_, enabled)| *enabled)
408 {
409 focus.focus(window, cx);
410 cx.stop_propagation();
411 }
412 }
413 "left" | "right" => {
414 let refs: Vec<(&FocusHandle, bool)> = nav_entries
415 .iter()
416 .map(|(focus, enabled)| (focus, *enabled))
417 .collect();
418 if move_roving_focus(&refs, key, Axis::Horizontal, direction, window, cx)
419 .is_some()
420 {
421 cx.stop_propagation();
422 }
423 }
424 _ => {}
425 }
426 });
427
428 if let Some(handle) = scroll_handle {
429 container = container
430 .w_full()
431 .overflow_x_scroll()
432 .track_scroll(&handle)
433 .gap(self.spacing)
434 .children(chips);
435 } else {
436 container = container
437 .flex_wrap()
438 .gap_x(self.spacing)
439 .gap_y(self.row_spacing)
440 .children(chips);
441 }
442
443 container
444 }
445}
446
447#[cfg(test)]
448mod tests {
449 use super::*;
450
451 #[test]
452 fn chip_group_selection_modes_compute_expected_transitions() {
453 let a: SharedString = "a".into();
454 let b: SharedString = "b".into();
455
456 assert_eq!(
458 ChipGroupSelection::Single.next(&[], &a),
459 Some(vec![a.clone()])
460 );
461 assert_eq!(
462 ChipGroupSelection::Single.next(std::slice::from_ref(&a), &b),
463 Some(vec![b.clone()])
464 );
465 assert_eq!(
466 ChipGroupSelection::Single.next(std::slice::from_ref(&a), &a),
467 Some(vec![])
468 );
469
470 assert_eq!(
472 ChipGroupSelection::SingleRequired.next(&[], &a),
473 Some(vec![a.clone()])
474 );
475 assert_eq!(
476 ChipGroupSelection::SingleRequired.next(std::slice::from_ref(&a), &a),
477 None
478 );
479 assert_eq!(
480 ChipGroupSelection::SingleRequired.next(std::slice::from_ref(&a), &b),
481 Some(vec![b.clone()])
482 );
483
484 assert_eq!(
486 ChipGroupSelection::Multiple.next(&[], &a),
487 Some(vec![a.clone()])
488 );
489 assert_eq!(
490 ChipGroupSelection::Multiple.next(std::slice::from_ref(&a), &b),
491 Some(vec![a.clone(), b.clone()])
492 );
493 assert_eq!(
494 ChipGroupSelection::Multiple.next(&[a.clone(), b.clone()], &a),
495 Some(vec![b])
496 );
497 }
498}