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
247impl<T: 'static, E: 'static + Render> Element for ResizeHandle<T, E> {
248 type RequestLayoutState = AnyElement;
249 /// The band's own hitbox, so the listeners in `paint` can ask whether the
250 /// pointer is really on the handle rather than merely within its bounds.
251 type PrepaintState = Hitbox;
252
253 fn id(&self) -> Option<ElementId> {
254 Some(self.id.clone())
255 }
256
257 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
258 None
259 }
260
261 fn request_layout(
262 &mut self,
263 id: Option<&GlobalElementId>,
264 _: Option<&gpui::InspectorElementId>,
265 window: &mut Window,
266 cx: &mut App,
267 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
268 let neg_offset = -HANDLE_PADDING;
269 let axis = self.axis;
270 let edge = self.edge;
271 // Sizes are border-box: the extent has to name the whole band, padding
272 // included, or the content box resolves to zero and the hairline
273 // overflows into the padding, landing wherever the padding happens to
274 // push it.
275 let hug_extent = HANDLE_SIZE + HANDLE_PADDING;
276 let straddle_extent = HANDLE_SIZE + HANDLE_PADDING * 2.;
277 // The caller's listeners are already on it; what base adds is where the
278 // band goes and what it holds.
279 let base = std::mem::replace(&mut self.base, div());
280 let drag = self.drag.take();
281
282 window.with_element_state(id.unwrap(), |state, window| {
283 let state: SharedHandleState = state.unwrap_or_default();
284
285 let bg_color = handle_color(&cx.theme(), state.get().is_active());
286
287 let mut el = base
288 .id(self.id.clone())
289 .test_support()
290 .occlude()
291 .absolute()
292 .flex_shrink_0()
293 .group("handle")
294 .when_some(drag, |this, (value, on_drag)| {
295 this.on_drag(value, move |value, position, window, cx| {
296 on_drag(value, &position, window, cx)
297 })
298 })
299 .map(|this| match (edge, axis) {
300 // Hugging an edge: the whole band is inside the container,
301 // padded on the inner side only, so the hairline is the
302 // container's outermost pixel -- the seam itself.
303 // FIXME: Improve this to let the scroll bar have px(HANDLE_PADDING)
304 (Some(HandleEdge::Trailing), Axis::Horizontal) => this
305 .cursor_col_resize()
306 .top_0()
307 .right_0()
308 .h_full()
309 .w(hug_extent)
310 .pl(HANDLE_PADDING),
311 (Some(HandleEdge::Leading), Axis::Horizontal) => this
312 .cursor_col_resize()
313 .top_0()
314 .left_0()
315 .h_full()
316 .w(hug_extent)
317 .pr(HANDLE_PADDING),
318 (Some(HandleEdge::Trailing), Axis::Vertical) => this
319 .cursor_row_resize()
320 .bottom_0()
321 .left_0()
322 .w_full()
323 .h(hug_extent)
324 .pt(HANDLE_PADDING),
325 (Some(HandleEdge::Leading), Axis::Vertical) => this
326 .cursor_row_resize()
327 .top_0()
328 .left_0()
329 .w_full()
330 .h(hug_extent)
331 .pb(HANDLE_PADDING),
332 // Straddling the boundary: half the band on either side.
333 (None, Axis::Horizontal) => this
334 .cursor_col_resize()
335 .top_0()
336 .left(neg_offset)
337 .h_full()
338 .w(straddle_extent)
339 .px(HANDLE_PADDING),
340 (None, Axis::Vertical) => this
341 .cursor_row_resize()
342 .top(neg_offset)
343 .left_0()
344 .w_full()
345 .h(straddle_extent)
346 .py(HANDLE_PADDING),
347 })
348 .child(
349 // A renderer that declines — or is absent — leaves the
350 // built-in line, so overriding one handle never obliges a
351 // caller to redraw them all. What it paints stays in tree
352 // order, under the container's own mask: a divider is
353 // part of the panel it edges, and anything the
354 // application floats over that panel has to cover it.
355 self.appearance
356 .as_ref()
357 .and_then(|appearance| {
358 appearance(
359 &ResizeHandleContext {
360 axis,
361 edge,
362 state: state.get(),
363 },
364 window,
365 cx,
366 )
367 })
368 .unwrap_or_else(|| {
369 div()
370 // The line fills the handle's content box
371 // exactly, so it has nothing to give: a
372 // shrinkable child collapses with it.
373 .flex_none()
374 .bg(bg_color)
375 .group_hover("handle", |this| this.bg(bg_color))
376 .when(axis.is_horizontal(), |this| this.h_full().w(HANDLE_SIZE))
377 .when(axis.is_vertical(), |this| this.w_full().h(HANDLE_SIZE))
378 .into_any_element()
379 }),
380 )
381 .into_any_element();
382
383 let layout_id = el.request_layout(window, cx);
384
385 ((layout_id, el), state)
386 })
387 }
388
389 fn prepaint(
390 &mut self,
391 _: Option<&GlobalElementId>,
392 _: Option<&gpui::InspectorElementId>,
393 bounds: gpui::Bounds<Pixels>,
394 request_layout: &mut Self::RequestLayoutState,
395 window: &mut Window,
396 cx: &mut App,
397 ) -> Self::PrepaintState {
398 request_layout.prepaint(window, cx);
399 // After the child, deliberately. The band's own div occludes, and a
400 // hit test stops at the first hitbox that does, so a hitbox inserted
401 // before it would sit underneath and never read as hovered. Inserted
402 // here it sits directly on top of the band and directly under whatever
403 // is painted after this handle -- a sheet's overlay, a toast -- which
404 // is exactly the ordering `is_hovered_at` should answer from.
405 window.insert_hitbox(bounds, HitboxBehavior::Normal)
406 }
407
408 fn paint(
409 &mut self,
410 id: Option<&GlobalElementId>,
411 _: Option<&gpui::InspectorElementId>,
412 _: gpui::Bounds<Pixels>,
413 request_layout: &mut Self::RequestLayoutState,
414 hitbox: &mut Self::PrepaintState,
415 window: &mut Window,
416 cx: &mut App,
417 ) {
418 request_layout.paint(window, cx);
419
420 // Hovered and pressed are answered by the hitbox, not by the bounds.
421 // Bounds containment reads true through anything painted over the
422 // handle, so a divider under a sheet lit up as the pointer crossed
423 // where it lay; the hitbox is occluded by that sheet and says no.
424 let hitbox = hitbox.clone();
425
426 window.with_element_state(id.unwrap(), |state: Option<SharedHandleState>, window| {
427 let state = state.unwrap_or_default();
428
429 window.on_mouse_event({
430 let state = state.clone();
431 let hitbox = hitbox.clone();
432 move |ev: &MouseDownEvent, phase, window, _| {
433 if phase.bubble()
434 && ev.button == MouseButton::Left
435 && hitbox.is_hovered_at(ev.position, window)
436 && state.set(ResizeHandleState::Pressed)
437 {
438 window.refresh();
439 }
440 }
441 });
442
443 window.on_mouse_event({
444 let state = state.clone();
445 let hitbox = hitbox.clone();
446 move |ev: &MouseMoveEvent, phase, window, cx| {
447 if phase.capture()
448 && ev.pressed_button != Some(MouseButton::Left)
449 && state.get().is_active()
450 {
451 state.set(ResizeHandleState::Idle);
452 cx.stop_active_drag(window);
453 window.refresh();
454 }
455 if !phase.bubble() {
456 return;
457 }
458
459 // A press that moves is a drag, and stays one until the
460 // button comes back up: by the second frame the pointer is
461 // outside this nine-pixel band, so where it is says nothing
462 // about whether the handle is still being dragged.
463 let next = match state.get() {
464 engaged if engaged.is_active() => ResizeHandleState::Dragging,
465 _ if hitbox.is_hovered_at(ev.position, window) => {
466 ResizeHandleState::Hovered
467 }
468 _ => ResizeHandleState::Idle,
469 };
470 if state.set(next) {
471 window.refresh();
472 }
473 }
474 });
475
476 window.on_mouse_event({
477 let state = state.clone();
478 move |_: &MouseExitEvent, phase, window, cx| {
479 if phase.capture() && state.get().is_active() {
480 state.set(ResizeHandleState::Idle);
481 cx.stop_active_drag(window);
482 window.refresh();
483 }
484 }
485 });
486
487 window.on_mouse_event({
488 let state = state.clone();
489 let hitbox = hitbox.clone();
490 move |ev: &MouseUpEvent, _, window, _| {
491 if !state.get().is_active() {
492 return;
493 }
494
495 // Releasing over the handle leaves it hovered. Going
496 // straight to idle there would drop the indicator for one
497 // frame and bring it back under a pointer that never left.
498 let next = if hitbox.is_hovered_at(ev.position, window) {
499 ResizeHandleState::Hovered
500 } else {
501 ResizeHandleState::Idle
502 };
503 if state.set(next) {
504 window.refresh();
505 }
506 }
507 });
508
509 ((), state)
510 });
511 }
512}
513
514/// What a resize handle paints, given the active theme.
515///
516/// Projected colors win; without them the handle resolves from the tokens that
517/// already mean these two states everywhere else -- `border` for a divider at
518/// rest, `ring` for the thing the pointer currently owns. Before this the
519/// unprojected answer was `Hsla::default()`, which is transparent, so a
520/// consumer with no styled façade had no divider at all.
521pub(crate) fn handle_color(theme: &crate::Theme, active: bool) -> gpui::Hsla {
522 if active {
523 theme
524 .resizable
525 .active_handle
526 .unwrap_or(theme.tokens.colors.ring)
527 } else {
528 theme.resizable.handle.unwrap_or(theme.tokens.colors.border)
529 }
530}
531
532#[cfg(test)]
533mod tests {
534 use std::{
535 cell::{Cell, RefCell},
536 rc::Rc,
537 };
538
539 use gpui::{
540 AnyElement, App, AppContext as _, Axis, Bounds, Context, DragMoveEvent, Empty,
541 InteractiveElement as _, IntoElement, Modifiers, MouseButton, MouseDownEvent, MouseUpEvent,
542 ParentElement as _, Pixels, Render, StatefulInteractiveElement as _, Styled as _,
543 TestAppContext, VisualTestContext, Window, deferred, div, hsla, point,
544 prelude::FluentBuilder as _, px,
545 };
546
547 use super::{
548 HandleEdge, ResizeHandleContext, ResizeHandleState, SharedHandleState, handle_color,
549 resize_handle,
550 };
551 use crate::{ElementExt as _, InteractiveElementExt as _, ResizableTheme, Theme};
552
553 /// What a hugging handle's renderer was told and drew, and where the
554 /// drawing landed in the frame: under which mask, and before or after a
555 /// popover the application deferred from a panel drawn ahead of the dock.
556 #[derive(Default)]
557 struct Probe {
558 edge: Cell<Option<Option<HandleEdge>>>,
559 line: Cell<Option<Bounds<Pixels>>>,
560 mask: Cell<Option<Bounds<Pixels>>>,
561 /// Ticked by every prepaint hook below, in the order the frame reaches
562 /// them.
563 prepaints: Cell<usize>,
564 line_prepainted: Cell<Option<usize>>,
565 popover_prepainted: Cell<Option<usize>>,
566 }
567
568 impl Probe {
569 fn tick(&self) -> usize {
570 let n = self.prepaints.get();
571 self.prepaints.set(n + 1);
572 n
573 }
574 }
575
576 /// A hairline filling the handle's content box, the way a styled divider
577 /// rests.
578 fn hairline(axis: Axis, probe: Rc<Probe>) -> AnyElement {
579 div()
580 .flex_none()
581 .map(|line| match axis {
582 Axis::Horizontal => line.w(px(1.)).h_full(),
583 Axis::Vertical => line.h(px(1.)).w_full(),
584 })
585 .on_prepaint(move |bounds, window, _| {
586 probe.line.set(Some(bounds));
587 probe.mask.set(Some(window.content_mask().bounds));
588 probe.line_prepainted.set(Some(probe.tick()));
589 })
590 .into_any_element()
591 }
592
593 /// A drag payload for a handle nobody drags in these tests.
594 struct NoDrag;
595
596 impl Render for NoDrag {
597 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
598 Empty
599 }
600 }
601
602 /// A dock-shaped box: 200px along the axis, clipped to itself the way
603 /// `dock_frame` is, sitting between two 100px neighbours so both of its
604 /// edges are seams. The handle hugs one of them.
605 ///
606 /// The first neighbour floats a popover across both seams, deferred at the
607 /// default priority the way an application's own `deferred(anchored())`
608 /// is -- a panel drawn before the dock, opening something over it.
609 struct HuggingHarness {
610 axis: Axis,
611 edge: HandleEdge,
612 probe: Rc<Probe>,
613 }
614
615 impl Render for HuggingHarness {
616 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
617 let axis = self.axis;
618 let probe = self.probe.clone();
619 let neighbour = || match axis {
620 Axis::Horizontal => div().w(px(100.)).h_full(),
621 Axis::Vertical => div().h(px(100.)).w_full(),
622 };
623 let popover = div()
624 .absolute()
625 .map(|popover| match axis {
626 Axis::Horizontal => popover.top_0().left(px(50.)).w(px(300.)).h_full(),
627 Axis::Vertical => popover.left_0().top(px(50.)).h(px(300.)).w_full(),
628 })
629 .on_prepaint({
630 let probe = probe.clone();
631 move |_, _, _| probe.popover_prepainted.set(Some(probe.tick()))
632 });
633 div()
634 .flex()
635 .map(|row| match axis {
636 Axis::Horizontal => row.flex_row().w(px(400.)).h(px(100.)),
637 Axis::Vertical => row.flex_col().h(px(400.)).w(px(100.)),
638 })
639 .child(neighbour().child(deferred(popover)))
640 .child(
641 div()
642 .relative()
643 .overflow_hidden()
644 .map(|dock| match axis {
645 Axis::Horizontal => dock.w(px(200.)).h_full(),
646 Axis::Vertical => dock.h(px(200.)).w_full(),
647 })
648 .child(
649 resize_handle::<(), NoDrag>("hugging", axis)
650 .inside(self.edge)
651 .with_appearance(Rc::new(
652 move |handle: &ResizeHandleContext,
653 _: &mut Window,
654 _: &mut App| {
655 probe.edge.set(Some(handle.edge()));
656 Some(hairline(handle.axis(), probe.clone()))
657 },
658 )),
659 ),
660 )
661 .child(neighbour())
662 }
663 }
664
665 fn draw_hugging(cx: &mut TestAppContext, axis: Axis, edge: HandleEdge) -> Rc<Probe> {
666 let probe = Rc::new(Probe::default());
667 let (_, cx) = cx.add_window_view({
668 let probe = probe.clone();
669 move |_, _| HuggingHarness { axis, edge, probe }
670 });
671 cx.update(|window, cx| window.draw(cx).clear(cx));
672 probe
673 }
674
675 /// The seam a hugging handle marks, along its axis.
676 ///
677 /// The dock spans 100..300 in the harness, so its leading seam is at 100
678 /// and its trailing one at 300.
679 fn seam(edge: HandleEdge) -> Pixels {
680 match edge {
681 HandleEdge::Leading => px(100.),
682 HandleEdge::Trailing => px(300.),
683 }
684 }
685
686 fn along(axis: Axis, bounds: Bounds<Pixels>) -> (Pixels, Pixels) {
687 match axis {
688 Axis::Horizontal => (bounds.left(), bounds.right()),
689 Axis::Vertical => (bounds.top(), bounds.bottom()),
690 }
691 }
692
693 /// A hugging handle's hairline is the container's outermost pixel.
694 ///
695 /// This is the regression. The line was set one pixel in from the
696 /// boundary, to make room for an indicator to overhang it, and along the
697 /// whole seam that pixel of the dock showed past the line on one side of
698 /// the area and opened a gap before it on the other.
699 #[gpui::test]
700 fn a_hugging_handle_draws_its_line_on_the_seam(cx: &mut TestAppContext) {
701 for axis in [Axis::Horizontal, Axis::Vertical] {
702 for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
703 let probe = draw_hugging(cx, axis, edge);
704 let line = probe.line.get().expect("the renderer was asked to draw");
705 let (start, end) = along(axis, line);
706 let expected = match edge {
707 HandleEdge::Leading => (seam(edge), seam(edge) + px(1.)),
708 HandleEdge::Trailing => (seam(edge) - px(1.), seam(edge)),
709 };
710 assert_eq!(
711 (start, end),
712 expected,
713 "{axis:?} {edge:?}: the hairline has to be the pixel against the seam"
714 );
715 }
716 }
717 }
718
719 /// A hugging handle's appearance is painted in tree order, under its
720 /// container's mask -- beneath whatever the application floats over the
721 /// panels around it.
722 ///
723 /// This is the regression. The appearance was deferred so that an
724 /// indicator centred on the hairline would keep the pixel overhanging the
725 /// container, and a deferred element paints after the whole tree at a
726 /// priority no lower than the default. A popover an application defers
727 /// from a panel drawn before the dock -- at that default priority, as
728 /// `deferred(anchored())` is -- was painted first, and the dock's divider
729 /// ran straight through it.
730 #[gpui::test]
731 fn a_hugging_handle_paints_beneath_a_popover_deferred_before_it(cx: &mut TestAppContext) {
732 for axis in [Axis::Horizontal, Axis::Vertical] {
733 for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
734 let probe = draw_hugging(cx, axis, edge);
735 let line = probe
736 .line_prepainted
737 .get()
738 .expect("the line was prepainted");
739 let popover = probe
740 .popover_prepainted
741 .get()
742 .expect("the popover was prepainted");
743 assert!(
744 line < popover,
745 "{axis:?} {edge:?}: the line (prepaint #{line}) has to go down before \
746 the popover (#{popover}), or it is painted over it"
747 );
748
749 // The dock spans 100..300 along the axis; a deferred line would
750 // have been prepainted under the window's mask instead.
751 let mask = probe.mask.get().expect("the line was prepainted");
752 assert_eq!(
753 along(axis, mask),
754 (px(100.), px(300.)),
755 "{axis:?} {edge:?}: the line is painted under its container's clip"
756 );
757 }
758 }
759 }
760
761 /// A renderer is told which edge the handle hugs, so it can keep what it
762 /// centres on the line clear of the container's clip itself.
763 #[gpui::test]
764 fn a_renderer_is_told_the_edge_a_handle_hugs(cx: &mut TestAppContext) {
765 for axis in [Axis::Horizontal, Axis::Vertical] {
766 for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
767 let probe = draw_hugging(cx, axis, edge);
768 assert_eq!(probe.edge.get(), Some(Some(edge)), "{axis:?} {edge:?}");
769 }
770 }
771 }
772
773 #[test]
774 fn a_listener_writes_its_progress_back_into_the_stored_state() {
775 let stored = SharedHandleState::default();
776 // What `paint` hands each mouse listener.
777 let listener = stored.clone();
778
779 assert!(listener.set(ResizeHandleState::Pressed));
780
781 // The regression this pins down: the state used to be a bare `Cell`,
782 // which clones by value, so a listener wrote into a copy that died
783 // with the event and the handle never left `Idle`.
784 assert_eq!(stored.get(), ResizeHandleState::Pressed);
785 assert!(stored.get().is_active());
786 }
787
788 #[test]
789 fn setting_the_state_it_already_has_asks_for_no_repaint() {
790 let state = SharedHandleState::default();
791
792 assert!(state.set(ResizeHandleState::Hovered));
793 assert!(!state.set(ResizeHandleState::Hovered));
794 }
795
796 #[test]
797 fn only_a_held_handle_is_active() {
798 assert!(!ResizeHandleState::Idle.is_active());
799 assert!(!ResizeHandleState::Hovered.is_active());
800 assert!(ResizeHandleState::Pressed.is_active());
801 assert!(ResizeHandleState::Dragging.is_active());
802 }
803
804 #[gpui::test]
805 fn an_unprojected_handle_resolves_from_the_theme_tokens(cx: &mut TestAppContext) {
806 cx.update(|cx| {
807 let border = hsla(0., 0., 0.5, 1.0);
808 let ring = hsla(0.6, 0.5, 0.5, 1.0);
809 let theme = Theme::global_mut(cx);
810 theme.tokens.colors.border = border;
811 theme.tokens.colors.ring = ring;
812 theme.resizable = ResizableTheme::default();
813
814 let theme = Theme::global(cx);
815 assert_eq!(handle_color(&theme, false), border);
816 assert_eq!(handle_color(&theme, true), ring);
817 // The point of the change: the default used to be transparent, so
818 // a divider with nothing projected onto it was not drawn at all.
819 assert_ne!(handle_color(&theme, false), gpui::Hsla::default());
820 });
821 }
822
823 #[gpui::test]
824 fn a_projected_handle_still_wins(cx: &mut TestAppContext) {
825 cx.update(|cx| {
826 let projected = hsla(0.3, 0.4, 0.5, 1.0);
827 let active = hsla(0.9, 0.4, 0.5, 1.0);
828 let theme = Theme::global_mut(cx);
829 theme.tokens.colors.border = hsla(0., 0., 0.5, 1.0);
830 theme.resizable = ResizableTheme {
831 handle: Some(projected),
832 active_handle: Some(active),
833 };
834
835 let theme = Theme::global(cx);
836 assert_eq!(handle_color(&theme, false), projected);
837 assert_eq!(handle_color(&theme, true), active);
838 });
839 }
840
841 /// The payload a caller drags a handle with.
842 #[derive(Clone)]
843 struct Resize;
844
845 impl Render for Resize {
846 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
847 Empty
848 }
849 }
850
851 /// What the listeners a caller put on a handle, and on its container, heard.
852 #[derive(Default)]
853 struct Heard {
854 container_hovered: Cell<Option<bool>>,
855 handle_hovered: Cell<Option<bool>>,
856 double_clicks: Cell<usize>,
857 drag_moves: RefCell<Vec<Pixels>>,
858 /// Every state the appearance was drawn in, repeats collapsed.
859 states: RefCell<Vec<ResizeHandleState>>,
860 }
861
862 /// A 200px container whose trailing edge a handle hugs, listened to the way
863 /// an application's own sidebar would be.
864 struct CallerHarness {
865 heard: Rc<Heard>,
866 }
867
868 impl Render for CallerHarness {
869 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
870 let heard = self.heard.clone();
871 div().w(px(400.)).h(px(100.)).child(
872 div()
873 .id("container")
874 .relative()
875 .w(px(200.))
876 .h_full()
877 .on_hover({
878 let heard = heard.clone();
879 move |hovered: &bool, _, _| heard.container_hovered.set(Some(*hovered))
880 })
881 .on_drag_move({
882 let heard = heard.clone();
883 move |event: &DragMoveEvent<Resize>, _, _| {
884 heard.drag_moves.borrow_mut().push(event.event.position.x)
885 }
886 })
887 .child(
888 resize_handle("edge", Axis::Horizontal)
889 .inside(HandleEdge::Trailing)
890 .with_appearance(Rc::new({
891 let heard = heard.clone();
892 move |handle: &ResizeHandleContext, _: &mut Window, _: &mut App| {
893 let mut states = heard.states.borrow_mut();
894 if states.last() != Some(&handle.state()) {
895 states.push(handle.state());
896 }
897 None
898 }
899 }))
900 .on_hover({
901 let heard = heard.clone();
902 move |hovered: &bool, _, _| heard.handle_hovered.set(Some(*hovered))
903 })
904 .on_double_click(move |_, _, _| {
905 heard.double_clicks.set(heard.double_clicks.get() + 1)
906 })
907 .on_drag(Resize, |drag, _, _, cx| cx.new(|_| drag.clone())),
908 ),
909 )
910 }
911 }
912
913 /// Listeners a caller attaches to a handle reach the band, and leave the
914 /// progression base reports to the appearance as it was.
915 #[gpui::test]
916 fn a_callers_listeners_reach_the_band(cx: &mut TestAppContext) {
917 let heard = Rc::new(Heard::default());
918 let (_, cx) = cx.add_window_view({
919 let heard = heard.clone();
920 move |_, _| CallerHarness { heard }
921 });
922 let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
923 let press = |cx: &mut VisualTestContext, click_count| {
924 cx.simulate_event(MouseDownEvent {
925 position: point(px(198.), px(50.)),
926 modifiers: Modifiers::default(),
927 button: MouseButton::Left,
928 click_count,
929 first_mouse: false,
930 });
931 };
932 let release = |cx: &mut VisualTestContext, x, click_count| {
933 cx.simulate_event(MouseUpEvent {
934 position: point(x, px(50.)),
935 modifiers: Modifiers::default(),
936 button: MouseButton::Left,
937 click_count,
938 });
939 };
940 draw(cx);
941
942 // The container spans 0..200, and the band hugs its last five pixels.
943 cx.simulate_mouse_move(point(px(100.), px(50.)), None, Modifiers::default());
944 draw(cx);
945 assert_eq!(heard.container_hovered.get(), Some(true));
946
947 cx.simulate_mouse_move(point(px(198.), px(50.)), None, Modifiers::default());
948 draw(cx);
949 assert_eq!(heard.handle_hovered.get(), Some(true));
950 // The band occludes, so its own container stops reading as hovered.
951 assert_eq!(heard.container_hovered.get(), Some(false));
952
953 for click_count in [1, 2] {
954 press(cx, click_count);
955 draw(cx);
956 release(cx, px(198.), click_count);
957 draw(cx);
958 }
959 assert_eq!(heard.double_clicks.get(), 1);
960
961 press(cx, 1);
962 draw(cx);
963 for x in [px(190.), px(120.)] {
964 cx.simulate_mouse_move(
965 point(x, px(50.)),
966 Some(MouseButton::Left),
967 Modifiers::default(),
968 );
969 draw(cx);
970 }
971 release(cx, px(120.), 1);
972 draw(cx);
973
974 // The drag carries `Resize` itself. When it carried an `Rc<Resize>`,
975 // the container's `on_drag_move::<Resize>` never heard a thing.
976 assert_eq!(heard.drag_moves.borrow().last(), Some(&px(120.)));
977 // A drag is no click, let alone a double one.
978 assert_eq!(heard.double_clicks.get(), 1);
979 assert_eq!(
980 *heard.states.borrow(),
981 vec![
982 ResizeHandleState::Idle,
983 ResizeHandleState::Hovered,
984 ResizeHandleState::Pressed,
985 ResizeHandleState::Hovered,
986 ResizeHandleState::Pressed,
987 ResizeHandleState::Hovered,
988 ResizeHandleState::Pressed,
989 ResizeHandleState::Dragging,
990 ResizeHandleState::Idle,
991 ]
992 );
993 }
994}