1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4 AccessibleAction, AnyElement, App, Axis, BorderStyle, ClickEvent, Corners, ElementId, Entity,
5 FocusHandle, Hsla, InteractiveElement, IntoElement, ParentElement, RenderOnce, Role,
6 SharedString, StatefulInteractiveElement, Styled, Window, accesskit::Toggled, canvas, div,
7 prelude::FluentBuilder, px, quad,
8};
9use gpui_base::TestSupportExt;
10use gpui_material_foundation::{
11 InteractionFeedback, InteractionSource, Shape, animate, color, elevation_shadows,
12 move_roving_focus, window_material_theme,
13};
14use gpui_material_theme::{
15 ColorRole, CornerRole, CornerShape, Direction, MotionKind, MotionSpec, MotionSpeed, TypeRole,
16};
17
18use crate::{
19 Button, ButtonVariant, ControlSize, SwipeToDismiss, SwipeToDismissState, Text,
20 action::{Activate, activate_feedback, feedback_target, ripple_state},
21 button_style::finite_length,
22};
23
24mod long_press;
25mod style;
26
27use long_press::LongPress;
28pub use style::{
29 ListItemAlignment, ListItemColors, ListItemElevations, ListItemPadding, ListItemShapes,
30 ListItemStateColors,
31};
32
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
34pub enum ListVariant {
35 #[default]
36 Standard,
37 Segmented,
38}
39
40type ValueChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
41type SwipeConfig = Box<dyn FnOnce(SwipeToDismiss) -> SwipeToDismiss>;
42
43enum Slot {
44 Text(SharedString),
45 Custom(AnyElement),
46}
47
48impl Slot {
49 fn render(self, id: &'static str, role: TypeRole, tint: Hsla, wrap: bool) -> AnyElement {
50 let content = match self {
51 Self::Text(value) => Text::new(value)
52 .id(id)
53 .role(role)
54 .when(wrap, Text::wrap)
55 .into_any_element(),
56 Self::Custom(element) => element,
57 };
58 inherit_color((ElementId::from(id), "slot"), content, Some(tint))
59 }
60
61 fn has_line_break(&self) -> bool {
62 matches!(self, Self::Text(value) if value.contains('\n'))
63 }
64}
65
66struct Expansion {
67 expanded: bool,
68 content: AnyElement,
69}
70
71struct SecondaryAction {
72 label: SharedString,
73 handler: Activate,
74}
75
76struct RowSwipe {
77 state: Entity<SwipeToDismissState>,
78 configure: SwipeConfig,
79}
80
81#[derive(IntoElement)]
83pub struct ListItem {
84 id: ElementId,
85 label: SharedString,
86 content: Option<AnyElement>,
87 supporting: Option<Slot>,
88 overline: Option<Slot>,
89 leading: Option<AnyElement>,
90 trailing: Option<AnyElement>,
91 activation: Option<Activate>,
92 checked_change: Option<ValueChange>,
93 expanded_change: Option<ValueChange>,
94 long_press: Option<SecondaryAction>,
95 long_press_button: Option<ElementId>,
96 expansion: Option<Expansion>,
97 swipe: Option<RowSwipe>,
98 checked: Option<bool>,
99 selected: bool,
100 disabled: bool,
101 dragged: bool,
102 focus: Option<(FocusHandle, bool)>,
103 shapes: ListItemShapes,
104 colors: ListItemColors,
105 elevations: ListItemElevations,
106 alignment: ListItemAlignment,
107 padding: Option<ListItemPadding>,
108 source: Option<Entity<InteractionSource>>,
109}
110
111impl ListItem {
112 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
113 Self {
114 id: id.into(),
115 label: label.into(),
116 content: None,
117 supporting: None,
118 overline: None,
119 leading: None,
120 trailing: None,
121 activation: None,
122 checked_change: None,
123 expanded_change: None,
124 long_press: None,
125 long_press_button: None,
126 expansion: None,
127 swipe: None,
128 checked: None,
129 selected: false,
130 disabled: false,
131 dragged: false,
132 focus: None,
133 shapes: ListItemShapes::default(),
134 colors: ListItemColors::default(),
135 elevations: ListItemElevations::default(),
136 alignment: ListItemAlignment::Auto,
137 padding: None,
138 source: None,
139 }
140 }
141
142 pub fn content(mut self, content: impl IntoElement) -> Self {
144 self.content = Some(content.into_any_element());
145 self
146 }
147
148 pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
149 self.supporting = Some(Slot::Text(text.into()));
150 self
151 }
152
153 pub fn supporting_content(mut self, content: impl IntoElement) -> Self {
154 self.supporting = Some(Slot::Custom(content.into_any_element()));
155 self
156 }
157
158 pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
159 self.overline = Some(Slot::Text(text.into()));
160 self
161 }
162
163 pub fn overline_content(mut self, content: impl IntoElement) -> Self {
164 self.overline = Some(Slot::Custom(content.into_any_element()));
165 self
166 }
167
168 pub fn leading(mut self, leading: impl IntoElement) -> Self {
169 self.leading = Some(leading.into_any_element());
170 self
171 }
172
173 pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
174 self.trailing = Some(trailing.into_any_element());
175 self
176 }
177
178 pub fn selected(mut self, selected: bool) -> Self {
179 self.selected = selected;
180 self
181 }
182
183 pub fn checked(mut self, checked: bool) -> Self {
185 self.checked = Some(checked);
186 self
187 }
188
189 pub fn on_checked_change(
191 mut self,
192 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
193 ) -> Self {
194 self.checked.get_or_insert(false);
195 self.checked_change = Some(Rc::new(handler));
196 self
197 }
198
199 pub fn expanded_content(mut self, expanded: bool, content: impl IntoElement) -> Self {
201 self.expansion = Some(Expansion {
202 expanded,
203 content: content.into_any_element(),
204 });
205 self
206 }
207
208 pub fn on_expanded_change(
209 mut self,
210 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
211 ) -> Self {
212 self.expanded_change = Some(Rc::new(handler));
213 self
214 }
215
216 pub fn on_long_press(
218 mut self,
219 label: impl Into<SharedString>,
220 handler: impl Fn(&mut Window, &mut App) + 'static,
221 ) -> Self {
222 self.long_press = Some(SecondaryAction {
223 label: label.into(),
224 handler: Rc::new(handler),
225 });
226 self
227 }
228
229 pub fn long_press_button(mut self, id: impl Into<ElementId>) -> Self {
231 self.long_press_button = Some(id.into());
232 self
233 }
234
235 pub fn swipe_to_dismiss(
238 mut self,
239 state: &Entity<SwipeToDismissState>,
240 configure: impl FnOnce(SwipeToDismiss) -> SwipeToDismiss + 'static,
241 ) -> Self {
242 self.swipe = Some(RowSwipe {
243 state: state.clone(),
244 configure: Box::new(configure),
245 });
246 self
247 }
248
249 pub fn disabled(mut self, disabled: bool) -> Self {
250 self.disabled = disabled;
251 self
252 }
253
254 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
255 self.activation = Some(Rc::new(handler));
256 self
257 }
258
259 pub fn shapes(mut self, shapes: ListItemShapes) -> Self {
260 self.shapes = shapes;
261 self
262 }
263
264 pub fn colors(mut self, colors: ListItemColors) -> Self {
265 self.colors = colors;
266 self
267 }
268
269 pub fn elevations(mut self, elevations: ListItemElevations) -> Self {
270 self.elevations = elevations;
271 self
272 }
273
274 pub fn vertical_alignment(mut self, alignment: ListItemAlignment) -> Self {
275 self.alignment = alignment;
276 self
277 }
278
279 pub fn content_padding(mut self, padding: ListItemPadding) -> Self {
280 self.padding = Some(padding);
281 self
282 }
283
284 pub fn dragged(mut self, dragged: bool) -> Self {
286 self.dragged = dragged;
287 self
288 }
289
290 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
291 self.source = Some(source.clone());
292 self
293 }
294
295 pub fn track_focus(mut self, focus: &FocusHandle, tab_stop: bool) -> Self {
298 self.focus = Some((focus.clone(), tab_stop));
299 self
300 }
301
302 fn has_primary_action(&self) -> bool {
303 self.activation.is_some()
304 || self.checked_change.is_some()
305 || self.expansion.is_some() && self.expanded_change.is_some()
306 }
307
308 fn takes_focus(&self, cx: &App) -> bool {
309 !self.disabled
310 && (self.has_primary_action() || self.long_press.is_some())
311 && self
312 .swipe
313 .as_ref()
314 .is_none_or(|swipe| swipe.state.read(cx).shows_foreground())
315 }
316
317 fn primary_action(&self) -> Option<Activate> {
318 if !self.has_primary_action() {
319 return None;
320 }
321 let action = self.activation.clone();
322 let check = self.checked.zip(self.checked_change.clone());
323 let expansion = self
324 .expansion
325 .as_ref()
326 .map(|expansion| expansion.expanded)
327 .zip(self.expanded_change.clone());
328 Some(Rc::new(move |window, cx| {
329 if let Some((checked, change)) = &check {
330 change(!checked, window, cx);
331 }
332 if let Some((expanded, change)) = &expansion {
333 change(!expanded, window, cx);
334 }
335 if let Some(action) = &action {
336 action(window, cx);
337 }
338 }))
339 }
340
341 fn row(
342 self,
343 resting: CornerShape,
344 selected_shape: CornerShape,
345 focus: Option<(FocusHandle, bool)>,
346 window: &mut Window,
347 cx: &mut App,
348 ) -> AnyElement {
349 window.with_element_namespace((self.id.clone(), "material-list-row"), |window| {
350 self.render_row(resting, selected_shape, focus, window, cx)
351 })
352 }
353
354 fn render_row(
355 self,
356 resting: CornerShape,
357 selected_shape: CornerShape,
358 focus: Option<(FocusHandle, bool)>,
359 window: &mut Window,
360 cx: &mut App,
361 ) -> AnyElement {
362 let (focus, tab_stop) = focus.unwrap_or_else(|| {
363 let focus = window
364 .use_keyed_state("focus", cx, |_, cx| cx.focus_handle())
365 .read(cx)
366 .clone();
367 (focus, true)
368 });
369 let primary = self.primary_action();
370 let interactive = primary.is_some() || self.long_press.is_some();
371 let visible = self
372 .swipe
373 .as_ref()
374 .is_none_or(|swipe| swipe.state.read(cx).shows_foreground());
375 let enabled = !self.disabled && visible;
376 let dragged = enabled
377 && (self.dragged
378 || self
379 .swipe
380 .as_ref()
381 .is_some_and(|swipe| swipe.state.read(cx).is_dragging()));
382 let feedback = ripple_state(&self.id, interactive && enabled, window, cx);
383 let tracker = self
384 .source
385 .as_ref()
386 .filter(|_| visible)
387 .map(|source| InteractionSource::track(source, &self.id, window, cx));
388 let interaction = {
389 let mut feedback = feedback.borrow_mut();
390 feedback.set_dragged(dragged);
391 feedback.track(enabled, &focus, tracker, window, cx)
392 };
393
394 let long_press = self.long_press.as_ref().map(|long_press| {
395 LongPress::mount(
396 (enabled && !dragged).then(|| long_press.handler.clone()),
397 window,
398 cx,
399 )
400 });
401 let theme = window_material_theme(window, cx);
402 let layout = theme.layout;
403 let direction = layout.direction;
404 let motion = theme.motion;
405 let reduced = cx.reduce_motion();
406 let selected = self.selected || self.checked == Some(true);
407 let shape = self
408 .shapes
409 .resolve(resting, selected_shape, selected, interaction);
410 let effects = motion.spec(MotionKind::Effects, MotionSpeed::Default, reduced);
411 let spatial = motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
412 let selection =
413 animate("selection", f32::from(selected), effects, window, cx).clamp(0., 1.);
414 let scheme = &window_material_theme(window, cx).colors;
415 let tone = |role| color(scheme.color(role));
416 let ring = tone(ColorRole::Secondary);
417 let shadow = tone(ColorRole::Shadow);
418 let colors = self.colors.resolve(selected, selection, interaction, tone);
419 let layer = animate(
420 "opacity",
421 interaction
422 .layer_with_ripple(reduced)
423 .map_or(0., |layer| layer.opacity()),
424 if enabled {
425 effects
426 } else {
427 MotionSpec::Instant
428 },
429 window,
430 cx,
431 )
432 .clamp(0., 1.);
433 let elevation = animate(
434 "elevation",
435 self.elevations.resolve(interaction).dp(),
436 if enabled {
437 spatial
438 } else {
439 MotionSpec::Instant
440 },
441 window,
442 cx,
443 )
444 .max(0.);
445 let text_height = window
446 .use_keyed_state("text-height", cx, |_, _| Rc::new(Cell::new(px(0.))))
447 .read(cx)
448 .clone();
449 let three_lines = self.overline.is_some() && self.supporting.is_some()
450 || self.supporting.as_ref().is_some_and(Slot::has_line_break)
451 || text_height.get() > px(44.);
452 let height = match (self.overline.is_some(), self.supporting.is_some()) {
453 _ if three_lines => 88.,
454 (false, false) => 56.,
455 _ => 72.,
456 };
457 let radii = match shape {
458 CornerShape::Radii(radii) => radii,
459 CornerShape::Full => [height * 0.5; 4],
460 };
461 let full = animate(
464 "full",
465 f32::from(shape == CornerShape::Full),
466 spatial,
467 window,
468 cx,
469 )
470 .clamp(0., 1.);
471 let radii = std::array::from_fn(|ix| {
472 animate(["ts", "te", "be", "bs"][ix], radii[ix], spatial, window, cx).max(0.)
473 });
474 let geometry = feedback.clone();
475 let ink = feedback.clone();
476 let visual = canvas(
477 move |bounds, window, _| {
478 let extent = f32::from(bounds.size.width.min(bounds.size.height)) * 0.5;
479 let shape =
480 CornerShape::Radii(radii.map(|radius| radius + (extent - radius) * full));
481 let [top_left, top_right, bottom_right, bottom_left] = shape
482 .radii(
483 bounds.size.width.into(),
484 bounds.size.height.into(),
485 direction,
486 )
487 .map(px);
488 let feedback_shape = enabled
489 .then(|| Shape::rounded(bounds, shape, direction))
490 .flatten();
491 geometry.borrow_mut().set_shape(feedback_shape, window);
492 Corners {
493 top_left,
494 top_right,
495 bottom_right,
496 bottom_left,
497 }
498 },
499 move |bounds, corners, window, cx| {
500 if elevation > 0. {
501 window.paint_drop_shadows(
502 bounds,
503 corners,
504 &elevation_shadows(elevation, 1., shadow),
505 );
506 }
507 window.paint_quad(quad(
508 bounds,
509 corners,
510 colors.container,
511 px(0.),
512 gpui::transparent_black(),
513 BorderStyle::Solid,
514 ));
515 let feedback = ink.borrow();
516 if let Some(shape) = &feedback.shape {
517 let mut visual_interaction = interaction;
519 visual_interaction.focus_visible = false;
520 InteractionFeedback::new(visual_interaction, colors.content, ring)
521 .paint_with_opacity(
522 shape,
523 feedback.ripple.as_ref(),
524 layer,
525 cx.background_executor().now(),
526 reduced,
527 window,
528 );
529 }
530 },
531 )
532 .absolute()
533 .inset_0();
534
535 let content = div()
536 .relative()
537 .flex()
538 .flex_col()
539 .flex_1()
540 .min_w_0()
541 .overflow_hidden()
542 .text_color(colors.content)
543 .children(
544 self.overline.map(|slot| {
545 slot.render("overline", TypeRole::LabelSmall, colors.overline, false)
546 }),
547 )
548 .child(div().id("headline-slot").child(
549 self.content.unwrap_or_else(|| {
550 Text::new(self.label.clone()).id("label").into_any_element()
551 }),
552 ))
553 .children(self.supporting.map(|slot| {
554 slot.render("supporting", TypeRole::BodyMedium, colors.supporting, true)
555 }))
556 .children(
557 long_press
558 .as_ref()
559 .filter(|_| enabled && !dragged)
560 .map(|press| press.target()),
561 )
562 .child(
563 canvas(
564 move |bounds, window, _| {
565 if text_height.replace(bounds.size.height) != bounds.size.height {
566 window.refresh();
567 }
568 },
569 |_, _, _, _| {},
570 )
571 .absolute()
572 .inset_0(),
573 );
574
575 let padding = self.padding.unwrap_or_else(|| {
576 let vertical = px(if three_lines { 12. } else { 10. });
577 ListItemPadding {
578 top: vertical,
579 bottom: vertical,
580 ..ListItemPadding::default()
581 }
582 });
583 let (left, right) =
584 layout.horizontal(finite_length(padding.start), finite_length(padding.end));
585 let press_button =
586 self.long_press
587 .as_ref()
588 .zip(self.long_press_button)
589 .map(|(press, id)| {
590 let invoke = press.handler.clone();
591 Button::new(id, press.label.clone())
592 .variant(ButtonVariant::Text)
593 .size(ControlSize::ExtraSmall)
594 .disabled(!enabled || dragged)
595 .on_activate(move |window, cx| invoke(window, cx))
596 });
597 let alignment = if self.alignment == ListItemAlignment::Auto {
598 if three_lines {
599 ListItemAlignment::Start
600 } else {
601 ListItemAlignment::Center
602 }
603 } else {
604 self.alignment
605 };
606 let surface = div()
607 .id("list-surface")
608 .relative()
609 .min_h(px(height))
610 .w_full()
611 .flex()
612 .map(|row| match alignment {
613 ListItemAlignment::Start => row.items_start(),
614 ListItemAlignment::End => row.items_end(),
615 _ => row.items_center(),
616 })
617 .gap(px(12.))
618 .pl(left)
619 .pr(right)
620 .pt(finite_length(padding.top))
621 .pb(finite_length(padding.bottom))
622 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
623 .child(visual)
624 .children(
625 self.leading
626 .map(|element| inherit_color("leading-slot", element, colors.leading)),
627 )
628 .child(content)
629 .children(
630 self.trailing
631 .map(|element| inherit_color("trailing-slot", element, colors.trailing)),
632 )
633 .children(press_button.map(|button| div().id("long-press-slot").child(button)));
634
635 let expanded = self.expansion.as_ref().map(|expansion| expansion.expanded);
636 let checked = self.checked.map(|checked| {
637 if checked {
638 Toggled::True
639 } else {
640 Toggled::False
641 }
642 });
643 let expanded_content = self.expansion.and_then(|expansion| {
644 let scope = window
645 .use_keyed_state("disclosure-focus", cx, |_, cx| {
646 cx.focus_handle().tab_stop(false)
647 })
648 .read(cx)
649 .clone();
650 if !expansion.expanded && interactive && enabled && scope.contains_focused(window, cx) {
651 focus.focus(window, cx);
652 }
653 expansion.expanded.then(|| {
654 div()
655 .id("list-expanded-content")
656 .track_focus(&scope)
657 .child(expansion.content)
658 })
659 });
660 let row = if interactive {
661 let activate = feedback.clone();
662 let mut control = gpui_base::Button::new((self.id.clone(), "activate"))
663 .track_focus(&focus)
664 .tab_stop(tab_stop)
665 .w_full()
666 .accessibility_label(self.label.clone())
667 .disabled(!enabled)
668 .selected(self.selected)
669 .when_some(checked, |control, checked| {
670 control.role(Role::CheckBox).aria_toggled(checked)
671 })
672 .when_some(expanded, |control, expanded| {
673 control.aria_expanded(expanded)
674 })
675 .border_2()
676 .border_color(gpui::transparent_black())
677 .rounded_md()
678 .focus_visible(move |style| style.border_color(ring))
679 .when(enabled && !dragged, |control| {
680 feedback_target(control, feedback, true, Some(focus.clone()))
681 });
682 if let Some(primary) = primary.filter(|_| enabled && !dragged) {
683 let invoke = primary.clone();
684 let hold = long_press.clone();
685 control = control
686 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
687 invoke(window, cx)
688 })
689 .on_click(move |event, window, cx| {
690 cx.stop_propagation();
691 let native_drag =
692 matches!(event, ClickEvent::Mouse(_)) && cx.has_active_drag();
693 let allowed = !native_drag
694 && !activate.borrow().blocks_activation(event)
695 && !hold
696 .as_ref()
697 .is_some_and(|hold| hold.blocks_activation(event));
698 if allowed || matches!(event, ClickEvent::Mouse(_)) {
699 activate_feedback(event, &activate, window, cx);
700 }
701 if allowed {
702 primary(window, cx);
703 }
704 });
705 }
706 if let Some((expanded, change)) = expanded
707 .zip(self.expanded_change)
708 .filter(|_| enabled && !dragged)
709 {
710 control = control.on_a11y_action(
711 if expanded {
712 AccessibleAction::Collapse
713 } else {
714 AccessibleAction::Expand
715 },
716 move |_, window, cx| change(!expanded, window, cx),
717 );
718 }
719 if let Some((secondary, hold)) = self
720 .long_press
721 .zip(long_press)
722 .filter(|_| enabled && !dragged)
723 {
724 let invoke = secondary.handler.clone();
725 control = control
726 .aria_description(secondary.label)
727 .on_a11y_action(AccessibleAction::ShowContextMenu, move |_, window, cx| {
728 invoke(window, cx)
729 })
730 .on_key_down(move |event, window, cx| {
731 if !focus.is_focused(window) {
732 return;
733 }
734 if event.keystroke.key == "escape" {
735 hold.cancel();
736 }
737 if is_long_press_shortcut(&event.keystroke) {
738 cx.stop_propagation();
739 if !event.is_held {
740 (secondary.handler)(window, cx);
741 }
742 }
743 });
744 }
745 control.child(surface).into_any_element()
746 } else {
747 surface
748 .when_some(checked, |row, checked| {
749 row.role(Role::CheckBox).aria_toggled(checked)
750 })
751 .when_some(expanded, |row, expanded| {
752 row.when(checked.is_none(), |row| row.role(Role::Group))
753 .aria_expanded(expanded)
754 })
755 .when(
756 self.disabled && (checked.is_some() || expanded.is_some()),
757 |row| row.a11y_synthetic_children(|tree| tree.parent_node().set_disabled()),
758 )
759 .into_any_element()
760 };
761 let id = self.id;
762 let row = div()
763 .id(id.clone())
764 .role(Role::ListItem)
765 .test_support()
766 .aria_selected(self.selected)
767 .when(!interactive, |row| row.aria_label(self.label))
768 .flex()
769 .flex_col()
770 .w_full()
771 .child(row)
772 .children(expanded_content);
773 match self.swipe {
774 Some(swipe) => (swipe.configure)(SwipeToDismiss::new((id, "swipe"), &swipe.state, row))
775 .when(self.disabled, |swipe| swipe.gestures_enabled(false))
776 .into_any_element(),
777 None => row.into_any_element(),
778 }
779 }
780}
781
782fn inherit_color(id: impl Into<ElementId>, element: AnyElement, color: Option<Hsla>) -> AnyElement {
783 div()
786 .id(id)
787 .when_some(color, Styled::text_color)
788 .child(element)
789 .into_any_element()
790}
791
792fn is_long_press_shortcut(keystroke: &gpui::Keystroke) -> bool {
793 let modifiers = keystroke.modifiers;
794 keystroke.key == "f10"
795 && modifiers.shift
796 && !modifiers.control
797 && !modifiers.alt
798 && !modifiers.platform
799}
800
801impl RenderOnce for ListItem {
802 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
803 let focus = self.focus.clone();
804 self.row(
805 CornerRole::None.shape(),
806 CornerRole::None.shape(),
807 focus,
808 window,
809 cx,
810 )
811 }
812}
813
814#[derive(IntoElement)]
817pub struct List {
818 id: ElementId,
819 items: Vec<ListItem>,
820 variant: ListVariant,
821}
822
823impl List {
824 pub fn new(id: impl Into<ElementId>) -> Self {
825 Self {
826 id: id.into(),
827 items: Vec::new(),
828 variant: ListVariant::default(),
829 }
830 }
831
832 pub fn variant(mut self, variant: ListVariant) -> Self {
833 self.variant = variant;
834 self
835 }
836
837 pub fn items(mut self, items: impl IntoIterator<Item = ListItem>) -> Self {
838 self.items.extend(items);
839 self
840 }
841}
842
843impl RenderOnce for List {
844 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
845 window.with_element_namespace((self.id.clone(), "material-list"), |window| {
846 let last = self.items.len().saturating_sub(1);
847 let direction = window_material_theme(window, cx).layout.direction;
848 let focus: Vec<_> = self
849 .items
850 .iter()
851 .map(|item| {
852 window
853 .use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
854 .read(cx)
855 .clone()
856 })
857 .collect();
858 let enabled: Vec<_> = self.items.iter().map(|item| item.takes_focus(cx)).collect();
859 let tab_stop = focus
860 .iter()
861 .enumerate()
862 .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
863 .or_else(|| {
864 self.items
865 .iter()
866 .enumerate()
867 .position(|(ix, item)| enabled[ix] && item.selected)
868 })
869 .or_else(|| enabled.iter().position(|enabled| *enabled));
870 let navigation = focus.clone();
871 div()
872 .id(self.id)
873 .role(Role::List)
874 .test_support()
875 .flex()
876 .flex_col()
877 .w_full()
878 .on_key_down(move |event, window, cx| {
879 if !navigation.iter().any(|focus| focus.is_focused(window)) {
881 return;
882 }
883 let items: Vec<_> = navigation
884 .iter()
885 .zip(&enabled)
886 .map(|(focus, enabled)| (focus, *enabled))
887 .collect();
888 if move_roving_focus(
889 &items,
890 &event.keystroke.key,
891 Axis::Vertical,
892 direction,
893 window,
894 cx,
895 )
896 .is_some()
897 {
898 cx.stop_propagation();
899 window.refresh();
900 }
901 })
902 .when(self.variant == ListVariant::Segmented, |list| {
903 list.gap(px(2.))
904 })
905 .children(self.items.into_iter().enumerate().map(|(ix, item)| {
906 let (resting, selected) = match self.variant {
907 ListVariant::Standard => {
908 (CornerRole::None.shape(), CornerRole::None.shape())
909 }
910 ListVariant::Segmented => {
911 let top = if ix == 0 { 16. } else { 4. };
912 let bottom = if ix == last { 16. } else { 4. };
913 (
914 CornerShape::Radii([top, top, bottom, bottom]),
915 CornerRole::Large.shape(),
916 )
917 }
918 };
919 item.row(
920 resting,
921 selected,
922 Some((focus[ix].clone(), Some(ix) == tab_stop)),
923 window,
924 cx,
925 )
926 }))
927 })
928 }
929}