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
use plaster::prelude::*;

/// An <input type="text" /> field
pub struct File {
    label: String,
    value: Vec<web_sys::File>,
    class: String,
    on_change: Option<Callback<Vec<web_sys::File>>>,
}

pub enum Msg {
    Change(ChangeData),
}

#[derive(Default, Clone, PartialEq)]
pub struct Props {
    /// The input label
    pub label: String,
    /// HTML class
    pub class: String,
    /// A callback that is fired when the user changes the input value
    pub on_change: Option<Callback<Vec<web_sys::File>>>,
}

impl Component for File {
    type Message = Msg;
    type Properties = Props;

    fn create(props: Self::Properties, _context: ComponentLink<Self>) -> Self {
        File {
            label: props.label,
            value: Vec::new(),
            class: props.class,
            on_change: props.on_change,
        }
    }

    fn change(&mut self, props: Self::Properties) -> ShouldRender {
        let mut updated = false;

        if props.label != self.label {
            self.label = props.label;
            updated = true;
        }

        if props.class != self.class {
            self.class = props.class;
            updated = true;
        }

        self.on_change = props.on_change;

        updated
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::Change(data) => {
                if let ChangeData::Files(list) = data {
                    self.value.clear();

                    if let Some(files) = list {
                        for i in 0..files.length() {
                            self.value.push(files.get(i).unwrap());
                        }
                    }

                    if let Some(ref callback) = self.on_change {
                        callback.emit(self.value.clone());
                    }
                }
            }
        };

        false
    }
}

impl Renderable<File> for File {
    fn view(&self) -> Html<Self> {
        html! {
            <div class=&self.class,>
                <input
                    type="file",
                    onchange=|data| Msg::Change(data),
                />
            </div>
        }
    }
}