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
use std::fmt::Display;
use web_sys::HtmlSelectElement;
use yew::prelude::*;

pub struct DropDown<T> {
    selected: T,
    node: NodeRef,
}

pub enum Msg {
    SelectionChanged(usize),
}

#[derive(PartialEq, Properties)]
pub struct DropDownProps<T>
where
    T: PartialEq,
{
    pub initial: T,
    pub options: Vec<T>,
    pub selection_changed: Callback<T>,
}

impl<T> Component for DropDown<T>
where
    T: Display + Clone + PartialEq + 'static,
{
    type Message = Msg;
    type Properties = DropDownProps<T>;

    fn create(ctx: &Context<Self>) -> Self {
        Self {
            selected: ctx.props().initial.clone(),
            node: NodeRef::default(),
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let node = self.node.clone();

        html! {
            <select ref={node.clone()} onchange={ctx.link().callback(move |_| {
                let node2: HtmlSelectElement = node.cast().unwrap();
                let idx = node2.selected_index() as usize;
                Msg::SelectionChanged(idx)
            })}>
            {
                for ctx.props().options.iter().map(|opt| {
                    if opt == &self.selected {
                        html! {
                            <option value={opt.to_string()} selected=true>{opt}</option>
                        }
                    } else {
                        html! {
                            <option value={opt.to_string()}>{opt}</option>
                        }
                    }
                })

            }
            </select>
        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            Msg::SelectionChanged(idx) => {
                if let Some(selected) = ctx.props().options.get(idx) {
                    self.selected = selected.clone();
                    ctx.props().selection_changed.emit(selected.clone());
                }
                true
            }
        }
    }
}