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::{InteractionSource, ThemeScope, color, current_material_theme};
10use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, StateLayer, TypeRole};
11
12use crate::{
13 Icon, IconName, Text,
14 action::{activate_feedback, feedback_target, ripple_state},
15};
16
17type DropPredicate<T> = Rc<dyn Fn(&T, &mut Window, &mut App) -> bool>;
18type DropHandler<T> = Rc<dyn Fn(&T, &mut Window, &mut App)>;
19type ActivateHandler = Rc<dyn Fn(&mut Window, &mut App)>;
20
21#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub struct DropTargetColors {
24 pub container: Option<Hsla>,
25 pub active_container: Option<Hsla>,
26 pub invalid_container: Option<Hsla>,
27 pub border: Option<Hsla>,
28 pub active_border: Option<Hsla>,
29 pub invalid_border: Option<Hsla>,
30 pub content: Option<Hsla>,
31 pub active_content: Option<Hsla>,
32 pub invalid_content: Option<Hsla>,
33}
34
35#[derive(Clone, Copy)]
36struct ResolvedPalette {
37 container: Hsla,
38 active_container: Hsla,
39 invalid_container: Hsla,
40 border: Hsla,
41 active_border: Hsla,
42 invalid_border: Hsla,
43 content: Hsla,
44 active_content: Hsla,
45 invalid_content: Hsla,
46 hover_tint: Hsla,
47 ring: Hsla,
48}
49
50impl DropTargetColors {
51 fn resolve(self, disabled: bool, window: &Window, cx: &App) -> ResolvedPalette {
52 use ColorRole::*;
53 let theme = current_material_theme(window, cx);
54 let role = |r| color(theme.colors.color(r));
55 let on_surface = role(OnSurface);
56 let ring = role(Secondary);
57 if disabled {
58 return ResolvedPalette {
59 container: self.container.unwrap_or_else(|| on_surface.opacity(0.06)),
60 active_container: self
61 .active_container
62 .unwrap_or_else(|| on_surface.opacity(0.06)),
63 invalid_container: self
64 .invalid_container
65 .unwrap_or_else(|| on_surface.opacity(0.06)),
66 border: self.border.unwrap_or_else(|| on_surface.opacity(0.12)),
67 active_border: self
68 .active_border
69 .unwrap_or_else(|| on_surface.opacity(0.12)),
70 invalid_border: self
71 .invalid_border
72 .unwrap_or_else(|| on_surface.opacity(0.12)),
73 content: self.content.unwrap_or_else(|| on_surface.opacity(0.38)),
74 active_content: self
75 .active_content
76 .unwrap_or_else(|| on_surface.opacity(0.38)),
77 invalid_content: self
78 .invalid_content
79 .unwrap_or_else(|| on_surface.opacity(0.38)),
80 hover_tint: gpui::transparent_black(),
81 ring,
82 };
83 }
84
85 ResolvedPalette {
86 container: self
87 .container
88 .unwrap_or_else(|| role(SurfaceContainerLowest)),
89 active_container: self
90 .active_container
91 .unwrap_or_else(|| role(PrimaryContainer)),
92 invalid_container: self
93 .invalid_container
94 .unwrap_or_else(|| role(ErrorContainer)),
95 border: self.border.unwrap_or_else(|| role(OutlineVariant)),
96 active_border: self.active_border.unwrap_or_else(|| role(Primary)),
97 invalid_border: self.invalid_border.unwrap_or_else(|| role(Error)),
98 content: self.content.unwrap_or_else(|| role(OnSurfaceVariant)),
99 active_content: self
100 .active_content
101 .unwrap_or_else(|| role(OnPrimaryContainer)),
102 invalid_content: self
103 .invalid_content
104 .unwrap_or_else(|| role(OnErrorContainer)),
105 hover_tint: role(OnSurface).opacity(StateLayer::Hover.opacity()),
106 ring,
107 }
108 }
109}
110
111#[derive(IntoElement)]
114pub struct DropTarget<T: 'static = ExternalPaths> {
115 id: ElementId,
116 title: Option<SharedString>,
117 supporting: Option<SharedString>,
118 icon: Option<AnyElement>,
119 content: Option<AnyElement>,
120 shape: CornerShape,
121 colors: DropTargetColors,
122 disabled: bool,
123 can_drop: Option<DropPredicate<T>>,
124 on_drop: Option<DropHandler<T>>,
125 on_activate: Option<ActivateHandler>,
126 accessible_label: Option<SharedString>,
127 focus: Option<FocusHandle>,
128 source: Option<Entity<InteractionSource>>,
129 _payload: PhantomData<fn(&T)>,
130}
131
132impl DropTarget<ExternalPaths> {
133 pub fn files(id: impl Into<ElementId>) -> Self {
135 Self::new(id)
136 }
137}
138
139impl<T: 'static> DropTarget<T> {
140 pub fn new(id: impl Into<ElementId>) -> Self {
142 Self {
143 id: id.into(),
144 title: None,
145 supporting: None,
146 icon: None,
147 content: None,
148 shape: CornerRole::Large.shape(),
149 colors: DropTargetColors::default(),
150 disabled: false,
151 can_drop: None,
152 on_drop: None,
153 on_activate: None,
154 accessible_label: None,
155 focus: None,
156 source: None,
157 _payload: PhantomData,
158 }
159 }
160
161 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
163 self.title = Some(title.into());
164 self
165 }
166
167 pub fn supporting(mut self, supporting: impl Into<SharedString>) -> Self {
169 self.supporting = Some(supporting.into());
170 self
171 }
172
173 pub fn icon(mut self, icon: impl IntoElement) -> Self {
175 self.icon = Some(icon.into_any_element());
176 self
177 }
178
179 pub fn content(mut self, content: impl IntoElement) -> Self {
181 self.content = Some(content.into_any_element());
182 self
183 }
184
185 pub fn shape(mut self, shape: CornerShape) -> Self {
187 self.shape = shape;
188 self
189 }
190
191 pub fn colors(mut self, colors: DropTargetColors) -> Self {
193 self.colors = colors;
194 self
195 }
196
197 pub fn disabled(mut self, disabled: bool) -> Self {
199 self.disabled = disabled;
200 self
201 }
202
203 pub fn can_drop(
206 mut self,
207 predicate: impl Fn(&T, &mut Window, &mut App) -> bool + 'static,
208 ) -> Self {
209 self.can_drop = Some(Rc::new(predicate));
210 self
211 }
212
213 pub fn on_drop(mut self, handler: impl Fn(&T, &mut Window, &mut App) + 'static) -> Self {
215 self.on_drop = Some(Rc::new(handler));
216 self
217 }
218
219 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
221 self.on_activate = Some(Rc::new(handler));
222 self
223 }
224
225 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
227 self.accessible_label = Some(label.into());
228 self
229 }
230
231 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
233 self.focus = Some(focus.clone());
234 self
235 }
236
237 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
239 self.source = Some(source.clone());
240 self
241 }
242}
243
244fn apply_corner_shape<E: Styled>(element: E, shape: CornerShape, direction: Direction) -> E {
245 if shape == CornerShape::Full {
246 element.rounded_full()
247 } else {
248 let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, direction);
249 element
250 .rounded_tl(px(tl))
251 .rounded_tr(px(tr))
252 .rounded_br(px(br))
253 .rounded_bl(px(bl))
254 }
255}
256
257impl<T: 'static> RenderOnce for DropTarget<T> {
258 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
259 let theme = current_material_theme(window, cx);
260 let direction = theme.layout.direction;
261 let palette = self.colors.resolve(self.disabled, window, cx);
262 let accessible_name = self
263 .accessible_label
264 .or_else(|| self.title.clone())
265 .unwrap_or_else(|| "Drop target".into());
266 let actionable = self.on_activate.is_some();
267 let enabled = !self.disabled;
268 let focus = self.focus.filter(|_| actionable).unwrap_or_else(|| {
269 window
270 .use_keyed_state((self.id.clone(), "drop-target-focus"), cx, |_, cx| {
271 cx.focus_handle()
272 })
273 .read(cx)
274 .clone()
275 });
276 let feedback = ripple_state(&self.id, actionable && enabled, window, cx);
277 let tracker = self
278 .source
279 .as_ref()
280 .map(|source| InteractionSource::track(source, &self.id, window, cx));
281 feedback
282 .borrow_mut()
283 .track(enabled, &focus, tracker, 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.title.unwrap_or_else(|| "Drop files here".into());
292 div()
293 .w_full()
294 .min_h(px(120.))
295 .p(px(24.))
296 .flex()
297 .flex_col()
298 .items_center()
299 .justify_center()
300 .gap(px(8.))
301 .child(div().text_size(px(28.)).child(icon))
302 .child(
303 Text::new(title)
304 .id("drop-target-title")
305 .role(TypeRole::TitleMedium)
306 .wrap(),
307 )
308 .children(self.supporting.map(|text| {
309 Text::new(text)
310 .id("drop-target-supporting")
311 .role(TypeRole::BodyMedium)
312 .wrap()
313 }))
314 .into_any_element()
315 }
316 };
317
318 let body = if let Some(on_activate) = self.on_activate {
319 let on_activate = Rc::new(ThemeScope::bind_action(
320 move |window, cx| on_activate(window, cx),
321 window,
322 cx,
323 ));
324 let click_handler = on_activate.clone();
325 let a11y_handler = on_activate;
326 let press = feedback.clone();
327 let hover_tint = palette.hover_tint;
328 let ring = palette.ring;
329 apply_corner_shape(
330 BaseButton::new((self.id.clone(), "activate"))
331 .track_focus(&focus)
332 .tab_stop(enabled)
333 .disabled(self.disabled)
334 .w_full()
335 .accessibility_label(accessible_name)
336 .border_2()
337 .border_color(gpui::transparent_black()),
338 self.shape,
339 direction,
340 )
341 .when(enabled, |button| {
342 feedback_target(button, feedback, true, Some(focus.clone()))
343 .hover(move |style| style.bg(hover_tint))
344 .focus_visible(move |style| style.border_color(ring))
345 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
346 a11y_handler(window, cx);
347 })
348 .on_click(move |event, window, cx| {
349 if matches!(event, ClickEvent::Mouse(_)) && cx.has_active_drag() {
350 return;
351 }
352 cx.stop_propagation();
353 activate_feedback(event, &press, window, cx);
354 click_handler(window, cx);
355 })
356 })
357 .child(inner_content)
358 .into_any_element()
359 } else {
360 div()
361 .id((self.id.clone(), "body"))
362 .test_support()
363 .w_full()
364 .role(Role::Region)
365 .aria_label(accessible_name)
366 .child(inner_content)
367 .into_any_element()
368 };
369
370 let visual_can_drop = self.can_drop.clone();
373 let drop_can_drop = self.can_drop;
374 let on_drop = self.on_drop;
375
376 let receiver = div()
377 .id((self.id.clone(), "receiver"))
378 .test_support()
379 .w_full()
380 .when(!self.disabled, |receiver| {
381 let check = drop_can_drop;
382 receiver
383 .can_drop(move |any, window, cx| {
384 any.downcast_ref::<T>().is_some_and(|payload| {
385 check
386 .as_ref()
387 .is_none_or(|predicate| predicate(payload, window, cx))
388 })
389 })
390 .on_drop::<T>(move |payload, window, cx| {
391 if let Some(handler) = &on_drop {
392 handler(payload, window, cx);
393 }
394 })
395 })
396 .child(body);
397
398 apply_corner_shape(
399 div()
400 .id(self.id)
401 .test_support()
402 .w_full()
403 .overflow_hidden()
404 .bg(palette.container)
405 .border_2()
406 .border_dashed()
407 .border_color(palette.border)
408 .text_color(palette.content),
409 self.shape,
410 direction,
411 )
412 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
413 .when(!self.disabled, move |surface| {
414 surface.drag_over::<T>(move |style, payload, window, cx| {
415 let accepted = visual_can_drop
416 .as_ref()
417 .is_none_or(|predicate| predicate(payload, window, cx));
418 if accepted {
419 style
420 .bg(palette.active_container)
421 .border_color(palette.active_border)
422 .text_color(palette.active_content)
423 } else {
424 style
425 .bg(palette.invalid_container)
426 .border_color(palette.invalid_border)
427 .text_color(palette.invalid_content)
428 }
429 })
430 })
431 .child(receiver)
432 }
433}