use std::sync::Arc;
use super::{
Button, ButtonVariant, DropZone, Progress, ProgressSize,
drop_zone::{Hosted, Refocus, RejectReason, RejectedFile, Takes, TakesFiles, mount_files},
icons, names,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{fading, glyph, pressable},
theme::{Themed, current_theme, touch_form},
};
use crate::{
app::{
ctx::Ctx,
events::{FileDragEvent, FileDropEvent},
theme::{OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{Column, Row, Stack},
core::Signal,
files::{DroppedFile, FileKind},
layout::{Alignment, stack_alignment::StackAlignment, text_style::FontWeight},
node::{CursorIcon, Element, border::Border as Edge, dimension::Dimension, node_kind::TextOverflow},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FileUploadPart {
Root,
Trigger,
List,
Item,
Icon,
Text,
Label,
Meta,
Progress,
Error,
Status,
Remove,
Retry,
Reveal,
}
names!(FileUploadPart {
Root => "root",
Trigger => "trigger",
List => "list",
Item => "item",
Icon => "icon",
Text => "text",
Label => "label",
Meta => "meta",
Progress => "progress",
Error => "error",
Status => "status",
Remove => "remove",
Retry => "retry",
Reveal => "reveal",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FileUploadState {
Zone,
Invalid,
Disabled,
Waiting,
Uploading,
Done,
Failed,
Unavailable,
}
names!(FileUploadState {
Zone => "zone",
Invalid => "invalid",
Disabled => "disabled",
Waiting => "waiting",
Uploading => "uploading",
Done => "done",
Failed => "failed",
Unavailable => "unavailable",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum UploadState {
#[default]
Waiting,
Uploading,
Done,
Failed,
}
#[derive(Clone, Debug, PartialEq)]
pub struct UploadFile {
pub file: DroppedFile,
pub state: UploadState,
pub progress: f32,
pub error: Option<Arc<str>>,
pub id: Arc<str>,
pub key: Option<Arc<str>>,
pub disabled: bool,
}
impl UploadFile {
pub fn new(file: DroppedFile) -> Self {
let id = match file.path() {
Some(path) => Arc::from(path.to_string_lossy().as_ref()),
None => Arc::from(file.name()),
};
Self {
file,
state: UploadState::Waiting,
progress: 0.0,
error: None,
id,
key: None,
disabled: false,
}
}
pub fn uploading(mut self, progress: f32) -> Self {
self.state = UploadState::Uploading;
self.progress = progress.clamp(0.0, 1.0);
self.error = None;
self
}
pub fn done(mut self) -> Self {
self.state = UploadState::Done;
self.progress = 1.0;
self.error = None;
self
}
pub fn failed(mut self, error: &str) -> Self {
self.state = UploadState::Failed;
self.error = Some(Arc::from(error));
self
}
pub fn waiting(mut self) -> Self {
self.state = UploadState::Waiting;
self.progress = 0.0;
self.error = None;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = id.into();
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
impl From<DroppedFile> for UploadFile {
fn from(file: DroppedFile) -> Self {
Self::new(file)
}
}
impl crate::app::component::DevtoolsInspectable for UploadFile {
fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
formatter.value_display(&format!("{} ({:?})", self.file.name(), self.state));
}
}
pub type FileUploadRenderer = Arc<dyn Fn(FileUploadView) -> Element + Send + Sync>;
type ListHandler = Arc<dyn Fn(&[UploadFile]) + Send + Sync>;
type FileHandler = Arc<dyn Fn(&UploadFile) + Send + Sync>;
type FilesHandler = Arc<dyn Fn(&[DroppedFile]) + Send + Sync>;
type RejectHandler = Arc<dyn Fn(&[RejectedFile]) + Send + Sync>;
type SizeText = Arc<dyn Fn(u64) -> String + Send + Sync>;
#[derive(Clone)]
enum Files {
Signal(Signal<Vec<UploadFile>>),
Held(Vec<UploadFile>),
Shown(Vec<UploadFile>),
}
impl Files {
fn list(&self) -> Vec<UploadFile> {
match self {
Self::Signal(signal) => signal.get(),
Self::Held(files) | Self::Shown(files) => files.clone(),
}
}
fn count(&self) -> usize {
match self {
Self::Signal(signal) => signal.with_untracked(Vec::len),
Self::Held(files) | Self::Shown(files) => files.len(),
}
}
}
#[derive(Clone)]
pub struct FileUpload {
files: Files,
zone: DropZone,
zone_shown: bool,
choose_label: Arc<str>,
remove_label: Arc<str>,
retry_label: Arc<str>,
size_text: Option<SizeText>,
label: Option<Arc<str>>,
invalid: bool,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
on_change: Vec<ListHandler>,
on_files: Vec<FilesHandler>,
on_reject: Vec<RejectHandler>,
on_remove: Vec<FileHandler>,
on_retry: Vec<FileHandler>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
host: Option<Hosted>,
}
impl FileUpload {
pub fn new(files: Signal<Vec<UploadFile>>) -> Self {
Self::with(Files::Signal(files))
}
pub fn controlled(files: Vec<UploadFile>, on_change: impl Fn(&[UploadFile]) + Send + Sync + 'static) -> Self {
Self::with(Files::Held(files)).on_change(on_change)
}
pub fn at(files: Vec<UploadFile>) -> Self {
Self::with(Files::Shown(files))
}
fn with(files: Files) -> Self {
Self {
files,
zone: DropZone::new(),
zone_shown: false,
choose_label: super::current_locale().fields.choose_files.clone(),
remove_label: super::current_locale().common.remove.clone(),
retry_label: super::current_locale().common.retry.clone(),
size_text: None,
label: None,
invalid: false,
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
on_change: Vec::new(),
on_files: Vec::new(),
on_reject: Vec::new(),
on_remove: Vec::new(),
on_retry: Vec::new(),
id: None,
key: None,
host: None,
}
}
pub fn accept<S: AsRef<str>>(mut self, accepted: impl IntoIterator<Item = S>) -> Self {
self.zone = self.zone.accept(accepted);
self
}
pub fn multiple(mut self, multiple: bool) -> Self {
self.zone = self.zone.multiple(multiple);
self
}
pub fn max_size(mut self, bytes: u64) -> Self {
self.zone = self.zone.max_size(bytes);
self
}
pub fn sources(mut self, sources: impl IntoIterator<Item = crate::files::FileSource>) -> Self {
self.zone = self.zone.sources(sources);
self
}
pub fn max_files(mut self, max: usize) -> Self {
self.zone = self.zone.max_files(max);
self
}
pub fn zone(mut self, zone: bool) -> Self {
self.zone_shown = zone;
self
}
pub fn title(mut self, title: &str) -> Self {
self.zone = self.zone.title(title);
self
}
pub fn description(mut self, description: &str) -> Self {
self.zone = self.zone.description(description);
self
}
pub fn choose_label(mut self, label: &str) -> Self {
self.choose_label = Arc::from(label);
self
}
pub fn remove_label(mut self, label: &str) -> Self {
self.remove_label = Arc::from(label);
self
}
pub fn retry_label(mut self, label: &str) -> Self {
self.retry_label = Arc::from(label);
self
}
pub fn size_text(mut self, text: impl Fn(u64) -> String + Send + Sync + 'static) -> Self {
self.size_text = Some(Arc::new(text));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self.zone = self.zone.label(label);
self
}
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_change(mut self, handler: impl Fn(&[UploadFile]) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
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 on_remove(mut self, handler: impl Fn(&UploadFile) + Send + Sync + 'static) -> Self {
self.on_remove.push(Arc::new(handler));
self
}
pub fn on_retry(mut self, handler: impl Fn(&UploadFile) + Send + Sync + 'static) -> Self {
self.on_retry.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 fn mount(self, ctx: &mut Ctx) -> Element {
mount_files(self, ctx)
}
fn operated(&self) -> bool {
!matches!(self.files, Files::Shown(_)) && !self.disabled
}
fn change(&self) -> Change {
Change {
files: self.files.clone(),
on_change: self.on_change.clone(),
on_files: self.on_files.clone(),
on_reject: self.on_reject.clone(),
on_remove: self.on_remove.clone(),
}
}
pub fn build(self, theme: &Theme) -> Element {
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(FileUploadState::Zone, self.zone_shown)
.state(FileUploadState::Invalid, self.invalid)
.state(FileUploadState::Disabled, self.disabled);
let recipe = theme
.resolve::<FileUpload>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let item_recipe = |file: &UploadFile| {
let state = match file.state {
UploadState::Waiting => FileUploadState::Waiting,
UploadState::Uploading => FileUploadState::Uploading,
UploadState::Done => FileUploadState::Done,
UploadState::Failed => FileUploadState::Failed,
};
let case = case
.clone()
.state(state, true)
.state(FileUploadState::Unavailable, file.disabled);
let item = theme
.resolve::<FileUpload>(&case, Some(&self.rules))
.owned_like(&recipe);
match &self.id {
Some(id) => item.item(Some(&Arc::from(format!("{id}-{}", file.id))), FileUploadPart::Item),
None => item.keyed_item(&file.id, FileUploadPart::Item),
}
};
let files = self.files.list();
let items = files.iter().map(item_recipe).collect();
let operated = self.operated();
let view = FileUploadView {
label: self.label.clone().unwrap_or_else(|| self.choose_label.clone()),
choose_label: self.choose_label.clone(),
remove_label: self.remove_label.clone(),
retry_label: self.retry_label.clone(),
size_text: self.size_text.clone(),
zone_shown: self.zone_shown,
invalid: self.invalid,
disabled: self.disabled,
operated,
recipe,
items,
change: self.change(),
takes: self.takes_now(),
zone: self.zone.clone(),
on_retry: self.on_retry.clone(),
host: self.host.clone(),
forced: self.forced,
id: self.id.clone(),
key: self.key.clone(),
files,
};
match theme.renderer::<FileUpload>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<FileUpload> for Element {
fn from(upload: FileUpload) -> Self {
upload.build(¤t_theme())
}
}
impl TakesFiles for FileUpload {
fn takes_now(&self) -> Takes {
let mut takes = self.zone.takes().clone();
let held = self.files.count();
takes.max_files = match (takes.multiple, takes.max_files) {
(false, _) => Some(1usize.saturating_sub(held)),
(true, Some(max)) => Some(max.saturating_sub(held)),
(true, None) => None,
};
takes.multiple = true;
takes
}
fn deliver(&self, taken: &[DroppedFile], rejected: &[RejectedFile]) {
if self.operated() {
self.change().give(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()
}
}
#[derive(Clone)]
struct Change {
files: Files,
on_change: Vec<ListHandler>,
on_files: Vec<FilesHandler>,
on_reject: Vec<RejectHandler>,
on_remove: Vec<FileHandler>,
}
impl Change {
fn give(&self, taken: &[DroppedFile], rejected: &[RejectedFile]) {
let mut list = self.current();
let same = |a: &DroppedFile, b: &DroppedFile| a.name() == b.name() && a.size() == b.size();
let (mut fresh, mut refused): (Vec<DroppedFile>, Vec<RejectedFile>) = (Vec::new(), rejected.to_vec());
for file in taken {
if list.iter().any(|held| same(&held.file, file)) || fresh.iter().any(|given| same(given, file)) {
refused.push(RejectedFile {
file: file.clone(),
reason: RejectReason::Duplicate,
});
} else {
fresh.push(file.clone());
}
}
let (taken, rejected) = (fresh.as_slice(), refused.as_slice());
if !taken.is_empty() {
list.extend(taken.iter().cloned().map(UploadFile::new));
self.set(&list);
for handler in &self.on_files {
handler(taken);
}
}
if !rejected.is_empty() {
for handler in &self.on_reject {
handler(rejected);
}
}
}
fn remove(&self, id: &str) {
let mut list = self.current();
let Some(index) = list.iter().position(|file| &*file.id == id) else {
return;
};
let removed = list.remove(index);
self.set(&list);
for handler in &self.on_remove {
handler(&removed);
}
}
fn current(&self) -> Vec<UploadFile> {
match &self.files {
Files::Signal(signal) => signal.get_untracked(),
Files::Held(files) | Files::Shown(files) => files.clone(),
}
}
fn set(&self, list: &[UploadFile]) {
if let Files::Signal(signal) = &self.files {
signal.set(list.to_vec());
}
for handler in &self.on_change {
handler(list);
}
}
}
pub struct FileUploadView {
pub label: Arc<str>,
pub choose_label: Arc<str>,
pub remove_label: Arc<str>,
pub retry_label: Arc<str>,
pub files: Vec<UploadFile>,
pub zone_shown: bool,
pub invalid: bool,
pub disabled: bool,
pub operated: bool,
pub recipe: ResolvedRecipe,
items: Vec<ResolvedRecipe>,
size_text: Option<SizeText>,
change: Change,
takes: Takes,
zone: DropZone,
on_retry: Vec<FileHandler>,
host: Option<Hosted>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl FileUploadView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn item_part(&self, index: usize, part: impl Into<Name>) -> ResolvedPart {
self.items.get(index).unwrap_or(&self.recipe).part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
fn child_id(&self, suffix: &str) -> Option<Arc<str>> {
self.id.as_ref().map(|id| Arc::from(format!("{id}-{suffix}")))
}
pub fn trigger(&self) -> Element {
if self.zone_shown {
let change = self.change.clone();
let operated = self.operated;
let mut zone = self
.zone
.clone()
.invalid(self.invalid)
.disabled(self.disabled)
.force(self.forced)
.rules(&self.recipe.lend(FileUploadPart::Trigger))
.with_host(self.host.clone());
zone = zone
.max_files(self.takes.max_files.unwrap_or(usize::MAX))
.multiple(true);
zone = zone
.on_files({
let change = change.clone();
move |taken| {
if operated {
change.give(taken, &[]);
}
}
})
.on_reject(move |rejected| {
if operated {
change.give(&[], rejected);
}
});
if let Some(id) = self.child_id("trigger") {
zone = zone.id(id);
}
return zone.into();
}
let mut button = Button::new(&self.choose_label)
.variant(ButtonVariant::Outline)
.icon(icons::UPLOAD)
.disabled(self.disabled)
.rules(&self.recipe.rules_for(FileUploadPart::Trigger, super::ButtonPart::Root))
.force(self.forced);
if let (true, Some(host)) = (self.operated, &self.host) {
let (choose, dialog) = (host.choose.clone(), self.takes.dialog(&self.label));
button = button.on_click(move |_| choose(dialog.clone()));
}
if let Some(id) = self.child_id("trigger") {
button = button.id(id);
}
if let Some(element) = self.focus_ref(&Refocus::Trigger) {
button = button.ref_element(element);
}
button.into()
}
pub fn item(&self, index: usize) -> Option<Element> {
let file = self.files.get(index)?;
let part = |name: FileUploadPart| self.item_part(index, name);
let icon = match file.file.kind() {
FileKind::Image => icons::IMAGE,
FileKind::Text => icons::FILE_TEXT,
FileKind::Archive => icons::ARCHIVE,
_ => icons::FILE,
};
let meta = match file.state {
UploadState::Uploading => format!("{}%", (file.progress * 100.0).round() as u32),
_ => file
.file
.size()
.map(|size| match &self.size_text {
Some(text) => text(size),
None => super::current_locale().fields.size(size),
})
.unwrap_or_default(),
};
let fill = Dimension::Pct(100.0);
let name = part(FileUploadPart::Label);
let mut line = Row::new()
.width(fill)
.align_items(Alignment::Center)
.spacing(8.0)
.child(
Row::new()
.flex(1.0)
.min_width(crate::node::dimension::Dimension::Px(0.0))
.part(&name)
.child(
name
.text(file.file.name())
.nowrap()
.text_overflow(TextOverflow::Elipsis)
.width(fill),
),
);
if !meta.is_empty() {
let meta_part = part(FileUploadPart::Meta);
line = line.child(Row::new().part(&meta_part).child(meta_part.text(&meta).nowrap()));
}
let mut text = Column::new()
.flex(1.0)
.width(fill)
.part(&part(FileUploadPart::Text))
.child(line);
if file.state == UploadState::Uploading {
let progress = Progress::new(file.progress)
.rules(
&self
.items
.get(index)
.unwrap_or(&self.recipe)
.lend(FileUploadPart::Progress),
)
.size(ProgressSize::Sm)
.label(file.file.name())
.label_hidden(true);
text = text.child(
Row::new()
.width(fill)
.part(&part(FileUploadPart::Progress).unnamed())
.child(progress),
);
}
if let (UploadState::Failed, Some(error)) = (file.state, &file.error) {
let error_part = part(FileUploadPart::Error);
text = text.child(
Column::new()
.width(fill)
.part(&error_part)
.child(error_part.text(error).width(fill)),
);
}
let mut item = Row::new()
.width(fill)
.align_items(Alignment::Center)
.part(&part(FileUploadPart::Item))
.child(glyph(&part(FileUploadPart::Icon), Name::from(icon), false))
.child(text);
let able = self.operated && !file.disabled;
match file.state {
UploadState::Done => {
let check = glyph(&part(FileUploadPart::Status), Name::from(icons::CHECK_CIRCLE), false);
item = match (able, touch_form()) {
(false, _) => item.child(check),
(true, true) => item.child(check).child(self.remove(index, able)),
(true, false) => item.interaction_group(true).child(
Stack::new().stack_align(StackAlignment::Center).child(check).child(
Row::new()
.part(&part(FileUploadPart::Reveal))
.child(self.remove(index, able)),
),
),
};
}
UploadState::Failed => {
let retry = {
let (handlers, file) = (self.on_retry.clone(), file.clone());
move || {
for handler in &handlers {
handler(&file);
}
}
};
item = item
.child(self.control(
index,
FileUploadPart::Retry,
icons::REFRESH,
&self.retry_label,
able,
retry,
))
.child(self.remove(index, able));
}
UploadState::Waiting | UploadState::Uploading => item = item.child(self.remove(index, able)),
}
if let Some(id) = self.child_id(&file.id) {
item = item.id(id);
}
if let Some(key) = &file.key {
item = item.key(key.clone());
}
Some(item.into())
}
fn remove(&self, index: usize, able: bool) -> Element {
let (change, id) = (self.change.clone(), self.files[index].id.clone());
let next = self
.has_control(index + 1..self.files.len())
.or_else(|| self.has_control_back(index));
let target = next
.map(|other| Refocus::Control(self.files[other].id.clone()))
.unwrap_or(Refocus::Trigger);
let refocus = self.host.as_ref().map(|host| host.refocus.clone());
self.control(
index,
FileUploadPart::Remove,
icons::CLOSE,
&self.remove_label,
able,
move || {
if let Some(refocus) = &refocus {
*refocus.lock().unwrap() = Some(target.clone());
}
change.remove(&id)
},
)
}
fn has_control(&self, mut range: std::ops::Range<usize>) -> Option<usize> {
range.find(|&index| self.pressed(index))
}
fn has_control_back(&self, index: usize) -> Option<usize> {
(0..index).rev().find(|&index| self.pressed(index))
}
fn pressed(&self, index: usize) -> bool {
let file = &self.files[index];
self.operated && !file.disabled
}
fn focus_ref(&self, target: &Refocus) -> Option<crate::core::ElementRef> {
let (to, element) = self.host.as_ref()?.focus.as_ref()?;
(to == target).then(|| element.clone())
}
fn control(
&self,
index: usize,
part: FileUploadPart,
icon: &'static str,
label: &str,
able: bool,
action: impl Fn() + Send + Sync + 'static,
) -> Element {
let style = self.item_part(index, part);
let name = format!("{label} {}", self.files[index].file.name());
if !able {
return Row::new()
.part(&style)
.describe("a11y_name", name)
.child(glyph(&style.clone().unnamed(), Name::from(icon), false))
.into();
}
let mut control = pressable(&style, false)
.describe("a11y_role", "button")
.describe("a11y_name", name)
.on_click(move |_| action())
.child(glyph(&style.clone().unnamed(), Name::from(icon), false));
let first = part == FileUploadPart::Retry || self.files[index].state != UploadState::Failed;
if first && let Some(element) = self.focus_ref(&Refocus::Control(self.files[index].id.clone())) {
control = control.ref_element(element);
}
if let Some(id) = self.child_id(&format!("{}-{}", self.files[index].id, part_name(part))) {
control = control.id(id);
}
control.into()
}
pub fn list(&self) -> Option<Column> {
if self.files.is_empty() {
return None;
}
let mut list = Column::new()
.width(Dimension::Pct(100.0))
.part(&self.part(FileUploadPart::List))
.describe("a11y_role", "list");
for index in 0..self.files.len() {
if let Some(item) = self.item(index) {
list = list.child(item);
}
}
Some(list)
}
pub fn render(self) -> Element {
let mut root = Column::new()
.align_items(Alignment::Start)
.part(&self.part(FileUploadPart::Root))
.describe("a11y_name", self.label.clone())
.child(self.trigger());
if let Some(list) = self.list() {
root = root.child(list);
}
if self.operated && !self.zone_shown {
let (change, takes) = (self.change.clone(), self.takes.clone());
root = root
.on_file_drag_enter({
let takes = takes.clone();
move |event: FileDragEvent| {
if takes.sort_dragged(&event.paths).0.is_empty() {
event.refuse();
}
}
})
.on_file_drop(move |event: FileDropEvent| {
let (taken, rejected) = takes.sort_dragged(&event.paths);
change.give(&taken, &rejected);
});
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
}
fn part_name(part: FileUploadPart) -> &'static str {
match part {
FileUploadPart::Retry => "retry",
_ => "remove",
}
}
impl super::FieldControl for FileUpload {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self = self.label(&field.label);
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.into()
}
fn mount_in_field(mut self, field: &super::InField, ctx: &mut Ctx) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self = self.label(&field.label);
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.mount(ctx)
}
}
impl super::FieldControl for DropZone {
fn in_field(self, field: &super::InField) -> Element {
self
.named_by(field)
.invalid(field.judgment == Some(super::Judgment::Invalid))
.disabled(field.disabled)
.into()
}
fn mount_in_field(self, field: &super::InField, ctx: &mut Ctx) -> Element {
self
.named_by(field)
.invalid(field.judgment == Some(super::Judgment::Invalid))
.disabled(field.disabled)
.mount(ctx)
}
}
impl crate::ui::Styled for FileUpload {
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 FileUpload {
const NAME: &'static str = "file_upload";
type Renderer = FileUploadRenderer;
fn parts() -> crate::ui::Declared {
FileUploadPart::declared()
}
fn states() -> crate::ui::Declared {
FileUploadState::declared()
}
fn recipe() -> Recipe {
use FileUploadPart::*;
use PaletteColor::{Border as BorderColor, Destructive, Foreground, MutedForeground, Success};
let edge = |color: PaletteColor| Edge::inside(1.0, color);
let control = |s: super::PartStyle| {
fading(
s.square(16.0)
.radius(RadiusSize::Sm)
.foreground(MutedForeground)
.cursor(CursorIcon::Pointer),
)
};
Recipe::new()
.base(Root, |s| s.width(300.0).max_width(super::Length::Fill).gap(8.0))
.base(List, |s| s.gap(8.0))
.base(Item, |s| {
s.border(edge(BorderColor))
.radius(RadiusSize::Md)
.padding_x(12.0)
.padding_y(10.0)
.gap(10.0)
})
.base(Icon, |s| s.square(16.0).foreground(MutedForeground))
.base(Text, |s| s.gap(6.0))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.base(Meta, |s| {
s.typography(TypographyStyle::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Error, |s| {
s.typography(TypographyStyle::Caption).foreground(Destructive)
})
.base(Status, |s| s.square(16.0).foreground(Success))
.base(Remove, control)
.base(Retry, control)
.hovered(Remove, |s| s.foreground(Foreground))
.hovered(Retry, |s| s.foreground(Foreground))
.focus_visible(Remove, |s| s.focus_ring())
.focus_visible(Retry, |s| s.focus_ring())
.base(Reveal, |s| s.opacity(0.0))
.within(Reveal, |s| s.opacity(1.0))
.within(Status, |s| s.opacity(0.0))
.state(FileUploadState::Zone, Root, |s| s.width(320.0))
.state(FileUploadState::Failed, Item, |s| s.border(edge(Destructive)))
.state(FileUploadState::Failed, Icon, |s| s.foreground(Destructive))
.state(FileUploadState::Invalid, Trigger, |s| s.border(edge(Destructive)))
.state(FileUploadState::Unavailable, Remove, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.state(FileUploadState::Unavailable, Retry, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.state(FileUploadState::Disabled, List, |s| s.opacity(OpacityLevel::Disabled))
}
}