sidebar.rs

  1use crate::StatusItemView;
  2use gpui::{
  3    elements::*, impl_actions, platform::CursorStyle, AnyViewHandle, AppContext, Entity,
  4    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(|_, _| {}) // This prevents the mouse down event from being propagated elsewhere
191        .on_drag(move |delta, cx| {
192            let prev_width = *actual_width.borrow();
193            *custom_width.borrow_mut() = 0f32
194                .max(match side {
195                    Side::Left => prev_width + delta.x(),
196                    Side::Right => prev_width - delta.x(),
197                })
198                .round();
199
200            cx.notify();
201        })
202        .boxed()
203    }
204}
205
206impl Entity for Sidebar {
207    type Event = ();
208}
209
210impl View for Sidebar {
211    fn ui_name() -> &'static str {
212        "Sidebar"
213    }
214
215    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
216        let theme = cx.global::<Settings>().theme.clone();
217        if let Some(active_item) = self.active_item() {
218            let mut container = Flex::row();
219            if matches!(self.side, Side::Right) {
220                container.add_child(self.render_resize_handle(&theme, cx));
221            }
222
223            container.add_child(
224                Hook::new(
225                    ChildView::new(active_item.to_any())
226                        .constrained()
227                        .with_max_width(*self.custom_width.borrow())
228                        .boxed(),
229                )
230                .on_after_layout({
231                    let actual_width = self.actual_width.clone();
232                    move |size, _| *actual_width.borrow_mut() = size.x()
233                })
234                .flex(1., false)
235                .boxed(),
236            );
237            if matches!(self.side, Side::Left) {
238                container.add_child(self.render_resize_handle(&theme, cx));
239            }
240            container.boxed()
241        } else {
242            Empty::new().boxed()
243        }
244    }
245}
246
247impl SidebarButtons {
248    pub fn new(sidebar: ViewHandle<Sidebar>, cx: &mut ViewContext<Self>) -> Self {
249        cx.observe(&sidebar, |_, _, cx| cx.notify()).detach();
250        Self { sidebar }
251    }
252}
253
254impl Entity for SidebarButtons {
255    type Event = ();
256}
257
258impl View for SidebarButtons {
259    fn ui_name() -> &'static str {
260        "SidebarToggleButton"
261    }
262
263    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
264        let theme = &cx.global::<Settings>().theme;
265        let tooltip_style = theme.tooltip.clone();
266        let theme = &theme.workspace.status_bar.sidebar_buttons;
267        let sidebar = self.sidebar.read(cx);
268        let item_style = theme.item;
269        let badge_style = theme.badge;
270        let active_ix = sidebar.active_item_ix;
271        let is_open = sidebar.is_open;
272        let side = sidebar.side;
273        let group_style = match side {
274            Side::Left => theme.group_left,
275            Side::Right => theme.group_right,
276        };
277        let items = sidebar
278            .items
279            .iter()
280            .map(|item| (item.icon_path, item.tooltip.clone(), item.view.clone()))
281            .collect::<Vec<_>>();
282        Flex::row()
283            .with_children(items.into_iter().enumerate().map(
284                |(ix, (icon_path, tooltip, item_view))| {
285                    let action = ToggleSidebarItem {
286                        side,
287                        item_index: ix,
288                    };
289                    MouseEventHandler::new::<Self, _, _>(ix, cx, move |state, cx| {
290                        let is_active = is_open && ix == active_ix;
291                        let style = item_style.style_for(state, is_active);
292                        Stack::new()
293                            .with_child(Svg::new(icon_path).with_color(style.icon_color).boxed())
294                            .with_children(if !is_active && item_view.should_show_badge(cx) {
295                                Some(
296                                    Empty::new()
297                                        .collapsed()
298                                        .contained()
299                                        .with_style(badge_style)
300                                        .aligned()
301                                        .bottom()
302                                        .right()
303                                        .boxed(),
304                                )
305                            } else {
306                                None
307                            })
308                            .constrained()
309                            .with_width(style.icon_size)
310                            .with_height(style.icon_size)
311                            .contained()
312                            .with_style(style.container)
313                            .boxed()
314                    })
315                    .with_cursor_style(CursorStyle::PointingHand)
316                    .on_click({
317                        let action = action.clone();
318                        move |_, _, cx| cx.dispatch_action(action.clone())
319                    })
320                    .with_tooltip::<Self, _>(
321                        ix,
322                        tooltip,
323                        Some(Box::new(action)),
324                        tooltip_style.clone(),
325                        cx,
326                    )
327                    .boxed()
328                },
329            ))
330            .contained()
331            .with_style(group_style)
332            .boxed()
333    }
334}
335
336impl StatusItemView for SidebarButtons {
337    fn set_active_pane_item(
338        &mut self,
339        _: Option<&dyn crate::ItemHandle>,
340        _: &mut ViewContext<Self>,
341    ) {
342    }
343}