Skip to main content

gpui_material_components/
drag_handle.rs

1mod pointer;
2mod state;
3
4use std::{ops::RangeInclusive, rc::Rc};
5
6use gpui::{
7    AccessibleAction, App, Bounds, Corners, ElementId, Entity, HitboxBehavior, Hsla,
8    InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, Role, SharedString, Size,
9    StatefulInteractiveElement, Styled, Window,
10    accesskit::{ActionData, Orientation},
11    canvas, div, fill, point, px, size,
12};
13use gpui_base::TestSupportExt as _;
14use gpui_material_foundation::{
15    InteractionFeedback, InteractionSource, InteractionState, Shape, color, current_material_theme,
16};
17use gpui_material_theme::{ColorRole, CornerRole, CornerShape};
18
19use pointer::pointer_listeners;
20use state::{HandleState, ResizeBinding, ResizeRequest, logical_delta};
21
22const REST_SIZE: Size<Pixels> = size(px(4.), px(48.));
23const ACTIVE_SIZE: Size<Pixels> = size(px(12.), px(52.));
24const DEFAULT_STEP: Pixels = px(8.);
25
26/// Visual sizes in logical pixels. Omitted values use Material defaults.
27#[derive(Clone, Copy, Debug, Default, PartialEq)]
28pub struct DragHandleSizes {
29    /// Handle dimensions while idle. Defaults to `4 × 48 px`.
30    pub resting: Option<Size<Pixels>>,
31    /// Handle dimensions while pressed. Defaults to `12 × 52 px`.
32    pub pressed: Option<Size<Pixels>>,
33    /// Handle dimensions while actively dragged. Defaults to `12 × 52 px`.
34    pub dragged: Option<Size<Pixels>>,
35}
36
37/// Fill colors. Omitted values use the corresponding window theme role.
38#[derive(Clone, Copy, Debug, Default, PartialEq)]
39pub struct DragHandleColors {
40    /// Fill color while idle. Defaults to `ColorRole::Outline`.
41    pub resting: Option<Hsla>,
42    /// Fill color while pressed. Defaults to `ColorRole::OnSurface`.
43    pub pressed: Option<Hsla>,
44    /// Fill color while actively dragged. Defaults to `ColorRole::OnSurface`.
45    pub dragged: Option<Hsla>,
46}
47
48/// Corner shapes in logical corner order. Omitted values use Material defaults.
49#[derive(Clone, Copy, Debug, Default, PartialEq)]
50pub struct DragHandleShapes {
51    /// Corner shape while idle. Defaults to `CornerRole::Full`.
52    pub resting: Option<CornerShape>,
53    /// Corner shape while pressed. Defaults to `CornerRole::Medium`.
54    pub pressed: Option<CornerShape>,
55    /// Corner shape while actively dragged. Defaults to `CornerRole::Medium`.
56    pub dragged: Option<CornerShape>,
57}
58
59/// A vertical Material handle for a horizontally adjustable boundary.
60/// The owner provides the layout and decides which requested widths to apply.
61#[derive(IntoElement)]
62pub struct VerticalDragHandle {
63    id: ElementId,
64    sizes: DragHandleSizes,
65    colors: DragHandleColors,
66    shapes: DragHandleShapes,
67    source: Option<Entity<InteractionSource>>,
68    resize: Option<Rc<ResizeBinding>>,
69    on_resize_end: Option<ResizeRequest>,
70    resize_context: Option<Size<Pixels>>,
71    keyboard_step: Pixels,
72}
73
74impl VerticalDragHandle {
75    /// Creates a handle with the default appearance and no resize binding.
76    pub fn new(id: impl Into<ElementId>) -> Self {
77        Self {
78            id: id.into(),
79            sizes: DragHandleSizes::default(),
80            colors: DragHandleColors::default(),
81            shapes: DragHandleShapes::default(),
82            source: None,
83            resize: None,
84            on_resize_end: None,
85            resize_context: None,
86            keyboard_step: DEFAULT_STEP,
87        }
88    }
89
90    /// Overrides the resting, pressed, and dragged handle dimensions.
91    pub fn sizes(mut self, sizes: DragHandleSizes) -> Self {
92        self.sizes = sizes;
93        self
94    }
95
96    /// Overrides the resting, pressed, and dragged handle fill colors.
97    pub fn colors(mut self, colors: DragHandleColors) -> Self {
98        self.colors = colors;
99        self
100    }
101
102    /// Overrides the resting, pressed, and dragged handle corner shapes.
103    pub fn shapes(mut self, shapes: DragHandleShapes) -> Self {
104        self.shapes = shapes;
105        self
106    }
107
108    /// Observes hover, press, drag, and keyboard focus under the handle's ID.
109    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
110        self.source = Some(source.clone());
111        self
112    }
113
114    /// Configures a focusable splitter with an accessible name, start pane
115    /// width, and bounds. The callback receives a requested absolute width.
116    /// Invalid or empty width bounds leave a visual handle.
117    pub fn on_resize(
118        mut self,
119        label: impl Into<SharedString>,
120        width: Pixels,
121        range: RangeInclusive<Pixels>,
122        on_resize: impl Fn(Pixels, &mut Window, &mut App) + 'static,
123    ) -> Self {
124        let (min, max) = range.into_inner();
125        self.resize = (min >= px(0.)
126            && min < max
127            && f32::from(max).is_finite()
128            && f32::from(width).is_finite())
129        .then(|| {
130            Rc::new(ResizeBinding {
131                label: label.into(),
132                width: width.clamp(min, max),
133                min,
134                max,
135                request: Rc::new(on_resize),
136            })
137        });
138        self
139    }
140
141    /// Final pointer value after a completed drag. Cancellation skips this callback.
142    #[cfg_attr(not(feature = "navigation"), allow(dead_code))]
143    pub(crate) fn on_resize_end(
144        mut self,
145        callback: impl Fn(Pixels, &mut Window, &mut App) + 'static,
146    ) -> Self {
147        self.on_resize_end = Some(Rc::new(callback));
148        self
149    }
150
151    /// A consumer can invalidate the pointer origin when its viewport changes.
152    #[cfg_attr(not(feature = "navigation"), allow(dead_code))]
153    pub(crate) fn resize_context(mut self, viewport: Size<Pixels>) -> Self {
154        self.resize_context = Some(viewport);
155        self
156    }
157
158    /// Sets the keyboard and accessibility increment. Defaults to 8 logical pixels.
159    pub fn keyboard_step(mut self, step: Pixels) -> Self {
160        self.keyboard_step = positive_or(step, DEFAULT_STEP);
161        self
162    }
163}
164
165fn positive_or(value: Pixels, fallback: Pixels) -> Pixels {
166    if value > px(0.) && f32::from(value).is_finite() {
167        value
168    } else {
169        fallback
170    }
171}
172
173fn handle_size(value: Option<Size<Pixels>>, fallback: Size<Pixels>) -> Size<Pixels> {
174    value.map_or(fallback, |value| {
175        size(
176            positive_or(value.width, fallback.width),
177            positive_or(value.height, fallback.height),
178        )
179    })
180}
181
182impl RenderOnce for VerticalDragHandle {
183    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
184        let theme = current_material_theme(window, cx);
185        let direction = theme.layout.direction;
186        let minimum = px(theme.layout.density.interactive_size(0.));
187        let outline = color(theme.colors.color(ColorRole::Outline));
188        let on_surface = color(theme.colors.color(ColorRole::OnSurface));
189        let ring = color(theme.colors.color(ColorRole::Secondary));
190
191        let state =
192            window.use_keyed_state((self.id.clone(), "drag-handle-state"), cx, HandleState::new);
193        let tracker = self
194            .source
195            .as_ref()
196            .map(|source| InteractionSource::track(source, &self.id, window, cx));
197        let (focus, interaction) = state.update(cx, |state, cx| {
198            if (state.direction != direction
199                || state.adjustable != self.resize.is_some()
200                || state.resize_context != self.resize_context)
201                && state.press.is_some()
202            {
203                state.end(window);
204            }
205            state.adjustable = self.resize.is_some();
206            state.direction = direction;
207            state.resize_context = self.resize_context;
208            state.tracker = tracker;
209            state.record(window, cx);
210            (state.focus.clone(), state.snapshot(window))
211        });
212
213        let resting = handle_size(self.sizes.resting, REST_SIZE);
214        let pressed = handle_size(self.sizes.pressed, ACTIVE_SIZE);
215        let dragged = handle_size(self.sizes.dragged, ACTIVE_SIZE);
216        let width = resting
217            .width
218            .max(pressed.width)
219            .max(dragged.width)
220            .max(minimum);
221        let height = resting
222            .height
223            .max(pressed.height)
224            .max(dragged.height)
225            .max(minimum);
226        let (mark, tint, shape) = if interaction.dragged {
227            (
228                dragged,
229                self.colors.dragged.unwrap_or(on_surface),
230                self.shapes.dragged.unwrap_or(CornerRole::Medium.shape()),
231            )
232        } else if interaction.pressed {
233            (
234                pressed,
235                self.colors.pressed.unwrap_or(on_surface),
236                self.shapes.pressed.unwrap_or(CornerRole::Medium.shape()),
237            )
238        } else {
239            (
240                resting,
241                self.colors.resting.unwrap_or(outline),
242                self.shapes.resting.unwrap_or(CornerRole::Full.shape()),
243            )
244        };
245        let listeners = state.clone();
246        let pointer_resize = self.resize.clone();
247        let pointer_end = self.on_resize_end;
248        let target = canvas(
249            |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
250            move |bounds, hitbox, window, cx| {
251                let mark_bounds = Bounds::new(
252                    bounds.center() - point(mark.width / 2., mark.height / 2.),
253                    mark,
254                );
255                let [top_left, top_right, bottom_right, bottom_left] = shape
256                    .radii(f32::from(mark.width), f32::from(mark.height), direction)
257                    .map(px);
258                window.paint_quad(fill(mark_bounds, tint).corner_radii(Corners {
259                    top_left,
260                    top_right,
261                    bottom_right,
262                    bottom_left,
263                }));
264                if (interaction.hovered || interaction.focus_visible)
265                    && let Some(path) = Shape::rounded(mark_bounds, shape, direction)
266                {
267                    let mut feedback = InteractionState::default();
268                    feedback.hovered = interaction.hovered;
269                    feedback.focus_visible = interaction.focus_visible;
270                    InteractionFeedback::new(feedback, on_surface, ring).paint(
271                        &path,
272                        None,
273                        cx.background_executor().now(),
274                        cx.reduce_motion(),
275                        window,
276                    );
277                }
278                pointer_listeners(listeners, hitbox, pointer_resize, pointer_end, window);
279            },
280        )
281        .size_full();
282        let mut root = div()
283            .id(self.id)
284            .test_support()
285            .flex_none()
286            .w(width)
287            .h(height)
288            .cursor_col_resize()
289            .child(target);
290        if let Some(resize) = self.resize {
291            let step = self.keyboard_step;
292            let increase = resize.clone();
293            let decrease = resize.clone();
294            let set_value = resize.clone();
295            root = root
296                .track_focus(&focus)
297                // AccessKit exposes writable range values through Slider.
298                .role(Role::Slider)
299                .a11y_synthetic_children(|tree| tree.parent_node().set_role_description("splitter"))
300                .aria_label(resize.label.clone())
301                .aria_orientation(Orientation::Vertical)
302                .aria_numeric_value(f64::from(f32::from(resize.width)))
303                .aria_min_numeric_value(f64::from(f32::from(resize.min)))
304                .aria_max_numeric_value(f64::from(f32::from(resize.max)))
305                .aria_numeric_value_step(f64::from(f32::from(step)))
306                .on_a11y_action(AccessibleAction::Increment, move |_, window, cx| {
307                    increase.request(increase.width + step, window, cx);
308                })
309                .on_a11y_action(AccessibleAction::Decrement, move |_, window, cx| {
310                    decrease.request(decrease.width - step, window, cx);
311                })
312                .on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
313                    if let Some(ActionData::NumericValue(value)) = data
314                        && value.is_finite()
315                    {
316                        set_value.request(px(*value as f32), window, cx);
317                    }
318                })
319                .on_key_down(move |event, window, cx| {
320                    if event.keystroke.modifiers.modified() {
321                        return;
322                    }
323                    let width = match event.keystroke.key.as_str() {
324                        "left" => resize.width + logical_delta(-step, direction),
325                        "right" => resize.width + logical_delta(step, direction),
326                        "home" => resize.min,
327                        "end" => resize.max,
328                        _ => return,
329                    };
330                    resize.request(width, window, cx);
331                    cx.stop_propagation();
332                });
333        }
334        root
335    }
336}