Skip to main content

gpui_material_components/list/
style.rs

1use gpui::{Hsla, Pixels, px};
2use gpui_material_foundation::InteractionState;
3use gpui_material_theme::{ColorRole, CornerShape, Elevation};
4
5use crate::SemanticTone;
6
7/// Alignment of the slots within one row.
8#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
9pub enum ListItemAlignment {
10    /// Adapts automatically based on line count (centered for 1–2 lines, top-aligned for 3+ lines).
11    #[default]
12    Auto,
13    /// Aligns slots to the top edge of the row.
14    Start,
15    /// Vertically centers slots within the row.
16    Center,
17    /// Aligns slots to the bottom edge of the row.
18    End,
19}
20
21/// Logical padding in pixels. Using the builder replaces the adaptive defaults.
22#[derive(Clone, Copy, Debug, PartialEq)]
23pub struct ListItemPadding {
24    /// Leading-edge padding (left in LTR, right in RTL). Defaults to `16 px`.
25    pub start: Pixels,
26    /// Trailing-edge padding (right in LTR, left in RTL). Defaults to `16 px`.
27    pub end: Pixels,
28    /// Top padding in logical pixels. Defaults to `10 px`.
29    pub top: Pixels,
30    /// Bottom padding in logical pixels. Defaults to `10 px`.
31    pub bottom: Pixels,
32}
33
34impl Default for ListItemPadding {
35    fn default() -> Self {
36        Self {
37            start: px(16.),
38            end: px(16.),
39            top: px(10.),
40            bottom: px(10.),
41        }
42    }
43}
44
45/// Logical shapes for one row. An omitted shape uses the resting or selected
46/// shape, including the list's grouped corners.
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct ListItemShapes {
49    /// Corner shape while resting and unselected.
50    pub resting: Option<CornerShape>,
51    /// Corner shape while selected.
52    pub selected: Option<CornerShape>,
53    /// Corner shape while pressed.
54    pub pressed: Option<CornerShape>,
55    /// Corner shape while keyboard focus is visible.
56    pub focused: Option<CornerShape>,
57    /// Corner shape while hovered.
58    pub hovered: Option<CornerShape>,
59    /// Corner shape while dragged.
60    pub dragged: Option<CornerShape>,
61}
62
63impl ListItemShapes {
64    pub(super) fn resolve(
65        self,
66        resting: CornerShape,
67        selected_shape: CornerShape,
68        selected: bool,
69        state: InteractionState,
70    ) -> CornerShape {
71        let base = if selected {
72            self.selected.unwrap_or(selected_shape)
73        } else {
74            self.resting.unwrap_or(resting)
75        };
76        let active = if state.disabled {
77            None
78        } else if state.dragged {
79            self.dragged
80        } else if state.pressed {
81            self.pressed
82        } else if state.focus_visible {
83            self.focused
84        } else if state.hovered {
85            self.hovered
86        } else {
87            None
88        };
89        active.unwrap_or(base)
90    }
91}
92
93/// Independent colors inherited by the container and each slot in one state.
94#[derive(Clone, Copy, Debug, Default, PartialEq)]
95pub struct ListItemStateColors {
96    /// Row container background color.
97    pub container: Option<Hsla>,
98    /// Primary headline text color.
99    pub content: Option<Hsla>,
100    /// Leading slot foreground color.
101    pub leading: Option<Hsla>,
102    /// Trailing slot foreground color.
103    pub trailing: Option<Hsla>,
104    /// Overline text color.
105    pub overline: Option<Hsla>,
106    /// Supporting text color.
107    pub supporting: Option<Hsla>,
108}
109
110/// Per-row palette. Omitted colors use the current window's theme.
111#[derive(Clone, Copy, Debug, Default, PartialEq)]
112pub struct ListItemColors {
113    /// Colors in the default enabled, unselected state.
114    pub normal: ListItemStateColors,
115    /// Colors when the row is disabled.
116    pub disabled: ListItemStateColors,
117    /// Colors when the row is selected.
118    pub selected: ListItemStateColors,
119    /// Colors when the row is dragged.
120    pub dragged: ListItemStateColors,
121}
122
123pub(super) struct RowColors {
124    pub container: Hsla,
125    pub content: Hsla,
126    pub leading: Option<Hsla>,
127    pub trailing: Option<Hsla>,
128    pub overline: Hsla,
129    pub supporting: Hsla,
130}
131
132impl ListItemColors {
133    pub(super) fn resolve(
134        self,
135        selected: bool,
136        selection: f32,
137        state: InteractionState,
138        semantic_tone: SemanticTone,
139        tone: impl Fn(ColorRole) -> Hsla,
140    ) -> RowColors {
141        let normal_container = self
142            .normal
143            .container
144            .unwrap_or_else(|| tone(ColorRole::Surface));
145        let selected_container = self.selected.container.unwrap_or_else(|| {
146            tone(
147                semantic_tone
148                    .container_role()
149                    .unwrap_or(ColorRole::SecondaryContainer),
150            )
151        });
152        let (colors, content, secondary, side, background) = if state.disabled {
153            let tint = tone(ColorRole::OnSurface).opacity(0.38);
154            let background = self
155                .disabled
156                .container
157                .unwrap_or_else(|| crate::motion::mix(normal_container, tint, selection));
158            (self.disabled, tint, tint, Some(tint), background)
159        } else if state.dragged {
160            let background = self.dragged.container.unwrap_or_else(|| {
161                if selected {
162                    selected_container
163                } else {
164                    tone(ColorRole::SurfaceContainerHighest)
165                }
166            });
167            let content = tone(if selected {
168                semantic_tone
169                    .on_container_role()
170                    .unwrap_or(ColorRole::OnSecondaryContainer)
171            } else {
172                semantic_tone.role().unwrap_or(ColorRole::OnSurface)
173            });
174            (self.dragged, content, content, Some(content), background)
175        } else {
176            let background = crate::motion::mix(normal_container, selected_container, selection);
177            if selected {
178                let tint = tone(
179                    semantic_tone
180                        .on_container_role()
181                        .unwrap_or(ColorRole::OnSecondaryContainer),
182                );
183                let side = semantic_tone.on_container_role().map(&tone);
184                (self.selected, tint, tint, side, background)
185            } else {
186                let accent = semantic_tone.role().map(&tone);
187                (
188                    self.normal,
189                    accent.unwrap_or_else(|| tone(ColorRole::OnSurface)),
190                    tone(ColorRole::OnSurfaceVariant),
191                    accent,
192                    background,
193                )
194            }
195        };
196        RowColors {
197            container: background,
198            content: colors.content.unwrap_or(content),
199            leading: colors.leading.or(side),
200            trailing: colors.trailing.or(side),
201            overline: colors.overline.unwrap_or(secondary),
202            supporting: colors.supporting.unwrap_or(secondary),
203        }
204    }
205}
206
207/// Per-state shadow levels. Rows default to Level0, or Level4 while dragged.
208#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
209pub struct ListItemElevations {
210    /// Elevation while resting.
211    pub resting: Option<Elevation>,
212    /// Elevation while hovered.
213    pub hovered: Option<Elevation>,
214    /// Elevation while keyboard focus is visible.
215    pub focused: Option<Elevation>,
216    /// Elevation while pressed.
217    pub pressed: Option<Elevation>,
218    /// Elevation while dragged.
219    pub dragged: Option<Elevation>,
220    /// Elevation while disabled.
221    pub disabled: Option<Elevation>,
222}
223
224impl ListItemElevations {
225    pub(super) fn resolve(self, state: InteractionState) -> Elevation {
226        let resting = self.resting.unwrap_or(Elevation::Level0);
227        if state.disabled {
228            self.disabled.unwrap_or(resting)
229        } else if state.dragged {
230            self.dragged.unwrap_or(Elevation::Level4)
231        } else if state.pressed {
232            self.pressed.unwrap_or(resting)
233        } else if state.focus_visible {
234            self.focused.unwrap_or(resting)
235        } else if state.hovered {
236            self.hovered.unwrap_or(resting)
237        } else {
238            resting
239        }
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use gpui_material_theme::{CornerRole, Direction};
246
247    use super::*;
248
249    #[test]
250    fn selected_and_active_shapes_are_logical_and_disabled_uses_selected_base() {
251        let shape = CornerShape::Radii([4., 8., 12., 16.]);
252        let selected = CornerRole::Large.shape();
253        let styles = ListItemShapes {
254            dragged: Some(shape),
255            ..Default::default()
256        };
257        let mut state = InteractionState::default();
258        state.dragged = true;
259        state.hovered = true;
260        assert_eq!(
261            styles
262                .resolve(CornerRole::None.shape(), selected, true, state)
263                .radii(100., 60., Direction::Rtl),
264            [8., 4., 16., 12.],
265        );
266        state.disabled = true;
267        assert_eq!(
268            styles.resolve(CornerRole::None.shape(), selected, true, state),
269            selected,
270        );
271    }
272
273    #[test]
274    fn all_slot_colors_follow_the_state_and_dragged_elevation_yields_to_disabled() {
275        let palette = |value| ListItemStateColors {
276            container: Some(gpui::rgb(value).into()),
277            content: Some(gpui::rgb(value + 1).into()),
278            leading: Some(gpui::rgb(value + 2).into()),
279            trailing: Some(gpui::rgb(value + 3).into()),
280            overline: Some(gpui::rgb(value + 4).into()),
281            supporting: Some(gpui::rgb(value + 5).into()),
282        };
283        let colors = ListItemColors {
284            normal: palette(0x113300),
285            selected: palette(0x224400),
286            dragged: palette(0x335500),
287            disabled: palette(0x446600),
288        };
289        let elevations = ListItemElevations {
290            dragged: Some(Elevation::Level3),
291            disabled: Some(Elevation::Level1),
292            ..Default::default()
293        };
294        let mut state = InteractionState::default();
295        for (selected, dragged, disabled, expected, level) in [
296            (false, false, false, colors.normal, Elevation::Level0),
297            (true, false, false, colors.selected, Elevation::Level0),
298            (true, true, false, colors.dragged, Elevation::Level3),
299            (true, true, true, colors.disabled, Elevation::Level1),
300        ] {
301            state.disabled = disabled;
302            state.dragged = dragged;
303            let actual = colors.resolve(
304                selected,
305                f32::from(selected),
306                state,
307                SemanticTone::Default,
308                |_| gpui::transparent_black(),
309            );
310            let expected_container = expected.container.unwrap();
311            let actual_container = actual.container;
312            assert!(
313                [
314                    actual_container.h - expected_container.h,
315                    actual_container.s - expected_container.s,
316                    actual_container.l - expected_container.l,
317                    actual_container.a - expected_container.a
318                ]
319                .into_iter()
320                .all(|delta| delta.abs() < 1e-6)
321            );
322            assert_eq!(Some(actual.content), expected.content);
323            assert_eq!(actual.leading, expected.leading);
324            assert_eq!(actual.trailing, expected.trailing);
325            assert_eq!(Some(actual.overline), expected.overline);
326            assert_eq!(Some(actual.supporting), expected.supporting);
327            assert_eq!(elevations.resolve(state), level);
328        }
329    }
330
331    #[test]
332    fn semantic_tone_tints_enabled_and_selected_roles_without_overriding_disabled_or_explicit_colors()
333     {
334        let role_color = |role: ColorRole| -> Hsla {
335            match role {
336                ColorRole::Error => gpui::rgb(0xB3261E).into(),
337                ColorRole::ErrorContainer => gpui::rgb(0xF9DEDC).into(),
338                ColorRole::OnErrorContainer => gpui::rgb(0x410E0B).into(),
339                ColorRole::OnSurface => gpui::rgb(0x1C1B1F).into(),
340                ColorRole::OnSurfaceVariant => gpui::rgb(0x49454F).into(),
341                _ => gpui::rgb(0xFFFFFF).into(),
342            }
343        };
344        let state = InteractionState::default();
345        let normal =
346            ListItemColors::default().resolve(false, 0., state, SemanticTone::Danger, role_color);
347        assert_eq!(normal.content, role_color(ColorRole::Error));
348        assert_eq!(normal.leading, Some(role_color(ColorRole::Error)));
349        assert_eq!(normal.trailing, Some(role_color(ColorRole::Error)));
350
351        let selected =
352            ListItemColors::default().resolve(true, 1., state, SemanticTone::Danger, role_color);
353        assert_eq!(selected.content, role_color(ColorRole::OnErrorContainer));
354        assert_eq!(
355            selected.leading,
356            Some(role_color(ColorRole::OnErrorContainer))
357        );
358        assert_eq!(
359            selected.trailing,
360            Some(role_color(ColorRole::OnErrorContainer))
361        );
362
363        let mut disabled_state = InteractionState::default();
364        disabled_state.disabled = true;
365        let disabled = ListItemColors::default().resolve(
366            false,
367            0.,
368            disabled_state,
369            SemanticTone::Danger,
370            role_color,
371        );
372        assert_eq!(
373            disabled.content,
374            role_color(ColorRole::OnSurface).opacity(0.38)
375        );
376
377        let custom: Hsla = gpui::rgb(0x123456).into();
378        let overridden = ListItemColors {
379            normal: ListItemStateColors {
380                content: Some(custom),
381                leading: Some(custom),
382                ..Default::default()
383            },
384            ..Default::default()
385        }
386        .resolve(false, 0., state, SemanticTone::Danger, role_color);
387        assert_eq!(overridden.content, custom);
388        assert_eq!(overridden.leading, Some(custom));
389        assert_eq!(overridden.trailing, Some(role_color(ColorRole::Error)));
390    }
391}