All files index.js

70.54% Statements 91/129
54.84% Branches 34/62
100% Functions 9/9
70.59% Lines 84/119
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 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 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307    1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x                     23x     22x     22x     22x     4x 3x 3x                         51x   31x   31x   31x     31x     4x   3x 3x     1x   1x   1x 1x                         2x 2x 2x 2x                                 3x 2x 2x 2x 2x 2x       3x 2x 2x 2x 2x 2x   2x 2x                                   31x 31x 31x 31x     31x 30x 30x 30x   30x                                                                                 30x 29x 29x 29x   29x                 29x     2x   1x 1x 1x           4x                                   71x 45x 45x                         62x                         31x                     12x 2x 2x 2x 2x 2x 2x       12x 12x 12x                         23x    
'use strict'
 
setDOM.KEY = 'data-key'
setDOM.IGNORE = 'data-ignore'
setDOM.CHECKSUM = 'data-checksum'
var parseHTML = require('./parse-html')
var KEY_PREFIX = '_set-dom-'
var NODE_MOUNTED = KEY_PREFIX + 'mounted'
var MOUNT_EVENT = 'mount'
var DISMOUNT_EVENT = 'dismount'
var ELEMENT_TYPE = window.Node.ELEMENT_NODE
var DOCUMENT_TYPE = window.Node.DOCUMENT_NODE
 
// Expose api.
module.exports = setDOM
 
/**
 * @description
 * Updates existing dom to match a new dom.
 *
 * @param {Node} prev - The html entity to update.
 * @param {String|Node} next - The updated html(entity).
 */
function setDOM (prev, next) {
  // Ensure a realish dom node is provided.
  assert(prev && prev.nodeType, 'You must provide a valid node to update.')
 
  // Alias document element with document.
  if (prev.nodeType === DOCUMENT_TYPE) prev = prev.documentElement
 
  // If a string was provided we will parse it as dom.
  if (typeof next === 'string') next = parseHTML(next, prev.nodeName)
 
  // Update the node.
  setNode(prev, next)
 
  // Trigger mount events on initial set.
  if (!prev[NODE_MOUNTED]) {
    prev[NODE_MOUNTED] = true
    dispatch(prev, MOUNT_EVENT)
  }
}
 
/**
 * @private
 * @description
 * Updates a specific htmlNode and does whatever it takes to convert it to another one.
 *
 * @param {Node} prev - The previous HTMLNode.
 * @param {Node} next - The updated HTMLNode.
 */
function setNode (prev, next) {
  if (prev.nodeType === next.nodeType) {
    // Handle regular element node updates.
    Eif (prev.nodeType === ELEMENT_TYPE) {
      // Ignore elements if their checksum matches.
      Iif (getCheckSum(prev) === getCheckSum(next)) return prev
      // Ignore elements that explicity choose not to be diffed.
      Iif (isIgnored(prev) && isIgnored(next)) return prev
 
      // Update all children (and subchildren).
      setChildNodes(prev, next)
 
      // Update the elements attributes / tagName.
      if (prev.nodeName === next.nodeName) {
        // If we have the same nodename then we can directly update the attributes.
        setAttributes(prev, prev.attributes, next.attributes)
        return prev
      } else {
        // Otherwise clone the new node to use as the existing node.
        var newPrev = next.cloneNode()
        // Copy over all existing children from the original node.
        while (prev.firstChild) newPrev.appendChild(prev.firstChild)
        // Replace the original node with the new one with the right tag.
        prev.parentNode.replaceChild(newPrev, prev)
        return newPrev
      }
    } else {
      // Handle other types of node updates (text/comments/etc).
      // If both are the same type of node we can update directly.
      if (prev.nodeValue !== next.nodeValue) {
        prev.nodeValue = next.nodeValue
      }
 
      return prev
    }
  } else {
    // we have to replace the node.
    dispatch(prev, DISMOUNT_EVENT)
    prev.parentNode.replaceChild(next, prev)
    dispatch(next, MOUNT_EVENT)
    return next
  }
}
 
/**
 * @private
 * @description
 * Utility that will update one list of attributes to match another.
 *
 * @param {Node} parent - The current parentNode being updated.
 * @param {NamedNodeMap} prev - The previous attributes.
 * @param {NamedNodeMap} next - The updated attributes.
 */
function setAttributes (parent, prev, next) {
  var i, a, b, ns, name
 
  // Remove old attributes.
  for (i = prev.length; i--;) {
    a = prev[i]
    ns = a.namespaceURI
    name = a.localName
    b = next.getNamedItemNS(ns, name)
    Eif (!b) prev.removeNamedItemNS(ns, name)
  }
 
  // Set new attributes.
  for (i = next.length; i--;) {
    a = next[i]
    ns = a.namespaceURI
    name = a.localName
    b = prev.getNamedItemNS(ns, name)
    Eif (!b) {
      // Add a new attribute.
      next.removeNamedItemNS(ns, name)
      prev.setNamedItemNS(a)
    } else if (b.value !== a.value) {
      // Update existing attribute.
      b.value = a.value
    }
  }
}
 
/**
 * @private
 * @description
 * Utility that will nodes childern to match another nodes children.
 *
 * @param {Node} prevParent - The existing parent node.
 * @param {Node} nextParent - The new parent node.
 */
function setChildNodes (oldParent, newParent) {
  var curKey, checkKey, seenNodes, checkNode, foundNode
  var oldNode = oldParent.firstChild
  var newNode = newParent.firstChild
  var nextToCheck = oldNode
  var nextSibling = newNode
 
  // Loop over new nodes and perform updates.
  while (nextSibling) {
    newNode = nextSibling
    curKey = getKey(newNode)
    nextSibling = newNode.nextSibling
 
    Iif (curKey) {
      // Try looking up key in previous node key cache.
      foundNode = seenNodes && seenNodes[curKey]
      // Start looking further in the previous nodelist.
      if (!foundNode) {
        console.log('looking for', curKey)
        while (nextToCheck) {
          checkNode = nextToCheck
          checkKey = getKey(checkNode)
          nextToCheck = nextToCheck.nextSibling
          console.log('check', checkNode.nodeName, checkKey)
          if (checkKey) {
            if (checkKey === curKey) {
              console.log('found the key', checkNode.nodeName)
              // Store the node to be moved below.
              foundNode = checkNode
              break
            } else {
              console.log('found a key to cache', checkNode.nodeName)
              seenNodes = seenNodes || {}
              seenNodes[checkKey] = checkNode
            }
          }
        }
      }
 
      if (foundNode) {
        // Check to see if the node is already in the proper place.
        if (foundNode !== oldNode) {
          console.log('move', foundNode.nodeName, 'to before', oldNode.nodeName)
          // If the node is out of place we move it.
          oldParent.insertBefore(foundNode, oldNode)
        }
 
        // And update the existing node
        newNode = setNode(foundNode, newNode)
      } else {
        // Otherwise we insert the new node here.
        oldParent.insertBefore(dispatch(newNode, MOUNT_EVENT), oldNode)
      }
    } else {
      if (oldNode) {
        checkNode = oldNode
        checkKey = getKey(checkNode)
        nextToCheck = oldNode = checkNode.nextSibling
 
        Iif (checkKey) {
          // If we got a keyed node we do nothing but track it.
          seenNodes = seenNodes || {}
          seenNodes[checkKey] = checkNode
 
          oldParent.insertBefore(newNode, checkKey)
          dispatch(newNode, MOUNT_EVENT)
        } else {
          // Otherwise we diff the two unkeyed nodes.
          setNode(oldNode, newNode)
        }
 
        oldNode = nextToCheck
      } else {
        nextToCheck = null
        oldParent.appendChild(newNode)
        dispatch(newNode, MOUNT_EVENT)
      }
    }
  }
 
  // If we have any remaining remove them from the end.
  while (nextToCheck) {
    console.log('remove', nextToCheck.nodeName)
    checkNode = nextToCheck
    nextToCheck = checkNode.nextSibling
    oldParent.removeChild(checkNode)
  }
}
 
/**
 * @private
 * @description
 * Utility to try to pull a key out of an element.
 * Uses 'data-key' if possible and falls back to 'id'.
 *
 * @param {Node} node - The node to get the key for.
 * @return {String}
 */
function getKey (node) {
  if (node.nodeType !== ELEMENT_TYPE) return
  var key = node.getAttribute(setDOM.KEY) || node.id
  if (key) return KEY_PREFIX + key
}
 
/**
 * @private
 * @description
 * Utility to try to pull a checksum attribute from an element.
 * Uses 'data-checksum' or user specified checksum property.
 *
 * @param {Node} node - The node to get the checksum for.
 * @return {String|NaN}
 */
function getCheckSum (node) {
  return node.getAttribute(setDOM.CHECKSUM) || NaN
}
 
/**
 * @private
 * @description
 * Utility to try to check if an element should be ignored by the algorithm.
 * Uses 'data-ignore' or user specified ignore property.
 *
 * @param {Node} node - The node to check if it should be ignored.
 * @return {Boolean}
 */
function isIgnored (node) {
  return node.getAttribute(setDOM.IGNORE) != null
}
 
/**
 * Recursively trigger an event for a node and it's children.
 * Only emits events for keyed nodes.
 *
 * @param {Node} node - the initial node.
 */
function dispatch (node, type) {
  // Trigger event for this element if it has a key.
  if (getKey(node)) {
    var ev = document.createEvent('Event')
    var prop = { value: node }
    ev.initEvent(type, false, false)
    Object.defineProperty(ev, 'target', prop)
    Object.defineProperty(ev, 'srcElement', prop)
    node.dispatchEvent(ev)
  }
 
  // Dispatch to all children.
  var child = node.firstChild
  while (child) child = dispatch(child, type).nextSibling
  return node
}
 
/**
 * @private
 * @description
 * Confirm that a value is truthy, throws an error message otherwise.
 *
 * @param {*} val - the val to test.
 * @param {String} msg - the error message on failure.
 * @throws Error
 */
function assert (val, msg) {
  if (!val) throw new Error('set-dom: ' + msg)
}