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