Panels split horizontally or vertically by draggable dividers, with sizes in percent.
use gpui::{div, prelude::*, px, Axis, Context, FontWeight, SharedString, Window};
use crate::theme::ActiveTheme;
use crate::ui::resizable::ResizablePanelGroup;
pub struct Workspace {
columns: Vec<f32>,
rows: Vec<f32>,
}
impl Default for Workspace {
fn default() -> Self {
Self { columns: vec![50.0, 50.0], rows: vec![25.0, 75.0] }
}
}
fn pane(label: impl Into<SharedString>) -> impl IntoElement {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.p_6()
.font_weight(FontWeight::SEMIBOLD)
.child(label.into())
}
impl Render for Workspace {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let border = cx.theme().border;
let stacked = ResizablePanelGroup::new("rows", Axis::Vertical)
.sizes(self.rows.clone())
.on_resize(cx.listener(|this, sizes: &Vec<f32>, _, cx| {
this.rows = sizes.clone();
cx.notify();
}))
.panel(pane("Two"))
.panel(pane("Three"));
div()
.w(px(448.0))
.h(px(200.0))
.rounded(px(10.0))
.border_1()
.border_color(border)
.overflow_hidden()
.child(
ResizablePanelGroup::new("columns", Axis::Horizontal)
.sizes(self.columns.clone())
.with_handle(true)
.on_resize(cx.listener(|this, sizes: &Vec<f32>, _, cx| {
this.columns = sizes.clone();
cx.notify();
}))
.panel(pane("One"))
.panel(stacked),
)
}
}Installation
Copies src/ui/resizable.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/resizable.rs.src/ui/resizable.rs use std::rc::Rc; use gpui::{ div, prelude::*, px, svg, Along, AnyElement, App, Axis, CursorStyle, ElementId, EmptyView, Hsla, Pixels, Window, }; use crate::theme::ActiveTheme; use crate::icons::{GRIP_HORIZONTAL, GRIP_VERTICAL}; /// How far the grabbable area reaches past each side of the 1px divider. const HIT_SLOP: Pixels = px(4.0); type ResizeHandler = Rc<dyn Fn(&Vec<f32>, &mut Window, &mut App) + 'static>; /// Drag payload: the group and the handle index. `on_drag_move` fires for every listener of /// this type, so nested groups use the id to ignore each other's handles. struct HandleDrag(ElementId, usize); /// Panels laid out side by side (`Axis::Horizontal`) or stacked (`Axis::Vertical`) with /// draggable dividers between them. The parent view owns `sizes`, in percent, and stores the /// new sizes it receives in `on_resize`, so it can also persist or reset the layout. #[derive(IntoElement)] pub struct ResizablePanelGroup { id: ElementId, axis: Axis, panels: Vec<AnyElement>, sizes: Vec<f32>, min_size: f32, with_handle: bool, on_resize: Option<ResizeHandler>, } impl ResizablePanelGroup { pub fn new(id: impl Into<ElementId>, axis: Axis) -> Self { Self { id: id.into(), axis, panels: Vec::new(), sizes: Vec::new(), min_size: 10.0, with_handle: false, on_resize: None, } } pub fn panel(mut self, panel: impl IntoElement) -> Self { self.panels.push(panel.into_any_element()); self } /// One percentage per panel. Missing or mismatched sizes fall back to an even split. pub fn sizes(mut self, sizes: impl IntoIterator<Item = f32>) -> Self { self.sizes = sizes.into_iter().collect(); self } /// The smallest size, in percent, a drag can shrink a panel to. pub fn min_size(mut self, min_size: f32) -> Self { self.min_size = min_size.max(0.0); self } /// Draws a small grip on each divider, like shadcn's `withHandle`. pub fn with_handle(mut self, with_handle: bool) -> Self { self.with_handle = with_handle; self } /// Receives every panel's next size, in percent. pub fn on_resize(mut self, handler: impl Fn(&Vec<f32>, &mut Window, &mut App) + 'static) -> Self { self.on_resize = Some(Rc::new(handler)); self } } impl RenderOnce for ResizablePanelGroup { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let (border, fg) = (theme.border, theme.foreground); let axis = self.axis; let count = self.panels.len(); let sizes = if self.sizes.len() == count && self.sizes.iter().all(|s| s.is_finite() && *s >= 0.0) { self.sizes } else { vec![100.0 / count.max(1) as f32; count] }; let cursor = match axis { Axis::Horizontal => CursorStyle::ResizeColumn, Axis::Vertical => CursorStyle::ResizeRow, }; let mut children: Vec<AnyElement> = Vec::with_capacity(count * 2); for (ix, panel) in self.panels.into_iter().enumerate() { if ix > 0 { children.push(handle(self.id.clone(), ix - 1, axis, self.with_handle, border, fg)); } // Growing from a zero basis in proportion to the sizes splits whatever space the // dividers leave, so the percentages hold at any group size. let panel_div = div() .flex_basis(px(0.0)) .flex_grow(sizes[ix]) .flex_shrink(1.0) .overflow_hidden() .map(|this| match axis { Axis::Horizontal => this.min_w_0().h_full(), Axis::Vertical => this.min_h_0().w_full(), }) .child(panel); children.push(panel_div.into_any_element()); } let id = self.id.clone(); let min = self.min_size; div() .id(self.id) .flex() .size_full() .when(axis == Axis::Vertical, |this| this.flex_col()) .when_some(self.on_resize, |this, on_resize| { this.on_drag_move::<HandleDrag>(move |event, window, cx| { let HandleDrag(drag_id, ix) = event.drag(cx); let ix = *ix; if *drag_id != id || ix + 1 >= sizes.len() { return; } // The pointer leaves the thin divider mid-drag; keep the resize cursor anyway. if cx.active_drag_cursor_style() != Some(cursor) { cx.set_active_drag_cursor_style(cursor, window); } let length = event.bounds.size.along(axis); if length <= px(0.0) { return; } let total: f32 = sizes.iter().sum(); let pointer = (event.event.position.along(axis) - event.bounds.origin.along(axis)) / length * total; let start: f32 = sizes[..ix].iter().sum(); let pair = sizes[ix] + sizes[ix + 1]; let min = min.min(pair / 2.0); let first = (pointer - start).clamp(min, pair - min); if (first - sizes[ix]).abs() < f32::EPSILON { return; } let mut next = sizes.clone(); next[ix] = first; next[ix + 1] = pair - first; on_resize(&next, window, cx); }) }) .children(children) } } fn handle( group: ElementId, ix: usize, axis: Axis, with_grip: bool, border: Hsla, fg: Hsla, ) -> AnyElement { let grip = with_grip.then(|| { div() .flex() .items_center() .justify_center() .rounded(px(2.0)) .border_1() .border_color(border) .bg(border) .map(|this| match axis { Axis::Horizontal => this.w(px(12.0)).h(px(16.0)), Axis::Vertical => this.w(px(16.0)).h(px(12.0)), }) .child( svg() .data(match axis { Axis::Horizontal => GRIP_VERTICAL, Axis::Vertical => GRIP_HORIZONTAL, }) .size(px(10.0)) .text_color(fg), ) }); // The divider itself is 1px; a wider invisible strip on top makes it easy to grab. let hit_area = div() .id(("resize-handle", ix)) .absolute() .map(|this| match axis { Axis::Horizontal => this.top_0().bottom_0().left(-HIT_SLOP).right(-HIT_SLOP), Axis::Vertical => this.left_0().right_0().top(-HIT_SLOP).bottom(-HIT_SLOP), }) .map(|this| match axis { Axis::Horizontal => this.cursor_col_resize(), Axis::Vertical => this.cursor_row_resize(), }) .on_drag(HandleDrag(group, ix), move |_, _, _, cx| cx.new(|_| EmptyView)); div() .relative() .flex_none() .flex() .items_center() .justify_center() .bg(border) .map(|this| match axis { Axis::Horizontal => this.w(px(1.0)).h_full(), Axis::Vertical => this.h(px(1.0)).w_full(), }) .children(grip) .child(hit_area) .into_any_element() }Register the module
// src/ui/mod.rs pub mod resizable;
Usage
use crate::ui::resizable::*;API Reference
ResizablePanelGroup
Panels laid out side by side (Axis::Horizontal) or stacked (Axis::Vertical) with draggable dividers between them. The parent view owns sizes, in percent, and stores the new sizes it receives in on_resize, so it can also persist or reset the layout.
ResizablePanelGroup::new(id: impl Into<ElementId>, axis: Axis) -> Self.panel(panel: impl IntoElement).sizes(sizes: impl IntoIterator<Item = f32>)One percentage per panel. Missing or mismatched sizes fall back to an even split.
.min_size(min_size: f32)The smallest size, in percent, a drag can shrink a panel to.
.with_handle(with_handle: bool)Draws a small grip on each divider, like shadcn's withHandle.
.on_resize(handler: impl Fn(&Vec<f32>, &mut Window, &mut App) + 'static)Receives every panel's next size, in percent.