本文經過對virtual-dom的源碼進行閱讀和分析,針對Virtual DOM的結構和相關的Diff算法進行講解,讓讀者可以對整個數據結構以及相關的Diff算法有必定的瞭解。javascript
Virtual DOM中Diff算法獲得的結果如何映射到真實DOM中,咱們將在下一篇博客揭曉。java
本文的主要內容爲:node
注:這個Virtual DOM的實現並非React Virtual DOM的源碼,而是基於virtual-dom這個庫。二者在原理上相似,而且這個庫更加簡單容易理解。相較於這個庫,React對Virtual DOM作了進一步的優化和調整,我會在後續的博客中進行分析。git
做爲Virtual DOM的元數據結構,VirtualNode位於vnode/vnode.js
文件中。咱們截取一部分聲明代碼來看下內部結構:github
function VirtualNode(tagName, properties, children, key, namespace) {
this.tagName = tagName
this.properties = properties || noProperties //props對象,Object類型
this.children = children || noChildren //子節點,Array類型
this.key = key != null ? String(key) : undefined
this.namespace = (typeof namespace === "string") ? namespace : null
...
this.count = count + descendants
this.hasWidgets = hasWidgets
this.hasThunks = hasThunks
this.hooks = hooks
this.descendantHooks = descendantHooks
}
VirtualNode.prototype.version = version //VirtualNode版本號,isVnode()檢測標誌
VirtualNode.prototype.type = "VirtualNode" // VirtualNode類型,isVnode()檢測標誌
複製代碼
上面就是一個VirtualNode的完整結構,包含了特定的標籤名、屬性、子節點等。算法
VText是一個純文本的節點,對應的是HTML中的純文本。所以,這個屬性也只有text
這一個字段。數組
function VirtualText(text) {
this.text = String(text)
}
VirtualText.prototype.version = version
VirtualText.prototype.type = "VirtualText"
複製代碼
VPatch是表示須要對Virtual DOM執行的操做記錄的數據結構。它位於vnode/vpatch.js
文件中。咱們來看下里面的具體代碼:數據結構
// 定義了操做的常量,如Props變化,增長節點等
VirtualPatch.NONE = 0
VirtualPatch.VTEXT = 1
VirtualPatch.VNODE = 2
VirtualPatch.WIDGET = 3
VirtualPatch.PROPS = 4
VirtualPatch.ORDER = 5
VirtualPatch.INSERT = 6
VirtualPatch.REMOVE = 7
VirtualPatch.THUNK = 8
module.exports = VirtualPatch
function VirtualPatch(type, vNode, patch) {
this.type = Number(type) //操做類型
this.vNode = vNode //須要操做的節點
this.patch = patch //須要操做的內容
}
VirtualPatch.prototype.version = version
VirtualPatch.prototype.type = "VirtualPatch"
複製代碼
其中常量定義了對VNode節點的操做。例如:VTEXT就是增長一個VText節點,PROPS就是當前節點有Props屬性改變。app
瞭解了虛擬DOM中的三個結構,那咱們下面來看下Virtual DOM的Diff算法。dom
這個Diff算法是Virtual DOM中最核心的一個算法。經過輸入初始狀態A(VNode)和最終狀態B(VNode),這個算法能夠獲得從A到B的變化步驟(VPatch),根據獲得的這一連串步驟,咱們就能夠知道哪些節點須要新增,哪些節點須要刪除,哪些節點的屬性有了變化。在這個Diff算法中,又分紅了三部分:
下面,咱們就來一個一個介紹這些Diff算法。
該算法是針對於單個VNode的比較算法。它是用於兩個樹中單個節點比較的場景。具體算法以下,若是不想直接閱讀源碼的同窗也能夠翻到下面,會有相關代碼流程說明供你們參考:
function walk(a, b, patch, index) {
if (a === b) {
return
}
var apply = patch[index]
var applyClear = false
if (isThunk(a) || isThunk(b)) {
thunks(a, b, patch, index)
} else if (b == null) {
// If a is a widget we will add a remove patch for it
// Otherwise any child widgets/hooks must be destroyed.
// This prevents adding two remove patches for a widget.
if (!isWidget(a)) {
clearState(a, patch, index)
apply = patch[index]
}
apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
} else if (isVNode(b)) {
if (isVNode(a)) {
if (a.tagName === b.tagName &&
a.namespace === b.namespace &&
a.key === b.key) {
var propsPatch = diffProps(a.properties, b.properties)
if (propsPatch) {
apply = appendPatch(apply,
new VPatch(VPatch.PROPS, a, propsPatch))
}
apply = diffChildren(a, b, patch, apply, index)
} else {
apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
applyClear = true
}
} else {
apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
applyClear = true
}
} else if (isVText(b)) {
if (!isVText(a)) {
apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
applyClear = true
} else if (a.text !== b.text) {
apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
}
} else if (isWidget(b)) {
if (!isWidget(a)) {
applyClear = true
}
apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
}
if (apply) {
patch[index] = apply
}
if (applyClear) {
clearState(a, patch, index)
}
}
複製代碼
代碼具體邏輯以下:
a
和b
這兩個VNode全等,則認爲沒有修改,直接返回。thunks
。a
是widget且b
爲空,那麼經過遞歸將a
和它的子節點的remove
操做添加到patch中。b
是VNode的話,
a
也是VNode,那麼比較tagName
、namespace
、key
,若是相同則比較兩個VNode的Props(用下面提到的diffProps算法),同時比較兩個VNode的children(用下面提到的diffChildren算法);若是不一樣則直接將b
節點的insert
操做添加到patch中,同時將標記位置爲true。a
不是VNode,那麼直接將b
節點的insert
操做添加到patch中,同時將標記位置爲true。b
是VText的話,看a
的類型是否爲VText,若是不是,則將VText
操做添加到patch中,而且將標誌位設置爲true;若是是且文本內容不一樣,則將VText
操做添加到patch中。b
是Widget的話,看a
的類型是否爲widget,若是是,將標誌位設置爲true。不論a
類型爲何,都將Widget
操做添加到patch中。a
和它的子節點的remove
操做添加到patch中。這就是單個VNode節點的diff算法全過程。這個算法是整個diff算法的入口,兩棵樹的比較就是從這個算法開始的。
看完了單個VNode節點的diff算法,咱們來看下上面提到的diffProps
算法。
該算法是針對於兩個比較的VNode節點的Props比較算法。它是用於兩個場景中key值和標籤名都相同的狀況。具體算法以下,若是不想直接閱讀源碼的同窗也能夠翻到下面,會有相關代碼流程說明供你們參考:
function diffProps(a, b) {
var diff
for (var aKey in a) {
if (!(aKey in b)) {
diff = diff || {}
diff[aKey] = undefined
}
var aValue = a[aKey]
var bValue = b[aKey]
if (aValue === bValue) {
continue
} else if (isObject(aValue) && isObject(bValue)) {
if (getPrototype(bValue) !== getPrototype(aValue)) {
diff = diff || {}
diff[aKey] = bValue
} else if (isHook(bValue)) {
diff = diff || {}
diff[aKey] = bValue
} else {
var objectDiff = diffProps(aValue, bValue)
if (objectDiff) {
diff = diff || {}
diff[aKey] = objectDiff
}
}
} else {
diff = diff || {}
diff[aKey] = bValue
}
}
for (var bKey in b) {
if (!(bKey in a)) {
diff = diff || {}
diff[bKey] = b[bKey]
}
}
return diff
}
複製代碼
代碼具體邏輯以下:
a
對象。
b
,則將此值存儲下來,value賦值爲undefined
。b
對象的值;若是b
對應的value是hook
的話,記錄b的值。b
對應的value進行記錄。b
對象,將全部a
對象中不存在的key值對應的對象都記錄下來。整個算法的大體流程以下,由於比較簡單,就不畫相關流程圖了。若是邏輯有些繞的話,能夠配合代碼食用,效果更佳。
下面讓咱們來看下最後一個算法,就是關於兩個VNode節點的children屬性的diffChildren
算法。這個個diff算法分爲兩個部分,第一部分是將變化後的結果b
的children進行順序調整的算法,保證可以快速的和a
的children進行比較;第二部分就是將a
的children與從新排序調整後的b
的children進行比較,獲得相關的patch。下面,讓咱們一個一個算法來看。
該算法的做用是將b
節點的children數組進行調整從新排序,讓a
和b
兩個children之間的diff算法更加節約時間。具體代碼以下:
function reorder(aChildren, bChildren) {
// O(M) time, O(M) memory
var bChildIndex = keyIndex(bChildren)
var bKeys = bChildIndex.keys // have "key" prop,object
var bFree = bChildIndex.free //don't have "key" prop,array
// all children of b don't have "key"
if (bFree.length === bChildren.length) {
return {
children: bChildren,
moves: null
}
}
// O(N) time, O(N) memory
var aChildIndex = keyIndex(aChildren)
var aKeys = aChildIndex.keys
var aFree = aChildIndex.free
// all children of a don't have "key"
if (aFree.length === aChildren.length) {
return {
children: bChildren,
moves: null
}
}
// O(MAX(N, M)) memory
var newChildren = []
var freeIndex = 0
var freeCount = bFree.length
var deletedItems = 0
// Iterate through a and match a node in b
// O(N) time,
for (var i = 0 ; i < aChildren.length; i++) {
var aItem = aChildren[i]
var itemIndex
if (aItem.key) {
if (bKeys.hasOwnProperty(aItem.key)) {
// Match up the old keys
itemIndex = bKeys[aItem.key]
newChildren.push(bChildren[itemIndex])
} else {
// Remove old keyed items
itemIndex = i - deletedItems++
newChildren.push(null)
}
} else {
// Match the item in a with the next free item in b
if (freeIndex < freeCount) {
itemIndex = bFree[freeIndex++]
newChildren.push(bChildren[itemIndex])
} else {
// There are no free items in b to match with
// the free items in a, so the extra free nodes
// are deleted.
itemIndex = i - deletedItems++
newChildren.push(null)
}
}
}
var lastFreeIndex = freeIndex >= bFree.length ?
bChildren.length :
bFree[freeIndex]
// Iterate through b and append any new keys
// O(M) time
for (var j = 0; j < bChildren.length; j++) {
var newItem = bChildren[j]
if (newItem.key) {
if (!aKeys.hasOwnProperty(newItem.key)) {
// Add any new keyed items
// We are adding new items to the end and then sorting them
// in place. In future we should insert new items in place.
newChildren.push(newItem)
}
} else if (j >= lastFreeIndex) {
// Add any leftover non-keyed items
newChildren.push(newItem)
}
}
var simulate = newChildren.slice()
var simulateIndex = 0
var removes = []
var inserts = []
var simulateItem
for (var k = 0; k < bChildren.length;) {
var wantedItem = bChildren[k]
simulateItem = simulate[simulateIndex]
// remove items
while (simulateItem === null && simulate.length) {
removes.push(remove(simulate, simulateIndex, null))
simulateItem = simulate[simulateIndex]
}
if (!simulateItem || simulateItem.key !== wantedItem.key) {
// if we need a key in this position...
if (wantedItem.key) {
if (simulateItem && simulateItem.key) {
// if an insert doesn't put this key in place, it needs to move
if (bKeys[simulateItem.key] !== k + 1) {
removes.push(remove(simulate, simulateIndex, simulateItem.key))
simulateItem = simulate[simulateIndex]
// if the remove didn't put the wanted item in place, we need to insert it
if (!simulateItem || simulateItem.key !== wantedItem.key) {
inserts.push({key: wantedItem.key, to: k})
}
// items are matching, so skip ahead
else {
simulateIndex++
}
}
else {
inserts.push({key: wantedItem.key, to: k})
}
}
else {
inserts.push({key: wantedItem.key, to: k})
}
k++
}
// a key in simulate has no matching wanted key, remove it
else if (simulateItem && simulateItem.key) {
removes.push(remove(simulate, simulateIndex, simulateItem.key))
}
}
else {
simulateIndex++
k++
}
}
// remove all the remaining nodes from simulate
while(simulateIndex < simulate.length) {
simulateItem = simulate[simulateIndex]
removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
}
// If the only moves we have are deletes then we can just
// let the delete patch remove these items.
if (removes.length === deletedItems && !inserts.length) {
return {
children: newChildren,
moves: null
}
}
return {
children: newChildren,
moves: {
removes: removes,
inserts: inserts
}
}
}
複製代碼
下面,咱們來簡單介紹下這個排序算法:
a
和b
中的children是否擁有key字段,若是沒有,直接返回b
的children數組。a
的children元素。
move
操做patch(即remove
+insert
)。move
操做列表。經過上面這個排序算法,咱們能夠獲得一個新的b
的children數組。在使用這個數組來進行比較厚,咱們能夠將兩個children數組之間比較的時間複雜度從o(n^2)轉換成o(n)。具體的方法和效果咱們能夠看下面的DiffChildren算法。
function diffChildren(a, b, patch, apply, index) {
var aChildren = a.children
var orderedSet = reorder(aChildren, b.children)
var bChildren = orderedSet.children
var aLen = aChildren.length
var bLen = bChildren.length
var len = aLen > bLen ? aLen : bLen
for (var i = 0; i < len; i++) {
var leftNode = aChildren[i]
var rightNode = bChildren[i]
index += 1
if (!leftNode) {
if (rightNode) {
// Excess nodes in b need to be added
apply = appendPatch(apply,
new VPatch(VPatch.INSERT, null, rightNode))
}
} else {
walk(leftNode, rightNode, patch, index)
}
if (isVNode(leftNode) && leftNode.count) {
index += leftNode.count
}
}
if (orderedSet.moves) {
// Reorder nodes last
apply = appendPatch(apply, new VPatch(
VPatch.ORDER,
a,
orderedSet.moves
))
}
return apply
}
複製代碼
經過上面的從新排序算法整理了之後,兩個children比較就只需在相同下標的狀況下比較了,即aChildren的第N個元素和bChildren的第N個元素進行比較。而後較長的那個元素作insert
操做(bChildren)或者remove
操做(aChildren)便可。最後,咱們將move操做再增長到patch中,就可以抵消咱們在reorder時對整個數組的操做。這樣只須要一次便利就獲得了最終的patch值。
整個Virtual DOM的diff算法設計的很是精巧,經過三個不一樣的分部算法來實現了VNode、Props和Children的diff算法,將整個Virtual DOM的的diff操做分紅了三類。同時三個算法又互相遞歸調用,對兩個Virtual DOM數作了一次(僞)深度優先的遞歸比較。
下面一片博客,我會介紹如何將獲得的VPatch操做應用到真實的DOM中,從而致使HTML樹的變化。