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 let axis = self.axis;
400 this.child(
401 resize_handle(("resizable-handle", ix), self.axis)
402 .when_some(self.handle_appearance.clone(), |handle, appearance| {
403 handle.with_appearance(appearance)
404 })
405 .on_drag(DragPanel, move |drag_panel, _, window, cx| {
406 cx.stop_propagation();
407 state.update(cx, |state, cx| {
408 state.resizing_panel_ix = Some(ix);
409 let Some(panel) = state.panels.get(ix) else {
410 return;
411 };
412 let pointer = window.mouse_position();
413 let requested_size = match axis {
414 Axis::Horizontal => pointer.x - panel.bounds.left(),
415 Axis::Vertical => pointer.y - panel.bounds.top(),
416 };
417 state.resize_panel_at_handle(ix, requested_size, window, cx);
418 });
419 cx.new(|_| drag_panel.clone())
420 }),
421 )
422 })
423 }
424}
425
426struct ResizePanelGroupElement {
427 state: Entity<ResizableState>,
428 on_resize: Rc<dyn Fn(&Entity<ResizableState>, &mut Window, &mut App)>,
429 axis: Axis,
430}
431
432impl Element for ResizePanelGroupElement {
433 type RequestLayoutState = ();
434 type PrepaintState = ();
435
436 fn id(&self) -> Option<gpui::ElementId> {
437 None
438 }
439
440 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
441 None
442 }
443
444 fn request_layout(
445 &mut self,
446 _: Option<&gpui::GlobalElementId>,
447 _: Option<&gpui::InspectorElementId>,
448 window: &mut Window,
449 cx: &mut App,
450 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
451 (window.request_layout(Style::default(), None, cx), ())
452 }
453
454 fn prepaint(
455 &mut self,
456 _: Option<&gpui::GlobalElementId>,
457 _: Option<&gpui::InspectorElementId>,
458 _: Bounds<Pixels>,
459 _: &mut Self::RequestLayoutState,
460 _window: &mut Window,
461 _cx: &mut App,
462 ) -> Self::PrepaintState {
463 ()
464 }
465
466 fn paint(
467 &mut self,
468 _: Option<&gpui::GlobalElementId>,
469 _: Option<&gpui::InspectorElementId>,
470 _: Bounds<Pixels>,
471 _: &mut Self::RequestLayoutState,
472 _: &mut Self::PrepaintState,
473 window: &mut Window,
474 cx: &mut App,
475 ) {
476 if self.state.read(cx).resizing_panel_ix.is_some() && !cx.has_active_drag() {
479 let state = self.state.clone();
480 let on_resize = self.on_resize.clone();
481 window.defer(cx, move |window, cx| {
482 if state.read(cx).resizing_panel_ix.is_none() || cx.has_active_drag() {
483 return;
484 }
485 state.update(cx, |state, cx| {
486 state.done_resizing(cx);
487 cx.notify();
488 });
489 on_resize(&state, window, cx);
490 });
491 }
492
493 window.on_mouse_event({
494 let state = self.state.clone();
495 let axis = self.axis;
496 move |e: &MouseMoveEvent, phase, window, cx| {
497 if !phase.bubble() || !cx.has_active_drag() {
498 return;
499 }
500 let Some(ix) = state.read(cx).resizing_panel_ix else {
501 return;
502 };
503
504 state.update(cx, |state, cx| {
505 let panel = state.panels.get(ix).expect("BUG: invalid panel index");
506
507 match axis {
508 Axis::Horizontal => state.resize_panel_at_handle(
509 ix,
510 e.position.x - panel.bounds.left(),
511 window,
512 cx,
513 ),
514 Axis::Vertical => state.resize_panel_at_handle(
515 ix,
516 e.position.y - panel.bounds.top(),
517 window,
518 cx,
519 ),
520 }
521 cx.notify();
522 })
523 }
524 });
525
526 window.on_mouse_event({
528 let state = self.state.clone();
529 let on_resize = self.on_resize.clone();
530 move |_: &MouseUpEvent, phase, window, cx| {
531 if state.read(cx).resizing_panel_ix.is_none() {
532 return;
533 }
534 if phase.bubble() {
535 state.update(cx, |state, cx| state.done_resizing(cx));
536 on_resize(&state, window, cx);
537 }
538 }
539 })
540 }
541}