toolbar.rs

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