1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, Axis, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5 KeyDownEvent, ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement,
6 Styled, Window, 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, Direction, LogicalEdges};
11
12use crate::{
13 SemanticTone, SwipeToDismiss, SwipeToDismissState, action::Activate,
14 control_style::ControlElevations,
15};
16
17mod long_press;
18mod render;
19mod row_wrapper;
20mod style;
21mod surface;
22
23pub use style::{ListItemAlignment, ListItemColors, ListItemShapes, ListItemStateColors};
24
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
27pub enum ListVariant {
28 #[default]
30 Standard,
31 Segmented,
33}
34
35pub(crate) fn segmented_corners(
36 variant: ListVariant,
37 ix: usize,
38 last: usize,
39) -> (CornerShape, CornerShape) {
40 match variant {
41 ListVariant::Standard => (CornerRole::None.shape(), CornerRole::None.shape()),
42 ListVariant::Segmented => {
43 let top = if ix == 0 { 16. } else { 4. };
44 let bottom = if ix == last { 16. } else { 4. };
45 (
46 CornerShape::Radii([top, top, bottom, bottom]),
47 CornerRole::Large.shape(),
48 )
49 }
50 }
51}
52
53pub(crate) fn compute_roving_tab_stop(
54 focus: &[FocusHandle],
55 enabled: &[bool],
56 selected: &[bool],
57 window: &Window,
58) -> Option<usize> {
59 focus
60 .iter()
61 .enumerate()
62 .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
63 .or_else(|| {
64 selected
65 .iter()
66 .enumerate()
67 .position(|(ix, is_selected)| enabled[ix] && *is_selected)
68 })
69 .or_else(|| enabled.iter().position(|enabled| *enabled))
70}
71
72pub(crate) fn handle_vertical_roving_key(
73 navigation: &[FocusHandle],
74 enabled: &[bool],
75 event: &KeyDownEvent,
76 direction: Direction,
77 window: &mut Window,
78 cx: &mut App,
79) -> bool {
80 if event.keystroke.modifiers.modified() {
81 return false;
82 }
83 if !navigation.iter().any(|focus| focus.is_focused(window)) {
85 return false;
86 }
87 let items: Vec<_> = navigation
88 .iter()
89 .zip(enabled)
90 .map(|(focus, enabled)| (focus, *enabled))
91 .collect();
92 if move_roving_focus(
93 &items,
94 &event.keystroke.key,
95 Axis::Vertical,
96 direction,
97 window,
98 cx,
99 )
100 .is_some()
101 {
102 cx.stop_propagation();
103 window.refresh();
104 true
105 } else {
106 false
107 }
108}
109
110type ValueChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
111type SwipeConfig = Box<dyn FnOnce(SwipeToDismiss) -> SwipeToDismiss>;
112
113enum Slot {
114 Text(SharedString),
115 Custom(AnyElement),
116}
117
118impl Slot {
119 fn has_line_break(&self) -> bool {
120 matches!(self, Self::Text(value) if value.contains('\n'))
121 }
122}
123
124struct Expansion {
125 expanded: bool,
126 content: AnyElement,
127}
128
129struct SecondaryAction {
130 label: SharedString,
131 handler: Activate,
132}
133
134struct RowSwipe {
135 state: Entity<SwipeToDismissState>,
136 configure: SwipeConfig,
137}
138
139#[derive(IntoElement)]
141pub struct ListItem {
142 id: ElementId,
143 label: SharedString,
144 content: Option<AnyElement>,
145 supporting: Option<Slot>,
146 overline: Option<Slot>,
147 leading: Option<AnyElement>,
148 trailing: Option<AnyElement>,
149 activation: Option<Activate>,
150 checked_change: Option<ValueChange>,
151 expanded_change: Option<ValueChange>,
152 long_press: Option<SecondaryAction>,
153 long_press_button: Option<ElementId>,
154 expansion: Option<Expansion>,
155 swipe: Option<RowSwipe>,
156 checked: Option<Toggled>,
157 checked_role: Role,
158 checked_selects_row: bool,
159 invalid: bool,
160 footer: Option<AnyElement>,
161 aria_description: Option<SharedString>,
162 #[cfg(feature = "settings-tiles")]
163 menu_trigger: Option<(bool, Activate)>,
164 selected: bool,
165 selectable: bool,
166 disabled: bool,
167 dragged: bool,
168 focus: Option<FocusHandle>,
169 tab_stop: Option<bool>,
170 tone: SemanticTone,
171 shapes: ListItemShapes,
172 colors: ListItemColors,
173 elevations: ControlElevations,
174 alignment: ListItemAlignment,
175 padding: Option<LogicalEdges>,
176 source: Option<Entity<InteractionSource>>,
177}
178
179impl ListItem {
180 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
182 Self {
183 id: id.into(),
184 label: label.into(),
185 content: None,
186 supporting: None,
187 overline: None,
188 leading: None,
189 trailing: None,
190 activation: None,
191 checked_change: None,
192 expanded_change: None,
193 long_press: None,
194 long_press_button: None,
195 expansion: None,
196 swipe: None,
197 checked: None,
198 checked_role: Role::CheckBox,
199 checked_selects_row: true,
200 invalid: false,
201 footer: None,
202 aria_description: None,
203 #[cfg(feature = "settings-tiles")]
204 menu_trigger: None,
205 selected: false,
206 selectable: false,
207 disabled: false,
208 dragged: false,
209 focus: None,
210 tab_stop: None,
211 tone: SemanticTone::Default,
212 shapes: ListItemShapes::default(),
213 colors: ListItemColors::default(),
214 elevations: ControlElevations::default(),
215 alignment: ListItemAlignment::Auto,
216 padding: None,
217 source: None,
218 }
219 }
220
221 pub fn content(mut self, content: impl IntoElement) -> Self {
223 self.content = Some(content.into_any_element());
224 self
225 }
226
227 pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
229 self.supporting = Some(Slot::Text(text.into()));
230 self
231 }
232
233 pub fn supporting_content(mut self, content: impl IntoElement) -> Self {
235 self.supporting = Some(Slot::Custom(content.into_any_element()));
236 self
237 }
238
239 pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
241 self.overline = Some(Slot::Text(text.into()));
242 self
243 }
244
245 pub fn overline_content(mut self, content: impl IntoElement) -> Self {
247 self.overline = Some(Slot::Custom(content.into_any_element()));
248 self
249 }
250
251 pub fn leading(mut self, leading: impl IntoElement) -> Self {
253 self.leading = Some(leading.into_any_element());
254 self
255 }
256
257 pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
259 self.trailing = Some(trailing.into_any_element());
260 self
261 }
262
263 pub fn selected(mut self, selected: bool) -> Self {
265 self.selected = selected;
266 self.selectable = true;
267 self
268 }
269
270 pub fn checked(mut self, checked: bool) -> Self {
272 self.checked = Some(if checked {
273 Toggled::True
274 } else {
275 Toggled::False
276 });
277 self
278 }
279
280 pub fn on_checked_change(
282 mut self,
283 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
284 ) -> Self {
285 self.checked.get_or_insert(Toggled::False);
286 self.checked_change = Some(Rc::new(handler));
287 self
288 }
289
290 pub fn expanded_content(mut self, expanded: bool, content: impl IntoElement) -> Self {
292 self.expansion = Some(Expansion {
293 expanded,
294 content: content.into_any_element(),
295 });
296 self
297 }
298
299 pub fn on_expanded_change(
301 mut self,
302 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
303 ) -> Self {
304 self.expanded_change = Some(Rc::new(handler));
305 self
306 }
307
308 pub fn on_long_press(
311 mut self,
312 label: impl Into<SharedString>,
313 handler: impl Fn(&mut Window, &mut App) + 'static,
314 ) -> Self {
315 self.long_press = Some(SecondaryAction {
316 label: label.into(),
317 handler: Rc::new(handler),
318 });
319 self
320 }
321
322 pub fn long_press_button(mut self, id: impl Into<ElementId>) -> Self {
324 self.long_press_button = Some(id.into());
325 self
326 }
327
328 pub fn swipe_to_dismiss(
331 mut self,
332 state: &Entity<SwipeToDismissState>,
333 configure: impl FnOnce(SwipeToDismiss) -> SwipeToDismiss + 'static,
334 ) -> Self {
335 self.swipe = Some(RowSwipe {
336 state: state.clone(),
337 configure: Box::new(configure),
338 });
339 self
340 }
341
342 pub fn disabled(mut self, disabled: bool) -> Self {
344 self.disabled = disabled;
345 self
346 }
347
348 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
350 self.activation = Some(Rc::new(handler));
351 self
352 }
353
354 pub fn shapes(mut self, shapes: ListItemShapes) -> Self {
356 self.shapes = shapes;
357 self
358 }
359
360 pub fn tone(mut self, tone: SemanticTone) -> Self {
363 self.tone = tone;
364 self
365 }
366
367 pub fn colors(mut self, colors: ListItemColors) -> Self {
369 self.colors = colors;
370 self
371 }
372
373 pub fn elevations(mut self, elevations: ControlElevations) -> Self {
375 self.elevations = elevations;
376 self
377 }
378
379 pub fn vertical_alignment(mut self, alignment: ListItemAlignment) -> Self {
381 self.alignment = alignment;
382 self
383 }
384
385 pub fn content_padding(mut self, padding: LogicalEdges) -> Self {
387 self.padding = Some(padding.sanitize());
388 self
389 }
390
391 pub fn dragged(mut self, dragged: bool) -> Self {
393 self.dragged = dragged;
394 self
395 }
396
397 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
399 self.source = Some(source.clone());
400 self
401 }
402
403 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
405 self.focus = Some(focus.clone());
406 self
407 }
408
409 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
412 self.tab_stop = Some(tab_stop);
413 self
414 }
415
416 #[cfg(feature = "settings-tiles")]
417 pub(crate) fn checked_role(mut self, role: Role) -> Self {
418 self.checked_role = role;
419 self
420 }
421
422 #[cfg(feature = "settings-tiles")]
423 pub(crate) fn checked_toggled(mut self, state: Toggled) -> Self {
424 self.checked = Some(state);
425 self
426 }
427
428 #[cfg(feature = "settings-tiles")]
429 pub(crate) fn checked_selects_row(mut self, selects: bool) -> Self {
430 self.checked_selects_row = selects;
431 self
432 }
433
434 #[cfg(feature = "settings-tiles")]
435 pub(crate) fn invalid(mut self, invalid: bool) -> Self {
436 self.invalid = invalid;
437 self
438 }
439
440 #[cfg(feature = "settings-tiles")]
441 pub(crate) fn footer(mut self, footer: impl IntoElement) -> Self {
442 self.footer = Some(footer.into_any_element());
443 self
444 }
445
446 #[cfg(feature = "settings-tiles")]
447 pub(crate) fn menu_trigger(mut self, open: bool, a11y_toggle: Activate) -> Self {
448 self.menu_trigger = Some((open, a11y_toggle));
449 self
450 }
451
452 #[cfg(feature = "settings-tiles")]
453 pub(crate) fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
454 self.aria_description = Some(description.into());
455 self
456 }
457
458 pub(crate) fn custom_focus(&self) -> Option<FocusHandle> {
459 self.focus.clone()
460 }
461
462 pub(crate) fn id(&self) -> &ElementId {
463 &self.id
464 }
465
466 pub(crate) fn is_selected(&self) -> bool {
467 self.selected
468 }
469
470 fn has_primary_action(&self) -> bool {
471 self.activation.is_some()
472 || self.checked_change.is_some()
473 || self.expansion.is_some() && self.expanded_change.is_some()
474 }
475
476 fn has_menu_trigger(&self) -> bool {
477 #[cfg(feature = "settings-tiles")]
478 {
479 self.menu_trigger.is_some()
480 }
481 #[cfg(not(feature = "settings-tiles"))]
482 {
483 false
484 }
485 }
486
487 pub(crate) fn takes_focus(&self, cx: &App) -> bool {
488 !self.disabled
489 && (self.has_primary_action() || self.has_menu_trigger() || self.long_press.is_some())
490 && self
491 .swipe
492 .as_ref()
493 .is_none_or(|swipe| swipe.state.read(cx).shows_foreground())
494 }
495
496 fn primary_action(&self) -> Option<Activate> {
497 if !self.has_primary_action() {
498 return None;
499 }
500 let action = self.activation.clone();
501 let check = self.checked.zip(self.checked_change.clone());
502 let expansion = self
503 .expansion
504 .as_ref()
505 .map(|expansion| expansion.expanded)
506 .zip(self.expanded_change.clone());
507 Some(Rc::new(move |window, cx| {
508 if let Some((checked, change)) = &check {
509 change(*checked != Toggled::True, window, cx);
510 }
511 if let Some((expanded, change)) = &expansion {
512 change(!expanded, window, cx);
513 }
514 if let Some(action) = &action {
515 action(window, cx);
516 }
517 }))
518 }
519
520 pub(crate) fn row(
521 self,
522 resting: CornerShape,
523 selected_shape: CornerShape,
524 focus: Option<(FocusHandle, bool)>,
525 window: &mut Window,
526 cx: &mut App,
527 ) -> AnyElement {
528 window.with_element_namespace((self.id.clone(), "material-list-row"), |window| {
529 self.render_row(resting, selected_shape, focus, window, cx)
530 })
531 }
532}
533
534impl RenderOnce for ListItem {
535 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
536 self.row(
537 CornerRole::None.shape(),
538 CornerRole::None.shape(),
539 None,
540 window,
541 cx,
542 )
543 }
544}
545
546#[derive(IntoElement)]
549pub struct List {
550 id: ElementId,
551 items: Vec<ListItem>,
552 variant: ListVariant,
553 accessible_label: Option<SharedString>,
554}
555
556impl List {
557 pub fn new(id: impl Into<ElementId>) -> Self {
559 Self {
560 id: id.into(),
561 items: Vec::new(),
562 variant: ListVariant::default(),
563 accessible_label: None,
564 }
565 }
566
567 pub fn variant(mut self, variant: ListVariant) -> Self {
569 self.variant = variant;
570 self
571 }
572
573 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
575 self.accessible_label = Some(label.into());
576 self
577 }
578
579 pub fn item(mut self, item: ListItem) -> Self {
581 self.items.push(item);
582 self
583 }
584
585 pub fn items(mut self, items: impl IntoIterator<Item = ListItem>) -> Self {
587 self.items.extend(items);
588 self
589 }
590}
591
592impl RenderOnce for List {
593 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
594 window.with_element_namespace((self.id.clone(), "material-list"), |window| {
595 let last = self.items.len().saturating_sub(1);
596 let direction = current_material_theme(window, cx).layout.direction;
597 let focus: Vec<_> = self
598 .items
599 .iter()
600 .map(|item| {
601 item.custom_focus().unwrap_or_else(|| {
602 window
603 .use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| {
604 cx.focus_handle()
605 })
606 .read(cx)
607 .clone()
608 })
609 })
610 .collect();
611 let enabled: Vec<_> = self.items.iter().map(|item| item.takes_focus(cx)).collect();
612 let selected: Vec<_> = self.items.iter().map(|item| item.selected).collect();
613 let tab_stop = compute_roving_tab_stop(&focus, &enabled, &selected, window);
614 let navigation = focus.clone();
615 div()
616 .id(self.id)
617 .role(Role::List)
618 .when_some(self.accessible_label, |list, label| list.aria_label(label))
619 .test_support()
620 .flex()
621 .flex_col()
622 .w_full()
623 .on_key_down(move |event, window, cx| {
624 handle_vertical_roving_key(&navigation, &enabled, event, direction, window, cx);
625 })
626 .when(self.variant == ListVariant::Segmented, |list| {
627 list.gap(px(2.))
628 })
629 .children(self.items.into_iter().zip(focus).enumerate().map(
630 |(ix, (item, focus))| {
631 let (resting, selected) = segmented_corners(self.variant, ix, last);
632 item.row(
633 resting,
634 selected,
635 Some((focus, Some(ix) == tab_stop)),
636 window,
637 cx,
638 )
639 },
640 ))
641 })
642 }
643}
644
645#[cfg(test)]
646mod tests {
647 use super::*;
648
649 #[test]
650 fn segmented_corners_match_standard_and_m3e_geometry() {
651 assert_eq!(
652 segmented_corners(ListVariant::Standard, 0, 2),
653 (CornerRole::None.shape(), CornerRole::None.shape())
654 );
655 assert_eq!(
656 segmented_corners(ListVariant::Segmented, 0, 0),
657 (
658 CornerShape::Radii([16., 16., 16., 16.]),
659 CornerRole::Large.shape()
660 )
661 );
662 assert_eq!(
663 segmented_corners(ListVariant::Segmented, 0, 2),
664 (
665 CornerShape::Radii([16., 16., 4., 4.]),
666 CornerRole::Large.shape()
667 )
668 );
669 assert_eq!(
670 segmented_corners(ListVariant::Segmented, 1, 2),
671 (
672 CornerShape::Radii([4., 4., 4., 4.]),
673 CornerRole::Large.shape()
674 )
675 );
676 assert_eq!(
677 segmented_corners(ListVariant::Segmented, 2, 2),
678 (
679 CornerShape::Radii([4., 4., 16., 16.]),
680 CornerRole::Large.shape()
681 )
682 );
683 }
684}