1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#![allow(clippy::redundant_closure_call)]
use web_sys::File as SysFile;
use yew::events::ChangeData;
use yew::prelude::*;
use yewtil::NeqAssign;
use crate::{Alignment, Size};
#[derive(Clone, Debug, Properties, PartialEq)]
pub struct FileProps {
pub name: String,
pub files: Vec<SysFile>,
pub update: Callback<Vec<SysFile>>,
#[prop_or_else(|| "Choose a file...".into())]
pub selector_label: String,
#[prop_or_default]
pub selector_icon: Html,
#[prop_or_default]
pub classes: Option<String>,
#[prop_or_default]
pub has_name: Option<String>,
#[prop_or_default]
pub right: bool,
#[prop_or_default]
pub fullwidth: bool,
#[prop_or_default]
pub boxed: bool,
#[prop_or_default]
pub multiple: bool,
#[prop_or_default]
pub size: Option<Size>,
#[prop_or_default]
pub alignment: Option<Alignment>,
}
pub struct File {
props: FileProps,
link: ComponentLink<Self>,
}
impl Component for File {
type Message = Vec<SysFile>;
type Properties = FileProps;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self { props, link }
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
self.props.update.emit(msg);
false
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
self.props.neq_assign(props)
}
fn view(&self) -> Html {
let mut classes = Classes::from("file");
if let Some(extra) = &self.props.classes {
classes = classes.extend(extra);
}
if self.props.has_name.is_some() {
classes.push("has-name");
}
if self.props.right {
classes.push("is-right");
}
if self.props.fullwidth {
classes.push("is-fullwidth");
}
if self.props.boxed {
classes.push("is-boxed");
}
if let Some(size) = &self.props.size {
classes.push(&size.to_string());
}
if let Some(alignment) = &self.props.alignment {
classes.push(&alignment.to_string());
}
let filenames = self
.props
.files
.iter()
.map(|file| html! {<span class="file-name">{file.name()}</span>})
.collect::<Vec<_>>();
html! {
<div class=classes>
<label class="file-label">
<input
type="file"
class="file-input"
name=self.props.name.clone()
multiple=self.props.multiple
onchange=self.link.callback(|data: ChangeData| match data {
ChangeData::Files(list) => (0..list.length()).into_iter()
.filter_map(|idx| list.item(idx))
.collect::<Vec<_>>(),
_ => unreachable!("invariant violation: received non-file change event from a file input element"),
})
/>
<span class="file-cta">
<span class="file-icon">
{self.props.selector_icon.clone()}
</span>
<span class="file-label">
{self.props.selector_label.clone()}
</span>
</span>
{filenames}
</label>
</div>
}
}
}