toolbar.rs

  1use crate::ItemHandle;
  2use gpui::{
  3    AnyView, Div, Entity, EntityId, EventEmitter, ParentElement as _, Render, Styled, View,
  4    ViewContext, WindowContext,
  5};
  6use ui::prelude::*;
  7use ui::{h_stack, v_stack};
  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 has_any_visible_items(&self) -> bool {
 59        self.items
 60            .iter()
 61            .any(|(_item, location)| *location != ToolbarItemLocation::Hidden)
 62    }
 63
 64    fn left_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 65        self.items.iter().filter_map(|(item, location)| {
 66            if *location == ToolbarItemLocation::PrimaryLeft {
 67                Some(item.as_ref())
 68            } else {
 69                None
 70            }
 71        })
 72    }
 73
 74    fn right_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 75        self.items.iter().filter_map(|(item, location)| {
 76            if *location == ToolbarItemLocation::PrimaryRight {
 77                Some(item.as_ref())
 78            } else {
 79                None
 80            }
 81        })
 82    }
 83
 84    fn secondary_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 85        self.items.iter().filter_map(|(item, location)| {
 86            if *location == ToolbarItemLocation::Secondary {
 87                Some(item.as_ref())
 88            } else {
 89                None
 90            }
 91        })
 92    }
 93}
 94
 95impl Render for Toolbar {
 96    type Element = Div;
 97
 98    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
 99        if !self.has_any_visible_items() {
100            return div();
101        }
102
103        let secondary_item = self.secondary_items().next().map(|item| item.to_any());
104
105        v_stack()
106            .border_b()
107            .border_color(cx.theme().colors().border_variant)
108            .bg(cx.theme().colors().toolbar_background)
109            .child(
110                h_stack()
111                    .when(self.left_items().count() > 0, |this| {
112                        this.child(
113                            h_stack()
114                                .flex_1()
115                                .justify_start()
116                                .children(self.left_items().map(|item| item.to_any())),
117                        )
118                    })
119                    // Render an empty div that takes up the space between
120                    // the left and right sides. This won't cause items to
121                    // be centered like justify_center() will if left or
122                    // right is missing.
123                    .child(div().flex_1())
124                    .when(self.right_items().count() > 0, |this| {
125                        this.child(
126                            h_stack()
127                                .flex_1()
128                                .justify_end()
129                                .children(self.right_items().map(|item| item.to_any())),
130                        )
131                    }),
132            )
133            .children(secondary_item)
134    }
135}
136
137// todo!()
138// impl View for Toolbar {
139//     fn ui_name() -> &'static str {
140//         "Toolbar"
141//     }
142
143//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
144//         let theme = &theme::current(cx).workspace.toolbar;
145
146//         let mut primary_left_items = Vec::new();
147//         let mut primary_right_items = Vec::new();
148//         let mut secondary_item = None;
149//         let spacing = theme.item_spacing;
150//         let mut primary_items_row_count = 1;
151
152//         for (item, position) in &self.items {
153//             match *position {
154//                 ToolbarItemLocation::Hidden => {}
155
156//                 ToolbarItemLocation::PrimaryLeft { flex } => {
157//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
158//                     let left_item = ChildView::new(item.as_any(), cx).aligned();
159//                     if let Some((flex, expanded)) = flex {
160//                         primary_left_items.push(left_item.flex(flex, expanded).into_any());
161//                     } else {
162//                         primary_left_items.push(left_item.into_any());
163//                     }
164//                 }
165
166//                 ToolbarItemLocation::PrimaryRight { flex } => {
167//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
168//                     let right_item = ChildView::new(item.as_any(), cx).aligned().flex_float();
169//                     if let Some((flex, expanded)) = flex {
170//                         primary_right_items.push(right_item.flex(flex, expanded).into_any());
171//                     } else {
172//                         primary_right_items.push(right_item.into_any());
173//                     }
174//                 }
175
176//                 ToolbarItemLocation::Secondary => {
177//                     secondary_item = Some(
178//                         ChildView::new(item.as_any(), cx)
179//                             .constrained()
180//                             .with_height(theme.height * item.row_count(cx) as f32)
181//                             .into_any(),
182//                     );
183//                 }
184//             }
185//         }
186
187//         let container_style = theme.container;
188//         let height = theme.height * primary_items_row_count as f32;
189
190//         let mut primary_items = Flex::row().with_spacing(spacing);
191//         primary_items.extend(primary_left_items);
192//         primary_items.extend(primary_right_items);
193
194//         let mut toolbar = Flex::column();
195//         if !primary_items.is_empty() {
196//             toolbar.add_child(primary_items.constrained().with_height(height));
197//         }
198//         if let Some(secondary_item) = secondary_item {
199//             toolbar.add_child(secondary_item);
200//         }
201
202//         if toolbar.is_empty() {
203//             toolbar.into_any_named("toolbar")
204//         } else {
205//             toolbar
206//                 .contained()
207//                 .with_style(container_style)
208//                 .into_any_named("toolbar")
209//         }
210//     }
211// }
212
213impl Toolbar {
214    pub fn new() -> Self {
215        Self {
216            active_item: None,
217            items: Default::default(),
218            hidden: false,
219            can_navigate: true,
220        }
221    }
222
223    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
224        self.can_navigate = can_navigate;
225        cx.notify();
226    }
227
228    pub fn add_item<T>(&mut self, item: View<T>, cx: &mut ViewContext<Self>)
229    where
230        T: 'static + ToolbarItemView,
231    {
232        let location = item.set_active_pane_item(self.active_item.as_deref(), cx);
233        cx.subscribe(&item, |this, item, event, cx| {
234            if let Some((_, current_location)) =
235                this.items.iter_mut().find(|(i, _)| i.id() == item.id())
236            {
237                match event {
238                    ToolbarItemEvent::ChangeLocation(new_location) => {
239                        if new_location != current_location {
240                            *current_location = *new_location;
241                            cx.notify();
242                        }
243                    }
244                }
245            }
246        })
247        .detach();
248        self.items.push((Box::new(item), location));
249        cx.notify();
250    }
251
252    pub fn set_active_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
253        self.active_item = item.map(|item| item.boxed_clone());
254        self.hidden = self
255            .active_item
256            .as_ref()
257            .map(|item| !item.show_toolbar(cx))
258            .unwrap_or(false);
259
260        for (toolbar_item, current_location) in self.items.iter_mut() {
261            let new_location = toolbar_item.set_active_pane_item(item, cx);
262            if new_location != *current_location {
263                *current_location = new_location;
264                cx.notify();
265            }
266        }
267    }
268
269    pub fn focus_changed(&mut self, focused: bool, cx: &mut ViewContext<Self>) {
270        for (toolbar_item, _) in self.items.iter_mut() {
271            toolbar_item.focus_changed(focused, cx);
272        }
273    }
274
275    pub fn item_of_type<T: ToolbarItemView>(&self) -> Option<View<T>> {
276        self.items
277            .iter()
278            .find_map(|(item, _)| item.to_any().downcast().ok())
279    }
280
281    pub fn hidden(&self) -> bool {
282        self.hidden
283    }
284}
285
286impl<T: ToolbarItemView> ToolbarItemViewHandle for View<T> {
287    fn id(&self) -> EntityId {
288        self.entity_id()
289    }
290
291    fn to_any(&self) -> AnyView {
292        self.clone().into()
293    }
294
295    fn set_active_pane_item(
296        &self,
297        active_pane_item: Option<&dyn ItemHandle>,
298        cx: &mut WindowContext,
299    ) -> ToolbarItemLocation {
300        self.update(cx, |this, cx| {
301            this.set_active_pane_item(active_pane_item, cx)
302        })
303    }
304
305    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext) {
306        self.update(cx, |this, cx| {
307            this.pane_focus_update(pane_focused, cx);
308            cx.notify();
309        });
310    }
311
312    fn row_count(&self, cx: &WindowContext) -> usize {
313        self.read(cx).row_count(cx)
314    }
315}
316
317// todo!()
318// impl From<&dyn ToolbarItemViewHandle> for AnyViewHandle {
319//     fn from(val: &dyn ToolbarItemViewHandle) -> Self {
320//         val.as_any().clone()
321//     }
322// }