1use std::{cell::Cell, ops::Range, rc::Rc};
4
5use gpui::{prelude::FluentBuilder as _, *};
6
7use crate::capabilities::foundation::theme::use_theme;
8use crate::capabilities::foundation::util::AxisExt;
9
10const PANEL_MIN_SIZE: Pixels = px(100.0);
11const HANDLE_PADDING: Pixels = px(4.0);
12const HANDLE_SIZE: Pixels = px(1.0);
13
14pub fn h_resizable(id: impl Into<ElementId>, state: Entity<ResizableState>) -> ResizablePanelGroup {
15 ResizablePanelGroup::new(id, state).axis(Axis::Horizontal)
16}
17
18pub fn v_resizable(id: impl Into<ElementId>, state: Entity<ResizableState>) -> ResizablePanelGroup {
19 ResizablePanelGroup::new(id, state).axis(Axis::Vertical)
20}
21
22pub fn resizable_panel() -> ResizablePanel {
23 ResizablePanel::new()
24}
25
26#[derive(Clone, Debug)]
27pub enum ResizablePanelEvent {
28 Resized {
29 panel_index: usize,
30 new_size: Pixels,
31 },
32}
33
34#[derive(Debug, Clone)]
35pub struct ResizableState {
36 axis: Axis,
37 panels: Vec<ResizablePanelState>,
38 sizes: Vec<Pixels>,
39 resizing_panel_ix: Option<usize>,
40 bounds: Bounds<Pixels>,
41}
42
43impl ResizableState {
44 pub fn new(cx: &mut App) -> Entity<Self> {
45 cx.new(|_| Self {
46 axis: Axis::Horizontal,
47 panels: vec![],
48 sizes: vec![],
49 resizing_panel_ix: None,
50 bounds: Bounds::default(),
51 })
52 }
53
54 pub fn insert_panel(
55 &mut self,
56 size: Option<Pixels>,
57 index: Option<usize>,
58 cx: &mut Context<Self>,
59 ) {
60 let panel_state = ResizablePanelState {
61 size,
62 ..Default::default()
63 };
64
65 if let Some(index) = index {
66 self.panels.insert(index, panel_state);
67 self.sizes.insert(index, size.unwrap_or(PANEL_MIN_SIZE));
68 } else {
69 self.panels.push(panel_state);
70 self.sizes.push(size.unwrap_or(PANEL_MIN_SIZE));
71 }
72
73 cx.notify();
74 }
75
76 pub fn remove_panel(&mut self, index: usize, cx: &mut Context<Self>) {
77 if index >= self.panels.len() {
78 return;
79 }
80
81 self.panels.remove(index);
82 self.sizes.remove(index);
83
84 if let Some(resizing_ix) = self.resizing_panel_ix {
85 if resizing_ix > index {
86 self.resizing_panel_ix = Some(resizing_ix - 1);
87 } else if resizing_ix == index {
88 self.resizing_panel_ix = None;
89 }
90 }
91
92 cx.notify();
93 }
94
95 pub fn sizes(&self) -> &Vec<Pixels> {
96 &self.sizes
97 }
98
99 pub fn total_size(&self) -> Pixels {
100 self.sizes.iter().fold(px(0.0), |acc, &size| acc + size)
101 }
102
103 pub fn clear(&mut self) {
104 self.panels.clear();
105 self.sizes.clear();
106 }
107
108 fn sync_panels_count(&mut self, axis: Axis, panels_count: usize) {
109 self.axis = axis;
110
111 if panels_count > self.panels.len() {
112 let diff = panels_count - self.panels.len();
113 self.panels
114 .extend(vec![ResizablePanelState::default(); diff]);
115 self.sizes.extend(vec![PANEL_MIN_SIZE; diff]);
116 }
117 }
118
119 fn update_panel_size(
120 &mut self,
121 index: usize,
122 bounds: Bounds<Pixels>,
123 size_range: Range<Pixels>,
124 cx: &mut Context<Self>,
125 ) {
126 if index >= self.panels.len() {
127 return;
128 }
129
130 let size = bounds.size.along(self.axis);
131 self.sizes[index] = size;
132 self.panels[index].size = Some(size);
133 self.panels[index].bounds = bounds;
134 self.panels[index].size_range = size_range;
135
136 cx.notify();
137 }
138
139 fn done_resizing(&mut self, cx: &mut Context<Self>) {
140 if let Some(index) = self.resizing_panel_ix {
141 let new_size = self.sizes.get(index).copied().unwrap_or(PANEL_MIN_SIZE);
142
143 cx.emit(ResizablePanelEvent::Resized {
144 panel_index: index,
145 new_size,
146 });
147 }
148
149 self.resizing_panel_ix = None;
150 }
151
152 fn panel_size_range(&self, index: usize) -> Range<Pixels> {
153 self.panels
154 .get(index)
155 .map(|p| p.size_range.clone())
156 .unwrap_or(PANEL_MIN_SIZE..Pixels::MAX)
157 }
158
159 fn sync_real_panel_sizes(&mut self, _: &App) {
160 for (i, panel) in self.panels.iter().enumerate() {
161 if i < self.sizes.len() {
162 self.sizes[i] = panel.bounds.size.along(self.axis).floor();
163 }
164 }
165 }
166
167 fn resize_panel(&mut self, index: usize, size: Pixels, _: &mut Window, cx: &mut Context<Self>) {
168 let old_sizes = self.sizes.clone();
169
170 if index >= old_sizes.len() - 1 {
171 return;
172 }
173
174 let size = size.floor();
175 let container_size = self.bounds.size.along(self.axis);
176
177 self.sync_real_panel_sizes(cx);
178
179 let move_changed = size - old_sizes[index];
180 if move_changed == px(0.0) {
181 return;
182 }
183
184 let size_range = self.panel_size_range(index);
185 let new_size = size.clamp(size_range.start, size_range.end);
186 let is_expand = move_changed > px(0.0);
187
188 let main_ix = index;
189 let mut new_sizes = old_sizes.clone();
190 let mut ix = index;
191
192 if is_expand {
193 let mut changed = new_size - old_sizes[index];
194 new_sizes[index] = new_size;
195
196 while changed > px(0.0) && ix < old_sizes.len() - 1 {
197 ix += 1;
198 let size_range = self.panel_size_range(ix);
199 let available_size = (new_sizes[ix] - size_range.start).max(px(0.0));
200 let to_reduce = changed.min(available_size);
201 new_sizes[ix] -= to_reduce;
202 changed -= to_reduce;
203 }
204 } else {
205 let mut changed = old_sizes[index] - new_size;
206 new_sizes[index + 1] += changed;
207 new_sizes[index] = new_size;
208
209 let right_size_range = self.panel_size_range(index + 1);
210 if new_sizes[index + 1] > right_size_range.end {
211 let overflow = new_sizes[index + 1] - right_size_range.end;
212 new_sizes[index + 1] = right_size_range.end;
213 changed = overflow;
214
215 while changed > px(0.0) && ix > 0 {
216 ix -= 1;
217 let size_range = self.panel_size_range(ix);
218 let available_size = (new_sizes[ix] - size_range.start).max(px(0.0));
219 let to_reduce = changed.min(available_size);
220 changed -= to_reduce;
221 new_sizes[ix] -= to_reduce;
222 }
223 }
224 }
225
226 let total_size: Pixels = new_sizes.iter().fold(px(0.0), |acc, &size| acc + size);
227 if total_size > container_size {
228 let overflow = total_size - container_size;
229 let size_range = self.panel_size_range(main_ix);
230 new_sizes[main_ix] = (new_sizes[main_ix] - overflow).max(size_range.start);
231 }
232
233 for (i, _) in old_sizes.iter().enumerate() {
234 if i < new_sizes.len() && i < self.panels.len() {
235 let size = new_sizes[i];
236 self.panels[i].size = Some(size);
237 }
238 }
239
240 self.sizes = new_sizes;
241 cx.notify();
242 }
243}
244
245impl EventEmitter<ResizablePanelEvent> for ResizableState {}
246
247#[derive(Debug, Clone, Default)]
248struct ResizablePanelState {
249 size: Option<Pixels>,
250 size_range: Range<Pixels>,
251 bounds: Bounds<Pixels>,
252}
253
254#[derive(IntoElement)]
256pub struct ResizablePanelGroup {
257 id: ElementId,
258 state: Entity<ResizableState>,
259 axis: Axis,
260 children: Vec<ResizablePanel>,
261}
262
263impl ResizablePanelGroup {
264 fn new(id: impl Into<ElementId>, state: Entity<ResizableState>) -> Self {
265 Self {
266 id: id.into(),
267 axis: Axis::Horizontal,
268 children: vec![],
269 state,
270 }
271 }
272
273 pub fn axis(mut self, axis: Axis) -> Self {
274 self.axis = axis;
275 self
276 }
277
278 pub fn child(mut self, panel: impl Into<ResizablePanel>) -> Self {
279 self.children.push(panel.into());
280 self
281 }
282
283 pub fn children<I>(mut self, panels: impl IntoIterator<Item = I>) -> Self
284 where
285 I: Into<ResizablePanel>,
286 {
287 self.children = panels.into_iter().map(|panel| panel.into()).collect();
288 self
289 }
290
291 pub fn group(self, group: ResizablePanelGroup) -> Self {
292 self.child(resizable_panel().child(group.into_any_element()))
293 }
294}
295
296impl<T> From<T> for ResizablePanel
297where
298 T: Into<AnyElement>,
299{
300 fn from(value: T) -> Self {
301 resizable_panel().child(value.into())
302 }
303}
304
305impl EventEmitter<ResizablePanelEvent> for ResizablePanelGroup {}
306
307impl RenderOnce for ResizablePanelGroup {
308 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
309 let state = self.state.clone();
310
311 let panels_count = self.children.len();
312 self.state.update(cx, |state, _| {
313 state.sync_panels_count(self.axis, panels_count);
314 });
315
316 let container = div()
317 .id(self.id)
318 .flex()
319 .size_full()
320 .when(self.axis.is_horizontal(), |this| this.flex_row())
321 .when(self.axis.is_vertical(), |this| this.flex_col());
322
323 container
324 .children(
325 self.children
326 .into_iter()
327 .enumerate()
328 .map(|(index, mut panel)| {
329 panel.index = index;
330 panel.axis = self.axis;
331 panel.state = Some(self.state.clone());
332 panel
333 }),
334 )
335 .child({
336 canvas(
337 move |bounds, _, cx| {
338 state.update(cx, |state, _| {
339 state.bounds = bounds;
340 })
341 },
342 |_, _, _, _| {},
343 )
344 .absolute()
345 .size_full()
346 })
347 .child(ResizePanelGroupElement {
348 state: self.state.clone(),
349 axis: self.axis,
350 })
351 }
352}
353
354#[derive(IntoElement)]
356pub struct ResizablePanel {
357 axis: Axis,
358 index: usize,
359 state: Option<Entity<ResizableState>>,
360 initial_size: Option<Pixels>,
361 size_range: Range<Pixels>,
362 children: Vec<AnyElement>,
363 visible: bool,
364 style: StyleRefinement,
365}
366
367impl ResizablePanel {
368 fn new() -> Self {
369 Self {
370 index: 0,
371 initial_size: None,
372 state: None,
373 size_range: (PANEL_MIN_SIZE..Pixels::MAX),
374 axis: Axis::Horizontal,
375 children: vec![],
376 visible: true,
377 style: StyleRefinement::default(),
378 }
379 }
380
381 pub fn child(mut self, child: impl IntoElement) -> Self {
382 self.children.push(child.into_any_element());
383 self
384 }
385
386 pub fn visible(mut self, visible: bool) -> Self {
387 self.visible = visible;
388 self
389 }
390
391 pub fn size(mut self, size: impl Into<Pixels>) -> Self {
392 self.initial_size = Some(size.into());
393 self
394 }
395
396 pub fn size_range(mut self, range: impl Into<Range<Pixels>>) -> Self {
397 self.size_range = range.into();
398 self
399 }
400
401 pub fn min_size(mut self, min: impl Into<Pixels>) -> Self {
402 self.size_range.start = min.into();
403 self
404 }
405
406 pub fn max_size(mut self, max: impl Into<Pixels>) -> Self {
407 self.size_range.end = max.into();
408 self
409 }
410}
411
412impl Styled for ResizablePanel {
413 fn style(&mut self) -> &mut StyleRefinement {
414 &mut self.style
415 }
416}
417
418impl RenderOnce for ResizablePanel {
419 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
420 if !self.visible {
421 return div().id(("resizable-panel", self.index)).into_any_element();
422 }
423
424 let state = self
425 .state
426 .as_ref()
427 .expect("ResizablePanel must be used within a ResizablePanelGroup");
428
429 let panel_state = state.read(cx).panels.get(self.index).cloned();
430
431 let size_range = self.size_range.clone();
432 let has_custom_size =
433 self.initial_size.is_some() || panel_state.as_ref().and_then(|p| p.size).is_some();
434
435 let mut panel_div = div()
436 .id(("resizable-panel", self.index))
437 .flex()
438 .flex_grow()
439 .size_full()
440 .relative();
441
442 panel_div = panel_div.when(self.axis.is_vertical(), |this| {
443 this.min_h(size_range.start).max_h(size_range.end)
444 });
445
446 panel_div = panel_div.when(self.axis.is_horizontal(), |this| {
447 this.min_w(size_range.start).max_w(size_range.end)
448 });
449
450 panel_div = panel_div.when(!has_custom_size, |this| this.flex_shrink());
451
452 if let Some(initial_size) = self.initial_size {
453 let should_use_flex_none = panel_state
454 .as_ref()
455 .map(|p| p.size.is_none() && !initial_size.is_zero())
456 .unwrap_or(false);
457
458 panel_div = panel_div
459 .when(should_use_flex_none, |this| this.flex_none())
460 .flex_basis(initial_size);
461 }
462
463 if let Some(panel_state) = panel_state.as_ref() {
464 if let Some(size) = panel_state.size {
465 panel_div = panel_div.flex_basis(size);
466 }
467 }
468
469 let user_style = self.style;
470
471 panel_div
472 .map(|this| {
473 let mut div = this;
474 div.style().refine(&user_style);
475 div
476 })
477 .children(self.children)
478 .when(self.index > 0, |this| {
479 let handle_index = self.index - 1;
480 let state = state.clone();
481
482 this.child(ResizeHandle::new(
483 ("resizable-handle", handle_index),
484 self.axis,
485 DragPanel,
486 move |drag_panel, _, _, cx| {
487 cx.stop_propagation();
488 state.update(cx, |state, _| {
489 state.resizing_panel_ix = Some(handle_index);
490 });
491 cx.new(|_| (*drag_panel).clone())
492 },
493 ))
494 })
495 .child({
496 let state = state.clone();
497 let index = self.index;
498 let size_range = self.size_range.clone();
499
500 canvas(
501 move |bounds, _, cx| {
502 state.update(cx, |state, cx| {
503 state.update_panel_size(index, bounds, size_range.clone(), cx)
504 })
505 },
506 |_, _, _, _| {},
507 )
508 .absolute()
509 .size_full()
510 })
511 .into_any_element()
512 }
513}
514
515#[derive(Clone)]
516struct DragPanel;
517
518impl Render for DragPanel {
519 fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
520 Empty
521 }
522}
523
524struct ResizeHandle<T: 'static, E: 'static + Render> {
525 id: ElementId,
526 axis: Axis,
527 drag_value: Rc<T>,
528 on_drag: Rc<dyn Fn(Rc<T>, &Point<Pixels>, &mut Window, &mut App) -> Entity<E>>,
529}
530
531impl<T: 'static, E: 'static + Render> ResizeHandle<T, E> {
532 fn new(
533 id: impl Into<ElementId>,
534 axis: Axis,
535 value: T,
536 f: impl Fn(Rc<T>, &Point<Pixels>, &mut Window, &mut App) -> Entity<E> + 'static,
537 ) -> Self {
538 Self {
539 id: id.into(),
540 axis,
541 drag_value: Rc::new(value),
542 on_drag: Rc::new(f),
543 }
544 }
545}
546
547#[derive(Default, Debug, Clone)]
548struct ResizeHandleState {
549 active: Cell<bool>,
550}
551
552impl ResizeHandleState {
553 fn set_active(&self, active: bool) {
554 self.active.set(active);
555 }
556
557 fn is_active(&self) -> bool {
558 self.active.get()
559 }
560}
561
562impl<T: 'static, E: 'static + Render> IntoElement for ResizeHandle<T, E> {
563 type Element = ResizeHandle<T, E>;
564
565 fn into_element(self) -> Self::Element {
566 self
567 }
568}
569
570impl<T: 'static, E: 'static + Render> Element for ResizeHandle<T, E> {
571 type RequestLayoutState = AnyElement;
572 type PrepaintState = ();
573
574 fn id(&self) -> Option<ElementId> {
575 Some(self.id.clone())
576 }
577
578 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
579 None
580 }
581
582 fn request_layout(
583 &mut self,
584 id: Option<&GlobalElementId>,
585 _: Option<&gpui::InspectorElementId>,
586 window: &mut Window,
587 cx: &mut App,
588 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
589 let neg_offset = -HANDLE_PADDING;
590 let axis = self.axis;
591 let theme = use_theme(cx);
592
593 window.with_element_state(id.unwrap(), |state, window| {
594 let state: ResizeHandleState = state.unwrap_or_default();
595
596 let bg_color = if state.is_active() {
597 theme.tokens.accent
598 } else {
599 theme.tokens.border
600 };
601
602 let mut handle_element = div()
603 .id(self.id.clone())
604 .occlude()
605 .absolute()
606 .flex_shrink_0()
607 .group("handle");
608
609 let on_drag = self.on_drag.clone();
610 let drag_value = self.drag_value.clone();
611 handle_element = handle_element
612 .on_drag(drag_value.clone(), move |_, position, window, cx| {
613 (on_drag)(drag_value.clone(), &position, window, cx)
614 });
615
616 handle_element = match axis {
617 Axis::Horizontal => handle_element
618 .cursor_col_resize()
619 .top_0()
620 .left(neg_offset)
621 .h_full()
622 .w(HANDLE_SIZE)
623 .px(HANDLE_PADDING),
624 Axis::Vertical => handle_element
625 .cursor_row_resize()
626 .top(neg_offset)
627 .left_0()
628 .w_full()
629 .h(HANDLE_SIZE)
630 .py(HANDLE_PADDING),
631 };
632
633 handle_element = handle_element.child(
634 div()
635 .bg(bg_color)
636 .group_hover("handle", |this| this.bg(theme.tokens.accent))
637 .when(axis.is_horizontal(), |this| this.h_full().w(HANDLE_SIZE))
638 .when(axis.is_vertical(), |this| this.w_full().h(HANDLE_SIZE)),
639 );
640
641 let mut el = handle_element.into_any_element();
642 let layout_id = el.request_layout(window, cx);
643
644 ((layout_id, el), state)
645 })
646 }
647
648 fn prepaint(
649 &mut self,
650 _: Option<&GlobalElementId>,
651 _: Option<&gpui::InspectorElementId>,
652 _: gpui::Bounds<Pixels>,
653 request_layout: &mut Self::RequestLayoutState,
654 window: &mut Window,
655 cx: &mut App,
656 ) -> Self::PrepaintState {
657 request_layout.prepaint(window, cx);
658 }
659
660 fn paint(
661 &mut self,
662 id: Option<&GlobalElementId>,
663 _: Option<&gpui::InspectorElementId>,
664 bounds: gpui::Bounds<Pixels>,
665 request_layout: &mut Self::RequestLayoutState,
666 _: &mut Self::PrepaintState,
667 window: &mut Window,
668 cx: &mut App,
669 ) {
670 request_layout.paint(window, cx);
671
672 window.with_element_state(id.unwrap(), |state: Option<ResizeHandleState>, window| {
673 let state = state.unwrap_or_default();
674
675 window.on_mouse_event({
676 let state = state.clone();
677 move |event: &MouseDownEvent, phase, window, _| {
678 if bounds.contains(&event.position) && phase.bubble() {
679 state.set_active(true);
680 window.refresh();
681 }
682 }
683 });
684
685 window.on_mouse_event({
686 let state = state.clone();
687 move |_: &MouseUpEvent, _, window, _| {
688 if state.is_active() {
689 state.set_active(false);
690 window.refresh();
691 }
692 }
693 });
694
695 ((), state)
696 });
697 }
698}
699
700struct ResizePanelGroupElement {
701 state: Entity<ResizableState>,
702 axis: Axis,
703}
704
705impl IntoElement for ResizePanelGroupElement {
706 type Element = Self;
707
708 fn into_element(self) -> Self::Element {
709 self
710 }
711}
712
713impl Element for ResizePanelGroupElement {
714 type RequestLayoutState = ();
715 type PrepaintState = ();
716
717 fn id(&self) -> Option<gpui::ElementId> {
718 None
719 }
720
721 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
722 None
723 }
724
725 fn request_layout(
726 &mut self,
727 _: Option<&gpui::GlobalElementId>,
728 _: Option<&gpui::InspectorElementId>,
729 window: &mut Window,
730 cx: &mut App,
731 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
732 (window.request_layout(Style::default(), None, cx), ())
733 }
734
735 fn prepaint(
736 &mut self,
737 _: Option<&gpui::GlobalElementId>,
738 _: Option<&gpui::InspectorElementId>,
739 _: Bounds<Pixels>,
740 _: &mut Self::RequestLayoutState,
741 _: &mut Window,
742 _: &mut App,
743 ) -> Self::PrepaintState {
744 }
745
746 fn paint(
747 &mut self,
748 _: Option<&gpui::GlobalElementId>,
749 _: Option<&gpui::InspectorElementId>,
750 _: Bounds<Pixels>,
751 _: &mut Self::RequestLayoutState,
752 _: &mut Self::PrepaintState,
753 window: &mut Window,
754 _cx: &mut App,
755 ) {
756 window.on_mouse_event({
757 let state = self.state.clone();
758 let axis = self.axis;
759
760 move |event: &MouseMoveEvent, phase, window, cx| {
761 if !phase.bubble() {
762 return;
763 }
764
765 let Some(panel_index) = state.read(cx).resizing_panel_ix else {
766 return;
767 };
768
769 state.update(cx, |state, cx| {
770 if let Some(panel) = state.panels.get(panel_index) {
771 let new_size = match axis {
772 Axis::Horizontal => event.position.x - panel.bounds.left(),
773 Axis::Vertical => event.position.y - panel.bounds.top(),
774 };
775
776 state.resize_panel(panel_index, new_size, window, cx);
777 }
778
779 cx.notify();
780 });
781 }
782 });
783
784 window.on_mouse_event({
785 let state = self.state.clone();
786
787 move |_: &MouseUpEvent, phase, _, cx| {
788 if state.read(cx).resizing_panel_ix.is_none() {
789 return;
790 }
791
792 if phase.bubble() {
793 state.update(cx, |state, cx| {
794 state.done_resizing(cx);
795 });
796 }
797 }
798 });
799 }
800}