1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, Axis, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5 ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Window, div,
6 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::{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<bool>,
77 selected: bool,
78 disabled: bool,
79 dragged: bool,
80 focus: Option<(FocusHandle, bool)>,
81 shapes: ListItemShapes,
82 colors: ListItemColors,
83 elevations: ListItemElevations,
84 alignment: ListItemAlignment,
85 padding: Option<ListItemPadding>,
86 source: Option<Entity<InteractionSource>>,
87}
88
89impl ListItem {
90 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
91 Self {
92 id: id.into(),
93 label: label.into(),
94 content: None,
95 supporting: None,
96 overline: None,
97 leading: None,
98 trailing: None,
99 activation: None,
100 checked_change: None,
101 expanded_change: None,
102 long_press: None,
103 long_press_button: None,
104 expansion: None,
105 swipe: None,
106 checked: None,
107 selected: false,
108 disabled: false,
109 dragged: false,
110 focus: None,
111 shapes: ListItemShapes::default(),
112 colors: ListItemColors::default(),
113 elevations: ListItemElevations::default(),
114 alignment: ListItemAlignment::Auto,
115 padding: None,
116 source: None,
117 }
118 }
119
120 pub fn content(mut self, content: impl IntoElement) -> Self {
122 self.content = Some(content.into_any_element());
123 self
124 }
125
126 pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
127 self.supporting = Some(Slot::Text(text.into()));
128 self
129 }
130
131 pub fn supporting_content(mut self, content: impl IntoElement) -> Self {
132 self.supporting = Some(Slot::Custom(content.into_any_element()));
133 self
134 }
135
136 pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
137 self.overline = Some(Slot::Text(text.into()));
138 self
139 }
140
141 pub fn overline_content(mut self, content: impl IntoElement) -> Self {
142 self.overline = Some(Slot::Custom(content.into_any_element()));
143 self
144 }
145
146 pub fn leading(mut self, leading: impl IntoElement) -> Self {
147 self.leading = Some(leading.into_any_element());
148 self
149 }
150
151 pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
152 self.trailing = Some(trailing.into_any_element());
153 self
154 }
155
156 pub fn selected(mut self, selected: bool) -> Self {
157 self.selected = selected;
158 self
159 }
160
161 pub fn checked(mut self, checked: bool) -> Self {
163 self.checked = Some(checked);
164 self
165 }
166
167 pub fn on_checked_change(
169 mut self,
170 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
171 ) -> Self {
172 self.checked.get_or_insert(false);
173 self.checked_change = Some(Rc::new(handler));
174 self
175 }
176
177 pub fn expanded_content(mut self, expanded: bool, content: impl IntoElement) -> Self {
179 self.expansion = Some(Expansion {
180 expanded,
181 content: content.into_any_element(),
182 });
183 self
184 }
185
186 pub fn on_expanded_change(
187 mut self,
188 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
189 ) -> Self {
190 self.expanded_change = Some(Rc::new(handler));
191 self
192 }
193
194 pub fn on_long_press(
196 mut self,
197 label: impl Into<SharedString>,
198 handler: impl Fn(&mut Window, &mut App) + 'static,
199 ) -> Self {
200 self.long_press = Some(SecondaryAction {
201 label: label.into(),
202 handler: Rc::new(handler),
203 });
204 self
205 }
206
207 pub fn long_press_button(mut self, id: impl Into<ElementId>) -> Self {
209 self.long_press_button = Some(id.into());
210 self
211 }
212
213 pub fn swipe_to_dismiss(
216 mut self,
217 state: &Entity<SwipeToDismissState>,
218 configure: impl FnOnce(SwipeToDismiss) -> SwipeToDismiss + 'static,
219 ) -> Self {
220 self.swipe = Some(RowSwipe {
221 state: state.clone(),
222 configure: Box::new(configure),
223 });
224 self
225 }
226
227 pub fn disabled(mut self, disabled: bool) -> Self {
228 self.disabled = disabled;
229 self
230 }
231
232 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
233 self.activation = Some(Rc::new(handler));
234 self
235 }
236
237 pub fn shapes(mut self, shapes: ListItemShapes) -> Self {
238 self.shapes = shapes;
239 self
240 }
241
242 pub fn colors(mut self, colors: ListItemColors) -> Self {
243 self.colors = colors;
244 self
245 }
246
247 pub fn elevations(mut self, elevations: ListItemElevations) -> Self {
248 self.elevations = elevations;
249 self
250 }
251
252 pub fn vertical_alignment(mut self, alignment: ListItemAlignment) -> Self {
253 self.alignment = alignment;
254 self
255 }
256
257 pub fn content_padding(mut self, padding: ListItemPadding) -> Self {
258 self.padding = Some(padding);
259 self
260 }
261
262 pub fn dragged(mut self, dragged: bool) -> Self {
264 self.dragged = dragged;
265 self
266 }
267
268 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
269 self.source = Some(source.clone());
270 self
271 }
272
273 pub fn track_focus(mut self, focus: &FocusHandle, tab_stop: bool) -> Self {
276 self.focus = Some((focus.clone(), tab_stop));
277 self
278 }
279
280 fn has_primary_action(&self) -> bool {
281 self.activation.is_some()
282 || self.checked_change.is_some()
283 || self.expansion.is_some() && self.expanded_change.is_some()
284 }
285
286 fn takes_focus(&self, cx: &App) -> bool {
287 !self.disabled
288 && (self.has_primary_action() || self.long_press.is_some())
289 && self
290 .swipe
291 .as_ref()
292 .is_none_or(|swipe| swipe.state.read(cx).shows_foreground())
293 }
294
295 fn primary_action(&self) -> Option<Activate> {
296 if !self.has_primary_action() {
297 return None;
298 }
299 let action = self.activation.clone();
300 let check = self.checked.zip(self.checked_change.clone());
301 let expansion = self
302 .expansion
303 .as_ref()
304 .map(|expansion| expansion.expanded)
305 .zip(self.expanded_change.clone());
306 Some(Rc::new(move |window, cx| {
307 if let Some((checked, change)) = &check {
308 change(!checked, window, cx);
309 }
310 if let Some((expanded, change)) = &expansion {
311 change(!expanded, window, cx);
312 }
313 if let Some(action) = &action {
314 action(window, cx);
315 }
316 }))
317 }
318
319 fn row(
320 self,
321 resting: CornerShape,
322 selected_shape: CornerShape,
323 focus: Option<(FocusHandle, bool)>,
324 window: &mut Window,
325 cx: &mut App,
326 ) -> AnyElement {
327 window.with_element_namespace((self.id.clone(), "material-list-row"), |window| {
328 self.render_row(resting, selected_shape, focus, window, cx)
329 })
330 }
331}
332
333impl RenderOnce for ListItem {
334 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
335 let focus = self.focus.clone();
336 self.row(
337 CornerRole::None.shape(),
338 CornerRole::None.shape(),
339 focus,
340 window,
341 cx,
342 )
343 }
344}
345
346#[derive(IntoElement)]
349pub struct List {
350 id: ElementId,
351 items: Vec<ListItem>,
352 variant: ListVariant,
353}
354
355impl List {
356 pub fn new(id: impl Into<ElementId>) -> Self {
357 Self {
358 id: id.into(),
359 items: Vec::new(),
360 variant: ListVariant::default(),
361 }
362 }
363
364 pub fn variant(mut self, variant: ListVariant) -> Self {
365 self.variant = variant;
366 self
367 }
368
369 pub fn items(mut self, items: impl IntoIterator<Item = ListItem>) -> Self {
370 self.items.extend(items);
371 self
372 }
373}
374
375impl RenderOnce for List {
376 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
377 window.with_element_namespace((self.id.clone(), "material-list"), |window| {
378 let last = self.items.len().saturating_sub(1);
379 let direction = current_material_theme(window, cx).layout.direction;
380 let focus: Vec<_> = self
381 .items
382 .iter()
383 .map(|item| {
384 window
385 .use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
386 .read(cx)
387 .clone()
388 })
389 .collect();
390 let enabled: Vec<_> = self.items.iter().map(|item| item.takes_focus(cx)).collect();
391 let tab_stop = focus
392 .iter()
393 .enumerate()
394 .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
395 .or_else(|| {
396 self.items
397 .iter()
398 .enumerate()
399 .position(|(ix, item)| enabled[ix] && item.selected)
400 })
401 .or_else(|| enabled.iter().position(|enabled| *enabled));
402 let navigation = focus.clone();
403 div()
404 .id(self.id)
405 .role(Role::List)
406 .test_support()
407 .flex()
408 .flex_col()
409 .w_full()
410 .on_key_down(move |event, window, cx| {
411 if !navigation.iter().any(|focus| focus.is_focused(window)) {
413 return;
414 }
415 let items: Vec<_> = navigation
416 .iter()
417 .zip(&enabled)
418 .map(|(focus, enabled)| (focus, *enabled))
419 .collect();
420 if move_roving_focus(
421 &items,
422 &event.keystroke.key,
423 Axis::Vertical,
424 direction,
425 window,
426 cx,
427 )
428 .is_some()
429 {
430 cx.stop_propagation();
431 window.refresh();
432 }
433 })
434 .when(self.variant == ListVariant::Segmented, |list| {
435 list.gap(px(2.))
436 })
437 .children(self.items.into_iter().enumerate().map(|(ix, item)| {
438 let (resting, selected) = match self.variant {
439 ListVariant::Standard => {
440 (CornerRole::None.shape(), CornerRole::None.shape())
441 }
442 ListVariant::Segmented => {
443 let top = if ix == 0 { 16. } else { 4. };
444 let bottom = if ix == last { 16. } else { 4. };
445 (
446 CornerShape::Radii([top, top, bottom, bottom]),
447 CornerRole::Large.shape(),
448 )
449 }
450 };
451 item.row(
452 resting,
453 selected,
454 Some((focus[ix].clone(), Some(ix) == tab_stop)),
455 window,
456 cx,
457 )
458 }))
459 })
460 }
461}