Skip to content

Vue.js设计与实现-简单Diff算法

作者:江月迟迟
发表于:2024-12-10
字数统计:2990 字
预计阅读10分钟
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/@vue/reactivity@3.0.5/dist/reactivity.global.js"></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
  <script>
    function createRenderer(options) {
      const {
        createElement,
        setElementText,
        insert,
        patchProps,
        createText,
        createComment,
        setText,
      } = options;

      function render(vnode, container) {
        if (vnode) {
          // 新node存在,将其与旧node一起传递给patch函数,进行打补丁
          patch(container._vnode, vnode, container);
        } else {
          if (container._vnode) {
            // 旧node存在,且新node不存在,说明是卸载(unmount)操作
            // 只需要将container中的DOM清空即可
            // container.innerHTML = "";
            // 8.5使用innerHTML直接清空是不严谨的,应该对每个DOM元素按照卸载流程清空
            // 调用unmount函数卸载vnode
            unmount(container._vnode);
          }
        }
        // 把vnode存储到container._vnode下面,就是此次渲染结束,新node应该叫做旧node了
        container._vnode = vnode;
      }

      function hydrate() {
        // do sth...
      }

      function patch(n1, n2, container, anchor = null) {
        // doing sth...
        // 如果n1存在,则对比n1和n2的类型
        console.log('update')
        if (n1 && n1.type !== n2.type) {
          // 如果新旧vnode的类型不同,直接将旧vnode卸载
          unmount(n1);
          n1 = null;
        }
        // 代码运行到这里,证明n1和n2所描述的内容相同
        const { type } = n2;
        // 如果n2.type的值是字符串类型,则它描述的是普通标签元素
        if (typeof type === "string") {
          if (!n1) {
            // 挂载
            mountElement(n2, container, anchor);
          } else {
            // 更新
            patchElement(n1, n2);
          }
        } else if (type === Text) {
          // 文本节点
          if (!n1) {
            // 如果没有就节点,那么挂载
            const el = (n2.el = createText(n2.children));
            // 插入
            insert(el, container);
          } else {
            // 旧node存在,替换
            const el = (n2.el = n1.el);
            if (n2.children !== n1.children) {
              setText(el, n2.children);
            }
          }
        } else if (type === Comment) {
          // 文本节点
          if (!n1) {
            // 如果没有就节点,那么挂载
            const el = (n2.el = createComment(n2.children));
            // 插入
            insert(el, container);
          } else {
            // 旧node存在,替换
            const el = (n2.el = n1.el);
            if (n2.children !== n1.children) {
              setText(el, n2.children);
            }
          }
        } else if(type === Fragment) {
          if (!n1) {
            n2.children.forEach(c => patch(null, c, container))
          } else {
            patchChildren(n1, n2, container)
          }
        } 
        else if (typeof type === "object") {
          // 如果n2.type的值的类型是对象,则它描述的是组件
        } else if (type === "xxx") {
          // 处理其他类型的vnode
        }
      }

      function mountElement(vnode, container, anchor = null) {
        // 创建DOM元素
        // 让vnode.el引用真实DOM元素,便于后续卸载操作
        const el = (vnode.el = createElement(vnode.type));

        if (typeof vnode.children === "string") {
          // 如果children是字符串,就直接放进去
          setElementText(el, vnode.children);
        } else if (Array.isArray(vnode.children)) {
          // 如果children是数组,则遍历每一个子节点,并调用patch函数挂载他们
          vnode.children.forEach((child) => {
            patch(null, child, el);
          });
        }

        // 如果vnode.props存在才处理它
        if (vnode.props) {
          // 遍历
          for (const key in vnode.props) {
            const value = vnode.props[key];
            // 使用shouldSetAsProps函数判断是否应该作为DOM Properties代理
            // 直接设置,是el[key]就行了,浏览器代理到DOM Properties上
            // 抽离了依赖浏览器API的代码,封装到配置项中
            patchProps(el, key, null, value);
          }
        }

        insert(el, container, anchor);
      }

      function unmount(vnode) {
        // 如果要卸载的是fragment,那么卸载它的children
        if (vnode.type === Fragment) {
          vnode.children.forEach(c => unmount(c))
          return
        }
        // 根据_vnode获取要卸载的真实DOM元素
        const el = vnode.el;
        // 获取el的父元素
        const parent = el.parentNode;
        parent && parent.removeChild(el);
      }

      function patchChildren(n1, n2, container) {
        // 判断新的子节点的类型是否是文本节点
        // 文本子节点
        if (typeof n2.children === "string") {
          // 旧子节点的类型有三种可能,没有子节点。文本子节点和一组子节点
          // 为一组子节点时,逐个卸载
          if (Array.isArray(n1.children)) {
            n1.children.forEach((child) => unmount(child));
          }
          // 其他情况什么也不用干,直接替换就行
          setElementText(container, n2.children);
        } else if (Array.isArray(n2.children)) {
          // 说明新子节点时一组子节点

          // 在这里,移动DOM前,确保DOM的更新(确保将要移动的DOM是最新的)。
          // 获取新旧children
          const oldChildren = n1.children
          const newChildren = n2.children
          // 新旧的一组子节点的长度
          const oldLen = oldChildren.length
          const newLen = newChildren.length

          // 用来存储寻找过程中遇到的最大索引值
          let lastIndex = 0

          // 遍历新的children
          for(let i = 0; i < newLen; i++) {
            const newVnode = newChildren[i]

            // 在第一层循环中定义变量find,代表是否在旧的一组子节点中找到可复现的节点
            let find = false

            // 遍历旧的children
            for(let j = 0; j < oldLen; j++) {
              const oldVnode = oldChildren[j]
              // 比较新旧vnode,如果找到具有相同key值的两个节点,说明是可复用的节点,不过仍需要调用patch更新
              if (newVnode.key === oldVnode.key) {
                patch(oldVnode, newVnode, container)

                // 一旦找到可复用的节点,将变量find的值设为true
                find = true
                
                // 如果当前找到的节点在旧的children中的索引小于最大索引值lastIndex
                // 说明该节点对应的真实DOM需要移动
                if (j < lastIndex) {
                  // 移动逻辑
                  // 我们经过看图说话可以知道,新的children的顺序就是要插入的顺序
                  // 统一之后插后的方法,找到新的需要移动的子节点newVnode的前一个节点prevVnode,
                  // 然后在真实DOM中将该子节点newVnode插入到前一个节点prevVnode的后面
                  
                  // 先获取newVnode的前一个vnode,即prevVnode
                  const prevVnode = newChildren[i - 1]
                  // 如果prevVnode不存在,则说明当前newVnode是第一个节点 不需要移动
                  if (prevVnode) {
                    // 由于我们要将newVnode对应的真实DOM插入到prevVnode所对应的真实DOM后面
                    // 所以我们需要获取prevVnode所对应的真实DOM的下一个兄弟节点(使用的insertBefore方法)作为描点
                    const anchor = prevVnode.el.nextSibling
                    insert(newVnode.el, container, anchor)
                  }
                } else {
                  // 无需移动,替换lastIndex
                  lastIndex = j
                }
                
                // 因为key值唯一,所以一个二重遍历这个条件只会出现一次,那么手动推出到下一个二重遍历
                break
              }
            }
            // 如果代码运行到这里,find仍为false
            // 说明当前newVnode没有在旧的一组子节点中找到可复用的节点
            // 那么newVnode是新增节点,需要挂载
            if (!find) {
              // 为了将节点挂载到正确位置,先要获取描点元素
              const prevVnode = newChildren[i - 1]
              let anchor = null
              if (prevVnode) {
                // 如果有前一个节点,那么用他的下一个兄弟节点作为描点
                anchor = prevVnode.el.nextSibling
              } else {
                // 如果没有前一个节点,那么挂载的新节点是首个节点
                anchor = container.firstChild
              }
              // 挂载
              patch(null, newVnode, container, anchor)
            }

          }

          // 以上是更新操作。不能删除子节点
          // 在这里,我们在遍历一次,如果发现了需要删除的子节点,执行删除
          for(let i = 0; i < oldLen; i++) {
            const oldVnode = oldChildren[i]
            // 拿旧子节点oldVnode去新子节点里面找
            const has = newChildren.find(vnode => vnode.key === oldVnode.key)
            // 如果没有找到相同key值的节点,就要删除这个节点
            if (!has) {
              unmount(oldVnode)
            }
          }

        } else {
          // 代码运行到这里,说明新子节点不存在
          // 旧子节点是一组子节点,只需逐个卸载
          if (Array.isArray(n1.children)) {
            n1.children.forEach((c) => unmount(c));
          } else if (typeof n1.children === "string") {
            // 旧子节点是文本子节点,清空内容
            setElementText(container, "");
          }
          // 如果没有旧子节点,啥也不干
        }
      }

      function patchElement(n1, n2) {
        // 在上面,已经判断了n1和n2是类型相同的节点,只是要更新而已
        // n1.type === n2.type,并且由于他们是相同的节点,所以n1.el === n2.el (比如说div)
        const el = (n2.el = n1.el);
        const oldProps = n1.props;
        const newProps = n2.props;

        // 更新props

        for (const key in newProps) {
          if (newProps[key] !== oldProps[key]) {
            patchProps(el, key, oldProps[key], newProps[key]);
          }
        }

        for (const key in oldProps) {
          if (!(key in newProps)) {
            // 删除
            patchProps(el, key, oldProps[key], null);
          }
        }

        // 更新children
        patchChildren(n1, n2, el);
      }

      return {
        render,
        hydrate,
      };
    }

    function normalizeClass(originClass) {
      if (typeof originClass === "string") {
        return originClass;
      } else if (
        typeof originClass === "object" &&
        originClass !== null &&
        !Array.isArray(originClass)
      ) {
        return extractKeys(originClass);
      } else if (Array.isArray(originClass)) {
        return originClass.map((item) => [normalizeClass(item)]).join(" ");
      } else {
        return "";
      }

      function extractKeys(originClass) {
        return Object.keys(originClass)
          .filter((key) => originClass[key])
          .join(" ");
      }
    }

    const renderer = createRenderer({
      createElement(tag) {
        return document.createElement(tag);
      },
      setElementText(el, text) {
        el.textContent = text;
      },
      insert(el, parent, anchor = null) {
        parent.insertBefore(el, anchor);
      },
      createText(text) {
        return document.createTextNode(text);
      },
      createComment(comment) {
        return document.createComment(comment);
      },
      setText(el, text) {
        el.nodeValue = text;
      },
      patchProps(el, key, prevValue, nextValue) {
        // 匹配以on开头的属性,认为是事件
        if (/^on/.test(key)) {
          // 获取为该元素伪造的事件处理函数invoker
          // 定义el._vei是一个对象
          let invokers = el._vei || (el._vei = {});
          // 根据事件名称获取invoker
          let invoker = invokers[key];
          const name = key.slice(2).toLowerCase();
          if (nextValue) {
            if (!invoker) {
              // 如果没有,就创建一个
              // vei是vue_event_invoker缩写
              invoker = el._vei[key] = (e) => {
                // 这个e是pointEvent

                // e.timeStamp是事件发生的时间
                // 屏蔽所有绑定时间晚于事件触发时间的事件处理函数的执行
                if (e.timeStamp < invoker.attached) {
                  return;
                }

                // 当伪造的事件处理函数执行时,会执行真正的事件
                // 如果invoke.value是数组,则遍历它并诸葛调用事件处理函数
                if (Array.isArray(invoker.value)) {
                  invoker.value.forEach((fn) => fn(e));
                } else {
                  invoker.value(e);
                }
              };
              // 将真正的事件处理函数赋值给invoker.value
              invoker.value = nextValue;
              // 添加attached属性,存储事件处理函数被绑定的事件
              invoker.attached = performance.now();
              // 绑定invoker作为事件处理函数
              el.addEventListener(name, invoker);
            } else {
              // 如果invoker存在,意味着更新,并且只需要更新invoker的值
              invoker.value = nextValue;
            }
          } else if (invoker) {
            // 新的事件绑定函数不存在,且之前绑定的invoker存在,则移除绑定
            el.removeEventListener(name, invoker);
          }
        }
        // class是比较多的,刚好发现使用className设置性能优化较大
        // 对class进行特殊处理
        else if (key === "class") {
          el.className = nextValue || "";
        } else if (shouldSetAsProps(el, key, nextValue)) {
          // 获取该DOM Properties的类型
          const type = typeof el[key];
          // 如果是布尔类型,并且value是空字符串,则将值矫正为true
          if (type === "boolean" && nextValue === "") {
            el[key] = true;
          } else {
            el[key] = nextValue;
          }
        } else {
          // 如果要设置的属性没有对应的DOM Properties,则使用setAttribute设置属性
          el.setAttribute(key, nextValue);
        }

        function shouldSetAsProps(el, key, value) {
          // 特殊处理
          if (key === "form" && el.tagName === "INPUT") {
            return false;
          }
          return key in el;
        }
      },
    });

    // 执行区

    const Fragment = Symbol()
    const Text = Symbol()
    const Comment = Symbol()

    const oldVnode = {
      type: 'div',
      children: [
        { type: "p", children: "1", key: 1 },
        { type: "p", children: "2", key: 2 },
        { type: "p", children: "hello", key: 3 },
      ],
    };

    const newVnode = {
      type: 'div',
      children: [
        { type: "p", children: "world", key: 3 },
        { type: "p", children: "1", key: 1 },
      ],
    }

    renderer.render(oldVnode, document.querySelector("#app"));
    setTimeout(() => {
      renderer.render(newVnode, document.querySelector("#app"));
    }, 1500);
</script>
</html>