Skip to main content

fc_ui/capabilities/controls/
dropdown.rs

1use crate::capabilities::foundation::theme::use_theme;
2use crate::capabilities::primitives::icon::Icon;
3use crate::capabilities::primitives::icon_source::IconSource;
4use gpui::{prelude::FluentBuilder as _, *};
5use std::rc::Rc;
6
7actions!(dropdown, [CloseDropdown]);
8
9#[derive(Clone)]
10pub struct DropdownItem {
11    id: SharedString,
12    label: SharedString,
13    icon: Option<IconSource>,
14    disabled: bool,
15    destructive: bool,
16    on_click: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
17}
18
19impl DropdownItem {
20    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
21        Self {
22            id: id.into(),
23            label: label.into(),
24            icon: None,
25            disabled: false,
26            destructive: false,
27            on_click: None,
28        }
29    }
30
31    pub fn separator() -> Self {
32        Self {
33            id: "__separator__".into(),
34            label: "".into(),
35            icon: None,
36            disabled: true,
37            destructive: false,
38            on_click: None,
39        }
40    }
41
42    pub fn icon(mut self, icon: impl Into<IconSource>) -> Self {
43        self.icon = Some(icon.into());
44        self
45    }
46
47    pub fn disabled(mut self, disabled: bool) -> Self {
48        self.disabled = disabled;
49        self
50    }
51
52    pub fn destructive(mut self, destructive: bool) -> Self {
53        self.destructive = destructive;
54        self
55    }
56
57    pub fn on_click(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
58        self.on_click = Some(Rc::new(handler));
59        self
60    }
61
62    fn is_separator(&self) -> bool {
63        self.id.as_ref() == "__separator__"
64    }
65}
66
67pub struct DropdownState {
68    open: bool,
69    focus_handle: FocusHandle,
70}
71
72impl DropdownState {
73    pub fn new(cx: &mut Context<Self>) -> Self {
74        Self {
75            open: false,
76            focus_handle: cx.focus_handle(),
77        }
78    }
79
80    pub fn is_open(&self) -> bool {
81        self.open
82    }
83
84    pub fn toggle(&mut self, cx: &mut Context<Self>) {
85        self.open = !self.open;
86        cx.notify();
87    }
88
89    pub fn open(&mut self, cx: &mut Context<Self>) {
90        self.open = true;
91        cx.notify();
92    }
93
94    pub fn close(&mut self, cx: &mut Context<Self>) {
95        self.open = false;
96        cx.notify();
97    }
98}
99
100impl Focusable for DropdownState {
101    fn focus_handle(&self, _: &App) -> FocusHandle {
102        self.focus_handle.clone()
103    }
104}
105
106impl Render for DropdownState {
107    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
108        div()
109    }
110}
111
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum DropdownAlign {
114    Start,
115    End,
116}
117
118#[derive(IntoElement)]
119pub struct Dropdown {
120    state: Entity<DropdownState>,
121    trigger: AnyElement,
122    items: Vec<DropdownItem>,
123    align: DropdownAlign,
124    min_width: Option<Pixels>,
125    style: StyleRefinement,
126}
127
128impl Dropdown {
129    pub fn new(state: Entity<DropdownState>, trigger: impl IntoElement) -> Self {
130        Self {
131            state,
132            trigger: trigger.into_any_element(),
133            items: Vec::new(),
134            align: DropdownAlign::Start,
135            min_width: Some(px(180.0)),
136            style: StyleRefinement::default(),
137        }
138    }
139
140    pub fn items(mut self, items: Vec<DropdownItem>) -> Self {
141        self.items = items;
142        self
143    }
144
145    pub fn align(mut self, align: DropdownAlign) -> Self {
146        self.align = align;
147        self
148    }
149
150    pub fn min_width(mut self, width: Pixels) -> Self {
151        self.min_width = Some(width);
152        self
153    }
154}
155
156impl Styled for Dropdown {
157    fn style(&mut self) -> &mut StyleRefinement {
158        &mut self.style
159    }
160}
161
162impl RenderOnce for Dropdown {
163    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
164        let theme = use_theme(cx);
165        let user_style = self.style;
166        let is_open = self.state.read(cx).open;
167        let focus_handle = self.state.read(cx).focus_handle(cx);
168        let state = self.state.clone();
169
170        div()
171            .relative()
172            .key_context("Dropdown")
173            .track_focus(&focus_handle.clone().tab_index(0).tab_stop(true))
174            .on_action(
175                window.listener_for(&state, |state, _: &CloseDropdown, _, cx| {
176                    if state.open {
177                        state.close(cx);
178                    }
179                }),
180            )
181            .on_key_down(
182                window.listener_for(&state, move |state, event: &KeyDownEvent, _, cx| {
183                    if event.keystroke.key == "escape" && state.open {
184                        cx.stop_propagation();
185                        state.close(cx);
186                    }
187                }),
188            )
189            .on_mouse_down_out(window.listener_for(&state, |state, _, _, cx| {
190                if state.open {
191                    state.close(cx);
192                }
193            }))
194            .child(
195                div()
196                    .id("dropdown-trigger")
197                    .cursor_pointer()
198                    .on_click({
199                        let state = state.clone();
200                        let focus_handle = focus_handle.clone();
201                        move |_, window, cx| {
202                            state.update(cx, |s, cx| s.toggle(cx));
203                            if state.read(cx).is_open() {
204                                window.focus(&focus_handle);
205                            }
206                        }
207                    })
208                    .child(self.trigger),
209            )
210            .when(is_open, |this| {
211                this.child(
212                    div()
213                        .absolute()
214                        .top_full()
215                        .mt(px(4.0))
216                        .when(self.align == DropdownAlign::Start, |d| d.left_0())
217                        .when(self.align == DropdownAlign::End, |d| d.right_0())
218                        .when_some(self.min_width, |d, w| d.min_w(w))
219                        .bg(theme.tokens.popover)
220                        .border_1()
221                        .border_color(theme.tokens.border)
222                        .rounded(theme.tokens.radius_md)
223                        .shadow(smallvec::smallvec![BoxShadow {
224                            color: hsla(0.0, 0.0, 0.0, 0.15),
225                            offset: point(px(0.0), px(4.0)),
226                            blur_radius: px(12.0),
227                            spread_radius: px(0.0),
228                            inset: false,
229                        }])
230                        .py(px(4.0))
231                        .children(self.items.iter().map(|item| {
232                            if item.is_separator() {
233                                return div()
234                                    .h(px(1.0))
235                                    .mx(px(8.0))
236                                    .my(px(4.0))
237                                    .bg(theme.tokens.border)
238                                    .into_any_element();
239                            }
240
241                            let text_color = if item.disabled {
242                                theme.tokens.muted_foreground
243                            } else if item.destructive {
244                                theme.tokens.destructive
245                            } else {
246                                theme.tokens.foreground
247                            };
248
249                            let hover_bg = if item.destructive {
250                                theme.tokens.destructive.opacity(0.1)
251                            } else {
252                                theme.tokens.accent
253                            };
254
255                            let on_click = item.on_click.clone();
256                            let state_for_click = state.clone();
257                            let disabled = item.disabled;
258
259                            div()
260                                .id(item.id.clone())
261                                .flex()
262                                .items_center()
263                                .gap(px(8.0))
264                                .px(px(12.0))
265                                .py(px(8.0))
266                                .mx(px(4.0))
267                                .rounded(px(4.0))
268                                .text_size(px(14.0))
269                                .text_color(text_color)
270                                .font_family(theme.tokens.font_family.clone())
271                                .when(!disabled, |d| {
272                                    d.cursor_pointer().hover(move |s| s.bg(hover_bg))
273                                })
274                                .when(!disabled, move |d| {
275                                    d.on_click(move |_, window, cx| {
276                                        if let Some(ref handler) = on_click {
277                                            handler(window, cx);
278                                        }
279                                        state_for_click.update(cx, |s, cx| s.close(cx));
280                                    })
281                                })
282                                .when_some(item.icon.as_ref(), |d, icon| {
283                                    d.child(
284                                        Icon::new(icon.clone()).size(px(16.0)).color(text_color),
285                                    )
286                                })
287                                .child(item.label.clone())
288                                .into_any_element()
289                        })),
290                )
291            })
292            .map(|this| {
293                let mut div = this;
294                div.style().refine(&user_style);
295                div
296            })
297    }
298}
299
300/// Initialize dropdown key bindings
301pub fn init_dropdown(cx: &mut App) {
302    if !crate::capabilities::foundation::initialization::begin(cx, "dropdown") {
303        return;
304    }
305    cx.bind_keys([KeyBinding::new("escape", CloseDropdown, Some("Dropdown"))]);
306}