1use std::ops::RangeInclusive;
4
5use gpui::{
6 AccessibleAction, AnyElement, App, AppContext as _, Axis, Bounds, Context, DragMoveEvent,
7 ElementId, Empty, Entity, EntityId, EventEmitter, FocusHandle, InteractiveElement,
8 Interactivity, IntoElement, KeyBinding, MouseButton, MouseDownEvent, Orientation,
9 ParentElement, Pixels, Point, Render, RenderOnce, Role, SharedString,
10 StatefulInteractiveElement, StyleRefinement, Styled, Window, accesskit, div,
11 prelude::FluentBuilder as _, px,
12};
13
14use crate::{
15 ElementExt as _, TestSupportExt as _,
16 a11y_disabled::A11yDisabledExt as _,
17 actions::{Confirm, SelectDown, SelectFirst, SelectLast, SelectLeft, SelectRight, SelectUp},
18};
19
20const STEP: f32 = 0.02;
21const EPSILON: f32 = 0.0001;
22
23pub(crate) fn init(cx: &mut App) {
24 cx.bind_keys([
25 KeyBinding::new(
26 "left",
27 SelectLeft,
28 Some("ResizableHandle && axis == horizontal"),
29 ),
30 KeyBinding::new(
31 "right",
32 SelectRight,
33 Some("ResizableHandle && axis == horizontal"),
34 ),
35 KeyBinding::new("up", SelectUp, Some("ResizableHandle && axis == vertical")),
36 KeyBinding::new(
37 "down",
38 SelectDown,
39 Some("ResizableHandle && axis == vertical"),
40 ),
41 KeyBinding::new("home", SelectFirst, Some("ResizableHandle")),
42 KeyBinding::new("end", SelectLast, Some("ResizableHandle")),
43 KeyBinding::new(
44 "enter",
45 Confirm { secondary: false },
46 Some("ResizableHandle"),
47 ),
48 ]);
49}
50
51#[derive(Clone, Debug, PartialEq)]
54pub enum ResizableEvent {
55 Change(Vec<f32>),
56}
57
58#[derive(Clone, Copy, Debug, PartialEq)]
61pub struct ResizablePanel {
62 default_size: f32,
63 minimum: f32,
64 maximum: f32,
65 pixel_minimum: Pixels,
66 pixel_maximum: Option<Pixels>,
67 collapsed: Option<f32>,
68}
69
70impl ResizablePanel {
71 pub fn new(default_size: f32) -> Self {
73 Self {
74 default_size,
75 minimum: 0.,
76 maximum: 1.,
77 pixel_minimum: px(0.),
78 pixel_maximum: None,
79 collapsed: None,
80 }
81 }
82
83 pub fn pixel_limits(mut self, limits: RangeInclusive<Pixels>) -> Self {
92 let (minimum, maximum) = limits.into_inner();
93 assert!(
94 f32::from(minimum).is_finite()
95 && f32::from(maximum).is_finite()
96 && px(0.) <= minimum
97 && minimum <= maximum,
98 "Resizable pixel limits must satisfy 0 <= minimum <= maximum"
99 );
100 self.pixel_minimum = minimum;
101 self.pixel_maximum = Some(maximum);
102 self
103 }
104
105 fn measured(mut self, usable: Pixels) -> Self {
107 if usable <= px(0.) {
108 return self;
109 }
110 self.minimum = self.minimum.max(self.pixel_minimum / usable).min(1.);
111 if let Some(maximum) = self.pixel_maximum {
112 self.maximum = self.maximum.min(maximum / usable);
113 }
114 self.maximum = self.maximum.max(self.minimum);
116 self
117 }
118
119 pub fn limits(mut self, limits: RangeInclusive<f32>) -> Self {
124 let (minimum, maximum) = limits.into_inner();
125 assert!(
126 minimum.is_finite()
127 && maximum.is_finite()
128 && 0. <= minimum
129 && minimum <= maximum
130 && maximum <= 1.,
131 "Resizable panel limits must satisfy 0 <= minimum <= maximum <= 1"
132 );
133 self.minimum = minimum;
134 self.maximum = maximum;
135 self
136 }
137
138 pub fn collapsible(mut self, collapsed_size: f32) -> Self {
144 assert!(
145 collapsed_size.is_finite() && 0. <= collapsed_size,
146 "Resizable collapsed size must be finite and non-negative"
147 );
148 self.collapsed = Some(collapsed_size);
149 self
150 }
151
152 fn is_collapsed_size(&self, size: f32) -> bool {
153 self.collapsed
154 .is_some_and(|collapsed| (size - collapsed).abs() < EPSILON)
155 }
156
157 fn accepts(&self, size: f32) -> bool {
158 self.is_collapsed_size(size)
159 || (self.minimum - EPSILON <= size && size <= self.maximum + EPSILON)
160 }
161
162 fn constrain(&self, requested: f32) -> f32 {
164 match self.collapsed {
165 Some(collapsed) if requested < self.minimum => {
166 if requested < (collapsed + self.minimum) / 2. {
167 collapsed
168 } else {
169 self.minimum
170 }
171 }
172 _ => requested.clamp(self.minimum, self.maximum),
173 }
174 }
175
176 fn smallest(&self) -> f32 {
177 self.collapsed.unwrap_or(self.minimum)
178 }
179}
180
181struct Drag {
182 handle: usize,
183 origin: Vec<f32>,
184 start: Pixels,
185 usable: Pixels,
186}
187
188pub struct ResizableState {
197 axis: Axis,
198 panels: Vec<ResizablePanel>,
199 effective: Vec<ResizablePanel>,
201 usable: Pixels,
202 sizes: Vec<f32>,
203 restore: Vec<f32>,
204 disabled: bool,
205 root_focus: FocusHandle,
206 panel_focus: Vec<FocusHandle>,
207 handle_focus: Vec<FocusHandle>,
208 panel_bounds: Vec<Bounds<Pixels>>,
209 handle_bounds: Vec<Bounds<Pixels>>,
210 grab: Pixels,
211 drag: Option<Drag>,
212}
213
214impl ResizableState {
215 pub fn new(
221 axis: Axis,
222 panels: impl IntoIterator<Item = ResizablePanel>,
223 cx: &mut Context<Self>,
224 ) -> Self {
225 let panels: Vec<_> = panels.into_iter().collect();
226 assert!(panels.len() >= 2, "Resizable requires at least two panels");
227 for panel in &panels {
228 if let Some(collapsed) = panel.collapsed {
229 assert!(
230 collapsed < panel.minimum,
231 "Resizable collapsed size must be below the panel minimum"
232 );
233 }
234 }
235 let sizes: Vec<_> = panels.iter().map(|panel| panel.default_size).collect();
236 assert!(
237 valid_layout(&panels, &sizes),
238 "Resizable default sizes must satisfy panel limits and sum to one"
239 );
240 let restore = panels
241 .iter()
242 .zip(&sizes)
243 .map(|(panel, size)| {
244 if panel.is_collapsed_size(*size) {
245 panel.minimum
246 } else {
247 *size
248 }
249 })
250 .collect();
251 let count = panels.len();
252 Self {
253 axis,
254 sizes,
255 restore,
256 disabled: false,
257 root_focus: cx.focus_handle(),
258 panel_focus: (0..count).map(|_| cx.focus_handle()).collect(),
259 handle_focus: (1..count).map(|_| cx.focus_handle()).collect(),
260 panel_bounds: vec![Bounds::default(); count],
261 handle_bounds: vec![Bounds::default(); count - 1],
262 effective: panels.clone(),
263 usable: px(0.),
264 panels,
265 grab: px(0.),
266 drag: None,
267 }
268 }
269
270 pub fn axis(&self) -> Axis {
271 self.axis
272 }
273
274 pub fn sizes(&self) -> &[f32] {
276 &self.sizes
277 }
278
279 pub fn panel_count(&self) -> usize {
280 self.panels.len()
281 }
282
283 pub fn handle_focus(&self, index: usize) -> &FocusHandle {
285 &self.handle_focus[index]
286 }
287
288 pub fn is_disabled(&self) -> bool {
289 self.disabled
290 }
291
292 pub fn is_collapsed(&self, panel: usize) -> bool {
294 self.panels[panel].is_collapsed_size(self.sizes[panel])
295 }
296
297 pub fn set_sizes(&mut self, sizes: Vec<f32>, window: &mut Window, cx: &mut Context<Self>) {
306 assert!(
307 sizes.len() == self.panels.len() && valid_layout(&self.panels, &sizes),
308 "Resizable sizes must match the panels, satisfy their limits and sum to one"
309 );
310 let sizes = fit(&self.effective, &sizes).unwrap_or(sizes);
311 self.apply(sizes, window, cx);
312 }
313
314 fn measure(&mut self, usable: Pixels, window: &mut Window, cx: &mut Context<Self>) -> bool {
317 if (usable - self.usable).abs() < px(0.5) {
318 return false;
319 }
320 self.usable = usable;
321 let measured: Vec<_> = self
322 .panels
323 .iter()
324 .map(|panel| panel.measured(usable))
325 .collect();
326 let smallest: f32 = measured.iter().map(ResizablePanel::smallest).sum();
327 let largest: f32 = measured.iter().map(|panel| panel.maximum).sum();
328 self.effective = if smallest <= 1. + EPSILON && largest >= 1. - EPSILON {
329 measured
330 } else {
331 self.panels.clone()
332 };
333 match fit(&self.effective, &self.sizes) {
334 Some(sizes) if sizes != self.sizes => {
335 self.apply(sizes, window, cx);
336 true
337 }
338 _ => false,
339 }
340 }
341
342 pub fn collapse(&mut self, panel: usize, window: &mut Window, cx: &mut Context<Self>) {
345 if let Some(collapsed) = self.panels[panel].collapsed {
346 self.resize_panel(panel, collapsed, window, cx);
347 }
348 }
349
350 pub fn expand(&mut self, panel: usize, window: &mut Window, cx: &mut Context<Self>) {
353 if self.is_collapsed(panel) {
354 self.resize_panel(panel, self.restore[panel], window, cx);
355 }
356 }
357
358 pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
361 if self.disabled != disabled {
362 self.disabled = disabled;
363 cx.notify();
364 window.refresh();
365 }
366 }
367
368 fn apply(&mut self, sizes: Vec<f32>, window: &mut Window, cx: &mut Context<Self>) {
369 if sizes == self.sizes {
370 return;
371 }
372 for (index, size) in sizes.iter().enumerate() {
373 let panel = &self.panels[index];
374 if panel.is_collapsed_size(*size) {
375 if *size == 0. && self.panel_focus[index].contains_focused(window, cx) {
376 let handle = index.min(self.handle_focus.len() - 1);
377 if self.disabled {
378 self.root_focus.focus(window, cx);
379 } else {
380 self.handle_focus[handle].focus(window, cx);
381 }
382 }
383 } else {
384 self.restore[index] = *size;
385 }
386 }
387 self.sizes = sizes;
388 cx.emit(ResizableEvent::Change(self.sizes.clone()));
389 cx.notify();
390 window.refresh();
391 }
392
393 fn resize_panel(
394 &mut self,
395 panel: usize,
396 target: f32,
397 window: &mut Window,
398 cx: &mut Context<Self>,
399 ) {
400 let delta = target - self.sizes[panel];
401 let layout = if panel + 1 < self.panels.len() {
402 adjust(&self.effective, &self.sizes, panel, delta)
403 } else {
404 adjust(&self.effective, &self.sizes, panel - 1, -delta)
405 };
406 if let Some(layout) = layout {
407 self.apply(layout, window, cx);
408 }
409 }
410
411 fn nudge(&mut self, handle: usize, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
414 if self.disabled {
415 return;
416 }
417 let (grow, shrink) = if forward {
418 (handle, handle + 1)
419 } else {
420 (handle + 1, handle)
421 };
422 let grow_panel = &self.effective[grow];
423 let shrink_panel = &self.effective[shrink];
424 let amount = if grow_panel.is_collapsed_size(self.sizes[grow]) {
425 grow_panel.minimum - self.sizes[grow]
426 } else if let Some(collapsed) = shrink_panel.collapsed
427 && (self.sizes[shrink] - shrink_panel.minimum).abs() < EPSILON
428 {
429 self.sizes[shrink] - collapsed
430 } else {
431 STEP
432 };
433 let delta = if forward { amount } else { -amount };
434 if let Some(layout) = adjust(&self.effective, &self.sizes, handle, delta) {
435 self.apply(layout, window, cx);
436 }
437 }
438
439 fn edge(&mut self, handle: usize, last: bool, window: &mut Window, cx: &mut Context<Self>) {
442 if self.disabled {
443 return;
444 }
445 let panel = self.effective[handle];
446 let target = if last {
447 panel.maximum
448 } else {
449 panel.smallest()
450 };
451 let mut layout = None;
452 let mut delta = target - self.sizes[handle];
455 for _ in 0..32 {
456 layout = adjust(&self.effective, &self.sizes, handle, delta);
457 if layout.is_some() || delta.abs() < EPSILON {
458 break;
459 }
460 delta /= 2.;
461 }
462 if let Some(layout) = layout {
463 self.apply(layout, window, cx);
464 }
465 }
466
467 fn toggle(&mut self, handle: usize, window: &mut Window, cx: &mut Context<Self>) {
469 if self.disabled || self.panels[handle].collapsed.is_none() {
470 return;
471 }
472 if self.is_collapsed(handle) {
473 self.expand(handle, window, cx);
474 } else {
475 self.collapse(handle, window, cx);
476 }
477 }
478
479 fn pointer_coordinate(&self, point: Point<Pixels>) -> Pixels {
480 match self.axis {
481 Axis::Horizontal => point.x,
482 Axis::Vertical => point.y,
483 }
484 }
485
486 fn length(&self, bounds: Bounds<Pixels>) -> Pixels {
487 match self.axis {
488 Axis::Horizontal => bounds.size.width,
489 Axis::Vertical => bounds.size.height,
490 }
491 }
492
493 fn begin_drag(&mut self, handle: usize) {
494 let usable = self
495 .panel_bounds
496 .iter()
497 .fold(px(0.), |total, bounds| total + self.length(*bounds));
498 self.drag = Some(Drag {
499 handle,
500 origin: self.sizes.clone(),
501 start: self.pointer_coordinate(self.handle_bounds[handle].origin),
502 usable,
503 });
504 }
505
506 fn resize_at_pointer(
507 &mut self,
508 position: Point<Pixels>,
509 window: &mut Window,
510 cx: &mut Context<Self>,
511 ) {
512 if self.disabled {
513 return;
514 }
515 let Some(drag) = &self.drag else {
516 return;
517 };
518 if drag.usable <= px(0.) {
519 return;
520 }
521 let moved = self.pointer_coordinate(position) - self.grab - drag.start;
522 if let Some(layout) = adjust(
523 &self.effective,
524 &drag.origin,
525 drag.handle,
526 moved / drag.usable,
527 ) {
528 self.apply(layout, window, cx);
529 }
530 }
531}
532
533impl EventEmitter<ResizableEvent> for ResizableState {}
534
535fn valid_layout(panels: &[ResizablePanel], sizes: &[f32]) -> bool {
536 let total: f32 = sizes.iter().sum();
537 sizes.iter().all(|size| size.is_finite())
538 && (total - 1.).abs() < EPSILON * sizes.len() as f32
539 && panels
540 .iter()
541 .zip(sizes)
542 .all(|(panel, size)| panel.accepts(*size))
543}
544
545fn fit(panels: &[ResizablePanel], sizes: &[f32]) -> Option<Vec<f32>> {
549 let mut fitted: Vec<f32> = panels
550 .iter()
551 .zip(sizes)
552 .map(|(panel, &size)| {
553 if panel.is_collapsed_size(size) {
554 size
555 } else {
556 size.clamp(panel.minimum, panel.maximum)
557 }
558 })
559 .collect();
560 for _ in 0..=panels.len() {
561 let difference = 1. - fitted.iter().sum::<f32>();
562 if difference.abs() < EPSILON {
563 break;
564 }
565 let room: Vec<f32> = panels
566 .iter()
567 .zip(&fitted)
568 .map(|(panel, &size)| {
569 if panel.is_collapsed_size(size) {
570 0.
571 } else if difference > 0. {
572 panel.maximum - size
573 } else {
574 size - panel.minimum
575 }
576 })
577 .collect();
578 let open = room.iter().filter(|room| **room > EPSILON).count();
579 if open == 0 {
580 break;
581 }
582 let share = difference.abs() / open as f32;
583 for (size, room) in fitted.iter_mut().zip(&room) {
584 if *room > EPSILON {
585 *size += share.min(*room).copysign(difference);
586 }
587 }
588 }
589 valid_layout(panels, &fitted).then_some(fitted)
590}
591
592fn adjust(panels: &[ResizablePanel], base: &[f32], handle: usize, delta: f32) -> Option<Vec<f32>> {
597 if delta.abs() < EPSILON {
598 return None;
599 }
600 let grow = if delta > 0. { handle } else { handle + 1 };
601 let shrink: Vec<usize> = if delta > 0. {
602 (handle + 1..panels.len()).collect()
603 } else {
604 (0..=handle).rev().collect()
605 };
606 let wanted = panels[grow].constrain(base[grow] + delta.abs()) - base[grow];
607 if wanted < EPSILON {
608 return None;
609 }
610 let mut sizes = base.to_vec();
611 let mut remaining = wanted;
612 for index in shrink {
613 if remaining < EPSILON {
614 break;
615 }
616 let next = panels[index].constrain(sizes[index] - remaining);
617 let freed = (sizes[index] - next).max(0.);
618 sizes[index] -= freed;
619 remaining -= freed;
620 }
621 let freed = wanted - remaining;
622 if freed < EPSILON {
623 return None;
624 }
625 sizes[grow] = base[grow] + freed;
626 valid_layout(panels, &sizes).then_some(sizes)
627}
628
629#[derive(Clone)]
630struct DragResizable(EntityId);
631
632impl Render for DragResizable {
633 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
634 Empty
635 }
636}
637
638#[derive(IntoElement)]
648pub struct Resizable {
649 id: ElementId,
650 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
651 state: Entity<ResizableState>,
652 panels: Vec<AnyElement>,
653 handle: Option<Box<dyn Fn(usize, ResizableHandle) -> ResizableHandle>>,
654}
655
656impl Resizable {
657 pub fn new(id: impl Into<ElementId>, state: &Entity<ResizableState>) -> Self {
658 let id = id.into();
659 Self {
660 base: div().id(id.clone()).test_support(),
661 state: state.clone(),
662 panels: Vec::new(),
663 handle: None,
664 id,
665 }
666 }
667
668 pub fn panel(mut self, content: impl IntoElement) -> Self {
670 self.panels.push(content.into_any_element());
671 self
672 }
673
674 pub fn handle(
676 mut self,
677 build: impl Fn(usize, ResizableHandle) -> ResizableHandle + 'static,
678 ) -> Self {
679 self.handle = Some(Box::new(build));
680 self
681 }
682}
683
684impl Styled for Resizable {
685 fn style(&mut self) -> &mut StyleRefinement {
686 self.base.style()
687 }
688}
689
690impl RenderOnce for Resizable {
691 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
692 let model = self.state.read(cx);
693 let axis = model.axis;
694 let sizes = model.sizes.clone();
695 let panel_focus = model.panel_focus.clone();
696 let root_focus = model.root_focus.clone();
697 assert_eq!(
698 self.panels.len(),
699 sizes.len(),
700 "Resizable needs one panel element per configured panel"
701 );
702 let mut layout = div()
703 .id((self.id.clone(), "layout"))
704 .flex()
705 .flex_1()
706 .w_full()
707 .min_w_0()
708 .min_h_0()
709 .gap_0()
710 .when(axis == Axis::Vertical, |this| this.flex_col());
711 for (index, content) in self.panels.into_iter().enumerate() {
712 if index > 0 {
713 let handle = ResizableHandle::new(
714 (
715 self.id.clone(),
716 SharedString::from(format!("handle-{}", index - 1)),
717 ),
718 &self.state,
719 index - 1,
720 );
721 layout = layout.child(match &self.handle {
722 Some(build) => build(index - 1, handle),
723 None => handle,
724 });
725 }
726 let size = sizes[index];
727 let geometry = self.state.clone();
728 layout = layout.child(
729 div()
730 .id((
731 self.id.clone(),
732 SharedString::from(format!("panel-{index}")),
733 ))
734 .test_support()
735 .track_focus(&panel_focus[index].clone().tab_stop(false))
736 .min_w_0()
737 .min_h_0()
738 .flex_basis(px(0.))
739 .flex_grow(size)
740 .flex_shrink_0()
741 .overflow_hidden()
742 .when(size > 0., |this| this.child(content))
743 .on_prepaint(move |bounds, window, cx| {
744 geometry.update(cx, |state, cx| {
745 state.panel_bounds[index] = bounds;
746 if index + 1 == state.panels.len() {
747 let usable = state
749 .panel_bounds
750 .iter()
751 .fold(px(0.), |total, bounds| total + state.length(*bounds));
752 state.measure(usable, window, cx);
753 }
754 });
755 }),
756 );
757 }
758 self.base
759 .track_focus(&root_focus.tab_stop(false))
760 .flex()
761 .flex_col()
762 .child(layout)
763 }
764}
765
766#[derive(IntoElement)]
776pub struct ResizableHandle {
777 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
778 state: Entity<ResizableState>,
779 index: usize,
780 label: Option<SharedString>,
781}
782
783impl ResizableHandle {
784 fn new(id: impl Into<ElementId>, state: &Entity<ResizableState>, index: usize) -> Self {
785 Self {
786 base: div().id(id).test_support(),
787 state: state.clone(),
788 index,
789 label: None,
790 }
791 }
792
793 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
794 self.label = Some(label.into());
795 self
796 }
797}
798
799impl Styled for ResizableHandle {
800 fn style(&mut self) -> &mut StyleRefinement {
801 self.base.style()
802 }
803}
804
805impl ParentElement for ResizableHandle {
806 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
807 self.base.extend(elements);
808 }
809}
810
811impl InteractiveElement for ResizableHandle {
812 fn interactivity(&mut self) -> &mut Interactivity {
813 self.base.interactivity()
814 }
815}
816
817impl StatefulInteractiveElement for ResizableHandle {}
818
819impl RenderOnce for ResizableHandle {
820 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
821 let index = self.index;
822 let model = self.state.read(cx);
823 let axis = model.axis;
824 let disabled = model.disabled;
825 let focus = model.handle_focus[index].clone();
826 let panel = model.effective[index];
827 let size = model.sizes[index];
828 let entity_id = self.state.entity_id();
829 let geometry = self.state.clone();
830 let drag_start = self.state.clone();
831 let increment = self.state.clone();
832 let decrement = self.state.clone();
833 let set_value = self.state.clone();
834
835 self.base
836 .role(Role::Splitter)
837 .flex_shrink_0()
838 .aria_numeric_value((size * 100.) as f64)
839 .aria_min_numeric_value((panel.smallest() * 100.) as f64)
840 .aria_max_numeric_value((panel.maximum * 100.) as f64)
841 .aria_numeric_value_step((STEP * 100.) as f64)
842 .when_some(self.label, |this, label| this.aria_label(label))
843 .when(axis == Axis::Horizontal, |this| {
844 this.mx_0()
845 .cursor_col_resize()
846 .aria_orientation(Orientation::Vertical)
847 .key_context("ResizableHandle axis=horizontal")
848 .on_action(window.listener_for(
849 &self.state,
850 move |state, _: &SelectLeft, window, cx| {
851 state.nudge(index, false, window, cx)
852 },
853 ))
854 .on_action(window.listener_for(
855 &self.state,
856 move |state, _: &SelectRight, window, cx| {
857 state.nudge(index, true, window, cx)
858 },
859 ))
860 })
861 .when(axis == Axis::Vertical, |this| {
862 this.my_0()
863 .cursor_row_resize()
864 .aria_orientation(Orientation::Horizontal)
865 .key_context("ResizableHandle axis=vertical")
866 .on_action(window.listener_for(
867 &self.state,
868 move |state, _: &SelectUp, window, cx| {
869 state.nudge(index, false, window, cx)
870 },
871 ))
872 .on_action(window.listener_for(
873 &self.state,
874 move |state, _: &SelectDown, window, cx| {
875 state.nudge(index, true, window, cx)
876 },
877 ))
878 })
879 .when(!disabled || focus.is_focused(window), |this| {
880 this.track_focus(&focus.tab_stop(!disabled))
881 })
882 .on_action(window.listener_for(
883 &self.state,
884 move |state, _: &SelectFirst, window, cx| {
885 state.edge(index, false, window, cx);
886 },
887 ))
888 .on_action(window.listener_for(
889 &self.state,
890 move |state, _: &SelectLast, window, cx| {
891 state.edge(index, true, window, cx);
892 },
893 ))
894 .on_action(
895 window.listener_for(&self.state, move |state, _: &Confirm, window, cx| {
896 state.toggle(index, window, cx);
897 }),
898 )
899 .when(disabled, |this| {
900 this.cursor_default()
901 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
902 })
903 .when(!disabled, |this| {
904 this.on_mouse_down(
905 MouseButton::Left,
906 window.listener_for(
907 &self.state,
908 move |state, event: &MouseDownEvent, window, cx| {
909 if state.disabled {
910 return;
911 }
912 state.grab = state.pointer_coordinate(event.position)
913 - state.pointer_coordinate(state.handle_bounds[index].origin);
914 state.handle_focus[index].focus(window, cx);
915 },
916 ),
917 )
918 .on_drag(DragResizable(entity_id), move |drag, _, window, cx| {
919 let position = window.mouse_position();
920 drag_start.update(cx, |state, cx| {
921 state.begin_drag(index);
922 state.resize_at_pointer(position, window, cx)
923 });
924 cx.stop_propagation();
925 cx.new(|_| drag.clone())
926 })
927 .on_drag_move(window.listener_for(
928 &self.state,
929 move |state, event: &DragMoveEvent<DragResizable>, window, cx| {
930 if event.drag(cx).0 == entity_id
931 && state.drag.as_ref().is_some_and(|drag| drag.handle == index)
932 {
933 state.resize_at_pointer(event.event.position, window, cx);
934 }
935 },
936 ))
937 .on_a11y_action(AccessibleAction::Increment, move |_, window, cx| {
938 increment.update(cx, |state, cx| state.nudge(index, true, window, cx));
939 })
940 .on_a11y_action(AccessibleAction::Decrement, move |_, window, cx| {
941 decrement.update(cx, |state, cx| state.nudge(index, false, window, cx));
942 })
943 .on_a11y_action(
944 AccessibleAction::SetValue,
945 move |data, window, cx| {
946 if let Some(accesskit::ActionData::NumericValue(value)) = data
947 && value.is_finite()
948 {
949 set_value.update(cx, |state, cx| {
950 if !state.disabled {
951 let target =
952 state.effective[index].constrain(*value as f32 / 100.);
953 state.resize_panel(index, target, window, cx);
954 }
955 });
956 }
957 },
958 )
959 })
960 .on_prepaint(move |bounds, _, cx| {
961 geometry.update(cx, |state, _| state.handle_bounds[index] = bounds);
962 })
963 .a11y_disabled(disabled)
964 }
965}
966
967#[cfg(test)]
968mod tests {
969 use std::{cell::RefCell, rc::Rc};
970
971 use gpui::{Element as _, Modifiers, Subscription, TestAppContext, VisualTestContext, point};
972
973 use super::*;
974 use crate::{Button, Root};
975
976 fn panels(sizes: &[f32]) -> Vec<ResizablePanel> {
977 sizes
978 .iter()
979 .map(|size| ResizablePanel::new(*size).limits(0.2..=0.8))
980 .collect()
981 }
982
983 fn close(actual: &[f32], expected: &[f32]) -> bool {
984 actual.len() == expected.len()
985 && actual
986 .iter()
987 .zip(expected)
988 .all(|(a, b)| (a - b).abs() < 0.0001)
989 }
990
991 #[test]
992 fn divider_moves_cascade_through_constraints_and_collapse_snaps() {
993 let three = [
994 ResizablePanel::new(0.4).limits(0.2..=0.6),
995 ResizablePanel::new(0.3).limits(0.2..=0.6),
996 ResizablePanel::new(0.3).limits(0.2..=0.6),
997 ];
998 let base = [0.4, 0.3, 0.3];
999 let moved = adjust(&three, &base, 0, 0.15).unwrap();
1001 assert!(close(&moved, &[0.55, 0.2, 0.25]), "{moved:?}");
1002 let moved = adjust(&three, &base, 0, 0.5).unwrap();
1004 assert!(close(&moved, &[0.6, 0.2, 0.2]), "{moved:?}");
1005 assert_eq!(adjust(&three, &[0.6, 0.2, 0.2], 0, 0.1), None);
1007
1008 let sidebar = [
1009 ResizablePanel::new(0.25).limits(0.15..=0.4).collapsible(0.),
1010 ResizablePanel::new(0.75).limits(0.3..=1.),
1011 ];
1012 let moved = adjust(&sidebar, &[0.25, 0.75], 0, -0.15).unwrap();
1014 assert!(close(&moved, &[0.15, 0.85]), "{moved:?}");
1015 let moved = adjust(&sidebar, &[0.25, 0.75], 0, -0.2).unwrap();
1017 assert!(close(&moved, &[0., 1.]), "{moved:?}");
1018 assert_eq!(adjust(&sidebar, &[0., 1.], 0, 0.05), None);
1020 let moved = adjust(&sidebar, &[0., 1.], 0, 0.1).unwrap();
1021 assert!(close(&moved, &[0.15, 0.85]), "{moved:?}");
1022 }
1023
1024 struct Harness {
1025 state: Entity<ResizableState>,
1026 before: FocusHandle,
1027 actions: Vec<FocusHandle>,
1028 after: FocusHandle,
1029 extent: Pixels,
1030 _subscription: Subscription,
1031 }
1032
1033 impl Render for Harness {
1034 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1035 let axis = self.state.read(cx).axis();
1036 let mut group = Resizable::new("split", &self.state)
1037 .w(if axis == Axis::Horizontal {
1038 self.extent
1039 } else {
1040 px(120.)
1041 })
1042 .h(if axis == Axis::Vertical {
1043 self.extent
1044 } else {
1045 px(120.)
1046 })
1047 .p(px(10.))
1048 .flex_shrink_0()
1049 .handle(move |index, handle| {
1050 handle
1051 .accessibility_label(format!("Panel {} size", index + 1))
1052 .when(axis == Axis::Horizontal, |handle| handle.w(px(10.)))
1053 .when(axis == Axis::Vertical, |handle| handle.h(px(10.)))
1054 });
1055 for (index, focus) in self.actions.iter().enumerate() {
1056 group = group.panel(
1057 Button::new(("action", index))
1058 .track_focus(focus)
1059 .h(px(30.))
1060 .child(format!("Panel {index}")),
1061 );
1062 }
1063 div()
1064 .size(px(600.))
1065 .flex()
1066 .flex_col()
1067 .items_start()
1068 .child(
1069 Button::new("before")
1070 .track_focus(&self.before)
1071 .h(px(30.))
1072 .child("Before"),
1073 )
1074 .child(group)
1075 .child(
1076 Button::new("after")
1077 .track_focus(&self.after)
1078 .h(px(30.))
1079 .child("After"),
1080 )
1081 }
1082 }
1083
1084 type Changes = Rc<RefCell<Vec<Vec<f32>>>>;
1085
1086 fn harness(
1087 cx: &mut TestAppContext,
1088 axis: Axis,
1089 panels: Vec<ResizablePanel>,
1090 ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
1091 cx.update(crate::init);
1092 let (root, cx) = cx.add_window_view(move |window, cx| {
1093 let view = cx.new(|cx| {
1094 let count = panels.len();
1095 let state = cx.new(|cx| ResizableState::new(axis, panels, cx));
1096 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
1097 Harness {
1098 state,
1099 before: cx.focus_handle(),
1100 actions: (0..count).map(|_| cx.focus_handle()).collect(),
1101 after: cx.focus_handle(),
1102 extent: px(320.),
1103 _subscription: subscription,
1104 }
1105 });
1106 Root::new(view, window, cx)
1107 });
1108 let view = root
1109 .read_with(cx, |root, _| root.view().clone())
1110 .downcast::<Harness>()
1111 .unwrap();
1112 let changes = Rc::new(RefCell::new(Vec::new()));
1113 cx.update(|window, cx| {
1114 let state = view.read(cx).state.clone();
1115 let changes = changes.clone();
1116 cx.subscribe(&state, move |_, event: &ResizableEvent, _| {
1117 let ResizableEvent::Change(sizes) = event;
1118 changes.borrow_mut().push(sizes.clone());
1119 })
1120 .detach();
1121 window.activate_window();
1122 view.read(cx).before.clone().focus(window, cx);
1123 window.draw(cx).clear(cx);
1124 });
1125 cx.run_until_parked();
1126 (cx, view, changes)
1127 }
1128
1129 fn draw(cx: &mut VisualTestContext) {
1130 cx.update(|window, cx| window.draw(cx).clear(cx));
1131 }
1132
1133 fn assert_sizes(cx: &mut VisualTestContext, view: &Entity<Harness>, expected: &[f32]) {
1134 cx.update(|_, cx| {
1135 let sizes = view.read(cx).state.read(cx).sizes().to_vec();
1136 assert!(close(&sizes, expected), "{sizes:?} != {expected:?}");
1137 });
1138 }
1139
1140 #[gpui::test]
1141 fn divider_keyboard_and_native_semantics_preserve_child_focus(cx: &mut TestAppContext) {
1142 for axis in [Axis::Horizontal, Axis::Vertical] {
1143 let (cx, view, changes) = harness(cx, axis, panels(&[0.5, 0.5]));
1144 let increase = if axis == Axis::Horizontal {
1145 "right"
1146 } else {
1147 "down"
1148 };
1149 let decrease = if axis == Axis::Horizontal {
1150 "left"
1151 } else {
1152 "up"
1153 };
1154 let other_axis = if axis == Axis::Horizontal {
1155 "down"
1156 } else {
1157 "right"
1158 };
1159 cx.simulate_keystrokes("tab");
1160 cx.simulate_keystrokes(increase);
1161 draw(cx);
1162 cx.update(|window, cx| assert!(view.read(cx).actions[0].is_focused(window)));
1163 assert_sizes(cx, &view, &[0.5, 0.5]);
1164
1165 cx.simulate_keystrokes("tab");
1166 cx.simulate_keystrokes(increase);
1167 draw(cx);
1168 assert_sizes(cx, &view, &[0.52, 0.48]);
1169 cx.simulate_keystrokes(other_axis);
1170 draw(cx);
1171 assert_sizes(cx, &view, &[0.52, 0.48]);
1172 if axis == Axis::Horizontal {
1174 cx.dispatch_action(SelectDown);
1175 } else {
1176 cx.dispatch_action(SelectRight);
1177 }
1178 draw(cx);
1179 assert_sizes(cx, &view, &[0.52, 0.48]);
1180 cx.simulate_keystrokes(decrease);
1181 cx.simulate_keystrokes("home end end enter");
1182 draw(cx);
1183 assert_sizes(cx, &view, &[0.8, 0.2]);
1184 assert_eq!(changes.borrow().len(), 4);
1185
1186 cx.update(|window, cx| {
1187 let state = view.read(cx).state.clone();
1188 assert!(state.read(cx).handle_focus(0).is_focused(window));
1189 let element = ResizableHandle::new("probe", &state, 0)
1190 .accessibility_label("First pane size")
1191 .render(window, cx)
1192 .into_element();
1193 let mut node = accesskit::Node::new(Role::Splitter);
1194 element.write_a11y_info(&mut node);
1195 assert_eq!(element.a11y_role(), Some(Role::Splitter));
1196 assert_eq!(node.label(), Some("First pane size"));
1197 assert_eq!(node.numeric_value(), Some(80.));
1198 assert_eq!(node.min_numeric_value(), Some(20.));
1199 assert_eq!(node.max_numeric_value(), Some(80.));
1200 assert_eq!(node.numeric_value_step(), Some(2.));
1201 assert_eq!(
1202 node.orientation(),
1203 Some(if axis == Axis::Horizontal {
1204 Orientation::Vertical
1205 } else {
1206 Orientation::Horizontal
1207 })
1208 );
1209 assert!(node.supports_action(AccessibleAction::SetValue));
1210 state.update(cx, |state, cx| state.set_disabled(true, window, cx));
1211 let element = ResizableHandle::new("disabled-probe", &state, 0)
1212 .render(window, cx)
1213 .into_element();
1214 let mut node = accesskit::Node::new(Role::Splitter);
1215 element.write_a11y_info(&mut node);
1216 assert!(node.is_disabled());
1217 assert!(!node.supports_action(AccessibleAction::SetValue));
1218 });
1219 draw(cx);
1220 cx.simulate_keystrokes("home");
1221 cx.simulate_keystrokes(decrease);
1222 draw(cx);
1223 assert_sizes(cx, &view, &[0.8, 0.2]);
1224 cx.simulate_keystrokes("tab");
1225 draw(cx);
1226 cx.update(|window, cx| assert!(view.read(cx).actions[1].is_focused(window)));
1227 cx.simulate_keystrokes("shift-tab");
1228 draw(cx);
1229 cx.update(|window, cx| assert!(view.read(cx).actions[0].is_focused(window)));
1230 assert_eq!(changes.borrow().len(), 4);
1231 }
1232 }
1233
1234 #[gpui::test]
1235 fn collapsible_panel_toggles_unmounts_content_and_restores_size(cx: &mut TestAppContext) {
1236 let (cx, view, changes) = harness(
1237 cx,
1238 Axis::Horizontal,
1239 vec![
1240 ResizablePanel::new(0.3).limits(0.2..=0.5).collapsible(0.),
1241 ResizablePanel::new(0.4).limits(0.2..=0.8),
1242 ResizablePanel::new(0.3).limits(0.2..=0.5),
1243 ],
1244 );
1245 cx.simulate_keystrokes("tab");
1247 draw(cx);
1248 cx.update(|window, cx| {
1249 let state = view.read(cx).state.clone();
1250 assert!(view.read(cx).actions[0].is_focused(window));
1251 state.update(cx, |state, cx| state.collapse(0, window, cx));
1252 });
1253 draw(cx);
1254 assert_sizes(cx, &view, &[0., 0.7, 0.3]);
1255 cx.update(|window, cx| {
1256 let view = view.read(cx);
1257 let state = view.state.read(cx);
1258 assert!(state.is_collapsed(0));
1259 assert!(state.handle_focus(0).is_focused(window));
1260 let content = (ElementId::from("split"), "panel-0").into();
1261 assert!(
1262 crate::test_support::find(window, &[], &("action", 0usize).into()).is_none(),
1263 "collapsed content is unmounted"
1264 );
1265 assert!(crate::test_support::find(window, &[], &content).is_some());
1266 });
1267 cx.simulate_keystrokes("right");
1269 draw(cx);
1270 assert_sizes(cx, &view, &[0.2, 0.5, 0.3]);
1271 cx.simulate_keystrokes("left");
1272 draw(cx);
1273 assert_sizes(cx, &view, &[0., 0.7, 0.3]);
1274 cx.simulate_keystrokes("enter");
1276 draw(cx);
1277 assert_sizes(cx, &view, &[0.2, 0.5, 0.3]);
1278 cx.simulate_keystrokes("right right enter enter");
1279 draw(cx);
1280 assert_sizes(cx, &view, &[0.24, 0.46, 0.3]);
1281 cx.simulate_keystrokes("tab tab right");
1283 draw(cx);
1284 assert_sizes(cx, &view, &[0.24, 0.48, 0.28]);
1285 cx.update(|window, cx| {
1286 let state = view.read(cx).state.clone();
1287 assert!(state.read(cx).handle_focus(1).is_focused(window));
1288 state.update(cx, |state, cx| {
1289 state.set_sizes(vec![0.3, 0.4, 0.3], window, cx)
1290 });
1291 });
1292 assert_sizes(cx, &view, &[0.3, 0.4, 0.3]);
1293 assert_eq!(changes.borrow().len(), 10);
1294 }
1295
1296 #[gpui::test]
1297 fn pointer_resize_uses_actual_pane_space_and_retains_sizes_on_parent_resize(
1298 cx: &mut TestAppContext,
1299 ) {
1300 for axis in [Axis::Horizontal, Axis::Vertical] {
1301 let (cx, view, _) = harness(cx, axis, panels(&[0.5, 0.5]));
1302 let (handle, origin, usable) = cx.update(|_, cx| {
1303 let state = view.read(cx).state.read(cx);
1304 let usable =
1305 state.length(state.panel_bounds[0]) + state.length(state.panel_bounds[1]);
1306 assert_eq!(
1307 usable,
1308 px(290.),
1309 "subtract frame padding and actual divider thickness"
1310 );
1311 assert_eq!(state.length(state.panel_bounds[0]), px(145.));
1312 (state.handle_bounds[0], state.panel_bounds[0].origin, usable)
1313 });
1314 let grab = px(2.);
1315 let start = match axis {
1316 Axis::Horizontal => point(handle.left() + grab, handle.center().y),
1317 Axis::Vertical => point(handle.center().x, handle.top() + grab),
1318 };
1319 let at = |ratio: f32| match axis {
1320 Axis::Horizontal => point(origin.x + usable * ratio + grab, start.y),
1321 Axis::Vertical => point(start.x, origin.y + usable * ratio + grab),
1322 };
1323 cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1324 draw(cx);
1325 assert_sizes(cx, &view, &[0.5, 0.5]);
1326 cx.simulate_mouse_move(at(0.7), MouseButton::Left, Modifiers::default());
1327 draw(cx);
1328 assert_sizes(cx, &view, &[0.7, 0.3]);
1329 cx.simulate_mouse_move(at(1.2), MouseButton::Left, Modifiers::default());
1330 draw(cx);
1331 assert_sizes(cx, &view, &[0.8, 0.2]);
1332 cx.simulate_mouse_up(at(1.2), MouseButton::Left, Modifiers::default());
1333 draw(cx);
1334 cx.simulate_mouse_move(at(0.3), None, Modifiers::default());
1335 draw(cx);
1336 assert_sizes(cx, &view, &[0.8, 0.2]);
1337 cx.update(|_, cx| assert!(!cx.has_active_drag()));
1338
1339 view.update(cx, |view, cx| {
1340 view.extent = px(420.);
1341 cx.notify();
1342 });
1343 draw(cx);
1344 cx.update(|_, cx| {
1345 let state = view.read(cx).state.read(cx);
1346 let first = state.length(state.panel_bounds[0]);
1347 let second = state.length(state.panel_bounds[1]);
1348 assert_eq!(first + second, px(390.));
1349 assert!((first / (first + second) - 0.8).abs() < 0.001);
1350 });
1351 }
1352 }
1353
1354 #[gpui::test]
1355 fn pixel_limits_follow_the_measured_group_and_refit_on_resize(cx: &mut TestAppContext) {
1356 let (cx, view, changes) = harness(
1357 cx,
1358 Axis::Horizontal,
1359 vec![
1360 ResizablePanel::new(0.5).pixel_limits(px(116.)..=px(1000.)),
1361 ResizablePanel::new(0.5).limits(0.2..=1.),
1362 ],
1363 );
1364 assert_sizes(cx, &view, &[0.5, 0.5]);
1366 assert!(
1367 changes.borrow().is_empty(),
1368 "a satisfied layout is not refitted"
1369 );
1370 view.update(cx, |view, cx| {
1371 view.extent = px(220.);
1372 cx.notify();
1373 });
1374 draw(cx);
1375 draw(cx);
1376 assert_sizes(cx, &view, &[116. / 190., 74. / 190.]);
1378 cx.update(|_, cx| {
1379 let state = view.read(cx).state.read(cx);
1380 assert!((state.length(state.panel_bounds[0]) - px(116.)).abs() < px(0.5));
1381 });
1382 assert_eq!(changes.borrow().len(), 1);
1383 cx.update(|window, cx| {
1384 view.read(cx)
1385 .state
1386 .read(cx)
1387 .handle_focus(0)
1388 .clone()
1389 .focus(window, cx);
1390 });
1391 draw(cx);
1392 cx.simulate_keystrokes("left");
1393 draw(cx);
1394 assert_sizes(cx, &view, &[116. / 190., 74. / 190.]);
1395 cx.simulate_keystrokes("right");
1396 draw(cx);
1397 assert_sizes(cx, &view, &[116. / 190. + STEP, 74. / 190. - STEP]);
1398 view.update(cx, |view, cx| {
1400 view.extent = px(320.);
1401 cx.notify();
1402 });
1403 draw(cx);
1404 draw(cx);
1405 assert_sizes(cx, &view, &[116. / 190. + STEP, 74. / 190. - STEP]);
1406 cx.update(|window, cx| {
1408 view.read(cx).state.clone().update(cx, |state, cx| {
1409 state.set_sizes(vec![0.3, 0.7], window, cx);
1410 })
1411 });
1412 assert_sizes(cx, &view, &[116. / 290., 174. / 290.]);
1413 }
1414}