Skip to content

Instantly share code, notes, and snippets.

@kaosat-dev
Created April 15, 2015 13:09
Show Gist options
  • Save kaosat-dev/b1eb2b8924654a84aca7 to your computer and use it in GitHub Desktop.
Save kaosat-dev/b1eb2b8924654a84aca7 to your computer and use it in GitHub Desktop.
requirebin sketch
// require() some stuff from npm (like you were using browserify)
// and then hit Run Code to run it on the right
/*var Immutable = require('immutable');
var diff = require('immutablediff');
var map1 = Immutable.Map({a:1, b:2, c:3,e:{a:42,stuff:"stom"} });
var map2 = Immutable.Map({a:1, b:2, d: 4,e:{c:4,foobar:4564}});
var a = diff(map1, map2);
console.log("blah",a.toJS());*/
//IMMSTRUCT
/*
var immstruct = require('immstruct');
var structure = immstruct({
someBox: { message: 'Hello World!' }
});
var structure = immstruct({ 'foo': 'bar',baz:42, burp:[25,0,"a"] });
var ref = structure.reference('burp');
console.log("hi",ref.cursor().deref())
console.log("hi",""+structure.cursor(['burp']).deref())
structure.cursor(['burp']).deref().map(function(entry){
console.log("yeah",entry);
});*/
var Baobab = require('baobab');
/*var tree = new Baobab({
palette: {
colors: ['yellow', 'purple'],
name: 'Glorious colors'
}
},{maxHistory: 10000});
var colorsCursor = tree.select('palette', 'colors');
colorsCursor.on('update', function() {
console.log('Selected colors have updated:', colorsCursor.get());
});
colorsCursor.push('orange');
tree.undo();*/
var baobab = new Baobab({name: 'Maria'}, {maxHistory: 100000,asynchronous: false});
console.log(baobab)
baobab.set('name', 'Isabella');
// On next frame, when update has been committed
console.log(baobab.get('name'))
baobab.undo()
console.log(baobab.get('name'))
baobab.redo()
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={autoCommit:true,asynchronous:true,clone:false,cloningFunction:null,cursorSingletons:true,maxHistory:0,mixins:[],shiftReferences:false,typology:null,validate:null}},{}],2:[function(require,module,exports){(function(){"use strict";var __allowedOptions={once:"boolean",scope:"object"};var Emitter=function(){this._enabled=true;this._children=[];this._handlers={};this._handlersAll=[]};Emitter.prototype.on=function(a,b,c){var i,l,k,event,eArray,bindingObject;if(typeof b==="function"){eArray=typeof a==="string"?[a]:a;for(i=0,l=eArray.length;i!==l;i+=1){event=eArray[i];if(!event)continue;if(!this._handlers[event])this._handlers[event]=[];bindingObject={handler:b};for(k in c||{})if(__allowedOptions[k])bindingObject[k]=c[k];else throw new Error('The option "'+k+'" is not recognized by Emmett.');this._handlers[event].push(bindingObject)}}else if(a&&typeof a==="object"&&!Array.isArray(a))for(event in a)Emitter.prototype.on.call(this,event,a[event],b);else if(typeof a==="function"){bindingObject={handler:a};for(k in c||{})if(__allowedOptions[k])bindingObject[k]=c[k];else throw new Error('The option "'+k+'" is not recognized by Emmett.');this._handlersAll.push(bindingObject)}else throw new Error("Wrong arguments.");return this};Emitter.prototype.once=function(a,b,c){if(typeof b==="function"){c=c||{};c.once=true;this.on(a,b,c)}else if(a&&typeof a==="object"&&!Array.isArray(a)||typeof a==="function"){b=b||{};b.once=true;this.on(a,b)}else throw new Error("Wrong arguments.");return this};Emitter.prototype.off=function(events,handler){var i,n,j,m,k,a,event,eArray=typeof events==="string"?[events]:events;if(arguments.length===1&&typeof eArray==="function"){handler=arguments[0];for(k in this._handlers){a=[];for(i=0,n=this._handlers[k].length;i!==n;i+=1)if(this._handlers[k][i].handler!==handler)a.push(this._handlers[k][i]);this._handlers[k]=a}a=[];for(i=0,n=this._handlersAll.length;i!==n;i+=1)if(this._handlersAll[i].handler!==handler)a.push(this._handlersAll[i]);this._handlersAll=a}else if(arguments.length===2){for(i=0,n=eArray.length;i!==n;i+=1){event=eArray[i];if(this._handlers[event]){a=[];for(j=0,m=this._handlers[event].length;j!==m;j+=1)if(this._handlers[event][j].handler!==handler)a.push(this._handlers[event][j]);this._handlers[event]=a}if(this._handlers[event]&&this._handlers[event].length===0)delete this._handlers[event]}}return this};Emitter.prototype.unbindAll=function(){var k;this._handlersAll=[];for(k in this._handlers)delete this._handlers[k];return this};Emitter.prototype.emit=function(events,data){var i,n,j,m,z,a,event,child,handlers,eventName,self=this,eArray=typeof events==="string"?[events]:events;if(!this._enabled)return this;data=data===undefined?{}:data;for(i=0,n=eArray.length;i!==n;i+=1){eventName=eArray[i];handlers=(this._handlers[eventName]||[]).concat(this._handlersAll);if(handlers.length){event={type:eventName,data:data||{},target:this};a=[];for(j=0,m=handlers.length;j!==m;j+=1){if(this._handlers[eventName]&&this._handlers[eventName].indexOf(handlers[j])>=0||this._handlersAll.indexOf(handlers[j])>=0){handlers[j].handler.call("scope"in handlers[j]?handlers[j].scope:this,event);if(handlers[j].once)a.push(handlers[j])}}for(z=0;z<a.length;z++){this._handlers[eventName].splice(a.indexOf(a[z]),1)}}}for(i=0,n=this._children.length;i!==n;i+=1){child=this._children[i];child.emit.apply(child,arguments)}return this};Emitter.prototype.child=function(){var self=this,child=new Emitter;child.on("emmett:kill",function(){if(self._children)for(var i=0,l=self._children.length;i<l;i++)if(self._children[i]===child){self._children.splice(i,1);break}});this._children.push(child);return child};function mapHandlers(a){var i,l,h=[];for(i=0,l=a.length;i<l;i++)h.push(a[i].handler);return h}Emitter.prototype.listeners=function(event){var handlers=[],k,i,l;if(!event){handlers=mapHandlers(this._handlersAll);for(k in this._handlers)handlers=handlers.concat(mapHandlers(this._handlers[k]));for(i=0,l=this._children.length;i<l;i++)handlers=handlers.concat(this._children[i].listeners())}else{handlers=mapHandlers(this._handlers[event]);for(i=0,l=this._children.length;i<l;i++)handlers=handlers.concat(this._children[i].listeners(event))}return handlers};Emitter.prototype.kill=function(){this.emit("emmett:kill");this.unbindAll();this._handlers=null;this._handlersAll=null;this._enabled=false;if(this._children)for(var i=0,l=this._children.length;i<l;i++)this._children[i].kill();this._children=null};Emitter.prototype.disable=function(){this._enabled=false;return this};Emitter.prototype.enable=function(){this._enabled=true;return this};Emitter.version="2.1.2";if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=Emitter;exports.Emitter=Emitter}else if(typeof define==="function"&&define.amd)define("emmett",[],function(){return Emitter});else this.Emitter=Emitter}).call(this)},{}],3:[function(require,module,exports){(function(global){"use strict";var __class2type={};var __nativeTypes=["*"];(function(){var k,className,classes=["Arguments","Boolean","Number","String","Function","Array","Date","RegExp","Object"];for(k in classes){className=classes[k];__nativeTypes.push(className.toLowerCase());__class2type["[object "+className+"]"]=className.toLowerCase()}})();function Typology(defs){var _self=this;var _customTypes={};function _scan(obj,type){var a,i,l,k,error,subError,hasStar,hasTypeOf,optional=false,exclusive=false,typeOf=_self.get(obj);if(_self.get(type)==="string"){a=type.replace(/^[\?\!]/,"").split(/\|/);l=a.length;for(i=0;i<l;i++)if(__nativeTypes.indexOf(a[i])<0&&!(a[i]in _customTypes))throw new Error("Invalid type.");if(type.match(/^\?/))optional=true;if(type.replace(/^\?/,"").match(/^\!/))exclusive=true;if(exclusive&&optional)throw new Error("Invalid type.");for(i in a)if(_customTypes[a[i]])if(typeof _customTypes[a[i]].type==="function"?_customTypes[a[i]].type.call(_self,obj)===true:!_scan(obj,_customTypes[a[i]].type)){if(exclusive){error=new Error;error.message='Expected a "'+type+'" but found a '+'"'+a[i]+'".';error.expected=type;error.type=a[i];error.value=obj;return error}else return null}if(obj===null||obj===undefined){if(!exclusive&&!optional){error=new Error;error.message='Expected a "'+type+'" but found a '+'"'+typeOf+'".';error.expected=type;error.type=typeOf;error.value=obj;return error}else return null}else{hasStar=~a.indexOf("*");hasTypeOf=~a.indexOf(typeOf);if(exclusive&&(hasStar||hasTypeOf)){error=new Error;error.message='Expected a "'+type+'" but found a '+'"'+(hasTypeOf?typeOf:"*")+'".';error.type=hasTypeOf?typeOf:"*";error.expected=type;error.value=obj;return error}else if(!exclusive&&!(hasStar||hasTypeOf)){error=new Error;error.message='Expected a "'+type+'" but found a '+'"'+typeOf+'".';error.expected=type;error.type=typeOf;error.value=obj;return error}else return null}}else if(_self.get(type)==="object"){if(typeOf!=="object"){error=new Error;error.message='Expected an object but found a "'+typeOf+'".';error.expected=type;error.type=typeOf;error.value=obj;return error}for(k in type)if(subError=_scan(obj[k],type[k])){error=subError;error.path=error.path?[k].concat(error.path):[k];return error}for(k in obj)if(type[k]===undefined){error=new Error;error.message='Unexpected key "'+k+'".';error.type=typeOf;error.value=obj;return error}return null}else if(_self.get(type)==="array"){if(type.length!==1)throw new Error("Invalid type.");if(typeOf!=="array"){error=new Error;error.message='Expected an array but found a "'+typeOf+'".';error.expected=type;error.type=typeOf;error.value=obj;return error}l=obj.length;for(i=0;i<l;i++)if(subError=_scan(obj[i],type[0])){error=subError;error.path=error.path?[i].concat(error.path):[i];return error}return null}else throw new Error("Invalid type.")}this.add=function(a1,a2){var o,k,a,id,tmp,type;if(arguments.length===1){if(this.get(a1)==="object"){o=a1;id=o.id;type=o.type}else throw new Error("If types.add is called with one argument, "+"this one has to be an object.")}else if(arguments.length===2){if(typeof a1!=="string"||!a1)throw new Error("If types.add is called with more than one "+"argument, the first one must be the string id.");else id=a1;type=a2}else throw new Error("types.add has to be called "+"with one or two arguments.");if(this.get(id)!=="string"||id.length===0)throw new Error("A type requires an string id.");if(_customTypes[id]!==undefined&&_customTypes[id]!=="proto")throw new Error('The type "'+id+'" already exists.');if(~__nativeTypes.indexOf(id))throw new Error('"'+id+'" is a reserved type name.');_customTypes[id]=1;a=(o||{}).proto||[];a=Array.isArray(a)?a:[a];tmp={};for(k in a)if(_customTypes[a[k]]===undefined){_customTypes[a[k]]=1;tmp[a[k]]=1}if(this.get(type)!=="function"&&!this.isValid(type))throw new Error("A type requires a valid definition. "+"This one can be a preexistant type or else "+"a function testing given objects.");_customTypes[id]=o===undefined?{id:id,type:type}:{};if(o!==undefined)for(k in o)_customTypes[id][k]=o[k];for(k in tmp)if(k!==id)delete _customTypes[k];return this};this.has=function(key){return!!_customTypes[key]};this.get=function(obj){return obj===null||obj===undefined?String(obj):__class2type[Object.prototype.toString.call(obj)]||"object"};this.check=function(obj,type,throws){var result=_scan(obj,type);if(throws&&result)throw result;else return!result};this.isValid=function(type){var a,k,i;if(this.get(type)==="string"){a=type.replace(/^[\?\!]/,"").split(/\|/);for(i in a)if(__nativeTypes.indexOf(a[i])<0&&!(a[i]in _customTypes))return false;return true}else if(this.get(type)==="object"){for(k in type)if(!this.isValid(type[k]))return false;return true}else if(this.get(type)==="array")return type.length===1?this.isValid(type[0]):false;else return false};this.add("type",function(v){return this.isValid(v)}.bind(this));this.add("primitive",function(v){return!v||!(v instanceof Object||typeof v==="object")});defs=defs||{};if(this.get(defs)!=="object")throw Error("Invalid argument.");for(var k in defs)this.add(k,defs[k])}var types=Typology;Typology.call(types);Object.defineProperty(types,"version",{value:"0.3.1"});if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=types;exports.types=types}else if(typeof define==="function"&&define.amd)define("typology",[],function(){return types});else this.types=types})(this)},{}],4:[function(require,module,exports){var Cursor=require("./cursor.js"),EventEmitter=require("emmett"),Typology=require("typology"),helpers=require("./helpers.js"),update=require("./update.js"),merge=require("./merge.js"),mixins=require("./mixins.js"),defaults=require("../defaults.js"),type=require("./type.js");function complexHash(type){return type+"$"+(new Date).getTime()+(""+Math.random()).replace("0.","")}function Baobab(initialData,opts){if(arguments.length<1)initialData={};if(!(this instanceof Baobab))return new Baobab(initialData,opts);if(!type.Object(initialData)&&!type.Array(initialData))throw Error("Baobab: invalid data.");EventEmitter.call(this);this.options=helpers.shallowMerge(defaults,opts);this._cloner=this.options.cloningFunction||helpers.deepClone;this._transaction={};this._future=undefined;this._history=[];this._cursors={};this.typology=this.options.typology?this.options.typology instanceof Typology?this.options.typology:new Typology(this.options.typology):new Typology;this.validate=this.options.validate||null;if(this.validate)try{this.typology.check(initialData,this.validate,true)}catch(e){e.message="/"+e.path.join("/")+": "+e.message;throw e}this.data=this._cloner(initialData);this.mixin=mixins.baobab(this)}helpers.inherits(Baobab,EventEmitter);Baobab.prototype._archive=function(){if(this.options.maxHistory<=0)return;var record={data:this._cloner(this.data)};if(this._history.length===this.options.maxHistory){this._history.pop()}this._history.unshift(record);return record};Baobab.prototype.commit=function(referenceRecord){var self=this,log;if(referenceRecord){this.data=referenceRecord.data;log=referenceRecord.log}else{if(this.options.shiftReferences)this.data=helpers.shallowClone(this.data);var record=this._archive();log=update(this.data,this._transaction,this.options);if(record)record.log=log}if(this.validate){var errors=[],l=log.length,d,i;for(i=0;i<l;i++){d=helpers.getIn(this.validate,log[i]);if(!d)continue;try{this.typology.check(this.get(log[i]),d,true)}catch(e){e.path=log[i].concat(e.path||[]);errors.push(e)}}if(errors.length)this.emit("invalid",{errors:errors})}this._transaction={};if(this._future)this._future=clearTimeout(this._future);this.emit("update",{log:log});return this};Baobab.prototype.select=function(path){if(!path)throw Error("Baobab.select: invalid path.");if(arguments.length>1)path=helpers.arrayOf(arguments);if(!type.Path(path))throw Error("Baobab.select: invalid path.");path=!type.Array(path)?[path]:path;var complex=type.ComplexPath(path);var solvedPath;if(complex)solvedPath=helpers.solvePath(this.data,path);if(!this.options.cursorSingletons){return new Cursor(this,path)}else{var hash=path.map(function(step){if(type.Function(step))return complexHash("fn");else if(type.Object(step))return complexHash("ob");else return step}).join("λ");if(!this._cursors[hash]){var cursor=new Cursor(this,path,solvedPath,hash);this._cursors[hash]=cursor;return cursor}else{return this._cursors[hash]}}};Baobab.prototype.root=function(){return this.select([])};Baobab.prototype.reference=function(path){var data;if(arguments.length>1)path=helpers.arrayOf(arguments);if(!type.Path(path))throw Error("Baobab.get: invalid path.");return helpers.getIn(this.data,type.String(path)||type.Number(path)?[path]:path)};Baobab.prototype.get=function(){var ref=this.reference.apply(this,arguments);return this.options.clone?this._cloner(ref):ref};Baobab.prototype.clone=function(path){return this._cloner(this.reference.apply(this,arguments))};Baobab.prototype.set=function(key,val){if(arguments.length<2)throw Error("Baobab.set: expects a key and a value.");var spec={};if(type.Array(key)){var path=helpers.solvePath(this.data,key);if(!path)throw Error("Baobab.set: could not solve dynamic path.");spec=helpers.pathObject(path,{$set:val})}else{spec[key]={$set:val}}return this.update(spec)};Baobab.prototype.unset=function(key){if(!key&&key!==0)throw Error("Baobab.unset: expects a valid key to unset.");var spec={};spec[key]={$unset:true};return this.update(spec)};Baobab.prototype.update=function(spec){var self=this;if(!type.Object(spec))throw Error("Baobab.update: wrong specification.");this._transaction=merge(spec,this._transaction);if(!this.options.autoCommit)return this;if(!this.options.asynchronous)return this.commit();if(!this._future)this._future=setTimeout(self.commit.bind(self,null),0);return this};Baobab.prototype.hasHistory=function(){return!!this._history.length};Baobab.prototype.getHistory=function(){return this._history};Baobab.prototype.undo=function(){if(!this.hasHistory())throw Error("Baobab.undo: no history recorded, cannot undo.");var lastRecord=this._history.shift();this.commit(lastRecord)};Baobab.prototype.release=function(){delete this.data;delete this._transaction;delete this._history;for(var k in this._cursors)this._cursors[k].release();delete this._cursors;this.kill()};Baobab.prototype.toJSON=function(){return this.reference()};module.exports=Baobab},{"../defaults.js":1,"./cursor.js":6,"./helpers.js":7,"./merge.js":8,"./mixins.js":9,"./type.js":10,"./update.js":11,emmett:2,typology:3}],5:[function(require,module,exports){var EventEmitter=require("emmett"),helpers=require("./helpers.js"),type=require("./type.js");function bindCursor(c,cursor){cursor.on("update",c.cursorListener);c.tree.off("update",c.treeListener);c.tree.on("update",c.treeListener)}function Combination(operator){var self=this;if(arguments.length<2)throw Error("baobab.Combination: not enough arguments.");var first=arguments[1],rest=helpers.arrayOf(arguments).slice(2);if(first instanceof Array){rest=first.slice(1);first=first[0]}if(!type.Cursor(first))throw Error("baobab.Combination: argument should be a cursor.");if(operator!=="or"&&operator!=="and")throw Error("baobab.Combination: invalid operator.");EventEmitter.call(this);this.cursors=[first];this.operators=[];this.tree=first.tree;this.updates=new Array(this.cursors.length);this.cursorListener=function(){self.updates[self.cursors.indexOf(this)]=true};this.treeListener=function(){var shouldFire=self.updates[0],i,l;for(i=1,l=self.cursors.length;i<l;i++){shouldFire=self.operators[i-1]==="or"?shouldFire||self.updates[i]:shouldFire&&self.updates[i]}if(shouldFire)self.emit("update");self.updates=new Array(self.cursors.length)};this.bound=false;var regularOn=this.on,regularOnce=this.once;var lazyBind=function(){if(self.bound)return;self.bound=true;self.cursors.forEach(function(cursor){bindCursor(self,cursor)})};this.on=function(){lazyBind();return regularOn.apply(this,arguments)};this.once=function(){lazyBind();return regularOnce.apply(this,arguments)};rest.forEach(function(cursor){this[operator](cursor)},this)}helpers.inherits(Combination,EventEmitter);function makeOperator(operator){Combination.prototype[operator]=function(cursor){if(!type.Cursor(cursor)){this.release();throw Error("baobab.Combination."+operator+": argument should be a cursor.")}if(~this.cursors.indexOf(cursor)){this.release();throw Error("baobab.Combination."+operator+": cursor already in combination.")}this.cursors.push(cursor);this.operators.push(operator);this.updates.length++;if(this.bound)bindCursor(this,cursor);return this}}makeOperator("or");makeOperator("and");Combination.prototype.release=function(){this.cursors.forEach(function(cursor){cursor.off("update",this.cursorListener)},this);this.tree.off("update",this.treeListener);this.cursors=null;this.operators=null;this.tree=null;this.updates=null;this.kill()};module.exports=Combination},{"./helpers.js":7,"./type.js":10,emmett:2}],6:[function(require,module,exports){var EventEmitter=require("emmett"),Combination=require("./combination.js"),mixins=require("./mixins.js"),helpers=require("./helpers.js"),type=require("./type.js");function Cursor(tree,path,solvedPath,hash){var self=this;EventEmitter.call(this);path=path||[];this.tree=tree;this.path=path;this.hash=hash;this.relevant=this.reference()!==undefined;this.complexPath=!!solvedPath;this.solvedPath=this.complexPath?solvedPath:this.path;this.updateHandler=function(e){var log=e.data.log,shouldFire=false,c,p,l,m,i,j;if(self.complexPath)self.solvedPath=helpers.solvePath(self.tree.data,self.path);if(!self.path.length)return self.emit("update");outer:for(i=0,l=log.length;i<l;i++){c=log[i];for(j=0,m=c.length;j<m;j++){p=c[j];if(p!==""+self.solvedPath[j])break;if(j+1===m||j+1===self.solvedPath.length){shouldFire=true;break outer}}}var data=self.reference()!==undefined;if(self.relevant){if(data&&shouldFire){self.emit("update")}else if(!data){self.emit("irrelevant");self.relevant=false}}else{if(data&&shouldFire){self.emit("relevant");self.emit("update");self.relevant=true}}};this.mixin=mixins.cursor(this);var bound=false,regularOn=this.on,regularOnce=this.once;var lazyBind=function(){if(bound)return;bound=true;self.tree.on("update",self.updateHandler)};this.on=function(){lazyBind();return regularOn.apply(this,arguments)};this.once=function(){lazyBind();return regularOnce.apply(this,arguments)}}helpers.inherits(Cursor,EventEmitter);Cursor.prototype.isRoot=function(){return!this.path.length};Cursor.prototype.isLeaf=function(){return type.Primitive(this.reference())};Cursor.prototype.isBranch=function(){return!this.isLeaf()&&!this.isRoot()};Cursor.prototype.root=function(){return this.tree.root()};Cursor.prototype.select=function(path){if(arguments.length>1)path=helpers.arrayOf(arguments);if(!type.Path(path))throw Error("baobab.Cursor.select: invalid path.");return this.tree.select(this.path.concat(path))};Cursor.prototype.up=function(){if(this.solvedPath&&this.solvedPath.length)return this.tree.select(this.path.slice(0,-1));else return null};Cursor.prototype.left=function(){var last=+this.solvedPath[this.solvedPath.length-1];if(isNaN(last))throw Error("baobab.Cursor.left: cannot go left on a non-list type.");return last?this.tree.select(this.solvedPath.slice(0,-1).concat(last-1)):null};Cursor.prototype.leftmost=function(){var last=+this.solvedPath[this.solvedPath.length-1];if(isNaN(last))throw Error("baobab.Cursor.leftmost: cannot go left on a non-list type.");return this.tree.select(this.solvedPath.slice(0,-1).concat(0))};Cursor.prototype.right=function(){var last=+this.solvedPath[this.solvedPath.length-1];if(isNaN(last))throw Error("baobab.Cursor.right: cannot go right on a non-list type.");if(last+1===this.up().reference().length)return null;return this.tree.select(this.solvedPath.slice(0,-1).concat(last+1))};Cursor.prototype.rightmost=function(){var last=+this.solvedPath[this.solvedPath.length-1];if(isNaN(last))throw Error("baobab.Cursor.right: cannot go right on a non-list type.");var list=this.up().reference();return this.tree.select(this.solvedPath.slice(0,-1).concat(list.length-1))};Cursor.prototype.down=function(){var last=+this.solvedPath[this.solvedPath.length-1];if(!(this.reference()instanceof Array))return null;return this.tree.select(this.solvedPath.concat(0))};Cursor.prototype.get=function(path){if(arguments.length>1)path=helpers.arrayOf(arguments);if(type.Step(path))return this.tree.get(this.solvedPath.concat(path));else return this.tree.get(this.solvedPath)};Cursor.prototype.reference=function(path){if(arguments.length>1)path=helpers.arrayOf(arguments);if(type.Step(path))return this.tree.reference(this.solvedPath.concat(path));else return this.tree.reference(this.solvedPath)};Cursor.prototype.clone=function(path){if(arguments.length>1)path=helpers.arrayOf(arguments);if(type.Step(path))return this.tree.clone(this.solvedPath.concat(path));else return this.tree.clone(this.solvedPath)};Cursor.prototype.set=function(key,val){if(arguments.length<2)throw Error("baobab.Cursor.set: expecting at least key/value.");var data=this.reference();if(typeof data!=="object")throw Error("baobab.Cursor.set: trying to set key to a non-object.");var spec={};if(type.Array(key)){var path=helpers.solvePath(data,key);if(!path)throw Error("baobab.Cursor.set: could not solve dynamic path.");spec=helpers.pathObject(path,{$set:val})}else{spec[key]={$set:val}}return this.update(spec)};Cursor.prototype.edit=function(val){return this.update({$set:val})};Cursor.prototype.unset=function(key){if(!key&&key!==0)throw Error("baobab.Cursor.unset: expects a valid key to unset.");if(typeof this.reference()!=="object")throw Error("baobab.Cursor.set: trying to set key to a non-object.");var spec={};spec[key]={$unset:true};return this.update(spec)};Cursor.prototype.remove=function(){if(this.isRoot())throw Error("baobab.Cursor.remove: cannot remove root node.");return this.update({$unset:true})};Cursor.prototype.apply=function(fn){if(typeof fn!=="function")throw Error("baobab.Cursor.apply: argument is not a function.");return this.update({$apply:fn})};Cursor.prototype.chain=function(fn){if(typeof fn!=="function")throw Error("baobab.Cursor.chain: argument is not a function.");return this.update({$chain:fn})};Cursor.prototype.push=function(value){if(!(this.reference()instanceof Array))throw Error("baobab.Cursor.push: trying to push to non-array value.");if(arguments.length>1)return this.update({$push:helpers.arrayOf(arguments)});else return this.update({$push:value})};Cursor.prototype.unshift=function(value){if(!(this.reference()instanceof Array))throw Error("baobab.Cursor.push: trying to push to non-array value.");if(arguments.length>1)return this.update({$unshift:helpers.arrayOf(arguments)});else return this.update({$unshift:value})};Cursor.prototype.merge=function(o){if(!type.Object(o))throw Error("baobab.Cursor.merge: trying to merge a non-object.");if(!type.Object(this.reference()))throw Error("baobab.Cursor.merge: trying to merge into a non-object.");this.update({$merge:o})};Cursor.prototype.update=function(spec){this.tree.update(helpers.pathObject(this.solvedPath,spec));return this};Cursor.prototype.or=function(otherCursor){return new Combination("or",this,otherCursor)};Cursor.prototype.and=function(otherCursor){return new Combination("and",this,otherCursor)};Cursor.prototype.release=function(){this.tree.off("update",this.updateHandler);if(this.hash)delete this.tree._cursors[this.hash];delete this.tree;delete this.path;delete this.solvedPath;this.kill()};Cursor.prototype.toJSON=function(){return this.reference()};type.Cursor=function(value){return value instanceof Cursor};module.exports=Cursor},{"./combination.js":5,"./helpers.js":7,"./mixins.js":9,"./type.js":10,emmett:2}],7:[function(require,module,exports){(function(global){var type=require("./type.js");function arrayOf(o){return Array.prototype.slice.call(o)}function shallowMerge(o1,o2){var o={},k;for(k in o1)o[k]=o1[k];for(k in o2)o[k]=o2[k];return o}function cloneRegexp(re){var pattern=re.source,flags="";if(re.global)flags+="g";if(re.multiline)flags+="m";if(re.ignoreCase)flags+="i";if(re.sticky)flags+="y";if(re.unicode)flags+="u";return new RegExp(pattern,flags)}function clone(deep,item){if(!item||typeof item!=="object"||item instanceof Error||"ArrayBuffer"in global&&item instanceof ArrayBuffer)return item;if(type.Array(item)){if(deep){var i,l,a=[];for(i=0,l=item.length;i<l;i++)a.push(deepClone(item[i]));return a}else{return item.slice(0)}}if(type.Date(item))return new Date(item.getTime());if(item instanceof RegExp)return cloneRegexp(item);if(type.Object(item)){var k,o={};if(item.constructor&&item.constructor!==Object)o=Object.create(item.constructor.prototype);for(k in item)if(item.hasOwnProperty(k))o[k]=deep?deepClone(item[k]):item[k];return o}return item}var shallowClone=clone.bind(null,false),deepClone=clone.bind(null,true);function compose(fn1,fn2){return function(arg){return fn2(fn1(arg))}}function first(a,fn){var i,l;for(i=0,l=a.length;i<l;i++){if(fn(a[i]))return a[i]}return}function index(a,fn){var i,l;for(i=0,l=a.length;i<l;i++){if(fn(a[i]))return i}return-1}function compare(object,spec){var ok=true,k;if(!object){return false}for(k in spec){if(type.Object(spec[k])){ok=ok&&compare(object[k],spec[k])}else if(type.Array(spec[k])){ok=ok&&!!~spec[k].indexOf(object[k])}else{if(object[k]!==spec[k])return false}}return ok}function firstByComparison(object,spec){return first(object,function(e){return compare(e,spec)})}function indexByComparison(object,spec){return index(object,function(e){return compare(e,spec)})}function getIn(object,path){path=path||[];var c=object,i,l;for(i=0,l=path.length;i<l;i++){if(!c)return;if(typeof path[i]==="function"){if(!type.Array(c))return;c=first(c,path[i])}else if(typeof path[i]==="object"){if(!type.Array(c))return;c=firstByComparison(c,path[i])}else{c=c[path[i]]}}return c}function solvePath(object,path){var solvedPath=[],c=object,idx,i,l;for(i=0,l=path.length;i<l;i++){if(!c)return null;if(typeof path[i]==="function"){if(!type.Array(c))return;idx=index(c,path[i]);solvedPath.push(idx);c=c[idx]}else if(typeof path[i]==="object"){if(!type.Array(c))return;idx=indexByComparison(c,path[i]);solvedPath.push(idx);c=c[idx]}else{solvedPath.push(path[i]);c=c[path[i]]||{}}}return solvedPath}function pathObject(path,spec){var l=path.length,o={},c=o,i;if(!l)o=spec;for(i=0;i<l;i++){c[path[i]]=i+1===l?spec:{};c=c[path[i]]}return o}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}module.exports={arrayOf:arrayOf,deepClone:deepClone,shallowClone:shallowClone,shallowMerge:shallowMerge,compose:compose,getIn:getIn,inherits:inherits,pathObject:pathObject,solvePath:solvePath}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./type.js":10}],8:[function(require,module,exports){var helpers=require("./helpers.js"),type=require("./type.js");function hasKey(o,key){return key in(o||{})}function conflict(a,b,key){return hasKey(a,key)&&hasKey(b,key)}function merge(){var res={},current,next,l=arguments.length,i,k;for(i=l-1;i>=0;i--){if(arguments[i].$unset){delete res.$set;delete res.$apply;delete res.$merge;res.$unset=arguments[i].$unset}else if(arguments[i].$set){delete res.$apply;delete res.$merge;delete res.$unset;res.$set=arguments[i].$set;continue}else if(arguments[i].$merge){delete res.$set;delete res.$apply;delete res.$unset;res.$merge=arguments[i].$merge;continue}else if(arguments[i].$apply){delete res.$set;delete res.$merge;delete res.$unset;res.$apply=arguments[i].$apply;continue}else if(arguments[i].$chain){delete res.$set;delete res.$merge;delete res.$unset;if(res.$apply)res.$apply=helpers.compose(res.$apply,arguments[i].$chain);else res.$apply=arguments[i].$chain;continue}for(k in arguments[i]){current=res[k];next=arguments[i][k];if(current&&type.Object(next)){if(conflict(current,next,"$push")){if(type.Array(current.$push))current.$push=current.$push.concat(next.$push);else current.$push=[current.$push].concat(next.$push)}else if(conflict(current,next,"$unshift")){if(type.Array(next.$unshift))current.$unshift=next.$unshift.concat(current.$unshift);else current.$unshift=[next.$unshift].concat(current.$unshift)}else{res[k]=merge(next,current)}}else{res[k]=next}}}return res}module.exports=merge},{"./helpers.js":7,"./type.js":10}],9:[function(require,module,exports){var Combination=require("./combination.js"),type=require("./type.js");module.exports={baobab:function(baobab){return{mixins:[{getInitialState:function(){this.tree=baobab;if(!this.cursor&&!this.cursors)return{};if(this.cursor&&this.cursors)throw Error("baobab.mixin: you cannot have both "+"`component.cursor` and `component.cursors`. Please "+"make up your mind.");this.__type=null;this.__updateHandler=function(){this.setState(this.__getCursorData())}.bind(this);if(this.cursor){if(!type.MixinCursor(this.cursor))throw Error("baobab.mixin.cursor: invalid data (cursor, "+"string, array or function).");if(type.Function(this.cursor))this.cursor=this.cursor();if(!type.Cursor(this.cursor))this.cursor=baobab.select(this.cursor);this.__getCursorData=function(){return{cursor:this.cursor.get()}}.bind(this);this.__type="single"}else if(this.cursors){if(!type.MixinCursors(this.cursors))throw Error("baobab.mixin.cursor: invalid data (object, array or function).");if(type.Function(this.cursors))this.cursors=this.cursors();if(type.Array(this.cursors)){this.cursors=this.cursors.map(function(path){return type.Cursor(path)?path:baobab.select(path)});this.__getCursorData=function(){return{cursors:this.cursors.map(function(cursor){return cursor.get()})}}.bind(this);this.__type="array"}else{for(var k in this.cursors){if(!type.Cursor(this.cursors[k]))this.cursors[k]=baobab.select(this.cursors[k])}this.__getCursorData=function(){var d={};for(k in this.cursors)d[k]=this.cursors[k].get();return{cursors:d}}.bind(this);this.__type="object"}}return this.__getCursorData()},componentDidMount:function(){if(this.__type==="single"){this.__combination=new Combination("or",[this.cursor]);this.__combination.on("update",this.__updateHandler)}else if(this.__type==="array"){this.__combination=new Combination("or",this.cursors);this.__combination.on("update",this.__updateHandler)}else if(this.__type==="object"){this.__combination=new Combination("or",Object.keys(this.cursors).map(function(k){return this.cursors[k]},this));this.__combination.on("update",this.__updateHandler)}},componentWillUnmount:function(){
if(this.__combination)this.__combination.release()}}].concat(baobab.options.mixins)}},cursor:function(cursor){return{mixins:[{getInitialState:function(){this.cursor=cursor;this.__updateHandler=function(){this.setState({cursor:this.cursor.get()})}.bind(this);return{cursor:this.cursor.get()}},componentDidMount:function(){this.cursor.on("update",this.__updateHandler)},componentWillUnmount:function(){this.cursor.off("update",this.__updateHandler)}}].concat(cursor.tree.options.mixins)}}}},{"./combination.js":5,"./type.js":10}],10:[function(require,module,exports){var type=function(value){if(Array.isArray(value)){return"array"}else if(typeof value==="object"&&value!==null){return"object"}else if(typeof value==="string"){return"string"}else if(typeof value==="number"){return"number"}else if(typeof value==="boolean"){return"boolean"}else if(typeof value==="function"){return"function"}else if(value===null){return"null"}else if(value===undefined){return"undefined"}else if(value instanceof Date){return"date"}else{return"invalid"}};type.Array=function(value){return Array.isArray(value)};type.Object=function(value){return!Array.isArray(value)&&typeof value==="object"&&value!==null};type.String=function(value){return typeof value==="string"};type.Number=function(value){return typeof value==="number"};type.Boolean=function(value){return typeof value==="boolean"};type.Function=function(value){return typeof value==="function"};type.Primitive=function(value){return typeof value==="string"||typeof value==="number"||typeof value==="boolean"};type.Date=function(value){return value instanceof Date};type.Step=function(value){var valueType=type(value);var notValid=["null","undefined","invalid","date"];return notValid.indexOf(valueType)===-1};type.Path=function(value){var types=["object","string","number","function","undefined"];if(type.Array(value)){for(var x=0;x<value.length;x++){if(types.indexOf(type(value[x]))===-1){return false}}}else{return types.indexOf(type(value))>=0}return true};type.MixinCursor=function(value){var allowedValues=["string","number","array","function"];return allowedValues.indexOf(type(value))>=0||type.Cursor(value)};type.MixinCursors=function(value){var allowedValues=["array","object","function"];return allowedValues.indexOf(type(value))>=0};type.ComplexPath=function(value){var complexTypes=["object","function"];for(var x=0;x<value.length;x++){if(complexTypes.indexOf(type(value[x]))>=0){return true}}return false};module.exports=type},{}],11:[function(require,module,exports){var helpers=require("./helpers.js"),type=require("./type.js");var COMMANDS={};["$set","$push","$unshift","$apply","$merge"].forEach(function(c){COMMANDS[c]=true});function makeError(path,message){var e=new Error("baobab.update: "+message+" at path /"+path.toString());e.path=path;return e}function update(target,spec,opts){opts=opts||{shiftReferences:false};var log={};(function mutator(o,spec,path,parent){path=path||[];var hash=path.join("λ"),fn,h,k,v;for(k in spec){if(COMMANDS[k]){v=spec[k];log[hash]=true;switch(k){case"$push":if(!type.Array(o))throw makeError(path,"using command $push to a non array");if(!type.Array(v))o.push(v);else o.push.apply(o,v);break;case"$unshift":if(!type.Array(o))throw makeError(path,"using command $unshift to a non array");if(!type.Array(v))o.unshift(v);else o.unshift.apply(o,v);break}}else{h=hash?hash+"λ"+k:k;if("$unset"in(spec[k]||{})){log[h]=true;if(type.Array(o)){if(!opts.shiftReferences)o.splice(k,1);else parent[path[path.length-1]]=o.slice(0,+k).concat(o.slice(+k+1))}else{delete o[k]}}else if("$set"in(spec[k]||{})){v=spec[k].$set;log[h]=true;o[k]=v}else if("$apply"in(spec[k]||{})||"$chain"in(spec[k]||{})){fn=spec[k].$apply||spec[k].$chain;if(typeof fn!=="function")throw makeError(path.concat(k),"using command $apply with a non function");log[h]=true;o[k]=fn.call(null,o[k])}else if("$merge"in(spec[k]||{})){v=spec[k].$merge;if(!type.Object(o[k]))throw makeError(path.concat(k),"using command $merge on a non-object");log[h]=true;o[k]=helpers.shallowMerge(o[k],v)}else if(opts.shiftReferences&&("$push"in(spec[k]||{})||"$unshift"in(spec[k]||{}))){if("$push"in(spec[k]||{})){v=spec[k].$push;if(!type.Array(o[k]))throw makeError(path.concat(k),"using command $push to a non array");o[k]=o[k].concat(v)}if("$unshift"in(spec[k]||{})){v=spec[k].$unshift;if(!type.Array(o[k]))throw makeError(path.concat(k),"using command $unshift to a non array");o[k]=(v instanceof Array?v:[v]).concat(o[k])}log[h]=true}else{if(typeof o[k]==="undefined")o[k]={};if(opts.shiftReferences)o[k]=helpers.shallowClone(o[k]);mutator(o[k],spec[k],path.concat(k),o)}}}})(target,spec);return Object.keys(log).map(function(hash){return hash.split("λ")})}module.exports=update},{"./helpers.js":7,"./type.js":10}],baobab:[function(require,module,exports){var Baobab=require("./src/baobab.js"),helpers=require("./src/helpers.js");Object.defineProperty(Baobab,"version",{value:"0.4.4"});Baobab.getIn=helpers.getIn;module.exports=Baobab},{"./src/baobab.js":4,"./src/helpers.js":7}]},{},[]);var Baobab=require("baobab");var baobab=new Baobab({name:"Maria"},{maxHistory:1e5,asynchronous:false});console.log(baobab);baobab.set("name","Isabella");console.log(baobab.get("name"));baobab.undo();console.log(baobab.get("name"));baobab.redo();
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"baobab": "0.4.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment