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