toolbar.rs

  1use crate::ItemHandle;
  2use gpui::{
  3    AnyView, Div, Entity, EntityId, EventEmitter, ParentElement as _, Render, Styled, View,
  4    ViewContext, WindowContext,
  5};
  6use theme2::ActiveTheme;
  7use ui::{h_stack, v_stack, Button, Color, Icon, IconButton, Label};
  8
  9pub enum ToolbarItemEvent {
 10    ChangeLocation(ToolbarItemLocation),
 11}
 12
 13pub trait ToolbarItemView: Render + EventEmitter<ToolbarItemEvent> {
 14    fn set_active_pane_item(
 15        &mut self,
 16        active_pane_item: Option<&dyn crate::ItemHandle>,
 17        cx: &mut ViewContext<Self>,
 18    ) -> ToolbarItemLocation;
 19
 20    fn pane_focus_update(&mut self, _pane_focused: bool, _cx: &mut ViewContext<Self>) {}
 21
 22    /// Number of times toolbar's height will be repeated to get the effective height.
 23    /// Useful when multiple rows one under each other are needed.
 24    /// The rows have the same width and act as a whole when reacting to resizes and similar events.
 25    fn row_count(&self, _cx: &WindowContext) -> usize {
 26        1
 27    }
 28}
 29
 30trait ToolbarItemViewHandle: Send {
 31    fn id(&self) -> EntityId;
 32    fn to_any(&self) -> AnyView;
 33    fn set_active_pane_item(
 34        &self,
 35        active_pane_item: Option<&dyn ItemHandle>,
 36        cx: &mut WindowContext,
 37    ) -> ToolbarItemLocation;
 38    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext);
 39    fn row_count(&self, cx: &WindowContext) -> usize;
 40}
 41
 42#[derive(Copy, Clone, Debug, PartialEq)]
 43pub enum ToolbarItemLocation {
 44    Hidden,
 45    PrimaryLeft,
 46    PrimaryRight,
 47    Secondary,
 48}
 49
 50pub struct Toolbar {
 51    active_item: Option<Box<dyn ItemHandle>>,
 52    hidden: bool,
 53    can_navigate: bool,
 54    items: Vec<(Box<dyn ToolbarItemViewHandle>, ToolbarItemLocation)>,
 55}
 56
 57impl Toolbar {
 58    fn left_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 59        self.items.iter().filter_map(|(item, location)| {
 60            if *location == ToolbarItemLocation::PrimaryLeft {
 61                Some(item.as_ref())
 62            } else {
 63                None
 64            }
 65        })
 66    }
 67
 68    fn right_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 69        self.items.iter().filter_map(|(item, location)| {
 70            if *location == ToolbarItemLocation::PrimaryRight {
 71                Some(item.as_ref())
 72            } else {
 73                None
 74            }
 75        })
 76    }
 77}
 78
 79impl Render for Toolbar {
 80    type Element = Div;
 81
 82    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
 83        //dbg!(&self.items.len());
 84        v_stack()
 85            .border_b()
 86            .border_color(cx.theme().colors().border_variant)
 87            .bg(cx.theme().colors().toolbar_background)
 88            .child(
 89                h_stack()
 90                    .justify_between()
 91                    .child(
 92                        // Toolbar left side
 93                        h_stack()
 94                            .p_1()
 95                            .child(Button::new("crates"))
 96                            .child(Label::new("/").color(Color::Muted))
 97                            .child(Button::new("workspace2")),
 98                    )
 99                    // Toolbar right side
100                    .child(
101                        h_stack()
102                            .p_1()
103                            .child(IconButton::new("buffer-search", Icon::MagnifyingGlass))
104                            .child(IconButton::new("inline-assist", Icon::MagicWand)),
105                    ),
106            )
107            .children(self.items.iter().map(|(child, _)| child.to_any()))
108    }
109}
110
111// todo!()
112// impl View for Toolbar {
113//     fn ui_name() -> &'static str {
114//         "Toolbar"
115//     }
116
117//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
118//         let theme = &theme::current(cx).workspace.toolbar;
119
120//         let mut primary_left_items = Vec::new();
121//         let mut primary_right_items = Vec::new();
122//         let mut secondary_item = None;
123//         let spacing = theme.item_spacing;
124//         let mut primary_items_row_count = 1;
125
126//         for (item, position) in &self.items {
127//             match *position {
128//                 ToolbarItemLocation::Hidden => {}
129
130//                 ToolbarItemLocation::PrimaryLeft { flex } => {
131//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
132//                     let left_item = ChildView::new(item.as_any(), cx).aligned();
133//                     if let Some((flex, expanded)) = flex {
134//                         primary_left_items.push(left_item.flex(flex, expanded).into_any());
135//                     } else {
136//                         primary_left_items.push(left_item.into_any());
137//                     }
138//                 }
139
140//                 ToolbarItemLocation::PrimaryRight { flex } => {
141//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
142//                     let right_item = ChildView::new(item.as_any(), cx).aligned().flex_float();
143//                     if let Some((flex, expanded)) = flex {
144//                         primary_right_items.push(right_item.flex(flex, expanded).into_any());
145//                     } else {
146//                         primary_right_items.push(right_item.into_any());
147//                     }
148//                 }
149
150//                 ToolbarItemLocation::Secondary => {
151//                     secondary_item = Some(
152//                         ChildView::new(item.as_any(), cx)
153//                             .constrained()
154//                             .with_height(theme.height * item.row_count(cx) as f32)
155//                             .into_any(),
156//                     );
157//                 }
158//             }
159//         }
160
161//         let container_style = theme.container;
162//         let height = theme.height * primary_items_row_count as f32;
163
164//         let mut primary_items = Flex::row().with_spacing(spacing);
165//         primary_items.extend(primary_left_items);
166//         primary_items.extend(primary_right_items);
167
168//         let mut toolbar = Flex::column();
169//         if !primary_items.is_empty() {
170//             toolbar.add_child(primary_items.constrained().with_height(height));
171//         }
172//         if let Some(secondary_item) = secondary_item {
173//             toolbar.add_child(secondary_item);
174//         }
175
176//         if toolbar.is_empty() {
177//             toolbar.into_any_named("toolbar")
178//         } else {
179//             toolbar
180//                 .contained()
181//                 .with_style(container_style)
182//                 .into_any_named("toolbar")
183//         }
184//     }
185// }
186
187impl Toolbar {
188    pub fn new() -> Self {
189        Self {
190            active_item: None,
191            items: Default::default(),
192            hidden: false,
193            can_navigate: true,
194        }
195    }
196
197    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
198        self.can_navigate = can_navigate;
199        cx.notify();
200    }
201
202    pub fn add_item<T>(&mut self, item: View<T>, cx: &mut ViewContext<Self>)
203    where
204        T: 'static + ToolbarItemView,
205    {
206        let location = item.set_active_pane_item(self.active_item.as_deref(), cx);
207        cx.subscribe(&item, |this, item, event, cx| {
208            if let Some((_, current_location)) =
209                this.items.iter_mut().find(|(i, _)| i.id() == item.id())
210            {
211                match event {
212                    ToolbarItemEvent::ChangeLocation(new_location) => {
213                        if new_location != current_location {
214                            *current_location = *new_location;
215                            cx.notify();
216                        }
217                    }
218                }
219            }
220        })
221        .detach();
222        self.items.push((Box::new(item), location));
223        cx.notify();
224    }
225
226    pub fn set_active_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
227        self.active_item = item.map(|item| item.boxed_clone());
228        self.hidden = self
229            .active_item
230            .as_ref()
231            .map(|item| !item.show_toolbar(cx))
232            .unwrap_or(false);
233
234        for (toolbar_item, current_location) in self.items.iter_mut() {
235            let new_location = toolbar_item.set_active_pane_item(item, cx);
236            if new_location != *current_location {
237                *current_location = new_location;
238                cx.notify();
239            }
240        }
241    }
242
243    pub fn focus_changed(&mut self, focused: bool, cx: &mut ViewContext<Self>) {
244        for (toolbar_item, _) in self.items.iter_mut() {
245            toolbar_item.focus_changed(focused, cx);
246        }
247    }
248
249    pub fn item_of_type<T: ToolbarItemView>(&self) -> Option<View<T>> {
250        self.items
251            .iter()
252            .find_map(|(item, _)| item.to_any().downcast().ok())
253    }
254
255    pub fn hidden(&self) -> bool {
256        self.hidden
257    }
258}
259
260impl<T: ToolbarItemView> ToolbarItemViewHandle for View<T> {
261    fn id(&self) -> EntityId {
262        self.entity_id()
263    }
264
265    fn to_any(&self) -> AnyView {
266        self.clone().into()
267    }
268
269    fn set_active_pane_item(
270        &self,
271        active_pane_item: Option<&dyn ItemHandle>,
272        cx: &mut WindowContext,
273    ) -> ToolbarItemLocation {
274        self.update(cx, |this, cx| {
275            this.set_active_pane_item(active_pane_item, cx)
276        })
277    }
278
279    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext) {
280        self.update(cx, |this, cx| {
281            this.pane_focus_update(pane_focused, cx);
282            cx.notify();
283        });
284    }
285
286    fn row_count(&self, cx: &WindowContext) -> usize {
287        self.read(cx).row_count(cx)
288    }
289}
290
291// todo!()
292// impl From<&dyn ToolbarItemViewHandle> for AnyViewHandle {
293//     fn from(val: &dyn ToolbarItemViewHandle) -> Self {
294//         val.as_any().clone()
295//     }
296// }