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 From<&dyn SidebarItemHandle> for AnyViewHandle {
50 fn from(val: &dyn SidebarItemHandle) -> Self {
51 val.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 cx.reparent(&view);
144 self.items.push(Item {
145 icon_path,
146 tooltip,
147 view: Rc::new(view),
148 _subscriptions: subscriptions,
149 });
150 cx.notify()
151 }
152
153 pub fn activate_item(&mut self, item_ix: usize, cx: &mut ViewContext<Self>) {
154 self.active_item_ix = item_ix;
155 cx.notify();
156 }
157
158 pub fn toggle_item(&mut self, item_ix: usize, cx: &mut ViewContext<Self>) {
159 if self.active_item_ix == item_ix {
160 self.is_open = false;
161 } else {
162 self.active_item_ix = item_ix;
163 }
164 cx.notify();
165 }
166
167 pub fn active_item(&self) -> Option<&Rc<dyn SidebarItemHandle>> {
168 if self.is_open {
169 self.items.get(self.active_item_ix).map(|item| &item.view)
170 } else {
171 None
172 }
173 }
174
175 fn render_resize_handle(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
176 let actual_width = self.actual_width.clone();
177 let custom_width = self.custom_width.clone();
178 let side = self.side;
179 MouseEventHandler::new::<Self, _, _>(side as usize, cx, |_, _| {
180 Empty::new()
181 .contained()
182 .with_style(theme.workspace.sidebar_resize_handle)
183 .boxed()
184 })
185 .with_padding(Padding {
186 left: 4.,
187 right: 4.,
188 ..Default::default()
189 })
190 .with_cursor_style(CursorStyle::ResizeLeftRight)
191 .on_down(MouseButton::Left, |_, _| {}) // This prevents the mouse down event from being propagated elsewhere
192 .on_drag(
193 MouseButton::Left,
194 move |old_position,
195 MouseMovedEvent {
196 position: new_position,
197 ..
198 },
199 cx| {
200 let delta = new_position.x() - old_position.x();
201 let prev_width = *actual_width.borrow();
202 *custom_width.borrow_mut() = 0f32
203 .max(match side {
204 Side::Left => prev_width + delta,
205 Side::Right => prev_width - delta,
206 })
207 .round();
208
209 cx.notify();
210 },
211 )
212 .boxed()
213 }
214}
215
216impl Entity for Sidebar {
217 type Event = ();
218}
219
220impl View for Sidebar {
221 fn ui_name() -> &'static str {
222 "Sidebar"
223 }
224
225 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
226 let theme = cx.global::<Settings>().theme.clone();
227 if let Some(active_item) = self.active_item() {
228 let mut container = Flex::row();
229 if matches!(self.side, Side::Right) {
230 container.add_child(self.render_resize_handle(&theme, cx));
231 }
232
233 container.add_child(
234 Hook::new(
235 ChildView::new(active_item.to_any())
236 .constrained()
237 .with_max_width(*self.custom_width.borrow())
238 .boxed(),
239 )
240 .on_after_layout({
241 let actual_width = self.actual_width.clone();
242 move |size, _| *actual_width.borrow_mut() = size.x()
243 })
244 .flex(1., false)
245 .boxed(),
246 );
247 if matches!(self.side, Side::Left) {
248 container.add_child(self.render_resize_handle(&theme, cx));
249 }
250 container.boxed()
251 } else {
252 Empty::new().boxed()
253 }
254 }
255}
256
257impl SidebarButtons {
258 pub fn new(sidebar: ViewHandle<Sidebar>, cx: &mut ViewContext<Self>) -> Self {
259 cx.observe(&sidebar, |_, _, cx| cx.notify()).detach();
260 Self { sidebar }
261 }
262}
263
264impl Entity for SidebarButtons {
265 type Event = ();
266}
267
268impl View for SidebarButtons {
269 fn ui_name() -> &'static str {
270 "SidebarToggleButton"
271 }
272
273 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
274 let theme = &cx.global::<Settings>().theme;
275 let tooltip_style = theme.tooltip.clone();
276 let theme = &theme.workspace.status_bar.sidebar_buttons;
277 let sidebar = self.sidebar.read(cx);
278 let item_style = theme.item;
279 let badge_style = theme.badge;
280 let active_ix = sidebar.active_item_ix;
281 let is_open = sidebar.is_open;
282 let side = sidebar.side;
283 let group_style = match side {
284 Side::Left => theme.group_left,
285 Side::Right => theme.group_right,
286 };
287
288 #[allow(clippy::needless_collect)]
289 let items = sidebar
290 .items
291 .iter()
292 .map(|item| (item.icon_path, item.tooltip.clone(), item.view.clone()))
293 .collect::<Vec<_>>();
294
295 Flex::row()
296 .with_children(items.into_iter().enumerate().map(
297 |(ix, (icon_path, tooltip, item_view))| {
298 let action = ToggleSidebarItem {
299 side,
300 item_index: ix,
301 };
302 MouseEventHandler::new::<Self, _, _>(ix, cx, move |state, cx| {
303 let is_active = is_open && ix == active_ix;
304 let style = item_style.style_for(state, is_active);
305 Stack::new()
306 .with_child(Svg::new(icon_path).with_color(style.icon_color).boxed())
307 .with_children(if !is_active && item_view.should_show_badge(cx) {
308 Some(
309 Empty::new()
310 .collapsed()
311 .contained()
312 .with_style(badge_style)
313 .aligned()
314 .bottom()
315 .right()
316 .boxed(),
317 )
318 } else {
319 None
320 })
321 .constrained()
322 .with_width(style.icon_size)
323 .with_height(style.icon_size)
324 .contained()
325 .with_style(style.container)
326 .boxed()
327 })
328 .with_cursor_style(CursorStyle::PointingHand)
329 .on_click(MouseButton::Left, {
330 let action = action.clone();
331 move |_, cx| cx.dispatch_action(action.clone())
332 })
333 .with_tooltip::<Self, _>(
334 ix,
335 tooltip,
336 Some(Box::new(action)),
337 tooltip_style.clone(),
338 cx,
339 )
340 .boxed()
341 },
342 ))
343 .contained()
344 .with_style(group_style)
345 .boxed()
346 }
347}
348
349impl StatusItemView for SidebarButtons {
350 fn set_active_pane_item(
351 &mut self,
352 _: Option<&dyn crate::ItemHandle>,
353 _: &mut ViewContext<Self>,
354 ) {
355 }
356}