Skip to main content

gpui_material_components/
drag_handle.rs

1use std::{ops::RangeInclusive, rc::Rc};
2
3use gpui::{
4    AccessibleAction, App, Bounds, Context, Corners, ElementId, Entity, FocusHandle, Hitbox,
5    HitboxBehavior, HitboxId, Hsla, InteractiveElement, IntoElement, MouseButton, MouseDownEvent,
6    MouseExitEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, RenderOnce, Role,
7    SharedString, Size, StatefulInteractiveElement, Styled, Subscription, TouchDragEvent,
8    TouchPhase, Window,
9    accesskit::{ActionData, Orientation},
10    canvas, div, fill, point, px, size,
11};
12use gpui_base::TestSupportExt as _;
13use gpui_material_foundation::{
14    DragCapture, InteractionFeedback, InteractionSource, InteractionState, InteractionTracker,
15    Shape, color, current_material_theme,
16};
17use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction};
18
19const REST_SIZE: Size<Pixels> = size(px(4.), px(48.));
20const ACTIVE_SIZE: Size<Pixels> = size(px(12.), px(52.));
21const DEFAULT_STEP: Pixels = px(8.);
22const DRAG_SLOP: Pixels = px(4.);
23
24/// Visual sizes in logical pixels. Omitted values use Material defaults.
25#[derive(Clone, Copy, Debug, Default, PartialEq)]
26pub struct DragHandleSizes {
27    pub resting: Option<Size<Pixels>>,
28    pub pressed: Option<Size<Pixels>>,
29    pub dragged: Option<Size<Pixels>>,
30}
31
32/// Fill colors. Omitted values use the corresponding window theme role.
33#[derive(Clone, Copy, Debug, Default, PartialEq)]
34pub struct DragHandleColors {
35    pub resting: Option<Hsla>,
36    pub pressed: Option<Hsla>,
37    pub dragged: Option<Hsla>,
38}
39
40/// Corner shapes in logical corner order. Omitted values use Material defaults.
41#[derive(Clone, Copy, Debug, Default, PartialEq)]
42pub struct DragHandleShapes {
43    pub resting: Option<CornerShape>,
44    pub pressed: Option<CornerShape>,
45    pub dragged: Option<CornerShape>,
46}
47
48type ResizeRequest = Rc<dyn Fn(Pixels, &mut Window, &mut App)>;
49
50struct ResizeBinding {
51    label: SharedString,
52    width: Pixels,
53    min: Pixels,
54    max: Pixels,
55    request: ResizeRequest,
56}
57
58impl ResizeBinding {
59    fn request(&self, width: Pixels, window: &mut Window, cx: &mut App) {
60        let width = width.clamp(self.min, self.max);
61        if width != self.width {
62            (self.request)(width, window, cx);
63        }
64    }
65}
66
67/// A vertical Material handle for a horizontally adjustable boundary.
68/// The owner provides the layout and decides which requested widths to apply.
69#[derive(IntoElement)]
70pub struct VerticalDragHandle {
71    id: ElementId,
72    sizes: DragHandleSizes,
73    colors: DragHandleColors,
74    shapes: DragHandleShapes,
75    source: Option<Entity<InteractionSource>>,
76    resize: Option<Rc<ResizeBinding>>,
77    on_resize_end: Option<ResizeRequest>,
78    resize_context: Option<Size<Pixels>>,
79    keyboard_step: Pixels,
80}
81
82impl VerticalDragHandle {
83    /// Creates a handle with the default appearance and no resize binding.
84    pub fn new(id: impl Into<ElementId>) -> Self {
85        Self {
86            id: id.into(),
87            sizes: DragHandleSizes::default(),
88            colors: DragHandleColors::default(),
89            shapes: DragHandleShapes::default(),
90            source: None,
91            resize: None,
92            on_resize_end: None,
93            resize_context: None,
94            keyboard_step: DEFAULT_STEP,
95        }
96    }
97
98    pub fn sizes(mut self, sizes: DragHandleSizes) -> Self {
99        self.sizes = sizes;
100        self
101    }
102
103    pub fn colors(mut self, colors: DragHandleColors) -> Self {
104        self.colors = colors;
105        self
106    }
107
108    pub fn shapes(mut self, shapes: DragHandleShapes) -> Self {
109        self.shapes = shapes;
110        self
111    }
112
113    /// Observes hover, press, drag, and keyboard focus under the handle's ID.
114    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
115        self.source = Some(source.clone());
116        self
117    }
118
119    /// Configures a focusable splitter with an accessible name, start pane
120    /// width, and bounds. The callback receives a requested absolute width.
121    /// Invalid or empty width bounds leave a visual handle.
122    pub fn on_resize(
123        mut self,
124        label: impl Into<SharedString>,
125        width: Pixels,
126        range: RangeInclusive<Pixels>,
127        on_resize: impl Fn(Pixels, &mut Window, &mut App) + 'static,
128    ) -> Self {
129        let (min, max) = range.into_inner();
130        self.resize = (min >= px(0.)
131            && min < max
132            && f32::from(max).is_finite()
133            && f32::from(width).is_finite())
134        .then(|| {
135            Rc::new(ResizeBinding {
136                label: label.into(),
137                width: width.clamp(min, max),
138                min,
139                max,
140                request: Rc::new(on_resize),
141            })
142        });
143        self
144    }
145
146    /// Final pointer value after a completed drag. Cancellation skips this callback.
147    #[cfg_attr(not(feature = "navigation"), allow(dead_code))]
148    pub(crate) fn on_resize_end(
149        mut self,
150        callback: impl Fn(Pixels, &mut Window, &mut App) + 'static,
151    ) -> Self {
152        self.on_resize_end = Some(Rc::new(callback));
153        self
154    }
155
156    /// A consumer can invalidate the pointer origin when its viewport changes.
157    #[cfg_attr(not(feature = "navigation"), allow(dead_code))]
158    pub(crate) fn resize_context(mut self, viewport: Size<Pixels>) -> Self {
159        self.resize_context = Some(viewport);
160        self
161    }
162
163    /// Sets the keyboard and accessibility increment. Defaults to 8 logical pixels.
164    pub fn keyboard_step(mut self, step: Pixels) -> Self {
165        self.keyboard_step = positive_or(step, DEFAULT_STEP);
166        self
167    }
168}
169
170fn positive_or(value: Pixels, fallback: Pixels) -> Pixels {
171    if value > px(0.) && f32::from(value).is_finite() {
172        value
173    } else {
174        fallback
175    }
176}
177
178fn handle_size(value: Option<Size<Pixels>>, fallback: Size<Pixels>) -> Size<Pixels> {
179    value.map_or(fallback, |value| {
180        size(
181            positive_or(value.width, fallback.width),
182            positive_or(value.height, fallback.height),
183        )
184    })
185}
186
187struct PointerPress {
188    mouse_capture: Option<(HitboxId, DragCapture)>,
189    origin: Point<Pixels>,
190    width_at_press: Option<Pixels>,
191    last_request: Option<Pixels>,
192    dragged: bool,
193}
194
195impl PointerPress {
196    fn new(
197        origin: Point<Pixels>,
198        width: Option<Pixels>,
199        mouse_capture: Option<(HitboxId, DragCapture)>,
200    ) -> Self {
201        Self {
202            mouse_capture,
203            origin,
204            width_at_press: width,
205            last_request: width,
206            dragged: false,
207        }
208    }
209}
210
211struct HandleState {
212    focus: FocusHandle,
213    press: Option<PointerPress>,
214    hovered: bool,
215    direction: Direction,
216    adjustable: bool,
217    resize_context: Option<Size<Pixels>>,
218    tracker: Option<InteractionTracker>,
219    _blur: Subscription,
220    _activation: Subscription,
221}
222
223impl HandleState {
224    fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
225        let focus = cx.focus_handle().tab_stop(true);
226        let blur = cx.on_blur(&focus, window, |state, window, cx| {
227            state.end(window);
228            state.publish(window, cx);
229        });
230        let activation = cx.observe_window_activation(window, |state, window, cx| {
231            if !window.is_window_active() {
232                state.end(window);
233                state.hovered = false;
234                state.publish(window, cx);
235            }
236        });
237        let handle = window.window_handle();
238        cx.on_release(move |state: &mut Self, cx| {
239            if let Some((hitbox, _)) = state.press.take().and_then(|press| press.mouse_capture) {
240                cx.defer(move |cx| {
241                    let _ = handle.update(cx, |_, window, _| release_pointer(hitbox, window));
242                });
243            }
244        })
245        .detach();
246        Self {
247            focus,
248            press: None,
249            hovered: false,
250            direction: Direction::Ltr,
251            adjustable: false,
252            resize_context: None,
253            tracker: None,
254            _blur: blur,
255            _activation: activation,
256        }
257    }
258
259    fn snapshot(&self, window: &Window) -> InteractionState {
260        let mut state = InteractionState::default();
261        state.hovered = self.hovered;
262        state.pressed = self.press.is_some();
263        state.dragged = self.press.as_ref().is_some_and(|press| press.dragged);
264        state.focus_visible =
265            self.adjustable && self.focus.is_focused(window) && window.last_input_was_keyboard();
266        state
267    }
268
269    fn record(&self, window: &Window, cx: &mut App) {
270        if let Some(tracker) = &self.tracker {
271            tracker.record(self.snapshot(window), cx);
272        }
273    }
274
275    fn publish(&self, window: &mut Window, cx: &mut Context<Self>) {
276        self.record(window, cx);
277        cx.notify();
278        window.refresh();
279    }
280
281    fn end(&mut self, window: &mut Window) {
282        if let Some((hitbox, _)) = self.press.take().and_then(|press| press.mouse_capture) {
283            release_pointer(hitbox, window);
284        }
285    }
286
287    fn final_pointer_width(&self) -> Option<Pixels> {
288        self.press
289            .as_ref()
290            .filter(|press| press.dragged)?
291            .last_request
292    }
293
294    fn mouse_pressed(&self) -> bool {
295        self.press
296            .as_ref()
297            .is_some_and(|press| press.mouse_capture.is_some())
298    }
299
300    fn move_pointer(
301        &mut self,
302        position: Point<Pixels>,
303        resize: Option<&ResizeBinding>,
304    ) -> Option<Pixels> {
305        let press = self.press.as_mut()?;
306        let delta = position - press.origin;
307        if !press.dragged {
308            press.dragged = starts_horizontal_drag(delta);
309        }
310        if !press.dragged {
311            return None;
312        }
313        let resize = resize?;
314        let origin = press.width_at_press?;
315        // Use the physical press origin even when the owner moves the handle
316        // or rejects a request while it is being dragged.
317        let value = (origin + logical_delta(delta.x, self.direction)).clamp(resize.min, resize.max);
318        (press.last_request.replace(value) != Some(value)).then_some(value)
319    }
320}
321
322fn starts_horizontal_drag(delta: Point<Pixels>) -> bool {
323    delta.x.abs() >= DRAG_SLOP && delta.x.abs() > delta.y.abs()
324}
325
326fn release_pointer(id: HitboxId, window: &mut Window) {
327    if window.captured_hitbox() == Some(id) {
328        window.release_pointer();
329    }
330}
331
332fn logical_delta(delta: Pixels, direction: Direction) -> Pixels {
333    if direction == Direction::Rtl {
334        -delta
335    } else {
336        delta
337    }
338}
339
340impl RenderOnce for VerticalDragHandle {
341    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
342        let theme = current_material_theme(window, cx);
343        let direction = theme.layout.direction;
344        let minimum = px(theme.layout.density.interactive_size(0.));
345        let outline = color(theme.colors.color(ColorRole::Outline));
346        let on_surface = color(theme.colors.color(ColorRole::OnSurface));
347        let ring = color(theme.colors.color(ColorRole::Secondary));
348
349        let state =
350            window.use_keyed_state((self.id.clone(), "drag-handle-state"), cx, HandleState::new);
351        let tracker = self
352            .source
353            .as_ref()
354            .map(|source| InteractionSource::track(source, &self.id, window, cx));
355        let (focus, interaction) = state.update(cx, |state, cx| {
356            if (state.direction != direction
357                || state.adjustable != self.resize.is_some()
358                || state.resize_context != self.resize_context)
359                && state.press.is_some()
360            {
361                state.end(window);
362            }
363            state.adjustable = self.resize.is_some();
364            state.direction = direction;
365            state.resize_context = self.resize_context;
366            state.tracker = tracker;
367            state.record(window, cx);
368            (state.focus.clone(), state.snapshot(window))
369        });
370
371        let resting = handle_size(self.sizes.resting, REST_SIZE);
372        let pressed = handle_size(self.sizes.pressed, ACTIVE_SIZE);
373        let dragged = handle_size(self.sizes.dragged, ACTIVE_SIZE);
374        let width = resting
375            .width
376            .max(pressed.width)
377            .max(dragged.width)
378            .max(minimum);
379        let height = resting
380            .height
381            .max(pressed.height)
382            .max(dragged.height)
383            .max(minimum);
384        let (mark, tint, shape) = if interaction.dragged {
385            (
386                dragged,
387                self.colors.dragged.unwrap_or(on_surface),
388                self.shapes.dragged.unwrap_or(CornerRole::Medium.shape()),
389            )
390        } else if interaction.pressed {
391            (
392                pressed,
393                self.colors.pressed.unwrap_or(on_surface),
394                self.shapes.pressed.unwrap_or(CornerRole::Medium.shape()),
395            )
396        } else {
397            (
398                resting,
399                self.colors.resting.unwrap_or(outline),
400                self.shapes.resting.unwrap_or(CornerRole::Full.shape()),
401            )
402        };
403        let listeners = state.clone();
404        let pointer_resize = self.resize.clone();
405        let pointer_end = self.on_resize_end;
406        let target = canvas(
407            |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
408            move |bounds, hitbox, window, cx| {
409                let mark_bounds = Bounds::new(
410                    bounds.center() - point(mark.width / 2., mark.height / 2.),
411                    mark,
412                );
413                let [top_left, top_right, bottom_right, bottom_left] = shape
414                    .radii(f32::from(mark.width), f32::from(mark.height), direction)
415                    .map(px);
416                window.paint_quad(fill(mark_bounds, tint).corner_radii(Corners {
417                    top_left,
418                    top_right,
419                    bottom_right,
420                    bottom_left,
421                }));
422                if (interaction.hovered || interaction.focus_visible)
423                    && let Some(path) = Shape::rounded(mark_bounds, shape, direction)
424                {
425                    let mut feedback = InteractionState::default();
426                    feedback.hovered = interaction.hovered;
427                    feedback.focus_visible = interaction.focus_visible;
428                    InteractionFeedback::new(feedback, on_surface, ring).paint(
429                        &path,
430                        None,
431                        cx.background_executor().now(),
432                        cx.reduce_motion(),
433                        window,
434                    );
435                }
436                pointer_listeners(listeners, hitbox, pointer_resize, pointer_end, window);
437            },
438        )
439        .size_full();
440        let cancel = state.clone();
441        let mut root = div()
442            .id(self.id)
443            .test_support()
444            .flex_none()
445            .w(width)
446            .h(height)
447            .cursor_col_resize()
448            .child(target)
449            .capture_key_down(move |event, window, cx| {
450                if event.keystroke.key == "escape" && cancel.read(cx).press.is_some() {
451                    cancel.update(cx, |state, cx| {
452                        state.end(window);
453                        state.publish(window, cx);
454                    });
455                    cx.stop_propagation();
456                }
457            });
458        if let Some(resize) = self.resize {
459            let step = self.keyboard_step;
460            let increase = resize.clone();
461            let decrease = resize.clone();
462            let set_value = resize.clone();
463            root = root
464                .track_focus(&focus)
465                // AccessKit exposes writable range values through Slider.
466                .role(Role::Slider)
467                .a11y_synthetic_children(|tree| tree.parent_node().set_role_description("splitter"))
468                .aria_label(resize.label.clone())
469                .aria_orientation(Orientation::Vertical)
470                .aria_numeric_value(f64::from(f32::from(resize.width)))
471                .aria_min_numeric_value(f64::from(f32::from(resize.min)))
472                .aria_max_numeric_value(f64::from(f32::from(resize.max)))
473                .aria_numeric_value_step(f64::from(f32::from(step)))
474                .on_a11y_action(AccessibleAction::Increment, move |_, window, cx| {
475                    increase.request(increase.width + step, window, cx);
476                })
477                .on_a11y_action(AccessibleAction::Decrement, move |_, window, cx| {
478                    decrease.request(decrease.width - step, window, cx);
479                })
480                .on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
481                    if let Some(ActionData::NumericValue(value)) = data
482                        && value.is_finite()
483                    {
484                        set_value.request(px(*value as f32), window, cx);
485                    }
486                })
487                .on_key_down(move |event, window, cx| {
488                    let width = match event.keystroke.key.as_str() {
489                        "left" => resize.width + logical_delta(-step, direction),
490                        "right" => resize.width + logical_delta(step, direction),
491                        "home" => resize.min,
492                        "end" => resize.max,
493                        _ => return,
494                    };
495                    resize.request(width, window, cx);
496                    cx.stop_propagation();
497                });
498        }
499        root
500    }
501}
502
503fn pointer_listeners(
504    state: Entity<HandleState>,
505    hitbox: Hitbox,
506    resize: Option<Rc<ResizeBinding>>,
507    on_resize_end: Option<ResizeRequest>,
508    window: &mut Window,
509) {
510    window.on_mouse_event({
511        let state = state.clone();
512        let focus = resize.is_some();
513        let initial_width = resize.as_ref().map(|resize| resize.width);
514        let hitbox = hitbox.clone();
515        move |event: &MouseDownEvent, phase, window, cx| {
516            if !phase.bubble()
517                || event.button != MouseButton::Left
518                || !hitbox.is_hovered(window)
519                || window.captured_hitbox().is_some()
520                || state.read(cx).press.is_some()
521            {
522                return;
523            }
524            state.update(cx, |state, cx| {
525                if focus {
526                    state.focus.focus(window, cx);
527                }
528                let owner = cx.weak_entity();
529                window.capture_pointer(hitbox.id);
530                let watch = DragCapture::watch_pointer(window, cx, move |window, cx| {
531                    let _ = owner.update(cx, |state, cx| {
532                        state.end(window);
533                        state.hovered = false;
534                        state.publish(window, cx);
535                    });
536                });
537                state.press = Some(PointerPress::new(
538                    event.position,
539                    initial_width,
540                    Some((hitbox.id, watch)),
541                ));
542                state.hovered = true;
543                state.publish(window, cx);
544            });
545            cx.stop_propagation();
546        }
547    });
548    window.on_mouse_event({
549        let state = state.clone();
550        let resize = resize.clone();
551        let hitbox = hitbox.clone();
552        move |event: &MouseMoveEvent, phase, window, cx| {
553            let current = state.read(cx);
554            let press = current.mouse_pressed();
555            // An active gesture still receives moves over other controls.
556            if phase.capture() != press {
557                return;
558            }
559            let hovered = hitbox.is_hovered_at(event.position, window);
560            if !press && hovered == current.hovered {
561                return;
562            }
563            let request = state.update(cx, |state, cx| {
564                state.hovered = hovered;
565                let request = if press && event.pressed_button == Some(MouseButton::Left) {
566                    state.move_pointer(event.position, resize.as_deref())
567                } else {
568                    if press {
569                        state.end(window);
570                    }
571                    None
572                };
573                state.publish(window, cx);
574                request
575            });
576            if let (Some(width), Some(resize)) = (request, &resize) {
577                resize.request(width, window, cx);
578            }
579            if press && event.pressed_button == Some(MouseButton::Left) {
580                cx.stop_propagation();
581            }
582        }
583    });
584    window.on_mouse_event({
585        let state = state.clone();
586        let hitbox = hitbox.clone();
587        let resize = resize.clone();
588        let on_resize_end = on_resize_end.clone();
589        move |event: &MouseUpEvent, phase, window, cx| {
590            if !phase.capture()
591                || event.button != MouseButton::Left
592                || !state.read(cx).mouse_pressed()
593            {
594                return;
595            }
596            let (request, finished) = state.update(cx, |state, cx| {
597                let request = state.move_pointer(event.position, resize.as_deref());
598                state.hovered = hitbox.is_hovered_at(event.position, window);
599                let finished = state.final_pointer_width();
600                state.end(window);
601                state.publish(window, cx);
602                (request, finished)
603            });
604            if let (Some(width), Some(resize)) = (request, &resize) {
605                resize.request(width, window, cx);
606            }
607            if let (Some(position), Some(end)) = (finished, &on_resize_end) {
608                end(position, window, cx);
609            }
610            cx.stop_propagation();
611        }
612    });
613    window.on_mouse_event({
614        let state = state.clone();
615        move |event: &TouchDragEvent, phase, window, cx| {
616            let current = state.read(cx);
617            if event.phase == TouchPhase::Started {
618                if !phase.bubble()
619                    || current.press.is_some()
620                    || !hitbox.is_hovered_at(event.start_position, window)
621                    || !starts_horizontal_drag(event.position - event.start_position)
622                {
623                    return;
624                }
625                window.prevent_default();
626            } else if !phase.capture() || current.press.is_none() || current.mouse_pressed() {
627                return;
628            }
629            let (request, finished) = state.update(cx, |state, cx| {
630                if event.phase == TouchPhase::Started {
631                    let width = resize.as_ref().map(|resize| {
632                        state.focus.focus(window, cx);
633                        resize.width
634                    });
635                    state.press = Some(PointerPress::new(event.start_position, width, None));
636                }
637                let request = if event.phase == TouchPhase::Cancelled {
638                    None
639                } else {
640                    state.move_pointer(event.position, resize.as_deref())
641                };
642                let finished = (event.phase == TouchPhase::Ended)
643                    .then(|| state.final_pointer_width())
644                    .flatten();
645                if matches!(event.phase, TouchPhase::Ended | TouchPhase::Cancelled) {
646                    state.end(window);
647                }
648                state.publish(window, cx);
649                (request, finished)
650            });
651            if let (Some(width), Some(resize)) = (request, &resize) {
652                resize.request(width, window, cx);
653            }
654            if let (Some(position), Some(end)) = (finished, &on_resize_end) {
655                end(position, window, cx);
656            }
657            cx.stop_propagation();
658        }
659    });
660    window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
661        if phase.bubble() && state.read(cx).hovered {
662            state.update(cx, |state, cx| {
663                state.hovered = false;
664                state.publish(window, cx);
665            });
666        }
667    });
668}