Skip to main content

gpui_base/resizable/
panel.rs

1use std::{ops::Range, rc::Rc};
2
3use gpui::{
4    Along, AnyElement, App, AppContext, Axis, Bounds, Context, Element, ElementId, Empty, Entity,
5    EventEmitter, InteractiveElement as _, IntoElement, IsZero as _, MouseMoveEvent, MouseUpEvent,
6    ParentElement, Pixels, Render, RenderOnce, Style, StyleRefinement, Styled, Window, div,
7    prelude::FluentBuilder,
8};
9
10use crate::{AxisExt, ElementExt, StyledExt as _, h_flex, resizable::PANEL_MIN_SIZE, v_flex};
11
12use super::{ResizableState, ResizeHandleRenderer, resizable_panel, resize_handle};
13
14pub enum ResizablePanelEvent {
15    Resized,
16}
17
18#[derive(Clone)]
19pub(crate) struct DragPanel;
20impl Render for DragPanel {
21    fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
22        Empty
23    }
24}
25
26/// A group of resizable panels.
27#[derive(IntoElement)]
28pub struct ResizablePanelGroup {
29    id: ElementId,
30    state: Option<Entity<ResizableState>>,
31    axis: Axis,
32    size: Option<Pixels>,
33    children: Vec<ResizablePanel>,
34    on_resize: Rc<dyn Fn(&Entity<ResizableState>, &mut Window, &mut App)>,
35    handle_appearance: Option<ResizeHandleRenderer>,
36}
37
38impl ResizablePanelGroup {
39    /// Create a new resizable panel group.
40    pub fn new(id: impl Into<ElementId>) -> Self {
41        Self {
42            id: id.into(),
43            axis: Axis::Horizontal,
44            children: vec![],
45            state: None,
46            size: None,
47            on_resize: Rc::new(|_, _, _| {}),
48            handle_appearance: None,
49        }
50    }
51
52    /// Hand the painted part of every divider in this group to `appearance`.
53    ///
54    /// The hit area, the cursor and the drag stay here; a renderer that
55    /// returns `None` for a given handle leaves the built-in line on it.
56    pub fn with_handle_appearance(mut self, appearance: ResizeHandleRenderer) -> Self {
57        self.handle_appearance = Some(appearance);
58        self
59    }
60
61    /// Bind yourself to a resizable state entity.
62    ///
63    /// If not provided, it will handle its own state internally.
64    pub fn with_state(mut self, state: &Entity<ResizableState>) -> Self {
65        self.state = Some(state.clone());
66        self
67    }
68
69    /// Set the axis of the resizable panel group, default is horizontal.
70    pub fn axis(mut self, axis: Axis) -> Self {
71        self.axis = axis;
72        self
73    }
74
75    /// Add a panel to the group.
76    ///
77    /// - The `axis` will be set to the same axis as the group.
78    /// - The `initial_size` will be set to the average size of all panels if not provided.
79    /// - The `group` will be set to the group entity.
80    pub fn child(mut self, panel: impl Into<ResizablePanel>) -> Self {
81        self.children.push(panel.into());
82        self
83    }
84
85    /// Add multiple panels to the group.
86    pub fn children<I>(mut self, panels: impl IntoIterator<Item = I>) -> Self
87    where
88        I: Into<ResizablePanel>,
89    {
90        self.children = panels.into_iter().map(|panel| panel.into()).collect();
91        self
92    }
93
94    /// Set size of the resizable panel group
95    ///
96    /// - When the axis is horizontal, the size is the height of the group.
97    /// - When the axis is vertical, the size is the width of the group.
98    pub fn size(mut self, size: Pixels) -> Self {
99        self.size = Some(size);
100        self
101    }
102
103    /// Set the callback to be called when the panels are resized.
104    ///
105    /// ## Callback arguments
106    ///
107    /// - Entity<ResizableState>: The state of the ResizablePanelGroup.
108    pub fn on_resize(
109        mut self,
110        on_resize: impl Fn(&Entity<ResizableState>, &mut Window, &mut App) + 'static,
111    ) -> Self {
112        self.on_resize = Rc::new(on_resize);
113        self
114    }
115}
116
117impl<T> From<T> for ResizablePanel
118where
119    T: Into<AnyElement>,
120{
121    fn from(value: T) -> Self {
122        resizable_panel().child(value.into())
123    }
124}
125
126impl From<ResizablePanelGroup> for ResizablePanel {
127    fn from(value: ResizablePanelGroup) -> Self {
128        resizable_panel().child(value)
129    }
130}
131
132impl EventEmitter<ResizablePanelEvent> for ResizablePanelGroup {}
133
134impl RenderOnce for ResizablePanelGroup {
135    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
136        let state = self.state.unwrap_or(
137            window.use_keyed_state(self.id.clone(), cx, |_, _| ResizableState::default()),
138        );
139        let container = if self.axis.is_horizontal() {
140            h_flex()
141        } else {
142            v_flex()
143        };
144
145        // Sync panels to the state
146        let panels_count = self.children.len();
147        state.update(cx, |state, cx| {
148            state.sync_panels_count(self.axis, panels_count, cx);
149            state.sync_panel_visibility(self.children.iter().map(|panel| panel.visible), cx);
150        });
151
152        container
153            .id(self.id)
154            .size_full()
155            // The group only distributes space along its own axis, so a caller
156            // supplied size can only mean the cross axis.
157            .when_some(self.size, |this, size| match self.axis {
158                Axis::Horizontal => this.h(size),
159                Axis::Vertical => this.w(size),
160            })
161            .children(
162                self.children
163                    .into_iter()
164                    .enumerate()
165                    .map(|(ix, mut panel)| {
166                        panel.panel_ix = ix;
167                        panel.axis = self.axis;
168                        panel.state = Some(state.clone());
169                        panel.handle_appearance = self.handle_appearance.clone();
170                        panel
171                    }),
172            )
173            .on_prepaint({
174                let state = state.clone();
175                move |bounds, window, cx| {
176                    // The same bounds as last frame change nothing; updating
177                    // the state for them would mark it changed every frame.
178                    if state.read(cx).bounds == bounds {
179                        return;
180                    }
181                    state.update(cx, |state, cx| {
182                        let size_changed =
183                            state.bounds.size.along(self.axis) != bounds.size.along(self.axis);
184
185                        state.bounds = bounds;
186
187                        if size_changed {
188                            state.adjust_to_container_size(cx);
189                            // The adjustment lands after this frame's layout has
190                            // already been computed, and a notify raised during a
191                            // draw only records the view as dirty without scheduling
192                            // a frame for it. Defer the notify so it runs once the
193                            // draw has finished and can schedule the settling frame.
194                            // Otherwise that frame stays pending until some later
195                            // input repaints the window, and the divider appears to
196                            // jump on hover.
197                            let state = cx.entity();
198                            window.defer(cx, move |_, cx| {
199                                state.update(cx, |_, cx| cx.notify());
200                            });
201                        }
202                    })
203                }
204            })
205            .child(ResizePanelGroupElement {
206                state: state.clone(),
207                axis: self.axis,
208                on_resize: self.on_resize.clone(),
209            })
210    }
211}
212
213/// A resizable panel inside a [`ResizablePanelGroup`].
214///
215/// Implements [`Styled`], so call sites can override the panel's
216/// rendered styles. User overrides are applied **between** the panel's
217/// flex defaults and its size management — the caller can override the
218/// internal `flex_grow: 1` (e.g. via `.flex_none()`) and add their own
219/// padding / colors / borders, while the panel's runtime size
220/// constraints (`min_w`/`max_w`/`flex_basis` driven by `ResizableState`)
221/// always win.
222///
223/// A common override is `.flex_none()`: the panel sets `flex_grow: 1`
224/// internally, so a sized panel that should hold its width when a
225/// sibling collapses needs to opt out of growth via `.flex_none()`.
226///
227/// To keep a panel's size when the group's container resizes, use
228/// [`ResizablePanel::fixed`].
229///
230/// ```ignore
231/// h_resizable("layout")
232///     .child(resizable_panel().size(px(220.)).flex_none().child(sidebar))
233///     .child(resizable_panel().child(content))                // flex
234///     .child(resizable_panel().size(px(280.)).flex_none().child(metadata))
235/// ```
236///
237/// **Reserved styles**: do not call these from outside — they fight the
238/// panel's own layout management:
239/// - `.flex_basis(...)` — driven by `ResizableState`, not by the caller.
240/// - `.absolute()` — would remove the panel from the resizable's flex flow.
241/// - `.overflow_hidden()` — may clip the resize handle, which is positioned
242///   absolute at `left: -4px` of each panel after the first.
243#[derive(IntoElement)]
244pub struct ResizablePanel {
245    axis: Axis,
246    panel_ix: usize,
247    state: Option<Entity<ResizableState>>,
248    /// Initial size is the size that the panel has when it is created.
249    initial_size: Option<Pixels>,
250    /// size range limit of this panel.
251    size_range: Range<Pixels>,
252    children: Vec<AnyElement>,
253    visible: bool,
254    style: StyleRefinement,
255    handle_appearance: Option<ResizeHandleRenderer>,
256    fixed: bool,
257}
258
259impl ResizablePanel {
260    /// Create a new resizable panel.
261    pub(super) fn new() -> Self {
262        Self {
263            panel_ix: 0,
264            initial_size: None,
265            state: None,
266            size_range: (PANEL_MIN_SIZE..Pixels::MAX),
267            axis: Axis::Horizontal,
268            children: vec![],
269            visible: true,
270            style: StyleRefinement::default(),
271            handle_appearance: None,
272            fixed: false,
273        }
274    }
275
276    /// Set the visibility of the panel, default is true.
277    pub fn visible(mut self, visible: bool) -> Self {
278        self.visible = visible;
279        self
280    }
281
282    /// Set the initial size of the panel.
283    pub fn size(mut self, size: impl Into<Pixels>) -> Self {
284        self.initial_size = Some(size.into());
285        self
286    }
287
288    /// Set the size range to limit panel resize.
289    ///
290    /// Default is [`PANEL_MIN_SIZE`] to [`Pixels::MAX`].
291    pub fn size_range(mut self, range: impl Into<Range<Pixels>>) -> Self {
292        self.size_range = range.into();
293        self
294    }
295
296    /// Keep this panel's size when the group's container resizes.
297    ///
298    /// When the container grows or shrinks, the other panels share the
299    /// difference in proportion to their sizes, so a sidebar or an inspector
300    /// keeps the width the user gave it. Dragging its own handle still resizes
301    /// it. It needs a [`Self::size`], and at least one panel in the group
302    /// should not be fixed.
303    pub fn fixed(mut self) -> Self {
304        self.fixed = true;
305        self
306    }
307}
308
309impl Styled for ResizablePanel {
310    fn style(&mut self) -> &mut StyleRefinement {
311        &mut self.style
312    }
313}
314
315impl ParentElement for ResizablePanel {
316    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
317        self.children.extend(elements);
318    }
319}
320
321impl RenderOnce for ResizablePanel {
322    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
323        if !self.visible {
324            return div().id(("resizable-panel", self.panel_ix));
325        }
326
327        let state = self
328            .state
329            .expect("BUG: The `state` in ResizablePanel should be present.");
330        let panel_state = state
331            .read(cx)
332            .panels
333            .get(self.panel_ix)
334            .expect("BUG: The `index` of ResizablePanel should be one of in `state`.");
335        let size_range = self.size_range.clone();
336        // A fixed panel needs a size to keep; without one it lays out as usual.
337        let fixed = self.fixed && self.initial_size.is_some();
338        let previous_panel = state.read(cx).previous_visible_panel(self.panel_ix);
339
340        div()
341            .id(("resizable-panel", self.panel_ix))
342            .flex()
343            .flex_grow_1()
344            .size_full()
345            .relative()
346            // Apply caller style overrides here — between the flex defaults
347            // above and the size management below. This lets callers cancel
348            // the unconditional `.flex_grow_1()` (via `.flex_none()`, the load-
349            // bearing case for sized panels next to a collapsing sibling) and
350            // add their own padding / colors / borders, while keeping the
351            // panel's runtime size constraints (min/max + `flex_basis` driven
352            // by `ResizableState`) authoritative.
353            .refine_style(&self.style)
354            .when(self.axis.is_vertical(), |this| {
355                this.min_h(size_range.start).max_h(size_range.end)
356            })
357            .when(self.axis.is_horizontal(), |this| {
358                this.min_w(size_range.start).max_w(size_range.end)
359            })
360            // 1. initial_size is None, to use auto size.
361            // 2. initial_size is Some and size is none, to use the initial size of the panel for first time render.
362            // 3. initial_size is Some and size is Some, use `size`.
363            .when(self.initial_size.is_none(), |this| this.flex_shrink_1())
364            .when_some(self.initial_size, |this, initial_size| {
365                // The `self.size` is None, that mean the initial size for the panel,
366                // so we need set `flex_shrink_0` To let it keep the initial size.
367                this.when(
368                    panel_state.size.is_none() && !initial_size.is_zero(),
369                    |this| this.flex_none(),
370                )
371                .flex_basis(initial_size)
372            })
373            .map(|this| match panel_state.size {
374                Some(size) => this.flex_basis(size.min(size_range.end).max(size_range.start)),
375                None => this,
376            })
377            // A fixed panel neither grows nor shrinks with the container, so
378            // the first frame of a resize already has its size. Not
379            // `flex_none`, which also resets the basis set above.
380            .when(fixed, |this| this.flex_grow_0().flex_shrink_0())
381            .on_prepaint({
382                let state = state.clone();
383                move |bounds, _, cx| {
384                    if !state.read(cx).panel_size_changes(
385                        self.panel_ix,
386                        bounds,
387                        &self.size_range,
388                        fixed,
389                    ) {
390                        return;
391                    }
392                    state.update(cx, |state, cx| {
393                        state.update_panel_size(self.panel_ix, bounds, self.size_range, fixed, cx)
394                    })
395                }
396            })
397            .children(self.children)
398            .when_some(previous_panel, |this, ix| {
399                this.child(
400                    resize_handle(("resizable-handle", ix), self.axis)
401                        .when_some(self.handle_appearance.clone(), |handle, appearance| {
402                            handle.with_appearance(appearance)
403                        })
404                        .on_drag(DragPanel, move |drag_panel, _, _, cx| {
405                            cx.stop_propagation();
406                            // Set current resizing panel ix
407                            state.update(cx, |state, _| {
408                                state.resizing_panel_ix = Some(ix);
409                            });
410                            cx.new(|_| drag_panel.clone())
411                        }),
412                )
413            })
414    }
415}
416
417struct ResizePanelGroupElement {
418    state: Entity<ResizableState>,
419    on_resize: Rc<dyn Fn(&Entity<ResizableState>, &mut Window, &mut App)>,
420    axis: Axis,
421}
422
423impl Element for ResizePanelGroupElement {
424    type RequestLayoutState = ();
425    type PrepaintState = ();
426
427    fn id(&self) -> Option<gpui::ElementId> {
428        None
429    }
430
431    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
432        None
433    }
434
435    fn request_layout(
436        &mut self,
437        _: Option<&gpui::GlobalElementId>,
438        _: Option<&gpui::InspectorElementId>,
439        window: &mut Window,
440        cx: &mut App,
441    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
442        (window.request_layout(Style::default(), None, cx), ())
443    }
444
445    fn prepaint(
446        &mut self,
447        _: Option<&gpui::GlobalElementId>,
448        _: Option<&gpui::InspectorElementId>,
449        _: Bounds<Pixels>,
450        _: &mut Self::RequestLayoutState,
451        _window: &mut Window,
452        _cx: &mut App,
453    ) -> Self::PrepaintState {
454        ()
455    }
456
457    fn paint(
458        &mut self,
459        _: Option<&gpui::GlobalElementId>,
460        _: Option<&gpui::InspectorElementId>,
461        _: Bounds<Pixels>,
462        _: &mut Self::RequestLayoutState,
463        _: &mut Self::PrepaintState,
464        window: &mut Window,
465        cx: &mut App,
466    ) {
467        // A drag cancelled with `cx.stop_active_drag` gets no mouse up, so end
468        // it after this frame instead of leaving `is_resizing()` stuck.
469        if self.state.read(cx).resizing_panel_ix.is_some() && !cx.has_active_drag() {
470            let state = self.state.clone();
471            let on_resize = self.on_resize.clone();
472            window.defer(cx, move |window, cx| {
473                if state.read(cx).resizing_panel_ix.is_none() || cx.has_active_drag() {
474                    return;
475                }
476                state.update(cx, |state, cx| {
477                    state.done_resizing(cx);
478                    cx.notify();
479                });
480                on_resize(&state, window, cx);
481            });
482        }
483
484        window.on_mouse_event({
485            let state = self.state.clone();
486            let axis = self.axis;
487            move |e: &MouseMoveEvent, phase, window, cx| {
488                if !phase.bubble() || !cx.has_active_drag() {
489                    return;
490                }
491                let Some(ix) = state.read(cx).resizing_panel_ix else {
492                    return;
493                };
494
495                state.update(cx, |state, cx| {
496                    let panel = state.panels.get(ix).expect("BUG: invalid panel index");
497
498                    match axis {
499                        Axis::Horizontal => state.resize_panel_at_handle(
500                            ix,
501                            e.position.x - panel.bounds.left(),
502                            window,
503                            cx,
504                        ),
505                        Axis::Vertical => state.resize_panel_at_handle(
506                            ix,
507                            e.position.y - panel.bounds.top(),
508                            window,
509                            cx,
510                        ),
511                    }
512                    cx.notify();
513                })
514            }
515        });
516
517        // When any mouse up, stop dragging
518        window.on_mouse_event({
519            let state = self.state.clone();
520            let on_resize = self.on_resize.clone();
521            move |_: &MouseUpEvent, phase, window, cx| {
522                if state.read(cx).resizing_panel_ix.is_none() {
523                    return;
524                }
525                if phase.bubble() {
526                    state.update(cx, |state, cx| state.done_resizing(cx));
527                    on_resize(&state, window, cx);
528                }
529            }
530        })
531    }
532}