Skip to content

Instantly share code, notes, and snippets.

@jondlm
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jondlm/a756b92223960fcc0441 to your computer and use it in GitHub Desktop.
Save jondlm/a756b92223960fcc0441 to your computer and use it in GitHub Desktop.
[requirebin] virtual dom example
var h = require('virtual-dom/h');
var diff = require('virtual-dom/diff');
var patch = require('virtual-dom/patch');
var createElement = require('virtual-dom/create-element');
// Create a deterministic function that declares what the DOM should look like
// Model data in, vtree out
function render(user) {
return h('div#bro', {}, [
h('div', {}, 'First name: ' + user.firstName),
h('div', {}, 'Email: ' + user.email),
h('div',
{style: {color: 'green'}},
'Bank Balance: $' + String(user.bankBalance.toFixed(2))
)
]);
}
// Initialise the "model"
var user = {firstName: 'jon', email: 'jondlm@gmail.com', bankBalance: 0 };
var tree = render(user); // We need an initial tree
var rootNode = createElement(tree); // Create an initial root DOM node ...
document.body.appendChild(rootNode); // ... and it should be in the document
setInterval(function(){
user.bankBalance += Math.random(); // Update the model
var newTree = render(user); // Render a new virtual tree
var patches = diff(tree, newTree); // Generate the diff
rootNode = patch(rootNode, patches); // Apply the diff
tree = newTree; // Update our reference of the master tree
}, 1000);
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var isArray=require("x-is-array");var isString=require("x-is-string");var VNode=require("vtree/vnode.js");var VText=require("vtree/vtext.js");var isVNode=require("vtree/is-vnode");var isVText=require("vtree/is-vtext");var isWidget=require("vtree/is-widget");var parseTag=require("./parse-tag");module.exports=h;function h(tagName,properties,children){var tag,props,childNodes,key;if(!children){if(isChildren(properties)){children=properties;properties=undefined}}tag=parseTag(tagName,properties);if(!isString(tag)){props=tag.properties;tag=tag.tagName}else{props=properties}if(isArray(children)){var len=children.length;for(var i=0;i<len;i++){var child=children[i];if(isString(child)){children[i]=new VText(child)}}childNodes=children}else if(isString(children)){childNodes=[new VText(children)]}else if(isChild(children)){childNodes=[children]}if(props&&"key"in props){key=props.key;delete props.key}return new VNode(tag,props,childNodes,key)}function isChild(x){return isVNode(x)||isVText(x)||isWidget(x)}function isChildren(x){return isArray(x)||isString(x)||isChild(x)}},{"./parse-tag":2,"vtree/is-vnode":5,"vtree/is-vtext":6,"vtree/is-widget":7,"vtree/vnode.js":9,"vtree/vtext.js":10,"x-is-array":11,"x-is-string":12}],2:[function(require,module,exports){var split=require("browser-split");var classIdSplit=/([\.#]?[a-zA-Z0-9_:-]+)/;var notClassId=/^\.|#/;module.exports=parseTag;function parseTag(tag,props){if(!tag){return"div"}var noId=!props||!("id"in props);var tagParts=split(tag,classIdSplit);var tagName=null;if(notClassId.test(tagParts[1])){tagName="div"}var id,classes,part,type,i;for(i=0;i<tagParts.length;i++){part=tagParts[i];if(!part){continue}type=part.charAt(0);if(!tagName){tagName=part}else if(type==="."){classes=classes||[];classes.push(part.substring(1,part.length))}else if(type==="#"&&noId){id=part.substring(1,part.length)}}var parsedTags;if(props){if(id!==undefined&&!("id"in props)){props.id=id}if(classes){if(props.className){classes.push(props.className)}props.className=classes.join(" ")}parsedTags=tagName}else if(classes||id!==undefined){var properties={};if(id!==undefined){properties.id=id}if(classes){properties.className=classes.join(" ")}parsedTags={tagName:tagName,properties:properties}}else{parsedTags=tagName}return parsedTags}},{"browser-split":3}],3:[function(require,module,exports){module.exports=function split(undef){var nativeSplit=String.prototype.split,compliantExecNpcg=/()??/.exec("")[1]===undef,self;self=function(str,separator,limit){if(Object.prototype.toString.call(separator)!=="[object RegExp]"){return nativeSplit.call(str,separator,limit)}var output=[],flags=(separator.ignoreCase?"i":"")+(separator.multiline?"m":"")+(separator.extended?"x":"")+(separator.sticky?"y":""),lastLastIndex=0,separator=new RegExp(separator.source,flags+"g"),separator2,match,lastIndex,lastLength;str+="";if(!compliantExecNpcg){separator2=new RegExp("^"+separator.source+"$(?!\\s)",flags)}limit=limit===undef?-1>>>0:limit>>>0;while(match=separator.exec(str)){lastIndex=match.index+match[0].length;if(lastIndex>lastLastIndex){output.push(str.slice(lastLastIndex,match.index));if(!compliantExecNpcg&&match.length>1){match[0].replace(separator2,function(){for(var i=1;i<arguments.length-2;i++){if(arguments[i]===undef){match[i]=undef}}})}if(match.length>1&&match.index<str.length){Array.prototype.push.apply(output,match.slice(1))}lastLength=match[0].length;lastLastIndex=lastIndex;if(output.length>=limit){break}}if(separator.lastIndex===match.index){separator.lastIndex++}}if(lastLastIndex===str.length){if(lastLength||!separator.test("")){output.push("")}}else{output.push(str.slice(lastLastIndex))}return output.length>limit?output.slice(0,limit):output};return self}()},{}],4:[function(require,module,exports){module.exports=isHook;function isHook(hook){return hook&&typeof hook.hook==="function"&&!hook.hasOwnProperty("hook")}},{}],5:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":8}],6:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":8}],7:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],8:[function(require,module,exports){module.exports="1"},{}],9:[function(require,module,exports){var version=require("./version");var isVNode=require("./is-vnode");var isWidget=require("./is-widget");var isVHook=require("./is-vhook");module.exports=VirtualNode;var noProperties={};var noChildren=[];function VirtualNode(tagName,properties,children,key,namespace){this.tagName=tagName;this.properties=properties||noProperties;this.children=children||noChildren;this.key=key!=null?String(key):undefined;this.namespace=typeof namespace==="string"?namespace:null;var count=children&&children.length||0;var descendants=0;var hasWidgets=false;var descendantHooks=false;var hooks;for(var propName in properties){if(properties.hasOwnProperty(propName)){var property=properties[propName];if(isVHook(property)){if(!hooks){hooks={}}hooks[propName]=property}}}for(var i=0;i<count;i++){var child=children[i];if(isVNode(child)){descendants+=child.count||0;if(!hasWidgets&&child.hasWidgets){hasWidgets=true}if(!descendantHooks&&(child.hooks||child.descendantHooks)){descendantHooks=true}}else if(!hasWidgets&&isWidget(child)){if(typeof child.destroy==="function"){hasWidgets=true}}}this.count=count+descendants;this.hasWidgets=hasWidgets;this.hooks=hooks;this.descendantHooks=descendantHooks}VirtualNode.prototype.version=version;VirtualNode.prototype.type="VirtualNode"},{"./is-vhook":4,"./is-vnode":5,"./is-widget":7,"./version":8}],10:[function(require,module,exports){var version=require("./version");module.exports=VirtualText;function VirtualText(text){this.text=String(text)}VirtualText.prototype.version=version;VirtualText.prototype.type="VirtualText"},{"./version":8}],11:[function(require,module,exports){var nativeIsArray=Array.isArray;var toString=Object.prototype.toString;module.exports=nativeIsArray||isArray;function isArray(obj){return toString.call(obj)==="[object Array]"}},{}],12:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=isString;function isString(obj){return toString.call(obj)==="[object String]"}},{}],"virtual-dom/h":[function(require,module,exports){var h=require("./h/index.js");module.exports=h},{"./h/index.js":1}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=isObject;function isObject(x){return typeof x==="object"&&x!==null}},{}],2:[function(require,module,exports){var isArray=require("x-is-array");var isObject=require("is-object");var VPatch=require("./vpatch");var isVNode=require("./is-vnode");var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");var handleThunk=require("./handle-thunk");module.exports=diff;function diff(a,b){var patch={a:a};walk(a,b,patch,0);return patch}function walk(a,b,patch,index){if(a===b){if(isThunk(a)||isThunk(b)){thunks(a,b,patch,index)}else{hooks(b,patch,index)}return}var apply=patch[index];if(b==null){apply=appendPatch(apply,new VPatch(VPatch.REMOVE,a,b));destroyWidgets(a,patch,index)}else if(isThunk(a)||isThunk(b)){thunks(a,b,patch,index)}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,b.hooks);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));destroyWidgets(a,patch,index)}}else{apply=appendPatch(apply,new VPatch(VPatch.VNODE,a,b));destroyWidgets(a,patch,index)}}else if(isVText(b)){if(!isVText(a)){apply=appendPatch(apply,new VPatch(VPatch.VTEXT,a,b));destroyWidgets(a,patch,index)}else if(a.text!==b.text){apply=appendPatch(apply,new VPatch(VPatch.VTEXT,a,b))}}else if(isWidget(b)){apply=appendPatch(apply,new VPatch(VPatch.WIDGET,a,b));if(!isWidget(a)){destroyWidgets(a,patch,index)}}if(apply){patch[index]=apply}}function diffProps(a,b,hooks){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(hooks&&aKey in hooks){diff=diff||{};diff[aKey]=bValue}else{if(isObject(aValue)&&isObject(bValue)){if(getPrototype(bValue)!==getPrototype(aValue)){diff=diff||{};diff[aKey]=bValue}else{var objectDiff=diffProps(aValue,bValue);if(objectDiff){diff=diff||{};diff[aKey]=objectDiff}}}else if(aValue!==bValue){diff=diff||{};diff[aKey]=bValue}}}for(var bKey in b){if(!(bKey in a)){diff=diff||{};diff[bKey]=b[bKey]}}return diff}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}function diffChildren(a,b,patch,apply,index){var aChildren=a.children;var bChildren=reorder(aChildren,b.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){apply=appendPatch(apply,new VPatch(VPatch.INSERT,null,rightNode))}}else if(!rightNode){if(leftNode){patch[index]=new VPatch(VPatch.REMOVE,leftNode,null);destroyWidgets(leftNode,patch,index)}}else{walk(leftNode,rightNode,patch,index)}if(isVNode(leftNode)&&leftNode.count){index+=leftNode.count}}if(bChildren.moves){apply=appendPatch(apply,new VPatch(VPatch.ORDER,a,bChildren.moves))}return apply}function destroyWidgets(vNode,patch,index){if(isWidget(vNode)){if(typeof vNode.destroy==="function"){patch[index]=new VPatch(VPatch.REMOVE,vNode,null)}}else if(isVNode(vNode)&&vNode.hasWidgets){var children=vNode.children;var len=children.length;for(var i=0;i<len;i++){var child=children[i];index+=1;destroyWidgets(child,patch,index);if(isVNode(child)&&child.count){index+=child.count}}}}function thunks(a,b,patch,index){var nodes=handleThunk(a,b);var thunkPatch=diff(nodes.a,nodes.b);if(hasPatches(thunkPatch)){patch[index]=new VPatch(VPatch.THUNK,null,thunkPatch)}}function hasPatches(patch){for(var index in patch){if(index!=="a"){return true}}return false}function hooks(vNode,patch,index){if(isVNode(vNode)){if(vNode.hooks){patch[index]=new VPatch(VPatch.PROPS,vNode.hooks,vNode.hooks)}if(vNode.descendantHooks){var children=vNode.children;var len=children.length;for(var i=0;i<len;i++){var child=children[i];index+=1;hooks(child,patch,index);if(isVNode(child)&&child.count){index+=child.count}}}}}function reorder(aChildren,bChildren){var bKeys=keyIndex(bChildren);if(!bKeys){return bChildren}var aKeys=keyIndex(aChildren);if(!aKeys){return bChildren}var bMatch={},aMatch={};for(var key in bKeys){bMatch[bKeys[key]]=aKeys[key]}for(var key in aKeys){aMatch[aKeys[key]]=bKeys[key]}var aLen=aChildren.length;var bLen=bChildren.length;var len=aLen>bLen?aLen:bLen;var shuffle=[];var freeIndex=0;var i=0;var moveIndex=0;var moves={};var removes=moves.removes={};var reverse=moves.reverse={};var hasMoves=false;while(freeIndex<len){var move=aMatch[i];if(move!==undefined){shuffle[i]=bChildren[move];if(move!==moveIndex){moves[move]=moveIndex;reverse[moveIndex]=move;hasMoves=true}moveIndex++}else if(i in aMatch){shuffle[i]=undefined;removes[i]=moveIndex++;hasMoves=true}else{while(bMatch[freeIndex]!==undefined){freeIndex++}if(freeIndex<len){var freeChild=bChildren[freeIndex];if(freeChild){shuffle[i]=freeChild;if(freeIndex!==moveIndex){hasMoves=true;moves[freeIndex]=moveIndex;reverse[moveIndex]=freeIndex}moveIndex++}freeIndex++}}i++}if(hasMoves){shuffle.moves=moves}return shuffle}function keyIndex(children){var i,keys;for(i=0;i<children.length;i++){var child=children[i];if(child.key!==undefined){keys=keys||{};keys[child.key]=i}}return keys}function appendPatch(apply,patch){if(apply){if(isArray(apply)){apply.push(patch)}else{apply=[apply,patch]}return apply}else{return patch}}},{"./handle-thunk":3,"./is-thunk":4,"./is-vnode":5,"./is-vtext":6,"./is-widget":7,"./vpatch":9,"is-object":1,"x-is-array":10}],3:[function(require,module,exports){var isVNode=require("./is-vnode");var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");module.exports=handleThunk;function handleThunk(a,b){var renderedA=a;var renderedB=b;if(isThunk(b)){renderedB=renderThunk(b,a)}if(isThunk(a)){renderedA=renderThunk(a,null)}return{a:renderedA,b:renderedB}}function renderThunk(thunk,previous){var renderedThunk=thunk.vnode;if(!renderedThunk){renderedThunk=thunk.vnode=thunk.render(previous)}if(!(isVNode(renderedThunk)||isVText(renderedThunk)||isWidget(renderedThunk))){throw new Error("thunk did not return a valid node")}return renderedThunk}},{"./is-thunk":4,"./is-vnode":5,"./is-vtext":6,"./is-widget":7}],4:[function(require,module,exports){module.exports=isThunk;function isThunk(t){return t&&t.type==="Thunk"}},{}],5:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":8}],6:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":8}],7:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],8:[function(require,module,exports){module.exports="1"},{}],9:[function(require,module,exports){var version=require("./version");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"},{"./version":8}],10:[function(require,module,exports){var nativeIsArray=Array.isArray;var toString=Object.prototype.toString;module.exports=nativeIsArray||isArray;function isArray(obj){return toString.call(obj)==="[object Array]"}},{}],"virtual-dom/diff":[function(require,module,exports){var diff=require("vtree/diff");module.exports=diff},{"vtree/diff":2}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){module.exports=isObject;function isObject(x){return typeof x==="object"&&x!==null}},{}],3:[function(require,module,exports){var isObject=require("is-object");var isHook=require("vtree/is-vhook");module.exports=applyProperties;function applyProperties(node,props,previous){for(var propName in props){var propValue=props[propName];if(propValue===undefined){removeProperty(node,props,previous,propName)}else if(isHook(propValue)){propValue.hook(node,propName,previous?previous[propName]:undefined)}else{if(isObject(propValue)){patchObject(node,props,previous,propName,propValue)}else if(propValue!==undefined){node[propName]=propValue}}}}function removeProperty(node,props,previous,propName){if(previous){var previousValue=previous[propName];if(!isHook(previousValue)){if(propName==="attributes"){for(var attrName in previousValue){node.removeAttribute(attrName)}}else if(propName==="style"){for(var i in previousValue){node.style[i]=""}}else if(typeof previousValue==="string"){node[propName]=""}else{node[propName]=null}}}}function patchObject(node,props,previous,propName,propValue){var previousValue=previous?previous[propName]:undefined;if(propName==="attributes"){for(var attrName in propValue){var attrValue=propValue[attrName];if(attrValue===undefined){node.removeAttribute(attrName)}else{node.setAttribute(attrName,attrValue)}}return}if(previousValue&&isObject(previousValue)&&getPrototype(previousValue)!==getPrototype(propValue)){node[propName]=propValue;return}if(!isObject(node[propName])){node[propName]={}}var replacer=propName==="style"?"":undefined;for(var k in propValue){var value=propValue[k];node[propName][k]=value===undefined?replacer:value}}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}},{"is-object":2,"vtree/is-vhook":12}],4:[function(require,module,exports){var document=require("global/document");var applyProperties=require("./apply-properties");var isVNode=require("vtree/is-vnode");var isVText=require("vtree/is-vtext");var isWidget=require("vtree/is-widget");var handleThunk=require("vtree/handle-thunk");module.exports=createElement;function createElement(vnode,opts){var doc=opts?opts.document||document:document;var warn=opts?opts.warn:null;vnode=handleThunk(vnode).a;if(isWidget(vnode)){return vnode.init()}else if(isVText(vnode)){return doc.createTextNode(vnode.text)}else if(!isVNode(vnode)){if(warn){warn("Item is not a valid virtual dom node",vnode)}return null}var node=vnode.namespace===null?doc.createElement(vnode.tagName):doc.createElementNS(vnode.namespace,vnode.tagName);var props=vnode.properties;applyProperties(node,props);var children=vnode.children;for(var i=0;i<children.length;i++){var childNode=createElement(children[i],opts);if(childNode){node.appendChild(childNode)}}return node}},{"./apply-properties":3,"global/document":6,"vtree/handle-thunk":10,"vtree/is-vnode":13,"vtree/is-vtext":14,"vtree/is-widget":15}],5:[function(require,module,exports){var noChild={};module.exports=domIndex;function domIndex(rootNode,tree,indices,nodes){if(!indices||indices.length===0){return{}}else{indices.sort(ascending);return recurse(rootNode,tree,indices,nodes,0)}}function recurse(rootNode,tree,indices,nodes,rootIndex){nodes=nodes||{};if(rootNode){if(indexInRange(indices,rootIndex,rootIndex)){nodes[rootIndex]=rootNode}var vChildren=tree.children;if(vChildren){var childNodes=rootNode.childNodes;for(var i=0;i<tree.children.length;i++){rootIndex+=1;var vChild=vChildren[i]||noChild;var nextIndex=rootIndex+(vChild.count||0);if(indexInRange(indices,rootIndex,nextIndex)){recurse(childNodes[i],vChild,indices,nodes,rootIndex)}rootIndex=nextIndex}}}return nodes}function indexInRange(indices,left,right){if(indices.length===0){return false}var minIndex=0;var maxIndex=indices.length-1;var currentIndex;var currentItem;while(minIndex<=maxIndex){currentIndex=(maxIndex+minIndex)/2>>0;currentItem=indices[currentIndex];if(minIndex===maxIndex){return currentItem>=left&&currentItem<=right}else if(currentItem<left){minIndex=currentIndex+1}else if(currentItem>right){maxIndex=currentIndex-1}else{return true}}return false}function ascending(a,b){return a>b?1:-1}},{}],6:[function(require,module,exports){(function(global){var topLevel=typeof global!=="undefined"?global:typeof window!=="undefined"?window:{};var minDoc=require("min-document");if(typeof document!=="undefined"){module.exports=document}else{var doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"];if(!doccy){doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"]=minDoc}module.exports=doccy}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"min-document":1}],7:[function(require,module,exports){var applyProperties=require("./apply-properties");var isWidget=require("vtree/is-widget");var VPatch=require("vtree/vpatch");var render=require("./create-element");var updateWidget=require("./update-widget");module.exports=applyPatch;function applyPatch(vpatch,domNode,renderOptions){var type=vpatch.type;var vNode=vpatch.vNode;var patch=vpatch.patch;switch(type){case VPatch.REMOVE:return removeNode(domNode,vNode);case VPatch.INSERT:return insertNode(domNode,patch,renderOptions);case VPatch.VTEXT:return stringPatch(domNode,vNode,patch,renderOptions);case VPatch.WIDGET:return widgetPatch(domNode,vNode,patch,renderOptions);case VPatch.VNODE:return vNodePatch(domNode,vNode,patch,renderOptions);case VPatch.ORDER:reorderChildren(domNode,patch);return domNode;case VPatch.PROPS:applyProperties(domNode,patch,vNode.properties);return domNode;case VPatch.THUNK:return replaceRoot(domNode,renderOptions.patch(domNode,patch,renderOptions));default:return domNode}}function removeNode(domNode,vNode){var parentNode=domNode.parentNode;if(parentNode){parentNode.removeChild(domNode)}destroyWidget(domNode,vNode);return null}function insertNode(parentNode,vNode,renderOptions){var newNode=render(vNode,renderOptions);if(parentNode){parentNode.appendChild(newNode)}return parentNode}function stringPatch(domNode,leftVNode,vText,renderOptions){var newNode;if(domNode.nodeType===3){domNode.replaceData(0,domNode.length,vText.text);newNode=domNode}else{var parentNode=domNode.parentNode;newNode=render(vText,renderOptions);if(parentNode){parentNode.replaceChild(newNode,domNode)}}destroyWidget(domNode,leftVNode);return newNode}function widgetPatch(domNode,leftVNode,widget,renderOptions){if(updateWidget(leftVNode,widget)){return widget.update(leftVNode,domNode)||domNode}var parentNode=domNode.parentNode;var newWidget=render(widget,renderOptions);if(parentNode){parentNode.replaceChild(newWidget,domNode)}destroyWidget(domNode,leftVNode);return newWidget}function vNodePatch(domNode,leftVNode,vNode,renderOptions){var parentNode=domNode.parentNode;var newNode=render(vNode,renderOptions);if(parentNode){parentNode.replaceChild(newNode,domNode)}destroyWidget(domNode,leftVNode);return newNode}function destroyWidget(domNode,w){if(typeof w.destroy==="function"&&isWidget(w)){w.destroy(domNode)}}function reorderChildren(domNode,bIndex){var children=[];var childNodes=domNode.childNodes;var len=childNodes.length;var i;var reverseIndex=bIndex.reverse;for(i=0;i<len;i++){children.push(domNode.childNodes[i])}var insertOffset=0;var move;var node;var insertNode;for(i=0;i<len;i++){move=bIndex[i];if(move!==undefined&&move!==i){if(reverseIndex[i]>i){insertOffset++}node=children[move];insertNode=childNodes[i+insertOffset]||null;if(node!==insertNode){domNode.insertBefore(node,insertNode)}if(move<i){insertOffset--}}if(i in bIndex.removes){insertOffset++}}}function replaceRoot(oldRoot,newRoot){if(oldRoot&&newRoot&&oldRoot!==newRoot&&oldRoot.parentNode){console.log(oldRoot);oldRoot.parentNode.replaceChild(newRoot,oldRoot)}return newRoot}},{"./apply-properties":3,"./create-element":4,"./update-widget":9,"vtree/is-widget":15,"vtree/vpatch":17}],8:[function(require,module,exports){var document=require("global/document");var isArray=require("x-is-array");var domIndex=require("./dom-index");var patchOp=require("./patch-op");module.exports=patch;function patch(rootNode,patches){return patchRecursive(rootNode,patches)}function patchRecursive(rootNode,patches,renderOptions){var indices=patchIndices(patches);if(indices.length===0){return rootNode}var index=domIndex(rootNode,patches.a,indices);var ownerDocument=rootNode.ownerDocument;if(!renderOptions){renderOptions={patch:patchRecursive};if(ownerDocument!==document){renderOptions.document=ownerDocument}}for(var i=0;i<indices.length;i++){var nodeIndex=indices[i];rootNode=applyPatch(rootNode,index[nodeIndex],patches[nodeIndex],renderOptions)}return rootNode}function applyPatch(rootNode,domNode,patchList,renderOptions){if(!domNode){return rootNode}var newNode;if(isArray(patchList)){for(var i=0;i<patchList.length;i++){newNode=patchOp(patchList[i],domNode,renderOptions);if(domNode===rootNode){rootNode=newNode}}}else{newNode=patchOp(patchList,domNode,renderOptions);if(domNode===rootNode){rootNode=newNode}}return rootNode}function patchIndices(patches){var indices=[];for(var key in patches){if(key!=="a"){indices.push(Number(key))}}return indices}},{"./dom-index":5,"./patch-op":7,"global/document":6,"x-is-array":18}],9:[function(require,module,exports){var isWidget=require("vtree/is-widget");module.exports=updateWidget;function updateWidget(a,b){if(isWidget(a)&&isWidget(b)){if("name"in a&&"name"in b){return a.id===b.id}else{return a.init===b.init}}return false}},{"vtree/is-widget":15}],10:[function(require,module,exports){var isVNode=require("./is-vnode");var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");module.exports=handleThunk;function handleThunk(a,b){var renderedA=a;var renderedB=b;if(isThunk(b)){renderedB=renderThunk(b,a)}if(isThunk(a)){renderedA=renderThunk(a,null)}return{a:renderedA,b:renderedB}}function renderThunk(thunk,previous){var renderedThunk=thunk.vnode;if(!renderedThunk){renderedThunk=thunk.vnode=thunk.render(previous)}if(!(isVNode(renderedThunk)||isVText(renderedThunk)||isWidget(renderedThunk))){throw new Error("thunk did not return a valid node")}return renderedThunk}},{"./is-thunk":11,"./is-vnode":13,"./is-vtext":14,"./is-widget":15}],11:[function(require,module,exports){module.exports=isThunk;function isThunk(t){return t&&t.type==="Thunk"}},{}],12:[function(require,module,exports){module.exports=isHook;function isHook(hook){return hook&&typeof hook.hook==="function"&&!hook.hasOwnProperty("hook")}},{}],13:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":16}],14:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":16}],15:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],16:[function(require,module,exports){module.exports="1"},{}],17:[function(require,module,exports){var version=require("./version");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"},{"./version":16}],18:[function(require,module,exports){var nativeIsArray=Array.isArray;var toString=Object.prototype.toString;module.exports=nativeIsArray||isArray;function isArray(obj){return toString.call(obj)==="[object Array]"}},{}],"virtual-dom/patch":[function(require,module,exports){var patch=require("vdom/patch");module.exports=patch},{"vdom/patch":8}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){module.exports=isObject;function isObject(x){return typeof x==="object"&&x!==null}},{}],3:[function(require,module,exports){var isObject=require("is-object");var isHook=require("vtree/is-vhook");module.exports=applyProperties;function applyProperties(node,props,previous){for(var propName in props){var propValue=props[propName];if(propValue===undefined){removeProperty(node,props,previous,propName)}else if(isHook(propValue)){propValue.hook(node,propName,previous?previous[propName]:undefined)}else{if(isObject(propValue)){patchObject(node,props,previous,propName,propValue)}else if(propValue!==undefined){node[propName]=propValue}}}}function removeProperty(node,props,previous,propName){if(previous){var previousValue=previous[propName];if(!isHook(previousValue)){if(propName==="attributes"){for(var attrName in previousValue){node.removeAttribute(attrName)}}else if(propName==="style"){for(var i in previousValue){node.style[i]=""}}else if(typeof previousValue==="string"){node[propName]=""}else{node[propName]=null}}}}function patchObject(node,props,previous,propName,propValue){var previousValue=previous?previous[propName]:undefined;if(propName==="attributes"){for(var attrName in propValue){var attrValue=propValue[attrName];if(attrValue===undefined){node.removeAttribute(attrName)}else{node.setAttribute(attrName,attrValue)}}return}if(previousValue&&isObject(previousValue)&&getPrototype(previousValue)!==getPrototype(propValue)){node[propName]=propValue;return}if(!isObject(node[propName])){node[propName]={}}var replacer=propName==="style"?"":undefined;for(var k in propValue){var value=propValue[k];node[propName][k]=value===undefined?replacer:value}}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}},{"is-object":2,"vtree/is-vhook":8}],4:[function(require,module,exports){var document=require("global/document");var applyProperties=require("./apply-properties");var isVNode=require("vtree/is-vnode");var isVText=require("vtree/is-vtext");var isWidget=require("vtree/is-widget");var handleThunk=require("vtree/handle-thunk");module.exports=createElement;function createElement(vnode,opts){var doc=opts?opts.document||document:document;var warn=opts?opts.warn:null;vnode=handleThunk(vnode).a;if(isWidget(vnode)){return vnode.init()}else if(isVText(vnode)){return doc.createTextNode(vnode.text)}else if(!isVNode(vnode)){if(warn){warn("Item is not a valid virtual dom node",vnode)}return null}var node=vnode.namespace===null?doc.createElement(vnode.tagName):doc.createElementNS(vnode.namespace,vnode.tagName);var props=vnode.properties;applyProperties(node,props);var children=vnode.children;for(var i=0;i<children.length;i++){var childNode=createElement(children[i],opts);if(childNode){node.appendChild(childNode)}}return node}},{"./apply-properties":3,"global/document":5,"vtree/handle-thunk":6,"vtree/is-vnode":9,"vtree/is-vtext":10,"vtree/is-widget":11}],5:[function(require,module,exports){(function(global){var topLevel=typeof global!=="undefined"?global:typeof window!=="undefined"?window:{};var minDoc=require("min-document");if(typeof document!=="undefined"){module.exports=document}else{var doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"];if(!doccy){doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"]=minDoc}module.exports=doccy}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"min-document":1}],6:[function(require,module,exports){var isVNode=require("./is-vnode");
var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");module.exports=handleThunk;function handleThunk(a,b){var renderedA=a;var renderedB=b;if(isThunk(b)){renderedB=renderThunk(b,a)}if(isThunk(a)){renderedA=renderThunk(a,null)}return{a:renderedA,b:renderedB}}function renderThunk(thunk,previous){var renderedThunk=thunk.vnode;if(!renderedThunk){renderedThunk=thunk.vnode=thunk.render(previous)}if(!(isVNode(renderedThunk)||isVText(renderedThunk)||isWidget(renderedThunk))){throw new Error("thunk did not return a valid node")}return renderedThunk}},{"./is-thunk":7,"./is-vnode":9,"./is-vtext":10,"./is-widget":11}],7:[function(require,module,exports){module.exports=isThunk;function isThunk(t){return t&&t.type==="Thunk"}},{}],8:[function(require,module,exports){module.exports=isHook;function isHook(hook){return hook&&typeof hook.hook==="function"&&!hook.hasOwnProperty("hook")}},{}],9:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":12}],10:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":12}],11:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],12:[function(require,module,exports){module.exports="1"},{}],"virtual-dom/create-element":[function(require,module,exports){var createElement=require("vdom/create-element");module.exports=createElement},{"vdom/create-element":4}]},{},[]);var h=require("virtual-dom/h");var diff=require("virtual-dom/diff");var patch=require("virtual-dom/patch");var createElement=require("virtual-dom/create-element");function render(user){return h("div#bro",{},[h("div",{},"First name: "+user.firstName),h("div",{},"Email: "+user.email),h("div",{style:{color:"green"}},"Bank Balance: $"+String(user.bankBalance.toFixed(2)))])}var user={firstName:"jon",email:"jondlm@gmail.com",bankBalance:0};var tree=render(user);var rootNode=createElement(tree);document.body.appendChild(rootNode);setInterval(function(){user.bankBalance+=Math.random();var newTree=render(user);var patches=diff(tree,newTree);rootNode=patch(rootNode,patches);tree=newTree},1e3);
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"virtual-dom": "0.0.21"
}
}
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; }
body, html { height: 100%; width: 100%; }</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment