Skip to main content

fc_ui/capabilities/scroll/
split_pane.rs

1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, *};
3use std::rc::Rc;
4
5const MIN_PANE_SIZE: f32 = 50.0;
6const DIVIDER_SIZE: Pixels = px(4.0);
7const DIVIDER_HIT_AREA: Pixels = px(8.0);
8
9#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
10pub enum SplitDirection {
11    #[default]
12    Horizontal,
13    Vertical,
14}
15
16#[derive(Clone, Debug)]
17pub enum SplitPaneEvent {
18    Resized { ratio: f32 },
19    PaneCollapsed { pane: CollapsiblePane },
20    PaneExpanded { pane: CollapsiblePane },
21}
22
23#[derive(Copy, Clone, Debug, PartialEq, Eq)]
24pub enum CollapsiblePane {
25    First,
26    Second,
27}
28
29pub struct SplitPaneState {
30    ratio: f32,
31    direction: SplitDirection,
32    min_first: f32,
33    max_first: f32,
34    min_second: f32,
35    max_second: f32,
36    is_dragging: bool,
37    collapsed_pane: Option<CollapsiblePane>,
38    ratio_before_collapse: f32,
39    bounds: Bounds<Pixels>,
40    focus_handle: FocusHandle,
41}
42
43impl SplitPaneState {
44    pub fn new(cx: &mut Context<Self>) -> Self {
45        Self {
46            ratio: 0.5,
47            direction: SplitDirection::Horizontal,
48            min_first: MIN_PANE_SIZE,
49            max_first: f32::MAX,
50            min_second: MIN_PANE_SIZE,
51            max_second: f32::MAX,
52            is_dragging: false,
53            collapsed_pane: None,
54            ratio_before_collapse: 0.5,
55            bounds: Bounds::default(),
56            focus_handle: cx.focus_handle(),
57        }
58    }
59
60    pub fn ratio(&self) -> f32 {
61        self.ratio
62    }
63
64    pub fn set_ratio(&mut self, ratio: f32, cx: &mut Context<Self>) {
65        let clamped = self.clamp_ratio(ratio);
66        if (self.ratio - clamped).abs() > f32::EPSILON {
67            self.ratio = clamped;
68            cx.notify();
69        }
70    }
71
72    pub fn direction(&self) -> SplitDirection {
73        self.direction
74    }
75
76    pub fn set_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
77        self.direction = direction;
78        cx.notify();
79    }
80
81    pub fn set_min_first(&mut self, min: f32, cx: &mut Context<Self>) {
82        self.min_first = min.max(0.0);
83        self.ratio = self.clamp_ratio(self.ratio);
84        cx.notify();
85    }
86
87    pub fn set_max_first(&mut self, max: f32, cx: &mut Context<Self>) {
88        self.max_first = max.max(self.min_first);
89        self.ratio = self.clamp_ratio(self.ratio);
90        cx.notify();
91    }
92
93    pub fn set_min_second(&mut self, min: f32, cx: &mut Context<Self>) {
94        self.min_second = min.max(0.0);
95        self.ratio = self.clamp_ratio(self.ratio);
96        cx.notify();
97    }
98
99    pub fn set_max_second(&mut self, max: f32, cx: &mut Context<Self>) {
100        self.max_second = max.max(self.min_second);
101        self.ratio = self.clamp_ratio(self.ratio);
102        cx.notify();
103    }
104
105    pub fn is_collapsed(&self) -> bool {
106        self.collapsed_pane.is_some()
107    }
108
109    pub fn collapsed_pane(&self) -> Option<CollapsiblePane> {
110        self.collapsed_pane
111    }
112
113    pub fn collapse(&mut self, pane: CollapsiblePane, cx: &mut Context<Self>) {
114        if self.collapsed_pane.is_some() {
115            return;
116        }
117        self.ratio_before_collapse = self.ratio;
118        self.collapsed_pane = Some(pane);
119        cx.emit(SplitPaneEvent::PaneCollapsed { pane });
120        cx.notify();
121    }
122
123    pub fn expand(&mut self, cx: &mut Context<Self>) {
124        if let Some(pane) = self.collapsed_pane.take() {
125            self.ratio = self.ratio_before_collapse;
126            cx.emit(SplitPaneEvent::PaneExpanded { pane });
127            cx.notify();
128        }
129    }
130
131    pub fn toggle_collapse(&mut self, pane: CollapsiblePane, cx: &mut Context<Self>) {
132        if self.collapsed_pane == Some(pane) {
133            self.expand(cx);
134        } else {
135            self.collapse(pane, cx);
136        }
137    }
138
139    fn clamp_ratio(&self, ratio: f32) -> f32 {
140        let total_size = self.total_size();
141        if total_size <= px(0.0) {
142            return ratio.clamp(0.0, 1.0);
143        }
144
145        let min_first_ratio = (px(self.min_first) / total_size).clamp(0.0, 1.0);
146        let max_first_ratio = (px(self.max_first) / total_size).clamp(0.0, 1.0);
147        let min_second_ratio = (px(self.min_second) / total_size).clamp(0.0, 1.0);
148        let max_second_ratio = (px(self.max_second) / total_size).clamp(0.0, 1.0);
149
150        let lower_bound = min_first_ratio.max(1.0 - max_second_ratio);
151        let upper_bound = max_first_ratio.min(1.0 - min_second_ratio);
152
153        ratio.clamp(lower_bound.min(upper_bound), upper_bound.max(lower_bound))
154    }
155
156    fn total_size(&self) -> Pixels {
157        match self.direction {
158            SplitDirection::Horizontal => self.bounds.size.width,
159            SplitDirection::Vertical => self.bounds.size.height,
160        }
161    }
162
163    fn update_from_position(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
164        let total_size = self.total_size();
165        if total_size <= px(0.0) {
166            return;
167        }
168
169        let relative_pos = match self.direction {
170            SplitDirection::Horizontal => position.x - self.bounds.left(),
171            SplitDirection::Vertical => position.y - self.bounds.top(),
172        };
173
174        let new_ratio = (relative_pos / total_size).clamp(0.0, 1.0);
175        let old_ratio = self.ratio;
176        self.set_ratio(new_ratio, cx);
177
178        if (self.ratio - old_ratio).abs() > f32::EPSILON {
179            cx.emit(SplitPaneEvent::Resized { ratio: self.ratio });
180        }
181    }
182}
183
184impl Focusable for SplitPaneState {
185    fn focus_handle(&self, _: &App) -> FocusHandle {
186        self.focus_handle.clone()
187    }
188}
189
190impl EventEmitter<SplitPaneEvent> for SplitPaneState {}
191
192impl Render for SplitPaneState {
193    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
194        div()
195    }
196}
197
198#[derive(IntoElement)]
199pub struct SplitPane {
200    state: Entity<SplitPaneState>,
201    first_child: Option<AnyElement>,
202    second_child: Option<AnyElement>,
203    direction: Option<SplitDirection>,
204    show_collapse_buttons: bool,
205    on_resize: Option<Rc<dyn Fn(f32, &mut Window, &mut App) + 'static>>,
206    style: StyleRefinement,
207}
208
209impl SplitPane {
210    pub fn new(state: Entity<SplitPaneState>) -> Self {
211        Self {
212            state,
213            first_child: None,
214            second_child: None,
215            direction: None,
216            show_collapse_buttons: false,
217            on_resize: None,
218            style: StyleRefinement::default(),
219        }
220    }
221
222    pub fn horizontal(state: Entity<SplitPaneState>) -> Self {
223        Self::new(state).direction(SplitDirection::Horizontal)
224    }
225
226    pub fn vertical(state: Entity<SplitPaneState>) -> Self {
227        Self::new(state).direction(SplitDirection::Vertical)
228    }
229
230    pub fn direction(mut self, direction: SplitDirection) -> Self {
231        self.direction = Some(direction);
232        self
233    }
234
235    pub fn first(mut self, child: impl IntoElement) -> Self {
236        self.first_child = Some(child.into_any_element());
237        self
238    }
239
240    pub fn second(mut self, child: impl IntoElement) -> Self {
241        self.second_child = Some(child.into_any_element());
242        self
243    }
244
245    pub fn show_collapse_buttons(mut self, show: bool) -> Self {
246        self.show_collapse_buttons = show;
247        self
248    }
249
250    pub fn on_resize(mut self, handler: impl Fn(f32, &mut Window, &mut App) + 'static) -> Self {
251        self.on_resize = Some(Rc::new(handler));
252        self
253    }
254}
255
256impl Styled for SplitPane {
257    fn style(&mut self) -> &mut StyleRefinement {
258        &mut self.style
259    }
260}
261
262impl RenderOnce for SplitPane {
263    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
264        let theme = use_theme(cx);
265        let state = self.state.read(cx);
266        let direction = self.direction.unwrap_or(state.direction);
267        let ratio = state.ratio;
268        let collapsed_pane = state.collapsed_pane;
269        let user_style = self.style;
270
271        let (first_size, second_size) = match collapsed_pane {
272            Some(CollapsiblePane::First) => (relative(0.0), relative(1.0)),
273            Some(CollapsiblePane::Second) => (relative(1.0), relative(0.0)),
274            None => (relative(ratio), relative(1.0 - ratio)),
275        };
276
277        let state_for_canvas = self.state.clone();
278        let state_for_drag = self.state.clone();
279        let state_for_move = self.state.clone();
280        let state_for_up = self.state.clone();
281        let on_resize_drag = self.on_resize.clone();
282        let on_resize_move = self.on_resize.clone();
283
284        let is_horizontal = direction == SplitDirection::Horizontal;
285        let is_dragging = state.is_dragging;
286
287        let divider = div()
288            .id("split-pane-divider")
289            .flex_shrink_0()
290            .bg(theme.tokens.border)
291            .when(is_horizontal, |this| {
292                this.w(DIVIDER_SIZE)
293                    .h_full()
294                    .cursor_col_resize()
295                    .px((DIVIDER_HIT_AREA - DIVIDER_SIZE) / 2.0)
296            })
297            .when(!is_horizontal, |this| {
298                this.h(DIVIDER_SIZE)
299                    .w_full()
300                    .cursor_row_resize()
301                    .py((DIVIDER_HIT_AREA - DIVIDER_SIZE) / 2.0)
302            })
303            .when(collapsed_pane.is_none(), |this| {
304                this.hover(|s| s.bg(theme.tokens.accent))
305            })
306            .when(is_dragging, |this| this.bg(theme.tokens.accent))
307            .when(collapsed_pane.is_none(), |this| {
308                this.on_mouse_down(
309                    MouseButton::Left,
310                    window.listener_for(
311                        &state_for_drag,
312                        move |state, e: &MouseDownEvent, window, cx| {
313                            state.is_dragging = true;
314                            state.update_from_position(e.position, cx);
315
316                            if let Some(ref handler) = on_resize_drag {
317                                handler(state.ratio, window, cx);
318                            }
319                        },
320                    ),
321                )
322            });
323
324        let container_mouse_move = window.listener_for(
325            &state_for_move,
326            move |state, e: &MouseMoveEvent, window, cx| {
327                if state.is_dragging {
328                    state.update_from_position(e.position, cx);
329
330                    if let Some(ref handler) = on_resize_move {
331                        handler(state.ratio, window, cx);
332                    }
333                }
334            },
335        );
336
337        let container_mouse_up =
338            window.listener_for(&state_for_up, move |state, _: &MouseUpEvent, _, cx| {
339                if state.is_dragging {
340                    state.is_dragging = false;
341                    cx.emit(SplitPaneEvent::Resized { ratio: state.ratio });
342                    cx.notify();
343                }
344            });
345
346        let mut container = div()
347            .flex()
348            .size_full()
349            .overflow_hidden()
350            .when(is_horizontal, |this| this.flex_row())
351            .when(!is_horizontal, |this| this.flex_col())
352            .on_mouse_move(container_mouse_move)
353            .on_mouse_up(MouseButton::Left, container_mouse_up);
354
355        container = container.map(|mut this| {
356            this.style().refine(&user_style);
357            this
358        });
359
360        let is_first_collapsed = collapsed_pane == Some(CollapsiblePane::First);
361        let is_second_collapsed = collapsed_pane == Some(CollapsiblePane::Second);
362
363        let first_pane = div()
364            .flex_shrink_0()
365            .overflow_hidden()
366            .when(is_horizontal && !is_first_collapsed, |this| {
367                this.h_full().w(first_size)
368            })
369            .when(!is_horizontal && !is_first_collapsed, |this| {
370                this.w_full().h(first_size)
371            })
372            .when(is_first_collapsed, |this| this.size_0())
373            .when_some(self.first_child, |this, child| this.child(child));
374
375        let second_pane = div()
376            .flex_shrink_0()
377            .overflow_hidden()
378            .when(is_horizontal && !is_second_collapsed, |this| {
379                this.h_full().w(second_size)
380            })
381            .when(!is_horizontal && !is_second_collapsed, |this| {
382                this.w_full().h(second_size)
383            })
384            .when(is_second_collapsed, |this| this.size_0())
385            .when_some(self.second_child, |this, child| this.child(child));
386
387        let collapse_buttons = if self.show_collapse_buttons && collapsed_pane.is_none() {
388            let state_first = self.state.clone();
389            let state_second = self.state.clone();
390
391            Some(
392                div()
393                    .absolute()
394                    .when(is_horizontal, |this| {
395                        this.top(px(4.0))
396                            .left(relative(ratio))
397                            .ml(-px(8.0))
398                            .flex()
399                            .flex_col()
400                            .gap(px(2.0))
401                    })
402                    .when(!is_horizontal, |this| {
403                        this.left(px(4.0))
404                            .top(relative(ratio))
405                            .mt(-px(8.0))
406                            .flex()
407                            .flex_row()
408                            .gap(px(2.0))
409                    })
410                    .child(
411                        div()
412                            .id("collapse-first")
413                            .size(px(16.0))
414                            .rounded_full()
415                            .bg(theme.tokens.muted)
416                            .hover(|s| s.bg(theme.tokens.accent))
417                            .cursor_pointer()
418                            .flex()
419                            .items_center()
420                            .justify_center()
421                            .text_size(px(10.0))
422                            .text_color(theme.tokens.muted_foreground)
423                            .when(is_horizontal, |this| this.child("<"))
424                            .when(!is_horizontal, |this| this.child("^"))
425                            .on_click(move |_, _, cx| {
426                                state_first.update(cx, |state, cx| {
427                                    state.collapse(CollapsiblePane::First, cx);
428                                });
429                            }),
430                    )
431                    .child(
432                        div()
433                            .id("collapse-second")
434                            .size(px(16.0))
435                            .rounded_full()
436                            .bg(theme.tokens.muted)
437                            .hover(|s| s.bg(theme.tokens.accent))
438                            .cursor_pointer()
439                            .flex()
440                            .items_center()
441                            .justify_center()
442                            .text_size(px(10.0))
443                            .text_color(theme.tokens.muted_foreground)
444                            .when(is_horizontal, |this| this.child(">"))
445                            .when(!is_horizontal, |this| this.child("v"))
446                            .on_click(move |_, _, cx| {
447                                state_second.update(cx, |state, cx| {
448                                    state.collapse(CollapsiblePane::Second, cx);
449                                });
450                            }),
451                    ),
452            )
453        } else if self.show_collapse_buttons && collapsed_pane.is_some() {
454            let state_expand = self.state.clone();
455
456            Some(
457                div()
458                    .absolute()
459                    .when(is_horizontal, |this| {
460                        if collapsed_pane == Some(CollapsiblePane::First) {
461                            this.top(px(4.0)).left(px(4.0))
462                        } else {
463                            this.top(px(4.0)).right(px(4.0))
464                        }
465                    })
466                    .when(!is_horizontal, |this| {
467                        if collapsed_pane == Some(CollapsiblePane::First) {
468                            this.left(px(4.0)).top(px(4.0))
469                        } else {
470                            this.left(px(4.0)).bottom(px(4.0))
471                        }
472                    })
473                    .child(
474                        div()
475                            .id("expand-pane")
476                            .size(px(20.0))
477                            .rounded_full()
478                            .bg(theme.tokens.accent)
479                            .hover(|s| s.bg(theme.tokens.primary))
480                            .cursor_pointer()
481                            .flex()
482                            .items_center()
483                            .justify_center()
484                            .text_size(px(12.0))
485                            .text_color(theme.tokens.accent_foreground)
486                            .when(
487                                is_horizontal && collapsed_pane == Some(CollapsiblePane::First),
488                                |this| this.child(">"),
489                            )
490                            .when(
491                                is_horizontal && collapsed_pane == Some(CollapsiblePane::Second),
492                                |this| this.child("<"),
493                            )
494                            .when(
495                                !is_horizontal && collapsed_pane == Some(CollapsiblePane::First),
496                                |this| this.child("v"),
497                            )
498                            .when(
499                                !is_horizontal && collapsed_pane == Some(CollapsiblePane::Second),
500                                |this| this.child("^"),
501                            )
502                            .on_click(move |_, _, cx| {
503                                state_expand.update(cx, |state, cx| {
504                                    state.expand(cx);
505                                });
506                            }),
507                    ),
508            )
509        } else {
510            None
511        };
512
513        container
514            .relative()
515            .child(first_pane)
516            .when(collapsed_pane.is_none(), |this| this.child(divider))
517            .child(second_pane)
518            .when_some(collapse_buttons, |this, buttons| this.child(buttons))
519            .child(
520                canvas(
521                    move |bounds, _, cx| {
522                        state_for_canvas.update(cx, |state, _| {
523                            state.bounds = bounds;
524                        });
525                    },
526                    |_, _, _, _| {},
527                )
528                .absolute()
529                .size_full(),
530            )
531    }
532}