ailloli_ui_widgets/controls/
upload_dropzone.rs

1//! Retained file dropzone with browse and filtered-drop callbacks.
2
3use std::rc::Rc;
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
6use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
7use ailloli_ui_core::event::{Event, FileEvent};
8use ailloli_ui_core::geometry::{Constraints, Rect, Size};
9use ailloli_ui_core::style::{
10    Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
11};
12use ailloli_ui_core::{Color, FontId, TextStyle, Theme, UploadAccept, UploadFile};
13use ailloli_ui_runtime::component::{
14    Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
15};
16use ailloli_ui_runtime::input::{ClickAction, EventCtx, FocusPolicy, IntoClickAction};
17use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
18use ailloli_ui_runtime::scene::PaintCtx;
19use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawRRect, DrawText};
20use ailloli_ui_text::{TextLayoutParams, WrapMode};
21
22/// Shared callback receiving accepted files in producer order.
23type UploadDropHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, Vec<UploadFile>)>;
24
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26/// Built-in density choices for an [`UploadDropzone`].
27///
28/// # Examples
29///
30/// ```
31/// use ailloli_ui_widgets::controls::UploadDropzoneVariant;
32/// assert_eq!(UploadDropzoneVariant::default(), UploadDropzoneVariant::Default);
33/// ```
34pub enum UploadDropzoneVariant {
35    /// `260 × 104` logical pixels with smaller typography and button.
36    Compact,
37    /// `360 × 142` logical pixels with standard typography and button.
38    #[default]
39    Default,
40}
41
42#[derive(Clone, Debug, PartialEq)]
43/// Resolved paint, typography, and intrinsic geometry for a dropzone.
44///
45/// `shadows` is retained for style compatibility but is not currently painted.
46/// Dimensions are logical pixels and are otherwise accepted as-is.
47///
48/// # Examples
49///
50/// ```
51/// use ailloli_ui_core::Theme;
52/// use ailloli_ui_widgets::controls::{UploadDropzoneStyle, UploadDropzoneVariant};
53/// let style = UploadDropzoneStyle::from_theme(Theme::dark(), UploadDropzoneVariant::Compact);
54/// assert_eq!((style.width, style.height), (260.0, 104.0));
55/// assert_eq!(style.button_height, 28.0);
56/// ```
57pub struct UploadDropzoneStyle {
58    /// Idle background fill.
59    pub background: Color,
60    /// Background fill while at least one dragged file is accepted.
61    pub background_hovered: Color,
62    /// Idle border.
63    pub border: Border,
64    /// Border while an accepted dragged file is over the bounds.
65    pub border_hovered: Border,
66    /// Border used while the enabled dropzone has focus.
67    pub focus_ring: Border,
68    /// Browse-button fill.
69    pub button_background: Color,
70    /// Browse-button label style.
71    pub button_text: TextStyle,
72    /// Primary title style.
73    pub title_text: TextStyle,
74    /// Secondary description style.
75    pub description_text: TextStyle,
76    /// Replacement alpha for disabled fills and text colors.
77    pub disabled_opacity: f32,
78    /// Reserved shadows; currently not painted.
79    pub shadows: Vec<BoxShadow>,
80    /// Intrinsic width in logical pixels.
81    pub width: f32,
82    /// Intrinsic height in logical pixels.
83    pub height: f32,
84    /// Dropzone border radius.
85    pub radius: Radius,
86    /// Browse-button height in logical pixels; its width is fixed at 116.
87    pub button_height: f32,
88}
89
90impl Default for UploadDropzoneStyle {
91    fn default() -> Self {
92        Self::from_theme(Theme::default(), UploadDropzoneVariant::Default)
93    }
94}
95
96impl UploadDropzoneStyle {
97    /// Resolves `variant` through `theme` into concrete style values.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// use ailloli_ui_core::Theme;
103    /// use ailloli_ui_widgets::controls::{UploadDropzoneStyle, UploadDropzoneVariant};
104    /// let style = UploadDropzoneStyle::from_theme(Theme::dark(), UploadDropzoneVariant::Default);
105    /// assert_eq!((style.width, style.height), (360.0, 142.0));
106    /// assert_eq!(style.disabled_opacity, 0.45);
107    /// ```
108    pub fn from_theme(theme: Theme, variant: UploadDropzoneVariant) -> Self {
109        let palette = theme.palette();
110        let compact = variant == UploadDropzoneVariant::Compact;
111        Self {
112            background: palette.surface,
113            background_hovered: palette.accent.with_alpha(0.12),
114            border: Border::new(1.0, palette.border),
115            border_hovered: Border::new(1.0, palette.accent),
116            focus_ring: Border::new(2.0, palette.focus),
117            button_background: palette.accent,
118            button_text: TextStyle::new(FontId::Ui, if compact { 12 } else { 13 }, Color::WHITE),
119            title_text: TextStyle::new(FontId::Ui, if compact { 13 } else { 15 }, palette.text),
120            description_text: TextStyle::new(
121                FontId::Ui,
122                if compact { 11 } else { 12 },
123                palette.text_muted,
124            ),
125            disabled_opacity: 0.45,
126            shadows: Vec::new(),
127            width: if compact { 260.0 } else { 360.0 },
128            height: if compact { 104.0 } else { 142.0 },
129            radius: Radius::uniform(theme.radius().md),
130            button_height: if compact { 28.0 } else { 32.0 },
131        }
132    }
133}
134
135/// A file drop target with reactive labels and caller-owned actions.
136///
137/// Dragged files are filtered using [`UploadAccept`]. With `multiple(false)`,
138/// only the first accepted file in producer order reaches the drop handler.
139/// Empty accepted sets do not invoke it. The browse button merely runs the
140/// installed action; opening a native picker remains the consumer's job.
141///
142/// # Examples
143///
144/// ```
145/// use ailloli_ui_widgets::controls::UploadDropzone;
146/// let dropzone: UploadDropzone<()> = UploadDropzone::new().accept([".png", "image/*"]);
147/// let _ = dropzone;
148/// ```
149pub struct UploadDropzone<A = ()> {
150    /// Layout configuration used to resolve intrinsic size.
151    pub(crate) layout: LayoutStyle,
152    /// Flex-item behavior used by the parent layout.
153    pub(crate) flex_item: FlexItemStyle,
154    /// Live primary label.
155    title: Binding<String>,
156    /// Live secondary label.
157    description: Binding<String>,
158    /// Live disabled state.
159    disabled: Binding<bool>,
160    /// Whether a drop may deliver every accepted file instead of only the first.
161    multiple: bool,
162    /// Normalized accepted extension and MIME patterns.
163    accept: UploadAccept,
164    /// Resolved paint and geometry configuration.
165    style: UploadDropzoneStyle,
166    /// Optional action run by a left-button release inside the browse button.
167    on_browse: Option<Rc<ClickAction<A>>>,
168    /// Optional callback receiving non-empty accepted drops.
169    on_drop: Option<UploadDropHandler<A>>,
170}
171
172crate::impl_layout_builders!(UploadDropzone);
173
174impl<A: 'static> Default for UploadDropzone<A> {
175    fn default() -> Self {
176        Self::new()
177    }
178}
179
180impl<A: 'static> UploadDropzone<A> {
181    /// Creates a single-file dropzone accepting every file.
182    ///
183    /// It starts enabled with default English labels and no callbacks. Without
184    /// callbacks it is not focusable, though it still paints drag-hover state.
185    ///
186    /// # Examples
187    ///
188    /// ```
189    /// use ailloli_ui_widgets::controls::UploadDropzone;
190    /// let dropzone: UploadDropzone<()> = UploadDropzone::new();
191    /// let _ = dropzone;
192    /// ```
193    pub fn new() -> Self {
194        Self {
195            layout: LayoutStyle::default(),
196            flex_item: FlexItemStyle::default(),
197            title: Binding::Static("Drag & drop files here".to_string()),
198            description: Binding::Static("or browse files".to_string()),
199            disabled: Binding::Static(false),
200            multiple: false,
201            accept: UploadAccept::default(),
202            style: UploadDropzoneStyle::default(),
203            on_browse: None,
204            on_drop: None,
205        }
206    }
207
208    /// Replaces the static or reactive primary label.
209    ///
210    /// Empty text is valid and simply produces no visible glyphs.
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// use ailloli_ui_widgets::controls::UploadDropzone;
216    /// let dropzone: UploadDropzone<()> = UploadDropzone::new().title("Drop images here");
217    /// let _ = dropzone;
218    /// ```
219    pub fn title(mut self, value: impl Into<Binding<String>>) -> Self {
220        self.title = value.into();
221        self
222    }
223
224    /// Replaces the static or reactive secondary label.
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// use ailloli_ui_widgets::controls::UploadDropzone;
230    /// let dropzone: UploadDropzone<()> = UploadDropzone::new().description("PNG or JPEG");
231    /// let _ = dropzone;
232    /// ```
233    pub fn description(mut self, value: impl Into<Binding<String>>) -> Self {
234        self.description = value.into();
235        self
236    }
237
238    /// Sets a static or reactive disabled binding.
239    ///
240    /// Disabled dropzones ignore pointer and file events, are not focusable,
241    /// clear hover visually, and apply the style's disabled alpha.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// use ailloli_ui_widgets::controls::UploadDropzone;
247    /// let dropzone: UploadDropzone<()> = UploadDropzone::new().disabled(true);
248    /// let _ = dropzone;
249    /// ```
250    pub fn disabled(mut self, value: impl Into<Binding<bool>>) -> Self {
251        self.disabled = value.into();
252        self
253    }
254
255    /// Controls whether a drop delivers all accepted files.
256    ///
257    /// `false` (the default) truncates the filtered list to one; `true` keeps
258    /// every accepted file in the producer's original order.
259    ///
260    /// # Examples
261    ///
262    /// ```
263    /// use ailloli_ui_widgets::controls::UploadDropzone;
264    /// let dropzone: UploadDropzone<()> = UploadDropzone::new().multiple(true);
265    /// let _ = dropzone;
266    /// ```
267    pub fn multiple(mut self, value: bool) -> Self {
268        self.multiple = value;
269        self
270    }
271
272    /// Replaces accepted extension and MIME patterns.
273    ///
274    /// Supported forms are `.ext`, exact MIME values, and top-level wildcards
275    /// such as `image/*`; matching behavior is defined by [`UploadAccept`]. An
276    /// empty iterator accepts every file. This filter applies to drag events;
277    /// the browse action receives no automatic native-picker configuration.
278    ///
279    /// # Examples
280    ///
281    /// ```
282    /// use ailloli_ui_widgets::controls::UploadDropzone;
283    /// let dropzone: UploadDropzone<()> = UploadDropzone::new().accept([".pdf", "image/*"]);
284    /// let _ = dropzone;
285    /// ```
286    pub fn accept(mut self, patterns: impl IntoIterator<Item = impl Into<String>>) -> Self {
287        self.accept = UploadAccept::new(patterns);
288        self
289    }
290
291    /// Replaces the complete resolved style without clamping its values.
292    ///
293    /// # Examples
294    ///
295    /// ```
296    /// use ailloli_ui_core::Theme;
297    /// use ailloli_ui_widgets::controls::{UploadDropzone, UploadDropzoneStyle, UploadDropzoneVariant};
298    /// let style = UploadDropzoneStyle::from_theme(Theme::dark(), UploadDropzoneVariant::Compact);
299    /// let dropzone: UploadDropzone<()> = UploadDropzone::new().upload_style(style);
300    /// let _ = dropzone;
301    /// ```
302    pub fn upload_style(mut self, style: UploadDropzoneStyle) -> Self {
303        self.style = style;
304        self
305    }
306
307    /// Replaces the complete style with the default-theme `variant`.
308    ///
309    /// This discards any previously customized style values. Explicit layout
310    /// width and height builders may still override its intrinsic dimensions.
311    ///
312    /// # Examples
313    ///
314    /// ```
315    /// use ailloli_ui_widgets::controls::{UploadDropzone, UploadDropzoneVariant};
316    /// let dropzone: UploadDropzone<()> =
317    ///     UploadDropzone::new().upload_variant(UploadDropzoneVariant::Compact);
318    /// let _ = dropzone;
319    /// ```
320    pub fn upload_variant(mut self, variant: UploadDropzoneVariant) -> Self {
321        self.style = UploadDropzoneStyle::from_theme(Theme::default(), variant);
322        self
323    }
324
325    /// Installs the action run by a left-button release inside the browse button.
326    ///
327    /// A later call replaces the action. Keyboard activation is not currently
328    /// synthesized by this widget.
329    ///
330    /// # Examples
331    ///
332    /// ```
333    /// use ailloli_ui_widgets::controls::UploadDropzone;
334    /// #[derive(Clone)]
335    /// enum Action { Browse }
336    /// let dropzone = UploadDropzone::new().on_browse(Action::Browse);
337    /// let _ = dropzone;
338    /// ```
339    pub fn on_browse(mut self, action: impl IntoClickAction<A>) -> Self {
340        self.on_browse = Some(Rc::new(action.into_click_action()));
341        self
342    }
343
344    /// Maps accepted files to one action and dispatches it.
345    ///
346    /// The mapper runs only for a non-empty accepted drop inside the widget.
347    /// A later drop-handler builder replaces it.
348    ///
349    /// # Examples
350    ///
351    /// ```
352    /// use ailloli_ui_core::UploadFile;
353    /// use ailloli_ui_widgets::controls::UploadDropzone;
354    /// enum Action { Dropped(Vec<UploadFile>) }
355    /// let dropzone = UploadDropzone::new().on_drop(Action::Dropped);
356    /// let _ = dropzone;
357    /// ```
358    pub fn on_drop(mut self, f: impl Fn(Vec<UploadFile>) -> A + 'static) -> Self {
359        self.on_drop = Some(Rc::new(move |ctx, files| ctx.dispatch(f(files))));
360        self
361    }
362
363    /// Installs a context-aware handler for accepted files.
364    ///
365    /// The handler may dispatch zero or more actions and request runtime effects.
366    /// It runs only for a non-empty accepted drop and replaces any prior handler.
367    ///
368    /// # Examples
369    ///
370    /// ```
371    /// use ailloli_ui_widgets::controls::UploadDropzone;
372    /// let dropzone = UploadDropzone::<()>::new().on_drop_ctx(|ctx, files| {
373    ///     if !files.is_empty() { ctx.request_repaint(); }
374    /// });
375    /// let _ = dropzone;
376    /// ```
377    pub fn on_drop_ctx(mut self, f: impl Fn(&mut EventCtx<A>, Vec<UploadFile>) + 'static) -> Self {
378        self.on_drop = Some(Rc::new(f));
379        self
380    }
381}
382
383/// Component wrapper allocating retained hover state during reconciliation.
384struct UploadDropzoneComponent<A> {
385    /// Complete builder snapshot used to allocate retained hover state.
386    props: UploadDropzone<A>,
387}
388
389impl<A: 'static> ComponentNode<A> for UploadDropzoneComponent<A> {
390    fn build(&self, context: &mut Context<A>) -> View<A> {
391        View::leaf(UploadDropzoneWidget {
392            layout: self.props.layout,
393            title: self.props.title.clone(),
394            description: self.props.description.clone(),
395            disabled: self.props.disabled.clone(),
396            multiple: self.props.multiple,
397            accept: self.props.accept.clone(),
398            style: self.props.style.clone(),
399            on_browse: self.props.on_browse.clone(),
400            on_drop: self.props.on_drop.clone(),
401            hovering: context.signal(false),
402        })
403    }
404}
405
406impl<A: 'static> IntoView<A> for UploadDropzone<A> {
407    fn into_view(self) -> View<A> {
408        let flex_item = self.flex_item;
409        let hint = LayoutSizeHint::from_layout(self.layout);
410        finish_view_sized(
411            View::component(UploadDropzoneComponent { props: self }),
412            flex_item,
413            hint,
414        )
415    }
416}
417
418/// Retained leaf that filters file events and paints drop/browse affordances.
419struct UploadDropzoneWidget<A> {
420    /// Outer logical sizing policy.
421    layout: LayoutStyle,
422    /// Reactive primary instruction text.
423    title: Binding<String>,
424    /// Reactive secondary constraint text.
425    description: Binding<String>,
426    /// Reactive interaction-disable flag.
427    disabled: Binding<bool>,
428    /// Whether a drop may contain more than one file.
429    multiple: bool,
430    /// Accepted extension and MIME-style patterns.
431    accept: UploadAccept,
432    /// Surface colors and logical-pixel geometry.
433    style: UploadDropzoneStyle,
434    /// Optional browse action shared by pointer and keyboard activation.
435    on_browse: Option<Rc<ClickAction<A>>>,
436    /// Optional callback receiving validated dropped files.
437    on_drop: Option<UploadDropHandler<A>>,
438    /// Whether an accepted drag currently hovers the surface.
439    hovering: Signal<bool>,
440}
441
442impl<A: 'static> Widget<A> for UploadDropzoneWidget<A> {
443    fn debug_name(&self) -> &'static str {
444        "UploadDropzone"
445    }
446
447    fn layout(
448        &self,
449        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
450        _ctx: &mut LayoutCtx<'_>,
451        _children: &mut [LayoutChild],
452        constraints: Constraints,
453    ) -> LayoutResult {
454        let size = apply_layout_size(
455            Size::new(self.style.width, self.style.height),
456            self.layout,
457            constraints,
458        );
459        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
460        LayoutResult {
461            size,
462            children: Vec::new(),
463            paint_bounds,
464            visual_bounds: paint_bounds,
465            overlay_hit_bounds: Vec::new(),
466            clip: None,
467            is_window_root_clip: false,
468            artifact: None,
469        }
470    }
471
472    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
473        let disabled = self.disabled.read();
474        let hovering = self.hovering.read() && !disabled;
475        let mut bg = if hovering {
476            self.style.background_hovered
477        } else {
478            self.style.background
479        };
480        if disabled {
481            bg = bg.with_alpha(self.style.disabled_opacity);
482        }
483        ctx.push(DrawCmd::RRect(DrawRRect {
484            rect: bounds,
485            radius: self.style.radius.tl,
486            color: bg,
487        }));
488        ctx.push(DrawCmd::Border(DrawBorder {
489            rect: bounds,
490            radius: self.style.radius,
491            border: if ctx.is_focused() && !disabled {
492                self.style.focus_ring
493            } else if hovering {
494                self.style.border_hovered
495            } else {
496                self.style.border
497            },
498        }));
499
500        let title = self.title.read();
501        let description = self.description.read();
502        let title_style = if disabled {
503            TextStyle {
504                color: self
505                    .style
506                    .title_text
507                    .color
508                    .with_alpha(self.style.disabled_opacity),
509                ..self.style.title_text
510            }
511        } else {
512            self.style.title_text
513        };
514        let description_style = if disabled {
515            TextStyle {
516                color: self
517                    .style
518                    .description_text
519                    .color
520                    .with_alpha(self.style.disabled_opacity),
521                ..self.style.description_text
522            }
523        } else {
524            self.style.description_text
525        };
526        let center_x = bounds.x + bounds.w * 0.5;
527        push_text_centered(ctx, &title, center_x, bounds.y + 36.0, title_style);
528        push_text_centered(
529            ctx,
530            &description,
531            center_x,
532            bounds.y + 58.0,
533            description_style,
534        );
535
536        let button = self.button_rect(bounds);
537        ctx.push(DrawCmd::RRect(DrawRRect {
538            rect: button,
539            radius: 7.0,
540            color: if disabled {
541                self.style
542                    .button_background
543                    .with_alpha(self.style.disabled_opacity)
544            } else {
545                self.style.button_background
546            },
547        }));
548        push_text_centered(
549            ctx,
550            "Browse Files",
551            button.x + button.w * 0.5,
552            button.y + button.h * 0.5 + self.style.button_text.px_size as f32 * 0.35,
553            if disabled {
554                TextStyle {
555                    color: self
556                        .style
557                        .button_text
558                        .color
559                        .with_alpha(self.style.disabled_opacity),
560                    ..self.style.button_text
561                }
562            } else {
563                self.style.button_text
564            },
565        );
566    }
567
568    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
569        if self.disabled.read() {
570            return;
571        }
572        match event {
573            Event::Pointer(PointerEvent::Button {
574                pos,
575                button: MouseButton::Left,
576                pressed: false,
577                ..
578            }) if self.button_rect(bounds).contains(pos.x, pos.y) => {
579                if let Some(action) = &self.on_browse {
580                    action.run(ctx);
581                    ctx.stop_propagation();
582                }
583            }
584            Event::File(FileEvent::Hover { pos, files }) if bounds.contains(pos.x, pos.y) => {
585                let accepted = files.iter().any(|file| self.accept.accepts(file));
586                self.hovering.set(accepted);
587                ctx.request_repaint();
588                ctx.stop_propagation();
589            }
590            Event::File(FileEvent::HoverCancelled) if self.hovering.read() => {
591                self.hovering.set(false);
592                ctx.request_repaint();
593            }
594            Event::File(FileEvent::Drop { pos, files }) if bounds.contains(pos.x, pos.y) => {
595                self.hovering.set(false);
596                let mut accepted: Vec<UploadFile> = files
597                    .iter()
598                    .filter(|file| self.accept.accepts(file))
599                    .cloned()
600                    .collect();
601                if !self.multiple {
602                    accepted.truncate(1);
603                }
604                if !accepted.is_empty() {
605                    if let Some(on_drop) = &self.on_drop {
606                        on_drop(ctx, accepted);
607                        ctx.stop_propagation();
608                    }
609                }
610                ctx.request_repaint();
611            }
612            _ => {}
613        }
614    }
615
616    fn focus_policy(&self) -> FocusPolicy {
617        if self.disabled.read() || (self.on_browse.is_none() && self.on_drop.is_none()) {
618            FocusPolicy::NotFocusable
619        } else {
620            FocusPolicy::Focusable
621        }
622    }
623}
624
625impl<A> UploadDropzoneWidget<A> {
626    /// Returns the fixed-width browse button centered 18 pixels above the bottom.
627    fn button_rect(&self, bounds: Rect) -> Rect {
628        Rect::new(
629            bounds.x + (bounds.w - 116.0) * 0.5,
630            bounds.bottom() - self.style.button_height - 18.0,
631            116.0,
632            self.style.button_height,
633        )
634    }
635}
636
637/// Paints one unwrapped line centered at `center_x`, if a text system exists.
638fn push_text_centered(
639    ctx: &mut PaintCtx<'_>,
640    text: &str,
641    center_x: f32,
642    baseline_y: f32,
643    style: TextStyle,
644) {
645    let layout = ctx.text_system.as_deref_mut().map(|ts| {
646        ts.layout_cached(TextLayoutParams {
647            text,
648            style,
649            max_width: None,
650            wrap_mode: WrapMode::NoWrap,
651        })
652    });
653    if let Some(layout) = layout {
654        let x = center_x - layout.metrics.width * 0.5;
655        ctx.push(DrawCmd::Text(DrawText {
656            pos: [x, baseline_y],
657            color: style.color,
658            decoration: ailloli_ui_core::TextDecoration::None,
659            layout,
660        }));
661    }
662}