Skip to main content

gpui_material_components/
drop_target.rs

1use std::{marker::PhantomData, rc::Rc};
2
3use gpui::{
4    AccessibleAction, AnyElement, App, ClickEvent, ElementId, Entity, ExternalPaths, FocusHandle,
5    Hsla, InteractiveElement, IntoElement, ParentElement, RenderOnce, Role, SharedString,
6    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button as BaseButton, TestSupportExt};
9use gpui_material_foundation::{
10    InteractionSource, InteractionState, ThemeScope, color, current_material_strings,
11    current_material_theme,
12};
13use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, StateLayer, TypeRole};
14
15use crate::{
16    Icon, IconName, Text,
17    action::{activate_feedback, feedback_target, ripple_state},
18};
19
20type DropPredicate<T> = Rc<dyn Fn(&T, &mut Window, &mut App) -> bool>;
21type DropHandler<T> = Rc<dyn Fn(&T, &mut Window, &mut App)>;
22type ActivateHandler = Rc<dyn Fn(&mut Window, &mut App)>;
23
24/// Per-instance pigments for idle, valid drag-over, and rejected drag-over states of a [`DropTarget`].
25#[derive(Clone, Copy, Debug, Default, PartialEq)]
26pub struct DropTargetColors {
27    /// Background color while idle. Defaults to `SurfaceContainerLowest`.
28    pub container: Option<Hsla>,
29    /// Background color while an accepted payload is dragged over the target. Defaults to `PrimaryContainer`.
30    pub active_container: Option<Hsla>,
31    /// Background color while a rejected payload is dragged over the target. Defaults to `ErrorContainer`.
32    pub invalid_container: Option<Hsla>,
33    /// Dashed border color while idle. Defaults to `OutlineVariant`.
34    pub border: Option<Hsla>,
35    /// Dashed border color while an accepted payload is dragged over the target. Defaults to `Primary`.
36    pub active_border: Option<Hsla>,
37    /// Dashed border color while a rejected payload is dragged over the target. Defaults to `Error`.
38    pub invalid_border: Option<Hsla>,
39    /// Foreground color for text and icons while idle. Defaults to `OnSurfaceVariant`.
40    pub content: Option<Hsla>,
41    /// Foreground color while an accepted payload is dragged over the target. Defaults to `OnPrimaryContainer`.
42    pub active_content: Option<Hsla>,
43    /// Foreground color while a rejected payload is dragged over the target. Defaults to `OnErrorContainer`.
44    pub invalid_content: Option<Hsla>,
45}
46
47#[derive(Clone, Copy)]
48struct ResolvedPalette {
49    container: Hsla,
50    active_container: Hsla,
51    invalid_container: Hsla,
52    border: Hsla,
53    active_border: Hsla,
54    invalid_border: Hsla,
55    content: Hsla,
56    active_content: Hsla,
57    invalid_content: Hsla,
58    hover_tint: Hsla,
59    ring: Hsla,
60}
61
62impl DropTargetColors {
63    fn resolve(self, disabled: bool, window: &Window, cx: &App) -> ResolvedPalette {
64        use ColorRole::*;
65        let theme = current_material_theme(window, cx);
66        let role = |r| color(theme.colors.color(r));
67        let on_surface = role(OnSurface);
68        let ring = role(Secondary);
69        if disabled {
70            return ResolvedPalette {
71                container: self.container.unwrap_or_else(|| on_surface.opacity(0.06)),
72                active_container: self
73                    .active_container
74                    .unwrap_or_else(|| on_surface.opacity(0.06)),
75                invalid_container: self
76                    .invalid_container
77                    .unwrap_or_else(|| on_surface.opacity(0.06)),
78                border: self.border.unwrap_or_else(|| on_surface.opacity(0.12)),
79                active_border: self
80                    .active_border
81                    .unwrap_or_else(|| on_surface.opacity(0.12)),
82                invalid_border: self
83                    .invalid_border
84                    .unwrap_or_else(|| on_surface.opacity(0.12)),
85                content: self.content.unwrap_or_else(|| on_surface.opacity(0.38)),
86                active_content: self
87                    .active_content
88                    .unwrap_or_else(|| on_surface.opacity(0.38)),
89                invalid_content: self
90                    .invalid_content
91                    .unwrap_or_else(|| on_surface.opacity(0.38)),
92                hover_tint: gpui::transparent_black(),
93                ring,
94            };
95        }
96
97        ResolvedPalette {
98            container: self
99                .container
100                .unwrap_or_else(|| role(SurfaceContainerLowest)),
101            active_container: self
102                .active_container
103                .unwrap_or_else(|| role(PrimaryContainer)),
104            invalid_container: self
105                .invalid_container
106                .unwrap_or_else(|| role(ErrorContainer)),
107            border: self.border.unwrap_or_else(|| role(OutlineVariant)),
108            active_border: self.active_border.unwrap_or_else(|| role(Primary)),
109            invalid_border: self.invalid_border.unwrap_or_else(|| role(Error)),
110            content: self.content.unwrap_or_else(|| role(OnSurfaceVariant)),
111            active_content: self
112                .active_content
113                .unwrap_or_else(|| role(OnPrimaryContainer)),
114            invalid_content: self
115                .invalid_content
116                .unwrap_or_else(|| role(OnErrorContainer)),
117            hover_tint: role(OnSurface).opacity(StateLayer::Hover.opacity()),
118            ring,
119        }
120    }
121}
122
123/// Material-styled drag-and-drop container supporting external OS files (`ExternalPaths`)
124/// and typed in-app GPUI drag payloads `T: 'static`.
125#[derive(IntoElement)]
126pub struct DropTarget<T: 'static = ExternalPaths> {
127    id: ElementId,
128    title: Option<SharedString>,
129    supporting: Option<SharedString>,
130    icon: Option<AnyElement>,
131    content: Option<AnyElement>,
132    shape: CornerShape,
133    colors: DropTargetColors,
134    disabled: bool,
135    can_drop: Option<DropPredicate<T>>,
136    on_drop: Option<DropHandler<T>>,
137    on_activate: Option<ActivateHandler>,
138    accessible_label: Option<SharedString>,
139    focus: Option<FocusHandle>,
140    source: Option<Entity<InteractionSource>>,
141    _payload: PhantomData<fn(&T)>,
142}
143
144impl DropTarget<ExternalPaths> {
145    /// Creates a drop target configured for external OS file drops (`gpui::ExternalPaths`).
146    pub fn files(id: impl Into<ElementId>) -> Self {
147        Self::new(id)
148    }
149}
150
151impl<T: 'static> DropTarget<T> {
152    /// Creates a drop target accepting GPUI drags of payload type `T`.
153    pub fn new(id: impl Into<ElementId>) -> Self {
154        Self {
155            id: id.into(),
156            title: None,
157            supporting: None,
158            icon: None,
159            content: None,
160            shape: CornerRole::Large.shape(),
161            colors: DropTargetColors::default(),
162            disabled: false,
163            can_drop: None,
164            on_drop: None,
165            on_activate: None,
166            accessible_label: None,
167            focus: None,
168            source: None,
169            _payload: PhantomData,
170        }
171    }
172
173    /// Primary prompt text displayed in the default placeholder layout when `.content(...)` is not set.
174    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
175        self.title = Some(title.into());
176        self
177    }
178
179    /// Secondary description displayed below the title in the default placeholder layout.
180    pub fn supporting(mut self, supporting: impl Into<SharedString>) -> Self {
181        self.supporting = Some(supporting.into());
182        self
183    }
184
185    /// Decorative icon displayed above the title in the default placeholder layout.
186    pub fn icon(mut self, icon: impl IntoElement) -> Self {
187        self.icon = Some(icon.into_any_element());
188        self
189    }
190
191    /// Wraps caller-supplied child content with the drop target's border, feedback, and drop handlers.
192    pub fn content(mut self, content: impl IntoElement) -> Self {
193        self.content = Some(content.into_any_element());
194        self
195    }
196
197    /// Sets the logical corner shape. Defaults to `CornerRole::Large`.
198    pub fn shape(mut self, shape: CornerShape) -> Self {
199        self.shape = shape;
200        self
201    }
202
203    /// Overrides idle, active drag-over, and invalid drag-over colors independently.
204    pub fn colors(mut self, colors: DropTargetColors) -> Self {
205        self.colors = colors;
206        self
207    }
208
209    /// Disables drop registration, drag-over visual feedback, and optional click/keyboard activation.
210    pub fn disabled(mut self, disabled: bool) -> Self {
211        self.disabled = disabled;
212        self
213    }
214
215    /// Validates whether a dragged payload `T` can be dropped here.
216    /// Rejected payloads show invalid/error visual feedback and skip `on_drop`.
217    pub fn can_drop(
218        mut self,
219        predicate: impl Fn(&T, &mut Window, &mut App) -> bool + 'static,
220    ) -> Self {
221        self.can_drop = Some(Rc::new(predicate));
222        self
223    }
224
225    /// Invoked when an accepted payload `T` is dropped onto this target.
226    pub fn on_drop(mut self, handler: impl Fn(&T, &mut Window, &mut App) + 'static) -> Self {
227        self.on_drop = Some(Rc::new(handler));
228        self
229    }
230
231    /// Enables pointer click and keyboard Enter/Space activation (for example, to open a file picker).
232    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
233        self.on_activate = Some(Rc::new(handler));
234        self
235    }
236
237    /// Sets the accessible name exposed to assistive technology. Falls back to `.title(...)` or `"Drop target"`.
238    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
239        self.accessible_label = Some(label.into());
240        self
241    }
242
243    /// Uses a caller-owned focus handle when the drop target is actionable via `.on_activate(...)`.
244    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
245        self.focus = Some(focus.clone());
246        self
247    }
248
249    /// Observes hover, focus, press, and disabled states under this drop target's element ID.
250    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
251        self.source = Some(source.clone());
252        self
253    }
254}
255
256fn apply_corner_shape<E: Styled>(element: E, shape: CornerShape, direction: Direction) -> E {
257    if shape == CornerShape::Full {
258        element.rounded_full()
259    } else {
260        let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, direction);
261        element
262            .rounded_tl(px(tl))
263            .rounded_tr(px(tr))
264            .rounded_br(px(br))
265            .rounded_bl(px(bl))
266    }
267}
268
269impl<T: 'static> RenderOnce for DropTarget<T> {
270    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
271        let theme = current_material_theme(window, cx);
272        let strings = current_material_strings(window, cx);
273        let direction = theme.layout.direction;
274        let palette = self.colors.resolve(self.disabled, window, cx);
275        let accessible_name = self
276            .accessible_label
277            .or_else(|| self.title.clone())
278            .unwrap_or_else(|| SharedString::from(strings.drop_target.clone()));
279        let enabled = !self.disabled;
280        let tracker = self
281            .source
282            .as_ref()
283            .map(|source| InteractionSource::track(source, &self.id, window, cx));
284
285        let inner_content = match self.content {
286            Some(content) => div().w_full().child(content).into_any_element(),
287            None => {
288                let icon = self
289                    .icon
290                    .unwrap_or_else(|| Icon::new(IconName::Add).size(px(28.)).into_any_element());
291                let title = self
292                    .title
293                    .unwrap_or_else(|| SharedString::from(strings.drop_files_here.clone()));
294                div()
295                    .w_full()
296                    .min_h(px(120.))
297                    .p(px(24.))
298                    .flex()
299                    .flex_col()
300                    .items_center()
301                    .justify_center()
302                    .gap(px(8.))
303                    .child(div().text_size(px(28.)).child(icon))
304                    .child(
305                        Text::new(title)
306                            .id("drop-target-title")
307                            .role(TypeRole::TitleMedium)
308                            .wrap(),
309                    )
310                    .children(self.supporting.map(|text| {
311                        Text::new(text)
312                            .id("drop-target-supporting")
313                            .role(TypeRole::BodyMedium)
314                            .wrap()
315                    }))
316                    .into_any_element()
317            }
318        };
319
320        let body = if let Some(on_activate) = self.on_activate {
321            let focus = self.focus.unwrap_or_else(|| {
322                window
323                    .use_keyed_state((self.id.clone(), "drop-target-focus"), cx, |_, cx| {
324                        cx.focus_handle()
325                    })
326                    .read(cx)
327                    .clone()
328            });
329            let feedback = ripple_state(&self.id, enabled, window, cx);
330            feedback
331                .borrow_mut()
332                .track(enabled, &focus, tracker, window, cx);
333            let on_activate = Rc::new(ThemeScope::bind_action(
334                move |window, cx| on_activate(window, cx),
335                window,
336                cx,
337            ));
338            let click_handler = on_activate.clone();
339            let a11y_handler = on_activate;
340            let press = feedback.clone();
341            let hover_tint = palette.hover_tint;
342            let ring = palette.ring;
343            apply_corner_shape(
344                BaseButton::new((self.id.clone(), "activate"))
345                    .track_focus(&focus)
346                    .tab_stop(enabled)
347                    .disabled(self.disabled)
348                    .w_full()
349                    .accessibility_label(accessible_name)
350                    .border_2()
351                    .border_color(gpui::transparent_black()),
352                self.shape,
353                direction,
354            )
355            .when(enabled, |button| {
356                feedback_target(button, feedback, true, Some(focus.clone()))
357                    .hover(move |style| style.bg(hover_tint))
358                    .focus_visible(move |style| style.border_color(ring))
359                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
360                        a11y_handler(window, cx);
361                    })
362                    .on_click(move |event, window, cx| {
363                        if matches!(event, ClickEvent::Mouse(_)) && cx.has_active_drag() {
364                            return;
365                        }
366                        cx.stop_propagation();
367                        activate_feedback(event, &press, window, cx);
368                        click_handler(window, cx);
369                    })
370            })
371            .child(inner_content)
372            .into_any_element()
373        } else {
374            if let Some(tracker) = tracker {
375                let mut state = InteractionState::default();
376                state.disabled = !enabled;
377                tracker.record(state, cx);
378            }
379            div()
380                .id((self.id.clone(), "body"))
381                .test_support()
382                .w_full()
383                .role(Role::Region)
384                .aria_label(accessible_name)
385                .child(inner_content)
386                .into_any_element()
387        };
388
389        // Keep `drag_over` on the visual wrapper (without `can_drop_predicate`) so rejected
390        // payloads still paint invalid feedback, while the drop receiver enforces `can_drop`.
391        let visual_can_drop = self.can_drop.clone();
392        let drop_can_drop = self.can_drop;
393        let on_drop = self.on_drop;
394
395        let receiver = div()
396            .id((self.id.clone(), "receiver"))
397            .test_support()
398            .w_full()
399            .when(!self.disabled, |receiver| {
400                let check = drop_can_drop;
401                receiver
402                    .can_drop(move |any, window, cx| {
403                        any.downcast_ref::<T>().is_some_and(|payload| {
404                            check
405                                .as_ref()
406                                .is_none_or(|predicate| predicate(payload, window, cx))
407                        })
408                    })
409                    .on_drop::<T>(move |payload, window, cx| {
410                        if let Some(handler) = &on_drop {
411                            handler(payload, window, cx);
412                        }
413                    })
414            })
415            .child(body);
416
417        apply_corner_shape(
418            div()
419                .id(self.id)
420                .test_support()
421                .w_full()
422                .overflow_hidden()
423                .bg(palette.container)
424                .border_2()
425                .border_dashed()
426                .border_color(palette.border)
427                .text_color(palette.content),
428            self.shape,
429            direction,
430        )
431        .when(direction == Direction::Rtl, Styled::flex_row_reverse)
432        .when(!self.disabled, move |surface| {
433            surface.drag_over::<T>(move |style, payload, window, cx| {
434                let accepted = visual_can_drop
435                    .as_ref()
436                    .is_none_or(|predicate| predicate(payload, window, cx));
437                if accepted {
438                    style
439                        .bg(palette.active_container)
440                        .border_color(palette.active_border)
441                        .text_color(palette.active_content)
442                } else {
443                    style
444                        .bg(palette.invalid_container)
445                        .border_color(palette.invalid_border)
446                        .text_color(palette.invalid_content)
447                }
448            })
449        })
450        .child(receiver)
451    }
452}