1use std::ops::Range;
2
3use gpui::{Along, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, px};
4
5mod panel;
6mod resize_handle;
7pub use panel::*;
8pub use resize_handle::{
9 HandleEdge, ResizeHandle, ResizeHandleContext, ResizeHandleRenderer, ResizeHandleState,
10 resize_handle,
11};
12
13#[doc(hidden)]
14pub const PANEL_MIN_SIZE: Pixels = px(100.);
15
16pub fn h_resizable(id: impl Into<ElementId>) -> ResizablePanelGroup {
18 ResizablePanelGroup::new(id).axis(Axis::Horizontal)
19}
20
21pub fn v_resizable(id: impl Into<ElementId>) -> ResizablePanelGroup {
23 ResizablePanelGroup::new(id).axis(Axis::Vertical)
24}
25
26pub fn resizable_panel() -> ResizablePanel {
28 ResizablePanel::new()
29}
30
31#[derive(Debug, Clone)]
33pub struct ResizableState {
34 axis: Axis,
36 panels: Vec<ResizablePanelState>,
37 sizes: Vec<Pixels>,
38 resizing_panel_ix: Option<usize>,
39 bounds: Bounds<Pixels>,
40}
41
42impl Default for ResizableState {
43 fn default() -> Self {
44 Self {
45 axis: Axis::Horizontal,
46 panels: vec![],
47 sizes: vec![],
48 resizing_panel_ix: None,
49 bounds: Bounds::default(),
50 }
51 }
52}
53
54impl ResizableState {
55 pub fn sizes(&self) -> &Vec<Pixels> {
57 &self.sizes
58 }
59
60 pub fn is_resizing(&self) -> bool {
65 self.resizing_panel_ix.is_some()
66 }
67
68 pub fn resize_panel(
78 &mut self,
79 ix: usize,
80 size: Pixels,
81 window: &mut Window,
82 cx: &mut Context<Self>,
83 ) {
84 if self.panels.get(ix).is_none_or(|panel| panel.hidden) {
85 return;
86 }
87 if self.next_visible_panel(ix).is_some() {
88 self.resize_panel_at_handle(ix, size, window, cx);
89 } else if let Some(previous) = self.previous_visible_panel(ix) {
90 let delta = self.panels[ix].bounds.size.along(self.axis) - size;
93 let previous_size = self.panels[previous].bounds.size.along(self.axis);
94 self.resize_panel_at_handle(previous, previous_size + delta, window, cx);
95 }
96 self.done_resizing(cx);
97 }
98
99 pub fn insert_panel(
104 &mut self,
105 size: Option<Pixels>,
106 ix: Option<usize>,
107 cx: &mut Context<Self>,
108 ) {
109 let panel_state = ResizablePanelState {
110 size,
111 ..Default::default()
112 };
113
114 let size = size.unwrap_or(PANEL_MIN_SIZE);
115
116 let container_size = self.container_size().max(px(1.));
119 let total_leftover_size = (container_size - size).max(px(1.));
120
121 for (i, panel) in self.panels.iter_mut().enumerate() {
122 if panel.hidden {
123 continue;
124 }
125 let ratio = self.sizes[i] / container_size;
126 self.sizes[i] = total_leftover_size * ratio;
127 panel.size = Some(self.sizes[i]);
128 }
129
130 if let Some(ix) = ix {
131 self.panels.insert(ix, panel_state);
132 self.sizes.insert(ix, size);
133 } else {
134 self.panels.push(panel_state);
135 self.sizes.push(size);
136 };
137
138 cx.notify();
139 }
140
141 pub(crate) fn adopt_sizes(&mut self, sizes: &[Option<Pixels>], cx: &mut Context<Self>) {
149 let mut changed = false;
150 for (ix, size) in sizes.iter().enumerate() {
151 if let Some(panel) = self.panels.get_mut(ix) {
159 if panel.size != *size {
160 panel.size = *size;
161 changed = true;
162 }
163 if panel.hidden {
164 continue;
165 }
166 }
167
168 let Some(size) = size else { continue };
172 if let Some(slot) = self.sizes.get_mut(ix) {
173 if *slot != *size {
174 *slot = *size;
175 changed = true;
176 }
177 }
178 }
179
180 if changed {
181 cx.notify();
182 }
183 }
184
185 pub(crate) fn sync_panels_count(
186 &mut self,
187 axis: Axis,
188 panels_count: usize,
189 cx: &mut Context<Self>,
190 ) {
191 let mut changed = self.axis != axis;
192 self.axis = axis;
193
194 if panels_count > self.panels.len() {
195 let diff = panels_count - self.panels.len();
196 self.panels
197 .extend(vec![ResizablePanelState::default(); diff]);
198 self.sizes.extend(vec![PANEL_MIN_SIZE; diff]);
199 changed = true;
200 }
201
202 if panels_count < self.panels.len() {
203 self.panels.truncate(panels_count);
204 self.sizes.truncate(panels_count);
205 changed = true;
206 }
207
208 if changed {
209 self.adjust_to_container_size(cx);
211 }
212 }
213
214 fn sync_panel_visibility(
215 &mut self,
216 visibility: impl Iterator<Item = bool>,
217 cx: &mut Context<Self>,
218 ) {
219 let mut changed = false;
220 for ((panel, size), visible) in self.panels.iter_mut().zip(&mut self.sizes).zip(visibility)
221 {
222 if panel.hidden == visible {
223 panel.hidden = !visible;
224 *size = if visible {
226 panel.size.unwrap_or(PANEL_MIN_SIZE)
227 } else {
228 px(0.)
229 };
230 changed = true;
231 }
232 }
233 if changed {
234 self.resizing_panel_ix = None;
235 cx.notify();
237 }
238 }
239
240 fn previous_visible_panel(&self, ix: usize) -> Option<usize> {
241 (0..ix).rfind(|&ix| !self.panels[ix].hidden)
242 }
243
244 fn next_visible_panel(&self, ix: usize) -> Option<usize> {
245 (ix + 1..self.panels.len()).find(|&ix| !self.panels[ix].hidden)
246 }
247
248 pub(crate) fn panel_size_changes(
253 &self,
254 panel_ix: usize,
255 bounds: Bounds<Pixels>,
256 size_range: &Range<Pixels>,
257 fixed: bool,
258 ) -> bool {
259 let Some(panel) = self.panels.get(panel_ix) else {
260 return true;
261 };
262 self.sizes.get(panel_ix).map(|size| size.as_f32()) == Some(PANEL_MIN_SIZE.as_f32())
263 || panel.bounds != bounds
264 || panel.size_range != *size_range
265 || panel.fixed != fixed
266 }
267
268 pub(crate) fn update_panel_size(
269 &mut self,
270 panel_ix: usize,
271 bounds: Bounds<Pixels>,
272 size_range: Range<Pixels>,
273 fixed: bool,
274 cx: &mut Context<Self>,
275 ) {
276 self.panels[panel_ix].fixed = fixed;
277 let size = bounds.size.along(self.axis);
278 if self.sizes[panel_ix].as_f32() == PANEL_MIN_SIZE.as_f32() {
282 self.sizes[panel_ix] = size;
283 self.panels[panel_ix].size = Some(size);
284 }
285 self.panels[panel_ix].bounds = bounds;
286 self.panels[panel_ix].size_range = size_range;
287 cx.notify();
288 }
289
290 pub fn remove_panel(&mut self, panel_ix: usize, cx: &mut Context<Self>) {
292 self.panels.remove(panel_ix);
293 self.sizes.remove(panel_ix);
294 if let Some(resizing_panel_ix) = self.resizing_panel_ix {
295 if resizing_panel_ix > panel_ix {
296 self.resizing_panel_ix = Some(resizing_panel_ix - 1);
297 }
298 }
299 self.adjust_to_container_size(cx);
300 }
301
302 pub fn reset_panel(&mut self, panel_ix: usize, cx: &mut Context<Self>) {
304 let panel = &mut self.panels[panel_ix];
305 *panel = ResizablePanelState {
306 hidden: panel.hidden,
307 size: if panel.hidden { panel.size } else { None },
308 ..Default::default()
309 };
310 self.adjust_to_container_size(cx);
311 }
312
313 pub fn clear(&mut self) {
315 self.panels.clear();
316 self.sizes.clear();
317 self.resizing_panel_ix = None;
318 }
319
320 #[inline]
321 pub fn container_size(&self) -> Pixels {
323 self.bounds.size.along(self.axis)
324 }
325
326 pub(crate) fn done_resizing(&mut self, cx: &mut Context<Self>) {
327 self.resizing_panel_ix = None;
328 cx.emit(ResizablePanelEvent::Resized);
329 }
330
331 fn resize_panel_at_handle(
337 &mut self,
338 ix: usize,
339 size: Pixels,
340 _: &mut Window,
341 cx: &mut Context<Self>,
342 ) {
343 if self.panels.get(ix).is_none_or(|panel| panel.hidden) {
344 return;
345 }
346 let Some(next) = self.next_visible_panel(ix) else {
347 return;
348 };
349 let mut sizes: Vec<_> = self
351 .panels
352 .iter()
353 .map(|panel| {
354 if panel.hidden {
355 px(0.)
356 } else {
357 panel.bounds.size.along(self.axis)
358 }
359 })
360 .collect();
361 let delta = size - sizes[ix];
362 if delta > px(0.) {
363 self.transfer_size(&mut sizes, ix, next..self.panels.len(), delta);
364 } else if delta < px(0.) {
365 self.transfer_size(&mut sizes, next, (0..=ix).rev(), -delta);
366 }
367
368 if sizes != self.sizes {
369 for (panel, &size) in self.panels.iter_mut().zip(&sizes) {
370 if !panel.hidden {
371 panel.size = Some(size);
372 }
373 }
374 self.sizes = sizes;
375 cx.notify();
376 }
377 }
378
379 fn transfer_size(
380 &self,
381 sizes: &mut [Pixels],
382 receiver: usize,
383 donors: impl Iterator<Item = usize>,
384 delta: Pixels,
385 ) {
386 let capacity = (self.panels[receiver].size_range.end - sizes[receiver]).max(px(0.));
387 let mut remaining = delta.min(capacity);
388 for (index, donor) in donors.enumerate() {
389 if remaining.is_zero() {
390 break;
391 }
392 let panel = &self.panels[donor];
393 if panel.hidden || (panel.fixed && index != 0) {
395 continue;
396 }
397 let amount = remaining.min((sizes[donor] - panel.size_range.start).max(px(0.)));
398 sizes[donor] -= amount;
399 sizes[receiver] += amount;
400 remaining -= amount;
401 }
402 }
403
404 fn adjust_to_container_size(&mut self, cx: &mut Context<Self>) {
408 if self.container_size().is_zero() {
409 return;
410 }
411
412 if self
420 .panels
421 .iter()
422 .any(|panel| !panel.hidden && panel.size.is_none())
423 {
424 return;
425 }
426
427 let sum = |fixed: bool| {
432 self.panels
433 .iter()
434 .zip(&self.sizes)
435 .filter(|(panel, _)| !panel.hidden && panel.fixed == fixed)
436 .map(|(_, size)| size.as_f32())
437 .sum::<f32>()
438 };
439 let (fixed_size, total) = (px(sum(true)), sum(false));
440 if !total.is_finite() || total <= 0. {
441 return;
442 }
443 let total_size = px(total);
444 let available = self.container_size() - fixed_size;
445 if available <= px(0.) {
446 return;
447 }
448
449 for i in 0..self.panels.len() {
450 if self.panels[i].hidden {
451 continue;
452 }
453 if self.panels[i].fixed {
454 self.panels[i].size = Some(self.sizes[i]);
455 continue;
456 }
457 let size = self.sizes[i];
458 let ratio = size / total_size;
459 let new_size = available * ratio;
460
461 self.sizes[i] = new_size;
462 self.panels[i].size = Some(new_size);
463 }
464 cx.notify();
465 }
466}
467
468impl EventEmitter<ResizablePanelEvent> for ResizableState {}
469
470#[derive(Debug, Clone, Default)]
471pub(crate) struct ResizablePanelState {
472 pub size: Option<Pixels>,
473 pub size_range: Range<Pixels>,
474 bounds: Bounds<Pixels>,
475 pub(crate) fixed: bool,
477 hidden: bool,
478}
479
480#[cfg(test)]
481mod tests {
482 use std::{
483 cell::{Cell, RefCell},
484 rc::Rc,
485 };
486
487 use gpui::{
488 App, AppContext as _, Axis, Context, InputEvent as _, InteractiveElement as _, IntoElement,
489 Modifiers, MouseButton, ParentElement as _, Pixels, Render, Styled as _, TestAppContext,
490 VisualTestContext, Window, div, point, prelude::FluentBuilder as _, px, size,
491 };
492
493 use super::{
494 ResizableState, ResizeHandleContext, ResizeHandleState, h_resizable, resizable_panel,
495 v_resizable,
496 };
497
498 struct MixedSizingHarness {
499 width: Pixels,
500 }
501
502 impl Render for MixedSizingHarness {
503 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
504 div().w(self.width).h(px(100.)).child(
505 h_resizable("mixed-sizing")
506 .child(
507 resizable_panel()
508 .size(px(240.))
509 .child(div().size_full().debug_selector(|| "fixed-sidebar".into())),
510 )
511 .child(
512 resizable_panel().child(
513 div()
514 .size_full()
515 .debug_selector(|| "flexible-content".into()),
516 ),
517 ),
518 )
519 }
520 }
521
522 #[gpui::test]
523 fn mixed_sizing_is_stable_between_resize_and_followup_frame(cx: &mut TestAppContext) {
524 let (view, cx) = cx.add_window_view(|_, _| MixedSizingHarness { width: px(800.) });
525 cx.update(|window, cx| {
526 window.draw(cx).clear(cx);
527 window.draw(cx).clear(cx);
528 });
529 let before = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
530
531 view.update(cx, |view, cx| {
532 view.width = px(1200.);
533 cx.notify();
534 });
535 cx.run_until_parked();
536 let settled_frame = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
537 cx.update(|window, cx| window.draw(cx).clear(cx));
538 let followup_frame = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
539
540 assert_ne!(settled_frame, before);
544 assert_eq!(followup_frame, settled_frame);
545 }
546
547 struct FixedPanelHarness {
548 width: Pixels,
549 fixed: bool,
550 state: gpui::Entity<ResizableState>,
551 }
552
553 impl Render for FixedPanelHarness {
554 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
555 div().w(self.width).h(px(100.)).child(
556 h_resizable("fixed-panel")
557 .with_state(&self.state)
558 .child(
559 resizable_panel()
560 .size(px(240.))
561 .size_range(px(100.)..px(480.))
562 .when(self.fixed, |panel| panel.fixed())
563 .child(div().size_full().debug_selector(|| "fp-sidebar".into())),
564 )
565 .child(
566 resizable_panel()
567 .size(px(400.))
568 .child(div().size_full().debug_selector(|| "fp-main".into())),
569 )
570 .child(
571 resizable_panel()
572 .child(div().size_full().debug_selector(|| "fp-aside".into())),
573 ),
574 )
575 }
576 }
577
578 #[gpui::test]
583 fn fixed_panel_keeps_its_size_across_a_container_resize(cx: &mut TestAppContext) {
584 let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
585 let (view, cx) = cx.add_window_view({
586 let state = state.clone();
587 move |_, _| FixedPanelHarness {
588 width: px(840.),
589 fixed: true,
590 state,
591 }
592 });
593 cx.update(|window, cx| {
594 window.draw(cx).clear(cx);
595 window.draw(cx).clear(cx);
596 });
597 let widths = |cx: &mut VisualTestContext| {
598 ["fp-sidebar", "fp-main", "fp-aside"].map(|selector| {
599 cx.debug_bounds(selector)
600 .expect("every panel must lay out")
601 .size
602 .width
603 })
604 };
605 assert_eq!(widths(cx), [px(240.), px(400.), px(200.)]);
606
607 for (width, expected) in [
608 (px(1140.), Some([px(240.), px(600.), px(300.)])),
609 (px(200.), None),
610 (px(600.), Some([px(240.), px(240.), px(120.)])),
611 ] {
612 view.update(cx, |view, cx| {
613 view.width = width;
614 cx.notify();
615 });
616 cx.run_until_parked();
617 cx.update(|window, cx| window.draw(cx).clear(cx));
618 assert_eq!(widths(cx)[0], px(240.), "{width:?}");
619 if let Some(expected) = expected {
620 assert_eq!(widths(cx), expected, "{width:?}");
621 }
622 }
623
624 cx.update(|window, cx| {
627 state.update(cx, |state, cx| state.resize_panel(1, px(50.), window, cx));
628 window.draw(cx).clear(cx);
629 });
630 assert_eq!(widths(cx), [px(240.), px(100.), px(260.)]);
631
632 cx.update(|window, cx| {
635 state.update(cx, |state, cx| state.resize_panel(0, px(300.), window, cx));
636 window.draw(cx).clear(cx);
637 });
638 assert_eq!(widths(cx), [px(300.), px(100.), px(200.)]);
639 view.update(cx, |view, cx| {
640 view.width = px(900.);
641 cx.notify();
642 });
643 cx.run_until_parked();
644 cx.update(|window, cx| window.draw(cx).clear(cx));
645 assert_eq!(widths(cx)[0], px(300.));
646 }
647
648 #[gpui::test]
651 fn panel_made_fixed_in_place_keeps_its_size_across_a_container_resize(cx: &mut TestAppContext) {
652 let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
653 let (view, cx) = cx.add_window_view(move |_, _| FixedPanelHarness {
654 width: px(840.),
655 fixed: false,
656 state,
657 });
658 let draw = |cx: &mut VisualTestContext, update: fn(&mut FixedPanelHarness)| {
659 view.update(cx, |view, cx| {
660 update(view);
661 cx.notify();
662 });
663 cx.run_until_parked();
664 cx.update(|window, cx| window.draw(cx).clear(cx));
665 };
666 draw(cx, |_| {});
667 draw(cx, |view| view.fixed = true);
668 draw(cx, |view| view.width = px(1140.));
669
670 let sidebar = cx
671 .debug_bounds("fp-sidebar")
672 .expect("the sidebar must lay out");
673 assert_eq!(sidebar.size.width, px(240.));
674 }
675
676 struct CallerStateHarness {
677 width: Pixels,
678 state: gpui::Entity<ResizableState>,
679 }
680
681 impl Render for CallerStateHarness {
682 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
683 div().w(self.width).h(px(100.)).child(
684 h_resizable("caller-state")
685 .with_state(&self.state)
686 .child(
687 resizable_panel()
688 .size(px(240.))
689 .child(div().size_full().debug_selector(|| "cs-sidebar".into())),
690 )
691 .child(resizable_panel().child(div().size_full())),
692 )
693 }
694 }
695
696 #[gpui::test]
700 fn caller_owned_state_settles_on_the_same_frame(cx: &mut TestAppContext) {
701 let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
702 let (view, cx) = cx.add_window_view(move |_, _| CallerStateHarness {
703 width: px(800.),
704 state,
705 });
706 cx.update(|window, cx| {
707 window.draw(cx).clear(cx);
708 window.draw(cx).clear(cx);
709 });
710
711 view.update(cx, |view, cx| {
712 view.width = px(1200.);
713 cx.notify();
714 });
715 cx.run_until_parked();
716 let settled = cx.debug_bounds("cs-sidebar").unwrap().size.width;
717 cx.update(|window, cx| window.draw(cx).clear(cx));
718 let followup = cx.debug_bounds("cs-sidebar").unwrap().size.width;
719
720 assert_eq!(followup, settled, "settling frame must not be pending");
721 }
722
723 struct ResizableHarness {
724 state: gpui::Entity<ResizableState>,
725 resizes: Rc<Cell<usize>>,
726 }
727
728 impl Render for ResizableHarness {
729 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
730 div().w(px(400.)).h(px(100.)).child(
731 h_resizable("resizable")
732 .with_state(&self.state)
733 .on_resize({
734 let resizes = self.resizes.clone();
735 move |_, _, _| resizes.set(resizes.get() + 1)
736 })
737 .child(
738 resizable_panel()
739 .size(px(150.))
740 .child(div().size_full().debug_selector(|| "first-panel".into())),
741 )
742 .child(
743 resizable_panel()
744 .size(px(250.))
745 .child(div().size_full().debug_selector(|| "second-panel".into())),
746 ),
747 )
748 }
749 }
750
751 fn harness(
752 cx: &mut TestAppContext,
753 ) -> (
754 &mut VisualTestContext,
755 gpui::Entity<ResizableState>,
756 Rc<Cell<usize>>,
757 ) {
758 let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
759 let resizes = Rc::new(Cell::new(0));
760 let (_, cx) = cx.add_window_view({
761 let state = state.clone();
762 let resizes = resizes.clone();
763 move |_, _| ResizableHarness { state, resizes }
764 });
765 cx.update(|window, cx| window.draw(cx).clear(cx));
766 cx.update(|window, cx| window.draw(cx).clear(cx));
767 (cx, state, resizes)
768 }
769
770 #[cfg(feature = "gpui-fast")]
772 struct StateReader {
773 state: gpui::Entity<ResizableState>,
774 renders: Rc<Cell<usize>>,
775 }
776
777 #[cfg(feature = "gpui-fast")]
778 impl Render for StateReader {
779 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
780 self.renders.set(self.renders.get() + 1);
781 let _ = self.state.read(cx).sizes.len();
782 div()
783 }
784 }
785
786 #[cfg(feature = "gpui-fast")]
788 struct ReaderBesidePanels {
789 state: gpui::Entity<ResizableState>,
790 reader: gpui::Entity<StateReader>,
791 }
792
793 #[cfg(feature = "gpui-fast")]
794 impl Render for ReaderBesidePanels {
795 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
796 div()
797 .w(px(800.))
798 .h(px(100.))
799 .child(self.reader.clone())
800 .child(
801 h_resizable("reader-panels")
802 .with_state(&self.state)
803 .child(resizable_panel().size(px(240.)).child(div().size_full()))
804 .child(resizable_panel().child(div().size_full())),
805 )
806 }
807 }
808
809 #[cfg(feature = "gpui-fast")]
813 #[gpui::test]
814 fn redrawing_panels_where_they_were_leaves_their_readers_retained(cx: &mut TestAppContext) {
815 let renders = Rc::new(Cell::new(0));
816 let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
817 let (view, cx) = cx.add_window_view({
818 let state = state.clone();
819 let renders = renders.clone();
820 move |_, cx| ReaderBesidePanels {
821 state: state.clone(),
822 reader: cx.new(|_| StateReader { state, renders }),
823 }
824 });
825 for _ in 0..3 {
826 cx.update(|window, cx| window.draw(cx).clear(cx));
827 cx.run_until_parked();
828 }
829 let before = renders.get();
830 for _ in 0..3 {
831 view.update(cx, |_, cx| cx.notify());
832 cx.update(|window, cx| window.draw(cx).clear(cx));
833 cx.run_until_parked();
834 }
835 assert_eq!(renders.get(), before, "the reader rendered again");
836 }
837
838 #[gpui::test]
839 fn dynamic_panel_lifecycle_is_owned_by_resizable_state(cx: &mut TestAppContext) {
840 let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
841
842 cx.update(|cx| {
843 state.update(cx, |state, cx| {
844 state.bounds.size = size(px(400.), px(100.));
845 state.panels.push(Default::default());
846 state.sizes.push(px(400.));
847 state.insert_panel(Some(px(200.)), None, cx);
848 assert_eq!(state.sizes(), &vec![px(200.), px(200.)]);
849
850 state.reset_panel(0, cx);
851 assert_eq!(state.sizes(), &vec![px(200.), px(200.)]);
852
853 state.remove_panel(0, cx);
854 assert_eq!(state.sizes(), &vec![px(400.)]);
855
856 state.clear();
857 assert!(state.sizes().is_empty());
858 });
859 });
860 }
861
862 #[gpui::test]
863 fn group_measures_panels_and_programmatic_resize_uses_drag_rules(cx: &mut TestAppContext) {
864 let (cx, state, _) = harness(cx);
865 let first = cx.debug_bounds("first-panel").unwrap();
866 let second = cx.debug_bounds("second-panel").unwrap();
867 assert_eq!(first.size.width + second.size.width, px(400.));
868
869 cx.update(|window, cx| {
870 state.update(cx, |state, cx| {
871 state.resize_panel(0, px(220.), window, cx);
872 });
873 window.draw(cx).clear(cx);
874 });
875
876 state.read_with(cx, |state, _| {
877 assert_eq!(state.sizes(), &vec![px(220.), px(180.)]);
878 });
879 }
880
881 #[gpui::test]
882 fn resizing_uses_measured_sizes_and_respects_both_limits(cx: &mut TestAppContext) {
883 let (cx, state, _) = harness(cx);
884 cx.update(|window, cx| {
885 state.update(cx, |state, cx| {
886 let first = state.panels[0].bounds.size.width;
887 let second = state.panels[1].bounds.size.width;
888 state.sizes[0] = first - px(20.);
889 state.panels[0].size_range.start = first - px(30.);
890 state.panels[1].size_range.end = second + px(10.);
891 state.resize_panel_at_handle(0, first - px(50.), window, cx);
892 assert_eq!(state.sizes.as_slice(), &[first - px(10.), second + px(10.)]);
893
894 state.panels[1].size_range.end = second + px(60.);
895 state.resize_panel_at_handle(0, first - px(50.), window, cx);
896 assert_eq!(state.sizes.as_slice(), &[first - px(30.), second + px(30.)]);
897 });
898 });
899 }
900
901 #[gpui::test]
902 fn hiding_a_panel_preserves_its_slot_and_preferred_size(cx: &mut TestAppContext) {
903 let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
904 cx.update(|cx| {
905 state.update(cx, |state, cx| {
906 state.bounds.size = size(px(600.), px(100.));
907 state.sync_panels_count(Axis::Horizontal, 3, cx);
908 state.adopt_sizes(&[Some(px(200.)); 3], cx);
909
910 state.sync_panel_visibility([true, false, true].into_iter(), cx);
911 assert_eq!(state.sizes.as_slice(), &[px(200.), px(0.), px(200.)]);
912 assert_eq!(state.next_visible_panel(0), Some(2));
913 assert_eq!(state.previous_visible_panel(2), Some(0));
914
915 state.insert_panel(Some(px(100.)), None, cx);
916 state.sync_panel_visibility([true; 4].into_iter(), cx);
917 assert_eq!(state.sizes[1], px(200.));
918 assert_eq!(state.next_visible_panel(0), Some(1));
919 });
920 });
921 }
922
923 #[gpui::test]
924 fn dragging_the_handle_resizes_and_emits_once(cx: &mut TestAppContext) {
925 let (cx, state, resizes) = harness(cx);
926 let boundary = cx.debug_bounds("second-panel").unwrap().left();
927 assert!(!state.read_with(cx, |state, _| state.is_resizing()));
928
929 cx.simulate_mouse_down(
930 point(boundary - px(2.), px(50.)),
931 MouseButton::Left,
932 Modifiers::default(),
933 );
934 cx.simulate_mouse_move(
935 point(boundary + px(10.), px(50.)),
936 Some(MouseButton::Left),
937 Modifiers::default(),
938 );
939 cx.simulate_mouse_move(
940 point(px(220.), px(50.)),
941 Some(MouseButton::Left),
942 Modifiers::default(),
943 );
944 assert!(state.read_with(cx, |state, _| state.is_resizing()));
945 cx.simulate_mouse_up(
946 point(px(220.), px(50.)),
947 MouseButton::Left,
948 Modifiers::default(),
949 );
950
951 state.read_with(cx, |state, _| {
952 assert_eq!(state.sizes(), &vec![px(220.), px(180.)]);
953 assert!(!state.is_resizing());
954 });
955 assert_eq!(resizes.get(), 1);
956 }
957
958 #[gpui::test]
959 fn dragging_before_the_next_paint_resizes_and_emits_once(cx: &mut TestAppContext) {
960 let (cx, state, resizes) = harness(cx);
961 let boundary = cx.debug_bounds("second-panel").unwrap().left();
962
963 cx.update(|window, cx| {
966 window.dispatch_event(
967 gpui::MouseDownEvent {
968 position: point(boundary - px(2.), px(50.)),
969 button: MouseButton::Left,
970 click_count: 1,
971 ..Default::default()
972 }
973 .to_platform_input(),
974 cx,
975 );
976 for x in [boundary + px(10.), px(220.)] {
977 window.dispatch_event(
978 gpui::MouseMoveEvent {
979 position: point(x, px(50.)),
980 pressed_button: Some(MouseButton::Left),
981 ..Default::default()
982 }
983 .to_platform_input(),
984 cx,
985 );
986 }
987 assert_eq!(state.read(cx).resizing_panel_ix, Some(0));
988 assert_eq!(state.read(cx).sizes(), &vec![px(220.), px(180.)]);
989 assert_eq!(resizes.get(), 0);
990
991 for _ in 0..2 {
994 window.dispatch_event(
995 gpui::MouseUpEvent {
996 position: point(px(220.), px(50.)),
997 button: MouseButton::Left,
998 click_count: 1,
999 ..Default::default()
1000 }
1001 .to_platform_input(),
1002 cx,
1003 );
1004 }
1005 window.dispatch_event(
1006 gpui::MouseMoveEvent {
1007 position: point(px(260.), px(50.)),
1008 ..Default::default()
1009 }
1010 .to_platform_input(),
1011 cx,
1012 );
1013 assert_eq!(state.read(cx).resizing_panel_ix, None);
1014 assert_eq!(state.read(cx).sizes(), &vec![px(220.), px(180.)]);
1015 assert_eq!(resizes.get(), 1);
1016 });
1017 }
1018
1019 #[gpui::test]
1020 fn cancelled_drag_does_not_reuse_the_painted_index(cx: &mut TestAppContext) {
1021 let (cx, state, resizes) = harness(cx);
1022 let boundary = cx.debug_bounds("second-panel").unwrap().left();
1023 cx.simulate_mouse_down(
1024 point(boundary - px(2.), px(50.)),
1025 MouseButton::Left,
1026 Modifiers::default(),
1027 );
1028 cx.simulate_mouse_move(
1029 point(boundary + px(10.), px(50.)),
1030 Some(MouseButton::Left),
1031 Modifiers::default(),
1032 );
1033 cx.update(|window, cx| {
1034 assert_eq!(state.read(cx).resizing_panel_ix, Some(0));
1035 window.draw(cx).clear(cx);
1036 state.update(cx, |state, cx| state.resize_panel(0, px(210.), window, cx));
1037 cx.stop_active_drag(window);
1038 assert_eq!(state.read(cx).resizing_panel_ix, None);
1039
1040 window.dispatch_event(
1043 gpui::MouseMoveEvent {
1044 position: point(px(260.), px(50.)),
1045 pressed_button: Some(MouseButton::Left),
1046 ..Default::default()
1047 }
1048 .to_platform_input(),
1049 cx,
1050 );
1051 window.dispatch_event(
1052 gpui::MouseUpEvent {
1053 position: point(px(260.), px(50.)),
1054 button: MouseButton::Left,
1055 click_count: 1,
1056 ..Default::default()
1057 }
1058 .to_platform_input(),
1059 cx,
1060 );
1061 assert_eq!(state.read(cx).sizes(), &vec![px(210.), px(190.)]);
1062 assert_eq!(state.read(cx).resizing_panel_ix, None);
1063 assert_eq!(resizes.get(), 0);
1064 });
1065 }
1066
1067 #[gpui::test]
1068 fn clearing_mid_drag_stops_resizing(cx: &mut TestAppContext) {
1069 let (cx, state, _) = harness(cx);
1070 let boundary = cx.debug_bounds("second-panel").unwrap().left();
1071 cx.simulate_mouse_down(
1072 point(boundary - px(2.), px(50.)),
1073 MouseButton::Left,
1074 Modifiers::default(),
1075 );
1076 cx.simulate_mouse_move(
1077 point(boundary + px(10.), px(50.)),
1078 Some(MouseButton::Left),
1079 Modifiers::default(),
1080 );
1081 assert!(state.read_with(cx, |state, _| state.is_resizing()));
1082
1083 state.update(cx, |state, _| state.clear());
1084 assert!(!state.read_with(cx, |state, _| state.is_resizing()));
1085 }
1086
1087 #[gpui::test]
1088 fn stopping_the_drag_ends_resizing(cx: &mut TestAppContext) {
1089 let (cx, state, resizes) = harness(cx);
1090 let boundary = cx.debug_bounds("second-panel").unwrap().left();
1091 cx.simulate_mouse_down(
1092 point(boundary - px(2.), px(50.)),
1093 MouseButton::Left,
1094 Modifiers::default(),
1095 );
1096 cx.simulate_mouse_move(
1097 point(px(220.), px(50.)),
1098 Some(MouseButton::Left),
1099 Modifiers::default(),
1100 );
1101 assert!(state.read_with(cx, |state, _| state.is_resizing()));
1102
1103 cx.update(|window, cx| {
1105 cx.stop_active_drag(window);
1106 window.draw(cx).clear(cx);
1107 });
1108 let sizes = state.read_with(cx, |state, _| {
1109 assert!(!state.is_resizing());
1110 state.sizes().clone()
1111 });
1112 assert_eq!(resizes.get(), 1);
1113
1114 cx.simulate_mouse_move(
1116 point(px(260.), px(50.)),
1117 Some(MouseButton::Left),
1118 Modifiers::default(),
1119 );
1120 assert_eq!(state.read_with(cx, |state, _| state.sizes().clone()), sizes);
1121 assert_eq!(resizes.get(), 1);
1122 }
1123
1124 struct HandleStateHarness {
1130 seen: Rc<RefCell<Vec<ResizeHandleState>>>,
1131 covered: bool,
1132 }
1133
1134 impl Render for HandleStateHarness {
1135 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1136 let seen = self.seen.clone();
1137 div()
1138 .relative()
1139 .w(px(400.))
1140 .h(px(100.))
1141 .child(
1142 h_resizable("handle-state")
1143 .with_handle_appearance(Rc::new(
1144 move |handle: &ResizeHandleContext, _: &mut Window, _: &mut App| {
1145 let mut seen = seen.borrow_mut();
1146 if seen.last() != Some(&handle.state()) {
1147 seen.push(handle.state());
1148 }
1149 None
1151 },
1152 ))
1153 .child(resizable_panel().size(px(150.)).child(div().size_full()))
1154 .child(
1155 resizable_panel()
1156 .size(px(250.))
1157 .child(div().size_full().debug_selector(|| "hs-second".into())),
1158 ),
1159 )
1160 .when(self.covered, |this| {
1161 this.child(div().absolute().inset_0().occlude())
1162 })
1163 }
1164 }
1165
1166 #[gpui::test]
1174 fn a_covered_handle_stays_idle(cx: &mut TestAppContext) {
1175 let seen: Rc<RefCell<Vec<ResizeHandleState>>> = Rc::new(RefCell::new(Vec::new()));
1176 let (_, cx) = cx.add_window_view({
1177 let seen = seen.clone();
1178 move |_, _| HandleStateHarness {
1179 seen,
1180 covered: true,
1181 }
1182 });
1183 cx.update(|window, cx| window.draw(cx).clear(cx));
1184 cx.update(|window, cx| window.draw(cx).clear(cx));
1185
1186 let boundary = cx.debug_bounds("hs-second").unwrap().left();
1187 let on_handle = point(boundary - px(2.), px(50.));
1188 let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
1189
1190 cx.simulate_mouse_move(on_handle, None, Modifiers::default());
1191 draw(cx);
1192 cx.simulate_mouse_down(on_handle, MouseButton::Left, Modifiers::default());
1193 draw(cx);
1194 cx.simulate_mouse_up(on_handle, MouseButton::Left, Modifiers::default());
1195 draw(cx);
1196
1197 assert_eq!(*seen.borrow(), vec![ResizeHandleState::Idle]);
1198 }
1199
1200 #[gpui::test]
1201 fn a_handle_reports_the_press_and_the_drag_to_its_renderer(cx: &mut TestAppContext) {
1202 let seen: Rc<RefCell<Vec<ResizeHandleState>>> = Rc::new(RefCell::new(Vec::new()));
1203 let (_, cx) = cx.add_window_view({
1204 let seen = seen.clone();
1205 move |_, _| HandleStateHarness {
1206 seen,
1207 covered: false,
1208 }
1209 });
1210 cx.update(|window, cx| window.draw(cx).clear(cx));
1211 cx.update(|window, cx| window.draw(cx).clear(cx));
1212
1213 let boundary = cx.debug_bounds("hs-second").unwrap().left();
1214 let on_handle = point(boundary - px(2.), px(50.));
1215 let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
1216
1217 cx.simulate_mouse_move(on_handle, None, Modifiers::default());
1218 draw(cx);
1219 cx.simulate_mouse_down(on_handle, MouseButton::Left, Modifiers::default());
1220 draw(cx);
1221 cx.simulate_mouse_move(
1222 point(px(260.), px(50.)),
1223 Some(MouseButton::Left),
1224 Modifiers::default(),
1225 );
1226 draw(cx);
1227 cx.simulate_mouse_up(
1228 point(px(390.), px(90.)),
1229 MouseButton::Left,
1230 Modifiers::default(),
1231 );
1232 draw(cx);
1233
1234 assert_eq!(
1238 *seen.borrow(),
1239 vec![
1240 ResizeHandleState::Idle,
1241 ResizeHandleState::Hovered,
1242 ResizeHandleState::Pressed,
1243 ResizeHandleState::Dragging,
1244 ResizeHandleState::Idle,
1245 ]
1246 );
1247 }
1248
1249 struct SizedGroupHarness;
1250
1251 impl Render for SizedGroupHarness {
1252 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1253 div()
1254 .w(px(400.))
1255 .h(px(100.))
1256 .child(
1257 h_resizable("sized-resizable").size(px(40.)).child(
1258 resizable_panel()
1259 .child(div().size_full().debug_selector(|| "sized-panel".into())),
1260 ),
1261 )
1262 }
1263 }
1264
1265 #[gpui::test]
1266 fn a_group_size_binds_the_cross_axis(cx: &mut TestAppContext) {
1267 let (_, cx) = cx.add_window_view(|_, _| SizedGroupHarness);
1268 cx.update(|window, cx| window.draw(cx).clear(cx));
1269 cx.update(|window, cx| window.draw(cx).clear(cx));
1270
1271 let panel = cx.debug_bounds("sized-panel").unwrap();
1272 assert_eq!(panel.size.width, px(400.));
1273 assert_eq!(panel.size.height, px(40.));
1274 }
1275
1276 #[gpui::test]
1277 fn initial_drag_move_resizes_horizontal_panel_immediately(cx: &mut TestAppContext) {
1278 let (cx, state, resizes) = harness(cx);
1279 let boundary = cx.debug_bounds("second-panel").unwrap().left();
1280 let initial_sizes = state.read_with(cx, |state, _| state.sizes().clone());
1281 assert_eq!(initial_sizes, vec![px(150.), px(250.)]);
1282
1283 cx.simulate_mouse_down(
1287 point(boundary - px(2.), px(50.)),
1288 MouseButton::Left,
1289 Modifiers::default(),
1290 );
1291 cx.simulate_mouse_move(
1292 point(px(210.), px(50.)),
1293 Some(MouseButton::Left),
1294 Modifiers::default(),
1295 );
1296
1297 state.read_with(cx, |state, _| {
1298 assert!(state.is_resizing());
1299 assert_eq!(state.sizes(), &vec![px(210.), px(190.)]);
1300 });
1301 assert_eq!(resizes.get(), 0);
1302
1303 cx.simulate_mouse_up(
1304 point(px(210.), px(50.)),
1305 MouseButton::Left,
1306 Modifiers::default(),
1307 );
1308 assert_eq!(resizes.get(), 1);
1309 }
1310
1311 struct VerticalDragHarness {
1312 state: gpui::Entity<ResizableState>,
1313 }
1314
1315 impl Render for VerticalDragHarness {
1316 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1317 div().w(px(100.)).h(px(400.)).child(
1318 v_resizable("vertical-initial-drag")
1319 .with_state(&self.state)
1320 .child(
1321 resizable_panel()
1322 .size(px(150.))
1323 .child(div().size_full().debug_selector(|| "v-first-panel".into())),
1324 )
1325 .child(
1326 resizable_panel()
1327 .size(px(250.))
1328 .child(div().size_full().debug_selector(|| "v-second-panel".into())),
1329 ),
1330 )
1331 }
1332 }
1333
1334 #[gpui::test]
1335 fn initial_drag_move_resizes_vertical_panel_immediately(cx: &mut TestAppContext) {
1336 let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
1337 let (_, cx) = cx.add_window_view({
1338 let state = state.clone();
1339 move |_, _| VerticalDragHarness { state }
1340 });
1341 cx.update(|window, cx| {
1342 window.draw(cx).clear(cx);
1343 window.draw(cx).clear(cx);
1344 });
1345
1346 let boundary = cx.debug_bounds("v-second-panel").unwrap().top();
1347 cx.simulate_mouse_down(
1348 point(px(50.), boundary - px(2.)),
1349 MouseButton::Left,
1350 Modifiers::default(),
1351 );
1352 cx.simulate_mouse_move(
1353 point(px(50.), px(220.)),
1354 Some(MouseButton::Left),
1355 Modifiers::default(),
1356 );
1357
1358 state.read_with(cx, |state, _| {
1359 assert!(state.is_resizing());
1360 assert_eq!(state.sizes(), &vec![px(220.), px(180.)]);
1361 });
1362 }
1363}