patch function

void patch (
  1. Node parent,
  2. dynamic element,
  3. dynamic oldNode,
  4. dynamic node
)

Implementation

void patch(Node parent, dynamic element, dynamic oldNode, dynamic node) {
  if (oldNode is String && node is String && oldNode != node && element is Text) {
    element.replaceWith(Text(node));
  }

  if ((oldNode is Node || oldNode == null) && node is String) {
    var newEl = document.createElement(node);
    parent.insertBefore(newEl, element);
    element.remove();
    element = newEl;
  }

  if ((oldNode is String || oldNode == null) && node is BaseContext) {
    var newEl = render(node);
    parent.insertBefore(newEl, element);
    element.remove();
    element = newEl;
  }

  if (oldNode is BaseContext && node is BaseContext) {
    if (node.props !=null) {
      (node.props as Map).forEach((key,value){
        if (key is String) {
          if(key.startsWith('on')) {
            return;
          }
        }
        node.el.setAttribute(key, value);
      });
    }
    // 处理子节点
    List oldElements = element.childNodes;
    List oldChildren = oldNode.childrens;
    List children = node.childrens;
    var k = 0;
    while (k < node.childrens.length) {
      var oldNode = null;
      if (k < oldChildren.length - 1) {
        oldNode = oldChildren[k];
      }
      patch(element, oldElements[k], oldNode, children[k]);
      k++;
    }
  }

}