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: bool,
68 elevated: 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: false,
83 elevated: false,
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 = tonal;
111 self
112 }
113
114 pub fn elevated(mut self, elevated: bool) -> Self {
115 self.elevated = 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 scrollable: bool,
147 scroll_handle: Option<ScrollHandle>,
148 spacing: Pixels,
149 row_spacing: Pixels,
150}
151
152impl ChipGroup {
153 pub fn new(
154 id: impl Into<ElementId>,
155 name: impl Into<SharedString>,
156 items: impl IntoIterator<Item = ChipGroupItem>,
157 ) -> Self {
158 Self {
159 id: id.into(),
160 name: name.into(),
161 items: items.into_iter().collect(),
162 selection_mode: ChipGroupSelection::default(),
163 selected: Vec::new(),
164 on_change: None,
165 variant: ChipVariant::Filter,
166 scrollable: false,
167 scroll_handle: None,
168 spacing: px(8.),
169 row_spacing: px(8.),
170 }
171 }
172
173 pub fn selection(
175 mut self,
176 mode: ChipGroupSelection,
177 selected: impl IntoIterator<Item = SharedString>,
178 ) -> Self {
179 self.selection_mode = mode;
180 self.selected = selected.into_iter().collect();
181 self
182 }
183
184 pub fn on_change(
186 mut self,
187 handler: impl Fn(Vec<SharedString>, &mut Window, &mut App) + 'static,
188 ) -> Self {
189 self.on_change = Some(Rc::new(handler));
190 self
191 }
192
193 pub fn single_select(
195 mut self,
196 selected: impl Into<SharedString>,
197 on_select: impl Fn(SharedString, &mut Window, &mut App) + 'static,
198 ) -> Self {
199 self.selection_mode = ChipGroupSelection::SingleRequired;
200 self.selected = vec![selected.into()];
201 self.on_change = Some(Rc::new(move |next, window, cx| {
202 if let Some(id) = next.into_iter().next() {
203 on_select(id, window, cx);
204 }
205 }));
206 self
207 }
208
209 pub fn variant(mut self, variant: ChipVariant) -> Self {
211 self.variant = variant;
212 self
213 }
214
215 pub fn scrollable(mut self, scrollable: bool) -> Self {
218 self.scrollable = scrollable;
219 self
220 }
221
222 pub fn scroll_handle(mut self, handle: &ScrollHandle) -> Self {
224 self.scroll_handle = Some(handle.clone());
225 self
226 }
227
228 pub fn spacing(mut self, spacing: Pixels) -> Self {
230 self.spacing = finite_length(spacing);
231 self
232 }
233
234 pub fn row_spacing(mut self, row_spacing: Pixels) -> Self {
236 self.row_spacing = finite_length(row_spacing);
237 self
238 }
239}
240
241impl RenderOnce for ChipGroup {
242 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
243 let direction = current_material_theme(window, cx).layout.direction;
244 let focus_handles: Vec<FocusHandle> = self
245 .items
246 .iter()
247 .map(|item| {
248 let scope_id = ElementId::from((self.id.clone(), "chip-focus"));
249 window.with_id(scope_id, |window| {
250 window
251 .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
252 .read(cx)
253 .clone()
254 })
255 })
256 .collect();
257
258 let focused_index = self
259 .items
260 .iter()
261 .zip(&focus_handles)
262 .position(|(item, focus)| !item.disabled && focus.is_focused(window));
263 let selected_index = self
264 .items
265 .iter()
266 .position(|item| !item.disabled && self.selected.iter().any(|id| id == &item.id));
267 let first_enabled = self.items.iter().position(|item| !item.disabled);
268 let tab_stop = focused_index.or(selected_index).or(first_enabled);
269
270 let nav_entries: Vec<(FocusHandle, bool)> = self
271 .items
272 .iter()
273 .zip(&focus_handles)
274 .map(|(item, focus)| (focus.clone(), !item.disabled))
275 .collect();
276
277 let scroll_handle = self.scrollable.then(|| {
278 self.scroll_handle.clone().unwrap_or_else(|| {
279 window
280 .use_keyed_state((self.id.clone(), "chip-group-scroll"), cx, |_, _| {
281 ScrollHandle::new()
282 })
283 .read(cx)
284 .clone()
285 })
286 });
287
288 let selection: Rc<[SharedString]> = Rc::from(self.selected.as_slice());
289 let mode = self.selection_mode;
290 let variant = self.variant;
291 let group_id = self.id.clone();
292
293 let chips: Vec<AnyElement> = self
294 .items
295 .into_iter()
296 .enumerate()
297 .map(|(ix, item)| {
298 let focus = focus_handles[ix].clone();
299 let is_selected = selection.iter().any(|id| id == &item.id);
300 let item_id = item.id.clone();
301 let chip_id = ElementId::from((group_id.clone(), item_id.clone()));
302
303 let restore = item.remove.as_ref().and_then(|_| {
304 ((ix + 1)..nav_entries.len())
305 .find(|&next| nav_entries[next].1)
306 .or_else(|| (0..ix).rev().find(|&prev| nav_entries[prev].1))
307 .map(|target| nav_entries[target].0.clone())
308 });
309
310 let mut chip = Chip::new(chip_id, item.label)
311 .variant(variant)
312 .selected(is_selected)
313 .disabled(item.disabled)
314 .tonal(item.tonal)
315 .elevated(item.elevated)
316 .tone(item.tone)
317 .track_focus(&focus)
318 .tab_stop(Some(ix) == tab_stop);
319
320 if let Some(leading) = item.leading {
321 chip = chip.leading_icon(leading);
322 }
323 if let Some(avatar) = item.avatar {
324 chip = chip.avatar(avatar);
325 }
326 if let Some(trailing) = item.trailing {
327 chip = chip.trailing(trailing);
328 }
329 if let Some((remove_label, remove_handler)) = item.remove {
330 chip = chip.on_remove(remove_label, restore, move |window, cx| {
331 remove_handler(window, cx);
332 });
333 }
334 if let Some(on_change) = self.on_change.clone() {
335 let selection = selection.clone();
336 let target_id = item_id.clone();
337 if matches!(variant, ChipVariant::Filter | ChipVariant::Input) {
338 chip = chip.on_change(move |_, window, cx| {
339 if let Some(next) = mode.next(&selection, &target_id) {
340 on_change(next, window, cx);
341 }
342 });
343 } else {
344 chip = chip.on_activate(move |window, cx| {
345 if let Some(next) = mode.next(&selection, &target_id) {
346 on_change(next, window, cx);
347 }
348 });
349 }
350 }
351 chip.into_any_element()
352 })
353 .collect();
354
355 let mut container = div()
356 .id(self.id)
357 .test_support()
358 .role(Role::ListBox)
359 .aria_label(self.name)
360 .flex()
361 .flex_row()
362 .items_center()
363 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
364 .on_key_down(move |event, window, cx| {
365 let key = event.keystroke.key.as_str();
366 match key {
367 "home" => {
368 if let Some((focus, _)) = nav_entries.iter().find(|(_, enabled)| *enabled) {
369 focus.focus(window, cx);
370 cx.stop_propagation();
371 }
372 }
373 "end" => {
374 if let Some((focus, _)) =
375 nav_entries.iter().rev().find(|(_, enabled)| *enabled)
376 {
377 focus.focus(window, cx);
378 cx.stop_propagation();
379 }
380 }
381 "left" | "right" => {
382 let refs: Vec<(&FocusHandle, bool)> = nav_entries
383 .iter()
384 .map(|(focus, enabled)| (focus, *enabled))
385 .collect();
386 if move_roving_focus(&refs, key, Axis::Horizontal, direction, window, cx)
387 .is_some()
388 {
389 cx.stop_propagation();
390 }
391 }
392 _ => {}
393 }
394 });
395
396 if let Some(handle) = scroll_handle {
397 container = container
398 .w_full()
399 .overflow_x_scroll()
400 .track_scroll(&handle)
401 .gap(self.spacing)
402 .children(chips);
403 } else {
404 container = container
405 .flex_wrap()
406 .gap_x(self.spacing)
407 .gap_y(self.row_spacing)
408 .children(chips);
409 }
410
411 container
412 }
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418
419 #[test]
420 fn chip_group_selection_modes_compute_expected_transitions() {
421 let a: SharedString = "a".into();
422 let b: SharedString = "b".into();
423
424 assert_eq!(
426 ChipGroupSelection::Single.next(&[], &a),
427 Some(vec![a.clone()])
428 );
429 assert_eq!(
430 ChipGroupSelection::Single.next(std::slice::from_ref(&a), &b),
431 Some(vec![b.clone()])
432 );
433 assert_eq!(
434 ChipGroupSelection::Single.next(std::slice::from_ref(&a), &a),
435 Some(vec![])
436 );
437
438 assert_eq!(
440 ChipGroupSelection::SingleRequired.next(&[], &a),
441 Some(vec![a.clone()])
442 );
443 assert_eq!(
444 ChipGroupSelection::SingleRequired.next(std::slice::from_ref(&a), &a),
445 None
446 );
447 assert_eq!(
448 ChipGroupSelection::SingleRequired.next(std::slice::from_ref(&a), &b),
449 Some(vec![b.clone()])
450 );
451
452 assert_eq!(
454 ChipGroupSelection::Multiple.next(&[], &a),
455 Some(vec![a.clone()])
456 );
457 assert_eq!(
458 ChipGroupSelection::Multiple.next(std::slice::from_ref(&a), &b),
459 Some(vec![a.clone(), b.clone()])
460 );
461 assert_eq!(
462 ChipGroupSelection::Multiple.next(&[a.clone(), b.clone()], &a),
463 Some(vec![b])
464 );
465 }
466}