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            .p_1()
107            .gap_2()
108            .border_b()
109            .border_color(cx.theme().colors().border_variant)
110            .bg(cx.theme().colors().toolbar_background)
111            .child(
112                h_stack()
113                    .justify_between()
114                    .when(self.left_items().count() > 0, |this| {
115                        this.child(
116                            h_stack()
117                                .flex_1()
118                                .justify_start()
119                                .children(self.left_items().map(|item| item.to_any())),
120                        )
121                    })
122                    .when(self.right_items().count() > 0, |this| {
123                        this.child(
124                            h_stack()
125                                .flex_1()
126                                .justify_end()
127                                .children(self.right_items().map(|item| item.to_any())),
128                        )
129                    }),
130            )
131            .children(secondary_item)
132    }
133}
134
135// todo!()
136// impl View for Toolbar {
137//     fn ui_name() -> &'static str {
138//         "Toolbar"
139//     }
140
141//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
142//         let theme = &theme::current(cx).workspace.toolbar;
143
144//         let mut primary_left_items = Vec::new();
145//         let mut primary_right_items = Vec::new();
146//         let mut secondary_item = None;
147//         let spacing = theme.item_spacing;
148//         let mut primary_items_row_count = 1;
149
150//         for (item, position) in &self.items {
151//             match *position {
152//                 ToolbarItemLocation::Hidden => {}
153
154//                 ToolbarItemLocation::PrimaryLeft { flex } => {
155//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
156//                     let left_item = ChildView::new(item.as_any(), cx).aligned();
157//                     if let Some((flex, expanded)) = flex {
158//                         primary_left_items.push(left_item.flex(flex, expanded).into_any());
159//                     } else {
160//                         primary_left_items.push(left_item.into_any());
161//                     }
162//                 }
163
164//                 ToolbarItemLocation::PrimaryRight { flex } => {
165//                     primary_items_row_count = primary_items_row_count.max(item.row_count(cx));
166//                     let right_item = ChildView::new(item.as_any(), cx).aligned().flex_float();
167//                     if let Some((flex, expanded)) = flex {
168//                         primary_right_items.push(right_item.flex(flex, expanded).into_any());
169//                     } else {
170//                         primary_right_items.push(right_item.into_any());
171//                     }
172//                 }
173
174//                 ToolbarItemLocation::Secondary => {
175//                     secondary_item = Some(
176//                         ChildView::new(item.as_any(), cx)
177//                             .constrained()
178//                             .with_height(theme.height * item.row_count(cx) as f32)
179//                             .into_any(),
180//                     );
181//                 }
182//             }
183//         }
184
185//         let container_style = theme.container;
186//         let height = theme.height * primary_items_row_count as f32;
187
188//         let mut primary_items = Flex::row().with_spacing(spacing);
189//         primary_items.extend(primary_left_items);
190//         primary_items.extend(primary_right_items);
191
192//         let mut toolbar = Flex::column();
193//         if !primary_items.is_empty() {
194//             toolbar.add_child(primary_items.constrained().with_height(height));
195//         }
196//         if let Some(secondary_item) = secondary_item {
197//             toolbar.add_child(secondary_item);
198//         }
199
200//         if toolbar.is_empty() {
201//             toolbar.into_any_named("toolbar")
202//         } else {
203//             toolbar
204//                 .contained()
205//                 .with_style(container_style)
206//                 .into_any_named("toolbar")
207//         }
208//     }
209// }
210
211impl Toolbar {
212    pub fn new() -> Self {
213        Self {
214            active_item: None,
215            items: Default::default(),
216            hidden: false,
217            can_navigate: true,
218        }
219    }
220
221    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
222        self.can_navigate = can_navigate;
223        cx.notify();
224    }
225
226    pub fn add_item<T>(&mut self, item: View<T>, cx: &mut ViewContext<Self>)
227    where
228        T: 'static + ToolbarItemView,
229    {
230        let location = item.set_active_pane_item(self.active_item.as_deref(), cx);
231        cx.subscribe(&item, |this, item, event, cx| {
232            if let Some((_, current_location)) =
233                this.items.iter_mut().find(|(i, _)| i.id() == item.id())
234            {
235                match event {
236                    ToolbarItemEvent::ChangeLocation(new_location) => {
237                        if new_location != current_location {
238                            *current_location = *new_location;
239                            cx.notify();
240                        }
241                    }
242                }
243            }
244        })
245        .detach();
246        self.items.push((Box::new(item), location));
247        cx.notify();
248    }
249
250    pub fn set_active_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
251        self.active_item = item.map(|item| item.boxed_clone());
252        self.hidden = self
253            .active_item
254            .as_ref()
255            .map(|item| !item.show_toolbar(cx))
256            .unwrap_or(false);
257
258        for (toolbar_item, current_location) in self.items.iter_mut() {
259            let new_location = toolbar_item.set_active_pane_item(item, cx);
260            if new_location != *current_location {
261                *current_location = new_location;
262                cx.notify();
263            }
264        }
265    }
266
267    pub fn focus_changed(&mut self, focused: bool, cx: &mut ViewContext<Self>) {
268        for (toolbar_item, _) in self.items.iter_mut() {
269            toolbar_item.focus_changed(focused, cx);
270        }
271    }
272
273    pub fn item_of_type<T: ToolbarItemView>(&self) -> Option<View<T>> {
274        self.items
275            .iter()
276            .find_map(|(item, _)| item.to_any().downcast().ok())
277    }
278
279    pub fn hidden(&self) -> bool {
280        self.hidden
281    }
282}
283
284impl<T: ToolbarItemView> ToolbarItemViewHandle for View<T> {
285    fn id(&self) -> EntityId {
286        self.entity_id()
287    }
288
289    fn to_any(&self) -> AnyView {
290        self.clone().into()
291    }
292
293    fn set_active_pane_item(
294        &self,
295        active_pane_item: Option<&dyn ItemHandle>,
296        cx: &mut WindowContext,
297    ) -> ToolbarItemLocation {
298        self.update(cx, |this, cx| {
299            this.set_active_pane_item(active_pane_item, cx)
300        })
301    }
302
303    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext) {
304        self.update(cx, |this, cx| {
305            this.pane_focus_update(pane_focused, cx);
306            cx.notify();
307        });
308    }
309
310    fn row_count(&self, cx: &WindowContext) -> usize {
311        self.read(cx).row_count(cx)
312    }
313}
314
315// todo!()
316// impl From<&dyn ToolbarItemViewHandle> for AnyViewHandle {
317//     fn from(val: &dyn ToolbarItemViewHandle) -> Self {
318//         val.as_any().clone()
319//     }
320// }