Struct respo::RespoEffect

source ·
pub struct RespoEffect {
    pub args: Vec<RespoEffectArg>,
    /* private fields */
}
Expand description

effects that attached to components

Fields§

§args: Vec<RespoEffectArg>

arguments passed to this effect. the events WillUpdate and Updated are triggered when these arguments are changed

Implementations§

Examples found in repository?
src/respo/patch.rs (line 57)
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
pub fn patch_tree<T>(
  tree: &RespoNode<T>,
  old_tree: &RespoNode<T>,
  mount_target: &Node,
  changes: &[DomChange<T>],
  handle_event: RespoEventMarkFn,
) -> Result<(), String>
where
  T: Debug + Clone,
{
  // let el = mount_target.dyn_ref::<Element>().expect("to element");

  if mount_target.child_nodes().length() != 1 {
    return Err(format!(
      "expected a single node under mount target, got: {:?}",
      mount_target.child_nodes().length()
    ));
  }

  // handle BeforeUpdate before DOM changes
  for op in changes {
    if let DomChange::Effect {
      coord,
      effect_type,
      skip_indexes,
      ..
    } = op
    {
      if effect_type == &RespoEffectType::BeforeUpdate {
        let target = find_coord_dom_target(&mount_target.first_child().ok_or("mount position")?, &op.get_dom_path())?;
        let target_tree = if effect_type == &RespoEffectType::BeforeUnmount {
          load_coord_target_tree(old_tree, coord)?
        } else {
          load_coord_target_tree(tree, coord)?
        };
        if let RespoNode::Component(_, effects, _) = target_tree {
          for (idx, effect) in effects.iter().enumerate() {
            if !skip_indexes.contains(&(idx as u32)) {
              effect.run(effect_type.to_owned(), &target)?;
            }
          }
        } else {
          crate::util::log!("expected component for effects, got: {}", target_tree);
        }
      }
    }
  }

  for op in changes {
    // crate::util::log!("op: {:?}", op);
    let coord = op.get_coord();
    let target = find_coord_dom_target(&mount_target.first_child().ok_or("mount position")?, &op.get_dom_path())?;
    match op {
      DomChange::ModifyAttrs { set, unset, .. } => {
        let el = target.dyn_ref::<Element>().expect("load as element");
        for (k, v) in set {
          if k == "innerText" {
            el.dyn_ref::<HtmlElement>().ok_or("to html element")?.set_inner_text(v);
          } else if k == "innerHTML" {
            el.set_inner_html(v);
          } else if k == "htmlFor" {
            el.dyn_ref::<HtmlLabelElement>().ok_or("to label element")?.set_html_for(v);
          } else if k == "value" {
            match el.tag_name().as_str() {
              "INPUT" => {
                let input_el = el.dyn_ref::<HtmlInputElement>().expect("to input");
                let prev_value = input_el.value();
                if &prev_value != v {
                  input_el.set_value(v);
                }
              }
              "TEXTAREA" => {
                let textarea_el = el.dyn_ref::<HtmlTextAreaElement>().expect("to textarea");
                let prev_value = textarea_el.value();
                if &prev_value != v {
                  textarea_el.set_value(v);
                }
              }
              name => {
                return Err(format!("unsupported value for {}", name));
              }
            }
          } else {
            el.set_attribute(k, v).expect("to set attribute");
          }
        }
        for k in unset {
          if k == "innerText" {
            el.dyn_ref::<HtmlElement>().ok_or("to html element")?.set_inner_text("");
          } else if k == "innerHTML" {
            el.set_inner_html("");
          } else if k == "value" {
            let input_el = el.dyn_ref::<HtmlInputElement>().expect("to input");
            let prev_value = input_el.value();
            if !prev_value.is_empty() {
              input_el.set_value("");
            }
          } else {
            el.remove_attribute(k).expect("to remove attribute");
          }
        }
      }
      DomChange::ModifyStyle { set, unset, .. } => {
        let style = target.dyn_ref::<HtmlElement>().expect("into html element").style();
        for s in unset {
          style.remove_property(s).expect("remove style");
        }
        for (k, v) in set {
          style.set_property(k, v).expect("set style");
        }
      }
      DomChange::ModifyEvent { add, remove, coord, .. } => {
        let el = target.dyn_ref::<Element>().expect("to element");
        for k in add.iter() {
          let handler = handle_event.clone();
          attach_event(el, k, coord, handler)?;
        }
        let el = el.dyn_ref::<HtmlElement>().expect("html element");
        for k in remove {
          match k.as_str() {
            "click" => {
              el.set_onclick(None);
            }
            "input" => {
              el.set_oninput(None);
            }
            _ => warn_1(&format!("TODO event {}", k).into()),
          }
        }
      }
      DomChange::ReplaceElement { node, .. } => {
        let parent = target.parent_element().expect("load parent");
        let handler = handle_event.clone();
        let new_element = build_dom_tree(node, &coord, handler).expect("build element");
        parent
          .dyn_ref::<Node>()
          .expect("to node")
          .insert_before(&new_element, Some(&target))
          .expect("element inserted");
        target.dyn_ref::<Element>().expect("get node").remove();
      }
      DomChange::ModifyChildren { operations, coord, .. } => {
        let base_tree = load_coord_target_tree(tree, coord)?;
        let old_base_tree = load_coord_target_tree(old_tree, coord)?;
        for op in operations {
          let handler = handle_event.clone();
          match op {
            ChildDomOp::Append(k, node) => {
              let mut next_coord = coord.to_owned();
              next_coord.push(RespoCoord::Key(k.to_owned()));
              let new_element = build_dom_tree(node, &next_coord, handler).expect("new element");
              target
                .dyn_ref::<Node>()
                .expect("to node")
                .append_child(&new_element)
                .expect("element appended");
            }
            ChildDomOp::Prepend(k, node) => {
              let mut next_coord = coord.to_owned();
              next_coord.push(RespoCoord::Key(k.to_owned()));
              let new_element = build_dom_tree(node, &next_coord, handler).expect("new element");
              if target.child_nodes().length() == 0 {
                target
                  .dyn_ref::<Node>()
                  .expect("to node")
                  .append_child(&new_element)
                  .expect("element appended");
              } else {
                let base = target.dyn_ref::<Node>().expect("to node").first_child().ok_or("to first child")?;
                target
                  .dyn_ref::<Node>()
                  .expect("to node")
                  .insert_before(&new_element, Some(&base))
                  .expect("element appended");
              }
            }
            ChildDomOp::RemoveAt(idx) => {
              let child = target
                .dyn_ref::<Element>()
                .expect("get node")
                .children()
                .item(*idx)
                .ok_or_else(|| format!("child to remove not found at {}", &idx))?;
              target.remove_child(&child).expect("child removed");
            }
            ChildDomOp::InsertAfter(idx, k, node) => {
              let children = target.dyn_ref::<Element>().expect("get node").children();
              if idx >= &children.length() {
                return Err(format!("child to insert not found at {}", &idx));
              } else {
                let handler = handle_event.clone();
                let mut next_coord = coord.to_owned();
                next_coord.push(RespoCoord::Key(k.to_owned()));
                let new_element = build_dom_tree(node, &next_coord, handler).expect("new element");
                match (idx + 1).cmp(&children.length()) {
                  Ordering::Less => {
                    let child = children.item(*idx + 1).ok_or_else(|| format!("child not found at {}", &idx))?;
                    target.insert_before(&new_element, Some(&child)).expect("element inserted");
                  }
                  Ordering::Equal => {
                    target.append_child(&new_element).expect("element appended");
                  }
                  Ordering::Greater => {
                    return Err(format!("out of bounds: {} of {} at coord {:?}", idx, &children.length(), coord));
                  }
                }
              }
            }
            ChildDomOp::NestedEffect {
              nested_coord,
              nested_dom_path: nesteed_dom_path,
              effect_type,
              skip_indexes,
            } => {
              let target_tree = if effect_type == &RespoEffectType::BeforeUnmount {
                load_coord_target_tree(&old_base_tree, nested_coord)?
              } else {
                load_coord_target_tree(&base_tree, nested_coord)?
              };
              let nested_el = find_coord_dom_target(&target, nesteed_dom_path)?;
              if let RespoNode::Component(_, effects, _) = target_tree {
                for (idx, effect) in effects.iter().enumerate() {
                  if !skip_indexes.contains(&(idx as u32)) {
                    effect.run(effect_type.to_owned(), &nested_el)?;
                  }
                }
              } else {
                crate::util::log!("expected component for effects, got: {}", target_tree);
              }
            }
          }
        }
      }

      DomChange::Effect {
        coord,
        effect_type,
        skip_indexes,
        ..
      } => {
        if effect_type == &RespoEffectType::BeforeUpdate {
          // should be handled before current pass
          continue;
        }
        let target_tree = if effect_type == &RespoEffectType::BeforeUnmount {
          load_coord_target_tree(old_tree, coord)?
        } else {
          load_coord_target_tree(tree, coord)?
        };
        if let RespoNode::Component(_, effects, _) = target_tree {
          for (idx, effect) in effects.iter().enumerate() {
            if !skip_indexes.contains(&(idx as u32)) {
              effect.run(effect_type.to_owned(), &target)?;
            }
          }
        } else {
          crate::util::log!("expected component for effects, got: {}", target_tree);
        }
      }
    }
  }
  Ok(())
}
Examples found in repository?
src/respo/primes.rs (line 315)
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
  pub fn effect<U, V>(&mut self, args: &[V], handler: U) -> &mut Self
  where
    U: Fn(Vec<RespoEffectArg>, RespoEffectType, &Node) -> Result<(), String> + 'static,
    V: Serialize + Clone,
  {
    match self {
      RespoNode::Component(_, ref mut effects, _) => {
        effects.push(RespoEffect::new(args.to_vec(), handler));
        self
      }
      RespoNode::Element { .. } => unreachable!("effects are on components"),
      RespoNode::Referenced(_) => {
        unreachable!("should not be called on a referenced node");
      }
    }
  }
  /// add an empty args effect on component, which does not update
  pub fn stable_effect<U>(&mut self, handler: U) -> &mut Self
  where
    U: Fn(Vec<RespoEffectArg>, RespoEffectType, &Node) -> Result<(), String> + 'static,
  {
    match self {
      RespoNode::Component(_, ref mut effects, _) => {
        effects.push(RespoEffect::new(vec![] as Vec<()>, handler));
        self
      }
      RespoNode::Element { .. } => unreachable!("effects are on components"),
      RespoNode::Referenced(_) => {
        unreachable!("should not be called on a referenced node");
      }
    }
  }

no need to have args, only handler

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

closure are not compared, changes happen in and passed via args

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.