kitchen_ui/widgets/
menu_select.rs1use std::rc::Rc;
4
5use gpui_kit::component::button::Button;
6use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
7use gpui_kit::component::{Icon, IconName, Sizable as _, h_flex};
8use gpui_kit::{
9 App, ElementId, IntoElement, ParentElement as _, RenderOnce, SharedString, Styled as _, Window, div, px,
10};
11
12type OnPick = Rc<dyn Fn(usize, &mut Window, &mut App)>;
13
14const MENU_MAX_H: f32 = 360.;
16
17#[derive(IntoElement)]
21pub struct MenuSelect {
22 id: ElementId,
23 options: Vec<SharedString>,
24 selected: Option<usize>,
25 placeholder: SharedString,
26 on_pick: OnPick,
27}
28
29impl MenuSelect {
30 pub fn new(
32 id: impl Into<ElementId>,
33 options: Vec<SharedString>,
34 selected: Option<usize>,
35 on_pick: impl Fn(usize, &mut Window, &mut App) + 'static,
36 ) -> Self {
37 Self { id: id.into(), options, selected, placeholder: "Choose…".into(), on_pick: Rc::new(on_pick) }
38 }
39
40 pub fn placeholder(mut self, text: impl Into<SharedString>) -> Self {
42 self.placeholder = text.into();
43 self
44 }
45}
46
47impl RenderOnce for MenuSelect {
48 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
49 let Self { id, options, selected, placeholder, on_pick } = self;
50 let current = selected.and_then(|i| options.get(i).cloned()).unwrap_or(placeholder);
51 let face = h_flex()
52 .w_full()
53 .min_w_0()
54 .gap_1()
55 .child(div().flex_1().min_w_0().truncate().text_left().child(current))
56 .child(Icon::new(IconName::ChevronDown).xsmall());
57 Button::new(id).outline().small().min_w_0().w_full().child(face).cursor_pointer().dropdown_menu(
58 move |menu, _, _| {
59 let mut menu = menu.scrollable(true).max_h(px(MENU_MAX_H));
60 for (i, label) in options.iter().enumerate() {
61 let on_pick = on_pick.clone();
62 menu = menu.item(
63 PopupMenuItem::new(label.clone())
64 .checked(selected == Some(i))
65 .on_click(move |_, window, cx| on_pick(i, window, cx)),
66 );
67 }
68 menu
69 },
70 )
71 }
72}