use std::ops::Range;
use gpui::{Along, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, px};
mod panel;
mod resize_handle;
pub use panel::*;
pub use resize_handle::{
HandleEdge, ResizeHandle, ResizeHandleContext, ResizeHandleRenderer, ResizeHandleState,
resize_handle,
};
#[doc(hidden)]
pub const PANEL_MIN_SIZE: Pixels = px(100.);
pub fn h_resizable(id: impl Into<ElementId>) -> ResizablePanelGroup {
ResizablePanelGroup::new(id).axis(Axis::Horizontal)
}
pub fn v_resizable(id: impl Into<ElementId>) -> ResizablePanelGroup {
ResizablePanelGroup::new(id).axis(Axis::Vertical)
}
pub fn resizable_panel() -> ResizablePanel {
ResizablePanel::new()
}
#[derive(Debug, Clone)]
pub struct ResizableState {
axis: Axis,
panels: Vec<ResizablePanelState>,
sizes: Vec<Pixels>,
resizing_panel_ix: Option<usize>,
bounds: Bounds<Pixels>,
}
impl Default for ResizableState {
fn default() -> Self {
Self {
axis: Axis::Horizontal,
panels: vec![],
sizes: vec![],
resizing_panel_ix: None,
bounds: Bounds::default(),
}
}
}
impl ResizableState {
pub fn sizes(&self) -> &Vec<Pixels> {
&self.sizes
}
pub fn is_resizing(&self) -> bool {
self.resizing_panel_ix.is_some()
}
pub fn resize_panel(
&mut self,
ix: usize,
size: Pixels,
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.panels.get(ix).is_none_or(|panel| panel.hidden) {
return;
}
if self.next_visible_panel(ix).is_some() {
self.resize_panel_at_handle(ix, size, window, cx);
} else if let Some(previous) = self.previous_visible_panel(ix) {
let delta = self.panels[ix].bounds.size.along(self.axis) - size;
let previous_size = self.panels[previous].bounds.size.along(self.axis);
self.resize_panel_at_handle(previous, previous_size + delta, window, cx);
}
self.done_resizing(cx);
}
pub fn insert_panel(
&mut self,
size: Option<Pixels>,
ix: Option<usize>,
cx: &mut Context<Self>,
) {
let panel_state = ResizablePanelState {
size,
..Default::default()
};
let size = size.unwrap_or(PANEL_MIN_SIZE);
let container_size = self.container_size().max(px(1.));
let total_leftover_size = (container_size - size).max(px(1.));
for (i, panel) in self.panels.iter_mut().enumerate() {
if panel.hidden {
continue;
}
let ratio = self.sizes[i] / container_size;
self.sizes[i] = total_leftover_size * ratio;
panel.size = Some(self.sizes[i]);
}
if let Some(ix) = ix {
self.panels.insert(ix, panel_state);
self.sizes.insert(ix, size);
} else {
self.panels.push(panel_state);
self.sizes.push(size);
};
cx.notify();
}
pub(crate) fn adopt_sizes(&mut self, sizes: &[Option<Pixels>], cx: &mut Context<Self>) {
let mut changed = false;
for (ix, size) in sizes.iter().enumerate() {
if let Some(panel) = self.panels.get_mut(ix) {
if panel.size != *size {
panel.size = *size;
changed = true;
}
if panel.hidden {
continue;
}
}
let Some(size) = size else { continue };
if let Some(slot) = self.sizes.get_mut(ix) {
if *slot != *size {
*slot = *size;
changed = true;
}
}
}
if changed {
cx.notify();
}
}
pub(crate) fn sync_panels_count(
&mut self,
axis: Axis,
panels_count: usize,
cx: &mut Context<Self>,
) {
let mut changed = self.axis != axis;
self.axis = axis;
if panels_count > self.panels.len() {
let diff = panels_count - self.panels.len();
self.panels
.extend(vec![ResizablePanelState::default(); diff]);
self.sizes.extend(vec![PANEL_MIN_SIZE; diff]);
changed = true;
}
if panels_count < self.panels.len() {
self.panels.truncate(panels_count);
self.sizes.truncate(panels_count);
changed = true;
}
if changed {
self.adjust_to_container_size(cx);
}
}
fn sync_panel_visibility(
&mut self,
visibility: impl Iterator<Item = bool>,
cx: &mut Context<Self>,
) {
let mut changed = false;
for ((panel, size), visible) in self.panels.iter_mut().zip(&mut self.sizes).zip(visibility)
{
if panel.hidden == visible {
panel.hidden = !visible;
*size = if visible {
panel.size.unwrap_or(PANEL_MIN_SIZE)
} else {
px(0.)
};
changed = true;
}
}
if changed {
self.resizing_panel_ix = None;
cx.notify();
}
}
fn previous_visible_panel(&self, ix: usize) -> Option<usize> {
(0..ix).rfind(|&ix| !self.panels[ix].hidden)
}
fn next_visible_panel(&self, ix: usize) -> Option<usize> {
(ix + 1..self.panels.len()).find(|&ix| !self.panels[ix].hidden)
}
pub(crate) fn panel_size_changes(
&self,
panel_ix: usize,
bounds: Bounds<Pixels>,
size_range: &Range<Pixels>,
fixed: bool,
) -> bool {
let Some(panel) = self.panels.get(panel_ix) else {
return true;
};
self.sizes.get(panel_ix).map(|size| size.as_f32()) == Some(PANEL_MIN_SIZE.as_f32())
|| panel.bounds != bounds
|| panel.size_range != *size_range
|| panel.fixed != fixed
}
pub(crate) fn update_panel_size(
&mut self,
panel_ix: usize,
bounds: Bounds<Pixels>,
size_range: Range<Pixels>,
fixed: bool,
cx: &mut Context<Self>,
) {
self.panels[panel_ix].fixed = fixed;
let size = bounds.size.along(self.axis);
if self.sizes[panel_ix].as_f32() == PANEL_MIN_SIZE.as_f32() {
self.sizes[panel_ix] = size;
self.panels[panel_ix].size = Some(size);
}
self.panels[panel_ix].bounds = bounds;
self.panels[panel_ix].size_range = size_range;
cx.notify();
}
pub fn remove_panel(&mut self, panel_ix: usize, cx: &mut Context<Self>) {
self.panels.remove(panel_ix);
self.sizes.remove(panel_ix);
if let Some(resizing_panel_ix) = self.resizing_panel_ix {
if resizing_panel_ix > panel_ix {
self.resizing_panel_ix = Some(resizing_panel_ix - 1);
}
}
self.adjust_to_container_size(cx);
}
pub fn reset_panel(&mut self, panel_ix: usize, cx: &mut Context<Self>) {
let panel = &mut self.panels[panel_ix];
*panel = ResizablePanelState {
hidden: panel.hidden,
size: if panel.hidden { panel.size } else { None },
..Default::default()
};
self.adjust_to_container_size(cx);
}
pub fn clear(&mut self) {
self.panels.clear();
self.sizes.clear();
self.resizing_panel_ix = None;
}
#[inline]
pub fn container_size(&self) -> Pixels {
self.bounds.size.along(self.axis)
}
pub(crate) fn done_resizing(&mut self, cx: &mut Context<Self>) {
self.resizing_panel_ix = None;
cx.emit(ResizablePanelEvent::Resized);
}
fn resize_panel_at_handle(
&mut self,
ix: usize,
size: Pixels,
_: &mut Window,
cx: &mut Context<Self>,
) {
if self.panels.get(ix).is_none_or(|panel| panel.hidden) {
return;
}
let Some(next) = self.next_visible_panel(ix) else {
return;
};
let mut sizes: Vec<_> = self
.panels
.iter()
.map(|panel| {
if panel.hidden {
px(0.)
} else {
panel.bounds.size.along(self.axis)
}
})
.collect();
let delta = size - sizes[ix];
if delta > px(0.) {
self.transfer_size(&mut sizes, ix, next..self.panels.len(), delta);
} else if delta < px(0.) {
self.transfer_size(&mut sizes, next, (0..=ix).rev(), -delta);
}
if sizes != self.sizes {
for (panel, &size) in self.panels.iter_mut().zip(&sizes) {
if !panel.hidden {
panel.size = Some(size);
}
}
self.sizes = sizes;
cx.notify();
}
}
fn transfer_size(
&self,
sizes: &mut [Pixels],
receiver: usize,
donors: impl Iterator<Item = usize>,
delta: Pixels,
) {
let capacity = (self.panels[receiver].size_range.end - sizes[receiver]).max(px(0.));
let mut remaining = delta.min(capacity);
for (index, donor) in donors.enumerate() {
if remaining.is_zero() {
break;
}
let panel = &self.panels[donor];
if panel.hidden || (panel.fixed && index != 0) {
continue;
}
let amount = remaining.min((sizes[donor] - panel.size_range.start).max(px(0.)));
sizes[donor] -= amount;
sizes[receiver] += amount;
remaining -= amount;
}
}
fn adjust_to_container_size(&mut self, cx: &mut Context<Self>) {
if self.container_size().is_zero() {
return;
}
if self
.panels
.iter()
.any(|panel| !panel.hidden && panel.size.is_none())
{
return;
}
let sum = |fixed: bool| {
self.panels
.iter()
.zip(&self.sizes)
.filter(|(panel, _)| !panel.hidden && panel.fixed == fixed)
.map(|(_, size)| size.as_f32())
.sum::<f32>()
};
let (fixed_size, total) = (px(sum(true)), sum(false));
if !total.is_finite() || total <= 0. {
return;
}
let total_size = px(total);
let available = self.container_size() - fixed_size;
if available <= px(0.) {
return;
}
for i in 0..self.panels.len() {
if self.panels[i].hidden {
continue;
}
if self.panels[i].fixed {
self.panels[i].size = Some(self.sizes[i]);
continue;
}
let size = self.sizes[i];
let ratio = size / total_size;
let new_size = available * ratio;
self.sizes[i] = new_size;
self.panels[i].size = Some(new_size);
}
cx.notify();
}
}
impl EventEmitter<ResizablePanelEvent> for ResizableState {}
#[derive(Debug, Clone, Default)]
pub(crate) struct ResizablePanelState {
pub size: Option<Pixels>,
pub size_range: Range<Pixels>,
bounds: Bounds<Pixels>,
pub(crate) fixed: bool,
hidden: bool,
}
#[cfg(test)]
mod tests {
use std::{
cell::{Cell, RefCell},
rc::Rc,
};
use gpui::{
App, AppContext as _, Axis, Context, InputEvent as _, InteractiveElement as _, IntoElement,
Modifiers, MouseButton, ParentElement as _, Pixels, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, prelude::FluentBuilder as _, px, size,
};
use super::{
ResizableState, ResizeHandleContext, ResizeHandleState, h_resizable, resizable_panel,
};
struct MixedSizingHarness {
width: Pixels,
}
impl Render for MixedSizingHarness {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().w(self.width).h(px(100.)).child(
h_resizable("mixed-sizing")
.child(
resizable_panel()
.size(px(240.))
.child(div().size_full().debug_selector(|| "fixed-sidebar".into())),
)
.child(
resizable_panel().child(
div()
.size_full()
.debug_selector(|| "flexible-content".into()),
),
),
)
}
}
#[gpui::test]
fn mixed_sizing_is_stable_between_resize_and_followup_frame(cx: &mut TestAppContext) {
let (view, cx) = cx.add_window_view(|_, _| MixedSizingHarness { width: px(800.) });
cx.update(|window, cx| {
window.draw(cx).clear(cx);
window.draw(cx).clear(cx);
});
let before = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
view.update(cx, |view, cx| {
view.width = px(1200.);
cx.notify();
});
cx.run_until_parked();
let settled_frame = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
cx.update(|window, cx| window.draw(cx).clear(cx));
let followup_frame = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
assert_ne!(settled_frame, before);
assert_eq!(followup_frame, settled_frame);
}
struct FixedPanelHarness {
width: Pixels,
fixed: bool,
state: gpui::Entity<ResizableState>,
}
impl Render for FixedPanelHarness {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().w(self.width).h(px(100.)).child(
h_resizable("fixed-panel")
.with_state(&self.state)
.child(
resizable_panel()
.size(px(240.))
.size_range(px(100.)..px(480.))
.when(self.fixed, |panel| panel.fixed())
.child(div().size_full().debug_selector(|| "fp-sidebar".into())),
)
.child(
resizable_panel()
.size(px(400.))
.child(div().size_full().debug_selector(|| "fp-main".into())),
)
.child(
resizable_panel()
.child(div().size_full().debug_selector(|| "fp-aside".into())),
),
)
}
}
#[gpui::test]
fn fixed_panel_keeps_its_size_across_a_container_resize(cx: &mut TestAppContext) {
let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
let (view, cx) = cx.add_window_view({
let state = state.clone();
move |_, _| FixedPanelHarness {
width: px(840.),
fixed: true,
state,
}
});
cx.update(|window, cx| {
window.draw(cx).clear(cx);
window.draw(cx).clear(cx);
});
let widths = |cx: &mut VisualTestContext| {
["fp-sidebar", "fp-main", "fp-aside"].map(|selector| {
cx.debug_bounds(selector)
.expect("every panel must lay out")
.size
.width
})
};
assert_eq!(widths(cx), [px(240.), px(400.), px(200.)]);
for (width, expected) in [
(px(1140.), Some([px(240.), px(600.), px(300.)])),
(px(200.), None),
(px(600.), Some([px(240.), px(240.), px(120.)])),
] {
view.update(cx, |view, cx| {
view.width = width;
cx.notify();
});
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));
assert_eq!(widths(cx)[0], px(240.), "{width:?}");
if let Some(expected) = expected {
assert_eq!(widths(cx), expected, "{width:?}");
}
}
cx.update(|window, cx| {
state.update(cx, |state, cx| state.resize_panel(1, px(50.), window, cx));
window.draw(cx).clear(cx);
});
assert_eq!(widths(cx), [px(240.), px(100.), px(260.)]);
cx.update(|window, cx| {
state.update(cx, |state, cx| state.resize_panel(0, px(300.), window, cx));
window.draw(cx).clear(cx);
});
assert_eq!(widths(cx), [px(300.), px(100.), px(200.)]);
view.update(cx, |view, cx| {
view.width = px(900.);
cx.notify();
});
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));
assert_eq!(widths(cx)[0], px(300.));
}
#[gpui::test]
fn panel_made_fixed_in_place_keeps_its_size_across_a_container_resize(cx: &mut TestAppContext) {
let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
let (view, cx) = cx.add_window_view(move |_, _| FixedPanelHarness {
width: px(840.),
fixed: false,
state,
});
let draw = |cx: &mut VisualTestContext, update: fn(&mut FixedPanelHarness)| {
view.update(cx, |view, cx| {
update(view);
cx.notify();
});
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));
};
draw(cx, |_| {});
draw(cx, |view| view.fixed = true);
draw(cx, |view| view.width = px(1140.));
let sidebar = cx
.debug_bounds("fp-sidebar")
.expect("the sidebar must lay out");
assert_eq!(sidebar.size.width, px(240.));
}
struct CallerStateHarness {
width: Pixels,
state: gpui::Entity<ResizableState>,
}
impl Render for CallerStateHarness {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().w(self.width).h(px(100.)).child(
h_resizable("caller-state")
.with_state(&self.state)
.child(
resizable_panel()
.size(px(240.))
.child(div().size_full().debug_selector(|| "cs-sidebar".into())),
)
.child(resizable_panel().child(div().size_full())),
)
}
}
#[gpui::test]
fn caller_owned_state_settles_on_the_same_frame(cx: &mut TestAppContext) {
let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
let (view, cx) = cx.add_window_view(move |_, _| CallerStateHarness {
width: px(800.),
state,
});
cx.update(|window, cx| {
window.draw(cx).clear(cx);
window.draw(cx).clear(cx);
});
view.update(cx, |view, cx| {
view.width = px(1200.);
cx.notify();
});
cx.run_until_parked();
let settled = cx.debug_bounds("cs-sidebar").unwrap().size.width;
cx.update(|window, cx| window.draw(cx).clear(cx));
let followup = cx.debug_bounds("cs-sidebar").unwrap().size.width;
assert_eq!(followup, settled, "settling frame must not be pending");
}
struct ResizableHarness {
state: gpui::Entity<ResizableState>,
resizes: Rc<Cell<usize>>,
}
impl Render for ResizableHarness {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().w(px(400.)).h(px(100.)).child(
h_resizable("resizable")
.with_state(&self.state)
.on_resize({
let resizes = self.resizes.clone();
move |_, _, _| resizes.set(resizes.get() + 1)
})
.child(
resizable_panel()
.size(px(150.))
.child(div().size_full().debug_selector(|| "first-panel".into())),
)
.child(
resizable_panel()
.size(px(250.))
.child(div().size_full().debug_selector(|| "second-panel".into())),
),
)
}
}
fn harness(
cx: &mut TestAppContext,
) -> (
&mut VisualTestContext,
gpui::Entity<ResizableState>,
Rc<Cell<usize>>,
) {
let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
let resizes = Rc::new(Cell::new(0));
let (_, cx) = cx.add_window_view({
let state = state.clone();
let resizes = resizes.clone();
move |_, _| ResizableHarness { state, resizes }
});
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.update(|window, cx| window.draw(cx).clear(cx));
(cx, state, resizes)
}
#[cfg(feature = "gpui-fast")]
struct StateReader {
state: gpui::Entity<ResizableState>,
renders: Rc<Cell<usize>>,
}
#[cfg(feature = "gpui-fast")]
impl Render for StateReader {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
let _ = self.state.read(cx).sizes.len();
div()
}
}
#[cfg(feature = "gpui-fast")]
struct ReaderBesidePanels {
state: gpui::Entity<ResizableState>,
reader: gpui::Entity<StateReader>,
}
#[cfg(feature = "gpui-fast")]
impl Render for ReaderBesidePanels {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.w(px(800.))
.h(px(100.))
.child(self.reader.clone())
.child(
h_resizable("reader-panels")
.with_state(&self.state)
.child(resizable_panel().size(px(240.)).child(div().size_full()))
.child(resizable_panel().child(div().size_full())),
)
}
}
#[cfg(feature = "gpui-fast")]
#[gpui::test]
fn redrawing_panels_where_they_were_leaves_their_readers_retained(cx: &mut TestAppContext) {
let renders = Rc::new(Cell::new(0));
let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
let (view, cx) = cx.add_window_view({
let state = state.clone();
let renders = renders.clone();
move |_, cx| ReaderBesidePanels {
state: state.clone(),
reader: cx.new(|_| StateReader { state, renders }),
}
});
for _ in 0..3 {
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.run_until_parked();
}
let before = renders.get();
for _ in 0..3 {
view.update(cx, |_, cx| cx.notify());
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.run_until_parked();
}
assert_eq!(renders.get(), before, "the reader rendered again");
}
#[gpui::test]
fn dynamic_panel_lifecycle_is_owned_by_resizable_state(cx: &mut TestAppContext) {
let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
cx.update(|cx| {
state.update(cx, |state, cx| {
state.bounds.size = size(px(400.), px(100.));
state.panels.push(Default::default());
state.sizes.push(px(400.));
state.insert_panel(Some(px(200.)), None, cx);
assert_eq!(state.sizes(), &vec![px(200.), px(200.)]);
state.reset_panel(0, cx);
assert_eq!(state.sizes(), &vec![px(200.), px(200.)]);
state.remove_panel(0, cx);
assert_eq!(state.sizes(), &vec![px(400.)]);
state.clear();
assert!(state.sizes().is_empty());
});
});
}
#[gpui::test]
fn group_measures_panels_and_programmatic_resize_uses_drag_rules(cx: &mut TestAppContext) {
let (cx, state, _) = harness(cx);
let first = cx.debug_bounds("first-panel").unwrap();
let second = cx.debug_bounds("second-panel").unwrap();
assert_eq!(first.size.width + second.size.width, px(400.));
cx.update(|window, cx| {
state.update(cx, |state, cx| {
state.resize_panel(0, px(220.), window, cx);
});
window.draw(cx).clear(cx);
});
state.read_with(cx, |state, _| {
assert_eq!(state.sizes(), &vec![px(220.), px(180.)]);
});
}
#[gpui::test]
fn resizing_uses_measured_sizes_and_respects_both_limits(cx: &mut TestAppContext) {
let (cx, state, _) = harness(cx);
cx.update(|window, cx| {
state.update(cx, |state, cx| {
let first = state.panels[0].bounds.size.width;
let second = state.panels[1].bounds.size.width;
state.sizes[0] = first - px(20.);
state.panels[0].size_range.start = first - px(30.);
state.panels[1].size_range.end = second + px(10.);
state.resize_panel_at_handle(0, first - px(50.), window, cx);
assert_eq!(state.sizes.as_slice(), &[first - px(10.), second + px(10.)]);
state.panels[1].size_range.end = second + px(60.);
state.resize_panel_at_handle(0, first - px(50.), window, cx);
assert_eq!(state.sizes.as_slice(), &[first - px(30.), second + px(30.)]);
});
});
}
#[gpui::test]
fn hiding_a_panel_preserves_its_slot_and_preferred_size(cx: &mut TestAppContext) {
let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
cx.update(|cx| {
state.update(cx, |state, cx| {
state.bounds.size = size(px(600.), px(100.));
state.sync_panels_count(Axis::Horizontal, 3, cx);
state.adopt_sizes(&[Some(px(200.)); 3], cx);
state.sync_panel_visibility([true, false, true].into_iter(), cx);
assert_eq!(state.sizes.as_slice(), &[px(200.), px(0.), px(200.)]);
assert_eq!(state.next_visible_panel(0), Some(2));
assert_eq!(state.previous_visible_panel(2), Some(0));
state.insert_panel(Some(px(100.)), None, cx);
state.sync_panel_visibility([true; 4].into_iter(), cx);
assert_eq!(state.sizes[1], px(200.));
assert_eq!(state.next_visible_panel(0), Some(1));
});
});
}
#[gpui::test]
fn dragging_the_handle_resizes_and_emits_once(cx: &mut TestAppContext) {
let (cx, state, resizes) = harness(cx);
let boundary = cx.debug_bounds("second-panel").unwrap().left();
assert!(!state.read_with(cx, |state, _| state.is_resizing()));
cx.simulate_mouse_down(
point(boundary - px(2.), px(50.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_move(
point(boundary + px(10.), px(50.)),
Some(MouseButton::Left),
Modifiers::default(),
);
cx.simulate_mouse_move(
point(px(220.), px(50.)),
Some(MouseButton::Left),
Modifiers::default(),
);
assert!(state.read_with(cx, |state, _| state.is_resizing()));
cx.simulate_mouse_up(
point(px(220.), px(50.)),
MouseButton::Left,
Modifiers::default(),
);
state.read_with(cx, |state, _| {
assert_eq!(state.sizes(), &vec![px(220.), px(180.)]);
assert!(!state.is_resizing());
});
assert_eq!(resizes.get(), 1);
}
#[gpui::test]
fn dragging_before_the_next_paint_resizes_and_emits_once(cx: &mut TestAppContext) {
let (cx, state, resizes) = harness(cx);
let boundary = cx.debug_bounds("second-panel").unwrap().left();
cx.update(|window, cx| {
window.dispatch_event(
gpui::MouseDownEvent {
position: point(boundary - px(2.), px(50.)),
button: MouseButton::Left,
click_count: 1,
..Default::default()
}
.to_platform_input(),
cx,
);
for x in [boundary + px(10.), px(220.)] {
window.dispatch_event(
gpui::MouseMoveEvent {
position: point(x, px(50.)),
pressed_button: Some(MouseButton::Left),
..Default::default()
}
.to_platform_input(),
cx,
);
}
assert_eq!(state.read(cx).resizing_panel_ix, Some(0));
assert_eq!(state.read(cx).sizes(), &vec![px(220.), px(180.)]);
assert_eq!(resizes.get(), 0);
for _ in 0..2 {
window.dispatch_event(
gpui::MouseUpEvent {
position: point(px(220.), px(50.)),
button: MouseButton::Left,
click_count: 1,
..Default::default()
}
.to_platform_input(),
cx,
);
}
window.dispatch_event(
gpui::MouseMoveEvent {
position: point(px(260.), px(50.)),
..Default::default()
}
.to_platform_input(),
cx,
);
assert_eq!(state.read(cx).resizing_panel_ix, None);
assert_eq!(state.read(cx).sizes(), &vec![px(220.), px(180.)]);
assert_eq!(resizes.get(), 1);
});
}
#[gpui::test]
fn cancelled_drag_does_not_reuse_the_painted_index(cx: &mut TestAppContext) {
let (cx, state, resizes) = harness(cx);
let boundary = cx.debug_bounds("second-panel").unwrap().left();
cx.simulate_mouse_down(
point(boundary - px(2.), px(50.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_move(
point(boundary + px(10.), px(50.)),
Some(MouseButton::Left),
Modifiers::default(),
);
cx.update(|window, cx| {
assert_eq!(state.read(cx).resizing_panel_ix, Some(0));
window.draw(cx).clear(cx);
state.update(cx, |state, cx| state.resize_panel(0, px(210.), window, cx));
cx.stop_active_drag(window);
assert_eq!(state.read(cx).resizing_panel_ix, None);
window.dispatch_event(
gpui::MouseMoveEvent {
position: point(px(260.), px(50.)),
pressed_button: Some(MouseButton::Left),
..Default::default()
}
.to_platform_input(),
cx,
);
window.dispatch_event(
gpui::MouseUpEvent {
position: point(px(260.), px(50.)),
button: MouseButton::Left,
click_count: 1,
..Default::default()
}
.to_platform_input(),
cx,
);
assert_eq!(state.read(cx).sizes(), &vec![px(210.), px(190.)]);
assert_eq!(state.read(cx).resizing_panel_ix, None);
assert_eq!(resizes.get(), 0);
});
}
#[gpui::test]
fn clearing_mid_drag_stops_resizing(cx: &mut TestAppContext) {
let (cx, state, _) = harness(cx);
let boundary = cx.debug_bounds("second-panel").unwrap().left();
cx.simulate_mouse_down(
point(boundary - px(2.), px(50.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_move(
point(boundary + px(10.), px(50.)),
Some(MouseButton::Left),
Modifiers::default(),
);
assert!(state.read_with(cx, |state, _| state.is_resizing()));
state.update(cx, |state, _| state.clear());
assert!(!state.read_with(cx, |state, _| state.is_resizing()));
}
#[gpui::test]
fn stopping_the_drag_ends_resizing(cx: &mut TestAppContext) {
let (cx, state, resizes) = harness(cx);
let boundary = cx.debug_bounds("second-panel").unwrap().left();
cx.simulate_mouse_down(
point(boundary - px(2.), px(50.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_move(
point(px(220.), px(50.)),
Some(MouseButton::Left),
Modifiers::default(),
);
assert!(state.read_with(cx, |state, _| state.is_resizing()));
cx.update(|window, cx| {
cx.stop_active_drag(window);
window.draw(cx).clear(cx);
});
let sizes = state.read_with(cx, |state, _| {
assert!(!state.is_resizing());
state.sizes().clone()
});
assert_eq!(resizes.get(), 1);
cx.simulate_mouse_move(
point(px(260.), px(50.)),
Some(MouseButton::Left),
Modifiers::default(),
);
assert_eq!(state.read_with(cx, |state, _| state.sizes().clone()), sizes);
assert_eq!(resizes.get(), 1);
}
struct HandleStateHarness {
seen: Rc<RefCell<Vec<ResizeHandleState>>>,
covered: bool,
}
impl Render for HandleStateHarness {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let seen = self.seen.clone();
div()
.relative()
.w(px(400.))
.h(px(100.))
.child(
h_resizable("handle-state")
.with_handle_appearance(Rc::new(
move |handle: &ResizeHandleContext, _: &mut Window, _: &mut App| {
let mut seen = seen.borrow_mut();
if seen.last() != Some(&handle.state()) {
seen.push(handle.state());
}
None
},
))
.child(resizable_panel().size(px(150.)).child(div().size_full()))
.child(
resizable_panel()
.size(px(250.))
.child(div().size_full().debug_selector(|| "hs-second".into())),
),
)
.when(self.covered, |this| {
this.child(div().absolute().inset_0().occlude())
})
}
}
#[gpui::test]
fn a_covered_handle_stays_idle(cx: &mut TestAppContext) {
let seen: Rc<RefCell<Vec<ResizeHandleState>>> = Rc::new(RefCell::new(Vec::new()));
let (_, cx) = cx.add_window_view({
let seen = seen.clone();
move |_, _| HandleStateHarness {
seen,
covered: true,
}
});
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.update(|window, cx| window.draw(cx).clear(cx));
let boundary = cx.debug_bounds("hs-second").unwrap().left();
let on_handle = point(boundary - px(2.), px(50.));
let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_mouse_move(on_handle, None, Modifiers::default());
draw(cx);
cx.simulate_mouse_down(on_handle, MouseButton::Left, Modifiers::default());
draw(cx);
cx.simulate_mouse_up(on_handle, MouseButton::Left, Modifiers::default());
draw(cx);
assert_eq!(*seen.borrow(), vec![ResizeHandleState::Idle]);
}
#[gpui::test]
fn a_handle_reports_the_press_and_the_drag_to_its_renderer(cx: &mut TestAppContext) {
let seen: Rc<RefCell<Vec<ResizeHandleState>>> = Rc::new(RefCell::new(Vec::new()));
let (_, cx) = cx.add_window_view({
let seen = seen.clone();
move |_, _| HandleStateHarness {
seen,
covered: false,
}
});
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.update(|window, cx| window.draw(cx).clear(cx));
let boundary = cx.debug_bounds("hs-second").unwrap().left();
let on_handle = point(boundary - px(2.), px(50.));
let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_mouse_move(on_handle, None, Modifiers::default());
draw(cx);
cx.simulate_mouse_down(on_handle, MouseButton::Left, Modifiers::default());
draw(cx);
cx.simulate_mouse_move(
point(px(260.), px(50.)),
Some(MouseButton::Left),
Modifiers::default(),
);
draw(cx);
cx.simulate_mouse_up(
point(px(390.), px(90.)),
MouseButton::Left,
Modifiers::default(),
);
draw(cx);
assert_eq!(
*seen.borrow(),
vec![
ResizeHandleState::Idle,
ResizeHandleState::Hovered,
ResizeHandleState::Pressed,
ResizeHandleState::Dragging,
ResizeHandleState::Idle,
]
);
}
struct SizedGroupHarness;
impl Render for SizedGroupHarness {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.w(px(400.))
.h(px(100.))
.child(
h_resizable("sized-resizable").size(px(40.)).child(
resizable_panel()
.child(div().size_full().debug_selector(|| "sized-panel".into())),
),
)
}
}
#[gpui::test]
fn a_group_size_binds_the_cross_axis(cx: &mut TestAppContext) {
let (_, cx) = cx.add_window_view(|_, _| SizedGroupHarness);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.update(|window, cx| window.draw(cx).clear(cx));
let panel = cx.debug_bounds("sized-panel").unwrap();
assert_eq!(panel.size.width, px(400.));
assert_eq!(panel.size.height, px(40.));
}
}