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
use crate::utils::event::Event;
use crate::utils::style::{inline_style, scss_to_css};
use crate::widgets::widget::Widget;

/// # The state of a Radio
///
/// ## Fields
///
/// ```text
/// choices: Vec<String>
/// selected: u32
/// disabled: bool
/// stretched: bool
/// style: String
/// ```
pub struct RadioState {
    choices: Vec<String>,
    selected: u32,
    disabled: bool,
    stretched: bool,
    style: String,
}

impl RadioState {
    /// Get the choices
    pub fn choices(&self) -> &Vec<String> {
        &self.choices
    }

    /// Get the selected index
    pub fn selected(&self) -> u32 {
        self.selected
    }

    /// Get the disabled flag
    pub fn disabled(&self) -> bool {
        self.disabled
    }

    /// Get the stretched flag
    pub fn stretched(&self) -> bool {
        self.stretched
    }

    /// Get the style
    pub fn style(&self) -> &str {
        &self.style
    }

    /// Set the choices
    pub fn set_choices(&mut self, choices: Vec<&str>) {
        self.choices = choices
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<String>>();
    }

    /// Set the selected index
    pub fn set_selected(&mut self, selected: u32) {
        self.selected = selected;
    }

    /// Set the disabled flag
    pub fn set_disabled(&mut self, disabled: bool) {
        self.disabled = disabled;
    }

    /// Set the stretched flag
    pub fn set_stretched(&mut self, stretched: bool) {
        self.stretched = stretched;
    }

    /// Set the style
    pub fn set_style(&mut self, style: &str) {
        self.style = style.to_string();
    }
}

/// # The listener of a Radio
pub trait RadioListener {
    /// Function triggered on change event
    fn on_change(&self, state: &RadioState);

    /// Function triggered on update event
    fn on_update(&self, state: &mut RadioState);
}

/// # A list of radio buttons
///
/// Only one can be selected at a time.
///
/// ## Fields
///
/// ```text
/// name: String
/// state: RadioState
/// listener: Option<Box<dyn RadioListener>>
/// ```
///
/// ## Default values
///
/// ```text
/// name: name.to_string()
/// state:
///     choices: vec!["Choice 1".to_string(), "Choice 2".to_string()],
///     selected: 0
///     disabled: false
///     stretched: false
///     style: "".to_string()
/// listener: None
/// ```
///
/// ## Style
///
/// ```text
/// div.radio[.disabled][.selected]
///     label
///     div.radio-outer
///         div.radio-inner
/// ```
/// 
/// ## Example
///
/// ```
/// use std::cell::RefCell;
/// use std::rc::Rc;
///
/// use neutrino::widgets::radio::{Radio, RadioListener, RadioState};
/// use neutrino::utils::theme::Theme;
/// use neutrino::{App, Window};
///
///
/// struct Dessert {
///     index: u32,
///     value: String,
/// }
///
/// impl Dessert {
///     fn new() -> Self {
///         Self { index: 0, value: "Cake".to_string() }
///     }
///
///     fn index(&self) -> u32 {
///         self.index
///     }
///
///     fn value(&self) -> &str {
///         &self.value
///     }
///
///     fn set(&mut self, index: u32, value: &str) {
///         self.index = index;
///         self.value = value.to_string();
///     }
/// }
///
///
/// struct MyRadioListener {
///     dessert: Rc<RefCell<Dessert>>,
/// }
///
/// impl MyRadioListener {
///    pub fn new(dessert: Rc<RefCell<Dessert>>) -> Self {
///        Self { dessert }
///    }
/// }
///
/// impl RadioListener for MyRadioListener {
///     fn on_change(&self, state: &RadioState) {
///         let index = state.selected();
///         self.dessert.borrow_mut().set(
///             index,
///             &state.choices()[index as usize]
///         );
///     }
///
///     fn on_update(&self, state: &mut RadioState) {
///         state.set_selected(self.dessert.borrow().index());
///     }
/// }
///
///
/// fn main() {
///     let dessert = Rc::new(RefCell::new(Dessert::new()));
///
///     let my_listener = MyRadioListener::new(Rc::clone(&dessert));
///
///     let mut my_radio = Radio::new("my_radio");
///     my_radio.set_choices(vec!["Cake", "Ice Cream", "Pie"]);
///     my_radio.set_listener(Box::new(my_listener));
/// }
/// ```
pub struct Radio {
    name: String,
    state: RadioState,
    listener: Option<Box<dyn RadioListener>>,
}

impl Radio {
    /// Create a Radio
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            state: RadioState {
                choices: vec!["Choice 1".to_string(), "Choice 2".to_string()],
                selected: 0,
                disabled: false,
                stretched: false,
                style: "".to_string(),
            },
            listener: None,
        }
    }

    /// Set the choices
    pub fn set_choices(&mut self, choices: Vec<&str>) {
        self.state.set_choices(choices);
    }

    /// Set the selected index
    pub fn set_selected(&mut self, selected: u32) {
        self.state.set_selected(selected);
    }

    /// Set the disabled flag to true
    pub fn set_disabled(&mut self) {
        self.state.set_disabled(true);
    }

    /// Set the stretched flag
    pub fn set_stretched(&mut self) {
        self.state.set_stretched(true);
    }

    /// Set the listener
    pub fn set_listener(&mut self, listener: Box<dyn RadioListener>) {
        self.listener = Some(listener);
    }

    /// Set the style
    pub fn set_style(&mut self, style: &str) {
        self.state.set_style(style);
    }
}

impl Widget for Radio {
    fn eval(&self) -> String {
        let stretched = if self.state.stretched() {
            "stretched"
        } else {
            ""
        };
        let disabled = if self.state.disabled() {
            "disabled"
        } else {
            ""
        };
        let style = inline_style(&scss_to_css(&format!(
            r##"#{}{{{}}}"##,
            self.name,
            self.state.style(),
        )));
        let mut html = "".to_string();
        for (i, choice) in self.state.choices().iter().enumerate() {
            let selected = if self.state.selected() == i as u32 {
                "selected"
            } else {
                ""
            };
            html.push_str(
                &format!(
                    r#"<div id="{}" class="radio {} {} {}" onmousedown="{}"><div class="radio-outer"><div class="radio-inner"></div></div><label>{}</label></div>"#, 
                    self.name,
                    stretched,
                    disabled,
                    selected,
                    Event::change_js(&self.name, &format!("'{}'", i)), 
                    choice
                )
            );
        }
        format!("{}{}", style, html)
    }

    fn trigger(&mut self, event: &Event) {
        match event {
            Event::Update => self.on_update(),
            Event::Change { source, value } => {
                if source == &self.name && !self.state.disabled {
                    self.on_change(value);
                }
            }
            _ => (),
        }
    }

    fn on_update(&mut self) {
        match &self.listener {
            None => (),
            Some(listener) => {
                listener.on_update(&mut self.state);
            }
        }
    }

    fn on_change(&mut self, value: &str) {
        self.state.set_selected(value.parse::<u32>().unwrap());
        match &self.listener {
            None => (),
            Some(listener) => {
                listener.on_change(&self.state);
            }
        }
    }
}