toolbar.rs

  1use crate::ItemHandle;
  2use gpui::{
  3    AnyView, Entity, EntityId, EventEmitter, ParentElement as _, Render, Styled, View, ViewContext,
  4    WindowContext,
  5};
  6use ui::prelude::*;
  7use ui::{h_flex, v_flex};
  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
 23trait ToolbarItemViewHandle: Send {
 24    fn id(&self) -> EntityId;
 25    fn to_any(&self) -> AnyView;
 26    fn set_active_pane_item(
 27        &self,
 28        active_pane_item: Option<&dyn ItemHandle>,
 29        cx: &mut WindowContext,
 30    ) -> ToolbarItemLocation;
 31    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext);
 32}
 33
 34#[derive(Copy, Clone, Debug, PartialEq)]
 35pub enum ToolbarItemLocation {
 36    Hidden,
 37    PrimaryLeft,
 38    PrimaryRight,
 39    Secondary,
 40}
 41
 42pub struct Toolbar {
 43    active_item: Option<Box<dyn ItemHandle>>,
 44    hidden: bool,
 45    can_navigate: bool,
 46    items: Vec<(Box<dyn ToolbarItemViewHandle>, ToolbarItemLocation)>,
 47}
 48
 49impl Toolbar {
 50    fn has_any_visible_items(&self) -> bool {
 51        self.items
 52            .iter()
 53            .any(|(_item, location)| *location != ToolbarItemLocation::Hidden)
 54    }
 55
 56    fn left_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 57        self.items.iter().filter_map(|(item, location)| {
 58            if *location == ToolbarItemLocation::PrimaryLeft {
 59                Some(item.as_ref())
 60            } else {
 61                None
 62            }
 63        })
 64    }
 65
 66    fn right_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 67        self.items.iter().filter_map(|(item, location)| {
 68            if *location == ToolbarItemLocation::PrimaryRight {
 69                Some(item.as_ref())
 70            } else {
 71                None
 72            }
 73        })
 74    }
 75
 76    fn secondary_items(&self) -> impl Iterator<Item = &dyn ToolbarItemViewHandle> {
 77        self.items.iter().filter_map(|(item, location)| {
 78            if *location == ToolbarItemLocation::Secondary {
 79                Some(item.as_ref())
 80            } else {
 81                None
 82            }
 83        })
 84    }
 85}
 86
 87impl Render for Toolbar {
 88    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
 89        if !self.has_any_visible_items() {
 90            return div();
 91        }
 92
 93        let secondary_item = self.secondary_items().next().map(|item| item.to_any());
 94
 95        let has_left_items = self.left_items().count() > 0;
 96        let has_right_items = self.right_items().count() > 0;
 97
 98        v_flex()
 99            .group("toolbar")
100            .p(DynamicSpacing::Base08.rems(cx))
101            .when(has_left_items || has_right_items, |this| {
102                this.gap(DynamicSpacing::Base08.rems(cx))
103            })
104            .border_b_1()
105            .border_color(cx.theme().colors().border_variant)
106            .bg(cx.theme().colors().toolbar_background)
107            .when(has_left_items || has_right_items, |this| {
108                this.child(
109                    h_flex()
110                        .min_h(rems_from_px(24.))
111                        .justify_between()
112                        .gap(DynamicSpacing::Base08.rems(cx))
113                        .when(has_left_items, |this| {
114                            this.child(
115                                h_flex()
116                                    .flex_auto()
117                                    .justify_start()
118                                    .overflow_x_hidden()
119                                    .children(self.left_items().map(|item| item.to_any())),
120                            )
121                        })
122                        .when(has_right_items, |this| {
123                            this.child(
124                                h_flex()
125                                    .map(|el| {
126                                        if has_left_items {
127                                            // We're using `flex_none` here to prevent some flickering that can occur when the
128                                            // size of the left items container changes.
129                                            el.flex_none()
130                                        } else {
131                                            el.flex_auto()
132                                        }
133                                    })
134                                    .justify_end()
135                                    .children(self.right_items().map(|item| item.to_any())),
136                            )
137                        }),
138                )
139            })
140            .children(secondary_item)
141    }
142}
143
144impl Default for Toolbar {
145    fn default() -> Self {
146        Self::new()
147    }
148}
149
150impl Toolbar {
151    pub fn new() -> Self {
152        Self {
153            active_item: None,
154            items: Default::default(),
155            hidden: false,
156            can_navigate: true,
157        }
158    }
159
160    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
161        self.can_navigate = can_navigate;
162        cx.notify();
163    }
164
165    pub fn add_item<T>(&mut self, item: View<T>, cx: &mut ViewContext<Self>)
166    where
167        T: 'static + ToolbarItemView,
168    {
169        let location = item.set_active_pane_item(self.active_item.as_deref(), cx);
170        cx.subscribe(&item, |this, item, event, cx| {
171            if let Some((_, current_location)) = this
172                .items
173                .iter_mut()
174                .find(|(i, _)| i.id() == item.entity_id())
175            {
176                match event {
177                    ToolbarItemEvent::ChangeLocation(new_location) => {
178                        if new_location != current_location {
179                            *current_location = *new_location;
180                            cx.notify();
181                        }
182                    }
183                }
184            }
185        })
186        .detach();
187        self.items.push((Box::new(item), location));
188        cx.notify();
189    }
190
191    pub fn set_active_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext<Self>) {
192        self.active_item = item.map(|item| item.boxed_clone());
193        self.hidden = self
194            .active_item
195            .as_ref()
196            .map(|item| !item.show_toolbar(cx))
197            .unwrap_or(false);
198
199        for (toolbar_item, current_location) in self.items.iter_mut() {
200            let new_location = toolbar_item.set_active_pane_item(item, cx);
201            if new_location != *current_location {
202                *current_location = new_location;
203                cx.notify();
204            }
205        }
206    }
207
208    pub fn focus_changed(&mut self, focused: bool, cx: &mut ViewContext<Self>) {
209        for (toolbar_item, _) in self.items.iter_mut() {
210            toolbar_item.focus_changed(focused, cx);
211        }
212    }
213
214    pub fn item_of_type<T: ToolbarItemView>(&self) -> Option<View<T>> {
215        self.items
216            .iter()
217            .find_map(|(item, _)| item.to_any().downcast().ok())
218    }
219
220    pub fn hidden(&self) -> bool {
221        self.hidden
222    }
223}
224
225impl<T: ToolbarItemView> ToolbarItemViewHandle for View<T> {
226    fn id(&self) -> EntityId {
227        self.entity_id()
228    }
229
230    fn to_any(&self) -> AnyView {
231        self.clone().into()
232    }
233
234    fn set_active_pane_item(
235        &self,
236        active_pane_item: Option<&dyn ItemHandle>,
237        cx: &mut WindowContext,
238    ) -> ToolbarItemLocation {
239        self.update(cx, |this, cx| {
240            this.set_active_pane_item(active_pane_item, cx)
241        })
242    }
243
244    fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext) {
245        self.update(cx, |this, cx| {
246            this.pane_focus_update(pane_focused, cx);
247            cx.notify();
248        });
249    }
250}