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