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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use std::rc::Rc;

use web_sys::{Event, FocusEvent};
use yew::services::reader::{File, FileData, ReaderService, ReaderTask};
use yew::services::Task;
use yew::{
    html, Callback, ChangeData, Component, ComponentLink, Html, InputData, Properties, ShouldRender,
};
use yew_state::{GlobalHandle, SharedState, SharedStateComponent};

type ViewForm<T> = Rc<dyn Fn(FormHandle<T>) -> Html>;

pub struct FormHandle<'a, T>
where
    T: Default + Clone + 'static,
{
    handle: &'a GlobalHandle<T>,
    link: &'a ComponentLink<Model<T>>,
}

impl<'a, T> FormHandle<'a, T>
where
    T: Default + Clone + 'static,
{
    /// Current form state.
    pub fn state(&self) -> &T {
        self.handle.state()
    }

    /// Callback that sets state, ignoring callback event.
    pub fn set<E: 'static>(&self, f: impl FnOnce(&mut T) + 'static) -> Callback<E> {
        self.handle.reduce_callback_once(f)
    }

    /// Callback that sets state from callback event
    pub fn set_with<E: 'static>(&self, f: impl FnOnce(&mut T, E) + 'static) -> Callback<E> {
        self.handle.reduce_callback_once_with(f)
    }

    /// Callback for setting state from `InputData`.
    pub fn set_text(&self, f: impl FnOnce(&mut T, String) + 'static) -> Callback<InputData> {
        self.handle
            .reduce_callback_once_with(f)
            .reform(|data: InputData| data.value)
    }

    /// Callback for setting state from select elements.
    ///
    /// # Panics
    ///
    /// Panics if used on anything other than a select element.
    pub fn set_select(&self, f: impl FnOnce(&mut T, String) + 'static) -> Callback<ChangeData> {
        self.handle
            .reduce_callback_once_with(f)
            .reform(|data: ChangeData| {
                if let ChangeData::Select(el) = data {
                    el.value()
                } else {
                    panic!("Select element is required")
                }
            })
    }

    /// Callback for setting files
    pub fn set_file(
        &self,
        f: impl FnOnce(&mut T, FileData) + Copy + 'static,
    ) -> Callback<ChangeData> {
        let set_files = self.set_with(f);
        self.link.callback(move |data| {
            let mut result = Vec::new();
            if let ChangeData::Files(files) = data {
                let files = js_sys::try_iter(&files)
                    .unwrap()
                    .unwrap()
                    .into_iter()
                    .map(|v| File::from(v.unwrap()));
                result.extend(files);
            }
            Msg::Files(result, set_files.clone())
        })
    }
}

#[derive(Properties, Clone)]
pub struct Props<T>
where
    T: Default + Clone + 'static,
{
    #[prop_or_default]
    handle: GlobalHandle<T>,
    #[prop_or_default]
    pub on_submit: Callback<T>,
    #[prop_or_default]
    pub default: T,
    #[prop_or_default]
    pub auto_reset: bool,
    pub view: ViewForm<T>,
    // #[prop_or_default]
    // pub errors: InputErrors
}

impl<T> SharedState for Props<T>
where
    T: Default + Clone + 'static,
{
    type Handle = GlobalHandle<T>;

    fn handle(&mut self) -> &mut Self::Handle {
        &mut self.handle
    }
}

pub enum Msg {
    Files(Vec<File>, Callback<FileData>),
    Submit(FocusEvent),
}

pub struct Model<T>
where
    T: Default + Clone + 'static,
{
    props: Props<T>,
    cb_submit: Callback<FocusEvent>,
    cb_reset: Callback<()>,
    link: ComponentLink<Self>,
    file_reader: ReaderService,
    tasks: Vec<ReaderTask>,
}

impl<T> Component for Model<T>
where
    T: Default + Clone + 'static,
{
    type Message = Msg;
    type Properties = Props<T>;

    fn create(mut props: Self::Properties, link: ComponentLink<Self>) -> Self {
        let cb_submit = link.callback(|e: FocusEvent| {
            e.prevent_default();
            Msg::Submit(e)
        });
        let default = props.default.clone();
        let cb_reset = props
            .handle()
            .reduce_callback(move |state| *state = default.clone());
        // Make sure default is set.
        cb_reset.emit(());

        Self {
            props,
            cb_submit,
            cb_reset,
            link,
            tasks: Default::default(),
            file_reader: Default::default(),
        }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::Submit(e) => {
                self.props.on_submit.emit(self.props.handle.state().clone());
                if self.props.auto_reset {
                    // Clear form
                    let reset_event = Event::new("reset").unwrap();
                    e.target()
                        .map(|target| target.dispatch_event(&reset_event).ok());
                    // Reset state
                    self.cb_reset.emit(());
                }
                false
            }
            Msg::Files(files, cb) => {
                self.tasks.retain(Task::is_active);
                for file in files.into_iter() {
                    let task = self
                        .file_reader
                        .read_file(file, cb.clone())
                        .expect("Error reading file");

                    self.tasks.push(task);
                }
                false
            }
        }
    }

    fn view(&self) -> Html {
        let handle = FormHandle {
            handle: &self.props.handle,
            link: &self.link,
        };
        html! {
            <form onreset = self.cb_reset.reform(|_| ()) onsubmit = self.cb_submit.clone()>
                { (self.props.view)(handle) }
            </form>
        }
    }

    fn change(&mut self, props: Self::Properties) -> ShouldRender {
        self.props = props;
        true
    }
}

pub type Form<T> = SharedStateComponent<Model<T>>;

pub fn view_form<T: Default + Clone>(f: impl Fn(FormHandle<T>) -> Html + 'static) -> ViewForm<T> {
    Rc::new(f)
}