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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
use crate::{
    css,
    el::{self},
    events::Events,
    model::Model,
    render::Render,
    theme::Theme,
};
use derive_rich::Rich;
use seed::prelude::*;
use std::rc::Rc;

#[derive(Debug, Clone)]
pub enum Msg {
    MouseEnter,
    MouseLeave,
    Focus,
    Blur,
    Increment,
    Decrement,
    Input,
    IncrementButton(el::button::Msg),
    DecrementButton(el::button::Msg),
}

#[derive(Default, Rich)]
pub struct LocalEvents {
    #[rich(write(style = compose))]
    pub container: Events<Msg>,
    #[rich(write(style = compose))]
    pub input: Events<Msg>,
}

impl LocalEvents {
    pub fn remove_events(self) -> Self {
        Self::default()
    }
}

#[derive(Rich)]
pub struct ParentEvents<PMsg> {
    #[rich(write(style = compose))]
    pub container: Events<PMsg>,
    #[rich(write(style = compose))]
    pub input: Events<PMsg>,
}

impl<PMsg> Default for ParentEvents<PMsg> {
    fn default() -> Self {
        Self {
            container: Events::default(),
            input: Events::default(),
        }
    }
}

// TODO: add way to accept custom format (e.g. `100%`, `45$`)
#[derive(Rich)]
pub struct SpinEntry<PMsg> {
    el_ref: ElRef<web_sys::HtmlInputElement>,
    msg_mapper: Rc<dyn Fn(Msg) -> PMsg>,
    #[rich(write(style = compose))]
    pub local_events: LocalEvents,
    #[rich(write(style = compose))]
    pub events: ParentEvents<PMsg>,
    #[rich(read(copy))]
    value: Option<f32>,
    #[rich(read(copy))]
    max: f32,
    #[rich(read(copy))]
    min: f32,
    #[rich(read(copy))]
    step: f32,
    #[rich(read(copy))]
    placeholder: Option<f32>,
    #[rich(write(style = compose))]
    pub style: UserStyle,
    #[rich(
        read(copy, rename = is_disabled),
    )]
    pub disabled: bool,
    #[rich(read(copy, rename = is_focused))]
    focus: bool,
    #[rich(read(copy, rename = is_mouse_over))]
    mouse_over: bool,

    // children elements
    #[rich(write(style = compose))]
    pub increment_button: el::Button<Msg>,
    #[rich(write(style = compose))]
    pub decrement_button: el::Button<Msg>,
}

impl<PMsg> SpinEntry<PMsg> {
    pub fn new(msg_mapper: impl FnOnce(Msg) -> PMsg + Clone + 'static) -> Self {
        let mut local_events = LocalEvents::default();
        local_events
            .input(|conf| {
                conf.input(|_| Msg::Input)
                    .focus(|_| Msg::Focus)
                    .blur(|_| Msg::Blur)
            })
            .container(|conf| {
                conf.mouse_enter(|_| Msg::MouseEnter)
                    .mouse_leave(|_| Msg::MouseLeave)
            });

        let mut increment_button = el::Button::new(Msg::IncrementButton);
        increment_button.events(|conf| conf.click(|_| Msg::Increment));

        let mut decrement_button = el::Button::new(Msg::DecrementButton);
        decrement_button.events(|conf| conf.click(|_| Msg::Decrement));

        Self {
            el_ref: ElRef::default(),
            msg_mapper: Rc::new(move |msg| (msg_mapper.clone())(msg)),
            local_events,
            events: ParentEvents::default(),
            value: None,
            max: 10.,
            min: 0.,
            step: 1.,
            placeholder: None,
            style: UserStyle::default(),
            disabled: false,
            focus: false,
            mouse_over: false,
            increment_button,
            decrement_button,
        }
    }

    pub fn default_value(&self) -> f32 {
        self.min
    }

    pub fn value_or_default(&self) -> f32 {
        self.value.unwrap_or_else(|| self.default_value())
    }

    pub fn max(&mut self, max: f32) -> &mut Self {
        if max > self.min {
            self.max = max;
        } else {
            self.max = self.min;
            self.min = max;
        }
        self
    }

    pub fn min(&mut self, min: f32) -> &mut Self {
        if min < self.max {
            self.min = min;
        } else {
            self.min = self.max;
            self.max = min;
        }
        self
    }

    pub fn step(&mut self, step: f32) -> &mut Self {
        let range = self.min - self.max;
        self.step = if step > range { range } else { step };
        self
    }

    pub fn value(&mut self, value: f32) -> &mut Self {
        self.value = match value {
            x if x > self.max => Some(self.max),
            x if x < self.min => Some(self.min),
            x => Some(x),
        };
        self
    }

    pub fn enable(&mut self) -> &mut Self {
        self.disabled = false;
        self.increment_button(|conf| conf.enable())
            .decrement_button(|conf| conf.enable())
    }

    pub fn disable(&mut self) -> &mut Self {
        self.disabled = true;
        self.increment_button(|conf| conf.disable())
            .decrement_button(|conf| conf.disable())
    }

    pub fn placeholder(&mut self, value: impl Into<f32>) -> &mut Self {
        let value = value.into();
        self.placeholder = Some(value);
        if let Some(input) = self.el_ref.get() {
            input.set_placeholder(&value.to_string());
        }
        self
    }

    fn increment(&mut self) {
        let value = self.value_or_default();
        if value < self.max {
            let value = if self.max < value + self.step {
                self.max
            } else {
                value + self.step
            };
            self.value = Some(value);
        }
    }

    fn decrement(&mut self) {
        let value = self.value_or_default();
        if value > self.min {
            let value = if self.min > value - self.step {
                self.min
            } else {
                value - self.step
            };
            self.value = Some(value);
        }
    }

    fn handle_input(&mut self) {
        log!(self.el_ref.get());
        if let Some(input) = self.el_ref.get() {
            let value = input.value();
            // if value is empty then we set None to self.value
            if value.is_empty() {
                log!("value is empty");
                self.value = None;
            } else {
                // parse value to f32
                match value.parse::<f32>().ok() {
                    // check if value in accpeted range
                    Some(value) if value >= self.min && value <= self.max => {
                        self.value = Some(value)
                    }
                    // remove the input and set self.value as the value for input
                    _ => input.set_value(&self.value.map(|v| v.to_string()).unwrap_or("".into())),
                }
            }
        }
    }
}

impl<GMsg: 'static, PMsg: 'static> Model<PMsg, GMsg> for SpinEntry<PMsg> {
    type Message = Msg;

    fn update(&mut self, msg: Msg, orders: &mut impl Orders<PMsg, GMsg>) {
        let msg_mapper = Rc::clone(&self.msg_mapper.clone());
        let mut orders = orders.proxy(move |msg| (msg_mapper.clone())(msg));

        match msg {
            Msg::MouseEnter => self.mouse_over = true,
            Msg::MouseLeave => self.mouse_over = false,
            Msg::Focus => self.focus = true,
            Msg::Blur => self.focus = false,
            Msg::Increment => self.increment(),
            Msg::Decrement => self.decrement(),
            Msg::Input => self.handle_input(),
            Msg::IncrementButton(msg) => self.increment_button.update(msg, &mut orders),
            Msg::DecrementButton(msg) => self.decrement_button.update(msg, &mut orders),
        }
    }
}

/// This style used by users when they want to change styles of SpinEntry
#[derive(Clone, Default, Rich)]
pub struct UserStyle {
    #[rich(write(style = compose))]
    pub container: css::Style,
    #[rich(write(style = compose))]
    pub input: css::Style,
    #[rich(write(style = compose))]
    pub buttons_container: el::flexbox::Style,
    #[rich(write(style = compose))]
    pub increment_item: el::flexbox::ItemStyle,
    #[rich(write(style = compose))]
    pub decrement_item: el::flexbox::ItemStyle,
    #[rich(write(style = compose))]
    pub increment_button: el::button::Style,
    #[rich(write(style = compose))]
    pub decrement_button: el::button::Style,
    #[rich(write)]
    pub increment_icon: Option<el::Icon<Msg>>,
    #[rich(write)]
    pub decrement_icon: Option<el::Icon<Msg>>,
}

/// This style returned by the Theme and consumed by render function, thus the
/// icons must be returned by the theme
#[derive(Clone, Rich)]
pub struct Style {
    #[rich(write(style = compose))]
    pub container: css::Style,
    #[rich(write(style = compose))]
    pub input: css::Style,
    #[rich(write(style = compose))]
    pub buttons_container: el::flexbox::Style,
    #[rich(write(style = compose))]
    pub increment_item: el::flexbox::ItemStyle,
    #[rich(write(style = compose))]
    pub decrement_item: el::flexbox::ItemStyle,
    #[rich(write(style = compose))]
    pub increment_button: el::button::Style,
    #[rich(write(style = compose))]
    pub decrement_button: el::button::Style,
    // FIXME: should I use SvgIcon insted of Icon ?
    #[rich(write)]
    pub increment_icon: el::Icon<Msg>,
    #[rich(write)]
    pub decrement_icon: el::Icon<Msg>,
}

impl<PMsg: 'static> Render<PMsg> for SpinEntry<PMsg> {
    type View = Node<PMsg>;
    type Style = Style;

    fn style(&self, theme: &impl Theme) -> Self::Style {
        theme.spin_entry(self)
    }

    fn render_with_style(&self, theme: &impl Theme, style: Self::Style) -> Self::View {
        let Style {
            container,
            input,
            buttons_container,
            increment_item,
            decrement_item,
            increment_button,
            decrement_button,
            increment_icon,
            decrement_icon,
        } = style;

        let mut inc_btn = self
            .increment_button
            .render_with_style(theme, increment_button);
        let mut dec_btn = self
            .decrement_button
            .render_with_style(theme, decrement_button);

        // FIXME: try to use better way to add icons to the buttons, this way is
        // pretty hacky and wouldn't work if el::Button::render(theme) return
        // nasted nodes
        inc_btn.add_child(increment_icon.render(theme));
        dec_btn.add_child(decrement_icon.render(theme));

        let msg_mapper = Rc::clone(&self.msg_mapper.clone());
        let btns_container = el::Flexbox::new()
            .add(el::Flexbox::item_with(nodes![inc_btn]).render_with_style(theme, increment_item))
            .add(el::Flexbox::item_with(nodes![dec_btn]).render_with_style(theme, decrement_item))
            .render_with_style(theme, buttons_container)
            .map_msg(move |msg| (msg_mapper.clone())(msg));

        // input
        let msg_mapper = Rc::clone(&self.msg_mapper.clone());
        let mut input = input![
            el_ref(&self.el_ref),
            self.local_events.input.clone(),
            input,
            attrs![
                At::Value => self.value.map(|v| v.to_string()).unwrap_or("".into()),
                // TODO:
                //   At::Max => self.max,
                //   At::Min => self.min,
                //   At::Step => self.step,
                //   At::Placeholder => self.placeholder,
            ]
        ]
        .map_msg(move |msg| (msg_mapper.clone())(msg));

        for event in self.events.input.events.clone().into_iter() {
            input.add_listener(event);
        }

        // container
        let msg_mapper = Rc::clone(&self.msg_mapper.clone());
        let mut container = div![self.local_events.container.clone(), container,]
            .map_msg(move |msg| (msg_mapper.clone())(msg));

        for event in self.events.container.events.clone().into_iter() {
            container.add_listener(event);
        }

        container.add_child(input).add_child(btns_container);
        container
    }
}