Skip to main content

gpui_material_components/settings_tiles/
choice.rs

1use std::rc::Rc;
2
3use gpui::{
4    Anchor, AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, ParentElement,
5    RenderOnce, SharedString, Styled, Window, div, prelude::FluentBuilder, px,
6};
7use gpui_material_foundation::{InteractionSource, color, current_material_theme};
8use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, TypeRole};
9
10use crate::{
11    DialogState, Icon, IconName, ListItemColors, ListItemShapes, ListVariant, Menu, MenuItem, Text,
12};
13
14use super::common::TileFields;
15
16type LeadingFactory = Rc<dyn Fn() -> AnyElement>;
17type SelectChoice = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
18
19/// One selectable option in a [`ChoiceTile`] anchored menu.
20pub struct ChoiceOption {
21    id: SharedString,
22    label: SharedString,
23    supporting: Option<SharedString>,
24    leading: Option<LeadingFactory>,
25    disabled: bool,
26}
27
28impl ChoiceOption {
29    /// Creates a selectable choice option with a stable identifier and visible label.
30    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
31        Self {
32            id: id.into(),
33            label: label.into(),
34            supporting: None,
35            leading: None,
36            disabled: false,
37        }
38    }
39
40    /// Sets optional supporting text shown below the option label in the popup menu.
41    pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
42        self.supporting = Some(text.into());
43        self
44    }
45
46    /// Supplies a repeatable leading icon or graphic for the option row in the popup menu.
47    pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
48        self.leading = Some(Rc::new(move || build().into_any_element()));
49        self
50    }
51
52    /// Disables selecting this option in the popup menu when `true`.
53    pub fn disabled(mut self, disabled: bool) -> Self {
54        self.disabled = disabled;
55        self
56    }
57}
58
59/// Settings convenience row combining [`crate::ListItem`] with an anchored Material [`Menu`] of
60/// [`ChoiceOption`]s.
61#[derive(IntoElement)]
62pub struct ChoiceTile {
63    fields: TileFields,
64    options: Vec<ChoiceOption>,
65    selected: SharedString,
66    placeholder: Option<SharedString>,
67    menu_state: Option<Entity<DialogState>>,
68    on_select: Option<SelectChoice>,
69}
70
71impl ChoiceTile {
72    /// Creates a choice settings row with an element ID, headline label, available options, and currently selected option ID.
73    pub fn new(
74        id: impl Into<ElementId>,
75        label: impl Into<SharedString>,
76        options: impl IntoIterator<Item = ChoiceOption>,
77        selected: impl Into<SharedString>,
78    ) -> Self {
79        Self {
80            fields: TileFields::new(id, label),
81            options: options.into_iter().collect(),
82            selected: selected.into(),
83            placeholder: None,
84            menu_state: None,
85            on_select: None,
86        }
87    }
88
89    /// Sets secondary supporting text displayed below the headline.
90    pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
91        self.fields.supporting = Some(text.into());
92        self
93    }
94
95    /// Sets overline text displayed above the headline.
96    pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
97        self.fields.overline = Some(text.into());
98        self
99    }
100
101    /// Sets an optional leading icon or graphic.
102    pub fn leading(mut self, leading: impl IntoElement) -> Self {
103        self.fields.leading = Some(leading.into_any_element());
104        self
105    }
106
107    /// Sets fallback text shown on the trailing side when `selected` matches no option.
108    pub fn placeholder(mut self, text: impl Into<SharedString>) -> Self {
109        self.placeholder = Some(text.into());
110        self
111    }
112
113    /// Disables opening the menu and dims the tile when `true`.
114    pub fn disabled(mut self, disabled: bool) -> Self {
115        self.fields.disabled = disabled;
116        self
117    }
118
119    /// Sets standalone row styling (`Standard` or `Segmented`).
120    pub fn variant(mut self, variant: ListVariant) -> Self {
121        self.fields.variant = variant;
122        self
123    }
124
125    /// Overrides container and slot colors on the underlying [`crate::ListItem`].
126    pub fn colors(mut self, colors: ListItemColors) -> Self {
127        self.fields.colors = colors;
128        self
129    }
130
131    /// Uses a caller-owned focus handle for this tile.
132    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
133        self.fields.focus = Some(focus.clone());
134        self
135    }
136
137    /// Reports hover, focus, press, and disabled states through a caller-owned source.
138    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
139        self.fields.source = Some(source.clone());
140        self
141    }
142
143    /// Supplies an external `Entity<DialogState>` to observe or control popup menu visibility.
144    pub fn menu_state(mut self, state: &Entity<DialogState>) -> Self {
145        self.menu_state = Some(state.clone());
146        self
147    }
148
149    /// Invoked with the selected option's ID when the user picks an option from the menu.
150    pub fn on_select(
151        mut self,
152        handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
153    ) -> Self {
154        self.on_select = Some(Rc::new(handler));
155        self
156    }
157
158    pub(super) fn id(&self) -> &ElementId {
159        &self.fields.id
160    }
161
162    pub(super) fn custom_focus(&self) -> Option<FocusHandle> {
163        self.fields.focus.clone()
164    }
165
166    pub(super) fn takes_focus(&self) -> bool {
167        !self.fields.disabled
168    }
169
170    pub(super) fn render_in_section(
171        self,
172        resting: CornerShape,
173        selected_shape: CornerShape,
174        focus: Option<(FocusHandle, bool)>,
175        window: &mut Window,
176        cx: &mut App,
177    ) -> AnyElement {
178        let theme = current_material_theme(window, cx);
179        let rtl = theme.layout.direction == Direction::Rtl;
180        let value_color = if self.fields.disabled {
181            color(theme.colors.color(ColorRole::OnSurface)).opacity(0.38)
182        } else {
183            color(theme.colors.color(ColorRole::OnSurfaceVariant))
184        };
185
186        let current_text = self
187            .options
188            .iter()
189            .find(|option| option.id == self.selected)
190            .map(|option| option.label.clone())
191            .or(self.placeholder)
192            .unwrap_or_default();
193        let value_description = (!current_text.is_empty()).then(|| current_text.clone());
194
195        let trailing = div()
196            .flex()
197            .items_center()
198            .gap(px(4.))
199            .text_color(value_color)
200            .when(rtl, Styled::flex_row_reverse)
201            .when(!current_text.is_empty(), |row| {
202                row.child(
203                    Text::new(current_text)
204                        .id((self.fields.id.clone(), "choice-value"))
205                        .role(TypeRole::BodyMedium),
206                )
207            })
208            .child(Icon::new(IconName::ArrowDropDown).size(px(20.)));
209
210        let shapes = ListItemShapes {
211            resting: Some(resting),
212            selected: Some(selected_shape),
213            ..Default::default()
214        };
215
216        let build_row = move |fields: TileFields| {
217            let mut item = fields.into_list_item().shapes(shapes).trailing(trailing);
218            if let Some(description) = value_description {
219                item = item.aria_description(description);
220            }
221            item
222        };
223
224        if self.fields.disabled {
225            return build_row(self.fields).row(resting, selected_shape, None, window, cx);
226        }
227
228        let tile_id = self.fields.id.clone();
229        let state = self.menu_state.unwrap_or_else(|| {
230            window.use_keyed_state((tile_id.clone(), "choice-tile-menu-state"), cx, |_, cx| {
231                DialogState::new(cx)
232            })
233        });
234        let open = state.read(cx).is_open();
235        let view = window.current_view();
236        let (trigger_focus, tab_stop) = focus
237            .or_else(|| self.fields.focus.clone().map(|handle| (handle, true)))
238            .unwrap_or_else(|| {
239                let handle = window
240                    .use_keyed_state((tile_id.clone(), "choice-tile-focus"), cx, |_, cx| {
241                        cx.focus_handle()
242                    })
243                    .read(cx)
244                    .clone();
245                (handle, true)
246            });
247
248        let selected_id = self.selected;
249        let on_select = self.on_select;
250        let menu_items: Vec<MenuItem> = self
251            .options
252            .into_iter()
253            .map(|option| {
254                let is_selected = option.id == selected_id;
255                let option_id = option.id.clone();
256                let mut entry = MenuItem::new((tile_id.clone(), option.id), option.label)
257                    .selected(is_selected)
258                    .disabled(option.disabled);
259                if let Some(supporting) = option.supporting {
260                    entry = entry.supporting(move || supporting.clone());
261                }
262                if let Some(leading) = option.leading {
263                    entry = entry.leading(move || leading());
264                }
265                if let Some(callback) = on_select.clone() {
266                    entry = entry.on_activate(move |window, cx| {
267                        callback(option_id.clone(), window, cx);
268                    });
269                }
270                entry
271            })
272            .collect();
273
274        let mut fields = self.fields;
275        fields.focus = Some(trigger_focus.clone());
276
277        Menu::composed((tile_id, "menu"), menu_items, move |is_open, toggle| {
278            build_row(fields)
279                .tab_stop(tab_stop)
280                .menu_trigger(is_open, toggle)
281                .into_any_element()
282        })
283        // `Menu` mirrors `Anchor` internally via `gpui_material_foundation::logical_anchor`,
284        // so `Anchor::TopRight` aligns to the logical trailing edge in both LTR and RTL.
285        .anchor(Anchor::TopRight)
286        .open(open)
287        .on_open_change(move |requested, window, cx| {
288            state.update(cx, |dialog, cx| {
289                if requested {
290                    dialog.open(window, cx);
291                } else {
292                    dialog.close(window, cx);
293                }
294            });
295            if requested {
296                trigger_focus.focus(window, cx);
297            }
298            cx.notify(view);
299        })
300        .into_any_element()
301    }
302}
303
304impl RenderOnce for ChoiceTile {
305    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
306        let (resting, selected_shape) = if self.fields.variant == ListVariant::Segmented {
307            (CornerRole::Large.shape(), CornerRole::Large.shape())
308        } else {
309            (CornerRole::None.shape(), CornerRole::None.shape())
310        };
311        self.render_in_section(resting, selected_shape, None, window, cx)
312    }
313}