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