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