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
17pub 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
50pub type ResizeHandleRenderer =
55 Rc<dyn Fn(&ResizeHandleContext, &mut Window, &mut App) -> Option<AnyElement>>;
56
57pub struct ResizeHandleContext {
62 axis: Axis,
63 edge: Option<HandleEdge>,
64 state: ResizeHandleState,
65}
66
67impl ResizeHandleContext {
68 pub fn axis(&self) -> Axis {
71 self.axis
72 }
73
74 pub fn edge(&self) -> Option<HandleEdge> {
81 self.edge
82 }
83
84 pub fn is_active(&self) -> bool {
86 self.state.is_active()
87 }
88
89 pub fn state(&self) -> ResizeHandleState {
91 self.state
92 }
93}
94
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
102pub enum ResizeHandleState {
103 #[default]
105 Idle,
106 Hovered,
108 Pressed,
110 Dragging,
112}
113
114impl ResizeHandleState {
115 pub fn is_active(self) -> bool {
117 matches!(self, Self::Pressed | Self::Dragging)
118 }
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum HandleEdge {
146 Leading,
149 Trailing,
151}
152
153pub 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 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 pub fn with_appearance(mut self, appearance: ResizeHandleRenderer) -> Self {
182 self.appearance = Some(appearance);
183 self
184 }
185
186 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 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#[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 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 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 let hug_extent = HANDLE_SIZE + HANDLE_PADDING;
276 let straddle_extent = HANDLE_SIZE + HANDLE_PADDING * 2.;
277 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 (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 (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 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 .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 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 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({
432 let hitbox = hitbox.clone();
433 move |ev: &MouseDownEvent, phase, window, _| {
434 if phase.capture()
435 && ev.button == MouseButton::Left
436 && hitbox.is_hovered_at(ev.position, window)
437 {
438 window.prevent_default();
439 }
440 }
441 });
442
443 window.on_mouse_event({
444 let state = state.clone();
445 let hitbox = hitbox.clone();
446 move |ev: &MouseDownEvent, phase, window, _| {
447 if phase.bubble()
448 && ev.button == MouseButton::Left
449 && hitbox.is_hovered_at(ev.position, window)
450 && state.set(ResizeHandleState::Pressed)
451 {
452 window.refresh();
453 }
454 }
455 });
456
457 window.on_mouse_event({
458 let state = state.clone();
459 let hitbox = hitbox.clone();
460 move |ev: &MouseMoveEvent, phase, window, cx| {
461 if phase.capture()
462 && ev.pressed_button != Some(MouseButton::Left)
463 && state.get().is_active()
464 {
465 state.set(ResizeHandleState::Idle);
466 cx.stop_active_drag(window);
467 window.refresh();
468 }
469 if !phase.bubble() {
470 return;
471 }
472
473 let next = match state.get() {
478 engaged if engaged.is_active() => ResizeHandleState::Dragging,
479 _ if hitbox.is_hovered_at(ev.position, window) => {
480 ResizeHandleState::Hovered
481 }
482 _ => ResizeHandleState::Idle,
483 };
484 if state.set(next) {
485 window.refresh();
486 }
487 }
488 });
489
490 window.on_mouse_event({
491 let state = state.clone();
492 move |_: &MouseExitEvent, phase, window, cx| {
493 if phase.capture() && state.get().is_active() {
494 state.set(ResizeHandleState::Idle);
495 cx.stop_active_drag(window);
496 window.refresh();
497 }
498 }
499 });
500
501 window.on_mouse_event({
502 let state = state.clone();
503 let hitbox = hitbox.clone();
504 move |ev: &MouseUpEvent, _, window, _| {
505 if !state.get().is_active() {
506 return;
507 }
508
509 let next = if hitbox.is_hovered_at(ev.position, window) {
513 ResizeHandleState::Hovered
514 } else {
515 ResizeHandleState::Idle
516 };
517 if state.set(next) {
518 window.refresh();
519 }
520 }
521 });
522
523 ((), state)
524 });
525 }
526}
527
528pub(crate) fn handle_color(theme: &crate::Theme, active: bool) -> gpui::Hsla {
536 if active {
537 theme
538 .resizable
539 .active_handle
540 .unwrap_or(theme.tokens.colors.ring)
541 } else {
542 theme.resizable.handle.unwrap_or(theme.tokens.colors.border)
543 }
544}
545
546#[cfg(test)]
547mod tests {
548 use std::{
549 cell::{Cell, RefCell},
550 rc::Rc,
551 };
552
553 use gpui::{
554 AnyElement, App, AppContext as _, Axis, Bounds, Context, DragMoveEvent, Empty, FocusHandle,
555 InteractiveElement as _, IntoElement, Modifiers, MouseButton, MouseDownEvent, MouseUpEvent,
556 ParentElement as _, Pixels, Render, StatefulInteractiveElement as _, Styled as _,
557 TestAppContext, VisualTestContext, Window, deferred, div, hsla, point,
558 prelude::FluentBuilder as _, px,
559 };
560
561 use super::{
562 HandleEdge, ResizeHandleContext, ResizeHandleState, SharedHandleState, handle_color,
563 resize_handle,
564 };
565 use crate::{ElementExt as _, InteractiveElementExt as _, ResizableTheme, Theme};
566
567 #[derive(Default)]
571 struct Probe {
572 edge: Cell<Option<Option<HandleEdge>>>,
573 line: Cell<Option<Bounds<Pixels>>>,
574 mask: Cell<Option<Bounds<Pixels>>>,
575 prepaints: Cell<usize>,
578 line_prepainted: Cell<Option<usize>>,
579 popover_prepainted: Cell<Option<usize>>,
580 }
581
582 impl Probe {
583 fn tick(&self) -> usize {
584 let n = self.prepaints.get();
585 self.prepaints.set(n + 1);
586 n
587 }
588 }
589
590 fn hairline(axis: Axis, probe: Rc<Probe>) -> AnyElement {
593 div()
594 .flex_none()
595 .map(|line| match axis {
596 Axis::Horizontal => line.w(px(1.)).h_full(),
597 Axis::Vertical => line.h(px(1.)).w_full(),
598 })
599 .on_prepaint(move |bounds, window, _| {
600 probe.line.set(Some(bounds));
601 probe.mask.set(Some(window.content_mask().bounds));
602 probe.line_prepainted.set(Some(probe.tick()));
603 })
604 .into_any_element()
605 }
606
607 struct NoDrag;
609
610 impl Render for NoDrag {
611 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
612 Empty
613 }
614 }
615
616 struct HuggingHarness {
624 axis: Axis,
625 edge: HandleEdge,
626 probe: Rc<Probe>,
627 }
628
629 impl Render for HuggingHarness {
630 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
631 let axis = self.axis;
632 let probe = self.probe.clone();
633 let neighbour = || match axis {
634 Axis::Horizontal => div().w(px(100.)).h_full(),
635 Axis::Vertical => div().h(px(100.)).w_full(),
636 };
637 let popover = div()
638 .absolute()
639 .map(|popover| match axis {
640 Axis::Horizontal => popover.top_0().left(px(50.)).w(px(300.)).h_full(),
641 Axis::Vertical => popover.left_0().top(px(50.)).h(px(300.)).w_full(),
642 })
643 .on_prepaint({
644 let probe = probe.clone();
645 move |_, _, _| probe.popover_prepainted.set(Some(probe.tick()))
646 });
647 div()
648 .flex()
649 .map(|row| match axis {
650 Axis::Horizontal => row.flex_row().w(px(400.)).h(px(100.)),
651 Axis::Vertical => row.flex_col().h(px(400.)).w(px(100.)),
652 })
653 .child(neighbour().child(deferred(popover)))
654 .child(
655 div()
656 .relative()
657 .overflow_hidden()
658 .map(|dock| match axis {
659 Axis::Horizontal => dock.w(px(200.)).h_full(),
660 Axis::Vertical => dock.h(px(200.)).w_full(),
661 })
662 .child(
663 resize_handle::<(), NoDrag>("hugging", axis)
664 .inside(self.edge)
665 .with_appearance(Rc::new(
666 move |handle: &ResizeHandleContext,
667 _: &mut Window,
668 _: &mut App| {
669 probe.edge.set(Some(handle.edge()));
670 Some(hairline(handle.axis(), probe.clone()))
671 },
672 )),
673 ),
674 )
675 .child(neighbour())
676 }
677 }
678
679 fn draw_hugging(cx: &mut TestAppContext, axis: Axis, edge: HandleEdge) -> Rc<Probe> {
680 let probe = Rc::new(Probe::default());
681 let (_, cx) = cx.add_window_view({
682 let probe = probe.clone();
683 move |_, _| HuggingHarness { axis, edge, probe }
684 });
685 cx.update(|window, cx| window.draw(cx).clear(cx));
686 probe
687 }
688
689 fn seam(edge: HandleEdge) -> Pixels {
694 match edge {
695 HandleEdge::Leading => px(100.),
696 HandleEdge::Trailing => px(300.),
697 }
698 }
699
700 fn along(axis: Axis, bounds: Bounds<Pixels>) -> (Pixels, Pixels) {
701 match axis {
702 Axis::Horizontal => (bounds.left(), bounds.right()),
703 Axis::Vertical => (bounds.top(), bounds.bottom()),
704 }
705 }
706
707 #[gpui::test]
714 fn a_hugging_handle_draws_its_line_on_the_seam(cx: &mut TestAppContext) {
715 for axis in [Axis::Horizontal, Axis::Vertical] {
716 for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
717 let probe = draw_hugging(cx, axis, edge);
718 let line = probe.line.get().expect("the renderer was asked to draw");
719 let (start, end) = along(axis, line);
720 let expected = match edge {
721 HandleEdge::Leading => (seam(edge), seam(edge) + px(1.)),
722 HandleEdge::Trailing => (seam(edge) - px(1.), seam(edge)),
723 };
724 assert_eq!(
725 (start, end),
726 expected,
727 "{axis:?} {edge:?}: the hairline has to be the pixel against the seam"
728 );
729 }
730 }
731 }
732
733 #[gpui::test]
745 fn a_hugging_handle_paints_beneath_a_popover_deferred_before_it(cx: &mut TestAppContext) {
746 for axis in [Axis::Horizontal, Axis::Vertical] {
747 for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
748 let probe = draw_hugging(cx, axis, edge);
749 let line = probe
750 .line_prepainted
751 .get()
752 .expect("the line was prepainted");
753 let popover = probe
754 .popover_prepainted
755 .get()
756 .expect("the popover was prepainted");
757 assert!(
758 line < popover,
759 "{axis:?} {edge:?}: the line (prepaint #{line}) has to go down before \
760 the popover (#{popover}), or it is painted over it"
761 );
762
763 let mask = probe.mask.get().expect("the line was prepainted");
766 assert_eq!(
767 along(axis, mask),
768 (px(100.), px(300.)),
769 "{axis:?} {edge:?}: the line is painted under its container's clip"
770 );
771 }
772 }
773 }
774
775 #[gpui::test]
778 fn a_renderer_is_told_the_edge_a_handle_hugs(cx: &mut TestAppContext) {
779 for axis in [Axis::Horizontal, Axis::Vertical] {
780 for edge in [HandleEdge::Leading, HandleEdge::Trailing] {
781 let probe = draw_hugging(cx, axis, edge);
782 assert_eq!(probe.edge.get(), Some(Some(edge)), "{axis:?} {edge:?}");
783 }
784 }
785 }
786
787 #[test]
788 fn a_listener_writes_its_progress_back_into_the_stored_state() {
789 let stored = SharedHandleState::default();
790 let listener = stored.clone();
792
793 assert!(listener.set(ResizeHandleState::Pressed));
794
795 assert_eq!(stored.get(), ResizeHandleState::Pressed);
799 assert!(stored.get().is_active());
800 }
801
802 #[test]
803 fn setting_the_state_it_already_has_asks_for_no_repaint() {
804 let state = SharedHandleState::default();
805
806 assert!(state.set(ResizeHandleState::Hovered));
807 assert!(!state.set(ResizeHandleState::Hovered));
808 }
809
810 #[test]
811 fn only_a_held_handle_is_active() {
812 assert!(!ResizeHandleState::Idle.is_active());
813 assert!(!ResizeHandleState::Hovered.is_active());
814 assert!(ResizeHandleState::Pressed.is_active());
815 assert!(ResizeHandleState::Dragging.is_active());
816 }
817
818 #[gpui::test]
819 fn an_unprojected_handle_resolves_from_the_theme_tokens(cx: &mut TestAppContext) {
820 cx.update(|cx| {
821 let border = hsla(0., 0., 0.5, 1.0);
822 let ring = hsla(0.6, 0.5, 0.5, 1.0);
823 let theme = Theme::global_mut(cx);
824 theme.tokens.colors.border = border;
825 theme.tokens.colors.ring = ring;
826 theme.resizable = ResizableTheme::default();
827
828 let theme = Theme::global(cx);
829 assert_eq!(handle_color(&theme, false), border);
830 assert_eq!(handle_color(&theme, true), ring);
831 assert_ne!(handle_color(&theme, false), gpui::Hsla::default());
834 });
835 }
836
837 #[gpui::test]
838 fn a_projected_handle_still_wins(cx: &mut TestAppContext) {
839 cx.update(|cx| {
840 let projected = hsla(0.3, 0.4, 0.5, 1.0);
841 let active = hsla(0.9, 0.4, 0.5, 1.0);
842 let theme = Theme::global_mut(cx);
843 theme.tokens.colors.border = hsla(0., 0., 0.5, 1.0);
844 theme.resizable = ResizableTheme {
845 handle: Some(projected),
846 active_handle: Some(active),
847 };
848
849 let theme = Theme::global(cx);
850 assert_eq!(handle_color(&theme, false), projected);
851 assert_eq!(handle_color(&theme, true), active);
852 });
853 }
854
855 #[derive(Clone)]
857 struct Resize;
858
859 impl Render for Resize {
860 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
861 Empty
862 }
863 }
864
865 #[derive(Default)]
867 struct Heard {
868 container_hovered: Cell<Option<bool>>,
869 handle_hovered: Cell<Option<bool>>,
870 double_clicks: Cell<usize>,
871 drag_moves: RefCell<Vec<Pixels>>,
872 states: RefCell<Vec<ResizeHandleState>>,
874 }
875
876 struct CallerHarness {
879 heard: Rc<Heard>,
880 }
881
882 impl Render for CallerHarness {
883 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
884 let heard = self.heard.clone();
885 div().w(px(400.)).h(px(100.)).child(
886 div()
887 .id("container")
888 .relative()
889 .w(px(200.))
890 .h_full()
891 .on_hover({
892 let heard = heard.clone();
893 move |hovered: &bool, _, _| heard.container_hovered.set(Some(*hovered))
894 })
895 .on_drag_move({
896 let heard = heard.clone();
897 move |event: &DragMoveEvent<Resize>, _, _| {
898 heard.drag_moves.borrow_mut().push(event.event.position.x)
899 }
900 })
901 .child(
902 resize_handle("edge", Axis::Horizontal)
903 .inside(HandleEdge::Trailing)
904 .with_appearance(Rc::new({
905 let heard = heard.clone();
906 move |handle: &ResizeHandleContext, _: &mut Window, _: &mut App| {
907 let mut states = heard.states.borrow_mut();
908 if states.last() != Some(&handle.state()) {
909 states.push(handle.state());
910 }
911 None
912 }
913 }))
914 .on_hover({
915 let heard = heard.clone();
916 move |hovered: &bool, _, _| heard.handle_hovered.set(Some(*hovered))
917 })
918 .on_double_click(move |_, _, _| {
919 heard.double_clicks.set(heard.double_clicks.get() + 1)
920 })
921 .on_drag(Resize, |drag, _, _, cx| cx.new(|_| drag.clone())),
922 ),
923 )
924 }
925 }
926
927 #[gpui::test]
930 fn a_callers_listeners_reach_the_band(cx: &mut TestAppContext) {
931 let heard = Rc::new(Heard::default());
932 let (_, cx) = cx.add_window_view({
933 let heard = heard.clone();
934 move |_, _| CallerHarness { heard }
935 });
936 let draw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
937 let press = |cx: &mut VisualTestContext, click_count| {
938 cx.simulate_event(MouseDownEvent {
939 position: point(px(198.), px(50.)),
940 modifiers: Modifiers::default(),
941 button: MouseButton::Left,
942 click_count,
943 first_mouse: false,
944 });
945 };
946 let release = |cx: &mut VisualTestContext, x, click_count| {
947 cx.simulate_event(MouseUpEvent {
948 position: point(x, px(50.)),
949 modifiers: Modifiers::default(),
950 button: MouseButton::Left,
951 click_count,
952 });
953 };
954 draw(cx);
955
956 cx.simulate_mouse_move(point(px(100.), px(50.)), None, Modifiers::default());
958 draw(cx);
959 assert_eq!(heard.container_hovered.get(), Some(true));
960
961 cx.simulate_mouse_move(point(px(198.), px(50.)), None, Modifiers::default());
962 draw(cx);
963 assert_eq!(heard.handle_hovered.get(), Some(true));
964 assert_eq!(heard.container_hovered.get(), Some(false));
966
967 for click_count in [1, 2] {
968 press(cx, click_count);
969 draw(cx);
970 release(cx, px(198.), click_count);
971 draw(cx);
972 }
973 assert_eq!(heard.double_clicks.get(), 1);
974
975 press(cx, 1);
976 draw(cx);
977 for x in [px(190.), px(120.)] {
978 cx.simulate_mouse_move(
979 point(x, px(50.)),
980 Some(MouseButton::Left),
981 Modifiers::default(),
982 );
983 draw(cx);
984 }
985 release(cx, px(120.), 1);
986 draw(cx);
987
988 assert_eq!(heard.drag_moves.borrow().last(), Some(&px(120.)));
991 assert_eq!(heard.double_clicks.get(), 1);
993 assert_eq!(
994 *heard.states.borrow(),
995 vec![
996 ResizeHandleState::Idle,
997 ResizeHandleState::Hovered,
998 ResizeHandleState::Pressed,
999 ResizeHandleState::Hovered,
1000 ResizeHandleState::Pressed,
1001 ResizeHandleState::Hovered,
1002 ResizeHandleState::Pressed,
1003 ResizeHandleState::Dragging,
1004 ResizeHandleState::Idle,
1005 ]
1006 );
1007 }
1008
1009 struct FocusHarness {
1010 workbench_focus: FocusHandle,
1011 left_panel_focus: FocusHandle,
1012 right_panel_focus: FocusHandle,
1013 overlay_focus: FocusHandle,
1014 show_overlay: Rc<Cell<bool>>,
1015 }
1016
1017 impl Render for FocusHarness {
1018 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1019 let mut workbench = div()
1020 .id("focus-workbench")
1021 .relative()
1022 .size_full()
1023 .track_focus(&self.workbench_focus)
1024 .child(
1025 div()
1026 .id("focus-layout")
1027 .flex()
1028 .flex_row()
1029 .w(px(400.))
1030 .h(px(100.))
1031 .child(
1032 div()
1033 .id("left-panel")
1034 .debug_selector(|| "left-panel".into())
1035 .w(px(100.))
1036 .h_full()
1037 .track_focus(&self.left_panel_focus),
1038 )
1039 .child(
1040 div()
1041 .id("resize-dock")
1042 .debug_selector(|| "focus-resize-dock".into())
1043 .relative()
1044 .w(px(200.))
1045 .h_full()
1046 .child(
1047 resize_handle::<(), NoDrag>(
1048 "focus-resize-handle",
1049 Axis::Horizontal,
1050 )
1051 .inside(HandleEdge::Leading),
1052 ),
1053 )
1054 .child(
1055 div()
1056 .id("right-panel")
1057 .w(px(100.))
1058 .h_full()
1059 .track_focus(&self.right_panel_focus),
1060 ),
1061 );
1062
1063 if self.show_overlay.get() {
1064 workbench = workbench.child(
1065 div()
1066 .id("focus-overlay")
1067 .debug_selector(|| "focus-overlay".into())
1068 .occlude()
1069 .absolute()
1070 .top_0()
1071 .left(px(50.))
1072 .w(px(300.))
1073 .h(px(100.))
1074 .track_focus(&self.overlay_focus),
1075 );
1076 }
1077
1078 workbench
1079 }
1080 }
1081
1082 #[gpui::test]
1083 fn resize_handle_focus_guard_respects_top_hitbox_and_adjacent_controls(
1084 cx: &mut TestAppContext,
1085 ) {
1086 let (workbench_focus, left_panel_focus, right_panel_focus, overlay_focus) =
1087 cx.update(|cx| {
1088 (
1089 cx.focus_handle(),
1090 cx.focus_handle(),
1091 cx.focus_handle(),
1092 cx.focus_handle(),
1093 )
1094 });
1095 let show_overlay = Rc::new(Cell::new(false));
1096 let (view, cx) = cx.add_window_view({
1097 let show_overlay = show_overlay.clone();
1098 let workbench_focus = workbench_focus.clone();
1099 let left_panel_focus = left_panel_focus.clone();
1100 let right_panel_focus = right_panel_focus.clone();
1101 let overlay_focus = overlay_focus.clone();
1102 move |_, _| FocusHarness {
1103 workbench_focus,
1104 left_panel_focus,
1105 right_panel_focus,
1106 overlay_focus,
1107 show_overlay,
1108 }
1109 });
1110
1111 cx.update(|window, app| window.draw(app).clear(app));
1112 let left_bounds = cx.debug_bounds("left-panel").expect("left panel bounds");
1113 let dock_bounds = cx
1114 .debug_bounds("focus-resize-dock")
1115 .expect("resize dock bounds");
1116 let handle_point = point(dock_bounds.left() + px(0.5), dock_bounds.center().y);
1117
1118 cx.update(|window, app| window.focus(&right_panel_focus, app));
1119 cx.update(|window, app| window.draw(app).clear(app));
1120 cx.simulate_mouse_down(handle_point, MouseButton::Left, Modifiers::default());
1121 assert!(
1122 cx.update(|window, _| right_panel_focus.is_focused(window)),
1123 "left-clicking a resize handle must preserve the focused panel"
1124 );
1125 assert!(cx.update(|window, _| window.default_prevented()));
1126 cx.simulate_mouse_up(handle_point, MouseButton::Left, Modifiers::default());
1127
1128 cx.simulate_mouse_down(handle_point, MouseButton::Right, Modifiers::default());
1129 assert!(
1130 cx.update(|window, _| !window.default_prevented()),
1131 "the focus guard must not claim non-left mouse buttons"
1132 );
1133 assert!(
1134 cx.update(|window, _| right_panel_focus.is_focused(window)),
1135 "an occluding divider must leave the existing focus unchanged on right-click"
1136 );
1137 cx.simulate_mouse_up(handle_point, MouseButton::Right, Modifiers::default());
1138
1139 cx.update(|window, app| window.focus(&right_panel_focus, app));
1140 cx.update(|window, app| window.draw(app).clear(app));
1141 let adjacent_point = point(left_bounds.right() - px(1.), left_bounds.center().y);
1142 assert!(adjacent_point.x < dock_bounds.left());
1143 cx.simulate_click(adjacent_point, Modifiers::default());
1144 assert!(
1145 cx.update(|window, _| left_panel_focus.is_focused(window)),
1146 "a control immediately beside the handle must keep normal focus behavior"
1147 );
1148
1149 cx.update(|window, app| window.focus(&right_panel_focus, app));
1150 cx.update(|window, app| window.draw(app).clear(app));
1151 cx.simulate_mouse_move(handle_point, None::<MouseButton>, Modifiers::default());
1152 show_overlay.set(true);
1153 cx.update(|window, app| {
1154 view.update(app, |_, cx| cx.notify());
1155 window.draw(app).clear(app);
1156 });
1157 let overlay_bounds = cx.debug_bounds("focus-overlay").expect("overlay bounds");
1158 assert!(
1159 overlay_bounds.left() <= handle_point.x
1160 && handle_point.x <= overlay_bounds.right()
1161 && overlay_bounds.top() <= handle_point.y
1162 && handle_point.y <= overlay_bounds.bottom(),
1163 "the overlay must cover the point where the pointer hovered the divider"
1164 );
1165 cx.simulate_click(handle_point, Modifiers::default());
1166 assert!(
1167 cx.update(|window, _| overlay_focus.is_focused(window)),
1168 "a topmost overlay must receive focus over a previously hovered divider"
1169 );
1170 }
1171}