use std::sync::{Arc, Mutex};
use super::{
icons, names,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{IconChoice, fading, glyph, pressable, shown_icon},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::{Ctx, FutureAction},
events::{FileDragEvent, FileDropEvent},
theme::{OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::Column,
core::Signal,
files::{DroppedFile, FileDialog},
layout::{
Alignment,
layout_kind::Justify,
text_style::{FontWeight, TextAlign},
},
node::{CursorIcon, Element, border::Border as Edge, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DropZonePart {
Root,
Icon,
Text,
Title,
Description,
}
names!(DropZonePart {
Root => "root",
Icon => "icon",
Text => "text",
Title => "title",
Description => "description",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DropZoneState {
DragOver,
Rejected,
Invalid,
Disabled,
Icon,
Description,
}
names!(DropZoneState {
DragOver => "drag_over",
Rejected => "rejected",
Invalid => "invalid",
Disabled => "disabled",
Icon => "icon",
Description => "description",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RejectReason {
Kind,
TooLarge,
TooMany,
Folder,
Duplicate,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RejectedFile {
pub file: DroppedFile,
pub reason: RejectReason,
}
pub type DropZoneRenderer = Arc<dyn Fn(DropZoneView) -> Element + Send + Sync>;
type FilesHandler = Arc<dyn Fn(&[DroppedFile]) + Send + Sync>;
type RejectHandler = Arc<dyn Fn(&[RejectedFile]) + Send + Sync>;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Takes {
pub(crate) accept: Vec<Arc<str>>,
pub(crate) multiple: bool,
pub(crate) max_size: Option<u64>,
pub(crate) max_files: Option<usize>,
pub(crate) sources: Vec<crate::files::FileSource>,
}
impl Takes {
pub(crate) fn sort(
&self,
given: impl IntoIterator<Item = (DroppedFile, bool)>,
) -> (Vec<DroppedFile>, Vec<RejectedFile>) {
let room = match (self.multiple, self.max_files) {
(false, _) => 1,
(true, Some(max)) => max,
(true, None) => usize::MAX,
};
let (mut taken, mut rejected) = (Vec::new(), Vec::new());
for (file, is_folder) in given {
let reason = if is_folder {
Some(RejectReason::Folder)
} else if !file.is_accepted(&self.accept) {
Some(RejectReason::Kind)
} else if self
.max_size
.is_some_and(|max| file.size().is_some_and(|size| size > max))
{
Some(RejectReason::TooLarge)
} else if taken.len() >= room {
Some(RejectReason::TooMany)
} else {
None
};
match reason {
Some(reason) => rejected.push(RejectedFile { file, reason }),
None => taken.push(file),
}
}
(taken, rejected)
}
pub(crate) fn sort_dragged(&self, paths: &crate::app::events::DraggedPaths) -> (Vec<DroppedFile>, Vec<RejectedFile>) {
self.sort(
paths
.items()
.iter()
.map(|item| (DroppedFile::from_path(item.path()), item.is_folder())),
)
}
pub(crate) fn dialog(&self, title: &str) -> FileDialog {
let mut dialog = FileDialog::new()
.title(title)
.multiple(self.multiple && self.max_files != Some(1))
.sources(self.sources.iter().copied());
let mut extensions: Vec<String> = Vec::new();
for entry in &self.accept {
let entry = entry.trim().to_ascii_lowercase();
match entry.strip_suffix("/*") {
Some(name) => match crate::files::FileKind::named(name) {
Some(kind) => extensions.extend(kind.extensions().iter().map(|extension| (*extension).to_owned())),
None => return dialog,
},
None => extensions.push(entry.trim_start_matches('.').to_owned()),
}
}
if !extensions.is_empty() {
let names: Vec<&str> = self.accept.iter().map(|entry| entry.as_ref()).collect();
let extensions: Vec<&str> = extensions.iter().map(String::as_str).collect();
dialog = dialog.filter(&names.join(", "), &extensions);
}
dialog
}
}
#[derive(Clone)]
pub struct DropZone {
takes: Takes,
icon: Option<IconChoice>,
title: Arc<str>,
description: Option<Arc<str>>,
drop_text: Arc<str>,
reject_text: Arc<str>,
label: Option<Arc<str>>,
invalid: bool,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
on_files: Vec<FilesHandler>,
on_reject: Vec<RejectHandler>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
host: Option<Hosted>,
}
#[derive(Clone)]
pub(crate) struct Hosted {
pub(crate) over: Signal<Option<bool>>,
pub(crate) choose: Arc<dyn Fn(FileDialog) + Send + Sync>,
pub(crate) refocus: Arc<Mutex<Option<Refocus>>>,
pub(crate) focus: Option<(Refocus, crate::core::ElementRef)>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Refocus {
Control(Arc<str>),
Trigger,
}
impl Default for DropZone {
fn default() -> Self {
Self::new()
}
}
impl DropZone {
pub fn new() -> Self {
Self {
takes: Takes {
multiple: true,
..Takes::default()
},
icon: None,
title: super::current_locale().fields.drop_files.clone(),
description: Some(super::current_locale().fields.or_browse.clone()),
drop_text: super::current_locale().fields.drop_to_add.clone(),
reject_text: super::current_locale().fields.cannot_add.clone(),
label: None,
invalid: false,
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
on_files: Vec::new(),
on_reject: Vec::new(),
id: None,
key: None,
host: None,
}
}
pub fn accept<S: AsRef<str>>(mut self, accepted: impl IntoIterator<Item = S>) -> Self {
self
.takes
.accept
.extend(accepted.into_iter().map(|entry| Arc::from(entry.as_ref())));
self
}
pub fn multiple(mut self, multiple: bool) -> Self {
self.takes.multiple = multiple;
self
}
pub fn max_size(mut self, bytes: u64) -> Self {
self.takes.max_size = Some(bytes);
self
}
pub fn sources(mut self, sources: impl IntoIterator<Item = crate::files::FileSource>) -> Self {
self.takes.sources = sources.into_iter().collect();
self
}
pub fn max_files(mut self, max: usize) -> Self {
self.takes.max_files = Some(max);
self
}
pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn title(mut self, title: &str) -> Self {
self.title = Arc::from(title);
self
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn no_description(mut self) -> Self {
self.description = None;
self
}
pub fn drop_text(mut self, text: &str) -> Self {
self.drop_text = Arc::from(text);
self
}
pub fn reject_text(mut self, text: &str) -> Self {
self.reject_text = Arc::from(text);
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub(crate) fn named_by(self, field: &super::InField) -> Self {
if self.label.is_some() || field.label.is_empty() {
return self;
}
self.label(&field.label)
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_files(mut self, handler: impl Fn(&[DroppedFile]) + Send + Sync + 'static) -> Self {
self.on_files.push(Arc::new(handler));
self
}
pub fn on_reject(mut self, handler: impl Fn(&[RejectedFile]) + Send + Sync + 'static) -> Self {
self.on_reject.push(Arc::new(handler));
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub(crate) fn takes(&self) -> &Takes {
&self.takes
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
mount_files(self, ctx)
}
pub(crate) fn with_host(mut self, host: Option<Hosted>) -> Self {
self.host = host;
self
}
pub fn build(self, theme: &Theme) -> Element {
let over = self.host.as_ref().and_then(|host| host.over.get());
let icon = shown_icon(self.icon, icons::UPLOAD);
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(DropZoneState::DragOver, over == Some(true) && !self.disabled)
.state(DropZoneState::Rejected, over == Some(false) && !self.disabled)
.state(DropZoneState::Invalid, self.invalid)
.state(DropZoneState::Disabled, self.disabled)
.state(DropZoneState::Icon, icon.is_some())
.state(DropZoneState::Description, self.description.is_some());
let shown = |state: DropZoneState| case.states.contains(&Name::from(state));
let (drag_over, rejected) = (shown(DropZoneState::DragOver), shown(DropZoneState::Rejected));
let view = DropZoneView {
title: if drag_over {
self.drop_text.clone()
} else if rejected {
self.reject_text.clone()
} else {
self.title.clone()
},
description: if drag_over || rejected {
None
} else {
self.description.clone()
},
label: self.label.unwrap_or_else(|| self.title.clone()),
icon,
drag_over,
rejected,
invalid: self.invalid,
disabled: self.disabled,
recipe: theme
.resolve::<DropZone>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
forced: self.forced,
takes: self.takes,
on_files: self.on_files,
on_reject: self.on_reject,
host: self.host,
id: self.id,
key: self.key,
};
match theme.renderer::<DropZone>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<DropZone> for Element {
fn from(zone: DropZone) -> Self {
zone.build(¤t_theme())
}
}
pub struct DropZoneView {
pub title: Arc<str>,
pub description: Option<Arc<str>>,
pub label: Arc<str>,
pub icon: Option<Name>,
pub drag_over: bool,
pub rejected: bool,
pub invalid: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
takes: Takes,
on_files: Vec<FilesHandler>,
on_reject: Vec<RejectHandler>,
host: Option<Hosted>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl DropZoneView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn zone(&self) -> crate::components::Button {
let mut zone = pressable(&self.part(DropZonePart::Root), self.disabled)
.justify(Justify::Center)
.align_items(Alignment::Center)
.describe("a11y_role", "button")
.describe("a11y_name", self.label.clone());
if !self.disabled {
zone = self.hear_files(zone);
}
if let Some(id) = &self.id {
zone = zone.id(id.clone());
}
if let Some(key) = &self.key {
zone = zone.key(key.clone());
}
if let Some(Hosted {
focus: Some((Refocus::Trigger, element)),
..
}) = &self.host
{
zone = zone.ref_element(element.clone());
}
zone
}
fn hear_files(&self, zone: crate::components::Button) -> crate::components::Button {
let (takes, on_files, on_reject) = (self.takes.clone(), self.on_files.clone(), self.on_reject.clone());
let over = self.host.as_ref().map(|host| host.over.clone());
let mut zone = zone.on_file_drop({
let over = over.clone();
move |event: FileDropEvent| {
if let Some(over) = &over {
over.set(None);
}
let (taken, rejected) = takes.sort_dragged(&event.paths);
deliver(&on_files, &on_reject, &taken, &rejected);
}
});
if let Some(over) = over {
let takes = self.takes.clone();
zone = zone
.on_file_drag_enter({
let over = over.clone();
move |event: FileDragEvent| {
let (taken, _) = takes.sort_dragged(&event.paths);
if taken.is_empty() {
event.refuse();
}
over.set(Some(!taken.is_empty()));
}
})
.on_file_drag_leave(move || over.set(None));
}
if let Some(host) = &self.host {
let (choose, dialog) = (host.choose.clone(), self.takes.dialog(&self.label));
zone = zone.on_click(move |_| choose(dialog.clone()));
}
zone
}
pub fn icon(&self) -> Option<Element> {
let icon = self.icon?;
Some(glyph(&self.part(DropZonePart::Icon), icon, false))
}
pub fn text(&self) -> Column {
let fill = Dimension::Pct(100.0);
let line = |part: ResolvedPart, content: &str| {
Column::new()
.width(fill)
.align_items(Alignment::Center)
.part(&part)
.child(part.text(content).width(fill).text_align(TextAlign::Center))
};
let mut text = Column::new()
.width(fill)
.align_items(Alignment::Center)
.part(&self.part(DropZonePart::Text))
.child(line(self.part(DropZonePart::Title), &self.title));
if let Some(description) = &self.description {
text = text.child(line(self.part(DropZonePart::Description), description));
}
text
}
pub fn render(self) -> Element {
let gap = self.part(DropZonePart::Root).rest().gap.unwrap_or_default();
let mut column = Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.spacing(gap.resolve(&self.theme().spacing(), 0.0));
if let Some(icon) = self.icon() {
column = column.child(icon);
}
self.zone().child(column.child(self.text())).into()
}
}
pub(crate) fn deliver(
on_files: &[FilesHandler],
on_reject: &[RejectHandler],
taken: &[DroppedFile],
rejected: &[RejectedFile],
) {
if !taken.is_empty() {
for handler in on_files {
handler(taken);
}
}
if !rejected.is_empty() {
for handler in on_reject {
handler(rejected);
}
}
}
impl crate::ui::Styled for DropZone {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for DropZone {
const NAME: &'static str = "drop_zone";
type Renderer = DropZoneRenderer;
fn parts() -> crate::ui::Declared {
DropZonePart::declared()
}
fn states() -> crate::ui::Declared {
DropZoneState::declared()
}
fn recipe() -> Recipe {
use DropZonePart::{Description, Icon, Root, Text, Title};
use PaletteColor::*;
let edge = |width: f32, color: PaletteColor| Edge::inside(width, color);
Recipe::new()
.base(Root, |s| {
fading(
s.width(320.0)
.max_width(super::Length::Fill)
.min_height(140.0)
.padding_x(24.0)
.padding_y(16.0)
.gap(8.0)
.background(Muted)
.radius(RadiusSize::Lg)
.border(edge(1.5, Input))
.cursor(CursorIcon::Pointer),
)
})
.base(Icon, |s| s.square(20.0).foreground(MutedForeground))
.base(Text, |s| s.gap(4.0))
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(14.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.base(Description, |s| {
s.typography(TypographyStyle::Caption).foreground(MutedForeground)
})
.hovered(Root, |s| s.border(edge(1.5, Ring)))
.focus_visible(Root, |s| s.focus_ring())
.state(DropZoneState::Invalid, Root, |s| s.border(edge(1.5, Destructive)))
.state(DropZoneState::DragOver, Root, |s| {
s.background(InfoMuted).border(edge(2.0, Info))
})
.state(DropZoneState::DragOver, Icon, |s| s.foreground(Info))
.state(DropZoneState::DragOver, Title, |s| s.foreground(Info))
.state(DropZoneState::Rejected, Root, |s| {
s.background(DestructiveMuted).border(edge(2.0, Destructive))
})
.state(DropZoneState::Rejected, Icon, |s| s.foreground(Destructive))
.state(DropZoneState::Rejected, Title, |s| s.foreground(Destructive))
.state(DropZoneState::Disabled, Root, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
}
}
pub(crate) trait TakesFiles: Clone + Send + Sync + 'static {
fn takes_now(&self) -> Takes;
fn deliver(&self, taken: &[DroppedFile], rejected: &[RejectedFile]);
fn hosted(self, host: Hosted) -> Element;
fn host_key(&self) -> Option<Arc<str>>;
}
impl TakesFiles for DropZone {
fn takes_now(&self) -> Takes {
self.takes.clone()
}
fn deliver(&self, taken: &[DroppedFile], rejected: &[RejectedFile]) {
deliver(&self.on_files, &self.on_reject, taken, rejected);
}
fn hosted(mut self, host: Hosted) -> Element {
self.host = Some(host);
self.into()
}
fn host_key(&self) -> Option<Arc<str>> {
self.key.clone()
}
}
pub(crate) fn mount_files<C: TakesFiles>(taker: C, ctx: &mut Ctx) -> Element {
let key = taker.host_key();
let props = FilesProps { taker: Arc::new(taker) };
match key {
Some(key) => ctx.mount_keyed::<FilesHost<C>>(&key, props),
None => ctx.mount::<FilesHost<C>>(props),
}
}
struct FilesProps<C> {
taker: Arc<C>,
}
impl<C> Clone for FilesProps<C> {
fn clone(&self) -> Self {
Self {
taker: self.taker.clone(),
}
}
}
impl<C> PartialEq for FilesProps<C> {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl<C> crate::app::component::DevtoolsInspectable for FilesProps<C> {}
struct FilesHost<C> {
over: Signal<Option<bool>>,
refocus: Arc<Mutex<Option<Refocus>>>,
choose: FutureAction<FileDialog, Vec<DroppedFile>, ()>,
latest: Arc<Mutex<Option<C>>>,
}
impl<C: TakesFiles> Component for FilesHost<C> {
type Props = FilesProps<C>;
fn create(ctx: &mut Ctx) -> Self {
let window = ctx.window();
let choose = ctx.future_action(move |dialog: FileDialog| dialog.pick_result(&window));
let latest: Arc<Mutex<Option<C>>> = Arc::new(Mutex::new(None));
ctx.watch(&choose.state(), {
let latest = latest.clone();
move |state| {
let Some(Ok(chosen)) = state.outcome() else {
return;
};
let Some(taker) = latest.lock().unwrap().clone() else {
return;
};
let (taken, rejected) = taker.takes_now().sort(chosen.iter().map(|file| (file.clone(), false)));
taker.deliver(&taken, &rejected);
}
});
Self {
over: ctx.signal(None),
refocus: Arc::default(),
choose,
latest,
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let taker = (*ctx.props::<FilesProps<C>>().taker).clone();
*self.latest.lock().unwrap() = Some(taker.clone());
let choose = self.choose.clone();
let focus = self.refocus.lock().unwrap().take().map(|target| {
let element = crate::core::ElementRef::new();
ctx.focus(&element);
(target, element)
});
taker.hosted(Hosted {
over: self.over.clone(),
refocus: self.refocus.clone(),
focus,
choose: Arc::new(move |dialog| {
choose.run_if_idle(dialog);
}),
})
}
}