1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, Axis, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5 ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Window,
6 accesskit::Toggled, div, prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{InteractionSource, current_material_theme, move_roving_focus};
10use gpui_material_theme::{CornerRole, CornerShape};
11
12use crate::{SemanticTone, SwipeToDismiss, SwipeToDismissState, action::Activate};
13
14mod long_press;
15mod render;
16mod style;
17
18pub use style::{
19 ListItemAlignment, ListItemColors, ListItemElevations, ListItemPadding, ListItemShapes,
20 ListItemStateColors,
21};
22
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24pub enum ListVariant {
25 #[default]
26 Standard,
27 Segmented,
28}
29
30type ValueChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
31type SwipeConfig = Box<dyn FnOnce(SwipeToDismiss) -> SwipeToDismiss>;
32
33enum Slot {
34 Text(SharedString),
35 Custom(AnyElement),
36}
37
38impl Slot {
39 fn has_line_break(&self) -> bool {
40 matches!(self, Self::Text(value) if value.contains('\n'))
41 }
42}
43
44struct Expansion {
45 expanded: bool,
46 content: AnyElement,
47}
48
49struct SecondaryAction {
50 label: SharedString,
51 handler: Activate,
52}
53
54struct RowSwipe {
55 state: Entity<SwipeToDismissState>,
56 configure: SwipeConfig,
57}
58
59#[derive(IntoElement)]
61pub struct ListItem {
62 id: ElementId,
63 label: SharedString,
64 content: Option<AnyElement>,
65 supporting: Option<Slot>,
66 overline: Option<Slot>,
67 leading: Option<AnyElement>,
68 trailing: Option<AnyElement>,
69 activation: Option<Activate>,
70 checked_change: Option<ValueChange>,
71 expanded_change: Option<ValueChange>,
72 long_press: Option<SecondaryAction>,
73 long_press_button: Option<ElementId>,
74 expansion: Option<Expansion>,
75 swipe: Option<RowSwipe>,
76 checked: Option<Toggled>,
77 checked_role: Role,
78 checked_selects_row: bool,
79 invalid: bool,
80 footer: Option<AnyElement>,
81 aria_description: Option<SharedString>,
82 #[cfg(feature = "feedback")]
83 menu_trigger: Option<(bool, Activate)>,
84 selected: bool,
85 disabled: bool,
86 dragged: bool,
87 focus: Option<(FocusHandle, bool)>,
88 tone: SemanticTone,
89 shapes: ListItemShapes,
90 colors: ListItemColors,
91 elevations: ListItemElevations,
92 alignment: ListItemAlignment,
93 padding: Option<ListItemPadding>,
94 source: Option<Entity<InteractionSource>>,
95}
96
97impl ListItem {
98 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
99 Self {
100 id: id.into(),
101 label: label.into(),
102 content: None,
103 supporting: None,
104 overline: None,
105 leading: None,
106 trailing: None,
107 activation: None,
108 checked_change: None,
109 expanded_change: None,
110 long_press: None,
111 long_press_button: None,
112 expansion: None,
113 swipe: None,
114 checked: None,
115 checked_role: Role::CheckBox,
116 checked_selects_row: true,
117 invalid: false,
118 footer: None,
119 aria_description: None,
120 #[cfg(feature = "feedback")]
121 menu_trigger: None,
122 selected: false,
123 disabled: false,
124 dragged: false,
125 focus: None,
126 tone: SemanticTone::Default,
127 shapes: ListItemShapes::default(),
128 colors: ListItemColors::default(),
129 elevations: ListItemElevations::default(),
130 alignment: ListItemAlignment::Auto,
131 padding: None,
132 source: None,
133 }
134 }
135
136 pub fn content(mut self, content: impl IntoElement) -> Self {
138 self.content = Some(content.into_any_element());
139 self
140 }
141
142 pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
143 self.supporting = Some(Slot::Text(text.into()));
144 self
145 }
146
147 pub fn supporting_content(mut self, content: impl IntoElement) -> Self {
148 self.supporting = Some(Slot::Custom(content.into_any_element()));
149 self
150 }
151
152 pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
153 self.overline = Some(Slot::Text(text.into()));
154 self
155 }
156
157 pub fn overline_content(mut self, content: impl IntoElement) -> Self {
158 self.overline = Some(Slot::Custom(content.into_any_element()));
159 self
160 }
161
162 pub fn leading(mut self, leading: impl IntoElement) -> Self {
163 self.leading = Some(leading.into_any_element());
164 self
165 }
166
167 pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
168 self.trailing = Some(trailing.into_any_element());
169 self
170 }
171
172 pub fn selected(mut self, selected: bool) -> Self {
173 self.selected = selected;
174 self
175 }
176
177 pub fn checked(mut self, checked: bool) -> Self {
179 self.checked = Some(if checked {
180 Toggled::True
181 } else {
182 Toggled::False
183 });
184 self
185 }
186
187 pub fn on_checked_change(
189 mut self,
190 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
191 ) -> Self {
192 self.checked.get_or_insert(Toggled::False);
193 self.checked_change = Some(Rc::new(handler));
194 self
195 }
196
197 pub fn expanded_content(mut self, expanded: bool, content: impl IntoElement) -> Self {
199 self.expansion = Some(Expansion {
200 expanded,
201 content: content.into_any_element(),
202 });
203 self
204 }
205
206 pub fn on_expanded_change(
207 mut self,
208 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
209 ) -> Self {
210 self.expanded_change = Some(Rc::new(handler));
211 self
212 }
213
214 pub fn on_long_press(
217 mut self,
218 label: impl Into<SharedString>,
219 handler: impl Fn(&mut Window, &mut App) + 'static,
220 ) -> Self {
221 self.long_press = Some(SecondaryAction {
222 label: label.into(),
223 handler: Rc::new(handler),
224 });
225 self
226 }
227
228 pub fn long_press_button(mut self, id: impl Into<ElementId>) -> Self {
230 self.long_press_button = Some(id.into());
231 self
232 }
233
234 pub fn swipe_to_dismiss(
237 mut self,
238 state: &Entity<SwipeToDismissState>,
239 configure: impl FnOnce(SwipeToDismiss) -> SwipeToDismiss + 'static,
240 ) -> Self {
241 self.swipe = Some(RowSwipe {
242 state: state.clone(),
243 configure: Box::new(configure),
244 });
245 self
246 }
247
248 pub fn disabled(mut self, disabled: bool) -> Self {
249 self.disabled = disabled;
250 self
251 }
252
253 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
254 self.activation = Some(Rc::new(handler));
255 self
256 }
257
258 pub fn shapes(mut self, shapes: ListItemShapes) -> Self {
259 self.shapes = shapes;
260 self
261 }
262
263 pub fn tone(mut self, tone: SemanticTone) -> Self {
266 self.tone = tone;
267 self
268 }
269
270 pub fn colors(mut self, colors: ListItemColors) -> Self {
271 self.colors = colors;
272 self
273 }
274
275 pub fn elevations(mut self, elevations: ListItemElevations) -> Self {
276 self.elevations = elevations;
277 self
278 }
279
280 pub fn vertical_alignment(mut self, alignment: ListItemAlignment) -> Self {
281 self.alignment = alignment;
282 self
283 }
284
285 pub fn content_padding(mut self, padding: ListItemPadding) -> Self {
286 self.padding = Some(padding);
287 self
288 }
289
290 pub fn dragged(mut self, dragged: bool) -> Self {
292 self.dragged = dragged;
293 self
294 }
295
296 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
297 self.source = Some(source.clone());
298 self
299 }
300
301 pub fn track_focus(mut self, focus: &FocusHandle, tab_stop: bool) -> Self {
304 self.focus = Some((focus.clone(), tab_stop));
305 self
306 }
307
308 #[cfg(feature = "selection")]
309 pub(crate) fn checked_role(mut self, role: Role) -> Self {
310 self.checked_role = role;
311 self
312 }
313
314 #[cfg(feature = "selection")]
315 pub(crate) fn checked_toggled(mut self, state: Toggled) -> Self {
316 self.checked = Some(state);
317 self
318 }
319
320 #[cfg(feature = "selection")]
321 pub(crate) fn checked_selects_row(mut self, selects: bool) -> Self {
322 self.checked_selects_row = selects;
323 self
324 }
325
326 #[cfg(feature = "selection")]
327 pub(crate) fn invalid(mut self, invalid: bool) -> Self {
328 self.invalid = invalid;
329 self
330 }
331
332 #[cfg(feature = "selection")]
333 pub(crate) fn footer(mut self, footer: impl IntoElement) -> Self {
334 self.footer = Some(footer.into_any_element());
335 self
336 }
337
338 #[cfg(feature = "feedback")]
339 pub(crate) fn menu_trigger(mut self, open: bool, a11y_toggle: Activate) -> Self {
340 self.menu_trigger = Some((open, a11y_toggle));
341 self
342 }
343
344 #[cfg(feature = "feedback")]
345 pub(crate) fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
346 self.aria_description = Some(description.into());
347 self
348 }
349
350 pub(crate) fn custom_focus(&self) -> Option<FocusHandle> {
351 self.focus.as_ref().map(|(focus, _)| focus.clone())
352 }
353
354 pub(crate) fn id(&self) -> &ElementId {
355 &self.id
356 }
357
358 pub(crate) fn is_selected(&self) -> bool {
359 self.selected
360 }
361
362 fn has_primary_action(&self) -> bool {
363 self.activation.is_some()
364 || self.checked_change.is_some()
365 || self.expansion.is_some() && self.expanded_change.is_some()
366 }
367
368 fn has_menu_trigger(&self) -> bool {
369 #[cfg(feature = "feedback")]
370 {
371 self.menu_trigger.is_some()
372 }
373 #[cfg(not(feature = "feedback"))]
374 {
375 false
376 }
377 }
378
379 pub(crate) fn takes_focus(&self, cx: &App) -> bool {
380 !self.disabled
381 && (self.has_primary_action() || self.has_menu_trigger() || self.long_press.is_some())
382 && self
383 .swipe
384 .as_ref()
385 .is_none_or(|swipe| swipe.state.read(cx).shows_foreground())
386 }
387
388 fn primary_action(&self) -> Option<Activate> {
389 if !self.has_primary_action() {
390 return None;
391 }
392 let action = self.activation.clone();
393 let check = self.checked.zip(self.checked_change.clone());
394 let expansion = self
395 .expansion
396 .as_ref()
397 .map(|expansion| expansion.expanded)
398 .zip(self.expanded_change.clone());
399 Some(Rc::new(move |window, cx| {
400 if let Some((checked, change)) = &check {
401 change(*checked != Toggled::True, window, cx);
402 }
403 if let Some((expanded, change)) = &expansion {
404 change(!expanded, window, cx);
405 }
406 if let Some(action) = &action {
407 action(window, cx);
408 }
409 }))
410 }
411
412 pub(crate) fn row(
413 self,
414 resting: CornerShape,
415 selected_shape: CornerShape,
416 focus: Option<(FocusHandle, bool)>,
417 window: &mut Window,
418 cx: &mut App,
419 ) -> AnyElement {
420 window.with_element_namespace((self.id.clone(), "material-list-row"), |window| {
421 self.render_row(resting, selected_shape, focus, window, cx)
422 })
423 }
424}
425
426impl RenderOnce for ListItem {
427 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
428 let focus = self.focus.clone();
429 self.row(
430 CornerRole::None.shape(),
431 CornerRole::None.shape(),
432 focus,
433 window,
434 cx,
435 )
436 }
437}
438
439#[derive(IntoElement)]
442pub struct List {
443 id: ElementId,
444 items: Vec<ListItem>,
445 variant: ListVariant,
446 accessible_label: Option<SharedString>,
447}
448
449impl List {
450 pub fn new(id: impl Into<ElementId>) -> Self {
451 Self {
452 id: id.into(),
453 items: Vec::new(),
454 variant: ListVariant::default(),
455 accessible_label: None,
456 }
457 }
458
459 pub fn variant(mut self, variant: ListVariant) -> Self {
460 self.variant = variant;
461 self
462 }
463
464 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
466 self.accessible_label = Some(label.into());
467 self
468 }
469
470 pub fn item(mut self, item: ListItem) -> Self {
472 self.items.push(item);
473 self
474 }
475
476 pub fn items(mut self, items: impl IntoIterator<Item = ListItem>) -> Self {
477 self.items.extend(items);
478 self
479 }
480}
481
482impl RenderOnce for List {
483 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
484 window.with_element_namespace((self.id.clone(), "material-list"), |window| {
485 let last = self.items.len().saturating_sub(1);
486 let direction = current_material_theme(window, cx).layout.direction;
487 let focus: Vec<_> = self
488 .items
489 .iter()
490 .map(|item| {
491 item.custom_focus().unwrap_or_else(|| {
492 window
493 .use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| {
494 cx.focus_handle()
495 })
496 .read(cx)
497 .clone()
498 })
499 })
500 .collect();
501 let enabled: Vec<_> = self.items.iter().map(|item| item.takes_focus(cx)).collect();
502 let tab_stop = focus
503 .iter()
504 .enumerate()
505 .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
506 .or_else(|| {
507 self.items
508 .iter()
509 .enumerate()
510 .position(|(ix, item)| enabled[ix] && item.selected)
511 })
512 .or_else(|| enabled.iter().position(|enabled| *enabled));
513 let navigation = focus.clone();
514 div()
515 .id(self.id)
516 .role(Role::List)
517 .when_some(self.accessible_label, |list, label| list.aria_label(label))
518 .test_support()
519 .flex()
520 .flex_col()
521 .w_full()
522 .on_key_down(move |event, window, cx| {
523 if !navigation.iter().any(|focus| focus.is_focused(window)) {
525 return;
526 }
527 let items: Vec<_> = navigation
528 .iter()
529 .zip(&enabled)
530 .map(|(focus, enabled)| (focus, *enabled))
531 .collect();
532 if move_roving_focus(
533 &items,
534 &event.keystroke.key,
535 Axis::Vertical,
536 direction,
537 window,
538 cx,
539 )
540 .is_some()
541 {
542 cx.stop_propagation();
543 window.refresh();
544 }
545 })
546 .when(self.variant == ListVariant::Segmented, |list| {
547 list.gap(px(2.))
548 })
549 .children(self.items.into_iter().zip(focus).enumerate().map(
550 |(ix, (item, focus))| {
551 let (resting, selected) = match self.variant {
552 ListVariant::Standard => {
553 (CornerRole::None.shape(), CornerRole::None.shape())
554 }
555 ListVariant::Segmented => {
556 let top = if ix == 0 { 16. } else { 4. };
557 let bottom = if ix == last { 16. } else { 4. };
558 (
559 CornerShape::Radii([top, top, bottom, bottom]),
560 CornerRole::Large.shape(),
561 )
562 }
563 };
564 item.row(
565 resting,
566 selected,
567 Some((focus, Some(ix) == tab_stop)),
568 window,
569 cx,
570 )
571 },
572 ))
573 })
574 }
575}