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, window_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    pub(crate) fn on_resize_end(
148        mut self,
149        callback: impl Fn(Pixels, &mut Window, &mut App) + 'static,
150    ) -> Self {
151        self.on_resize_end = Some(Rc::new(callback));
152        self
153    }
154
155    /// A consumer can invalidate the pointer origin when its viewport changes.
156    pub(crate) fn resize_context(mut self, viewport: Size<Pixels>) -> Self {
157        self.resize_context = Some(viewport);
158        self
159    }
160
161    /// Sets the keyboard and accessibility increment. Defaults to 8 logical pixels.
162    pub fn keyboard_step(mut self, step: Pixels) -> Self {
163        self.keyboard_step = positive_or(step, DEFAULT_STEP);
164        self
165    }
166}
167
168fn positive_or(value: Pixels, fallback: Pixels) -> Pixels {
169    if value > px(0.) && f32::from(value).is_finite() {
170        value
171    } else {
172        fallback
173    }
174}
175
176fn handle_size(value: Option<Size<Pixels>>, fallback: Size<Pixels>) -> Size<Pixels> {
177    value.map_or(fallback, |value| {
178        size(
179            positive_or(value.width, fallback.width),
180            positive_or(value.height, fallback.height),
181        )
182    })
183}
184
185struct PointerPress {
186    mouse_capture: Option<(HitboxId, DragCapture)>,
187    origin: Point<Pixels>,
188    width_at_press: Option<Pixels>,
189    last_request: Option<Pixels>,
190    dragged: bool,
191}
192
193impl PointerPress {
194    fn new(
195        origin: Point<Pixels>,
196        width: Option<Pixels>,
197        mouse_capture: Option<(HitboxId, DragCapture)>,
198    ) -> Self {
199        Self {
200            mouse_capture,
201            origin,
202            width_at_press: width,
203            last_request: width,
204            dragged: false,
205        }
206    }
207}
208
209struct HandleState {
210    focus: FocusHandle,
211    press: Option<PointerPress>,
212    hovered: bool,
213    direction: Direction,
214    adjustable: bool,
215    resize_context: Option<Size<Pixels>>,
216    tracker: Option<InteractionTracker>,
217    _blur: Subscription,
218    _activation: Subscription,
219}
220
221impl HandleState {
222    fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
223        let focus = cx.focus_handle().tab_stop(true);
224        let blur = cx.on_blur(&focus, window, |state, window, cx| {
225            state.end(window);
226            state.publish(window, cx);
227        });
228        let activation = cx.observe_window_activation(window, |state, window, cx| {
229            if !window.is_window_active() {
230                state.end(window);
231                state.hovered = false;
232                state.publish(window, cx);
233            }
234        });
235        let handle = window.window_handle();
236        cx.on_release(move |state: &mut Self, cx| {
237            if let Some((hitbox, _)) = state.press.take().and_then(|press| press.mouse_capture) {
238                cx.defer(move |cx| {
239                    let _ = handle.update(cx, |_, window, _| release_pointer(hitbox, window));
240                });
241            }
242        })
243        .detach();
244        Self {
245            focus,
246            press: None,
247            hovered: false,
248            direction: Direction::Ltr,
249            adjustable: false,
250            resize_context: None,
251            tracker: None,
252            _blur: blur,
253            _activation: activation,
254        }
255    }
256
257    fn snapshot(&self, window: &Window) -> InteractionState {
258        let mut state = InteractionState::default();
259        state.hovered = self.hovered;
260        state.pressed = self.press.is_some();
261        state.dragged = self.press.as_ref().is_some_and(|press| press.dragged);
262        state.focus_visible =
263            self.adjustable && self.focus.is_focused(window) && window.last_input_was_keyboard();
264        state
265    }
266
267    fn record(&self, window: &Window, cx: &mut App) {
268        if let Some(tracker) = &self.tracker {
269            tracker.record(self.snapshot(window), cx);
270        }
271    }
272
273    fn publish(&self, window: &mut Window, cx: &mut Context<Self>) {
274        self.record(window, cx);
275        cx.notify();
276        window.refresh();
277    }
278
279    fn end(&mut self, window: &mut Window) {
280        if let Some((hitbox, _)) = self.press.take().and_then(|press| press.mouse_capture) {
281            release_pointer(hitbox, window);
282        }
283    }
284
285    fn final_pointer_width(&self) -> Option<Pixels> {
286        self.press
287            .as_ref()
288            .filter(|press| press.dragged)?
289            .last_request
290    }
291
292    fn mouse_pressed(&self) -> bool {
293        self.press
294            .as_ref()
295            .is_some_and(|press| press.mouse_capture.is_some())
296    }
297
298    fn move_pointer(
299        &mut self,
300        position: Point<Pixels>,
301        resize: Option<&ResizeBinding>,
302    ) -> Option<Pixels> {
303        let press = self.press.as_mut()?;
304        let delta = position - press.origin;
305        if !press.dragged {
306            press.dragged = starts_horizontal_drag(delta);
307        }
308        if !press.dragged {
309            return None;
310        }
311        let resize = resize?;
312        let origin = press.width_at_press?;
313        // Use the physical press origin even when the owner moves the handle
314        // or rejects a request while it is being dragged.
315        let value = (origin + logical_delta(delta.x, self.direction)).clamp(resize.min, resize.max);
316        (press.last_request.replace(value) != Some(value)).then_some(value)
317    }
318}
319
320fn starts_horizontal_drag(delta: Point<Pixels>) -> bool {
321    delta.x.abs() >= DRAG_SLOP && delta.x.abs() > delta.y.abs()
322}
323
324fn release_pointer(id: HitboxId, window: &mut Window) {
325    if window.captured_hitbox() == Some(id) {
326        window.release_pointer();
327    }
328}
329
330fn logical_delta(delta: Pixels, direction: Direction) -> Pixels {
331    if direction == Direction::Rtl {
332        -delta
333    } else {
334        delta
335    }
336}
337
338impl RenderOnce for VerticalDragHandle {
339    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
340        let theme = window_material_theme(window, cx);
341        let direction = theme.layout.direction;
342        let minimum = px(theme.layout.density.interactive_size(0.));
343        let outline = color(theme.colors.color(ColorRole::Outline));
344        let on_surface = color(theme.colors.color(ColorRole::OnSurface));
345        let ring = color(theme.colors.color(ColorRole::Secondary));
346
347        let state =
348            window.use_keyed_state((self.id.clone(), "drag-handle-state"), cx, HandleState::new);
349        let tracker = self
350            .source
351            .as_ref()
352            .map(|source| InteractionSource::track(source, &self.id, window, cx));
353        let (focus, interaction) = state.update(cx, |state, cx| {
354            if (state.direction != direction
355                || state.adjustable != self.resize.is_some()
356                || state.resize_context != self.resize_context)
357                && state.press.is_some()
358            {
359                state.end(window);
360            }
361            state.adjustable = self.resize.is_some();
362            state.direction = direction;
363            state.resize_context = self.resize_context;
364            state.tracker = tracker;
365            state.record(window, cx);
366            (state.focus.clone(), state.snapshot(window))
367        });
368
369        let resting = handle_size(self.sizes.resting, REST_SIZE);
370        let pressed = handle_size(self.sizes.pressed, ACTIVE_SIZE);
371        let dragged = handle_size(self.sizes.dragged, ACTIVE_SIZE);
372        let width = resting
373            .width
374            .max(pressed.width)
375            .max(dragged.width)
376            .max(minimum);
377        let height = resting
378            .height
379            .max(pressed.height)
380            .max(dragged.height)
381            .max(minimum);
382        let (mark, tint, shape) = if interaction.dragged {
383            (
384                dragged,
385                self.colors.dragged.unwrap_or(on_surface),
386                self.shapes.dragged.unwrap_or(CornerRole::Medium.shape()),
387            )
388        } else if interaction.pressed {
389            (
390                pressed,
391                self.colors.pressed.unwrap_or(on_surface),
392                self.shapes.pressed.unwrap_or(CornerRole::Medium.shape()),
393            )
394        } else {
395            (
396                resting,
397                self.colors.resting.unwrap_or(outline),
398                self.shapes.resting.unwrap_or(CornerRole::Full.shape()),
399            )
400        };
401        let listeners = state.clone();
402        let pointer_resize = self.resize.clone();
403        let pointer_end = self.on_resize_end;
404        let target = canvas(
405            |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
406            move |bounds, hitbox, window, cx| {
407                let mark_bounds = Bounds::new(
408                    bounds.center() - point(mark.width / 2., mark.height / 2.),
409                    mark,
410                );
411                let [top_left, top_right, bottom_right, bottom_left] = shape
412                    .radii(f32::from(mark.width), f32::from(mark.height), direction)
413                    .map(px);
414                window.paint_quad(fill(mark_bounds, tint).corner_radii(Corners {
415                    top_left,
416                    top_right,
417                    bottom_right,
418                    bottom_left,
419                }));
420                if (interaction.hovered || interaction.focus_visible)
421                    && let Some(path) = Shape::rounded(mark_bounds, shape, direction)
422                {
423                    let mut feedback = InteractionState::default();
424                    feedback.hovered = interaction.hovered;
425                    feedback.focus_visible = interaction.focus_visible;
426                    InteractionFeedback::new(feedback, on_surface, ring).paint(
427                        &path,
428                        None,
429                        cx.background_executor().now(),
430                        cx.reduce_motion(),
431                        window,
432                    );
433                }
434                pointer_listeners(listeners, hitbox, pointer_resize, pointer_end, window);
435            },
436        )
437        .size_full();
438        let cancel = state.clone();
439        let mut root = div()
440            .id(self.id)
441            .test_support()
442            .flex_none()
443            .w(width)
444            .h(height)
445            .cursor_col_resize()
446            .child(target)
447            .capture_key_down(move |event, window, cx| {
448                if event.keystroke.key == "escape" && cancel.read(cx).press.is_some() {
449                    cancel.update(cx, |state, cx| {
450                        state.end(window);
451                        state.publish(window, cx);
452                    });
453                    cx.stop_propagation();
454                }
455            });
456        if let Some(resize) = self.resize {
457            let step = self.keyboard_step;
458            let increase = resize.clone();
459            let decrease = resize.clone();
460            let set_value = resize.clone();
461            root = root
462                .track_focus(&focus)
463                // AccessKit exposes writable range values through Slider.
464                .role(Role::Slider)
465                .a11y_synthetic_children(|tree| tree.parent_node().set_role_description("splitter"))
466                .aria_label(resize.label.clone())
467                .aria_orientation(Orientation::Vertical)
468                .aria_numeric_value(f64::from(f32::from(resize.width)))
469                .aria_min_numeric_value(f64::from(f32::from(resize.min)))
470                .aria_max_numeric_value(f64::from(f32::from(resize.max)))
471                .aria_numeric_value_step(f64::from(f32::from(step)))
472                .on_a11y_action(AccessibleAction::Increment, move |_, window, cx| {
473                    increase.request(increase.width + step, window, cx);
474                })
475                .on_a11y_action(AccessibleAction::Decrement, move |_, window, cx| {
476                    decrease.request(decrease.width - step, window, cx);
477                })
478                .on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
479                    if let Some(ActionData::NumericValue(value)) = data
480                        && value.is_finite()
481                    {
482                        set_value.request(px(*value as f32), window, cx);
483                    }
484                })
485                .on_key_down(move |event, window, cx| {
486                    let width = match event.keystroke.key.as_str() {
487                        "left" => resize.width + logical_delta(-step, direction),
488                        "right" => resize.width + logical_delta(step, direction),
489                        "home" => resize.min,
490                        "end" => resize.max,
491                        _ => return,
492                    };
493                    resize.request(width, window, cx);
494                    cx.stop_propagation();
495                });
496        }
497        root
498    }
499}
500
501fn pointer_listeners(
502    state: Entity<HandleState>,
503    hitbox: Hitbox,
504    resize: Option<Rc<ResizeBinding>>,
505    on_resize_end: Option<ResizeRequest>,
506    window: &mut Window,
507) {
508    window.on_mouse_event({
509        let state = state.clone();
510        let focus = resize.is_some();
511        let initial_width = resize.as_ref().map(|resize| resize.width);
512        let hitbox = hitbox.clone();
513        move |event: &MouseDownEvent, phase, window, cx| {
514            if !phase.bubble()
515                || event.button != MouseButton::Left
516                || !hitbox.is_hovered(window)
517                || window.captured_hitbox().is_some()
518                || state.read(cx).press.is_some()
519            {
520                return;
521            }
522            state.update(cx, |state, cx| {
523                if focus {
524                    state.focus.focus(window, cx);
525                }
526                let owner = cx.weak_entity();
527                window.capture_pointer(hitbox.id);
528                let watch = DragCapture::watch_pointer(window, cx, move |window, cx| {
529                    let _ = owner.update(cx, |state, cx| {
530                        state.end(window);
531                        state.hovered = false;
532                        state.publish(window, cx);
533                    });
534                });
535                state.press = Some(PointerPress::new(
536                    event.position,
537                    initial_width,
538                    Some((hitbox.id, watch)),
539                ));
540                state.hovered = true;
541                state.publish(window, cx);
542            });
543            cx.stop_propagation();
544        }
545    });
546    window.on_mouse_event({
547        let state = state.clone();
548        let resize = resize.clone();
549        let hitbox = hitbox.clone();
550        move |event: &MouseMoveEvent, phase, window, cx| {
551            let current = state.read(cx);
552            let press = current.mouse_pressed();
553            // An active gesture still receives moves over other controls.
554            if phase.capture() != press {
555                return;
556            }
557            let hovered = hitbox.is_hovered_at(event.position, window);
558            if !press && hovered == current.hovered {
559                return;
560            }
561            let request = state.update(cx, |state, cx| {
562                state.hovered = hovered;
563                let request = if press && event.pressed_button == Some(MouseButton::Left) {
564                    state.move_pointer(event.position, resize.as_deref())
565                } else {
566                    if press {
567                        state.end(window);
568                    }
569                    None
570                };
571                state.publish(window, cx);
572                request
573            });
574            if let (Some(width), Some(resize)) = (request, &resize) {
575                resize.request(width, window, cx);
576            }
577            if press && event.pressed_button == Some(MouseButton::Left) {
578                cx.stop_propagation();
579            }
580        }
581    });
582    window.on_mouse_event({
583        let state = state.clone();
584        let hitbox = hitbox.clone();
585        let resize = resize.clone();
586        let on_resize_end = on_resize_end.clone();
587        move |event: &MouseUpEvent, phase, window, cx| {
588            if !phase.capture()
589                || event.button != MouseButton::Left
590                || !state.read(cx).mouse_pressed()
591            {
592                return;
593            }
594            let (request, finished) = state.update(cx, |state, cx| {
595                let request = state.move_pointer(event.position, resize.as_deref());
596                state.hovered = hitbox.is_hovered_at(event.position, window);
597                let finished = state.final_pointer_width();
598                state.end(window);
599                state.publish(window, cx);
600                (request, finished)
601            });
602            if let (Some(width), Some(resize)) = (request, &resize) {
603                resize.request(width, window, cx);
604            }
605            if let (Some(position), Some(end)) = (finished, &on_resize_end) {
606                end(position, window, cx);
607            }
608            cx.stop_propagation();
609        }
610    });
611    window.on_mouse_event({
612        let state = state.clone();
613        move |event: &TouchDragEvent, phase, window, cx| {
614            let current = state.read(cx);
615            if event.phase == TouchPhase::Started {
616                if !phase.bubble()
617                    || current.press.is_some()
618                    || !hitbox.is_hovered_at(event.start_position, window)
619                    || !starts_horizontal_drag(event.position - event.start_position)
620                {
621                    return;
622                }
623                window.prevent_default();
624            } else if !phase.capture() || current.press.is_none() || current.mouse_pressed() {
625                return;
626            }
627            let (request, finished) = state.update(cx, |state, cx| {
628                if event.phase == TouchPhase::Started {
629                    let width = resize.as_ref().map(|resize| {
630                        state.focus.focus(window, cx);
631                        resize.width
632                    });
633                    state.press = Some(PointerPress::new(event.start_position, width, None));
634                }
635                let request = if event.phase == TouchPhase::Cancelled {
636                    None
637                } else {
638                    state.move_pointer(event.position, resize.as_deref())
639                };
640                let finished = (event.phase == TouchPhase::Ended)
641                    .then(|| state.final_pointer_width())
642                    .flatten();
643                if matches!(event.phase, TouchPhase::Ended | TouchPhase::Cancelled) {
644                    state.end(window);
645                }
646                state.publish(window, cx);
647                (request, finished)
648            });
649            if let (Some(width), Some(resize)) = (request, &resize) {
650                resize.request(width, window, cx);
651            }
652            if let (Some(position), Some(end)) = (finished, &on_resize_end) {
653                end(position, window, cx);
654            }
655            cx.stop_propagation();
656        }
657    });
658    window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
659        if phase.bubble() && state.read(cx).hovered {
660            state.update(cx, |state, cx| {
661                state.hovered = false;
662                state.publish(window, cx);
663            });
664        }
665    });
666}