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