1use std::{marker::PhantomData, rc::Rc};
2
3use gpui::{
4 AccessibleAction, AnyElement, App, ClickEvent, ElementId, ExternalPaths, Hsla,
5 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::{color, current_material_theme};
10use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, StateLayer, TypeRole};
11
12use crate::{Icon, IconName, Text};
13
14type DropPredicate<T> = Rc<dyn Fn(&T, &mut Window, &mut App) -> bool>;
15type DropHandler<T> = Rc<dyn Fn(&T, &mut Window, &mut App)>;
16type ActivateHandler = Rc<dyn Fn(&mut Window, &mut App)>;
17
18#[derive(Clone, Copy, Debug, Default, PartialEq)]
20pub struct DropTargetColors {
21 pub container: Option<Hsla>,
22 pub active_container: Option<Hsla>,
23 pub invalid_container: Option<Hsla>,
24 pub border: Option<Hsla>,
25 pub active_border: Option<Hsla>,
26 pub invalid_border: Option<Hsla>,
27 pub content: Option<Hsla>,
28 pub active_content: Option<Hsla>,
29 pub invalid_content: Option<Hsla>,
30}
31
32#[derive(Clone, Copy)]
33struct ResolvedPalette {
34 container: Hsla,
35 active_container: Hsla,
36 invalid_container: Hsla,
37 border: Hsla,
38 active_border: Hsla,
39 invalid_border: Hsla,
40 content: Hsla,
41 active_content: Hsla,
42 invalid_content: Hsla,
43 hover_tint: Hsla,
44 ring: Hsla,
45}
46
47impl DropTargetColors {
48 fn resolve(self, disabled: bool, window: &Window, cx: &App) -> ResolvedPalette {
49 use ColorRole::*;
50 let theme = current_material_theme(window, cx);
51 let role = |r| color(theme.colors.color(r));
52 let on_surface = role(OnSurface);
53 let ring = role(Secondary);
54 if disabled {
55 return ResolvedPalette {
56 container: self.container.unwrap_or_else(|| on_surface.opacity(0.06)),
57 active_container: self
58 .active_container
59 .unwrap_or_else(|| on_surface.opacity(0.06)),
60 invalid_container: self
61 .invalid_container
62 .unwrap_or_else(|| on_surface.opacity(0.06)),
63 border: self.border.unwrap_or_else(|| on_surface.opacity(0.12)),
64 active_border: self
65 .active_border
66 .unwrap_or_else(|| on_surface.opacity(0.12)),
67 invalid_border: self
68 .invalid_border
69 .unwrap_or_else(|| on_surface.opacity(0.12)),
70 content: self.content.unwrap_or_else(|| on_surface.opacity(0.38)),
71 active_content: self
72 .active_content
73 .unwrap_or_else(|| on_surface.opacity(0.38)),
74 invalid_content: self
75 .invalid_content
76 .unwrap_or_else(|| on_surface.opacity(0.38)),
77 hover_tint: gpui::transparent_black(),
78 ring,
79 };
80 }
81
82 ResolvedPalette {
83 container: self
84 .container
85 .unwrap_or_else(|| role(SurfaceContainerLowest)),
86 active_container: self
87 .active_container
88 .unwrap_or_else(|| role(PrimaryContainer)),
89 invalid_container: self
90 .invalid_container
91 .unwrap_or_else(|| role(ErrorContainer)),
92 border: self.border.unwrap_or_else(|| role(OutlineVariant)),
93 active_border: self.active_border.unwrap_or_else(|| role(Primary)),
94 invalid_border: self.invalid_border.unwrap_or_else(|| role(Error)),
95 content: self.content.unwrap_or_else(|| role(OnSurfaceVariant)),
96 active_content: self
97 .active_content
98 .unwrap_or_else(|| role(OnPrimaryContainer)),
99 invalid_content: self
100 .invalid_content
101 .unwrap_or_else(|| role(OnErrorContainer)),
102 hover_tint: role(OnSurface).opacity(StateLayer::Hover.opacity()),
103 ring,
104 }
105 }
106}
107
108#[derive(IntoElement)]
111pub struct DropTarget<T: 'static = ExternalPaths> {
112 id: ElementId,
113 title: Option<SharedString>,
114 supporting: Option<SharedString>,
115 icon: Option<AnyElement>,
116 content: Option<AnyElement>,
117 shape: CornerShape,
118 colors: DropTargetColors,
119 disabled: bool,
120 can_drop: Option<DropPredicate<T>>,
121 on_drop: Option<DropHandler<T>>,
122 on_activate: Option<ActivateHandler>,
123 accessible_label: Option<SharedString>,
124 _payload: PhantomData<fn(&T)>,
125}
126
127impl DropTarget<ExternalPaths> {
128 pub fn files(id: impl Into<ElementId>) -> Self {
130 Self::new(id)
131 }
132}
133
134impl<T: 'static> DropTarget<T> {
135 pub fn new(id: impl Into<ElementId>) -> Self {
137 Self {
138 id: id.into(),
139 title: None,
140 supporting: None,
141 icon: None,
142 content: None,
143 shape: CornerRole::Large.shape(),
144 colors: DropTargetColors::default(),
145 disabled: false,
146 can_drop: None,
147 on_drop: None,
148 on_activate: None,
149 accessible_label: None,
150 _payload: PhantomData,
151 }
152 }
153
154 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
156 self.title = Some(title.into());
157 self
158 }
159
160 pub fn supporting(mut self, supporting: impl Into<SharedString>) -> Self {
162 self.supporting = Some(supporting.into());
163 self
164 }
165
166 pub fn icon(mut self, icon: impl IntoElement) -> Self {
168 self.icon = Some(icon.into_any_element());
169 self
170 }
171
172 pub fn content(mut self, content: impl IntoElement) -> Self {
174 self.content = Some(content.into_any_element());
175 self
176 }
177
178 pub fn shape(mut self, shape: CornerShape) -> Self {
180 self.shape = shape;
181 self
182 }
183
184 pub fn colors(mut self, colors: DropTargetColors) -> Self {
186 self.colors = colors;
187 self
188 }
189
190 pub fn disabled(mut self, disabled: bool) -> Self {
192 self.disabled = disabled;
193 self
194 }
195
196 pub fn can_drop(
199 mut self,
200 predicate: impl Fn(&T, &mut Window, &mut App) -> bool + 'static,
201 ) -> Self {
202 self.can_drop = Some(Rc::new(predicate));
203 self
204 }
205
206 pub fn on_drop(mut self, handler: impl Fn(&T, &mut Window, &mut App) + 'static) -> Self {
208 self.on_drop = Some(Rc::new(handler));
209 self
210 }
211
212 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
214 self.on_activate = Some(Rc::new(handler));
215 self
216 }
217
218 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
220 self.accessible_label = Some(label.into());
221 self
222 }
223}
224
225impl<T: 'static> RenderOnce for DropTarget<T> {
226 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
227 let theme = current_material_theme(window, cx);
228 let direction = theme.layout.direction;
229 let palette = self.colors.resolve(self.disabled, window, cx);
230 let [tl, tr, br, bl] = self.shape.radii(240., 120., direction).map(px);
231 let accessible_name = self
232 .accessible_label
233 .or_else(|| self.title.clone())
234 .unwrap_or_else(|| "Drop target".into());
235
236 let inner_content = match self.content {
237 Some(content) => div().w_full().child(content).into_any_element(),
238 None => {
239 let icon = self
240 .icon
241 .unwrap_or_else(|| Icon::new(IconName::Add).size(px(28.)).into_any_element());
242 let title = self.title.unwrap_or_else(|| "Drop files here".into());
243 div()
244 .w_full()
245 .min_h(px(120.))
246 .p(px(24.))
247 .flex()
248 .flex_col()
249 .items_center()
250 .justify_center()
251 .gap(px(8.))
252 .child(div().text_size(px(28.)).child(icon))
253 .child(
254 Text::new(title)
255 .id("drop-target-title")
256 .role(TypeRole::TitleMedium)
257 .wrap(),
258 )
259 .children(self.supporting.map(|text| {
260 Text::new(text)
261 .id("drop-target-supporting")
262 .role(TypeRole::BodyMedium)
263 .wrap()
264 }))
265 .into_any_element()
266 }
267 };
268
269 let body = if let Some(on_activate) = self.on_activate.filter(|_| !self.disabled) {
270 let click_handler = on_activate.clone();
271 let a11y_handler = on_activate;
272 let hover_tint = palette.hover_tint;
273 let ring = palette.ring;
274 BaseButton::new((self.id.clone(), "activate"))
275 .w_full()
276 .accessibility_label(accessible_name)
277 .rounded_tl(tl)
278 .rounded_tr(tr)
279 .rounded_br(br)
280 .rounded_bl(bl)
281 .border_2()
282 .border_color(gpui::transparent_black())
283 .hover(move |style| style.bg(hover_tint))
284 .focus_visible(move |style| style.border_color(ring))
285 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
286 a11y_handler(window, cx);
287 })
288 .on_click(move |event, window, cx| {
289 if matches!(event, ClickEvent::Mouse(_)) && cx.has_active_drag() {
290 return;
291 }
292 cx.stop_propagation();
293 click_handler(window, cx);
294 })
295 .child(inner_content)
296 .into_any_element()
297 } else {
298 div()
299 .id((self.id.clone(), "body"))
300 .test_support()
301 .w_full()
302 .role(Role::Region)
303 .aria_label(accessible_name)
304 .child(inner_content)
305 .into_any_element()
306 };
307
308 let visual_can_drop = self.can_drop.clone();
311 let drop_can_drop = self.can_drop;
312 let on_drop = self.on_drop;
313
314 let receiver = div()
315 .id((self.id.clone(), "receiver"))
316 .test_support()
317 .w_full()
318 .when(!self.disabled, |receiver| {
319 let check = drop_can_drop;
320 receiver
321 .can_drop(move |any, window, cx| {
322 any.downcast_ref::<T>().is_some_and(|payload| {
323 check
324 .as_ref()
325 .is_none_or(|predicate| predicate(payload, window, cx))
326 })
327 })
328 .on_drop::<T>(move |payload, window, cx| {
329 if let Some(handler) = &on_drop {
330 handler(payload, window, cx);
331 }
332 })
333 })
334 .child(body);
335
336 div()
337 .id(self.id)
338 .test_support()
339 .w_full()
340 .overflow_hidden()
341 .rounded_tl(tl)
342 .rounded_tr(tr)
343 .rounded_br(br)
344 .rounded_bl(bl)
345 .bg(palette.container)
346 .border_2()
347 .border_dashed()
348 .border_color(palette.border)
349 .text_color(palette.content)
350 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
351 .when(!self.disabled, move |surface| {
352 surface.drag_over::<T>(move |style, payload, window, cx| {
353 let accepted = visual_can_drop
354 .as_ref()
355 .is_none_or(|predicate| predicate(payload, window, cx));
356 if accepted {
357 style
358 .bg(palette.active_container)
359 .border_color(palette.active_border)
360 .text_color(palette.active_content)
361 } else {
362 style
363 .bg(palette.invalid_container)
364 .border_color(palette.invalid_border)
365 .text_color(palette.invalid_content)
366 }
367 })
368 })
369 .child(receiver)
370 }
371}