Skip to main content

gpui_base/resizable/
mod.rs

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
16/// Create a [`ResizablePanelGroup`] with horizontal resizing
17pub fn h_resizable(id: impl Into<ElementId>) -> ResizablePanelGroup {
18    ResizablePanelGroup::new(id).axis(Axis::Horizontal)
19}
20
21/// Create a [`ResizablePanelGroup`] with vertical resizing
22pub fn v_resizable(id: impl Into<ElementId>) -> ResizablePanelGroup {
23    ResizablePanelGroup::new(id).axis(Axis::Vertical)
24}
25
26/// Create a [`ResizablePanel`].
27pub fn resizable_panel() -> ResizablePanel {
28    ResizablePanel::new()
29}
30
31/// State for a [`ResizablePanel`]
32#[derive(Debug, Clone)]
33pub struct ResizableState {
34    /// The `axis` will sync to actual axis of the ResizablePanelGroup in use.
35    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    /// Get the size of the panels.
56    pub fn sizes(&self) -> &Vec<Pixels> {
57        &self.sizes
58    }
59
60    /// Whether a resize handle is being dragged.
61    ///
62    /// Starting a drag does not notify, so read this while rendering during
63    /// the drag rather than relying on a notification when it starts.
64    pub fn is_resizing(&self) -> bool {
65        self.resizing_panel_ix.is_some()
66    }
67
68    /// Programmatically resize the panel at `ix` to `size`, redistributing
69    /// space among siblings using the same logic as a drag.
70    ///
71    /// The size change respects the visible panels' `size_range` and available space.
72    /// Emits `ResizablePanelEvent::Resized` so subscribers (e.g. preference
73    /// persistence) see the change just as if the user had dragged a handle.
74    ///
75    /// Hidden panels and out-of-range indices are ignored. The last visible
76    /// panel resizes using the boundary with its previous visible sibling.
77    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            // Last panel: drive its size by resizing the previous sibling so
91            // the freed space lands here.
92            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    /// Insert a panel state at `ix`, or append it when no index is supplied.
100    ///
101    /// Existing panel sizes are redistributed so their total remains equal to
102    /// the current container size.
103    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        // We make sure that the size always sums up to the container size
117        // by reducing the size of all other panels first.
118        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    /// Adopt slot sizes decided by an owner that keeps its own record of the
142    /// layout — the dock's pane tree does.
143    ///
144    /// Unlike [`Self::insert_panel`], nothing is redistributed: the caller has
145    /// already decided how the space divides, and re-normalizing here would
146    /// undo exactly that decision. Slots the caller left unconstrained keep
147    /// whatever they had.
148    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            // The preference is mirrored exactly, `None` included. That is the
152            // load-bearing half: `insert_panel` resolves every existing
153            // panel's `None` into a concrete value as a side effect of
154            // redistributing, so after inserting one slot the caller's "these
155            // two are equally unconstrained" has quietly become "that one is
156            // pinned, this one is the only flexible slot" — and the flexible
157            // one then swallows whatever the pinned ones leave over.
158            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            // The measurement only moves when the tree names a size; an
169            // unconstrained slot keeps whatever it was last laid out at until
170            // the next pass recomputes it.
171            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            // We need to make sure the total size is in line with the container size.
210            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                // Hidden panels keep their slot and preferred size but occupy no space.
225                *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            // Flex lays out the visible panels without replacing their preferred sizes.
236            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    /// Whether [`Self::update_panel_size`] with these arguments would change
249    /// anything. A panel reports its bounds as it prepaints, every frame it
250    /// is drawn; updating the state for the same bounds would mark it, and
251    /// every view that reads it, changed on every frame.
252    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        // This check is only necessary to stop the very first panel from resizing on its own
279        // it needs to be passed when the panel is freshly created so we get the initial size,
280        // but its also fine when it sometimes passes later.
281        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    /// Remove the panel at `panel_ix` and redistribute the remaining space.
291    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    /// Reset the panel at `panel_ix` while preserving its current size.
303    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    /// Remove all panel state.
314    pub fn clear(&mut self) {
315        self.panels.clear();
316        self.sizes.clear();
317        self.resizing_panel_ix = None;
318    }
319
320    #[inline]
321    /// Return the measured size of the group along its resize axis.
322    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    /// Resize the panel at `ix` by treating `ix` as the drag-handle position
332    /// between it and the next visible panel.
333    ///
334    /// This is the worker behind drag interactions and the public
335    /// [`Self::resize_panel`] API.
336    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        // The pointer position is relative to the last layout, not the flex basis.
350        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            // A fixed panel can shrink only if it borders the dragged handle.
394            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    /// Adjust panel sizes according to the container size.
405    ///
406    /// When the container size changes, the panels should take up the same percentage as they did before.
407    fn adjust_to_container_size(&mut self, cx: &mut Context<Self>) {
408        if self.container_size().is_zero() {
409            return;
410        }
411
412        // A panel with no size preference is laid out by flex, and its entry
413        // in `sizes` is a placeholder until something measures it. Rescaling
414        // by a ratio computed from that placeholder drags the panels that
415        // *do* have a preference along with it: a 200px sidebar beside one
416        // flexible panel comes back 587px wide on the frame after the first,
417        // which reads as the layout jumping once for no reason. Flex already
418        // fits the container, so there is nothing here to adjust.
419        if self
420            .panels
421            .iter()
422            .any(|panel| !panel.hidden && panel.size.is_none())
423        {
424            return;
425        }
426
427        // Fixed panels keep their size; the other panels share what is left
428        // in the same proportions as before. A container too small for the
429        // fixed panels leaves every size alone, so the proportions survive
430        // until it grows again.
431        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    /// See [`ResizablePanel::fixed`].
476    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    };
496
497    struct MixedSizingHarness {
498        width: Pixels,
499    }
500
501    impl Render for MixedSizingHarness {
502        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
503            div().w(self.width).h(px(100.)).child(
504                h_resizable("mixed-sizing")
505                    .child(
506                        resizable_panel()
507                            .size(px(240.))
508                            .child(div().size_full().debug_selector(|| "fixed-sidebar".into())),
509                    )
510                    .child(
511                        resizable_panel().child(
512                            div()
513                                .size_full()
514                                .debug_selector(|| "flexible-content".into()),
515                        ),
516                    ),
517            )
518        }
519    }
520
521    #[gpui::test]
522    fn mixed_sizing_is_stable_between_resize_and_followup_frame(cx: &mut TestAppContext) {
523        let (view, cx) = cx.add_window_view(|_, _| MixedSizingHarness { width: px(800.) });
524        cx.update(|window, cx| {
525            window.draw(cx).clear(cx);
526            window.draw(cx).clear(cx);
527        });
528        let before = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
529
530        view.update(cx, |view, cx| {
531            view.width = px(1200.);
532            cx.notify();
533        });
534        cx.run_until_parked();
535        let settled_frame = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
536        cx.update(|window, cx| window.draw(cx).clear(cx));
537        let followup_frame = cx.debug_bounds("fixed-sidebar").unwrap().size.width;
538
539        // Resizable panels preserve their proportional sizing across a
540        // container resize; the important invariant is that applying the
541        // state on the follow-up frame does not move the divider again.
542        assert_ne!(settled_frame, before);
543        assert_eq!(followup_frame, settled_frame);
544    }
545
546    struct FixedPanelHarness {
547        width: Pixels,
548        fixed: bool,
549        state: gpui::Entity<ResizableState>,
550    }
551
552    impl Render for FixedPanelHarness {
553        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
554            div().w(self.width).h(px(100.)).child(
555                h_resizable("fixed-panel")
556                    .with_state(&self.state)
557                    .child(
558                        resizable_panel()
559                            .size(px(240.))
560                            .size_range(px(100.)..px(480.))
561                            .when(self.fixed, |panel| panel.fixed())
562                            .child(div().size_full().debug_selector(|| "fp-sidebar".into())),
563                    )
564                    .child(
565                        resizable_panel()
566                            .size(px(400.))
567                            .child(div().size_full().debug_selector(|| "fp-main".into())),
568                    )
569                    .child(
570                        resizable_panel()
571                            .child(div().size_full().debug_selector(|| "fp-aside".into())),
572                    ),
573            )
574        }
575    }
576
577    /// A fixed panel keeps its size when the container resizes, the other
578    /// panels share the rest in their proportions, and a container briefly
579    /// too small for the fixed panel does not lose those proportions. A drag
580    /// on another handle does not take space from it either.
581    #[gpui::test]
582    fn fixed_panel_keeps_its_size_across_a_container_resize(cx: &mut TestAppContext) {
583        let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
584        let (view, cx) = cx.add_window_view({
585            let state = state.clone();
586            move |_, _| FixedPanelHarness {
587                width: px(840.),
588                fixed: true,
589                state,
590            }
591        });
592        cx.update(|window, cx| {
593            window.draw(cx).clear(cx);
594            window.draw(cx).clear(cx);
595        });
596        let widths = |cx: &mut VisualTestContext| {
597            ["fp-sidebar", "fp-main", "fp-aside"].map(|selector| {
598                cx.debug_bounds(selector)
599                    .expect("every panel must lay out")
600                    .size
601                    .width
602            })
603        };
604        assert_eq!(widths(cx), [px(240.), px(400.), px(200.)]);
605
606        for (width, expected) in [
607            (px(1140.), Some([px(240.), px(600.), px(300.)])),
608            (px(200.), None),
609            (px(600.), Some([px(240.), px(240.), px(120.)])),
610        ] {
611            view.update(cx, |view, cx| {
612                view.width = width;
613                cx.notify();
614            });
615            cx.run_until_parked();
616            cx.update(|window, cx| window.draw(cx).clear(cx));
617            assert_eq!(widths(cx)[0], px(240.), "{width:?}");
618            if let Some(expected) = expected {
619                assert_eq!(widths(cx), expected, "{width:?}");
620            }
621        }
622
623        // Dragging the main panel below its minimum takes the rest from the
624        // panel after it, not from the fixed sidebar before it.
625        cx.update(|window, cx| {
626            state.update(cx, |state, cx| state.resize_panel(1, px(50.), window, cx));
627            window.draw(cx).clear(cx);
628        });
629        assert_eq!(widths(cx), [px(240.), px(100.), px(260.)]);
630
631        // Its own handle still resizes the fixed sidebar, and it keeps the
632        // new width when the container resizes again.
633        cx.update(|window, cx| {
634            state.update(cx, |state, cx| state.resize_panel(0, px(300.), window, cx));
635            window.draw(cx).clear(cx);
636        });
637        assert_eq!(widths(cx), [px(300.), px(100.), px(200.)]);
638        view.update(cx, |view, cx| {
639            view.width = px(900.);
640            cx.notify();
641        });
642        cx.run_until_parked();
643        cx.update(|window, cx| window.draw(cx).clear(cx));
644        assert_eq!(widths(cx)[0], px(300.));
645    }
646
647    /// A panel made fixed after its first frame, while its bounds stay the
648    /// same, keeps its size on the next container resize.
649    #[gpui::test]
650    fn panel_made_fixed_in_place_keeps_its_size_across_a_container_resize(cx: &mut TestAppContext) {
651        let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
652        let (view, cx) = cx.add_window_view(move |_, _| FixedPanelHarness {
653            width: px(840.),
654            fixed: false,
655            state,
656        });
657        let draw = |cx: &mut VisualTestContext, update: fn(&mut FixedPanelHarness)| {
658            view.update(cx, |view, cx| {
659                update(view);
660                cx.notify();
661            });
662            cx.run_until_parked();
663            cx.update(|window, cx| window.draw(cx).clear(cx));
664        };
665        draw(cx, |_| {});
666        draw(cx, |view| view.fixed = true);
667        draw(cx, |view| view.width = px(1140.));
668
669        let sidebar = cx
670            .debug_bounds("fp-sidebar")
671            .expect("the sidebar must lay out");
672        assert_eq!(sidebar.size.width, px(240.));
673    }
674
675    struct CallerStateHarness {
676        width: Pixels,
677        state: gpui::Entity<ResizableState>,
678    }
679
680    impl Render for CallerStateHarness {
681        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
682            div().w(self.width).h(px(100.)).child(
683                h_resizable("caller-state")
684                    .with_state(&self.state)
685                    .child(
686                        resizable_panel()
687                            .size(px(240.))
688                            .child(div().size_full().debug_selector(|| "cs-sidebar".into())),
689                    )
690                    .child(resizable_panel().child(div().size_full())),
691            )
692        }
693    }
694
695    /// A group whose state the caller owns (`with_state`, as the dock does)
696    /// has no `use_keyed_state` observer behind it, so the settling frame has
697    /// to be scheduled by the deferred notify rather than by that observer.
698    #[gpui::test]
699    fn caller_owned_state_settles_on_the_same_frame(cx: &mut TestAppContext) {
700        let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
701        let (view, cx) = cx.add_window_view(move |_, _| CallerStateHarness {
702            width: px(800.),
703            state,
704        });
705        cx.update(|window, cx| {
706            window.draw(cx).clear(cx);
707            window.draw(cx).clear(cx);
708        });
709
710        view.update(cx, |view, cx| {
711            view.width = px(1200.);
712            cx.notify();
713        });
714        cx.run_until_parked();
715        let settled = cx.debug_bounds("cs-sidebar").unwrap().size.width;
716        cx.update(|window, cx| window.draw(cx).clear(cx));
717        let followup = cx.debug_bounds("cs-sidebar").unwrap().size.width;
718
719        assert_eq!(followup, settled, "settling frame must not be pending");
720    }
721
722    struct ResizableHarness {
723        state: gpui::Entity<ResizableState>,
724        resizes: Rc<Cell<usize>>,
725    }
726
727    impl Render for ResizableHarness {
728        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
729            div().w(px(400.)).h(px(100.)).child(
730                h_resizable("resizable")
731                    .with_state(&self.state)
732                    .on_resize({
733                        let resizes = self.resizes.clone();
734                        move |_, _, _| resizes.set(resizes.get() + 1)
735                    })
736                    .child(
737                        resizable_panel()
738                            .size(px(150.))
739                            .child(div().size_full().debug_selector(|| "first-panel".into())),
740                    )
741                    .child(
742                        resizable_panel()
743                            .size(px(250.))
744                            .child(div().size_full().debug_selector(|| "second-panel".into())),
745                    ),
746            )
747        }
748    }
749
750    fn harness(
751        cx: &mut TestAppContext,
752    ) -> (
753        &mut VisualTestContext,
754        gpui::Entity<ResizableState>,
755        Rc<Cell<usize>>,
756    ) {
757        let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
758        let resizes = Rc::new(Cell::new(0));
759        let (_, cx) = cx.add_window_view({
760            let state = state.clone();
761            let resizes = resizes.clone();
762            move |_, _| ResizableHarness { state, resizes }
763        });
764        cx.update(|window, cx| window.draw(cx).clear(cx));
765        cx.update(|window, cx| window.draw(cx).clear(cx));
766        (cx, state, resizes)
767    }
768
769    /// A view reading a [`ResizableState`], counting its renders.
770    #[cfg(feature = "gpui-fast")]
771    struct StateReader {
772        state: gpui::Entity<ResizableState>,
773        renders: Rc<Cell<usize>>,
774    }
775
776    #[cfg(feature = "gpui-fast")]
777    impl Render for StateReader {
778        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
779            self.renders.set(self.renders.get() + 1);
780            let _ = self.state.read(cx).sizes.len();
781            div()
782        }
783    }
784
785    /// Panels beside a [`StateReader`] of their state.
786    #[cfg(feature = "gpui-fast")]
787    struct ReaderBesidePanels {
788        state: gpui::Entity<ResizableState>,
789        reader: gpui::Entity<StateReader>,
790    }
791
792    #[cfg(feature = "gpui-fast")]
793    impl Render for ReaderBesidePanels {
794        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
795            div()
796                .w(px(800.))
797                .h(px(100.))
798                .child(self.reader.clone())
799                .child(
800                    h_resizable("reader-panels")
801                        .with_state(&self.state)
802                        .child(resizable_panel().size(px(240.)).child(div().size_full()))
803                        .child(resizable_panel().child(div().size_full())),
804                )
805        }
806    }
807
808    /// Drawing panels again at the bounds they had changes nothing in their
809    /// state: a view reading it, beside them in a view drawn again, is not
810    /// built again for it.
811    #[cfg(feature = "gpui-fast")]
812    #[gpui::test]
813    fn redrawing_panels_where_they_were_leaves_their_readers_retained(cx: &mut TestAppContext) {
814        let renders = Rc::new(Cell::new(0));
815        let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
816        let (view, cx) = cx.add_window_view({
817            let state = state.clone();
818            let renders = renders.clone();
819            move |_, cx| ReaderBesidePanels {
820                state: state.clone(),
821                reader: cx.new(|_| StateReader { state, renders }),
822            }
823        });
824        for _ in 0..3 {
825            cx.update(|window, cx| window.draw(cx).clear(cx));
826            cx.run_until_parked();
827        }
828        let before = renders.get();
829        for _ in 0..3 {
830            view.update(cx, |_, cx| cx.notify());
831            cx.update(|window, cx| window.draw(cx).clear(cx));
832            cx.run_until_parked();
833        }
834        assert_eq!(renders.get(), before, "the reader rendered again");
835    }
836
837    #[gpui::test]
838    fn dynamic_panel_lifecycle_is_owned_by_resizable_state(cx: &mut TestAppContext) {
839        let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
840
841        cx.update(|cx| {
842            state.update(cx, |state, cx| {
843                state.bounds.size = size(px(400.), px(100.));
844                state.panels.push(Default::default());
845                state.sizes.push(px(400.));
846                state.insert_panel(Some(px(200.)), None, cx);
847                assert_eq!(state.sizes(), &vec![px(200.), px(200.)]);
848
849                state.reset_panel(0, cx);
850                assert_eq!(state.sizes(), &vec![px(200.), px(200.)]);
851
852                state.remove_panel(0, cx);
853                assert_eq!(state.sizes(), &vec![px(400.)]);
854
855                state.clear();
856                assert!(state.sizes().is_empty());
857            });
858        });
859    }
860
861    #[gpui::test]
862    fn group_measures_panels_and_programmatic_resize_uses_drag_rules(cx: &mut TestAppContext) {
863        let (cx, state, _) = harness(cx);
864        let first = cx.debug_bounds("first-panel").unwrap();
865        let second = cx.debug_bounds("second-panel").unwrap();
866        assert_eq!(first.size.width + second.size.width, px(400.));
867
868        cx.update(|window, cx| {
869            state.update(cx, |state, cx| {
870                state.resize_panel(0, px(220.), window, cx);
871            });
872            window.draw(cx).clear(cx);
873        });
874
875        state.read_with(cx, |state, _| {
876            assert_eq!(state.sizes(), &vec![px(220.), px(180.)]);
877        });
878    }
879
880    #[gpui::test]
881    fn resizing_uses_measured_sizes_and_respects_both_limits(cx: &mut TestAppContext) {
882        let (cx, state, _) = harness(cx);
883        cx.update(|window, cx| {
884            state.update(cx, |state, cx| {
885                let first = state.panels[0].bounds.size.width;
886                let second = state.panels[1].bounds.size.width;
887                state.sizes[0] = first - px(20.);
888                state.panels[0].size_range.start = first - px(30.);
889                state.panels[1].size_range.end = second + px(10.);
890                state.resize_panel_at_handle(0, first - px(50.), window, cx);
891                assert_eq!(state.sizes.as_slice(), &[first - px(10.), second + px(10.)]);
892
893                state.panels[1].size_range.end = second + px(60.);
894                state.resize_panel_at_handle(0, first - px(50.), window, cx);
895                assert_eq!(state.sizes.as_slice(), &[first - px(30.), second + px(30.)]);
896            });
897        });
898    }
899
900    #[gpui::test]
901    fn hiding_a_panel_preserves_its_slot_and_preferred_size(cx: &mut TestAppContext) {
902        let state = cx.update(|cx| cx.new(|_| ResizableState::default()));
903        cx.update(|cx| {
904            state.update(cx, |state, cx| {
905                state.bounds.size = size(px(600.), px(100.));
906                state.sync_panels_count(Axis::Horizontal, 3, cx);
907                state.adopt_sizes(&[Some(px(200.)); 3], cx);
908
909                state.sync_panel_visibility([true, false, true].into_iter(), cx);
910                assert_eq!(state.sizes.as_slice(), &[px(200.), px(0.), px(200.)]);
911                assert_eq!(state.next_visible_panel(0), Some(2));
912                assert_eq!(state.previous_visible_panel(2), Some(0));
913
914                state.insert_panel(Some(px(100.)), None, cx);
915                state.sync_panel_visibility([true; 4].into_iter(), cx);
916                assert_eq!(state.sizes[1], px(200.));
917                assert_eq!(state.next_visible_panel(0), Some(1));
918            });
919        });
920    }
921
922    #[gpui::test]
923    fn dragging_the_handle_resizes_and_emits_once(cx: &mut TestAppContext) {
924        let (cx, state, resizes) = harness(cx);
925        let boundary = cx.debug_bounds("second-panel").unwrap().left();
926        assert!(!state.read_with(cx, |state, _| state.is_resizing()));
927
928        cx.simulate_mouse_down(
929            point(boundary - px(2.), px(50.)),
930            MouseButton::Left,
931            Modifiers::default(),
932        );
933        cx.simulate_mouse_move(
934            point(boundary + px(10.), px(50.)),
935            Some(MouseButton::Left),
936            Modifiers::default(),
937        );
938        cx.simulate_mouse_move(
939            point(px(220.), px(50.)),
940            Some(MouseButton::Left),
941            Modifiers::default(),
942        );
943        assert!(state.read_with(cx, |state, _| state.is_resizing()));
944        cx.simulate_mouse_up(
945            point(px(220.), px(50.)),
946            MouseButton::Left,
947            Modifiers::default(),
948        );
949
950        state.read_with(cx, |state, _| {
951            assert_eq!(state.sizes(), &vec![px(220.), px(180.)]);
952            assert!(!state.is_resizing());
953        });
954        assert_eq!(resizes.get(), 1);
955    }
956
957    #[gpui::test]
958    fn dragging_before_the_next_paint_resizes_and_emits_once(cx: &mut TestAppContext) {
959        let (cx, state, resizes) = harness(cx);
960        let boundary = cx.debug_bounds("second-panel").unwrap().left();
961
962        // Dispatch the whole gesture in one update. The simulation helpers
963        // allow a paint between events and hide stale listener state.
964        cx.update(|window, cx| {
965            window.dispatch_event(
966                gpui::MouseDownEvent {
967                    position: point(boundary - px(2.), px(50.)),
968                    button: MouseButton::Left,
969                    click_count: 1,
970                    ..Default::default()
971                }
972                .to_platform_input(),
973                cx,
974            );
975            for x in [boundary + px(10.), px(220.)] {
976                window.dispatch_event(
977                    gpui::MouseMoveEvent {
978                        position: point(x, px(50.)),
979                        pressed_button: Some(MouseButton::Left),
980                        ..Default::default()
981                    }
982                    .to_platform_input(),
983                    cx,
984                );
985            }
986            assert_eq!(state.read(cx).resizing_panel_ix, Some(0));
987            assert_eq!(state.read(cx).sizes(), &vec![px(220.), px(180.)]);
988            assert_eq!(resizes.get(), 0);
989
990            // Repeated release and subsequent movement must not reuse the
991            // active index from the gesture that just finished.
992            for _ in 0..2 {
993                window.dispatch_event(
994                    gpui::MouseUpEvent {
995                        position: point(px(220.), px(50.)),
996                        button: MouseButton::Left,
997                        click_count: 1,
998                        ..Default::default()
999                    }
1000                    .to_platform_input(),
1001                    cx,
1002                );
1003            }
1004            window.dispatch_event(
1005                gpui::MouseMoveEvent {
1006                    position: point(px(260.), px(50.)),
1007                    ..Default::default()
1008                }
1009                .to_platform_input(),
1010                cx,
1011            );
1012            assert_eq!(state.read(cx).resizing_panel_ix, None);
1013            assert_eq!(state.read(cx).sizes(), &vec![px(220.), px(180.)]);
1014            assert_eq!(resizes.get(), 1);
1015        });
1016    }
1017
1018    #[gpui::test]
1019    fn cancelled_drag_does_not_reuse_the_painted_index(cx: &mut TestAppContext) {
1020        let (cx, state, resizes) = harness(cx);
1021        let boundary = cx.debug_bounds("second-panel").unwrap().left();
1022        cx.simulate_mouse_down(
1023            point(boundary - px(2.), px(50.)),
1024            MouseButton::Left,
1025            Modifiers::default(),
1026        );
1027        cx.simulate_mouse_move(
1028            point(boundary + px(10.), px(50.)),
1029            Some(MouseButton::Left),
1030            Modifiers::default(),
1031        );
1032        cx.update(|window, cx| {
1033            assert_eq!(state.read(cx).resizing_panel_ix, Some(0));
1034            window.draw(cx).clear(cx);
1035            state.update(cx, |state, cx| state.resize_panel(0, px(210.), window, cx));
1036            cx.stop_active_drag(window);
1037            assert_eq!(state.read(cx).resizing_panel_ix, None);
1038
1039            // Cancel after painting the active index, then deliver queued
1040            // events without replacing that frame's listeners.
1041            window.dispatch_event(
1042                gpui::MouseMoveEvent {
1043                    position: point(px(260.), px(50.)),
1044                    pressed_button: Some(MouseButton::Left),
1045                    ..Default::default()
1046                }
1047                .to_platform_input(),
1048                cx,
1049            );
1050            window.dispatch_event(
1051                gpui::MouseUpEvent {
1052                    position: point(px(260.), px(50.)),
1053                    button: MouseButton::Left,
1054                    click_count: 1,
1055                    ..Default::default()
1056                }
1057                .to_platform_input(),
1058                cx,
1059            );
1060            assert_eq!(state.read(cx).sizes(), &vec![px(210.), px(190.)]);
1061            assert_eq!(state.read(cx).resizing_panel_ix, None);
1062            assert_eq!(resizes.get(), 0);
1063        });
1064    }
1065
1066    #[gpui::test]
1067    fn clearing_mid_drag_stops_resizing(cx: &mut TestAppContext) {
1068        let (cx, state, _) = harness(cx);
1069        let boundary = cx.debug_bounds("second-panel").unwrap().left();
1070        cx.simulate_mouse_down(
1071            point(boundary - px(2.), px(50.)),
1072            MouseButton::Left,
1073            Modifiers::default(),
1074        );
1075        cx.simulate_mouse_move(
1076            point(boundary + px(10.), px(50.)),
1077            Some(MouseButton::Left),
1078            Modifiers::default(),
1079        );
1080        assert!(state.read_with(cx, |state, _| state.is_resizing()));
1081
1082        state.update(cx, |state, _| state.clear());
1083        assert!(!state.read_with(cx, |state, _| state.is_resizing()));
1084    }
1085
1086    #[gpui::test]
1087    fn stopping_the_drag_ends_resizing(cx: &mut TestAppContext) {
1088        let (cx, state, resizes) = harness(cx);
1089        let boundary = cx.debug_bounds("second-panel").unwrap().left();
1090        cx.simulate_mouse_down(
1091            point(boundary - px(2.), px(50.)),
1092            MouseButton::Left,
1093            Modifiers::default(),
1094        );
1095        cx.simulate_mouse_move(
1096            point(px(220.), px(50.)),
1097            Some(MouseButton::Left),
1098            Modifiers::default(),
1099        );
1100        assert!(state.read_with(cx, |state, _| state.is_resizing()));
1101
1102        // No mouse up follows a cancelled drag.
1103        cx.update(|window, cx| {
1104            cx.stop_active_drag(window);
1105            window.draw(cx).clear(cx);
1106        });
1107        let sizes = state.read_with(cx, |state, _| {
1108            assert!(!state.is_resizing());
1109            state.sizes().clone()
1110        });
1111        assert_eq!(resizes.get(), 1);
1112
1113        // Moving the mouse afterwards no longer resizes.
1114        cx.simulate_mouse_move(
1115            point(px(260.), px(50.)),
1116            Some(MouseButton::Left),
1117            Modifiers::default(),
1118        );
1119        assert_eq!(state.read_with(cx, |state, _| state.sizes().clone()), sizes);
1120        assert_eq!(resizes.get(), 1);
1121    }
1122
1123    /// Reports every state its divider is rendered in, so a drag can be watched
1124    /// from outside the handle.
1125    ///
1126    /// `covered` lays an occluding overlay over the whole group after it, the
1127    /// way a sheet's backdrop or a toast would sit over a dock.
1128    struct HandleStateHarness {
1129        seen: Rc<RefCell<Vec<ResizeHandleState>>>,
1130        covered: bool,
1131    }
1132
1133    impl Render for HandleStateHarness {
1134        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1135            let seen = self.seen.clone();
1136            div()
1137                .relative()
1138                .w(px(400.))
1139                .h(px(100.))
1140                .child(
1141                    h_resizable("handle-state")
1142                        .with_handle_appearance(Rc::new(
1143                            move |handle: &ResizeHandleContext, _: &mut Window, _: &mut App| {
1144                                let mut seen = seen.borrow_mut();
1145                                if seen.last() != Some(&handle.state()) {
1146                                    seen.push(handle.state());
1147                                }
1148                                // Nothing painted: this renderer is here to watch.
1149                                None
1150                            },
1151                        ))
1152                        .child(resizable_panel().size(px(150.)).child(div().size_full()))
1153                        .child(
1154                            resizable_panel()
1155                                .size(px(250.))
1156                                .child(div().size_full().debug_selector(|| "hs-second".into())),
1157                        ),
1158                )
1159                .when(self.covered, |this| {
1160                    this.child(div().absolute().inset_0().occlude())
1161                })
1162        }
1163    }
1164
1165    /// A handle under something else does not answer the pointer.
1166    ///
1167    /// The listeners used to test the pointer against the handle's bounds,
1168    /// which read true through anything painted over it: a divider under a
1169    /// sheet's backdrop lit up as the pointer crossed where it lay, and a
1170    /// press there counted as a press on the handle. They ask the hitbox now,
1171    /// and an occluding element in front of it answers for it.
1172    #[gpui::test]
1173    fn a_covered_handle_stays_idle(cx: &mut TestAppContext) {
1174        let seen: Rc<RefCell<Vec<ResizeHandleState>>> = Rc::new(RefCell::new(Vec::new()));
1175        let (_, cx) = cx.add_window_view({
1176            let seen = seen.clone();
1177            move |_, _| HandleStateHarness {
1178                seen,
1179                covered: true,
1180            }
1181        });
1182        cx.update(|window, cx| window.draw(cx).clear(cx));
1183        cx.update(|window, cx| window.draw(cx).clear(cx));
1184
1185        let boundary = cx.debug_bounds("hs-second").unwrap().left();
1186        let on_handle = point(boundary - px(2.), px(50.));
1187        let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
1188
1189        cx.simulate_mouse_move(on_handle, None, Modifiers::default());
1190        draw(cx);
1191        cx.simulate_mouse_down(on_handle, MouseButton::Left, Modifiers::default());
1192        draw(cx);
1193        cx.simulate_mouse_up(on_handle, MouseButton::Left, Modifiers::default());
1194        draw(cx);
1195
1196        assert_eq!(*seen.borrow(), vec![ResizeHandleState::Idle]);
1197    }
1198
1199    #[gpui::test]
1200    fn a_handle_reports_the_press_and_the_drag_to_its_renderer(cx: &mut TestAppContext) {
1201        let seen: Rc<RefCell<Vec<ResizeHandleState>>> = Rc::new(RefCell::new(Vec::new()));
1202        let (_, cx) = cx.add_window_view({
1203            let seen = seen.clone();
1204            move |_, _| HandleStateHarness {
1205                seen,
1206                covered: false,
1207            }
1208        });
1209        cx.update(|window, cx| window.draw(cx).clear(cx));
1210        cx.update(|window, cx| window.draw(cx).clear(cx));
1211
1212        let boundary = cx.debug_bounds("hs-second").unwrap().left();
1213        let on_handle = point(boundary - px(2.), px(50.));
1214        let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
1215
1216        cx.simulate_mouse_move(on_handle, None, Modifiers::default());
1217        draw(cx);
1218        cx.simulate_mouse_down(on_handle, MouseButton::Left, Modifiers::default());
1219        draw(cx);
1220        cx.simulate_mouse_move(
1221            point(px(260.), px(50.)),
1222            Some(MouseButton::Left),
1223            Modifiers::default(),
1224        );
1225        draw(cx);
1226        cx.simulate_mouse_up(
1227            point(px(390.), px(90.)),
1228            MouseButton::Left,
1229            Modifiers::default(),
1230        );
1231        draw(cx);
1232
1233        // Every one of these frames used to render `Idle`: the listeners wrote
1234        // their progress into a copy of the handle's state, so no renderer ever
1235        // saw a press, and `is_active` never once read true.
1236        assert_eq!(
1237            *seen.borrow(),
1238            vec![
1239                ResizeHandleState::Idle,
1240                ResizeHandleState::Hovered,
1241                ResizeHandleState::Pressed,
1242                ResizeHandleState::Dragging,
1243                ResizeHandleState::Idle,
1244            ]
1245        );
1246    }
1247
1248    struct SizedGroupHarness;
1249
1250    impl Render for SizedGroupHarness {
1251        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1252            div()
1253                .w(px(400.))
1254                .h(px(100.))
1255                .child(
1256                    h_resizable("sized-resizable").size(px(40.)).child(
1257                        resizable_panel()
1258                            .child(div().size_full().debug_selector(|| "sized-panel".into())),
1259                    ),
1260                )
1261        }
1262    }
1263
1264    #[gpui::test]
1265    fn a_group_size_binds_the_cross_axis(cx: &mut TestAppContext) {
1266        let (_, cx) = cx.add_window_view(|_, _| SizedGroupHarness);
1267        cx.update(|window, cx| window.draw(cx).clear(cx));
1268        cx.update(|window, cx| window.draw(cx).clear(cx));
1269
1270        let panel = cx.debug_bounds("sized-panel").unwrap();
1271        assert_eq!(panel.size.width, px(400.));
1272        assert_eq!(panel.size.height, px(40.));
1273    }
1274}