Skip to main content

gpui_base/resizable/
resize_handle.rs

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