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