Skip to main content

gpui_base/resizable/
resize_handle.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AnyElement, App, Axis, Element, ElementId, Entity, GlobalElementId, Hitbox, HitboxBehavior,
5    InteractiveElement, IntoElement, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
6    ParentElement as _, Pixels, Point, Render, StatefulInteractiveElement, Styled as _, Window,
7    div, prelude::FluentBuilder as _, px,
8};
9
10use crate::{AxisExt as _, theme::ActiveTheme as _};
11
12pub(crate) const HANDLE_PADDING: Pixels = px(4.);
13pub(crate) const HANDLE_SIZE: Pixels = px(1.);
14
15/// Create a resize handle for a resizable panel.
16#[doc(hidden)]
17pub fn resize_handle<T: 'static, E: 'static + Render>(
18    id: impl Into<ElementId>,
19    axis: Axis,
20) -> ResizeHandle<T, E> {
21    ResizeHandle::new(id, axis)
22}
23
24/// Draws the visible part of a resize handle.
25///
26/// Returning `None` keeps the built-in line, so a renderer can override some
27/// handles and leave the rest alone.
28pub type ResizeHandleRenderer =
29    Rc<dyn Fn(&ResizeHandleContext, &mut Window, &mut App) -> Option<AnyElement>>;
30
31/// What a [`ResizeHandleRenderer`] is told about the handle it is drawing.
32///
33/// The hit area, the cursor and the drag itself stay with the handle; a
34/// renderer only supplies what is painted inside it.
35pub struct ResizeHandleContext {
36    axis: Axis,
37    edge: Option<HandleEdge>,
38    state: ResizeHandleState,
39}
40
41impl ResizeHandleContext {
42    /// The axis the handle resizes along: `Horizontal` for a vertical divider
43    /// between two side-by-side panels.
44    pub fn axis(&self) -> Axis {
45        self.axis
46    }
47
48    /// The edge of its container this handle hugs, or `None` for a handle
49    /// straddling the boundary it resizes.
50    ///
51    /// A hugging handle's line is the container's outermost pixel, so anything
52    /// a renderer centres on it crosses the boundary; see [`HandleEdge`] for
53    /// what the container does with that.
54    pub fn edge(&self) -> Option<HandleEdge> {
55        self.edge
56    }
57
58    /// Whether the pointer currently owns this handle.
59    pub fn is_active(&self) -> bool {
60        self.state.is_active()
61    }
62
63    /// How far the pointer has gone with this handle.
64    pub fn state(&self) -> ResizeHandleState {
65        self.state
66    }
67}
68
69/// How far the pointer has gone with a resize handle.
70///
71/// A drag takes the pointer out of the handle's own band within a pixel or
72/// two, so GPUI's hover reads false for most of a drag and cannot stand in for
73/// `Dragging`. Base tracks the progression instead, and a renderer reads it
74/// through [`ResizeHandleContext::state`].
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
76pub enum ResizeHandleState {
77    /// The pointer is somewhere else.
78    #[default]
79    Idle,
80    /// The pointer is over the handle's band.
81    Hovered,
82    /// The pointer went down on the handle and has not moved since.
83    Pressed,
84    /// The handle is being dragged.
85    Dragging,
86}
87
88impl ResizeHandleState {
89    /// Whether the pointer owns the handle -- pressed on it, or dragging it.
90    pub fn is_active(self) -> bool {
91        matches!(self, Self::Pressed | Self::Dragging)
92    }
93}
94
95/// Which edge of its own container a handle hugs.
96///
97/// A handle named no edge straddles the boundary it resizes, half its band on
98/// either side, which is what a divider between two panels of a group wants.
99/// A dock's own edge handle cannot: [`dock_frame`] clips to the dock's box, so
100/// the half hanging outside is cut away -- what it paints and what it
101/// hit-tests alike, which is why the outer half of a dock's grab band has
102/// never actually been grabbable. Naming the edge moves the whole band inside.
103///
104/// The hairline stays on the boundary itself: it is the container's outermost
105/// pixel, the one the neighbour's content butts up against. Moving it inward
106/// by even a pixel leaves that pixel of the container showing past the line
107/// on one side, or a gap before it on the other, along the whole seam. What a
108/// renderer paints on top of the line -- an indicator thicker than the line,
109/// centred on it -- overhangs the boundary, and the container's clip takes
110/// the outer half off it unless the renderer defers that part. Only that part:
111/// a deferred element paints after the whole tree, and no priority puts it
112/// beneath the application's own deferred content, so a deferred line would
113/// cut straight through a popover opened at the default priority from a panel
114/// drawn before this container. A renderer learns which edge it is drawing for
115/// from [`ResizeHandleContext::edge`].
116///
117/// [`dock_frame`]: crate::dock::dock_frame
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119pub enum HandleEdge {
120    /// Where the axis starts: the left edge of a horizontal handle's
121    /// container, the top edge of a vertical one's.
122    Leading,
123    /// Where the axis ends.
124    Trailing,
125}
126
127#[doc(hidden)]
128pub struct ResizeHandle<T: 'static, E: 'static + Render> {
129    id: ElementId,
130    axis: Axis,
131    drag_value: Option<Rc<T>>,
132    edge: Option<HandleEdge>,
133    on_drag: Option<Rc<dyn Fn(&Point<Pixels>, &mut Window, &mut App) -> Entity<E>>>,
134    appearance: Option<ResizeHandleRenderer>,
135}
136
137impl<T: 'static, E: 'static + Render> ResizeHandle<T, E> {
138    fn new(id: impl Into<ElementId>, axis: Axis) -> Self {
139        let id = id.into();
140        Self {
141            id: id.clone(),
142            on_drag: None,
143            drag_value: None,
144            edge: None,
145            appearance: None,
146            axis,
147        }
148    }
149
150    /// Hand the painted part of this handle to `appearance`.
151    pub fn with_appearance(mut self, appearance: ResizeHandleRenderer) -> Self {
152        self.appearance = Some(appearance);
153        self
154    }
155
156    pub fn on_drag(
157        mut self,
158        value: T,
159        f: impl Fn(Rc<T>, &Point<Pixels>, &mut Window, &mut App) -> Entity<E> + 'static,
160    ) -> Self {
161        let value = Rc::new(value);
162        self.drag_value = Some(value.clone());
163        self.on_drag = Some(Rc::new(move |p, window, cx| {
164            f(value.clone(), p, window, cx)
165        }));
166        self
167    }
168
169    /// Keep the whole handle inside its container, hugging `edge`, instead of
170    /// straddling the boundary it resizes.
171    pub fn inside(mut self, edge: HandleEdge) -> Self {
172        self.edge = Some(edge);
173        self
174    }
175}
176
177/// One handle's [`ResizeHandleState`], shared between the element and the
178/// mouse listeners it registers.
179///
180/// The `Rc` is load-bearing. `with_element_state` hands back a clone and a
181/// bare `Cell` clones by value, so a listener holding one wrote its progress
182/// into a copy that died with the event: the stored state never left `Idle`
183/// and `is_active` never once read true.
184#[derive(Default, Debug, Clone)]
185struct SharedHandleState {
186    state: Rc<Cell<ResizeHandleState>>,
187}
188
189impl SharedHandleState {
190    fn get(&self) -> ResizeHandleState {
191        self.state.get()
192    }
193
194    /// Reports whether the state actually changed, so a listener repaints the
195    /// window only when there is something new to paint.
196    fn set(&self, state: ResizeHandleState) -> bool {
197        let changed = self.state.get() != state;
198        self.state.set(state);
199        changed
200    }
201}
202
203impl<T: 'static, E: 'static + Render> IntoElement for ResizeHandle<T, E> {
204    type Element = ResizeHandle<T, E>;
205    fn into_element(self) -> Self::Element {
206        self
207    }
208}
209
210impl<T: 'static, E: 'static + Render> Element for ResizeHandle<T, E> {
211    type RequestLayoutState = AnyElement;
212    /// The band's own hitbox, so the listeners in `paint` can ask whether the
213    /// pointer is really on the handle rather than merely within its bounds.
214    type PrepaintState = Hitbox;
215
216    fn id(&self) -> Option<ElementId> {
217        Some(self.id.clone())
218    }
219
220    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
221        None
222    }
223
224    fn request_layout(
225        &mut self,
226        id: Option<&GlobalElementId>,
227        _: Option<&gpui::InspectorElementId>,
228        window: &mut Window,
229        cx: &mut App,
230    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
231        let neg_offset = -HANDLE_PADDING;
232        let axis = self.axis;
233        let edge = self.edge;
234        // Sizes are border-box: the extent has to name the whole band, padding
235        // included, or the content box resolves to zero and the hairline
236        // overflows into the padding, landing wherever the padding happens to
237        // push it.
238        let hug_extent = HANDLE_SIZE + HANDLE_PADDING;
239        let straddle_extent = HANDLE_SIZE + HANDLE_PADDING * 2.;
240
241        window.with_element_state(id.unwrap(), |state, window| {
242            let state: SharedHandleState = state.unwrap_or_default();
243
244            let bg_color = handle_color(&cx.theme(), state.get().is_active());
245
246            let mut el = div()
247                .id(self.id.clone())
248                .occlude()
249                .absolute()
250                .flex_shrink_0()
251                .group("handle")
252                .when_some(self.on_drag.clone(), |this, on_drag| {
253                    this.on_drag(
254                        self.drag_value.clone().unwrap(),
255                        move |_, position, window, cx| on_drag(&position, window, cx),
256                    )
257                })
258                .map(|this| match (edge, axis) {
259                    // Hugging an edge: the whole band is inside the container,
260                    // padded on the inner side only, so the hairline is the
261                    // container's outermost pixel -- the seam itself.
262                    // FIXME: Improve this to let the scroll bar have px(HANDLE_PADDING)
263                    (Some(HandleEdge::Trailing), Axis::Horizontal) => this
264                        .cursor_col_resize()
265                        .top_0()
266                        .right_0()
267                        .h_full()
268                        .w(hug_extent)
269                        .pl(HANDLE_PADDING),
270                    (Some(HandleEdge::Leading), Axis::Horizontal) => this
271                        .cursor_col_resize()
272                        .top_0()
273                        .left_0()
274                        .h_full()
275                        .w(hug_extent)
276                        .pr(HANDLE_PADDING),
277                    (Some(HandleEdge::Trailing), Axis::Vertical) => this
278                        .cursor_row_resize()
279                        .bottom_0()
280                        .left_0()
281                        .w_full()
282                        .h(hug_extent)
283                        .pt(HANDLE_PADDING),
284                    (Some(HandleEdge::Leading), Axis::Vertical) => this
285                        .cursor_row_resize()
286                        .top_0()
287                        .left_0()
288                        .w_full()
289                        .h(hug_extent)
290                        .pb(HANDLE_PADDING),
291                    // Straddling the boundary: half the band on either side.
292                    (None, Axis::Horizontal) => this
293                        .cursor_col_resize()
294                        .top_0()
295                        .left(neg_offset)
296                        .h_full()
297                        .w(straddle_extent)
298                        .px(HANDLE_PADDING),
299                    (None, Axis::Vertical) => this
300                        .cursor_row_resize()
301                        .top(neg_offset)
302                        .left_0()
303                        .w_full()
304                        .h(straddle_extent)
305                        .py(HANDLE_PADDING),
306                })
307                .child(
308                    // A renderer that declines — or is absent — leaves the
309                    // built-in line, so overriding one handle never obliges a
310                    // caller to redraw them all. What it paints stays in tree
311                    // order, under the container's own mask: a divider is
312                    // part of the panel it edges, and anything the
313                    // application floats over that panel has to cover it.
314                    self.appearance
315                        .as_ref()
316                        .and_then(|appearance| {
317                            appearance(
318                                &ResizeHandleContext {
319                                    axis,
320                                    edge,
321                                    state: state.get(),
322                                },
323                                window,
324                                cx,
325                            )
326                        })
327                        .unwrap_or_else(|| {
328                            div()
329                                // The line fills the handle's content box
330                                // exactly, so it has nothing to give: a
331                                // shrinkable child collapses with it.
332                                .flex_none()
333                                .bg(bg_color)
334                                .group_hover("handle", |this| this.bg(bg_color))
335                                .when(axis.is_horizontal(), |this| this.h_full().w(HANDLE_SIZE))
336                                .when(axis.is_vertical(), |this| this.w_full().h(HANDLE_SIZE))
337                                .into_any_element()
338                        }),
339                )
340                .into_any_element();
341
342            let layout_id = el.request_layout(window, cx);
343
344            ((layout_id, el), state)
345        })
346    }
347
348    fn prepaint(
349        &mut self,
350        _: Option<&GlobalElementId>,
351        _: Option<&gpui::InspectorElementId>,
352        bounds: gpui::Bounds<Pixels>,
353        request_layout: &mut Self::RequestLayoutState,
354        window: &mut Window,
355        cx: &mut App,
356    ) -> Self::PrepaintState {
357        request_layout.prepaint(window, cx);
358        // After the child, deliberately. The band's own div occludes, and a
359        // hit test stops at the first hitbox that does, so a hitbox inserted
360        // before it would sit underneath and never read as hovered. Inserted
361        // here it sits directly on top of the band and directly under whatever
362        // is painted after this handle -- a sheet's overlay, a toast -- which
363        // is exactly the ordering `is_hovered_at` should answer from.
364        window.insert_hitbox(bounds, HitboxBehavior::Normal)
365    }
366
367    fn paint(
368        &mut self,
369        id: Option<&GlobalElementId>,
370        _: Option<&gpui::InspectorElementId>,
371        _: gpui::Bounds<Pixels>,
372        request_layout: &mut Self::RequestLayoutState,
373        hitbox: &mut Self::PrepaintState,
374        window: &mut Window,
375        cx: &mut App,
376    ) {
377        request_layout.paint(window, cx);
378
379        // Hovered and pressed are answered by the hitbox, not by the bounds.
380        // Bounds containment reads true through anything painted over the
381        // handle, so a divider under a sheet lit up as the pointer crossed
382        // where it lay; the hitbox is occluded by that sheet and says no.
383        let hitbox = hitbox.clone();
384
385        window.with_element_state(id.unwrap(), |state: Option<SharedHandleState>, window| {
386            let state = state.unwrap_or_default();
387
388            window.on_mouse_event({
389                let state = state.clone();
390                let hitbox = hitbox.clone();
391                move |_ev: &MouseDownEvent, phase, window, _| {
392                    if phase.bubble()
393                        && hitbox.is_hovered(window)
394                        && state.set(ResizeHandleState::Pressed)
395                    {
396                        window.refresh();
397                    }
398                }
399            });
400
401            window.on_mouse_event({
402                let state = state.clone();
403                let hitbox = hitbox.clone();
404                move |_ev: &MouseMoveEvent, phase, window, _| {
405                    if !phase.bubble() {
406                        return;
407                    }
408
409                    // A press that moves is a drag, and stays one until the
410                    // button comes back up: by the second frame the pointer is
411                    // outside this nine-pixel band, so where it is says nothing
412                    // about whether the handle is still being dragged.
413                    let next = match state.get() {
414                        engaged if engaged.is_active() => ResizeHandleState::Dragging,
415                        _ if hitbox.is_hovered(window) => ResizeHandleState::Hovered,
416                        _ => ResizeHandleState::Idle,
417                    };
418                    if state.set(next) {
419                        window.refresh();
420                    }
421                }
422            });
423
424            window.on_mouse_event({
425                let state = state.clone();
426                let hitbox = hitbox.clone();
427                move |_ev: &MouseUpEvent, _, window, _| {
428                    if !state.get().is_active() {
429                        return;
430                    }
431
432                    // Releasing over the handle leaves it hovered. Going
433                    // straight to idle there would drop the indicator for one
434                    // frame and bring it back under a pointer that never left.
435                    let next = if hitbox.is_hovered(window) {
436                        ResizeHandleState::Hovered
437                    } else {
438                        ResizeHandleState::Idle
439                    };
440                    if state.set(next) {
441                        window.refresh();
442                    }
443                }
444            });
445
446            ((), state)
447        });
448    }
449}
450
451/// What a resize handle paints, given the active theme.
452///
453/// Projected colors win; without them the handle resolves from the tokens that
454/// already mean these two states everywhere else -- `border` for a divider at
455/// rest, `ring` for the thing the pointer currently owns. Before this the
456/// unprojected answer was `Hsla::default()`, which is transparent, so a
457/// consumer with no styled façade had no divider at all.
458pub(crate) fn handle_color(theme: &crate::Theme, active: bool) -> gpui::Hsla {
459    if active {
460        theme
461            .resizable
462            .active_handle
463            .unwrap_or(theme.tokens.colors.ring)
464    } else {
465        theme.resizable.handle.unwrap_or(theme.tokens.colors.border)
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use std::{cell::Cell, rc::Rc};
472
473    use gpui::{
474        AnyElement, App, Axis, Bounds, Context, Empty, IntoElement, ParentElement as _, Pixels,
475        Render, Styled as _, TestAppContext, Window, deferred, div, hsla,
476        prelude::FluentBuilder as _, px,
477    };
478
479    use super::{
480        HandleEdge, ResizeHandleContext, ResizeHandleState, SharedHandleState, handle_color,
481        resize_handle,
482    };
483    use crate::{ElementExt as _, ResizableTheme, Theme};
484
485    /// What a hugging handle's renderer was told and drew, and where the
486    /// drawing landed in the frame: under which mask, and before or after a
487    /// popover the application deferred from a panel drawn ahead of the dock.
488    #[derive(Default)]
489    struct Probe {
490        edge: Cell<Option<Option<HandleEdge>>>,
491        line: Cell<Option<Bounds<Pixels>>>,
492        mask: Cell<Option<Bounds<Pixels>>>,
493        /// Ticked by every prepaint hook below, in the order the frame reaches
494        /// them.
495        prepaints: Cell<usize>,
496        line_prepainted: Cell<Option<usize>>,
497        popover_prepainted: Cell<Option<usize>>,
498    }
499
500    impl Probe {
501        fn tick(&self) -> usize {
502            let n = self.prepaints.get();
503            self.prepaints.set(n + 1);
504            n
505        }
506    }
507
508    /// A hairline filling the handle's content box, the way a styled divider
509    /// rests.
510    fn hairline(axis: Axis, probe: Rc<Probe>) -> AnyElement {
511        div()
512            .flex_none()
513            .map(|line| match axis {
514                Axis::Horizontal => line.w(px(1.)).h_full(),
515                Axis::Vertical => line.h(px(1.)).w_full(),
516            })
517            .on_prepaint(move |bounds, window, _| {
518                probe.line.set(Some(bounds));
519                probe.mask.set(Some(window.content_mask().bounds));
520                probe.line_prepainted.set(Some(probe.tick()));
521            })
522            .into_any_element()
523    }
524
525    /// A drag payload for a handle nobody drags in these tests.
526    struct NoDrag;
527
528    impl Render for NoDrag {
529        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
530            Empty
531        }
532    }
533
534    /// A dock-shaped box: 200px along the axis, clipped to itself the way
535    /// `dock_frame` is, sitting between two 100px neighbours so both of its
536    /// edges are seams. The handle hugs one of them.
537    ///
538    /// The first neighbour floats a popover across both seams, deferred at the
539    /// default priority the way an application's own `deferred(anchored())`
540    /// is -- a panel drawn before the dock, opening something over it.
541    struct HuggingHarness {
542        axis: Axis,
543        edge: HandleEdge,
544        probe: Rc<Probe>,
545    }
546
547    impl Render for HuggingHarness {
548        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
549            let axis = self.axis;
550            let probe = self.probe.clone();
551            let neighbour = || match axis {
552                Axis::Horizontal => div().w(px(100.)).h_full(),
553                Axis::Vertical => div().h(px(100.)).w_full(),
554            };
555            let popover = div()
556                .absolute()
557                .map(|popover| match axis {
558                    Axis::Horizontal => popover.top_0().left(px(50.)).w(px(300.)).h_full(),
559                    Axis::Vertical => popover.left_0().top(px(50.)).h(px(300.)).w_full(),
560                })
561                .on_prepaint({
562                    let probe = probe.clone();
563                    move |_, _, _| probe.popover_prepainted.set(Some(probe.tick()))
564                });
565            div()
566                .flex()
567                .map(|row| match axis {
568                    Axis::Horizontal => row.flex_row().w(px(400.)).h(px(100.)),
569                    Axis::Vertical => row.flex_col().h(px(400.)).w(px(100.)),
570                })
571                .child(neighbour().child(deferred(popover)))
572                .child(
573                    div()
574                        .relative()
575                        .overflow_hidden()
576                        .map(|dock| match axis {
577                            Axis::Horizontal => dock.w(px(200.)).h_full(),
578                            Axis::Vertical => dock.h(px(200.)).w_full(),
579                        })
580                        .child(
581                            resize_handle::<(), NoDrag>("hugging", axis)
582                                .inside(self.edge)
583                                .with_appearance(Rc::new(
584                                    move |handle: &ResizeHandleContext,
585                                          _: &mut Window,
586                                          _: &mut App| {
587                                        probe.edge.set(Some(handle.edge()));
588                                        Some(hairline(handle.axis(), probe.clone()))
589                                    },
590                                )),
591                        ),
592                )
593                .child(neighbour())
594        }
595    }
596
597    fn draw_hugging(cx: &mut TestAppContext, axis: Axis, edge: HandleEdge) -> Rc<Probe> {
598        let probe = Rc::new(Probe::default());
599        let (_, cx) = cx.add_window_view({
600            let probe = probe.clone();
601            move |_, _| HuggingHarness { axis, edge, probe }
602        });
603        cx.update(|window, cx| window.draw(cx).clear(cx));
604        probe
605    }
606
607    /// The seam a hugging handle marks, along its axis.
608    ///
609    /// The dock spans 100..300 in the harness, so its leading seam is at 100
610    /// and its trailing one at 300.
611    fn seam(edge: HandleEdge) -> Pixels {
612        match edge {
613            HandleEdge::Leading => px(100.),
614            HandleEdge::Trailing => px(300.),
615        }
616    }
617
618    fn along(axis: Axis, bounds: Bounds<Pixels>) -> (Pixels, Pixels) {
619        match axis {
620            Axis::Horizontal => (bounds.left(), bounds.right()),
621            Axis::Vertical => (bounds.top(), bounds.bottom()),
622        }
623    }
624
625    /// A hugging handle's hairline is the container's outermost pixel.
626    ///
627    /// This is the regression. The line was set one pixel in from the
628    /// boundary, to make room for an indicator to overhang it, and along the
629    /// whole seam that pixel of the dock showed past the line on one side of
630    /// the area and opened a gap before it on the other.
631    #[gpui::test]
632    fn a_hugging_handle_draws_its_line_on_the_seam(cx: &mut TestAppContext) {
633        for axis in [Axis::Horizontal, Axis::Vertical] {
634            for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
635                let probe = draw_hugging(cx, axis, edge);
636                let line = probe.line.get().expect("the renderer was asked to draw");
637                let (start, end) = along(axis, line);
638                let expected = match edge {
639                    HandleEdge::Leading => (seam(edge), seam(edge) + px(1.)),
640                    HandleEdge::Trailing => (seam(edge) - px(1.), seam(edge)),
641                };
642                assert_eq!(
643                    (start, end),
644                    expected,
645                    "{axis:?} {edge:?}: the hairline has to be the pixel against the seam"
646                );
647            }
648        }
649    }
650
651    /// A hugging handle's appearance is painted in tree order, under its
652    /// container's mask -- beneath whatever the application floats over the
653    /// panels around it.
654    ///
655    /// This is the regression. The appearance was deferred so that an
656    /// indicator centred on the hairline would keep the pixel overhanging the
657    /// container, and a deferred element paints after the whole tree at a
658    /// priority no lower than the default. A popover an application defers
659    /// from a panel drawn before the dock -- at that default priority, as
660    /// `deferred(anchored())` is -- was painted first, and the dock's divider
661    /// ran straight through it.
662    #[gpui::test]
663    fn a_hugging_handle_paints_beneath_a_popover_deferred_before_it(cx: &mut TestAppContext) {
664        for axis in [Axis::Horizontal, Axis::Vertical] {
665            for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
666                let probe = draw_hugging(cx, axis, edge);
667                let line = probe
668                    .line_prepainted
669                    .get()
670                    .expect("the line was prepainted");
671                let popover = probe
672                    .popover_prepainted
673                    .get()
674                    .expect("the popover was prepainted");
675                assert!(
676                    line < popover,
677                    "{axis:?} {edge:?}: the line (prepaint #{line}) has to go down before \
678                     the popover (#{popover}), or it is painted over it"
679                );
680
681                // The dock spans 100..300 along the axis; a deferred line would
682                // have been prepainted under the window's mask instead.
683                let mask = probe.mask.get().expect("the line was prepainted");
684                assert_eq!(
685                    along(axis, mask),
686                    (px(100.), px(300.)),
687                    "{axis:?} {edge:?}: the line is painted under its container's clip"
688                );
689            }
690        }
691    }
692
693    /// A renderer is told which edge the handle hugs, so it can keep what it
694    /// centres on the line clear of the container's clip itself.
695    #[gpui::test]
696    fn a_renderer_is_told_the_edge_a_handle_hugs(cx: &mut TestAppContext) {
697        for axis in [Axis::Horizontal, Axis::Vertical] {
698            for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
699                let probe = draw_hugging(cx, axis, edge);
700                assert_eq!(probe.edge.get(), Some(Some(edge)), "{axis:?} {edge:?}");
701            }
702        }
703    }
704
705    #[test]
706    fn a_listener_writes_its_progress_back_into_the_stored_state() {
707        let stored = SharedHandleState::default();
708        // What `paint` hands each mouse listener.
709        let listener = stored.clone();
710
711        assert!(listener.set(ResizeHandleState::Pressed));
712
713        // The regression this pins down: the state used to be a bare `Cell`,
714        // which clones by value, so a listener wrote into a copy that died
715        // with the event and the handle never left `Idle`.
716        assert_eq!(stored.get(), ResizeHandleState::Pressed);
717        assert!(stored.get().is_active());
718    }
719
720    #[test]
721    fn setting_the_state_it_already_has_asks_for_no_repaint() {
722        let state = SharedHandleState::default();
723
724        assert!(state.set(ResizeHandleState::Hovered));
725        assert!(!state.set(ResizeHandleState::Hovered));
726    }
727
728    #[test]
729    fn only_a_held_handle_is_active() {
730        assert!(!ResizeHandleState::Idle.is_active());
731        assert!(!ResizeHandleState::Hovered.is_active());
732        assert!(ResizeHandleState::Pressed.is_active());
733        assert!(ResizeHandleState::Dragging.is_active());
734    }
735
736    #[gpui::test]
737    fn an_unprojected_handle_resolves_from_the_theme_tokens(cx: &mut TestAppContext) {
738        cx.update(|cx| {
739            let border = hsla(0., 0., 0.5, 1.0);
740            let ring = hsla(0.6, 0.5, 0.5, 1.0);
741            let theme = Theme::global_mut(cx);
742            theme.tokens.colors.border = border;
743            theme.tokens.colors.ring = ring;
744            theme.resizable = ResizableTheme::default();
745
746            let theme = Theme::global(cx);
747            assert_eq!(handle_color(&theme, false), border);
748            assert_eq!(handle_color(&theme, true), ring);
749            // The point of the change: the default used to be transparent, so
750            // a divider with nothing projected onto it was not drawn at all.
751            assert_ne!(handle_color(&theme, false), gpui::Hsla::default());
752        });
753    }
754
755    #[gpui::test]
756    fn a_projected_handle_still_wins(cx: &mut TestAppContext) {
757        cx.update(|cx| {
758            let projected = hsla(0.3, 0.4, 0.5, 1.0);
759            let active = hsla(0.9, 0.4, 0.5, 1.0);
760            let theme = Theme::global_mut(cx);
761            theme.tokens.colors.border = hsla(0., 0., 0.5, 1.0);
762            theme.resizable = ResizableTheme {
763                handle: Some(projected),
764                active_handle: Some(active),
765            };
766
767            let theme = Theme::global(cx);
768            assert_eq!(handle_color(&theme, false), projected);
769            assert_eq!(handle_color(&theme, true), active);
770        });
771    }
772}