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
use crate::Button;
use css_in_rust_next::Style;
use yew::{html, Callback, Children, Component, Context, Html, Properties};
use yew_feather::{chevron_right::ChevronRight, trash_2::Trash2, x::X};

#[derive(PartialEq)]
pub enum ActionButton {
  Submit(bool),
  Update(bool),
  Delete,
}

#[derive(PartialEq, Properties)]
pub struct ModalProperties {
  pub height: String,
  pub width: String,
  #[prop_or_default]
  pub children: Children,
  pub event: Callback<ModalMessage>,
  #[prop_or_default]
  pub actions: Vec<ActionButton>,
  pub modal_title: String,
}

pub enum ModalMessage {
  Cancel,
  Submit,
  Update,
  Delete,
}

pub struct Modal {
  style: Style,
}

impl Component for Modal {
  type Message = ModalMessage;
  type Properties = ModalProperties;

  fn create(_ctx: &Context<Self>) -> Self {
    let style = Style::create("Component", include_str!("modal.css")).unwrap();
    Modal { style }
  }

  fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
    ctx.props().event.emit(msg);
    true
  }

  fn view(&self, ctx: &Context<Self>) -> Html {
    let buttons: Html = ctx
      .props()
      .actions
      .iter()
      .map(|action| match action {
        ActionButton::Submit(enabled) => html!(
          <Button
            label="Submit"
            icon={html!(<ChevronRight/>)}
            disabled={!*enabled}
            onclick={ctx.link().callback(|_|ModalMessage::Submit)}
            />
        ),
        ActionButton::Update(enabled) => html!(
          <Button
            label="Update"
            icon={html!(<ChevronRight/>)}
            disabled={!*enabled}
            onclick={ctx.link().callback(|_|ModalMessage::Update)}
            />
        ),
        ActionButton::Delete => html!(
          <Button
            label="Delete"
            icon={html!(<Trash2/>)}
            onclick={ctx.link().callback(|_|ModalMessage::Delete)}
            />
        ),
      })
      .collect();

    html!(
      <div class={self.style.clone()}>
        <div class="inner">
          <div class="title">
            <span> {ctx.props().modal_title.clone()} </span>
            <span class="close" onclick={ctx.link().callback(|_|ModalMessage::Cancel)} > <X/> </span>
          </div>
          <div class="modalContent">
            { for ctx.props().children.iter() }
          </div>
          <div class="actions">
            <Button
              label="Cancel"
              icon={html!(<X/>)}
              onclick={ctx.link().callback(|_|ModalMessage::Cancel)}
              />
            {buttons}
          </div>
        </div>
      </div>
    )
  }
}