sidebar.rs

  1use crate::StatusItemView;
  2use gpui::{
  3    elements::*, impl_actions, platform::CursorStyle, AnyViewHandle, AppContext, Entity,
  4    MouseButton, MouseMovedEvent, RenderContext, Subscription, View, ViewContext, ViewHandle,
  5};
  6use serde::Deserialize;
  7use settings::Settings;
  8use std::{cell::RefCell, rc::Rc};
  9use theme::Theme;
 10
 11pub trait SidebarItem: View {
 12    fn should_activate_item_on_event(&self, _: &Self::Event, _: &AppContext) -> bool {
 13        false
 14    }
 15    fn should_show_badge(&self, cx: &AppContext) -> bool;
 16    fn contains_focused_view(&self, _: &AppContext) -> bool {
 17        false
 18    }
 19}
 20
 21pub trait SidebarItemHandle {
 22    fn id(&self) -> usize;
 23    fn should_show_badge(&self, cx: &AppContext) -> bool;
 24    fn is_focused(&self, cx: &AppContext) -> bool;
 25    fn to_any(&self) -> AnyViewHandle;
 26}
 27
 28impl<T> SidebarItemHandle for ViewHandle<T>
 29where
 30    T: SidebarItem,
 31{
 32    fn id(&self) -> usize {
 33        self.id()
 34    }
 35
 36    fn should_show_badge(&self, cx: &AppContext) -> bool {
 37        self.read(cx).should_show_badge(cx)
 38    }
 39
 40    fn is_focused(&self, cx: &AppContext) -> bool {
 41        ViewHandle::is_focused(&self, cx) || self.read(cx).contains_focused_view(cx)
 42    }
 43
 44    fn to_any(&self) -> AnyViewHandle {
 45        self.into()
 46    }
 47}
 48
 49impl Into<AnyViewHandle> for &dyn SidebarItemHandle {
 50    fn into(self) -> AnyViewHandle {
 51        self.to_any()
 52    }
 53}
 54
 55pub struct Sidebar {
 56    side: Side,
 57    items: Vec<Item>,
 58    is_open: bool,
 59    active_item_ix: usize,
 60    actual_width: Rc<RefCell<f32>>,
 61    custom_width: Rc<RefCell<f32>>,
 62}
 63
 64#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
 65pub enum Side {
 66    Left,
 67    Right,
 68}
 69
 70struct Item {
 71    icon_path: &'static str,
 72    tooltip: String,
 73    view: Rc<dyn SidebarItemHandle>,
 74    _subscriptions: [Subscription; 2],
 75}
 76
 77pub struct SidebarButtons {
 78    sidebar: ViewHandle<Sidebar>,
 79}
 80
 81#[derive(Clone, Debug, Deserialize, PartialEq)]
 82pub struct ToggleSidebarItem {
 83    pub side: Side,
 84    pub item_index: usize,
 85}
 86
 87impl_actions!(workspace, [ToggleSidebarItem]);
 88
 89impl Sidebar {
 90    pub fn new(side: Side) -> Self {
 91        Self {
 92            side,
 93            items: Default::default(),
 94            active_item_ix: 0,
 95            is_open: false,
 96            actual_width: Rc::new(RefCell::new(260.)),
 97            custom_width: Rc::new(RefCell::new(260.)),
 98        }
 99    }
100
101    pub fn is_open(&self) -> bool {
102        self.is_open
103    }
104
105    pub fn active_item_ix(&self) -> usize {
106        self.active_item_ix
107    }
108
109    pub fn set_open(&mut self, open: bool, cx: &mut ViewContext<Self>) {
110        if open != self.is_open {
111            self.is_open = open;
112            cx.notify();
113        }
114    }
115
116    pub fn toggle_open(&mut self, cx: &mut ViewContext<Self>) {
117        if self.is_open {}
118        self.is_open = !self.is_open;
119        cx.notify();
120    }
121
122    pub fn add_item<T: SidebarItem>(
123        &mut self,
124        icon_path: &'static str,
125        tooltip: String,
126        view: ViewHandle<T>,
127        cx: &mut ViewContext<Self>,
128    ) {
129        let subscriptions = [
130            cx.observe(&view, |_, _, cx| cx.notify()),
131            cx.subscribe(&view, |this, view, event, cx| {
132                if view.read(cx).should_activate_item_on_event(event, cx) {
133                    if let Some(ix) = this
134                        .items
135                        .iter()
136                        .position(|item| item.view.id() == view.id())
137                    {
138                        this.activate_item(ix, cx);
139                    }
140                }
141            }),
142        ];
143        self.items.push(Item {
144            icon_path,
145            tooltip,
146            view: Rc::new(view),
147            _subscriptions: subscriptions,
148        });
149        cx.notify()
150    }
151
152    pub fn activate_item(&mut self, item_ix: usize, cx: &mut ViewContext<Self>) {
153        self.active_item_ix = item_ix;
154        cx.notify();
155    }
156
157    pub fn toggle_item(&mut self, item_ix: usize, cx: &mut ViewContext<Self>) {
158        if self.active_item_ix == item_ix {
159            self.is_open = false;
160        } else {
161            self.active_item_ix = item_ix;
162        }
163        cx.notify();
164    }
165
166    pub fn active_item(&self) -> Option<&Rc<dyn SidebarItemHandle>> {
167        if self.is_open {
168            self.items.get(self.active_item_ix).map(|item| &item.view)
169        } else {
170            None
171        }
172    }
173
174    fn render_resize_handle(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
175        let actual_width = self.actual_width.clone();
176        let custom_width = self.custom_width.clone();
177        let side = self.side;
178        MouseEventHandler::new::<Self, _, _>(side as usize, cx, |_, _| {
179            Empty::new()
180                .contained()
181                .with_style(theme.workspace.sidebar_resize_handle)
182                .boxed()
183        })
184        .with_padding(Padding {
185            left: 4.,
186            right: 4.,
187            ..Default::default()
188        })
189        .with_cursor_style(CursorStyle::ResizeLeftRight)
190        .on_mouse_down(MouseButton::Left, |_, _| {}) // This prevents the mouse down event from being propagated elsewhere
191        .on_drag(
192            MouseButton::Left,
193            move |old_position,
194                  MouseMovedEvent {
195                      position: new_position,
196                      ..
197                  },
198                  cx| {
199                let delta = new_position.x() - old_position.x();
200                let prev_width = *actual_width.borrow();
201                *custom_width.borrow_mut() = 0f32
202                    .max(match side {
203                        Side::Left => prev_width + delta,
204                        Side::Right => prev_width - delta,
205                    })
206                    .round();
207
208                cx.notify();
209            },
210        )
211        .boxed()
212    }
213}
214
215impl Entity for Sidebar {
216    type Event = ();
217}
218
219impl View for Sidebar {
220    fn ui_name() -> &'static str {
221        "Sidebar"
222    }
223
224    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
225        let theme = cx.global::<Settings>().theme.clone();
226        if let Some(active_item) = self.active_item() {
227            let mut container = Flex::row();
228            if matches!(self.side, Side::Right) {
229                container.add_child(self.render_resize_handle(&theme, cx));
230            }
231
232            container.add_child(
233                Hook::new(
234                    ChildView::new(active_item.to_any())
235                        .constrained()
236                        .with_max_width(*self.custom_width.borrow())
237                        .boxed(),
238                )
239                .on_after_layout({
240                    let actual_width = self.actual_width.clone();
241                    move |size, _| *actual_width.borrow_mut() = size.x()
242                })
243                .flex(1., false)
244                .boxed(),
245            );
246            if matches!(self.side, Side::Left) {
247                container.add_child(self.render_resize_handle(&theme, cx));
248            }
249            container.boxed()
250        } else {
251            Empty::new().boxed()
252        }
253    }
254}
255
256impl SidebarButtons {
257    pub fn new(sidebar: ViewHandle<Sidebar>, cx: &mut ViewContext<Self>) -> Self {
258        cx.observe(&sidebar, |_, _, cx| cx.notify()).detach();
259        Self { sidebar }
260    }
261}
262
263impl Entity for SidebarButtons {
264    type Event = ();
265}
266
267impl View for SidebarButtons {
268    fn ui_name() -> &'static str {
269        "SidebarToggleButton"
270    }
271
272    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
273        let theme = &cx.global::<Settings>().theme;
274        let tooltip_style = theme.tooltip.clone();
275        let theme = &theme.workspace.status_bar.sidebar_buttons;
276        let sidebar = self.sidebar.read(cx);
277        let item_style = theme.item;
278        let badge_style = theme.badge;
279        let active_ix = sidebar.active_item_ix;
280        let is_open = sidebar.is_open;
281        let side = sidebar.side;
282        let group_style = match side {
283            Side::Left => theme.group_left,
284            Side::Right => theme.group_right,
285        };
286        let items = sidebar
287            .items
288            .iter()
289            .map(|item| (item.icon_path, item.tooltip.clone(), item.view.clone()))
290            .collect::<Vec<_>>();
291        Flex::row()
292            .with_children(items.into_iter().enumerate().map(
293                |(ix, (icon_path, tooltip, item_view))| {
294                    let action = ToggleSidebarItem {
295                        side,
296                        item_index: ix,
297                    };
298                    MouseEventHandler::new::<Self, _, _>(ix, cx, move |state, cx| {
299                        let is_active = is_open && ix == active_ix;
300                        let style = item_style.style_for(state, is_active);
301                        Stack::new()
302                            .with_child(Svg::new(icon_path).with_color(style.icon_color).boxed())
303                            .with_children(if !is_active && item_view.should_show_badge(cx) {
304                                Some(
305                                    Empty::new()
306                                        .collapsed()
307                                        .contained()
308                                        .with_style(badge_style)
309                                        .aligned()
310                                        .bottom()
311                                        .right()
312                                        .boxed(),
313                                )
314                            } else {
315                                None
316                            })
317                            .constrained()
318                            .with_width(style.icon_size)
319                            .with_height(style.icon_size)
320                            .contained()
321                            .with_style(style.container)
322                            .boxed()
323                    })
324                    .with_cursor_style(CursorStyle::PointingHand)
325                    .on_click(MouseButton::Left, {
326                        let action = action.clone();
327                        move |_, cx| cx.dispatch_action(action.clone())
328                    })
329                    .with_tooltip::<Self, _>(
330                        ix,
331                        tooltip,
332                        Some(Box::new(action)),
333                        tooltip_style.clone(),
334                        cx,
335                    )
336                    .boxed()
337                },
338            ))
339            .contained()
340            .with_style(group_style)
341            .boxed()
342    }
343}
344
345impl StatusItemView for SidebarButtons {
346    fn set_active_pane_item(
347        &mut self,
348        _: Option<&dyn crate::ItemHandle>,
349        _: &mut ViewContext<Self>,
350    ) {
351    }
352}