toolbar.rs

  1use crate::ItemHandle;
  2use gpui::{
  3    AnyView, App, Context, Entity, EntityId, EventEmitter, ParentElement as _, Render, Styled,
  4    Window,
  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        window: &mut Window,
 18        cx: &mut Context<Self>,
 19    ) -> ToolbarItemLocation;
 20
 21    fn pane_focus_update(
 22        &mut self,
 23        _pane_focused: bool,
 24        _window: &mut Window,
 25        _cx: &mut Context<Self>,
 26    ) {
 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        window: &mut Window,
 37        cx: &mut App,
 38    ) -> ToolbarItemLocation;
 39    fn focus_changed(&mut self, pane_focused: bool, window: &mut Window, cx: &mut App);
 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().rev().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    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 97        if !self.has_any_visible_items() {
 98            return div();
 99        }
100
101        let secondary_items = self.secondary_items().map(|item| item.to_any());
102
103        let has_left_items = self.left_items().count() > 0;
104        let has_right_items = self.right_items().count() > 0;
105
106        v_flex()
107            .group("toolbar")
108            .p(DynamicSpacing::Base08.rems(cx))
109            .when(has_left_items || has_right_items, |this| {
110                this.gap(DynamicSpacing::Base08.rems(cx))
111            })
112            .border_b_1()
113            .border_color(cx.theme().colors().border_variant)
114            .bg(cx.theme().colors().toolbar_background)
115            .when(has_left_items || has_right_items, |this| {
116                this.child(
117                    h_flex()
118                        .min_h(rems_from_px(24.))
119                        .justify_between()
120                        .gap(DynamicSpacing::Base08.rems(cx))
121                        .when(has_left_items, |this| {
122                            this.child(
123                                h_flex()
124                                    .flex_auto()
125                                    .justify_start()
126                                    .overflow_x_hidden()
127                                    .children(self.left_items().map(|item| item.to_any())),
128                            )
129                        })
130                        .when(has_right_items, |this| {
131                            this.child(
132                                h_flex()
133                                    .map(|el| {
134                                        if has_left_items {
135                                            // We're using `flex_none` here to prevent some flickering that can occur when the
136                                            // size of the left items container changes.
137                                            el.flex_none()
138                                        } else {
139                                            el.flex_auto()
140                                        }
141                                    })
142                                    .justify_end()
143                                    .children(self.right_items().map(|item| item.to_any())),
144                            )
145                        }),
146                )
147            })
148            .children(secondary_items)
149    }
150}
151
152impl Default for Toolbar {
153    fn default() -> Self {
154        Self::new()
155    }
156}
157
158impl Toolbar {
159    pub fn new() -> Self {
160        Self {
161            active_item: None,
162            items: Default::default(),
163            hidden: false,
164            can_navigate: true,
165        }
166    }
167
168    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut Context<Self>) {
169        self.can_navigate = can_navigate;
170        cx.notify();
171    }
172
173    pub fn add_item<T>(&mut self, item: Entity<T>, window: &mut Window, cx: &mut Context<Self>)
174    where
175        T: 'static + ToolbarItemView,
176    {
177        let location = item.set_active_pane_item(self.active_item.as_deref(), window, cx);
178        cx.subscribe(&item, |this, item, event, cx| {
179            if let Some((_, current_location)) = this
180                .items
181                .iter_mut()
182                .find(|(i, _)| i.id() == item.entity_id())
183            {
184                match event {
185                    ToolbarItemEvent::ChangeLocation(new_location) => {
186                        if new_location != current_location {
187                            *current_location = *new_location;
188                            cx.notify();
189                        }
190                    }
191                }
192            }
193        })
194        .detach();
195        self.items.push((Box::new(item), location));
196        cx.notify();
197    }
198
199    pub fn set_active_item(
200        &mut self,
201        item: Option<&dyn ItemHandle>,
202        window: &mut Window,
203        cx: &mut Context<Self>,
204    ) {
205        self.active_item = item.map(|item| item.boxed_clone());
206        self.hidden = self
207            .active_item
208            .as_ref()
209            .map(|item| !item.show_toolbar(cx))
210            .unwrap_or(false);
211
212        for (toolbar_item, current_location) in self.items.iter_mut() {
213            let new_location = toolbar_item.set_active_pane_item(item, window, cx);
214            if new_location != *current_location {
215                *current_location = new_location;
216                cx.notify();
217            }
218        }
219    }
220
221    pub fn focus_changed(&mut self, focused: bool, window: &mut Window, cx: &mut Context<Self>) {
222        for (toolbar_item, _) in self.items.iter_mut() {
223            toolbar_item.focus_changed(focused, window, cx);
224        }
225    }
226
227    pub fn item_of_type<T: ToolbarItemView>(&self) -> Option<Entity<T>> {
228        self.items
229            .iter()
230            .find_map(|(item, _)| item.to_any().downcast().ok())
231    }
232
233    pub fn hidden(&self) -> bool {
234        self.hidden
235    }
236}
237
238impl<T: ToolbarItemView> ToolbarItemViewHandle for Entity<T> {
239    fn id(&self) -> EntityId {
240        self.entity_id()
241    }
242
243    fn to_any(&self) -> AnyView {
244        self.clone().into()
245    }
246
247    fn set_active_pane_item(
248        &self,
249        active_pane_item: Option<&dyn ItemHandle>,
250        window: &mut Window,
251        cx: &mut App,
252    ) -> ToolbarItemLocation {
253        self.update(cx, |this, cx| {
254            this.set_active_pane_item(active_pane_item, window, cx)
255        })
256    }
257
258    fn focus_changed(&mut self, pane_focused: bool, window: &mut Window, cx: &mut App) {
259        self.update(cx, |this, cx| {
260            this.pane_focus_update(pane_focused, window, cx);
261            cx.notify();
262        });
263    }
264}