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

/// An autocompleting search select field
pub struct Select {
    label: String,
    search: String,
    searching: bool,
    selected_option: i32,
    value: Option<String>,
    value_label: String,
    validate: ValidationFn<Option<String>>,
    validation_error: Option<String>,
    inline: bool,
    options: Vec<(String, String)>,
    on_change: Option<Callback<Option<String>>>,
    on_blur: Option<Callback<()>>,
}

pub enum Msg {
    Change(InputData),
    SoftSelect(usize),
    Select(String),
    Focus,
    Blur,
    KeyDown(KeyboardEvent),
    Noop,
}

#[derive(Default, Clone, PartialEq)]
pub struct Props {
    /// The input label
    pub label: String,
    /// The controlled value of the input
    pub value: Option<String>,
    /// Validation function
    pub validate: ValidationFn<Option<String>>,
    /// Whether or not the field should be inline
    pub inline: bool,
    /// An array of options, (value, label)
    pub options: Vec<(String, String)>,
    /// A callback that is fired when the user changes the input value
    pub on_change: Option<Callback<Option<String>>>,
    /// A callback that is fired when the select loses focus
    pub on_blur: Option<Callback<()>>,
}

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

    fn create(props: Self::Properties, _context: ComponentLink<Self>) -> Self {
        let value_label = if let Some(ref value) = props.value {
            props
                .options
                .iter()
                .find(|x| &x.0 == value)
                .map(|x| x.1.to_owned())
                .unwrap_or(String::new())
        } else {
            String::new()
        };

        Select {
            label: props.label,
            search: String::new(),
            searching: false,
            selected_option: -1,
            value: props.value,
            value_label,
            validate: props.validate,
            validation_error: None,
            inline: props.inline,
            options: props.options,
            on_change: props.on_change,
            on_blur: props.on_blur,
        }
    }

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

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

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

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

        if updated {
            self.value_label = if let Some(ref value) = self.value {
                self.options
                    .iter()
                    .find(|x| &x.0 == value)
                    .map(|x| x.1.to_owned())
                    .unwrap_or(String::new())
            } else {
                String::new()
            };
        }

        self.validate = props.validate;
        self.on_change = props.on_change;
        self.on_blur = props.on_blur;

        updated
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::Change(data) => {
                self.search = data.value;
                self.searching = true;

                let top_option = self.filtered_options().next();
                if let Some((i, _)) = top_option {
                    self.selected_option = i as i32;
                }
            }
            Msg::SoftSelect(i) => {
                self.selected_option = i as i32;
            }
            Msg::Select(value) => {
                self.value_label = self
                    .options
                    .iter()
                    .find(|x| x.0 == value)
                    .map(|x| x.1.to_owned())
                    .unwrap_or(String::new());
                self.value = Some(value);
                self.searching = false;

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

                self.validation_error = self.validate.validate(self.value.clone());
            }
            Msg::Focus => {
                self.searching = true;
            }
            Msg::Blur => {
                self.searching = false;

                if let Some(ref callback) = self.on_blur {
                    callback.emit(());
                }

                self.validation_error = self.validate.validate(self.value.clone());
            }
            Msg::KeyDown(e) => match e.key().as_str() {
                "ArrowUp" => {
                    if self.selected_option > 0 {
                        self.selected_option -= 1;
                    }
                }
                "ArrowDown" => {
                    if self.selected_option < self.options.len() as i32 {
                        self.selected_option += 1;
                    }
                }
                "Enter" => {
                    if self.selected_option >= 0 {
                        let selected = self.options.get(self.selected_option as usize).unwrap();
                        self.value_label = selected.1.clone();
                        self.value = Some(selected.0.clone());
                        self.searching = false;

                        if let Some(ref callback) = self.on_change {
                            callback.emit(self.value.clone());
                        }
                    }
                }
                _ => (),
            },
            Msg::Noop => (),
        };

        true
    }
}

impl Select {
    fn filtered_options<'a>(&'a self) -> impl Iterator<Item = (usize, &'a (String, String))> + 'a {
        let search_term = self.search.to_lowercase();

        self.options
            .iter()
            .enumerate()
            .filter(move |(_, o)| o.1.to_lowercase().contains(&search_term))
    }
}

impl Renderable<Select> for Select {
    fn view(&self) -> Html<Self> {
        let class = if self.inline {
            "select-inline"
        } else {
            "select"
        };

        let value = if self.searching {
            &self.search
        } else {
            &self.value_label
        };

        let search_list = if self.searching {
            let options = self.filtered_options().map(|(i, o)| {
                let value = o.0.to_owned();

                let class = if (i as i32) == self.selected_option {
                    "selected"
                } else {
                    ""
                };

                html! {
                    <a
                        href="",
                        class=class,
                        onmousedown=|e| { e.prevent_default(); Msg::Noop },
                        onmouseenter=|_| Msg::SoftSelect(i),
                        onclick=|e| { e.prevent_default(); Msg::Select(value.clone()) },
                    >{&o.1}</a>
                }
            });

            html! {
                <div class="select-drop",>
                    {for options}
                </div>
            }
        } else {
            html! {
                <span />
            }
        };

        let (class, error) = if let Some(ref err) = self.validation_error {
            if !self.searching {
                (
                    format!("{} error", class),
                    html! {
                        <div class="input-error",>
                            {err}
                        </div>
                    },
                )
            } else {
                (class.to_owned(), html!(<span />))
            }
        } else {
            (class.to_owned(), html!(<span />))
        };

        html! {
            <div class="select-wrapper",>
                <input
                    type="text",
                    class=class,
                    value=value,
                    name="search",
                    placeholder=&self.label,
                    oninput=|data| Msg::Change(data),
                    onfocus=|_| Msg::Focus,
                    onblur=|_| Msg::Blur,
                    onkeydown=|e| Msg::KeyDown(e),
                />
                {error}
                {search_list}
            </div>
        }
    }
}