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