ofdb_seed/components/
search_bar.rs

1//! Search bar
2
3use seed::{prelude::*, *};
4
5#[derive(Clone)]
6pub struct Mdl {
7    pub search_term: String,
8    pub placeholder: Option<String>,
9    pub attrs: Attrs,
10    pub input_attrs: Attrs,
11    pub clear_label: String,
12}
13
14impl Default for Mdl {
15    fn default() -> Self {
16        Self {
17            search_term: String::new(),
18            placeholder: Some("What are you looking for? (# for tags)".to_string()),
19            attrs: attrs! {},
20            input_attrs: attrs! {},
21            clear_label: "clear".to_string(),
22        }
23    }
24}
25
26#[derive(Clone)]
27pub enum Msg {
28    Search(String),
29    Clear,
30}
31
32pub fn view(mdl: &Mdl) -> Node<Msg> {
33    div![
34        &mdl.attrs,
35        input![
36            attrs! {
37                At::Value => mdl.search_term;
38                At::Type => "search";
39            },
40            mdl.placeholder
41                .as_ref()
42                .map(|p| attrs! { At::Placeholder => p; })
43                .unwrap_or_else(|| attrs! {}),
44            &mdl.input_attrs,
45            input_ev(Ev::Input, Msg::Search),
46            keyboard_ev(Ev::KeyUp, |ev| {
47                ev.prevent_default();
48                if ev.key().to_lowercase() == "escape" {
49                    Some(Msg::Clear)
50                } else {
51                    None
52                }
53            })
54        ],
55        if !mdl.search_term.is_empty() {
56            button![&mdl.clear_label, ev(Ev::Click, |_| Msg::Clear)]
57        } else {
58            empty!()
59        }
60    ]
61}