Ejemplo n.º 1
0
 it('should parentize a prime', function(){
     var A = prime({
         a: function(c){ return 'a' + c + this.d() },
         d: function(){ return 'd' }
     })
     var B = prime({inherits: A, a: function(){
         return this.parent('a', 'c') + 'b'
     }})
     mixin(B, parentize)
     var b = new B()
     var res
     expect(function(){
         res = b.a()
     }).not.to.throwException()
     expect(res).to.be('acdb')
 })
Ejemplo n.º 2
0
 it('should parentize a method from a grandparent class', function(){
     var A = prime({
         a: function(){ return 'a' }
     })
     var B = prime({inherits: A, c: function(){
         return 'b'
     }})
     var C = prime({inherits: B, c: function(){
         return this.parent('c') + 'c'
     }})
     var D = prime({
         inherits: C,
         a: function(){
             return this.parent('a') + 'b'
         },
         c: function(){
             return this.parent('c') + 'd' + this.parent('c')
         }
     })
     mixin(D, parentize)
     var d = new D()
     expect(d.a()).to.be('ab')
     expect(d.c()).to.be('bcdbc')
 })
Ejemplo n.º 3
0
var classy = function(proto){

	// accept empty proto, or if the proto is a function, use that as constructor (like MooTools 1.x)
	if (!proto) proto = {};
	else if (typeof proto == 'function') proto = {constructor: proto};

	// alias old Class keys

	if (proto.Extends){
		proto.inherits = proto.Extends;
		delete proto.Extends;
	}

	if (proto.Implements){
		proto.mixin = proto.Implements;
		delete proto.Implements;
	}

	// if it will inherit from another class, that class should be a subclass of Class
	if (proto.inherits && !isSubPrimeOf(proto.inherits, Class)) throw new Error('Inherited class should be classyfied');
	if (!proto.inherits) proto.inherits = Class;

	var prim = prime(proto);

	// overload implement method
	var implement = prim.implement;
	prim.implement = function(name, value){
		if (typeof name == 'string'){
			var object = {};
			object[name] = value;
			name = object;
		}
		return implement.call(this, name);
	};

	return prim;

};
Ejemplo n.º 4
0
var Partition = prime({

    inherits: Output,

    up: function(callback){
        var self = this

       if (!this.options.output){
            callback(new errors.RequiredOutputError())
            return this
        }

        var options = this.options
        this._path = (options.path ? options.path : process.cwd()) + '/a'

        async.parallel([
            getDefineAST,
            getWrapperAST,
            getMainAST
        ], function(err, results){
            if (err) callback(err)
            else self.output(callback, results[0], results[1], results[2])
        })
    },

    output: function(callback, defineAST, wrapperAST, mainAST){

        var self       = this
        var options    = this.options
        var map        = options.map || {}
        var output     = options.output
        var modules    = []
        var tasks      = []
        var first      = 0

        var resolved = resolveMapping(map, this.storage, this._path)

        forOwn(resolved.notFound, function(id, out){
            self.emit("warn", new Error("Module '" + id + "' in mapping not found"))
        })

        forOwn(resolved.modules, function(modules, file){
            var ast = util.clone(wrapperAST)
            if (first++ === 0) self.addMainToAST(ast, resolved.modules, mainAST)
            self.addModulesToAST(ast, modules, defineAST)
            tasks.push(function(callback){
                self.writeFile(file, ast, callback)
            })
        })

        async.parallel(tasks, callback)
    },

    getModuleName: function(module){
        return this.options.compress ? module.uid : module.getModuleID(this._path);
    },

    addMainToAST: function(ast, map, mainAST){
        var self = this
        var main = util.clone(mainAST.body[0])
        ast.body.push(main)
        var mapping = main.expression.callee.body.body[0].declarations[0].init.properties
        var files = mapping[0].value.elements
        var modules = mapping[1].value.properties
        forOwn(map, function(mods, file){
            var i = files.push({type: "Literal", value: file})
            mods.forEach(function(module){
                modules.push({
                    type: "Property",
                    key: {type: "Literal", value: module.getModuleID(self._path)},
                    value: {
                        type: "ArrayExpression",
                        elements: [
                            {type: "Literal", value: i - 1},
                            {type: "Literal", value: module.uid}
                        ]
                    },
                    kind: "init"
                })
            })
        })

        // replace the true/false defines/paths object construction mapping
        var forIn = main.expression.callee.body.body[3].body
        var testOne = forIn.body[0].expression.left.property.test
        var testTwo = forIn.body[1].expression.right.test
        testOne.value = testTwo.value = !!this.options.compress
    },

    addModulesToAST: function(wrapper, modules, defineAST){
        var self = this
        modules.forEach(function(module){

            if (!module || !module.full || module.err) return

            var ast = util.clone(module.ast)

            // replace require() calls
            Output.replaceRequire(ast, module, function(dep){
                return self.getModuleName(dep)
            })

            var newAST = util.clone(defineAST.body[0])
            var args = newAST.expression['arguments']

            // change module ID
            args[0].value = self.getModuleName(module)

            // add dependencies to the dependency array
            var deps = args[1].elements
            module.dependencies.forEach(function(dep){
                if (dep) deps.push({type: "Literal", value: self.getModuleName(dep)})
            })

            // body of the define function
            var body = args[2].body.body
            // put the module JS in the define factory function
            for (var i = 0; i < ast.body.length; i++){
                body.push(ast.body[i])
            }

            // and add the define() function to the wrapper
            wrapper.body.push(newAST)
        })
    },

    writeFile: function(file, ast, callback){
        var self      = this
        var output    = this.options.output
        var asASTJSON = this.options.ast

        var filename = path.normalize(output + '/' + file)
        if (asASTJSON){
            var ext = path.extname(filename);
            filename = filename.slice(0, - ext.length) + '.json'
        }

        var code = asASTJSON ?
            JSON.stringify(ast, null, 2) :
            escodegen.generate(ast)

        async.series([
            async.apply(mkdirp, path.dirname(filename)),
            async.apply(fs.writeFile, filename, code)
        ], function(err){
            if (!err) self.emit("output", filename)
            callback(err, filename)
        })
    }

})
Ejemplo n.º 5
0
module.exports = prime({

    outputSingleFile: function(wrapper, callback){

        var options   = this._options
        var compress  = options.compress
        var sourcemap = options.sourcemap
        var self = this

        if (compress) wrapper = esmangle.mangle(wrapper)

        var code, map

        var escodegenOptions = {
            format: compress ? {
                renumber: true,
                hexadecimal: true,
                escapeless: true,
                compact: true,
                semicolons: false,
                parentheses: false
            } : {}
        }

        if (sourcemap){
            map = escodegen.generate(wrapper, util.merge({
                sourceMap: true,
                // see https://github.com/Constellation/escodegen/pull/82
                sourceMapRoot: options.sourcemapRoot
            }, escodegenOptions))
            // temp fix for https://github.com/Constellation/escodegen/pull/82
            if (options.sourcemapRoot){
                map = JSON.parse(map)
                map.sourceRoot = options.sourcemapRoot
                map = JSON.stringify(map)
            }
        }

        if (!options.ast){
            code = escodegen.generate(wrapper, escodegenOptions)
            if (sourcemap) code += "\n//@ sourceMappingURL=" + (options.sourcemapURL || sourcemap) + "\n"
        } else {
            if (compress) code = JSON.stringify(wrapper)
            else code = JSON.stringify(wrapper, null, 2)
        }

        var tasks = []

        if (sourcemap){
            tasks.push(function(callback){
                fs.writeFile(sourcemap, map + "", "utf-8", function(err){
                    if (!err) self.wrup.emit("output", sourcemap)
                    callback(err)
                })
            })
        }

        if (options.output){
            tasks.push(function(callback){
                fs.writeFile(options.output, code, "utf-8", function(err){
                    if (!err) self.wrup.emit('output', options.output)
                    callback(err)
                })
            })
        }

        async.parallel(tasks, function(err){
            callback(err, code)
        })
    }

})
Ejemplo n.º 6
0
}

var Resolver = prime({

    // this makes sure we always use the same directory for a specified package
    // (the first it encounters) this might not be ideal, but duplicating
    // packages for the web is even worse
    resolve: function(what, from){

        var module = resolve(what, from)

        if (!module) return null // cannot find module
        if (!module.match(nativeModuleRegex)) return true // native require

        var jsonpath = findJSON(module)
        if (!jsonpath) return module // not part of any package

        var pkgpath = path.dirname(jsonpath) + pathsep
        var modulepath = module.replace(pkgpath, "")

        var json = require(jsonpath)
        var id = json.name + "@" + json.version
        var prevpkgpath = (this.packages || (this.packages = {}))[id]
        pkgpath = prevpkgpath || (this.packages[id] = pkgpath)

        return prevpkgpath ? resolve(path.join(pkgpath, modulepath), from) : module
    }

})

module.exports = Resolver
Ejemplo n.º 7
0
var Sift3FS = prime({

    inherits: FSModule,

    name: 'Sift3FS',
    options: {
        'maxDistanceTolerance': 3
    },

    search: function(searchTerm, haystack) {
        this.lastTerm = searchTerm;
        this.lastHaystack = haystack;

        if (!this.sift3) {
            this.sift3 = new sift3();
        }

        var needleWords = searchTerm.split(' ');
        var haystackWords = haystack.split(' ');

        var matches = [];

        var nwl = needleWords.length;
        var hwl = haystackWords.length;
        for (var i = 0; i < nwl; i++) {
            for (var j = 0; j < hwl; j++) {
                var needleWord = needleWords[i];
                var haystackWord = haystackWords[j];

                var score = this.sift3.getDifference(needleWord, haystackWord);

                if (score <= this.options.maxDistanceTolerance) {
                    matches.push({'match': needleWord, 'score': score});
                }
            }
        }

        this.lastResults = matches;

        return this;
    },

    getPoints: function() {
        var haystackWords = this.lastHaystack.split(' ');

        var combinedScore = 0;
        arr.forEach(this.lastResults, function(result) {
            combinedScore += result.score;
        });

        combinedScore += (haystackWords.length - this.lastResults.length) * this.options.maxDistanceTolerance;

        var points = 50 / haystackWords.length * this.lastResults.length;
        points += 50 / (haystackWords.length * this.options.maxDistanceTolerance) * (haystackWords.length * this.options.maxDistanceTolerance - combinedScore);

        return points;
    }

});
Ejemplo n.º 8
0
'use strict'

var prime = require('prime')

var _ = prime({
    constructor: function(obj) {
        if(obj == null || obj instanceof _) return obj
        if(!(this instanceof _)) return new _(obj)
        this._wrapped = obj
    },

    value: function() {
        return this._wrapped
    },

    toString: function() {
        return this._wrapped.toString()
    },

    valueOf: function() {
        return this.value()
    }
})

var arrayRef = []
var methods = {}

// add `Array` functions that return unwrapped values
prime.each(['join', 'pop', 'shift'], function(methodName) {
    var func = arrayRef[methodName]
    methods[methodName] = function() {
Ejemplo n.º 9
0
var Fx = prime({

    constructor: function Fx(render, options){

        // set options

        this.setOptions(options)

        // renderer

        this.render = render || function(){}

        // bound functions

        var self = this

        this.bStep = function(t){
            return self.step(t)
        }

        this.bExit = function(time){
            self.exit(time)
        }

    },

    setOptions: function(options){
        if (options == null) options = {}

        if (!(this.duration = this.parseDuration(options.duration || "500ms"))) throw new Error("invalid duration")
        if (!(this.equation = this.parseEquation(options.equation || "default"))) throw new Error("invalid equation")
        this.callback = options.callback || function(){}

        return this
    },

    parseDuration: function(duration){
        if (duration = (duration + "").match(rDuration)){
            var time = +duration[1],
                unit = duration[2] || "ms"

            if (unit === "s")  return time * 1e3
            if (unit === "ms") return time
        }
    },

    parseEquation: function(equation, array){
        var type = typeof equation

        if (type === "function"){ // function
            return equation
        } else if (type === "string"){ // cubic-bezier string
            equation = equations[equation] || equation
            var match = equation.replace(/\s+/g, "").match(rCubicBezier)
            if (match){
                equation = map(match.slice(1), function(v){return +v})
                if (array) return equation
                if (equation.toString() === "0,0,1,1") return function(x){return x}
                type = "object"
            }
        }

        if (type === "object"){ // array
            return bezier(equation[0], equation[1], equation[2], equation[3], 1e3 / 60 / this.duration / 4)
        }
    },

    cancel: function(to){
        this.to = to
        this.cancelExit = requestFrame(this.bExit)
    },

    exit: function(time){
        this.render(this.to)
        delete this.cancelExit
        this.callback(time)
    },

    start: function(from, to){

        this.stop()

        if (this.duration === 0){
            this.cancel(to)
            return this
        }

        this.isArray = false
        this.isNumber = false

        var fromType = typeof from,
            toType   = typeof to

        if (fromType === "object" && toType === "object"){
            this.isArray = true
        } else if (fromType === "number" && toType === "number"){
            this.isNumber = true
        }

        var from_ = divide(from),
            to_   = divide(to)

        this.from = from_[0]
        this.to = to_[0]
        this.templateFrom = from_[1]
        this.templateTo = to_[1]

        if (this.from.length !== this.to.length || this.from.toString() === this.to.toString()){
            this.cancel(to)
            return this
        }

        delete this.time
        this.length = this.from.length
        this.cancelStep = requestFrame(this.bStep)

        return this

    },

    stop: function(){

        if (this.cancelExit){
            this.cancelExit()
            delete this.cancelExit
        } else if (this.cancelStep){
            this.cancelStep()
            delete this.cancelStep
        }

        return this
    },

    step: function(now){

        this.time || (this.time = now)

        var factor = (now - this.time) / this.duration

        if (factor > 1) factor = 1

        var delta = this.equation(factor),
            from  = this.from,
            to    = this.to,
            tpl   = this.templateTo

        for (var i = 0, l = this.length; i < l; i++){
            var f = from[i], t = to[i]
            tpl = tpl.replace("@", t !== f ? compute(f, t, delta) : t)
        }

        this.render(this.isArray ? tpl.split(",") : this.isNumber ? +tpl : tpl, factor)

        if (factor !== 1){
            this.cancelStep = requestFrame(this.bStep)
        } else {
            delete this.cancelStep
            this.callback(now)
        }

    }

})
Ejemplo n.º 10
0
var prime = require('prime');
var Emitter = require('prime/emitter');
module.exports = prime({
    inherits: Emitter,
    once : function(type, fn){
        var ob = this;
        function cb(){
            ob.off(type, cb);
            fn();
        }
        this.on(type, cb);
    }
});
Ejemplo n.º 11
0
var unit = prime({
	_attached: true,
	_prefix: '',
	setPrefix: function(prefix){
		this._prefix = prefix;
		return this;
	},
	getPrefix: function(){
		return this._prefix;
	},
	publish: function(type, data, finalized){
		if(! this._attached) return;
		var event = [this.getPrefix(), '.', type].join('');
		dispatcher.emit(event, data);
		if (finalized) {
			var current = finalized.get(event) || [];
			current.push(data);
		}
	},
	subscribe: function(type, fn){
		if(! this._attached) return;
		var event = [this.getPrefix(), '.', type].join('');
		dispatcher.on(event, fn);
		var current = _(finalized.get(event) || []);
		current.each(function(data){
			fn(data);
		})
	},
	attachUnit: function(){
		this._attached = true;
	},
	detachUnit: function(){
		this._attached = false;
	},
	unsubscribe: function(type, fn){
		if(! this._attached) return;
		var event = [this.getPrefix(), '.', type].join('');
		dispatcher.off(event, fn);
	}
});
Ejemplo n.º 12
0
"use strict";

var prime = require('prime')

var WrapUpError = prime({

    inherits: Error,

    type: "generic",

    constructor: function WrapUpError(message, module, source){
        this.message = message
        if (module) this.module = module
        this.source = source || "you"
    }

})

var WrapUpNativeError = prime({

    inherits: WrapUpError,

    type: "native",

    constructor: function WrapUpNativeError(module, source){
        WrapUpError.call(this, "Native Module Required", module, source)
        this.type = "native"
    }

})
Ejemplo n.º 13
0
"use strict"

var prime = require('prime')
var array = require('prime/shell/array')

var Event = require('./event')

var TouchEvent = module.exports = prime({

    inherits: Event,

    constructor: function(type, bubbles, touches) {
        TouchEvent.parent.constructor.call(this, type, bubbles)
        this.__touches = array.slice(touches)
        return this
    }

})

prime.define(TouchEvent.prototype, 'touches', {

    get: function() {
        return this.__touches
    }

})
Ejemplo n.º 14
0
var FieldText = prime({
	inherits: FieldBase,
	type: 'text',

	constructor: function(spec, value){
		if (!(this instanceof FieldText)){
			return new FieldText(spec, value);
		}
		FieldBase.call(this, spec, value);
	},

	build: function(){
		this.wrap = zen('li');
		zen('label').text(this.spec.label || '').insert(this.wrap);
		this.input = zen('input[type=' + this.type + ']').insert(this.wrap);

		if (this.spec.name){
			this.input.attribute('name', this.spec.name);
		}
		if (this.spec.value){
			this.input.value(this.spec.value);
		}
		if (this.spec.required && this.spec.required === true){
			this.input.attribute('required', true);
		}
		if (this.spec.attributes){
			forOwn(this.spec.attributes, function(value, key){
				this.input.attribute(key, value);
			}.bind(this));
		}
		if (this.value){
			this.input.value(this.value);
		}
	}
});
Ejemplo n.º 15
0
var api = function(unit, definitions) {
    var methods = {}
    var u = prime({
        inherits: unit,
        constructor: function(){
            var scope = this

            if ( !(scope instanceof u) ) {
                return new u
            }

            // setting the definitions here so we don't need to pass it around
            u.parent.constructor.call(scope, definitions)

            // copy methods here because we want dot notation accessible methods
            merge(scope, recurse(methods, scope))
        }
    })

    // Expose the methods for testing
    u._methods = methods

    // Expose definitions for testing
    u._definitions = definitions

    /**
     * Set a generic method on the path. Generic method is generated from the definition name.
     * @param {String} path               Path to set the method, can be dot-notated string to set nested object property
     * @param {String} definitionName     Name of definition used to generate generic method.
     */
    u.set = function(path, definitionName){
        var scope = this

        set(scope, path, generic(scope, definitionName))

        return scope
    }

    /**
     * Get the generic method via path
     * @param  {String} path   Path to the set method
     * @return {Function}      Conversion method
     */
    u.get = function(path){
        return get(this, toDotString(path))
    }

    u.augment = function(name, path, def) {
        var scope = this

        if (!name) {
            throw new Error('Missing argument: name')
        }

        // Path is the definition
        if (path != undef && (isArray(path))) {
            def = path
            path = undef
        }

        if (path == undef) {
            path = name
        }

        path = toDotString(path)

        if (def != undef) {
            definitions.set.apply(definitions, def)
        }

        set(methods, path, implement(name))
        u.set(path, name)

        return scope
    }

    return u
}
Ejemplo n.º 16
0
define(function(require) {
  var settings = require('settings');
  var prime = require('prime');
  var Emitter = require('prime/emitter');

  /**
   * Helper class to provide CORS requests
   * TODO: make it more generic and move to lib directory
   */
  var CORSRequest = prime({
    inherits: Emitter,

    constructor: function(method, url, data, callback) {
      var self = this;

      this.request = new XMLHttpRequest({
        mozSystem: true,
        mozAnon: true
      });
    
      this.method = method.toUpperCase();

      if (data) {
        this.data = JSON.stringify(data);
      } else {
        // empty string is not valid for tastypie
        this.data = '{}';
      }

      this.request.open(this.method, url + '?format=json');
      this.request.setRequestHeader('Content-type', 'application/json');
      this.request.setRequestHeader('X-PINGOTHER', 'pingpong');

      this.request.onload = function() {
        if (self.request.status === 404 ||
            self.request.status === 500) {
          self.emit('error', this.request.status);
          return;
        }
        self.emit('success', this.responseText); 
      };

      if (callback) {
        this.send(callback);
      }
    },

    send: function(callback) {
      this.on('success', callback);
      this.request.send(this.data);
    }
  });

  var Collection = prime({
    inherits: Emitter,
    collectionServer: settings.get('collectionServer'),
    apiPrefix: '/api/v1',

    constructor: function() {
      var self = this;
      this.on('ready', function() {
        self.ready = true;
      });

      // this array will be empty after all data retrieved
      var allCallbacks = ['phone', 'app_version'];

      if ('lastCollectedData' in localStorage) {
        this.lastCollectedData = localStorage.lastCollectedData;
      }

      this.setPhoneResourceUri(function() {
        delete allCallbacks[allCallbacks.indexOf('phone')];
        if (!allCallbacks) {
          this.emit('ready');
        }
      });

      // get app_version
      var request = window.navigator.mozApps.getSelf();
      request.onsuccess = function() {
        delete allCallbacks[allCallbacks.indexOf('app_version')];
        if (request.result) {
          self.appVersion = request.result.manifest.version;
        } else {
          self.appVersion = 0;
        }
        if (allCallbacks.length === 0) {
          this.emit('ready');
        }
      };
    },

    /**
     * returns app id stored in localStorage or retrieves one from
     * collection server
     */
    getPhoneResourceUri: function(callback) {
      var self = this;
      if (settings.get('phoneResourceUri')) {
        callback(settings.get('phoneResourceUri'));
        return;
      }
      if (!settings.get('sendResults')) {
        callback(undefined);
        return;
      }
      // retrieve phoneResourceUri from collection server
      new CORSRequest('post', this.collectionServer + this.apiPrefix + '/phone/', 
          {}, function getPhoneResourceUriCallback(responseText) {
            var data = JSON.parse(responseText);
            callback(data.resource_uri);
          }
      );
    },

    /**
     * sets phoneResourceUri
     */
    setPhoneResourceUri: function(callback) {
      var self = this;
      this.getPhoneResourceUri(function(phoneResourceUri) {
        if (phoneResourceUri) {
          settings.set('phoneResourceUri', phoneResourceUri);
        }
        callback(phoneResourceUri);
      });
    },

    /**
     * prepares an object to be send to collection server
     */
    getFullData: function(currentResults) {
      return {
        test_result: JSON.stringify(currentResults),
        device: settings.get('deviceModel'),
        phone: settings.get('phoneResourceUri'),
        app_version: this.appVersion,
        user_agent: navigator.userAgent
      };
    },

    /**
     * send results to collection server
     *
     * param results: object containing all tests for supported APIs
     */
    sendResults: function(results) {
      var self = this;
      if (!settings.get('sendResults')) {
        return;
      }
      if (settings.get('phoneResourceUri')) {
        this._realSendResults(results);
      } else {
        this.setPhoneResourceUri(function() {
          self._realSendResults(results);
        });
      }
    },

    _realSendResults: function(results) {
      if (!settings.get('phoneResourceUri')) {
        // it should never happened if called via sendResults
        return;
      }
      var data = this.getFullData(results);
      if (!diffLastResults(data)) {
         return;
       }
      new CORSRequest('post', 
          this.collectionServer + this.apiPrefix + '/result/', 
          data, function() {
            // TODO: add the success failure
            localStorage.collectedData = JSON.stringify(data);
          }
      );
    }
  });

  /** 
   * Compare last results sent to current results
   * returns null if no difference
   */
  function diffLastResults(currentData) {
    if (!localStorage.collectedData) {
      return true;
    }
    var collectedData = JSON.parse(localStorage.collectedData);
    // compare currentData to collectedData 
    // tests are stored as JSON string - thee will need to be parsed
    // seoarately for each API
   
    if (collectedData.device !== currentData.device ||
        collectedData.app_version !== currentData.app_version ||
        collectedData.phone !== currentData.phone ||
        collectedData.user_agent !== currentData.user_agent) {
      return true;
    } 

    // compare test results
    var collectedResults = JSON.parse(collectedData.test_result);
    var currentResults = JSON.parse(currentData.test_result);
    // check if number of APIs is the same
    if (Object.keys(collectedData).length !== Object.keys(currentData).length) {
      return true;
    }
    for (var apiId in currentResults) {
      // check diff for each API
      var current = currentResults[apiId];
      if (!(apiId in collectedResults)) {
        return true;
      }
      var collected = collectedResults[apiId];
      if (collected.preparation !== current.preparation ||
          Object.keys(current.tests).length !== Object.keys(collected.tests).length) {
        return true;
      }
      for (var testName in current.tests) {
        // check each test in API
        if (!(testName in collected.tests) ||
            current.tests[testName] !== collected.tests[testName]) {
          return true;
        }
      }
    }
    // collectedData and currentData are the same
    return false;
  }


  return new Collection();
});
Ejemplo n.º 17
0
'use strict'

var prime = require('prime')

module.exports = prime({
    constructor: function(){
        this._defs = {}
    },

    set: function(name, base, factor, zero, validation) {
        var scope = this

        var def = scope._defs[name] = typeof base == 'object' ? base : {
            base: base,
            factor: factor,
            zero: zero,
            validation: validation
        }

        return scope
    },

    get: function(name) {
        return this._defs[name]
    }
})
Ejemplo n.º 18
0
'use strict'

var prime = require('prime')
var underdash = require('../')
var underdashMixin = underdash.mixin

var _ = prime({
    inherit: underdash,

    chain: function(){
        this._chain = true
        return this
    }
})

_.chain = function(obj){
    var o = _(obj)
    return o.chain()
}

_.mixin = function(name, shell){
    _[name] = shell[name]
    
    var proto = shell.prototype[name]
    var o = {}

    o[name] = function(){
        var result = arguments.length ?
            proto.apply(this._wrapped, arguments) :
            proto.call(this._wrapped)
        
var LevenshteinSimpleFS = prime({

	inherits: FSModule,

	name: 'LevenshteinSimpleFS',

	options: {
		'harshness': 1,
		'caseSensitive': false
	},

	/**
	 * Compares the two strings.
	 *
	 * @param {String} term
	 * @param {String} haystack
	 * @returns {LevenshteinSimpleFS}
	 */
	search: function (term, haystack) {

		this.lastTerm = term;
		this.lastHaystack = haystack;

		if (!this.options.caseSensitive) {
			term = term.toUpperCase();
			haystack = haystack.toUpperCase();
		}

		var score = lev(term, haystack);

		this.lastScore = score;

		return this;

	},

	/**
	 * Calculates the score of the previous search
	 *
	 * @returns {Number}
	 */
	getPoints: function () {

		var averageLength = (this.lastTerm.length + this.lastHaystack.length) / 2;

		return 100 * Math.pow(Math.E, -(this.options.harshness) * this.lastScore / averageLength);

	}

});
Ejemplo n.º 20
0
var Scrollbar = prime({

	constructor: function(elements, options){
		this.content = $(elements.content)
		this.wrapper = $(elements.wrapper)
		this.bar = $(elements.bar)
		this.left = $(elements.left)
		this.right = $(elements.right)
		this.doc = $(elements.document || document)

		this.setOptions(options || {})

		this.measure()
		this.attach()
		this.set(0)
	},

	setOptions: function(options){
		this.stepSize = options.step || 50
	},

	attach: function(){
		this.left.on('click', this.bound('scrollLeft'))
		this.right.on('click', this.bound('scrollRight'))
		this.bar.on('mousedown', this.bound('dragStart'))
	},

	measure: function(){
		this.wWidth = computeLength(this.wrapper, 'width')
		this.cWidth = computeLength(this.content, 'width')
		this.lWidth = computeLength(this.left, 'width')
		this.rWidth = computeLength(this.right, 'width')
		this.bWidth = computeLength(this.bar, 'width')
		this.scrollSpace = this.cWidth - this.wWidth
		this.barSpace = this.wWidth - this.bWidth - this.lWidth - this.rWidth
	},

	set: function(p){
		p = this.position = limit(p, 0, 1)
		style(this.content, 'left', - p * this.scrollSpace)
		style(this.bar, 'left', p * this.barSpace + this.lWidth)
		this.emit('set', p)
	},

	animate: function(p){
		p = this.position = limit(p, 0, 1)
		animate(this.content, {left: - p * this.scrollSpace})
		animate(this.bar, {left: p * this.barSpace + this.lWidth})
		this.emit('set', p)
	},

	// left/right buttons

	scrollLeft: function(){
		this.animate(this.position - this.stepSize / this.scrollSpace)
	},

	scrollRight: function(){
		this.animate(this.position + this.stepSize / this.scrollSpace)
	},

	// bar dragging

	dragStart: function(event){
		event = mouse(event)
		event.preventDefault()
		this._drag = event.page().x
		this._position = this.position
		$(this.doc)
			.on('mouseup', this.bound('stopDrag'))
			.on('mousemove', this.bound('drag'))
	},

	stopDrag: function(){
		$(this.doc)
			.off('mouseup', this.bound('stopDrag'))
			.off('mousemove', this.bound('drag'))
	},

	drag: function(event){
		var dx = (mouse(event).page().x - this._drag) / this.barSpace
		this.set(this._position + dx)
	}

})
Ejemplo n.º 21
0
var Event = require('../event')
var prime = require("prime")

var Key = prime({

    inherits: Event,

    constructor: function(event){
        if (!(this instanceof Key)) return new Key(event.event || event)
        Event.call(this, event)
    },

    keyCode: function(){
        return this.event.which || this.event.keyCode
    },

    key: function(){
        var code = this.keyCode()
        var key = keys[code]
        if (key) return key
        var type = this.type()
        if (type == 'keydown' || type == 'keyup'){
            if (code > 111 && code < 124) return 'f' + (code - 111)
            else if (code > 95 && code < 106) return code - 96
        }
        return String.fromCharCode(code).toLowerCase()
    }

})

var keys = {
    38: 'up', 40: 'down', 37: 'left', 39: 'right',
Ejemplo n.º 22
0
cardlayout = prime({
	constructor: function(element, options){
		this.options = {
			top:    0,
			left:   0,
			height: '300px'
		};
		this.setOptions(options);

		var GL = this.GridLayout = new gridlayout(element, $merge(this.options, { columns: 1, rows: 1 }));
		$(GL.toElement()).addClass('cardlayout');
		this.element = GL.toElement();
		this.cards = [];
	},
	setOptions: function(options){
		this.options = this.options || (this.options = {});
		for (var key in options) {
			this.options[key] = options[key];
		}
	},
	add: function(element){
		var card = this.GridLayout.add(element);
		this.cards.push(card);
		return card;
	},
	showPage: function(index){
		var card = this.cards[index];
		if (card) {
			var tabindexes = this.element.find('[tabIndex], input');
			tabindexes && tabindexes.handle(disableTabIndex);

			var cardindexes = card.find('[tabIndex], input');
			cardindexes && cardindexes.handle(enableTabIndex);
			var top = card.compute('top');

			var first = this.element[0].firstChild;
			$(first).style('top', top);
			card.style('top', 0);
			card.top(this.element);

		}
	},
	toElement: function(){
		return this.element;
	}
});
Ejemplo n.º 23
0
var Request = prime({

    constructor: function Request(){
        this._header = {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    },

    header: function(name, value){
        if (isObject(name)) for (var key in name) this.header(key, name[key])
        else if (!arguments.length) return this._header
        else if (arguments.length === 1) return this._header[capitalize(name)]
        else if (arguments.length === 2){
            if (value == null) delete this._header[capitalize(name)]
            else this._header[capitalize(name)] = value
        }
        return this
    },

    running: function(){
        return !!this._running
    },

    abort: function(){

        if (this._queued){
            remove(Q, this._queued)
            delete this._queued
        }

        if (this._xhr){
            this._xhr.abort()
            this._end()
        }

        return this
    },

    method: function(m){
        if (!arguments.length) return this._method
        this._method = m.toUpperCase()
        return this
    },

    data: function(d){
        if (!arguments.length) return this._data
        this._data = d
        return this
    },

    url: function(u){
        if (!arguments.length) return this._url
        this._url = u
        return this
    },

    user: function(u){
        if (!arguments.length) return this._user
        this._user = u
        return this
    },

    password: function(p){
        if (!arguments.length) return this._password
        this._password = p
        return this
    },

    _send: function(method, url, data, header, user, password, callback){
        var self = this

        if (REQUESTS === agent.MAX_REQUESTS) return Q.unshift(this._queued = function(){
            delete self._queued
            self._send(method, url, data, header, user, password, callback)
        })

        REQUESTS++

        var xhr = this._xhr = agent.getRequest()

        if (xhr.addEventListener) forEach(['progress', 'load', 'error' , 'abort', 'loadend'], function(method){
            xhr.addEventListener(method, function(event){
                self.emit(method, event)
            }, false)
        })

        xhr.open(method, url, true, user, password)
        if (user != null && "withCredentials" in xhr) xhr.withCredentials = true

        xhr.onreadystatechange = function(){
            if (xhr.readyState === 4){
                var status = xhr.status
                var response = new Response(xhr.responseText, status, parseHeader(xhr.getAllResponseHeaders()))
                var error = response.error ? new Error(method + " " + url + " " + status) : null
                self._end()
                callback(error, response)
            }
        }

        for (var field in header) xhr.setRequestHeader(field, header[field])
        xhr.send(data || null)
    },

    _end: function(){
        this._xhr.onreadystatechange = function(){}

        delete this._xhr
        delete this._running

        REQUESTS--

        var queued = Q.pop()
        if (queued) queued()
    },

    send: function(callback){
        if (this._running) this.abort()
        this._running = true

        if (!callback) callback = function(){}

        var method   = this._method || "POST",
            data     = this._data || null,
            url      = this._url,
            user     = this._user || null,
            password = this._password || null

        if (data && !isString(data)){
            var contentType = this._header['Content-Type'].split(/ *; */).shift(),
                encode      = encoders[contentType]
            if (encode) data = encode(data)
        }

        if (/GET|HEAD/.test(method) && data) url += (url.indexOf("?") > -1 ? "&" : "?") + data

        var header = mixIn({}, this._header);

        this._send(method, url, data, header, user, password, callback)

        return this

    }

})
Ejemplo n.º 24
0
'use strict';

var prime = require('prime'),
	zen = require('elements/zen'),
	GroupBase = require('./base');

var GroupDefault = prime({
	inherits: GroupBase,

	constructor: function(spec){
		if (!(this instanceof GroupDefault)){
			return new GroupDefault(spec);
		}
		GroupBase.call(this, spec);
	},

	build: function(){
		if (this.wrap) return;
		this.wrap = zen('fieldset');
		if (this.spec.name){
			zen('legend').text(this.spec.name).insert(this.wrap);
		}
		this.fieldContainer = zen('ul').insert(this.wrap);
	}
});

module.exports = GroupDefault;
Ejemplo n.º 25
0
var type = require('prime/type');


var _instance;
var Serialosc = prime({
  _devices: false,
  _factory: false,
  constructor: function() {
    this._devices = {};
    this._factory = new (require(__dirname+'/device.factory.js'));
    _instance  = this;
  },
  createDevice: function(options, callback) {
    if (!callback || type(callback) != 'function') callback = function(err) { if (err) throw Error(err); };


    this._factory.createDevice(options, function(err, device) {
      if (err) callback(err);
      callback(null, device);
    }.bind(this));
  },
  killDevice: function(deviceId, callback) {

  },
  getDevice: function(id) {
    return this._devices[id] ? this._devices[id] : false;
  }
});
module.exports = function(options) {
  return (!_instance) ? new Serialosc(options) : _instance;
}
Ejemplo n.º 26
0
var Watchout = prime({
    _stopped: false,

    /**
     * Constructor
     * @param  {Number}   time                      Delay for deferred function
     * @param  {Function} callback                  Deferred function
     * @param  {Function} task(reset, done, cancel) Optional. Executed immediately after deferred is created.
     */
    constructor: function(time, callback, task) {
        var scope = this

        checkTime(time)
        checkCallback(callback)
        
        scope._time = time
        scope._callback = callback
        scope._task = task

        scope._setDefer(time)

        task && task(function(time) {
            scope.reset(time)
        }, function() {
            scope.pass()
        }, function() {
            scope.cancel()
        })
    },

    /**
     * Cancel and cleanup deferred
     * @private
     */
    _cancel: function() {
        var scope = this
        var deferredCancel = scope._deferredCancel

        deferredCancel && deferredCancel()

        delete scope._deferredCancel
    },

    /**
     * Generate a deferred function
     * @private
     * @param {Number} time Delay for deferred function
     */
    _setDefer: function(time) {
        var scope = this

        checkTime(time)

        scope._deferredCancel = defer(function() {
            scope.fail()
        }, time)
    },

    /**
     * Reset the watchdog. Cancels the previously set deferred function
     * and sets a new one.
     * @param  {Number} time Delay for the deferred
     */
    reset: function(time) {
        var scope = this

        if (time === undefined) {
            time = scope._time
        }

        if (!scope._stopped) {
            scope._cancel()

            scope._setDefer(time)
        }
    },

    /**
     * Complete by canceling the watchdog and calling callback
     * @param  {Boolean}   haltedTimeout Determine whether the task was completed before the timeout
     */
    done: function(haltedTimeout) {
        var scope = this

        if (!scope._stopped) {
            scope._stopped = true

            scope._cancel()

            scope._callback(!!haltedTimeout)
        }
    },

    /**
     * Convenience method triggering done successfully
     */
    pass: function() {
        this.done(true)
    },

    /**
     * Convenience method triggering done unsuccessfully
     */
    fail: function() {
        this.done(false)
    },

    /**
     * Cancel the watchdog
     */
    cancel: function() {
        var scope = this

        if (!scope._stopped) {
            scope._stopped = true

            scope._cancel()
        }
    }
})
Ejemplo n.º 27
0
var FieldSingleOption = prime({
	inherits: FieldBase,

	constructor: function(spec, value){
		if (!(this instanceof FieldSingleOption)){
			return new FieldSingleOption(spec, value);
		}
		FieldBase.call(this, spec, value);

		this.styles = ['select', 'radio'];

		this.style = this.spec.style || 'select';
		if (indexOf(this.styles, this.style) == -1){
			throw new Error('Invalid style selected');
		}
	},

	build: function(){
		this.wrap = zen('li');
		zen('label').text(this.spec.label || '').insert(this.wrap);

		switch (this.style){
			case 'select': this.buildSelect(); break;
			case 'radio': this.buildRadio(); break;
		}
	},

	buildSelect: function(){
		this.input = zen('select').insert(this.wrap);
		zen('option').value('').text('...').insert(this.input);

		if (this.spec.name){
			this.input.attribute('name', this.spec.name);
		}

		if (!this.spec.options || !this.spec.options.length) return;

		var i, len = this.spec.options.length, opt;
		for (i = 0; i < len; i++){
			opt = this.spec.options[i];
			zen('option').value(opt.value).text(opt.label)
				.selected(opt.value == this.value)
				.insert(this.input);
		}
	},

	buildRadio: function(){
		var fieldset = zen('fieldset.options').insert(this.wrap),
			ul = zen('ul').insert(fieldset);

		if (!this.spec.options || !this.spec.options.length) return;

		var i, len = this.spec.options.length, opt, li;
		for (i = 0; i < len; i++){
			opt = this.spec.options[i];
			li = zen('li').insert(ul);
			zen('input[type=radio]').attribute('name', this.spec.name).value(opt.value).insert(li);
			zen('label').text(opt.label).insert(li);
		}
	}
});
Ejemplo n.º 28
0
"use strict";

var prime = require('prime')
var forOwn = require('prime/object/forOwn')
var Relative = require('./mixin/relative')

var ASCII = prime({

    inherits: require('./'),

    relativeModules: Relative.prototype.relativeModules,

    up: function(callback){
        var modules = this.relativeModules()
        var str = ''
        forOwn(modules, function(mod, name){
            str += name
            if (mod.namespace) str += ' (' + mod.namespace + ')'
            str += '\n'
            var len = mod.deps.length
            mod.deps.forEach(function(dep, i){
                str += (i + 1 == len ? '└─' : '├─') + dep + '\n'
            })
        })
        callback(null, str)
    }

})

module.exports = ASCII
Ejemplo n.º 29
0
var FuzzySearch = prime({

    modules: null,

    options: {
        'caseSensitive': false,
        'termPath': '',
        'returnEmptyArray': false,
        'minimumScore': 0
    },

    constructor: function(searchSet, options) {
        this.options = obj.mixin(obj.create(this.options), options);
        this.searchSet = searchSet;
        this.modules = [];
    },

    addModule: function(mod) {
        this.modules.push(mod);
    },

    search: function(needle) {
        needle = !this.options.caseSensitive ? trim(needle).toLowerCase() : trim(needle);
        var result = [];

        arr.forEach(this.searchSet, function(value) {
            var origValue = value;
            var searchValue = this.options.termPath.length === 0 ? value : obj.fromPath(value, this.options.termPath);

            if (!this.options.caseSensitive) {
                searchValue = searchValue.toLowerCase();
            }

            var score = this.getCombinedModulePoints(needle, searchValue);

            if (score.combined >= this.options.minimumScore) result.push({'score': score.combined, 'details': score.details, 'value': origValue});
        }, this);

        if (!this.options.returnEmptyArray && result.length === 0) {
            return null;
        }

        return result.sort(function(a, b) {
            return b.score - a.score;
        });
    },

    getCombinedModulePoints: function(needle, haystack) {
        var result = {'combined': 0, 'details': []};
        arr.forEach(this.modules, function(mod) {
            var score = mod.search(needle, haystack).getPoints();
            var name = mod.getName();
            var factor = mod.getFactor();

            result.combined += factor * score;
            result.details.push({'name': name, 'score': score, 'factor': factor});
        });

        return result;
    },

    getMaximumScore: function() {
        var factorSum = 0;
        arr.forEach(this.modules, function(mod) {
            factorSum += mod.getFactor();
        });

        return 100 * factorSum;
    }

});
Ejemplo n.º 30
0
var Scanner = prime({

    inherits: Emitter,

    constructor: function(resolver, storage){
        this.withResolver(resolver).withStorage(storage)
        this.options = {}
        this.index = 0
        this.uids = {}
        this.transforms = []
    },

    withResolver: function(resolver){
        this.resolver = resolver
        return this
    },

    withStorage: function(storage){
        this.storage = storage
        return this
    },

    addTransform: function(transform){
        this.transforms.push(transform)
        return this
    },

    set: function(option, value){
        this.options[option] = value
        return this
    },

    scan: function(what, from, callback){

        var resolver = this.resolver
        var storage  = this.storage

        var modulefull = resolver.resolve(what, from)
        var self = this

        if (modulefull == null){
            this.emit("warn", new ResolveError(what, from))
            return callback()
        }

        if (modulefull === true){
            this.emit("warn", new NativeError(what, from))
            return callback()
        }

        var inPath = this.options.inPath
        if (inPath && !util.inPath(inPath, modulefull)){
            this.emit("warn", new NotInPathError(what, from, inPath))
            return callback()
        }

        // check if we already have this module and it's still valid
        var module = storage.get(modulefull)
        if (module && !module.invalid) return callback(null, module)

        if (module && module.invalid){
            // make the module valid again, it will be reparsed now
            module.invalid = false
            module.err = false
        } else {
            // only create a new module object if it didn't exist yet
            module = new Module(modulefull, this.uids[modulefull] || (this.index++).toString(36))
            // ensure the file is always associated with the same uid
            this.uids[modulefull] = module.uid
        }

        storage.put(module)

        var transforms = []

        // from filename to code
        transforms.push(function(module, callback){
            fs.readFile(module.full, 'utf-8', function(err, src){

                if (err && err.code == 'ENOENT'){
                    // It is possible that .resolve still resolves the file
                    // correctly, but that the file actually doesn't exist anymore.
                    // Then still fire the "warn" event that the file cannot be
                    // resolved
                    self.emit("warn", new ResolveError(what, from))
                }

                module.src = src
                callback(err, module)

            })
        })

        function pushTransform(type){
            return function(transform){
                if (typeof transform != 'object') return
                transforms.push(function(module, callback){
                    var trsfrm = transform[type]
                    if (!trsfrm) callback(null, module)
                    else trsfrm(module, callback)
                })
            }
        }

        // some code transformations
        this.transforms.forEach(pushTransform('src'))

        // stream transforms compatible with browserify
        function pushStreamTransform(transform){
            if (typeof transform != 'function') return
            transforms.push(function(module, callback){
                var stream = transform(module.full)
                var src = ''
                stream.on('data', function(buf){
                    src += buf
                })
                stream.on('end', function(){
                    module.src = src
                    callback(null, module)
                })
                stream.write(module.src)
                stream.end()
            })
        }

        this.transforms.forEach(pushStreamTransform)

        // from code to AST
        transforms.push(function(module, callback){

            // parse the code with esprima to see if there are any errors and
            // so we can walk through the AST to find require()s
            try {
                module.ast = esprima.parse(module.src, {
                    loc: true,
                    source: util.relative(module.full)
                })
                callback(null, module)
            } catch (e){
                // add to the object so it will be watched for newer versions
                module.err = true
                var err = new JavaScriptError(modulefull, from, e.lineNumber, e.column)
                self.emit("warn", err)
                callback(err)
            }
        })

        // some AST transformations
        this.transforms.forEach(pushTransform('ast'))

        transforms.push(function(module, callback){
            self.findRequires(module, function(err){
                if (err) return callback(err)
                module.ready = true
                self.emit('scan', module)
                callback(null, module)
            })
        })

        async.reduce(transforms, module, function(memo, item, callback){
            item(memo, callback)
        }, function(err, module){
            if (module && module.err) return
            callback(err, module)
        })
    },

    findRequires: function(module, callback){
        var self = this

        var ast = module.ast
        var sourcemap = this.options.sourcemap && ast.loc && !ast.loc.source
        var source = sourcemap && util.relative(module.full)

        util.astWalker(ast, function(ast, parent, key, path){
            // temporary fix until https://github.com/ariya/esprima/pull/148
            // is pulled and released.
            if (ast && sourcemap && key == 'loc'){
                ast.source = source
                return true
            }

            if (ast &&
                    (ast.type == "CallExpression" || ast.type == "NewExpression") &&
                    ast.callee.name == "require"){
                module.requires.push({
                    path: path,
                    ast: ast,
                    argument: ast['arguments'].length == 1 && ast['arguments'][0].value,
                    i: module.requires.length})
                return true
            }
        })

        async.forEach(module.requires, function(require, callback){
            var dep = require.argument
            // note that deps also contains "null" values if the module could
            // not be resolved. This way an output prime can determine to
            // remove the require, or do something else with it.
            if (!dep){
                module.dependencies[require.i] = null
                callback()
            } else self.scan(dep, module.full, function(err, mod){
                if (err) return callback(err)
                module.dependencies[require.i] = mod ? mod : null
                if (mod) mod.dependents.push(module)
                callback()
            })
        }, callback)
    }

})