toolbar.rs

  1use crate::ItemHandle;
  2use gpui::{
  3    AnyView, Div, Entity, EntityId, EventEmitter, ParentComponent, Render, Styled, View,
  4    ViewContext, WindowContext,
  5};
  6use theme2::ActiveTheme;
  7use ui::{h_stack, v_stack, Button, Icon, IconButton, Label, TextColor};
  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<Self>;
 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)
 87            .child(
 88                h_stack()
 89                    .justify_between()
 90                    .child(
 91                        // Toolbar left side
 92                        h_stack()
 93                            .p_1()
 94                            .child(Button::new("crates"))
 95                            .child(Label::new("/").color(TextColor::Muted))
 96                            .child(Button::new("workspace2")),
 97                    )
 98                    // Toolbar right side
 99                    .child(
100                        h_stack()
101                            .p_1()
102                            .child(IconButton::new("buffer-search", Icon::MagnifyingGlass))
103                            .child(IconButton::new("inline-assist", Icon::MagicWand)),
104                    ),
105            )
106            .children(self.items.iter().map(|(child, _)| child.to_any()))
107    }
108}
109
110// todo!()
111// impl View for Toolbar {
112//     fn ui_name() -> &'static str {
113//         "Toolbar"
114//     }
115
116//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
117//         let theme = &theme::current(cx).workspace.toolbar;
118
119//         let mut primary_left_items = Vec::new();
120//         let mut primary_right_items = Vec::new();
121//         let mut secondary_item = None;
122//         let spacing = theme.item_spacing;
123//         let mut primary_items_row_count = 1;
124
125//         for (item, position) in &self.items {
126//             match *position {
127//                 ToolbarItemLocation::Hidden => {}
128
129//                 ToolbarItemLocation::PrimaryLeft { flex } => {
130//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
131//                     let left_item = ChildView::new(item.as_any(), cx).aligned();
132//                     if let Some((flex, expanded)) = flex {
133//                         primary_left_items.push(left_item.flex(flex, expanded).into_any());
134//                     } else {
135//                         primary_left_items.push(left_item.into_any());
136//                     }
137//                 }
138
139//                 ToolbarItemLocation::PrimaryRight { flex } => {
140//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
141//                     let right_item = ChildView::new(item.as_any(), cx).aligned().flex_float();
142//                     if let Some((flex, expanded)) = flex {
143//                         primary_right_items.push(right_item.flex(flex, expanded).into_any());
144//                     } else {
145//                         primary_right_items.push(right_item.into_any());
146//                     }
147//                 }
148
149//                 ToolbarItemLocation::Secondary => {
150//                     secondary_item = Some(
151//                         ChildView::new(item.as_any(), cx)
152//                             .constrained()
153//                             .with_height(theme.height * item.row_count(cx) as f32)
154//                             .into_any(),
155//                     );
156//                 }
157//             }
158//         }
159
160//         let container_style = theme.container;
161//         let height = theme.height * primary_items_row_count as f32;
162
163//         let mut primary_items = Flex::row().with_spacing(spacing);
164//         primary_items.extend(primary_left_items);
165//         primary_items.extend(primary_right_items);
166
167//         let mut toolbar = Flex::column();
168//         if !primary_items.is_empty() {
169//             toolbar.add_child(primary_items.constrained().with_height(height));
170//         }
171//         if let Some(secondary_item) = secondary_item {
172//             toolbar.add_child(secondary_item);
173//         }
174
175//         if toolbar.is_empty() {
176//             toolbar.into_any_named("toolbar")
177//         } else {
178//             toolbar
179//                 .contained()
180//                 .with_style(container_style)
181//                 .into_any_named("toolbar")
182//         }
183//     }
184// }
185
186impl Toolbar {
187    pub fn new() -> Self {
188        Self {
189            active_item: None,
190            items: Default::default(),
191            hidden: false,
192            can_navigate: true,
193        }
194    }
195
196    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
197        self.can_navigate = can_navigate;
198        cx.notify();
199    }
200
201    pub fn add_item<T>(&mut self, item: View<T>, cx: &mut ViewContext<Self>)
202    where
203        T: 'static + ToolbarItemView,
204    {
205        let location = item.set_active_pane_item(self.active_item.as_deref(), cx);
206        cx.subscribe(&item, |this, item, event, cx| {
207            if let Some((_, current_location)) =
208                this.items.iter_mut().find(|(i, _)| i.id() == item.id())
209            {
210                match event {
211                    ToolbarItemEvent::ChangeLocation(new_location) => {
212                        if new_location != current_location {
213                            *current_location = *new_location;
214                            cx.notify();
215                        }
216                    }
217                }
218            }
219        })
220        .detach();
221        self.items.push((Box::new(item), location));
222        cx.notify();
223    }
224
225    pub fn set_active_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
226        self.active_item = item.map(|item| item.boxed_clone());
227        self.hidden = self
228            .active_item
229            .as_ref()
230            .map(|item| !item.show_toolbar(cx))
231            .unwrap_or(false);
232
233        for (toolbar_item, current_location) in self.items.iter_mut() {
234            let new_location = toolbar_item.set_active_pane_item(item, cx);
235            if new_location != *current_location {
236                *current_location = new_location;
237                cx.notify();
238            }
239        }
240    }
241
242    pub fn focus_changed(&mut self, focused: bool, cx: &mut ViewContext<Self>) {
243        for (toolbar_item, _) in self.items.iter_mut() {
244            toolbar_item.focus_changed(focused, cx);
245        }
246    }
247
248    pub fn item_of_type<T: ToolbarItemView>(&self) -> Option<View<T>> {
249        self.items
250            .iter()
251            .find_map(|(item, _)| item.to_any().downcast().ok())
252    }
253
254    pub fn hidden(&self) -> bool {
255        self.hidden
256    }
257}
258
259impl<T: ToolbarItemView> ToolbarItemViewHandle for View<T> {
260    fn id(&self) -> EntityId {
261        self.entity_id()
262    }
263
264    fn to_any(&self) -> AnyView {
265        self.clone().into()
266    }
267
268    fn set_active_pane_item(
269        &self,
270        active_pane_item: Option<&dyn ItemHandle>,
271        cx: &mut WindowContext,
272    ) -> ToolbarItemLocation {
273        self.update(cx, |this, cx| {
274            this.set_active_pane_item(active_pane_item, cx)
275        })
276    }
277
278    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext) {
279        self.update(cx, |this, cx| {
280            this.pane_focus_update(pane_focused, cx);
281            cx.notify();
282        });
283    }
284
285    fn row_count(&self, cx: &WindowContext) -> usize {
286        self.read(cx).row_count(cx)
287    }
288}
289
290// todo!()
291// impl From<&dyn ToolbarItemViewHandle> for AnyViewHandle {
292//     fn from(val: &dyn ToolbarItemViewHandle) -> Self {
293//         val.as_any().clone()
294//     }
295// }