Skip to main content

gpui_material_components/list/
style.rs

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