1use std::{ops::Range, rc::Rc};
2
3use gpui::{
4 Along, AnyElement, App, AppContext, Axis, Bounds, Context, Element, ElementId, Empty, Entity,
5 EventEmitter, InteractiveElement as _, IntoElement, IsZero as _, MouseMoveEvent, MouseUpEvent,
6 ParentElement, Pixels, Render, RenderOnce, Style, StyleRefinement, Styled, Window, div,
7 prelude::FluentBuilder,
8};
9
10use crate::{AxisExt, ElementExt, StyledExt as _, h_flex, resizable::PANEL_MIN_SIZE, v_flex};
11
12use super::{ResizableState, ResizeHandleRenderer, resizable_panel, resize_handle};
13
14pub enum ResizablePanelEvent {
15 Resized,
16}
17
18#[derive(Clone)]
19pub(crate) struct DragPanel;
20impl Render for DragPanel {
21 fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
22 Empty
23 }
24}
25
26#[derive(IntoElement)]
28pub struct ResizablePanelGroup {
29 id: ElementId,
30 state: Option<Entity<ResizableState>>,
31 axis: Axis,
32 size: Option<Pixels>,
33 children: Vec<ResizablePanel>,
34 on_resize: Rc<dyn Fn(&Entity<ResizableState>, &mut Window, &mut App)>,
35 handle_appearance: Option<ResizeHandleRenderer>,
36}
37
38impl ResizablePanelGroup {
39 pub fn new(id: impl Into<ElementId>) -> Self {
41 Self {
42 id: id.into(),
43 axis: Axis::Horizontal,
44 children: vec![],
45 state: None,
46 size: None,
47 on_resize: Rc::new(|_, _, _| {}),
48 handle_appearance: None,
49 }
50 }
51
52 pub fn with_handle_appearance(mut self, appearance: ResizeHandleRenderer) -> Self {
57 self.handle_appearance = Some(appearance);
58 self
59 }
60
61 pub fn with_state(mut self, state: &Entity<ResizableState>) -> Self {
65 self.state = Some(state.clone());
66 self
67 }
68
69 pub fn axis(mut self, axis: Axis) -> Self {
71 self.axis = axis;
72 self
73 }
74
75 pub fn child(mut self, panel: impl Into<ResizablePanel>) -> Self {
81 self.children.push(panel.into());
82 self
83 }
84
85 pub fn children<I>(mut self, panels: impl IntoIterator<Item = I>) -> Self
87 where
88 I: Into<ResizablePanel>,
89 {
90 self.children = panels.into_iter().map(|panel| panel.into()).collect();
91 self
92 }
93
94 pub fn size(mut self, size: Pixels) -> Self {
99 self.size = Some(size);
100 self
101 }
102
103 pub fn on_resize(
109 mut self,
110 on_resize: impl Fn(&Entity<ResizableState>, &mut Window, &mut App) + 'static,
111 ) -> Self {
112 self.on_resize = Rc::new(on_resize);
113 self
114 }
115}
116
117impl<T> From<T> for ResizablePanel
118where
119 T: Into<AnyElement>,
120{
121 fn from(value: T) -> Self {
122 resizable_panel().child(value.into())
123 }
124}
125
126impl From<ResizablePanelGroup> for ResizablePanel {
127 fn from(value: ResizablePanelGroup) -> Self {
128 resizable_panel().child(value)
129 }
130}
131
132impl EventEmitter<ResizablePanelEvent> for ResizablePanelGroup {}
133
134impl RenderOnce for ResizablePanelGroup {
135 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
136 let state = self.state.unwrap_or(
137 window.use_keyed_state(self.id.clone(), cx, |_, _| ResizableState::default()),
138 );
139 let container = if self.axis.is_horizontal() {
140 h_flex()
141 } else {
142 v_flex()
143 };
144
145 let panels_count = self.children.len();
147 state.update(cx, |state, cx| {
148 state.sync_panels_count(self.axis, panels_count, cx);
149 state.sync_panel_visibility(self.children.iter().map(|panel| panel.visible), cx);
150 });
151
152 container
153 .id(self.id)
154 .size_full()
155 .when_some(self.size, |this, size| match self.axis {
158 Axis::Horizontal => this.h(size),
159 Axis::Vertical => this.w(size),
160 })
161 .children(
162 self.children
163 .into_iter()
164 .enumerate()
165 .map(|(ix, mut panel)| {
166 panel.panel_ix = ix;
167 panel.axis = self.axis;
168 panel.state = Some(state.clone());
169 panel.handle_appearance = self.handle_appearance.clone();
170 panel
171 }),
172 )
173 .on_prepaint({
174 let state = state.clone();
175 move |bounds, window, cx| {
176 if state.read(cx).bounds == bounds {
179 return;
180 }
181 state.update(cx, |state, cx| {
182 let size_changed =
183 state.bounds.size.along(self.axis) != bounds.size.along(self.axis);
184
185 state.bounds = bounds;
186
187 if size_changed {
188 state.adjust_to_container_size(cx);
189 let state = cx.entity();
198 window.defer(cx, move |_, cx| {
199 state.update(cx, |_, cx| cx.notify());
200 });
201 }
202 })
203 }
204 })
205 .child(ResizePanelGroupElement {
206 state: state.clone(),
207 axis: self.axis,
208 on_resize: self.on_resize.clone(),
209 })
210 }
211}
212
213#[derive(IntoElement)]
244pub struct ResizablePanel {
245 axis: Axis,
246 panel_ix: usize,
247 state: Option<Entity<ResizableState>>,
248 initial_size: Option<Pixels>,
250 size_range: Range<Pixels>,
252 children: Vec<AnyElement>,
253 visible: bool,
254 style: StyleRefinement,
255 handle_appearance: Option<ResizeHandleRenderer>,
256 fixed: bool,
257}
258
259impl ResizablePanel {
260 pub(super) fn new() -> Self {
262 Self {
263 panel_ix: 0,
264 initial_size: None,
265 state: None,
266 size_range: (PANEL_MIN_SIZE..Pixels::MAX),
267 axis: Axis::Horizontal,
268 children: vec![],
269 visible: true,
270 style: StyleRefinement::default(),
271 handle_appearance: None,
272 fixed: false,
273 }
274 }
275
276 pub fn visible(mut self, visible: bool) -> Self {
278 self.visible = visible;
279 self
280 }
281
282 pub fn size(mut self, size: impl Into<Pixels>) -> Self {
284 self.initial_size = Some(size.into());
285 self
286 }
287
288 pub fn size_range(mut self, range: impl Into<Range<Pixels>>) -> Self {
292 self.size_range = range.into();
293 self
294 }
295
296 pub fn fixed(mut self) -> Self {
304 self.fixed = true;
305 self
306 }
307}
308
309impl Styled for ResizablePanel {
310 fn style(&mut self) -> &mut StyleRefinement {
311 &mut self.style
312 }
313}
314
315impl ParentElement for ResizablePanel {
316 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
317 self.children.extend(elements);
318 }
319}
320
321impl RenderOnce for ResizablePanel {
322 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
323 if !self.visible {
324 return div().id(("resizable-panel", self.panel_ix));
325 }
326
327 let state = self
328 .state
329 .expect("BUG: The `state` in ResizablePanel should be present.");
330 let panel_state = state
331 .read(cx)
332 .panels
333 .get(self.panel_ix)
334 .expect("BUG: The `index` of ResizablePanel should be one of in `state`.");
335 let size_range = self.size_range.clone();
336 let fixed = self.fixed && self.initial_size.is_some();
338 let previous_panel = state.read(cx).previous_visible_panel(self.panel_ix);
339
340 div()
341 .id(("resizable-panel", self.panel_ix))
342 .flex()
343 .flex_grow_1()
344 .size_full()
345 .relative()
346 .refine_style(&self.style)
354 .when(self.axis.is_vertical(), |this| {
355 this.min_h(size_range.start).max_h(size_range.end)
356 })
357 .when(self.axis.is_horizontal(), |this| {
358 this.min_w(size_range.start).max_w(size_range.end)
359 })
360 .when(self.initial_size.is_none(), |this| this.flex_shrink_1())
364 .when_some(self.initial_size, |this, initial_size| {
365 this.when(
368 panel_state.size.is_none() && !initial_size.is_zero(),
369 |this| this.flex_none(),
370 )
371 .flex_basis(initial_size)
372 })
373 .map(|this| match panel_state.size {
374 Some(size) => this.flex_basis(size.min(size_range.end).max(size_range.start)),
375 None => this,
376 })
377 .when(fixed, |this| this.flex_grow_0().flex_shrink_0())
381 .on_prepaint({
382 let state = state.clone();
383 move |bounds, _, cx| {
384 if !state.read(cx).panel_size_changes(
385 self.panel_ix,
386 bounds,
387 &self.size_range,
388 fixed,
389 ) {
390 return;
391 }
392 state.update(cx, |state, cx| {
393 state.update_panel_size(self.panel_ix, bounds, self.size_range, fixed, cx)
394 })
395 }
396 })
397 .children(self.children)
398 .when_some(previous_panel, |this, ix| {
399 this.child(
400 resize_handle(("resizable-handle", ix), self.axis)
401 .when_some(self.handle_appearance.clone(), |handle, appearance| {
402 handle.with_appearance(appearance)
403 })
404 .on_drag(DragPanel, move |drag_panel, _, _, cx| {
405 cx.stop_propagation();
406 state.update(cx, |state, _| {
408 state.resizing_panel_ix = Some(ix);
409 });
410 cx.new(|_| drag_panel.clone())
411 }),
412 )
413 })
414 }
415}
416
417struct ResizePanelGroupElement {
418 state: Entity<ResizableState>,
419 on_resize: Rc<dyn Fn(&Entity<ResizableState>, &mut Window, &mut App)>,
420 axis: Axis,
421}
422
423impl Element for ResizePanelGroupElement {
424 type RequestLayoutState = ();
425 type PrepaintState = ();
426
427 fn id(&self) -> Option<gpui::ElementId> {
428 None
429 }
430
431 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
432 None
433 }
434
435 fn request_layout(
436 &mut self,
437 _: Option<&gpui::GlobalElementId>,
438 _: Option<&gpui::InspectorElementId>,
439 window: &mut Window,
440 cx: &mut App,
441 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
442 (window.request_layout(Style::default(), None, cx), ())
443 }
444
445 fn prepaint(
446 &mut self,
447 _: Option<&gpui::GlobalElementId>,
448 _: Option<&gpui::InspectorElementId>,
449 _: Bounds<Pixels>,
450 _: &mut Self::RequestLayoutState,
451 _window: &mut Window,
452 _cx: &mut App,
453 ) -> Self::PrepaintState {
454 ()
455 }
456
457 fn paint(
458 &mut self,
459 _: Option<&gpui::GlobalElementId>,
460 _: Option<&gpui::InspectorElementId>,
461 _: Bounds<Pixels>,
462 _: &mut Self::RequestLayoutState,
463 _: &mut Self::PrepaintState,
464 window: &mut Window,
465 cx: &mut App,
466 ) {
467 if self.state.read(cx).resizing_panel_ix.is_some() && !cx.has_active_drag() {
470 let state = self.state.clone();
471 let on_resize = self.on_resize.clone();
472 window.defer(cx, move |window, cx| {
473 if state.read(cx).resizing_panel_ix.is_none() || cx.has_active_drag() {
474 return;
475 }
476 state.update(cx, |state, cx| {
477 state.done_resizing(cx);
478 cx.notify();
479 });
480 on_resize(&state, window, cx);
481 });
482 }
483
484 window.on_mouse_event({
485 let state = self.state.clone();
486 let axis = self.axis;
487 move |e: &MouseMoveEvent, phase, window, cx| {
488 if !phase.bubble() || !cx.has_active_drag() {
489 return;
490 }
491 let Some(ix) = state.read(cx).resizing_panel_ix else {
492 return;
493 };
494
495 state.update(cx, |state, cx| {
496 let panel = state.panels.get(ix).expect("BUG: invalid panel index");
497
498 match axis {
499 Axis::Horizontal => state.resize_panel_at_handle(
500 ix,
501 e.position.x - panel.bounds.left(),
502 window,
503 cx,
504 ),
505 Axis::Vertical => state.resize_panel_at_handle(
506 ix,
507 e.position.y - panel.bounds.top(),
508 window,
509 cx,
510 ),
511 }
512 cx.notify();
513 })
514 }
515 });
516
517 window.on_mouse_event({
519 let state = self.state.clone();
520 let on_resize = self.on_resize.clone();
521 move |_: &MouseUpEvent, phase, window, cx| {
522 if state.read(cx).resizing_panel_ix.is_none() {
523 return;
524 }
525 if phase.bubble() {
526 state.update(cx, |state, cx| state.done_resizing(cx));
527 on_resize(&state, window, cx);
528 }
529 }
530 })
531 }
532}