<commit_before>/**
 * Primary passport service implementation
*/
var express     = require('express');
var http        = require('http');
var passport    = require('passport');
var MemoryStore = require('connect/lib/middleware/session/memory');

this.vent       = new Backbone.Wreqr.EventAggregator();
this.commands   = new Backbone.Wreqr.Commands();
this.reqres     = new Backbone.Wreqr.RequestResponse();
var _express    = express();
this.express    = _express;
this.server     = http.createServer(this.express);

_.extend(this, _express, {
    // Command execution, facilitated by Backbone.Wreqr.Commands
    execute: function(){
        var args = Array.prototype.slice.apply(arguments);
        this.commands.execute.apply(this.commands, args);
    },
    // Request/response, facilitated by Backbone.Wreqr.RequestResponse
    request: function(){
        var args = Array.prototype.slice.apply(arguments);
        return this.reqres.request.apply(this.reqres, args);
    }
});

// Set to specify which model is to be used for authentication.
this.Model = this.Model || Graft.BaseModel;

// Set a SessionStore to use for storing sessions.
this.SessionStore = this.SessionStore || new MemoryStore({
    reapInterval: 60000 * 10
});

this.commands.setHandler('deserialize', function(obj, done) {
    done(null, new this.Model(obj));
}, this);

this.commands.setHandler('serialize', function(user, done) {
    done(null, user);
});

this.commands.setHandler('verify', function(user, done) {
    done(null, false, { error: 'No Authentication Strategy' });
});

this.addInitializer(function(options) {
    passport.serializeUser(this.execute.bind(this, 'serialize'));
    passport.deserializeUser(this.execute.bind(this, 'deserialize'));
});

this.reqres.setHandler('failureRedirect', _.f.functionize('/'));
this.reqres.setHandler('successRedirect', _.f.functionize('/'));
this.reqres.aliasHandler('logoutRedirect', 'successRedirect');

this.commands.setHandler('mount', function(key, strategy, method) {
    var method = method || 'get';

    var opts = {
        successRedirect: this.request('successRedirect'),
        failureRedirect: this.request('failureRedirect')
    };

    debug('mount', method, key);
    function testFn(req, res, next) { debug('called mount', method, key); next(); }
    this[method]('/' + key, testFn, passport.authenticate(key, opts));
}, this);

this.reqres.setHandler('createStrategy', function(key, Strategy, opts) {
    var opts = opts || {};

    var verifyFn = function() {
        var args = Array.prototype.slice.apply(arguments);
        args.unshift('verify:'+key);
        this.execute.apply(this, args);
    }.bind(this);

    var strategy = new Strategy(opts, verifyFn);
    strategy.name = key;

    passport.use(key, strategy);
}, this);

Graft.Server.on('before:mount:router', function server(opts) {
    this.use(express.cookieParser());
    this.use(express.session({
        secret: 'secret',
        key: 'express.sid',
        store: this.SessionStore
    }));
    this.use(passport.initialize());
    this.use(passport.session());
    this.use(this.router);

    this.trigger('mount:routes');
    this.get('/', function(req, res, next) {
        if (!req.user) { return res.send(403, {error: 'Not Authorized'}); }
        res.send(req.user);
    });

    var logoutRedirect = this.request('logoutRedirect');
    this.del('/', function(req, res){
        req.logout();
        this.trigger('after:logout', logoutRedirect);
        res.send(302, { Location: logoutRedirect });
    }.bind(this));

}, this);

Graft.Server.on('listen', function(Server) {
    debug('Mounting auth server', this.routes);
    Graft.Server.use('/auth', this);
}, this);
<commit_msg>mount routes differently.<commit_after>/**
 * Primary passport service implementation
*/
var express     = require('express');
var http        = require('http');
var passport    = require('passport');
var MemoryStore = require('connect/lib/middleware/session/memory');

this.vent       = new Backbone.Wreqr.EventAggregator();
this.commands   = new Backbone.Wreqr.Commands();
this.reqres     = new Backbone.Wreqr.RequestResponse();
var _express    = express();
this.express    = _express;
this.server     = http.createServer(this.express);

_.extend(this, _express, {
    // Command execution, facilitated by Backbone.Wreqr.Commands
    execute: function(){
        var args = Array.prototype.slice.apply(arguments);
        this.commands.execute.apply(this.commands, args);
    },
    // Request/response, facilitated by Backbone.Wreqr.RequestResponse
    request: function(){
        var args = Array.prototype.slice.apply(arguments);
        return this.reqres.request.apply(this.reqres, args);
    }
});

// Set to specify which model is to be used for authentication.
this.Model = this.Model || Graft.BaseModel;

// Set a SessionStore to use for storing sessions.
this.SessionStore = this.SessionStore || new MemoryStore({
    reapInterval: 60000 * 10
});

this.commands.setHandler('deserialize', function(obj, done) {
    done(null, new this.Model(obj));
}, this);

this.commands.setHandler('serialize', function(user, done) {
    done(null, user);
});

this.commands.setHandler('verify', function(user, done) {
    done(null, false, { error: 'No Authentication Strategy' });
});

this.addInitializer(function(options) {
    passport.serializeUser(this.execute.bind(this, 'serialize'));
    passport.deserializeUser(this.execute.bind(this, 'deserialize'));
});

this.reqres.setHandler('failureRedirect', _.f.functionize('/'));
this.reqres.setHandler('successRedirect', _.f.functionize('/'));
this.reqres.aliasHandler('logoutRedirect', 'successRedirect');

this.commands.setHandler('mount', function(key, strategy, method) {
    var method = method || 'get';

    var opts = {
        successRedirect: this.request('successRedirect'),
        failureRedirect: this.request('failureRedirect')
    };

    debug('mount', method, key);
    function testFn(req, res, next) { debug('called mount', method, key); next(); }
    this[method]('/' + key, testFn, passport.authenticate(key, opts));
}, this);

this.reqres.setHandler('createStrategy', function(key, Strategy, opts) {
    var opts = opts || {};

    var verifyFn = function() {
        var args = Array.prototype.slice.apply(arguments);
        args.unshift('verify:'+key);
        this.execute.apply(this, args);
    }.bind(this);

    var strategy = new Strategy(opts, verifyFn);
    strategy.name = key;

    passport.use(key, strategy);
}, this);

Graft.Server.on('after:mount:server', function server(opts) {
    this.use(express.cookieParser());
    this.use(express.session({
        secret: 'secret',
        key: 'express.sid',
        store: this.SessionStore
    }));
    this.use(passport.initialize());
    this.use(passport.session());
    this.use(this.router);

    this.trigger('mount:routes');
    this.get('/', function(req, res, next) {
        if (!req.user) { return res.send(403, {error: 'Not Authorized'}); }
        res.send(req.user);
    });

    var logoutRedirect = this.request('logoutRedirect');
    this.del('/', function(req, res){
        req.logout();
        this.trigger('after:logout', logoutRedirect);
        res.send(302, { Location: logoutRedirect });
    }.bind(this));

}, this);

Graft.Server.on('listen', function(Server) {
    Graft.Server.use('/auth', this);
    debug('Mounting auth server', this.routes);
}, this);
<|endoftext|>


<commit_before>var Crafty = require('../core/core.js');

// An object for wrangling textures
// An assumption here is that doing anything with textures is fairly expensive, so the code should be expressive rather than performant
Crafty.TextureManager = TextureManager;

function TextureManager (gl, webgl) {
	this.gl = gl;
	this.webgl = webgl;
	// The maximum number of units the environment says it supports
	this.max_units =  gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
	// An array of textures bound to a texture unit; position corresponds to the unit in question
	this.bound_textures = [];
	// A dictionary of registered textures, so that multiple copies of the same texture aren't generated
	this.registered_textures = {};
	// Try to track which texture is active
	this.active = null;
}

TextureManager.prototype = {

	// Clear out the bound textures and other existing state
	reset: function(){
		var t;
		for (var i = 0; i < this.bound_textures.length; i++){
			t = this.bound_textures[i];
			t.unbind();
		}
		this.bound_textures = [];
		this.active = null;
	},

	// creates a texture out of the given image and repeating state
	// The url is just used to generate a unique id for the texture
	makeTexture: function(url, image, repeating) {
        // gl is the context, webgl is the Crafty object containing prefs/etc
        // var gl = this.gl;
        var webgl = this.webgl;

        // Check whether a texture that matches the one requested already exists
        var id =  "texture-(r:" + repeating + ")-" + url;
        if (typeof this.registered_textures[id] !== 'undefined')
            return this.registered_textures[id];

        // Create a texture, bind it to the next available unit
        var t = new TextureWrapper(this, id);
        this.registered_textures[id] = t;
        this.bindTexture(t);

        // Set the properties of the texture
        t.setImage(image);
        t.setFilter(webgl.texture_filter);
        t.setRepeat(repeating);

        return t;
    },

    // Returns the bound texture of smallest size
    // If we have more textures than available units, we should preferentially leave the larger textures bound?
	smallest: function() {
		var min_size = Infinity;
		var index = null;
		for (var i=0; i<this.bound_textures.length; i++) {
			var t = this.bound_textures[i];
			if (t.size < min_size) {
				min_size = t.size;
				index = i;
			}
		}
		return index;
	},

	// Returns either the first empty unit, or the unit of the smallest bound texture
	getAvailableUnit: function() {
		if (this.bound_textures.length < this.max_units) {
			return this.bound_textures.length;
		} else {
			return this.smallest();
		}
	},

	// takes a texture object and, if it isn't associated with a unit, binds it to one
	bindTexture: function(t) {
		// return if the texture is already bound
		if (t.unit !== null) return;
		var i = this.getAvailableUnit();
		if (this.bound_textures[i]){
			this.unbindTexture(this.bound_textures[i]);
		}
		this.bound_textures[i] = t;
		t.bind(i);

	},

	// We don't actually "unbind" the texture -- we just set it's bound state to null
	// This is called before another texture is bound
	unbindTexture: function(t) {
		t.unbind();
	},

	setActiveTexture: function(t) {
		if (this.active === t.id) return;
		this.gl.activeTexture(this.gl[t.name]);
		this.active = t.unit;
	}

};

// An object for abstracting out the gl calls associated with textures
Crafty.TextureWrapper = TextureWrapper;

function TextureWrapper (manager, id){
	this.manager = manager;
	this.gl = manager.gl;
	this.glTexture = this.gl.createTexture();
	this.id = id;
	this.active = false;
	this.unit = null;
	this.powerOfTwo = false;
}

TextureWrapper.prototype = {

	// Given a number, binds to the corresponding texture unit
	bind: function(unit) {
		var gl = this.gl;
		this.unit = unit;
		this.name = "TEXTURE" + unit;
		this.manager.setActiveTexture(this);
		gl.bindTexture(gl.TEXTURE_2D, this.glTexture);
	},

	// Check whether this texture is active (important for setting properties)
	isActive: function() {
		return (this.manager.active === this.unit);
	},

	// Since gl doesn't require unbinding, just clears the metadata
	unbind: function() {
		this.unit = null;
		this.name = null;
		if(this.isActive())
			this.manager.active = null;
	},

	// actually loads an image into the texture object; sets the appropriate metadata
	setImage: function(image) {
		if(!this.isActive()) throw("Trying to set image of texture that isn't active");
		this.width = image.width;
		this.height = image.height;
		this.size = image.width * image.height;
		this.powerOfTwo = !((Math.log(image.width)/Math.LN2 !== Math.floor(Math.log(image.width)/Math.LN2)) || (Math.log(image.height)/Math.LN2 !== Math.floor(Math.log(image.height)/Math.LN2)));
		var gl = this.gl;
		gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
	},

	// Sets the min/mag filters
	setFilter: function(filter) {
		if(!this.isActive()) throw("Trying to set filter of texture that isn't active");
		var gl = this.gl;
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
	},

	// set image wrapping
	setRepeat: function(repeat) {
		if(!this.isActive()) throw("Trying to set repeat property of texture that isn't active");
		if(repeat && !this.powerOfTwo){
			throw("Can't create a repeating image whose dimensions aren't a power of 2 in WebGL contexts");
		}
		var gl = this.gl;
		this.repeatMode = repeat ? gl.REPEAT : gl.CLAMP_TO_EDGE;
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.repeatMode);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.repeatMode);
	},

	// given a shader and pair of uniform names, sets the sampler and dimensions to be used by this texture
	setToProgram: function(shader, sampler_name, dimension_name) {
		if(this.unit === null) throw("Trying to use texture not set to a texture unit.");
		var gl = this.gl;
		gl.useProgram(shader);
        // Set the texture buffer to use
        gl.uniform1i(gl.getUniformLocation(shader, sampler_name), this.unit);
        // Set the image dimensions
        gl.uniform2f(gl.getUniformLocation(shader, dimension_name), this.width, this.height);
	}
};<commit_msg>Fix indentation of graphics/gl-textures.js<commit_after>var Crafty = require('../core/core.js');

// An object for wrangling textures
// An assumption here is that doing anything with textures is fairly expensive, so the code should be expressive rather than performant
Crafty.TextureManager = TextureManager;

function TextureManager (gl, webgl) {
    this.gl = gl;
    this.webgl = webgl;
    // The maximum number of units the environment says it supports
    this.max_units =  gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
    // An array of textures bound to a texture unit; position corresponds to the unit in question
    this.bound_textures = [];
    // A dictionary of registered textures, so that multiple copies of the same texture aren't generated
    this.registered_textures = {};
    // Try to track which texture is active
    this.active = null;
}

TextureManager.prototype = {

    // Clear out the bound textures and other existing state
    reset: function(){
        var t;
        for (var i = 0; i < this.bound_textures.length; i++){
            t = this.bound_textures[i];
            t.unbind();
        }
        this.bound_textures = [];
        this.active = null;
    },

    // creates a texture out of the given image and repeating state
    // The url is just used to generate a unique id for the texture
    makeTexture: function(url, image, repeating) {
        // gl is the context, webgl is the Crafty object containing prefs/etc
        // var gl = this.gl;
        var webgl = this.webgl;

        // Check whether a texture that matches the one requested already exists
        var id =  "texture-(r:" + repeating + ")-" + url;
        if (typeof this.registered_textures[id] !== 'undefined')
            return this.registered_textures[id];

        // Create a texture, bind it to the next available unit
        var t = new TextureWrapper(this, id);
        this.registered_textures[id] = t;
        this.bindTexture(t);

        // Set the properties of the texture
        t.setImage(image);
        t.setFilter(webgl.texture_filter);
        t.setRepeat(repeating);

        return t;
    },

    // Returns the bound texture of smallest size
    // If we have more textures than available units, we should preferentially leave the larger textures bound?
    smallest: function() {
        var min_size = Infinity;
        var index = null;
        for (var i=0; i<this.bound_textures.length; i++) {
            var t = this.bound_textures[i];
            if (t.size < min_size) {
                min_size = t.size;
                index = i;
            }
        }
        return index;
    },

    // Returns either the first empty unit, or the unit of the smallest bound texture
    getAvailableUnit: function() {
        if (this.bound_textures.length < this.max_units) {
            return this.bound_textures.length;
        } else {
            return this.smallest();
        }
    },

    // takes a texture object and, if it isn't associated with a unit, binds it to one
    bindTexture: function(t) {
        // return if the texture is already bound
        if (t.unit !== null) return;
        var i = this.getAvailableUnit();
        if (this.bound_textures[i]){
            this.unbindTexture(this.bound_textures[i]);
        }
        this.bound_textures[i] = t;
        t.bind(i);

    },

    // We don't actually "unbind" the texture -- we just set it's bound state to null
    // This is called before another texture is bound
    unbindTexture: function(t) {
        t.unbind();
    },

    setActiveTexture: function(t) {
        if (this.active === t.id) return;
        this.gl.activeTexture(this.gl[t.name]);
        this.active = t.unit;
    }

};

// An object for abstracting out the gl calls associated with textures
Crafty.TextureWrapper = TextureWrapper;

function TextureWrapper (manager, id){
    this.manager = manager;
    this.gl = manager.gl;
    this.glTexture = this.gl.createTexture();
    this.id = id;
    this.active = false;
    this.unit = null;
    this.powerOfTwo = false;
}

TextureWrapper.prototype = {

    // Given a number, binds to the corresponding texture unit
    bind: function(unit) {
        var gl = this.gl;
        this.unit = unit;
        this.name = "TEXTURE" + unit;
        this.manager.setActiveTexture(this);
        gl.bindTexture(gl.TEXTURE_2D, this.glTexture);
    },

    // Check whether this texture is active (important for setting properties)
    isActive: function() {
        return (this.manager.active === this.unit);
    },

    // Since gl doesn't require unbinding, just clears the metadata
    unbind: function() {
        this.unit = null;
        this.name = null;
        if(this.isActive())
            this.manager.active = null;
    },

    // actually loads an image into the texture object; sets the appropriate metadata
    setImage: function(image) {
        if(!this.isActive()) throw("Trying to set image of texture that isn't active");
        this.width = image.width;
        this.height = image.height;
        this.size = image.width * image.height;
        this.powerOfTwo = !((Math.log(image.width)/Math.LN2 !== Math.floor(Math.log(image.width)/Math.LN2)) || (Math.log(image.height)/Math.LN2 !== Math.floor(Math.log(image.height)/Math.LN2)));
        var gl = this.gl;
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
    },

    // Sets the min/mag filters
    setFilter: function(filter) {
        if(!this.isActive()) throw("Trying to set filter of texture that isn't active");
        var gl = this.gl;
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
    },

    // set image wrapping
    setRepeat: function(repeat) {
        if(!this.isActive()) throw("Trying to set repeat property of texture that isn't active");
        if(repeat && !this.powerOfTwo){
            throw("Can't create a repeating image whose dimensions aren't a power of 2 in WebGL contexts");
        }
        var gl = this.gl;
        this.repeatMode = repeat ? gl.REPEAT : gl.CLAMP_TO_EDGE;
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.repeatMode);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.repeatMode);
    },

    // given a shader and pair of uniform names, sets the sampler and dimensions to be used by this texture
    setToProgram: function(shader, sampler_name, dimension_name) {
        if(this.unit === null) throw("Trying to use texture not set to a texture unit.");
        var gl = this.gl;
        gl.useProgram(shader);
        // Set the texture buffer to use
        gl.uniform1i(gl.getUniformLocation(shader, sampler_name), this.unit);
        // Set the image dimensions
        gl.uniform2f(gl.getUniformLocation(shader, dimension_name), this.width, this.height);
    }
};<|endoftext|>


<commit_before>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

module.exports = function(f, min_interval_ms) {
    this.lastCall = 0;
    this.scheduledCall = undefined;

    var self = this;
    return function() {
        var now = Date.now();

        if (self.lastCall < now - min_interval_ms) {
            f.apply(this);
            self.lastCall = now;
        } else if (self.scheduledCall === undefined) {
            self.scheduledCall = setTimeout(() => {
                    self.scheduledCall = undefined;
                    f.apply(this);
                    self.lastCall = now;
                },
                (self.lastCall + min_interval_ms) - now
            );
        }
    };
};

<commit_msg>Style things from PR comments<commit_after>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

module.exports = function(f, minIntervalMs) {
    this.lastCall = 0;
    this.scheduledCall = undefined;

    var self = this;
    return function() {
        var now = Date.now();

        if (self.lastCall < now - minIntervalMs) {
            f.apply(this);
            self.lastCall = now;
        } else if (self.scheduledCall === undefined) {
            self.scheduledCall = setTimeout(
                () => {
                    self.scheduledCall = undefined;
                    f.apply(this);
                    self.lastCall = now;
                },
                (self.lastCall + minIntervalMs) - now
            );
        }
    };
};

<|endoftext|>


<commit_before>var _ = require('lodash'),
    reactDocs = require('react-docgen'),
    Handlebars = require('handlebars');

/********************************************************
 * Helpers                                              *
 ********************************************************/

var sortObjectByKey = function(obj){
    return _(obj).keys().sort().reduce(function(memo, key) {
        memo[key] = obj[key];
        return memo;
    }, {});
};

/********************************************************
 * Prop type partials and handblebars helpers           *
 ********************************************************/

Handlebars.registerPartial('catchAll', '{{name}}');

// Basic prop types
Handlebars.registerPartial('func', 'Function');
Handlebars.registerPartial('array', 'Array');
Handlebars.registerPartial('object', 'Object');
Handlebars.registerPartial('string', 'String');
Handlebars.registerPartial('number', 'Number');
Handlebars.registerPartial('bool', 'Boolean');
Handlebars.registerPartial('node', 'ReactNode');
Handlebars.registerPartial('element', 'ReactElement');
Handlebars.registerPartial('any', '*');
Handlebars.registerPartial('custom', '{{raw}} (custom validator)');

// composed prop types
Handlebars.registerPartial('arrayOf', '[{{> (whichPartial value) value level=level}}, ...]');

Handlebars.registerPartial('shape', '{\n\
{{#indent level}}\
{{#each value}}\
    {{@key}}: {{> (whichPartial this) this level=(addLevel ../level)}}\n\
{{/each}}\n\
}\
{{/indent}}');

Handlebars.registerPartial('enum', '(\
{{#each value}}\
{{this.value}}{{#unless @last}}|{{/unless}}\
{{/each}}\
)');

Handlebars.registerPartial('union', '(\
{{#each value}}\
{{> (whichPartial this) this level=../level}}{{#unless @last}}|{{/unless}}\
{{/each}}\
)');

// Partial helper. Tells us which partial to use based on the "propType" name
Handlebars.registerHelper('whichPartial', function(type) {
    var partials = [
        'any', 'array', 'arrayOf', 'bool', 'custom', 'element', 'enum', 'func',
        'node', 'number', 'object', 'shape', 'string', 'union'
    ];
    return type && _.includes(partials, type.name) ? type.name : 'catchAll';
});

/********************************************************
 * General helpers                                      *
 ********************************************************/

// math helper
Handlebars.registerHelper('addLevel', function(level) { return level + 1; });

// loop helper
Handlebars.registerHelper('indent', function(indentLevel, options) {
    var content = options.fn(this),
        lines = content.split('\n'),
        indentString = '';

    // build the indent string we need for this indent level
    for (var i = 0; i < indentLevel; i++) {
        indentString += '    ';
    }

    // add then indents to each line
    lines = lines.map(function(line) { return line = indentString + line; });
    return lines.join('\n');
});

/********************************************************
 * Top-level handlebars template                        *
 ********************************************************/

var reactDocgenTemplate = Handlebars.compile('\
## {{componentName}}\n\n\
{{#if srcLink }}From [`{{srcLink}}`]({{srcLink}})\n\n\{{/if}}\
{{#if description}}{{{description}}}\n\n{{/if}}\
{{#each props}}\
#### {{@key}}\n\n\
```js\n\
{{#if this.required}}// Required\n{{/if}}\
{{#if this.defaultValue}}// Default: {{{this.defaultValue.value}}}\n{{/if}}\
{{@key}}: {{> (whichPartial this.type) this.type level=0}}\n\
```\n\n\
{{#if this.description}}{{{this.description}}}\n\n{{/if}}\
{{/each}}\

\n');

/********************************************************
 * Documentation generator using react-docgen           *
 ********************************************************/

var reactDocgenMarkdown = function(componentSrc, options) {
    var docs = reactDocs.parse(componentSrc);
    return reactDocgenTemplate({
        srcLink         : options.srcLink,
        componentName   : options.componentName,
        description     : docs.description,
        props           : sortObjectByKey(docs.props)
    });
};

module.exports = reactDocgenMarkdown;
<commit_msg>Add a fallback for components with multiple export<commit_after>var _ = require('lodash'),
    reactDocs = require('react-docgen'),
    Handlebars = require('handlebars');

/********************************************************
 * Helpers                                              *
 ********************************************************/

var sortObjectByKey = function(obj){
    return _(obj).keys().sort().reduce(function(memo, key) {
        memo[key] = obj[key];
        return memo;
    }, {});
};

/********************************************************
 * Prop type partials and handblebars helpers           *
 ********************************************************/

Handlebars.registerPartial('catchAll', '{{name}}');

// Basic prop types
Handlebars.registerPartial('func', 'Function');
Handlebars.registerPartial('array', 'Array');
Handlebars.registerPartial('object', 'Object');
Handlebars.registerPartial('string', 'String');
Handlebars.registerPartial('number', 'Number');
Handlebars.registerPartial('bool', 'Boolean');
Handlebars.registerPartial('node', 'ReactNode');
Handlebars.registerPartial('element', 'ReactElement');
Handlebars.registerPartial('any', '*');
Handlebars.registerPartial('custom', '{{raw}} (custom validator)');

// composed prop types
Handlebars.registerPartial('arrayOf', '[{{> (whichPartial value) value level=level}}, ...]');

Handlebars.registerPartial('shape', '{\n\
{{#indent level}}\
{{#each value}}\
    {{@key}}: {{> (whichPartial this) this level=(addLevel ../level)}}\n\
{{/each}}\n\
}\
{{/indent}}');

Handlebars.registerPartial('enum', '(\
{{#each value}}\
{{this.value}}{{#unless @last}}|{{/unless}}\
{{/each}}\
)');

Handlebars.registerPartial('union', '(\
{{#each value}}\
{{> (whichPartial this) this level=../level}}{{#unless @last}}|{{/unless}}\
{{/each}}\
)');

// Partial helper. Tells us which partial to use based on the "propType" name
Handlebars.registerHelper('whichPartial', function(type) {
    var partials = [
        'any', 'array', 'arrayOf', 'bool', 'custom', 'element', 'enum', 'func',
        'node', 'number', 'object', 'shape', 'string', 'union'
    ];
    return type && _.includes(partials, type.name) ? type.name : 'catchAll';
});

/********************************************************
 * General helpers                                      *
 ********************************************************/

// math helper
Handlebars.registerHelper('addLevel', function(level) { return level + 1; });

// loop helper
Handlebars.registerHelper('indent', function(indentLevel, options) {
    var content = options.fn(this),
        lines = content.split('\n'),
        indentString = '';

    // build the indent string we need for this indent level
    for (var i = 0; i < indentLevel; i++) {
        indentString += '    ';
    }

    // add then indents to each line
    lines = lines.map(function(line) { return line = indentString + line; });
    return lines.join('\n');
});

/********************************************************
 * Top-level handlebars template                        *
 ********************************************************/

var reactDocgenTemplate = Handlebars.compile('\
## {{componentName}}\n\n\
{{#if srcLink }}From [`{{srcLink}}`]({{srcLink}})\n\n\{{/if}}\
{{#if description}}{{{description}}}\n\n{{/if}}\
{{#each props}}\
#### {{@key}}\n\n\
```js\n\
{{#if this.required}}// Required\n{{/if}}\
{{#if this.defaultValue}}// Default: {{{this.defaultValue.value}}}\n{{/if}}\
{{@key}}: {{> (whichPartial this.type) this.type level=0}}\n\
```\n\n\
{{#if this.description}}{{{this.description}}}\n\n{{/if}}\
{{/each}}\

\n');

/********************************************************
 * Documentation generator using react-docgen           *
 ********************************************************/

var reactDocgenMarkdown = function (componentSrc, options) {
    try {
        const docs = reactDocs.parse(componentSrc);
        return reactDocgenTemplate({
            srcLink: options.srcLink,
            componentName: options.componentName,
            description: docs.description,
            props: sortObjectByKey(docs.props)
        });
    } catch (error) {
        // Fallback for components using multiple exports in the same file
        const docsList = reactDocs.parse(componentSrc, reactDocs.resolver.findAllExportedComponentDefinitions);
        return docsList.reduce((acc, docs) => acc + reactDocgenTemplate({
            srcLink: options.srcLink,
            componentName: options.componentName,
            description: docs.description,
            props: sortObjectByKey(docs.props)
        }) + '\n', '');
    }
};

module.exports = reactDocgenMarkdown;
<|endoftext|>


<commit_before>import {List} from 'immutable';
import map from 'lodash/map';
import {Error, ErrorList, ErrorReport} from '../records';

const passedLanguageErrors = new ErrorList();

const validatingLanguageErrors = new ErrorList({state: 'validating'});

function buildFailedLanguageErrors(errorList) {
  return new ErrorList({
    items: new List(map(errorList, error => Error.fromJS(error))),
    state: 'validation-error',
  });
}

const validatingErrors = new ErrorReport({
  html: validatingLanguageErrors,
  css: validatingLanguageErrors,
  javascript: validatingLanguageErrors,
});

const emptyErrors = new ErrorReport({
  html: passedLanguageErrors,
  css: passedLanguageErrors,
  javascript: passedLanguageErrors,
});

function errors(stateIn, action) {
  let state = stateIn;
  if (state === undefined) {
    state = emptyErrors;
  }

  switch (action.type) {
    case 'PROJECT_CREATED':
      return emptyErrors;

    case 'CHANGE_CURRENT_PROJECT':
      return validatingErrors;

    case 'GIST_IMPORTED':
      return validatingErrors;

    case 'SNAPSHOT_IMPORTED':
      return validatingErrors;

    case 'TOGGLE_LIBRARY':
      return validatingErrors;

    case 'UPDATE_PROJECT_SOURCE':
      return state.set(action.payload.language, validatingLanguageErrors);

    case 'ADD_RUNTIME_ERROR':
      return state.update(
        action.payload.language,
        list => list.update(
          'items',
          items => items.push(Error.fromJS(action.payload.error)).
            sortBy(error => error.get('row')),
        ).set('state', 'runtime-error'));

    case 'VALIDATED_SOURCE':
      if (action.payload.errors.length) {
        return state.set(
          action.payload.language,
          buildFailedLanguageErrors(action.payload.errors),
        );
      }
      return state.set(action.payload.language, passedLanguageErrors);

    default:
      return state;
  }
}

export default errors;
<commit_msg>Clear runtime errors on refresh<commit_after>import {List} from 'immutable';
import map from 'lodash/map';
import {Error, ErrorList, ErrorReport} from '../records';

const passedLanguageErrors = new ErrorList();

const validatingLanguageErrors = new ErrorList({state: 'validating'});

function buildFailedLanguageErrors(errorList) {
  return new ErrorList({
    items: new List(map(errorList, error => Error.fromJS(error))),
    state: 'validation-error',
  });
}

const validatingErrors = new ErrorReport({
  html: validatingLanguageErrors,
  css: validatingLanguageErrors,
  javascript: validatingLanguageErrors,
});

const emptyErrors = new ErrorReport({
  html: passedLanguageErrors,
  css: passedLanguageErrors,
  javascript: passedLanguageErrors,
});

function errors(stateIn, action) {
  let state = stateIn;
  if (state === undefined) {
    state = emptyErrors;
  }

  switch (action.type) {
    case 'PROJECT_CREATED':
      return emptyErrors;

    case 'CHANGE_CURRENT_PROJECT':
      return validatingErrors;

    case 'GIST_IMPORTED':
      return validatingErrors;

    case 'SNAPSHOT_IMPORTED':
      return validatingErrors;

    case 'TOGGLE_LIBRARY':
      return validatingErrors;

    case 'UPDATE_PROJECT_SOURCE':
      return state.set(action.payload.language, validatingLanguageErrors);

    case 'ADD_RUNTIME_ERROR':
      return state.update(
        action.payload.language,
        list => list.update(
          'items',
          items => items.push(Error.fromJS(action.payload.error)).
            sortBy(error => error.get('row')),
        ).set('state', 'runtime-error'));

    case 'VALIDATED_SOURCE':
      if (action.payload.errors.length) {
        return state.set(
          action.payload.language,
          buildFailedLanguageErrors(action.payload.errors),
        );
      }
      return state.set(action.payload.language, passedLanguageErrors);

    case 'REFRESH_PREVIEW':
      return state.update(
        'javascript',
        (errorList) => {
          if (errorList.state === 'runtime-error') {
            return passedLanguageErrors;
          }
          return errorList;
        },
      );

    default:
      return state;
  }
}

export default errors;
<|endoftext|>


<commit_before>import {
  GET_HEADER_SUCCESS,
  GET_HEADER_FAILURE,
} from 'Constants/actionTypes';

const initialState = {
};

const header = (state = initialState, action) => {
  switch (action.type) {
    case GET_HEADER_SUCCESS:
      return {
        ...state,
        ...action.fields,
      };
    case GET_HEADER_FAILURE:
      return {
        ...state,
        error: action.error,
      };
    default:
      return state;
  }
};

export default header;
<commit_msg>feat(src/reducers/header.js): change to use redux-actions<commit_after>import {
  GET_HEADER,
} from 'Constants/actionTypes';
import { handleAction } from 'redux-actions';

const defaultState = {
};

const header = handleAction(GET_HEADER, (state, action) => ({
  ...state,
  ...action.payload.fields,
}), defaultState);

export default header;
<|endoftext|>


<commit_before>/**
 * @class Renderer
 */

EZ3.Renderer = function(canvas, options) {
  this.context = null;
  this.extension = null;
  this.canvas = canvas;
  this.options = options;
  this.state = null;
};

EZ3.Renderer.prototype._processContextLost = function(event) {
  event.preventDefault();
};

EZ3.Renderer.prototype._renderMesh = function(mesh, camera, lights) {
  var gl = this.context;
  var program = mesh.material.program;
  var modelView = new EZ3.Matrix4();
  var i;

  program.bind(gl);
  mesh.material.updateStates(gl, this.state);
  mesh.material.updateUniforms(gl, this.state);

  modelView.mul(camera.view, mesh.world);

  program.loadUniformFloat(gl, 'uEyePosition', camera.position);
  program.loadUniformMatrix(gl, 'uModel', mesh.world);
  program.loadUniformMatrix(gl, 'uModelView', modelView);
  program.loadUniformMatrix(gl, 'uProjection', camera.projection);

  if (!lights.empty)
    program.loadUniformMatrix(gl, 'uNormal', mesh.normal);

  for (i = 0; i < lights.point.length; i++)
    lights.point[i].updateUniforms(gl, program, i);

  for (i = 0; i < lights.directional.length; i++)
    lights.directional[i].updateUniforms(gl, program, i);

  for (i = 0; i < lights.spot.length; i++)
    lights.spot[i].updateUniforms(gl, program, i);

  mesh.render(gl, program.attributes, this.state, this.extension);
};

EZ3.Renderer.prototype._renderDepth = function(lights, shadowCasters) {
  var gl = this.context;
  var position = new EZ3.Vector2();
  var modelViewProjection = new EZ3.Matrix4();
  var framebuffer;
  var program;
  var fragment;
  var vertex;
  var light;
  var mesh;
  var i;
  var j;

  if (!this.state.programs.depth) {
    vertex = EZ3.ShaderLibrary.depth.vertex;
    fragment = EZ3.ShaderLibrary.depth.fragment;
    this.state.programs.depth = new EZ3.GLSLProgram(gl, vertex, fragment);
  }

  program = this.state.programs.depth;

  program.bind(gl);

  for (i = 0; i < lights.length; i++) {
    light = lights[i];
    framebuffer = light.depthFramebuffer;

    framebuffer.bind(gl);

    if (framebuffer.dirty) {
      framebuffer.update(gl);
      framebuffer.dirty = false;
    }

    gl.clear(gl.DEPTH_BUFFER_BIT);
    this.viewport(position, framebuffer.resolution);

    for (j = 0; j < shadowCasters.length; j++) {
      mesh = shadowCasters[j];

      modelViewProjection.mul(light.projection, new EZ3.Matrix4().mul(light.view, mesh.world));
      mesh.updateShadow(modelViewProjection);

      program.loadUniformMatrix(gl, 'uModelViewProjection', modelViewProjection);

      mesh.render(gl, program.attributes, this.state, this.extension);
    }
  }
};

EZ3.Renderer.prototype.initContext = function() {
  var that = this;
  var names = [
    'webgl',
    'experimental-webgl',
    'webkit-3d',
    'moz-webgl'
  ];
  var i;

  for (i = 0; i < names.length; i++) {
    try {
      this.context = this.canvas.getContext(names[i], this.options);
    } catch (e) {}

    if (this.context) {
      this.state = new EZ3.State();
      this.extension = new EZ3.Extension(this.context);
      break;
    }
  }

  if (!this.context)
    throw new Error('Unable to initialize WebGL with selected options.');

  this._onContextLost = function(event) {
    that._processContextLost(event);
  };

  this.canvas.addEventListener('webglcontextlost', this._onContextLost, false);
};

EZ3.Renderer.prototype.clear = function() {
  var gl = this.context;

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(this.context.COLOR_BUFFER_BIT | this.context.DEPTH_BUFFER_BIT);
};

EZ3.Renderer.prototype.viewport = function(position, size) {
  var gl = this.context;

  gl.viewport(position.x, position.y, size.x, size.y);
};

EZ3.Renderer.prototype.render = function(scene, camera) {
  var gl = this.context;
  var entities = [];
  var meshes = {
    common: [],
    opaque: [],
    transparent: [],
    shadowCasters: []
  };
  var lights = {
    empty: true,
    point: [],
    directional: [],
    spot: []
  };
  var entity;
  var mesh;
  var i;

  entities.push(scene);

  while (entities.length) {
    entity = entities.pop();

    if (entity instanceof EZ3.PointLight)
      lights.point.push(entity);
    else if (entity instanceof EZ3.DirectionalLight)
      lights.directional.push(entity);
    else if (entity instanceof EZ3.SpotLight)
      lights.spot.push(entity);
    else if (entity instanceof EZ3.Mesh)
      meshes.common.push(entity);

    for (i = entity.children.length - 1; i >= 0; i--)
      entities.push(entity.children[i]);

    entity.updateWorld();
  }

  if (lights.point.length || lights.directional.length || lights.spot.length)
    lights.empty = false;

  for (i = 0; i < meshes.common.length; i++) {
    mesh = meshes.common[i];

    mesh.updateEssentialBuffers();

    if (!lights.empty) {
      mesh.updateIlluminationBuffers();
      mesh.updateNormal();
    }

    mesh.material.updateProgram(gl, this.state, lights);

    if (mesh.material.transparent)
      meshes.transparent.push(mesh);
    else
      meshes.opaque.push(mesh);

    if (mesh.material.shadowCaster)
      meshes.shadowCasters.push(mesh);
  }

  if (meshes.shadowCasters.length) {
    this._renderDepth(lights.directional, meshes.shadowCasters);
    this._renderDepth(lights.spot, meshes.shadowCasters);

    gl.viewport(0.0, 0.0, this.canvas.width, this.canvas.height);
    gl.bindFramebuffer(gl.FRAMEBUFFER, 0);
  }

  for (i = 0; i < meshes.opaque.length; i++)
    this._renderMesh(meshes.opaque[i], camera, lights);

  for (i = 0; i < meshes.transparent.length; i++)
    this._renderMesh(meshes.transparent[i], camera, lights);
};
<commit_msg>Updated Renderer.js<commit_after>/**
 * @class Renderer
 */

EZ3.Renderer = function(canvas, options) {
  this.context = null;
  this.extension = null;
  this.canvas = canvas;
  this.options = options;
  this.state = null;
};

EZ3.Renderer.prototype._processContextLost = function(event) {
  event.preventDefault();
};

EZ3.Renderer.prototype._renderMesh = function(mesh, camera, lights) {
  var gl = this.context;
  var program = mesh.material.program;
  var modelView = new EZ3.Matrix4();
  var i;

  program.bind(gl);
  mesh.material.updateStates(gl, this.state);
  mesh.material.updateUniforms(gl, this.state);

  modelView.mul(camera.view, mesh.world);

  program.loadUniformFloat(gl, 'uEyePosition', camera.position);
  program.loadUniformMatrix(gl, 'uModel', mesh.world);
  program.loadUniformMatrix(gl, 'uModelView', modelView);
  program.loadUniformMatrix(gl, 'uProjection', camera.projection);

  if (!lights.empty)
    program.loadUniformMatrix(gl, 'uNormal', mesh.normal);

  for (i = 0; i < lights.point.length; i++)
    lights.point[i].updateUniforms(gl, program,  i);

  for (i = 0; i < lights.directional.length; i++)
    lights.directional[i].updateUniforms(gl, this.state, program, i);

  for (i = 0; i < lights.spot.length; i++)
    lights.spot[i].updateUniforms(gl, this.state, program, i);

  mesh.render(gl, program.attributes, this.state, this.extension);
};

EZ3.Renderer.prototype._renderDepth = function(lights, shadowCasters) {
  var gl = this.context;
  var position = new EZ3.Vector2();
  var lightWVP = new EZ3.Matrix4();
  var framebuffer;
  var program;
  var fragment;
  var vertex;
  var light;
  var mesh;
  var i;
  var j;

  if (!this.state.programs.depth) {
    vertex = EZ3.ShaderLibrary.depth.vertex;
    fragment = EZ3.ShaderLibrary.depth.fragment;
    this.state.programs.depth = new EZ3.GLSLProgram(gl, vertex, fragment);
  }

  program = this.state.programs.depth;

  program.bind(gl);

  for (i = 0; i < lights.length; i++) {
    light = lights[i];
    framebuffer = light.depthFramebuffer;

    framebuffer.bind(gl);

    framebuffer.update(gl);

    this.viewport(position, framebuffer.resolution);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    if (!this.state.frontFaceCulling) {
      if (this.state.backFaceCulling)
        this.state.backFaceCulling = false;

      if (!this.state.faceCulling) {
        gl.enable(gl.CULL_FACE);
        this.state.faceCulling = true;
      }

      gl.cullFace(gl.FRONT);
      this.state.frontFaceCulling = true;
    }

    for (j = 0; j < shadowCasters.length; j++) {
      mesh = shadowCasters[j];

      lightWVP.mul(light.projection, new EZ3.Matrix4().mul(light.view, mesh.world));
      mesh.updateShadow(lightWVP);

      program.loadUniformMatrix(gl, 'uLightWVP', lightWVP);

      mesh.render(gl, program.attributes, this.state, this.extension);
    }
  }
};

EZ3.Renderer.prototype.initContext = function() {
  var that = this;
  var names = [
    'webgl',
    'experimental-webgl',
    'webkit-3d',
    'moz-webgl'
  ];
  var i;

  for (i = 0; i < names.length; i++) {
    try {
      this.context = this.canvas.getContext(names[i], this.options);
    } catch (e) {}

    if (this.context) {
      this.state = new EZ3.State();
      this.extension = new EZ3.Extension(this.context);
      break;
    }
  }

  if (!this.context)
    throw new Error('Unable to initialize WebGL with selected options.');

  this._onContextLost = function(event) {
    that._processContextLost(event);
  };

  this.canvas.addEventListener('webglcontextlost', this._onContextLost, false);
};

EZ3.Renderer.prototype.clear = function() {
  var gl = this.context;

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(this.context.COLOR_BUFFER_BIT | this.context.DEPTH_BUFFER_BIT);
};

EZ3.Renderer.prototype.viewport = function(position, size) {
  var gl = this.context;

  gl.viewport(position.x, position.y, size.x, size.y);
};

EZ3.Renderer.prototype.render = function(scene, camera) {
  var gl = this.context;
  var entities = [];
  var meshes = {
    common: [],
    opaque: [],
    transparent: [],
    shadowCasters: []
  };
  var lights = {
    empty: true,
    point: [],
    directional: [],
    spot: []
  };
  var entity;
  var mesh;
  var i;

  entities.push(scene);

  while (entities.length) {
    entity = entities.pop();

    if (entity instanceof EZ3.PointLight)
      lights.point.push(entity);
    else if (entity instanceof EZ3.DirectionalLight)
      lights.directional.push(entity);
    else if (entity instanceof EZ3.SpotLight)
      lights.spot.push(entity);
    else if (entity instanceof EZ3.Mesh)
      meshes.common.push(entity);

    for (i = entity.children.length - 1; i >= 0; i--)
      entities.push(entity.children[i]);

    entity.updateWorld();
  }

  if (lights.point.length || lights.directional.length || lights.spot.length)
    lights.empty = false;

  for (i = 0; i < meshes.common.length; i++) {
    mesh = meshes.common[i];

    mesh.updateEssentialBuffers();

    if (!lights.empty) {
      mesh.updateIlluminationBuffers();
      mesh.updateNormal();
    }

    mesh.material.updateProgram(gl, this.state, lights);

    if (mesh.material.transparent)
      meshes.transparent.push(mesh);
    else
      meshes.opaque.push(mesh);

    if (mesh.material.shadowCaster)
      meshes.shadowCasters.push(mesh);
  }

  if (meshes.shadowCasters.length) {
    this._renderDepth(lights.directional, meshes.shadowCasters);
    this._renderDepth(lights.spot, meshes.shadowCasters);

    gl.viewport(0.0, 0.0, this.canvas.width, this.canvas.height);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  }

  for (i = 0; i < meshes.opaque.length; i++)
    this._renderMesh(meshes.opaque[i], camera, lights);

  for (i = 0; i < meshes.transparent.length; i++)
    this._renderMesh(meshes.transparent[i], camera, lights);
};
<|endoftext|>


<commit_before>/* jshint node:true */

import { readFile } from 'fs';
import { L10nError } from '../../lib/errors';

function load(url) {
  return new Promise((resolve, reject) => {
    readFile(url, (err, data) => {
      if (err) {
        reject(new L10nError(err.message));
      } else {
        resolve(data.toString());
      }
    });
  });
}

export function fetchResource(res, { code }) {
  const url = res.replace('{locale}', code);
  return load(url).catch(e => e);
}
<commit_msg>Fix node.js io to return null in case of fs errors<commit_after>/* jshint node:true */

import { readFile } from 'fs';

function load(url) {
  return new Promise((resolve, reject) => {
    readFile(url, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data.toString());
      }
    });
  });
}

export function fetchResource(res, { code }) {
  const url = res.replace('{locale}', code);
  return load(url).catch(() => null);
}
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../../FormBuilderPropTypes'
import RenderField from './RenderField'
import ObjectContainer from '../../state/ObjectContainer'
import Fieldset from '../../Fieldset'
import equals from 'shallow-equals'

export default class Obj extends React.Component {
  static displayName = 'Object'

  static valueContainer = ObjectContainer;

  static propTypes = {
    type: FormBuilderPropTypes.type,
    field: FormBuilderPropTypes.field,
    value: PropTypes.object,
    onChange: PropTypes.func
  };

  static defaultProps = {
    onChange() {}
  };

  static contextTypes = {
    resolveInputComponent: PropTypes.func,
    schema: PropTypes.object
  };

  constructor(props, context) {
    super(props, context)
    this.handleFieldChange = this.handleFieldChange.bind(this)
    this.renderField = this.renderField.bind(this)
  }

  handleFieldChange(event, fieldName) {
    const {onChange} = this.props
    const patch = {[fieldName]: event.patch}
    onChange({patch})
  }

  shouldComponentUpdate(nextProps) {
    console.log('Object update?', !equals(this.props, nextProps))
    return !equals(this.props, nextProps)
  }

  renderField(field) {
    const {value} = this.props
    const fieldValue = value && value.getFieldValue(field.name)
    return (
      <RenderField
        key={field.name}
        fieldName={field.name}
        field={field}
        value={fieldValue}
        onChange={this.handleFieldChange}
      />
    )

  }

  renderFieldset(fieldset) {
    return (
      <Fieldset legend={fieldset.title}>
        {fieldset.fields.map(this.renderField)}
      </Fieldset>
    )
  }

  renderFieldsets(fieldsets) {
    return fieldsets.map(fieldset => {
      return fieldset.lonely ? this.renderField(fieldset.field) : this.renderFieldset(fieldset)
    })
  }

  render() {
    const {type, field} = this.props
    return (

        {this.renderFieldsets(type.fieldsets)}

    )
  }
}
<commit_msg>Remove console.log<commit_after>import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../../FormBuilderPropTypes'
import RenderField from './RenderField'
import ObjectContainer from '../../state/ObjectContainer'
import Fieldset from '../../Fieldset'
import equals from 'shallow-equals'

export default class Obj extends React.Component {
  static displayName = 'Object'

  static valueContainer = ObjectContainer;

  static propTypes = {
    type: FormBuilderPropTypes.type,
    field: FormBuilderPropTypes.field,
    value: PropTypes.object,
    onChange: PropTypes.func
  };

  static defaultProps = {
    onChange() {}
  };

  static contextTypes = {
    resolveInputComponent: PropTypes.func,
    schema: PropTypes.object
  };

  constructor(props, context) {
    super(props, context)
    this.handleFieldChange = this.handleFieldChange.bind(this)
    this.renderField = this.renderField.bind(this)
  }

  handleFieldChange(event, fieldName) {
    const {onChange} = this.props
    const patch = {[fieldName]: event.patch}
    onChange({patch})
  }

  shouldComponentUpdate(nextProps) {
    return !equals(this.props, nextProps)
  }

  renderField(field) {
    const {value} = this.props
    const fieldValue = value && value.getFieldValue(field.name)
    return (
      <RenderField
        key={field.name}
        fieldName={field.name}
        field={field}
        value={fieldValue}
        onChange={this.handleFieldChange}
      />
    )

  }

  renderFieldset(fieldset) {
    return (
      <Fieldset legend={fieldset.title}>
        {fieldset.fields.map(this.renderField)}
      </Fieldset>
    )
  }

  renderFieldsets(fieldsets) {
    return fieldsets.map(fieldset => {
      return fieldset.lonely ? this.renderField(fieldset.field) : this.renderFieldset(fieldset)
    })
  }

  render() {
    const {type, field} = this.props
    return (

        {this.renderFieldsets(type.fieldsets)}

    )
  }
}
<|endoftext|>


<commit_before>const INVENTORY = 'inventory';
import events from '../events';
import consts from '../constants';
import requests from '../requests';
import auth from '../auth';
import items from '../items';
import voxel from '../voxel';

export default {
  allBlockTypes: [],
  allItemTypes: [],
  toolbarItems: [],
  isOpen: false,
  async editCode(item, type, toolbar) {
    type = type || (confirm('Want to create a new item or block? Yes = item, no = block') ? 'item' : 'block');

    // Technically this is not necessary, but it speeds up the loading :)
    if(item.id) {
      let loadOperation = type == 'block' ? voxel.load : items.load;
      await loadOperation(item.id);
    }

    this.isOpen = false;
    events.emit(consts.events.EDIT_CODE, {
      type,
      id: item && item.id,
      toolbar
    });
  },
  open() {
    this.isOpen = true;
    events.emit(consts.events.FULLSCREEN_WINDOW_OPEN, {name: INVENTORY});
  },
  close() {
    this.isOpen = false;
    events.emit(consts.events.FULLSCREEN_WINDOW_CLOSE, {name: INVENTORY});
  },
  async bringAllItems() {
    var self = this;

    this.toolbarItems.splice(0, this.toolbarItems.length);
    items.getToolbarItems().forEach(item => {
      self.toolbarItems.push(item);
    });

    let res = await requests.requestToServer('inventory/all', {
      method: 'GET',
      headers: auth.getAuthHeaders()
    });

    self.allBlockTypes.splice(0, self.allBlockTypes.length);
    res.blockTypes.forEach(type => {
      self.allBlockTypes.push(type);
    });

    self.allItemTypes.splice(0, self.allItemTypes.length);
    res.itemTypes.forEach(type => {
      self.allItemTypes.push(type);
    });
  },
  addToToolbar(type, id) {
    var position = parseInt(prompt('Enter position (2-9)'));
    if(Number.isNaN(position) || position > 9 || position < 2) {
      console.log('Invalid position');
      return;
    }
    position--;

    if(items.hasTestingCode(position - 1)) {
      console.log(`Item at #${position + 1} has testing code - it cannot be moved from the toolbar`);
      return;
    }

    items.setToolbarItem(position - 1, {type, id}).then(() => {
      this.toolbarItems.$set(position, items.getToolbarItems()[position]);
    });
  },
  removeFromToolbar(position) {
    if(position == 0) {
      console.log('Cannot remove interact from first position');
      return;
    }

    if(items.hasTestingCode(position - 1)) {
      console.log(`Item at #${position + 1} has testing code - it cannot be moved from the toolbar`);
      return;
    }

    items.removeToolbarItem(position - 1).then(() => {
      this.toolbarItems.$set(position, items.getToolbarItems()[position]);
    });
  },
  async addBlockType(name, material, code) {
    return await requests.requestToServer('inventory/blockType', {
      method: 'POST',
      body: JSON.stringify({
        code,
        name,
        material
      }),
      headers: auth.getAuthHeaders()
    });
  },
  async updateBlockCode(blockTypeId, code) {
    return await requests.requestToServer(`inventory/blockType/${blockTypeId}`, {
      method: 'PATCH',
      body: JSON.stringify({
        code
      }),
      headers: auth.getAuthHeaders()
    });
  },
  async updateItemCode(itemTypeId, code) {
    return await requests.requestToServer(`inventory/itemType/${itemTypeId}`, {
      method: 'PATCH',
      body: JSON.stringify({
        code
      }),
      headers: auth.getAuthHeaders()
    });
  },
  async addItemType(props, code) {
    return await requests.requestToServer('inventory/itemType', {
      method: 'POST',
      body: JSON.stringify({
        code,
        name: props.name,
        adjacentActive: props.adjacentActive,
        crosshairIcon: props.crosshairIcon
      }),
      headers: auth.getAuthHeaders()
    });
  }
};
<commit_msg>using async await in inventory<commit_after>const INVENTORY = 'inventory';
import events from '../events';
import consts from '../constants';
import requests from '../requests';
import auth from '../auth';
import items from '../items';
import voxel from '../voxel';

export default {
  allBlockTypes: [],
  allItemTypes: [],
  toolbarItems: [],
  isOpen: false,
  async editCode(item, type, toolbar) {
    type = type || (confirm('Want to create a new item or block? Yes = item, no = block') ? 'item' : 'block');

    // Technically this is not necessary, but it speeds up the loading :)
    if(item.id) {
      let loadOperation = type == 'block' ? voxel.load : items.load;
      await loadOperation(item.id);
    }

    this.isOpen = false;
    events.emit(consts.events.EDIT_CODE, {
      type,
      id: item && item.id,
      toolbar
    });
  },
  open() {
    this.isOpen = true;
    events.emit(consts.events.FULLSCREEN_WINDOW_OPEN, {name: INVENTORY});
  },
  close() {
    this.isOpen = false;
    events.emit(consts.events.FULLSCREEN_WINDOW_CLOSE, {name: INVENTORY});
  },
  async bringAllItems() {
    var self = this;

    this.toolbarItems.splice(0, this.toolbarItems.length);
    items.getToolbarItems().forEach(item => {
      self.toolbarItems.push(item);
    });

    let res = await requests.requestToServer('inventory/all', {
      method: 'GET',
      headers: auth.getAuthHeaders()
    });

    self.allBlockTypes.splice(0, self.allBlockTypes.length);
    res.blockTypes.forEach(type => {
      self.allBlockTypes.push(type);
    });

    self.allItemTypes.splice(0, self.allItemTypes.length);
    res.itemTypes.forEach(type => {
      self.allItemTypes.push(type);
    });
  },
  async addToToolbar(type, id) {
    var position = parseInt(prompt('Enter position (2-9)'));
    if(Number.isNaN(position) || position > 9 || position < 2) {
      console.log('Invalid position');
      return;
    }
    position--;

    if(items.hasTestingCode(position - 1)) {
      console.log(`Item at #${position + 1} has testing code - it cannot be moved from the toolbar`);
      return;
    }

    await items.setToolbarItem(position - 1, {type, id});
    this.toolbarItems.$set(position, items.getToolbarItems()[position]);
  },
  async removeFromToolbar(position) {
    if(position == 0) {
      console.log('Cannot remove interact from first position');
      return;
    }

    if(items.hasTestingCode(position - 1)) {
      console.log(`Item at #${position + 1} has testing code - it cannot be moved from the toolbar`);
      return;
    }

    await items.removeToolbarItem(position - 1);
    this.toolbarItems.$set(position, items.getToolbarItems()[position]);
  },
  async addBlockType(name, material, code) {
    return await requests.requestToServer('inventory/blockType', {
      method: 'POST',
      body: JSON.stringify({
        code,
        name,
        material
      }),
      headers: auth.getAuthHeaders()
    });
  },
  async updateBlockCode(blockTypeId, code) {
    return await requests.requestToServer(`inventory/blockType/${blockTypeId}`, {
      method: 'PATCH',
      body: JSON.stringify({
        code
      }),
      headers: auth.getAuthHeaders()
    });
  },
  async updateItemCode(itemTypeId, code) {
    return await requests.requestToServer(`inventory/itemType/${itemTypeId}`, {
      method: 'PATCH',
      body: JSON.stringify({
        code
      }),
      headers: auth.getAuthHeaders()
    });
  },
  async addItemType(props, code) {
    return await requests.requestToServer('inventory/itemType', {
      method: 'POST',
      body: JSON.stringify({
        code,
        name: props.name,
        adjacentActive: props.adjacentActive,
        crosshairIcon: props.crosshairIcon
      }),
      headers: auth.getAuthHeaders()
    });
  }
};
<|endoftext|>


<commit_before>(function($) {
  var version = '1.6.1';
  var optionOverrides = {};
  var defaults = {
    exclude: [],
    excludeWithin: [],
    offset: 0,

    // one of 'top' or 'left'
    direction: 'top',

    // if set, bind click events through delegation
    //  supported since jQuery 1.4.2
    delegateSelector: null,

    // jQuery set of elements you wish to scroll (for $.smoothScroll).
    //  if null (default), $('html, body').firstScrollable() is used.
    scrollElement: null,

    // only use if you want to override default behavior
    scrollTarget: null,

    // fn(opts) function to be called before scrolling occurs.
    // `this` is the element(s) being scrolled
    beforeScroll: function() {},

    // fn(opts) function to be called after scrolling occurs.
    // `this` is the triggering element
    afterScroll: function() {},
    easing: 'swing',
    speed: 400,

    // coefficient for "auto" speed
    autoCoefficient: 2,

    // $.fn.smoothScroll only: whether to prevent the default click action
    preventDefault: true
  };

  var getScrollable = function(opts) {
    var scrollable = [];
    var scrolled = false;
    var dir = opts.dir && opts.dir === 'left' ? 'scrollLeft' : 'scrollTop';

    this.each(function() {
      var el = $(this);

      if (this === document || this === window) {
        return;
      }

      if (document.scrollingElement && (this === document.documentElement || this === document.body)) {
        scrollable.push(document.scrollingElement);

        return false;
      }

      if (el[dir]() > 0) {
        scrollable.push(this);
      } else {
        // if scroll(Top|Left) === 0, nudge the element 1px and see if it moves
        el[dir](1);
        scrolled = el[dir]() > 0;

        if (scrolled) {
          scrollable.push(this);
        }
        // then put it back, of course
        el[dir](0);
      }
    });

    // If no scrollable elements, fall back to <body>,
    // if it's in the jQuery collection
    // (doing this because Safari sets scrollTop async,
    // so can't set it to 1 and immediately get the value.)
    if (!scrollable.length) {
      this.each(function() {
        if (this.nodeName === 'BODY') {
          scrollable = [this];
        }
      });
    }

    // Use the first scrollable element if we're calling firstScrollable()
    if (opts.el === 'first' && scrollable.length > 1) {
      scrollable = [scrollable[0]];
    }

    return scrollable;
  };

  $.fn.extend({
    scrollable: function(dir) {
      var scrl = getScrollable.call(this, {dir: dir});

      return this.pushStack(scrl);
    },
    firstScrollable: function(dir) {
      var scrl = getScrollable.call(this, {el: 'first', dir: dir});

      return this.pushStack(scrl);
    },

    smoothScroll: function(options, extra) {
      options = options || {};

      if (options === 'options') {
        if (!extra) {
          return this.first().data('ssOpts');
        }

        return this.each(function() {
          var $this = $(this);
          var opts = $.extend($this.data('ssOpts') || {}, extra);

          $(this).data('ssOpts', opts);
        });
      }

      var opts = $.extend({}, $.fn.smoothScroll.defaults, options);

      var clickHandler = function(event) {
        var escapeSelector = function(str) {
          return str.replace(/(:|\.|\/)/g, '\\$1');
        };

        var link = this;
        var $link = $(this);
        var thisOpts = $.extend({}, opts, $link.data('ssOpts') || {});
        var exclude = opts.exclude;
        var excludeWithin = thisOpts.excludeWithin;
        var elCounter = 0;
        var ewlCounter = 0;
        var include = true;
        var clickOpts = {};
        var locationPath = $.smoothScroll.filterPath(location.pathname);
        var linkPath = $.smoothScroll.filterPath(link.pathname);
        var hostMatch = location.hostname === link.hostname || !link.hostname;
        var pathMatch = thisOpts.scrollTarget || (linkPath === locationPath);
        var thisHash = escapeSelector(link.hash);

        if (!thisOpts.scrollTarget && (!hostMatch || !pathMatch || !thisHash)) {
          include = false;
        } else {
          while (include && elCounter < exclude.length) {
            if ($link.is(escapeSelector(exclude[elCounter++]))) {
              include = false;
            }
          }

          while (include && ewlCounter < excludeWithin.length) {
            if ($link.closest(excludeWithin[ewlCounter++]).length) {
              include = false;
            }
          }
        }

        if (include) {
          if (thisOpts.preventDefault) {
            event.preventDefault();
          }

          $.extend(clickOpts, thisOpts, {
            scrollTarget: thisOpts.scrollTarget || thisHash,
            link: link
          });

          $.smoothScroll(clickOpts);
        }
      };

      if (options.delegateSelector !== null) {
        this
        .undelegate(options.delegateSelector, 'click.smoothscroll')
        .delegate(options.delegateSelector, 'click.smoothscroll', clickHandler);
      } else {
        this
        .unbind('click.smoothscroll')
        .bind('click.smoothscroll', clickHandler);
      }

      return this;
    }
  });

  $.smoothScroll = function(options, px) {
    if (options === 'options' && typeof px === 'object') {
      return $.extend(optionOverrides, px);
    }
    var opts, $scroller, scrollTargetOffset, speed, delta;
    var scrollerOffset = 0;
    var offPos = 'offset';
    var scrollDir = 'scrollTop';
    var aniProps = {};
    var aniOpts = {};

    if (typeof options === 'number') {
      opts = $.extend({link: null}, $.fn.smoothScroll.defaults, optionOverrides);
      scrollTargetOffset = options;
    } else {
      opts = $.extend({link: null}, $.fn.smoothScroll.defaults, options || {}, optionOverrides);

      if (opts.scrollElement) {
        offPos = 'position';

        if (opts.scrollElement.css('position') === 'static') {
          opts.scrollElement.css('position', 'relative');
        }
      }
    }

    scrollDir = opts.direction === 'left' ? 'scrollLeft' : scrollDir;

    if (opts.scrollElement) {
      $scroller = opts.scrollElement;

      if (!(/^(?:HTML|BODY)$/).test($scroller[0].nodeName)) {
        scrollerOffset = $scroller[scrollDir]();
      }
    } else {
      $scroller = $('html, body').firstScrollable(opts.direction);
    }

    // beforeScroll callback function must fire before calculating offset
    opts.beforeScroll.call($scroller, opts);

    scrollTargetOffset = (typeof options === 'number') ? options :
                          px ||
                          ($(opts.scrollTarget)[offPos]() &&
                          $(opts.scrollTarget)[offPos]()[opts.direction]) ||
                          0;

    aniProps[scrollDir] = scrollTargetOffset + scrollerOffset + opts.offset;
    speed = opts.speed;

    // automatically calculate the speed of the scroll based on distance / coefficient
    if (speed === 'auto') {

      // $scroller[scrollDir]() is position before scroll, aniProps[scrollDir] is position after
      // When delta is greater, speed will be greater.
      delta = Math.abs(aniProps[scrollDir] - $scroller[scrollDir]());

      // Divide the delta by the coefficient
      speed = delta / opts.autoCoefficient;
    }

    aniOpts = {
      duration: speed,
      easing: opts.easing,
      complete: function() {
        opts.afterScroll.call(opts.link, opts);
      }
    };

    if (opts.step) {
      aniOpts.step = opts.step;
    }

    if ($scroller.length) {
      $scroller.stop().animate(aniProps, aniOpts);
    } else {
      opts.afterScroll.call(opts.link, opts);
    }
  };

  $.smoothScroll.version = version;
  $.smoothScroll.filterPath = function(string) {
    string = string || '';

    return string
      .replace(/^\//, '')
      .replace(/(?:index|default).[a-zA-Z]{3,4}$/, '')
      .replace(/\/$/, '');
  };

  // default options
  $.fn.smoothScroll.defaults = defaults;

})(jQuery);
<commit_msg>Make plugin work in Firefox when CSS has `html {scroll-behavior: smooth;}`<commit_after>(function($) {
  var version = '1.6.1';
  var optionOverrides = {};
  var defaults = {
    exclude: [],
    excludeWithin: [],
    offset: 0,

    // one of 'top' or 'left'
    direction: 'top',

    // if set, bind click events through delegation
    //  supported since jQuery 1.4.2
    delegateSelector: null,

    // jQuery set of elements you wish to scroll (for $.smoothScroll).
    //  if null (default), $('html, body').firstScrollable() is used.
    scrollElement: null,

    // only use if you want to override default behavior
    scrollTarget: null,

    // fn(opts) function to be called before scrolling occurs.
    // `this` is the element(s) being scrolled
    beforeScroll: function() {},

    // fn(opts) function to be called after scrolling occurs.
    // `this` is the triggering element
    afterScroll: function() {},
    easing: 'swing',
    speed: 400,

    // coefficient for "auto" speed
    autoCoefficient: 2,

    // $.fn.smoothScroll only: whether to prevent the default click action
    preventDefault: true
  };

  var getScrollable = function(opts) {
    var scrollable = [];
    var scrolled = false;
    var dir = opts.dir && opts.dir === 'left' ? 'scrollLeft' : 'scrollTop';

    this.each(function() {
      var el = $(this);

      if (this === document || this === window) {
        return;
      }

      if (document.scrollingElement && (this === document.documentElement || this === document.body)) {
        scrollable.push(document.scrollingElement);

        return false;
      }

      if (el[dir]() > 0) {
        scrollable.push(this);
      } else {
        // if scroll(Top|Left) === 0, nudge the element 1px and see if it moves
        el[dir](1);
        scrolled = el[dir]() > 0;

        if (scrolled) {
          scrollable.push(this);
        }
        // then put it back, of course
        el[dir](0);
      }
    });

    if (!scrollable.length) {
      this.each(function() {
        // If no scrollable elements and <html> has scroll-behavior:smooth because
        // "When this property is specified on the root element, it applies to the viewport instead."
        // and "The scroll-behavior property of the … body element is *not* propagated to the viewport."
        // → https://drafts.csswg.org/cssom-view/#propdef-scroll-behavior
        if (this === document.documentElement && $(this).css('scrollBehavior') === 'smooth') {
          scrollable = [this];
        }

        // If still no scrollable elements, fall back to <body>,
        // if it's in the jQuery collection
        // (doing this because Safari sets scrollTop async,
        // so can't set it to 1 and immediately get the value.)
        if (!scrollable.length && this.nodeName === 'BODY') {
          scrollable = [this];
        }
      });
    }

    // Use the first scrollable element if we're calling firstScrollable()
    if (opts.el === 'first' && scrollable.length > 1) {
      scrollable = [scrollable[0]];
    }

    return scrollable;
  };

  $.fn.extend({
    scrollable: function(dir) {
      var scrl = getScrollable.call(this, {dir: dir});

      return this.pushStack(scrl);
    },
    firstScrollable: function(dir) {
      var scrl = getScrollable.call(this, {el: 'first', dir: dir});

      return this.pushStack(scrl);
    },

    smoothScroll: function(options, extra) {
      options = options || {};

      if (options === 'options') {
        if (!extra) {
          return this.first().data('ssOpts');
        }

        return this.each(function() {
          var $this = $(this);
          var opts = $.extend($this.data('ssOpts') || {}, extra);

          $(this).data('ssOpts', opts);
        });
      }

      var opts = $.extend({}, $.fn.smoothScroll.defaults, options);

      var clickHandler = function(event) {
        var escapeSelector = function(str) {
          return str.replace(/(:|\.|\/)/g, '\\$1');
        };

        var link = this;
        var $link = $(this);
        var thisOpts = $.extend({}, opts, $link.data('ssOpts') || {});
        var exclude = opts.exclude;
        var excludeWithin = thisOpts.excludeWithin;
        var elCounter = 0;
        var ewlCounter = 0;
        var include = true;
        var clickOpts = {};
        var locationPath = $.smoothScroll.filterPath(location.pathname);
        var linkPath = $.smoothScroll.filterPath(link.pathname);
        var hostMatch = location.hostname === link.hostname || !link.hostname;
        var pathMatch = thisOpts.scrollTarget || (linkPath === locationPath);
        var thisHash = escapeSelector(link.hash);

        if (!thisOpts.scrollTarget && (!hostMatch || !pathMatch || !thisHash)) {
          include = false;
        } else {
          while (include && elCounter < exclude.length) {
            if ($link.is(escapeSelector(exclude[elCounter++]))) {
              include = false;
            }
          }

          while (include && ewlCounter < excludeWithin.length) {
            if ($link.closest(excludeWithin[ewlCounter++]).length) {
              include = false;
            }
          }
        }

        if (include) {
          if (thisOpts.preventDefault) {
            event.preventDefault();
          }

          $.extend(clickOpts, thisOpts, {
            scrollTarget: thisOpts.scrollTarget || thisHash,
            link: link
          });

          $.smoothScroll(clickOpts);
        }
      };

      if (options.delegateSelector !== null) {
        this
        .undelegate(options.delegateSelector, 'click.smoothscroll')
        .delegate(options.delegateSelector, 'click.smoothscroll', clickHandler);
      } else {
        this
        .unbind('click.smoothscroll')
        .bind('click.smoothscroll', clickHandler);
      }

      return this;
    }
  });

  $.smoothScroll = function(options, px) {
    if (options === 'options' && typeof px === 'object') {
      return $.extend(optionOverrides, px);
    }
    var opts, $scroller, scrollTargetOffset, speed, delta;
    var scrollerOffset = 0;
    var offPos = 'offset';
    var scrollDir = 'scrollTop';
    var aniProps = {};
    var aniOpts = {};

    if (typeof options === 'number') {
      opts = $.extend({link: null}, $.fn.smoothScroll.defaults, optionOverrides);
      scrollTargetOffset = options;
    } else {
      opts = $.extend({link: null}, $.fn.smoothScroll.defaults, options || {}, optionOverrides);

      if (opts.scrollElement) {
        offPos = 'position';

        if (opts.scrollElement.css('position') === 'static') {
          opts.scrollElement.css('position', 'relative');
        }
      }
    }

    scrollDir = opts.direction === 'left' ? 'scrollLeft' : scrollDir;

    if (opts.scrollElement) {
      $scroller = opts.scrollElement;

      if (!(/^(?:HTML|BODY)$/).test($scroller[0].nodeName)) {
        scrollerOffset = $scroller[scrollDir]();
      }
    } else {
      $scroller = $('html, body').firstScrollable(opts.direction);
    }

    // beforeScroll callback function must fire before calculating offset
    opts.beforeScroll.call($scroller, opts);

    scrollTargetOffset = (typeof options === 'number') ? options :
                          px ||
                          ($(opts.scrollTarget)[offPos]() &&
                          $(opts.scrollTarget)[offPos]()[opts.direction]) ||
                          0;

    aniProps[scrollDir] = scrollTargetOffset + scrollerOffset + opts.offset;
    speed = opts.speed;

    // automatically calculate the speed of the scroll based on distance / coefficient
    if (speed === 'auto') {

      // $scroller[scrollDir]() is position before scroll, aniProps[scrollDir] is position after
      // When delta is greater, speed will be greater.
      delta = Math.abs(aniProps[scrollDir] - $scroller[scrollDir]());

      // Divide the delta by the coefficient
      speed = delta / opts.autoCoefficient;
    }

    aniOpts = {
      duration: speed,
      easing: opts.easing,
      complete: function() {
        opts.afterScroll.call(opts.link, opts);
      }
    };

    if (opts.step) {
      aniOpts.step = opts.step;
    }

    if ($scroller.length) {
      $scroller.stop().animate(aniProps, aniOpts);
    } else {
      opts.afterScroll.call(opts.link, opts);
    }
  };

  $.smoothScroll.version = version;
  $.smoothScroll.filterPath = function(string) {
    string = string || '';

    return string
      .replace(/^\//, '')
      .replace(/(?:index|default).[a-zA-Z]{3,4}$/, '')
      .replace(/\/$/, '');
  };

  // default options
  $.fn.smoothScroll.defaults = defaults;

})(jQuery);
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { PropTypes } from 'react';
import classnames from 'classnames';
import Box from './Box';
import SkipLinkAnchor from './SkipLinkAnchor';
import Props from '../utils/Props';

const CLASS_ROOT = 'footer';

const Footer = props => {
  if (!props.size) {
    // Restore size value from deprecated props
    if (props.small) {
      props.size = 'small';
    } else if (props.large) {
      props.size = 'large';
    }
  }

  let classes = classnames(
    CLASS_ROOT,
    props.className,
    {
      [`${CLASS_ROOT}--${props.size}`]: props.size,
      [`${CLASS_ROOT}--float`]: props.float
    }
  );

  let containerClasses = classnames(
    `${CLASS_ROOT}__container`,
    {
      [`${CLASS_ROOT}__container--float`]: props.float
    }
  );

  let footerSkipLink;
  if (props.primary) {
    footerSkipLink = <SkipLinkAnchor label="Footer" />;
  }

  let boxProps = Props.pick(props, Box);

  return (
    <Box {...boxProps} tag="footer" className={classes}
      containerClassName={containerClasses}>
      {footerSkipLink}
      {props.children}
    </Box>
  );
};

Footer.propTypes = {
  float: PropTypes.bool,
  large: PropTypes.bool, // Deprecated
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  primary: PropTypes.bool,
  small: PropTypes.bool, // Deprecated
  ...Box.propTypes
};

Footer.defaultProps = {
  direction: 'row',
  responsive: false
};

Footer.displayName = 'Footer';

export default Footer;
<commit_msg>Removed deprecated small= and large= properties from Footer.<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { PropTypes } from 'react';
import classnames from 'classnames';
import Box from './Box';
import SkipLinkAnchor from './SkipLinkAnchor';
import Props from '../utils/Props';

const CLASS_ROOT = 'footer';

const Footer = props => {

  let classes = classnames(
    CLASS_ROOT,
    props.className,
    {
      [`${CLASS_ROOT}--${props.size}`]: props.size,
      [`${CLASS_ROOT}--float`]: props.float
    }
  );

  let containerClasses = classnames(
    `${CLASS_ROOT}__container`,
    {
      [`${CLASS_ROOT}__container--float`]: props.float
    }
  );

  let footerSkipLink;
  if (props.primary) {
    footerSkipLink = <SkipLinkAnchor label="Footer" />;
  }

  let boxProps = Props.pick(props, Box);

  return (
    <Box {...boxProps} tag="footer" className={classes}
      containerClassName={containerClasses}>
      {footerSkipLink}
      {props.children}
    </Box>
  );
};

Footer.propTypes = {
  float: PropTypes.bool,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  primary: PropTypes.bool,
  ...Box.propTypes
};

Footer.defaultProps = {
  direction: 'row',
  responsive: false
};

Footer.displayName = 'Footer';

export default Footer;
<|endoftext|>


<commit_before>import { addClass, addId, div, i, img, nav, span } from '../builders';

export default function navbar() {
  const logo = addClass(img('static/fancybear_white.png'), 'logo');
  const navLeft = addClass(div(logo), 'navbar-left');

  const cartIcon = addId(addClass(i(), 'fa', 'fa-shopping-cart'), 'cart-icon');
  const cartItems = addClass(span(), 'cart-items');
  const navbarItem = addClass(div(cartIcon, cartItems), 'navbar-item');
  const navRight = addClass(div(navbarItem), 'navbar-right', 'cart');

  return addClass(nav(navLeft, navRight), 'navbar');
}
<commit_msg>Removed random logo from navbar<commit_after>import { addClass, addId, div, i, nav, span } from '../builders';

export default function navbar() {
  const navLeft = addClass(div(), 'navbar-left');

  const cartIcon = addId(addClass(i(), 'fa', 'fa-shopping-cart'), 'cart-icon');
  const cartItems = addClass(span(), 'cart-items');
  const navbarItem = addClass(div(cartIcon, cartItems), 'navbar-item');
  const navRight = addClass(div(navbarItem), 'navbar-right', 'cart');

  return addClass(nav(navLeft, navRight), 'navbar');
}
<|endoftext|>


<commit_before>var window = require('window');
var $ = require('jquery');

// os: windows, linux, mac, iphone, ipad, android, windowsphone
// pc/mobile: pc, mobile
// browser: chrome, firefox, safari, ie8-11, edge

// http://www.useragentstring.com/pages/useragentstring.php
module.export = function detect() {
    var ua = window.navigator.userAgent.toLowerCase();

    var env = {};

    // os
    if (ua.indexOf('windows nt') !== -1) {
        env.windows = true;
    } else if (ua.indexOf('mac os x') !== -1) {
        env.mac = true;
    } else if (ua.indexOf('linux') !== -1 && ua.indexOf('x11;') !== -1) {
        env.linux = true;
    } else if (ua.indexOf('iphone') !== -1) {
        env.iphone = true;
    } else if (ua.indexOf('ipad') !== -1) {
        env.ipad = true;
    } else if (ua.indexOf('android') !== -1) {
        env.android = true;
    } else if (ua.indexOf('windows phone') !== -1) {
        env.windowsphone = true;
    }

    // pc or mobile
    env.pc = env.windows || env.mac || env.linux;
    env.mobile = env.iphone || env.ipad || env.android || env.windowsphone;

    // browser
    if (ua.indexOf('chrome') !== -1 && ua.indexOf('edge') === -1) {
        env.chrome = true;
    } else if (ua.indexOf('firefox') !== -1) {
        env.firefox = true;
    } else if (ua.indexOf('msie') !== -1) {
        env.msie = true;
    } else if (ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1) {
        env.safari = true;
    } else if (ua.indexOf('edge') !== -1) {
        env.msie = true;
    }

    // msie version
    if (env.msie) {
        if (ua.indexOf('msie 7.0') !== -1) {
            env.msie7 = true;
        } else if (ua.indexOf('msie 8.0') !== -1) {
            env.msie8 = true;
        } else if (ua.indexOf('msie 9.0') !== -1) {
            env.msie9 = true;
        } else if (ua.indexOf('msie 10.0') !== -1) {
            env.msie10 = true;
        } else if (ua.indexOf('msie 11.0') !== -1) {
            env.msie11 = true;
        }
    }

    // add css class
    var classList = Object.keys(env).join(' ');
    $('html').addClass(classList);

    // exports
    return env;
};
<commit_msg>Update detectBrowser.js<commit_after>var window = require('window');
var $ = require('jquery');

// os: windows, linux, mac, iphone, ipad, android, windowsphone
// pc/mobile: pc, mobile
// browser: chrome, firefox, safari, msie8-11, msedge

// http://www.useragentstring.com/pages/useragentstring.php
module.export = function detect() {
    var ua = window.navigator.userAgent.toLowerCase();

    var env = {};

    // os
    if (ua.indexOf('windows nt') !== -1) {
        env.windows = true;
    } else if (ua.indexOf('mac os x') !== -1) {
        env.mac = true;
    } else if (ua.indexOf('linux') !== -1 && ua.indexOf('x11;') !== -1) {
        env.linux = true;
    } else if (ua.indexOf('iphone') !== -1) {
        env.iphone = true;
    } else if (ua.indexOf('ipad') !== -1) {
        env.ipad = true;
    } else if (ua.indexOf('android') !== -1) {
        env.android = true;
    } else if (ua.indexOf('windows phone') !== -1) {
        env.windowsphone = true;
    }

    // pc or mobile
    env.pc = env.windows || env.mac || env.linux;
    env.mobile = env.iphone || env.ipad || env.android || env.windowsphone;

    // browser
    if (ua.indexOf('chrome') !== -1 && ua.indexOf('edge') === -1) {
        env.chrome = true;
    } else if (ua.indexOf('firefox') !== -1) {
        env.firefox = true;
    } else if (ua.indexOf('msie') !== -1) {
        env.msie = true;
    } else if (ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1) {
        env.safari = true;
    } else if (ua.indexOf('edge') !== -1) {
        env.msedge = true;
    }

    // msie version
    if (env.msie) {
        if (ua.indexOf('msie 7.0') !== -1) {
            env.msie7 = true;
        } else if (ua.indexOf('msie 8.0') !== -1) {
            env.msie8 = true;
        } else if (ua.indexOf('msie 9.0') !== -1) {
            env.msie9 = true;
        } else if (ua.indexOf('msie 10.0') !== -1) {
            env.msie10 = true;
        } else if (ua.indexOf('msie 11.0') !== -1) {
            env.msie11 = true;
        }
    }

    // add css class
    var classList = Object.keys(env).join(' ');
    $('html').addClass(classList);

    // exports
    return env;
};
<|endoftext|>