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
use crate::dom;
use crate::event;
use crate::Html;
use std::any::Any;
use std::collections::hash_set::HashSet;
use std::rc::Rc;

/// Wrapper of Component
pub trait Composable {
    fn update(&mut self, id: u128, msg: Rc<Any>) -> Option<(Box<Any>, u128)>;
    fn render(&mut self, id: Option<u128>) -> dom::Node;
    fn get_id(&self) -> u128;
    fn set_parent_id(&mut self, id: u128);
}

/// Component constructed by State-update-render
pub struct Component<Msg, State, Sub>
where
    Msg: 'static,
    State: 'static,
    Sub: 'static,
{
    state: State,
    update: fn(&mut State, &Msg) -> Option<Sub>,
    subscribe: Option<Box<FnMut(Sub) -> Box<Any>>>,
    render: fn(&State) -> Html<Msg>,
    children: Vec<Box<Composable>>,
    id: u128,
    parent_id: Option<u128>,
    events: HashSet<u128>,
}

impl<Msg, State, Sub> Component<Msg, State, Sub> {
    /// Creates new component ftom initial state, update, render
    ///
    /// # Example
    ///
    /// ```
    /// fn hello_world_component() -> Component<Msg, State, Sub> {
    ///     Component::new(initial_state, update, render)
    /// }
    ///
    /// struct Msg;
    /// struct State;
    /// struct Sub;
    ///
    /// fn update(_: &mut State, _: &Msg) -> Option<Sub> { None }
    ///
    /// fn render(_: &State) -> Html<Msg> {
    ///     Html::h1(
    ///     Attributes::new(),
    ///     Events::new(),
    ///     vec![
    ///         Html::unsafe_text("hello kagura"),
    ///     ],
    /// )
    /// }
    /// ```
    pub fn new(
        state: State,
        update: fn(&mut State, &Msg) -> Option<Sub>,
        render: fn(&State) -> Html<Msg>,
    ) -> Component<Msg, State, Sub> {
        let id = rand::random::<u128>();
        Component {
            state,
            update,
            render,
            children: vec![],
            id: id,
            subscribe: None,
            parent_id: None,
            events: HashSet::new(),
        }
    }

    fn append_composable(&mut self, mut composable: Box<Composable>) {
        composable.set_parent_id(self.id);
        self.children.push(composable);
    }

    /// Regists binder from child Sub to parent Msg
    ///
    /// #Example
    ///
    /// ```
    /// create_a_child_component(props).subscribe(|sub| {
    ///     match sub {
    ///         ChildComponent::Sub::Input(value) => Box::new(Msg::Send(value))
    ///     }
    /// })
    /// ```
    pub fn subscribe(mut self, sub: impl FnMut(Sub) -> Box<Any> + 'static) -> Self {
        self.subscribe = Some(Box::new(sub));
        self
    }

    fn adapt_html_lazy(&mut self, html: Html<Msg>, child_index: &mut usize, id: u128) -> dom::Node {
        match html {
            Html::Composable(mut composable) => {
                if let Some(child) = self.children.get_mut(*child_index) {
                    *child_index += 1;
                    (*child).render(Some(id))
                } else {
                    let node = composable.render(Some(id));
                    self.append_composable(composable);
                    node
                }
            }
            Html::TextNode(text) => dom::Node::Text(text),
            Html::ElementNode {
                tag_name,
                attributes: _,
                events: _,
                children,
            } => {
                let children = children
                    .into_iter()
                    .map(|child| self.adapt_html_lazy(child, child_index, id))
                    .collect::<Vec<dom::Node>>();
                dom::Node::element(
                    tag_name,
                    dom::Attributes::new(),
                    dom::Events::new(),
                    children,
                    false,
                )
            }
        }
    }

    fn adapt_html_force(&mut self, html: Html<Msg>) -> dom::Node {
        match html {
            Html::Composable(mut composable) => {
                let node = composable.render(None);
                self.append_composable(composable);
                node
            }
            Html::TextNode(text) => dom::Node::Text(text),
            Html::ElementNode {
                tag_name,
                attributes,
                events,
                children,
            } => {
                let children = children
                    .into_iter()
                    .map(|child| self.adapt_html_force(child))
                    .collect::<Vec<dom::Node>>();
                let component_id = self.id;
                let mut dom_events = dom::Events::new();

                for (name, mut handler) in events.handlers {
                    let event_id = rand::random::<u128>();
                    event::add(event_id, move |e| (component_id, Box::new(handler(e))));
                    dom_events.add(name, move |e| {
                        event::dispatch(event_id, e);
                    });
                    self.events.insert(event_id);
                }

                dom::Node::element(tag_name, attributes.attributes, dom_events, children, true)
            }
        }
    }
}

impl<Msg, State, Sub> Composable for Component<Msg, State, Sub> {
    fn update(&mut self, id: u128, msg: Rc<Any>) -> Option<(Box<Any>, u128)> {
        if id == self.id {
            if let Some(msg) = msg.downcast_ref::<Msg>() {
                if let Some(sub) = (self.update)(&mut self.state, msg) {
                    if let Some(parent_id) = self.parent_id {
                        if let Some(subscribe) = &mut self.subscribe {
                            return Some((subscribe(sub), parent_id));
                        }
                    }
                }
            }
        } else {
            let mut first_sub: Option<(Box<Any>, u128)> = None;
            for child in &mut self.children {
                if let Some(sub) = (*child).update(id, msg.clone()) {
                    if first_sub.is_none() {
                        first_sub = Some(sub);
                    }
                }
            }
            if first_sub.is_some() {
                return first_sub;
            }
        }
        None
    }

    fn render(&mut self, id: Option<u128>) -> dom::Node {
        let html = (self.render)(&self.state);
        if let Some(id) = id {
            if id == self.id {
                self.children.clear();
                for event_id in &self.events {
                    event::remove(*event_id);
                }
                self.events.clear();
                self.adapt_html_force(html)
            } else {
                self.adapt_html_lazy(html, &mut 0, id)
            }
        } else {
            self.adapt_html_force(html)
        }
    }

    fn get_id(&self) -> u128 {
        self.id
    }

    fn set_parent_id(&mut self, id: u128) {
        self.parent_id = Some(id);
    }
}