<commit_before>(function ContextMenu($angular, $document) {

    "use strict";

    /**
     * @module ngContextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    var module = $angular.module('ngContextMenu', []);

    /**
     * @module ngContextMenu
     * @service ContextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    module.factory('contextMenu', ['$rootScope', function contextMenuService($rootScope) {

        /**
         * @method cancelAll
         * @return {void}
         */
        function cancelAll() {
            $rootScope.$broadcast('context-menu/close');
        }

        return { cancelAll: cancelAll, eventBound: false };

    }]);

    /**
     * @module ngContextMenu
     * @directive contextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    module.directive('contextMenu', ['$http', '$interpolate', '$compile', 'contextMenu',

        function contextMenuDirective($http, $interpolate, $compile, contextMenu) {

            return {

                /**
                 * @property restrict
                 * @type {String}
                 */
                restrict: 'EA',

                /**
                 * @property scope
                 * @type {Boolean}
                 */
                scope: true,

                /**
                 * @property require
                 * @type {String}
                 */
                require: '?ngModel',

                /**
                 * @method link
                 * @param {Object} scope
                 * @param {angular.element} element
                 * @param {Object} attributes
                 * @param {Object} model
                 * @return {void}
                 */
                link: function link(scope, element, attributes, model) {

                    if (!contextMenu.eventBound) {

                        // Bind to the `document` if we haven't already.
                        $document.addEventListener('click', function click() {
                            contextMenu.cancelAll();
                            scope.$apply();
                        });

                        contextMenu.eventBound = true;

                    }

                    /**
                     * @method closeMenu
                     * @return {void}
                     */
                    function closeMenu() {

                        if (scope.menu) {
                            scope.menu.remove();
                            scope.menu     = null;
                            scope.position = null;
                        }

                    }

                    scope.$on('context-menu/close', closeMenu);

                    /**
                     * @method getModel
                     * @return {Object}
                     */
                    function getModel() {
                        return model ? $angular.extend(scope, model.$modelValue) : scope;
                    }

                    /**
                     * @method render
                     * @param {Object} event
                     * @param {String} [strategy="append"]
                     * @return {void}
                     */
                    function render(event, strategy) {

                        strategy = strategy || 'append';

                        if ('preventDefault' in event) {

                            contextMenu.cancelAll();
                            event.stopPropagation();
                            event.preventDefault();
                            scope.position = { x: event.clientX, y: event.clientY };

                        } else {

                            if (!scope.menu) {
                                return;
                            }

                        }

                        $http.get(attributes.contextMenu, { cache: true }).then(function then(response) {

                            var interpolated = $interpolate(response.data)($angular.extend(getModel())),
                                compiled     = $compile(interpolated)(scope),
                                menu         = $angular.element(compiled);

                            // Determine whether to append new, or replace an existing.
                            switch (strategy) {
                                case ('append'): element.append(menu); break;
                                default: scope.menu.replaceWith(menu); break;
                            }

                            menu.css({

                                position: 'absolute',
                                transform: $interpolate('translate({{x}}px, {{y}}px)')({
                                    x: scope.position.x, y: scope.position.y
                                })

                            });

                            scope.menu = menu;
                            scope.menu.bind('click', closeMenu);

                        });

                    }

                    if (model) {

                        var listener = function listener() {
                            return model.$modelValue;
                        };

                        // Listen for updates to the model...
                        scope.$watch(listener, function modelChanged() {
                            render({}, 'replaceWith');
                        }, true);

                    }

                    element.bind(attributes.contextEvent || 'contextmenu', render);

                }

            }

        }]);

})(window.angular, window.document);<commit_msg>Fixed bug in ng-repeat. Relates to #12<commit_after>(function ContextMenu($angular, $document) {

    "use strict";

    /**
     * @module ngContextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    var module = $angular.module('ngContextMenu', []);

    /**
     * @module ngContextMenu
     * @service ContextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    module.factory('contextMenu', ['$rootScope', function contextMenuService($rootScope) {

        /**
         * @method cancelAll
         * @return {void}
         */
        function cancelAll() {
            $rootScope.$broadcast('context-menu/close');
        }

        return { cancelAll: cancelAll, eventBound: false };

    }]);

    /**
     * @module ngContextMenu
     * @directive contextMenu
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngContextMenu
     */
    module.directive('contextMenu', ['$http', '$timeout', '$interpolate', '$compile', 'contextMenu',

        function contextMenuDirective($http, $timeout, $interpolate, $compile, contextMenu) {

            return {

                /**
                 * @property restrict
                 * @type {String}
                 */
                restrict: 'EA',

                /**
                 * @property scope
                 * @type {Boolean}
                 */
                scope: true,

                /**
                 * @property require
                 * @type {String}
                 */
                require: '?ngModel',

                /**
                 * @method link
                 * @param {Object} scope
                 * @param {angular.element} element
                 * @param {Object} attributes
                 * @param {Object} model
                 * @return {void}
                 */
                link: function link(scope, element, attributes, model) {

                    if (!contextMenu.eventBound) {

                        // Bind to the `document` if we haven't already.
                        $document.addEventListener('click', function click() {
                            contextMenu.cancelAll();
                            scope.$apply();
                        });

                        contextMenu.eventBound = true;

                    }

                    /**
                     * @method closeMenu
                     * @return {void}
                     */
                    function closeMenu() {

                        if (scope.menu) {
                            scope.menu.remove();
                            scope.menu     = null;
                            scope.position = null;
                        }

                    }

                    scope.$on('context-menu/close', closeMenu);

                    /**
                     * @method getModel
                     * @return {Object}
                     */
                    function getModel() {
                        return model ? $angular.extend(scope, model.$modelValue) : scope;
                    }

                    /**
                     * @method render
                     * @param {Object} event
                     * @param {String} [strategy="append"]
                     * @return {void}
                     */
                    function render(event, strategy) {

                        strategy = strategy || 'append';

                        if ('preventDefault' in event) {

                            contextMenu.cancelAll();
                            event.stopPropagation();
                            event.preventDefault();
                            scope.position = { x: event.clientX, y: event.clientY };

                        } else {

                            if (!scope.menu) {
                                return;
                            }

                        }

                        $http.get(attributes.contextMenu, { cache: true }).then(function then(response) {

                            var compiled     = $compile(response.data)($angular.extend(getModel())),
                                menu         = $angular.element(compiled);

                            // Determine whether to append new, or replace an existing.
                            switch (strategy) {
                                case ('append'): element.append(menu); break;
                                default: scope.menu.replaceWith(menu); break;
                            }

                            menu.css({

                                position: 'absolute',
                                transform: $interpolate('translate({{x}}px, {{y}}px)')({
                                    x: scope.position.x, y: scope.position.y
                                })

                            });

                            scope.menu = menu;
                            scope.menu.bind('click', closeMenu);

                        });

                    }

                    if (model) {

                        var listener = function listener() {
                            return model.$modelValue;
                        };

                        // Listen for updates to the model...
                        scope.$watch(listener, function modelChanged() {
                            render({}, 'replaceWith');
                        }, true);

                    }

                    element.bind(attributes.contextEvent || 'contextmenu', render);

                }

            }

        }]);

})(window.angular, window.document);<|endoftext|>


<commit_before>var express = require('express'),
    http = require('http'),
    https = require('https'),
    fs = require('fs'),
    config = require('./config.json'),
    routes = require('./src/routes.js'),
    httpsApp = express(),
    httpApp = express();

//CORS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'content-type, authorization, content-length, x-requested-with');
    next();
}

httpApp.use(allowCrossDomain);                  //allow CORS requests
routes.setup(httpApp);

//General error handling
httpApp.use(function(err, req, res, next){
    res.json(400, {"message":"Bad or invalid request, this may occur from improperly formatted input.", "code": 400});
});

//CREATE SERVER HTTP
http.createServer(httpApp).listen(config.http.port);
console.log("http  is listening on port", config.http.port);

if(config.https != null) {

    //MIDDLEWARE
    httpsApp.use(allowCrossDomain);                  //allow CORS requests
    routes.setup(httpsApp);

    //General error handling
    httpsApp.use(function(err, req, res, next){
        res.json(400, {"message":"Bad or invalid request, this may occur from improperly formatted input.", "code": 400});
    });

    //SSL MANAGEMENT
    var sslOptions = {},
        key = config.https.key,
        cert = config.https.cert,
        ca = config.https.ca;

    if(typeof key !== "undefined") {
        sslOptions.key = fs.readFileSync(key, 'utf8');
    }
    if(typeof cert !== "undefined") {
        sslOptions.cert = fs.readFileSync(cert, 'utf8');
    }
    if(typeof ca !== "undefined") {
        sslOptions.ca = [];
        for(var ci = 0; ci < ca.length; ci++) {
            var caFile = ca[ci];
            sslOptions.ca.push(fs.readFileSync(caFile, 'utf8'));
        }
    }

    //CREATE SERVER HTTPS
    https.createServer(sslOptions, httpsApp).listen(config.https.port);
    console.log("https is listening on port", config.https.port);
}<commit_msg>get rid of the general error messages... they do not appear to do what i thought they did.<commit_after>var express = require('express'),
    http = require('http'),
    https = require('https'),
    fs = require('fs'),
    config = require('./config.json'),
    routes = require('./src/routes.js'),
    httpsApp = express(),
    httpApp = express();

//CORS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'content-type, authorization, content-length, x-requested-with');
    next();
}

httpApp.use(allowCrossDomain);                  //allow CORS requests
routes.setup(httpApp);

//CREATE SERVER HTTP
http.createServer(httpApp).listen(config.http.port);
console.log("http  is listening on port", config.http.port);

if(config.https != null) {

    //MIDDLEWARE
    httpsApp.use(allowCrossDomain);                  //allow CORS requests
    routes.setup(httpsApp);

    //SSL MANAGEMENT
    var sslOptions = {},
        key = config.https.key,
        cert = config.https.cert,
        ca = config.https.ca;

    if(typeof key !== "undefined") {
        sslOptions.key = fs.readFileSync(key, 'utf8');
    }
    if(typeof cert !== "undefined") {
        sslOptions.cert = fs.readFileSync(cert, 'utf8');
    }
    if(typeof ca !== "undefined") {
        sslOptions.ca = [];
        for(var ci = 0; ci < ca.length; ci++) {
            var caFile = ca[ci];
            sslOptions.ca.push(fs.readFileSync(caFile, 'utf8'));
        }
    }

    //CREATE SERVER HTTPS
    https.createServer(sslOptions, httpsApp).listen(config.https.port);
    console.log("https is listening on port", config.https.port);
}<|endoftext|>


<commit_before>describe("VglRenderer component", function() {
    const {VglRenderer, VglNamespace} = VueGL;
    const assert = chai.assert;
    const webgl = (() => {
        const canvas = document.createElement("canvas");
        const opts = {
            antialias: true,
            premultipliedAlpha: false,
            depth: false
        };
        try {
            return canvas.getContext("webgl", opts) || canvas.getContext("experimental-webgl", opts);
        } catch(e) {}
        return false;
    })();
    let pvm;
    if (!webgl) {
        console.log("WebGL is not supported. Skip tests for the VglRenderer.");
    } else {
        //pvm = new Vue(VglRenderer).$mount();
    }
    beforeEach(function() {
        // Skip all tests when the WebGL is not supported.
        /*if (!webgl)*/ this.skip();
    });
    describe("Namespace injection", function() {
        describe("Should be able to access vglCameras", function() {
            it("When the component is the root namespace.", function() {
                assert.isObject(pvm.vglCameras);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglCameras);
            });
        });
        describe("Should be able to access vglScenes", function() {
            it("When the component is the root namespace.", function() {
                assert.isObject(pvm.vglScenes);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglScenes);
            });
        });
    });
    describe("Creating a renderer", function() {
        describe("Output canvas", function() {
            it("The domElement property of WebGLRenderer instance should be the Vue created canvas.", function() {
                assert.strictEqual(pvm.$refs.rdr, pvm.inst.domElement);
            });
        });
        describe("Context attributes", function() {
            describe("The alpha property should affect the alpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().alpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {alpha: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().alpha);
                });
            });
            describe("The disableDepth property should affect the depth attribute.", function() {
                const enable = !webgl.getContextAttributes().depth;
                if (!enable) console.log("Depth buffer cannot be disabled. Skip tests for the depth property.");
                beforeEach(function() {
                    if (!enable) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().depth);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableDepth: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().depth);
                });
            });
            describe("The disableStencil property should affect the stencil attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().stencil);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableStencil: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().stencil);
                });
            });
            describe("The antialias property should affect the antialias attribute.", function() {
                const enable = webgl.getContextAttributes().antialias;
                if (!enable) console.log("Antialiasing is not supported. Skip tests for the antialias property.");
                beforeEach(function() {
                    if (!enable) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().antialias);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {antialias: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().antialias);
                });
            });
            describe("The disablePremultipliedAlpha property should affect the premultipliedAlpha attribute.", function() {
                const enable = !webgl.getContextAttributes().premultipliedAlpha;
                if (!enable) console.log("PremultipliedAlpha cannot be disabled. Skip tests for the premultipliedAlpha property.");
                beforeEach(function() {
                    if (!enable) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().premultipliedAlpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disablePremultipliedAlpha: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().premultipliedAlpha);
                });
            });
            describe("The preserveDrawingBuffer property should affect the preserveDrawingBuffer attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().preserveDrawingBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {preserveDrawingBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().preserveDrawingBuffer);
                });
            });
        });
        describe("Capabilities", function() {
            describe("The logarithmicDepthBuffer property should affect the logarithmicDepthBuffer capability.", function() {
                const ext = webgl.getSupportedExtensions().indexOf("EXT_frag_depth") >= 0;
                if (!ext) console.log("The extension EXT_frag_depth is not supported. Skip tests for the logarithmicDepthBuffer property.");
                beforeEach(function() {
                    if (!ext) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.capabilities.logarithmicDepthBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {logarithmicDepthBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.capabilities.logarithmicDepthBuffer);
                });
            });
            describe("The precision property should affect the precision capability.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.strictEqual(pvm.inst.capabilities.precision, "highp");
                });
                it("When the property is \"lowp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "lowp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "lowp");
                });
                it("When the property is \"mediump\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "mediump"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "mediump");
                });
                it("When the property is \"highp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "highp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "highp");
                });
            });
        });
    });
    describe("When any properties are changed", function() {
        describe("Output canvas", function() {
            it("The canvas element should be replaced.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldCanvas = vm.$refs.rdr;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldCanvas, vm.$refs.rdr);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
            it("The WebGLRenderer instance should be newly created.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldInst = vm.inst;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldInst, vm.inst);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
            it("The domElement property of WebGLRenderer instance should be the replaced canvas.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.strictEqual(vm.inst.domElement, vm.$refs.rdr);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
        });
    });
});
<commit_msg>Temporary disables webgl detecting.<commit_after>describe("VglRenderer component", function() {
    const {VglRenderer, VglNamespace} = VueGL;
    const assert = chai.assert;
    const webgl = (() => {/*
        const canvas = document.createElement("canvas");
        const opts = {
            antialias: true,
            premultipliedAlpha: false,
            depth: false
        };
        try {
            return canvas.getContext("webgl", opts) || canvas.getContext("experimental-webgl", opts);
        } catch(e) {}*/
        return false;
    })();
    let pvm;
    if (!webgl) {
        console.log("WebGL is not supported. Skip tests for the VglRenderer.");
    } else {
        //pvm = new Vue(VglRenderer).$mount();
    }
    beforeEach(function() {
        // Skip all tests when the WebGL is not supported.
        /*if (!webgl)*/ this.skip();
    });
    describe("Namespace injection", function() {
        describe("Should be able to access vglCameras", function() {
            it("When the component is the root namespace.", function() {
                assert.isObject(pvm.vglCameras);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglCameras);
            });
        });
        describe("Should be able to access vglScenes", function() {
            it("When the component is the root namespace.", function() {
                assert.isObject(pvm.vglScenes);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglScenes);
            });
        });
    });
    describe("Creating a renderer", function() {
        describe("Output canvas", function() {
            it("The domElement property of WebGLRenderer instance should be the Vue created canvas.", function() {
                assert.strictEqual(pvm.$refs.rdr, pvm.inst.domElement);
            });
        });
        describe("Context attributes", function() {
            describe("The alpha property should affect the alpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().alpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {alpha: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().alpha);
                });
            });
            describe("The disableDepth property should affect the depth attribute.", function() {
                const enable = !webgl.getContextAttributes().depth;
                if (!enable) console.log("Depth buffer cannot be disabled. Skip tests for the depth property.");
                beforeEach(function() {
                    if (!enable) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().depth);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableDepth: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().depth);
                });
            });
            describe("The disableStencil property should affect the stencil attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().stencil);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableStencil: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().stencil);
                });
            });
            describe("The antialias property should affect the antialias attribute.", function() {
                const enable = webgl.getContextAttributes().antialias;
                if (!enable) console.log("Antialiasing is not supported. Skip tests for the antialias property.");
                beforeEach(function() {
                    if (!enable) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().antialias);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {antialias: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().antialias);
                });
            });
            describe("The disablePremultipliedAlpha property should affect the premultipliedAlpha attribute.", function() {
                const enable = !webgl.getContextAttributes().premultipliedAlpha;
                if (!enable) console.log("PremultipliedAlpha cannot be disabled. Skip tests for the premultipliedAlpha property.");
                beforeEach(function() {
                    if (!enable) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isTrue(pvm.inst.getContextAttributes().premultipliedAlpha);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disablePremultipliedAlpha: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().premultipliedAlpha);
                });
            });
            describe("The preserveDrawingBuffer property should affect the preserveDrawingBuffer attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.getContextAttributes().preserveDrawingBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {preserveDrawingBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().preserveDrawingBuffer);
                });
            });
        });
        describe("Capabilities", function() {
            describe("The logarithmicDepthBuffer property should affect the logarithmicDepthBuffer capability.", function() {
                const ext = webgl.getSupportedExtensions().indexOf("EXT_frag_depth") >= 0;
                if (!ext) console.log("The extension EXT_frag_depth is not supported. Skip tests for the logarithmicDepthBuffer property.");
                beforeEach(function() {
                    if (!ext) this.skip();
                });
                it("When the property is undefined (or false).", function() {
                    assert.isFalse(pvm.inst.capabilities.logarithmicDepthBuffer);
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {logarithmicDepthBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.capabilities.logarithmicDepthBuffer);
                });
            });
            describe("The precision property should affect the precision capability.", function() {
                it("When the property is undefined (or false).", function() {
                    assert.strictEqual(pvm.inst.capabilities.precision, "highp");
                });
                it("When the property is \"lowp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "lowp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "lowp");
                });
                it("When the property is \"mediump\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "mediump"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "mediump");
                });
                it("When the property is \"highp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "highp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "highp");
                });
            });
        });
    });
    describe("When any properties are changed", function() {
        describe("Output canvas", function() {
            it("The canvas element should be replaced.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldCanvas = vm.$refs.rdr;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldCanvas, vm.$refs.rdr);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
            it("The WebGLRenderer instance should be newly created.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldInst = vm.inst;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldInst, vm.inst);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
            it("The domElement property of WebGLRenderer instance should be the replaced canvas.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.strictEqual(vm.inst.domElement, vm.$refs.rdr);
                        done();
                    } catch(e) {
                        done(e);
                    }
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>/**
 * 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
 *
 *      https://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.
 */
import Variable from '../../src/models/Variable'
import assert from 'assert'

describe('Variable', function () {
  describe('#bind', function () {
    it('should return a new variable with the given value', function () {
      const v = new Variable('a', 'default', 'description')
      const o = v.bind('new')
      assert.strictEqual(v.value, 'default')
      assert.strictEqual(o.value, 'new')
    })
    it('should return a new variable with the pre-existing value if value is not a string', function () {
      const v = new Variable('a', 'default', 'description')
      const w = v.bind({})
      assert.strictEqual(w.value, 'default')
    })
  })

  describe('#apply', function () {
    it('should replace its $name with its value', function () {
      const v = new Variable('name', 'value', 'description')
      assert.strictEqual('value', v.apply('$name'))
    })

    it('should not touch booleans', function () {
      const v = new Variable('name', 'value', 'description')
      assert.strictEqual(true, v.apply(true))
    })
  })

  describe('#id', function () {
    it('a variable can have an `owner`', function () {
      const v1 = new Variable('name', 'value', 'description')
      const v2 = new Variable('name', 'value', 'description', 'owner')
      assert.strictEqual(v1.id, 'name')
      assert.strictEqual(v2.id, 'owner::name')
    })
  })

  describe('#chance', function () {
    it('creates random values with chance.js`', function () {
      const v1 = new Variable('==CHANCE=JS==', '', '')
      // eslint-disable-next-line no-template-curly-in-string
      assert.strictEqual(v1.chance('My magic number is ${chance.integer({min: 7, max: 7})}'), 'My magic number is 7')
      // eslint-disable-next-line no-template-curly-in-string
      assert.strictEqual(v1.chance('${chance.character({pool: "b"})}'), 'b')
      // eslint-disable-next-line no-template-curly-in-string
      assert(['false', 'null', 'undefined', '0', 'NaN', ''].includes(v1.chance('${chance.falsy()}')))
    })
  })
})
<commit_msg>feat: add extra test cases for Variable.chance.<commit_after>/**
 * 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
 *
 *      https://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.
 */
import Variable from '../../src/models/Variable'
import assert from 'assert'

describe('Variable', function () {
  describe('#bind', function () {
    it('should return a new variable with the given value', function () {
      const v = new Variable('a', 'default', 'description')
      const o = v.bind('new')
      assert.strictEqual(v.value, 'default')
      assert.strictEqual(o.value, 'new')
    })
    it('should return a new variable with the pre-existing value if value is not a string', function () {
      const v = new Variable('a', 'default', 'description')
      const w = v.bind({})
      assert.strictEqual(w.value, 'default')
    })
  })

  describe('#apply', function () {
    it('should replace its $name with its value', function () {
      const v = new Variable('name', 'value', 'description')
      assert.strictEqual('value', v.apply('$name'))
    })

    it('should not touch booleans', function () {
      const v = new Variable('name', 'value', 'description')
      assert.strictEqual(true, v.apply(true))
    })
  })

  describe('#id', function () {
    it('a variable can have an `owner`', function () {
      const v1 = new Variable('name', 'value', 'description')
      const v2 = new Variable('name', 'value', 'description', 'owner')
      assert.strictEqual(v1.id, 'name')
      assert.strictEqual(v2.id, 'owner::name')
    })
  })

  describe('#chance', function () {
    it('creates random values with chance.js`', function () {
      const v1 = new Variable('==CHANCE=JS==', '', '')
      // eslint-disable-next-line no-template-curly-in-string
      assert.strictEqual(v1.chance(v1.chance('My magic numbers are ${chance.integer({min: 7, max: 7})} and ${chance.integer({min: 17, max: 17})}')), 'My magic numbers are 7 and 17')
      // eslint-disable-next-line no-template-curly-in-string
      assert.strictEqual(v1.chance('${chance.character({pool: "b"})}'), 'b')
      // eslint-disable-next-line no-template-curly-in-string
      assert(['false', 'null', 'undefined', '0', 'NaN', ''].includes(v1.chance('${chance.falsy()}')))
      // eslint-disable-next-line no-template-curly-in-string
      assert.strictEqual(v1.chance('${lots} of $variables and symb$ols} { ${chance.character({pool: ")"})} ) } { } $'), '${lots} of $variables and symb$ols} { ) ) } { } $')
    })
  })
})
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

require('babel/register');

// Declare variables used
var app, base_url, bodyParser, express, hbs, mongoose, morgan, port, React, Todos, uristring;

// Define values
express = require('express');
app = express();
port = process.env.PORT || 5000;
base_url = process.env.BASE_URL || 'http://localhost:5000';
bodyParser = require('body-parser');
hbs = require('hbs');
morgan = require('morgan');
mongoose = require('mongoose');
uristring = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/react-todos';
React = require('react');
Todos = React.createFactory(require('./components/todos.jsx'));

// Connect to the database
mongoose.connect(uristring);

// Create a model for the todos
var TodoSchema = mongoose.Schema({
  text: {
    type: String,
    match: /^(\w+)/
  }
});
var Todo = mongoose.model('Todo', TodoSchema);

// Set up templating
app.set('views', __dirname + '/views');
app.set('view engine', "hbs");
app.engine('hbs', require('hbs').__express);

// Set up logging
app.use(morgan('combined'));

// Set URL
app.set('base_url', base_url);

// Handle POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
      extended: true
}));

// Serve static files
app.use(express.static(__dirname + '/static'));

// Define index route
app.get('/', function (req, res) {
  Todo.find(function (err, todos) {
    if (err) {
      console.log('Error: ' + err);
    } else {
      var markup = React.renderToString(Todos({ data: todos }));
      res.render('index', { markup: markup });
    }
  });
});

// Define todos route
app.get('/todos', function (req, res) {
  Todo.find(function (err, todos) {
    if (err) {
      console.log('Error: ' + err);
    } else {
      res.json(todos);
    }
  });
});

// Create new todo
app.post('/todos', function (req, res) {
  // Get text
  var text = req.body.text;

  // Save it
  var newtodo = new Todo({ text: text });
  newtodo.save(function (err) {
    if (err) {
      console.log('Error: ' + err);
    } else {
      Todo.find(function (err, todos) {
        if (err) {
          console.log('Error: ' + err);
        } else {
          res.status(201).json(todos);
        }
      });
    }
  });
});

// Listen
app.listen(port);
console.log("Listening on port " + port);
<commit_msg>Now include initial state in template<commit_after>/*jslint node: true */
'use strict';

require('babel/register');

// Declare variables used
var app, base_url, bodyParser, express, hbs, mongoose, morgan, port, React, Todos, uristring;

// Define values
express = require('express');
app = express();
port = process.env.PORT || 5000;
base_url = process.env.BASE_URL || 'http://localhost:5000';
bodyParser = require('body-parser');
hbs = require('hbs');
morgan = require('morgan');
mongoose = require('mongoose');
uristring = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/react-todos';
React = require('react');
Todos = React.createFactory(require('./components/todos.jsx'));

// Connect to the database
mongoose.connect(uristring);

// Create a model for the todos
var TodoSchema = mongoose.Schema({
  text: {
    type: String,
    match: /^(\w+)/
  }
});
var Todo = mongoose.model('Todo', TodoSchema);

// Set up templating
app.set('views', __dirname + '/views');
app.set('view engine', "hbs");
app.engine('hbs', require('hbs').__express);

// Set up logging
app.use(morgan('combined'));

// Set URL
app.set('base_url', base_url);

// Handle POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
      extended: true
}));

// Serve static files
app.use(express.static(__dirname + '/static'));

// Define index route
app.get('/', function (req, res) {
  Todo.find(function (err, todos) {
    if (err) {
      console.log('Error: ' + err);
    } else {
      var markup = React.renderToString(Todos({ data: todos }));
      res.render('index', {
        markup: markup,
        state: JSON.stringify(todos)
      });
    }
  });
});

// Define todos route
app.get('/todos', function (req, res) {
  Todo.find(function (err, todos) {
    if (err) {
      console.log('Error: ' + err);
    } else {
      res.json(todos);
    }
  });
});

// Create new todo
app.post('/todos', function (req, res) {
  // Get text
  var text = req.body.text;

  // Save it
  var newtodo = new Todo({ text: text });
  newtodo.save(function (err) {
    if (err) {
      console.log('Error: ' + err);
    } else {
      Todo.find(function (err, todos) {
        if (err) {
          console.log('Error: ' + err);
        } else {
          res.status(201).json(todos);
        }
      });
    }
  });
});

// Listen
app.listen(port);
console.log("Listening on port " + port);
<|endoftext|>


<commit_before>/*
 * This file is part of Arduino
 *
 * Arduino is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As a special exception, you may use this file as part of a free software
 * library without restriction.  Specifically, if other files instantiate
 * templates or use macros or inline functions from this file, or you compile
 * this file and link it with other files to produce an executable, this
 * file does not by itself cause the resulting executable to be covered by
 * the GNU General Public License.  This exception does not however
 * invalidate any other reasons why the executable file might be covered by
 * the GNU General Public License.
 *
 * Copyright 2015 Arduino Srl (http://www.arduino.org/) support@arduino.org
 *
 * authors: arduino.org team
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
 maxerr: 50, browser: true */
/*global $, define, brackets */

define(function(require, exports, module){
	"use strict";

	var	AppInit = brackets.getModule("utils/AppInit"),
		WorkspaceManager = brackets.getModule("view/WorkspaceManager"),
		ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
		StatusBar = brackets.getModule("widgets/StatusBar");

	var panelHTML = require("text!./html/Console.html"),
		panel,
		bTag = $('

'),
		pTag = $('

');

	var writeLog 	= 	function($event, data){
							if(data){
								$('#logger').html($('#logger').html()+""+data+"
");
							}
						},
		writeError	=	function($event, data){
							if(data){
								$('#logger').html($('#logger').html()+""+data+"
");
							}
		},
		clearLog	=	function($event){
							$('#logger').empty();
		},
		setBoard	=	function($event, data){
							if(data)
								document.getElementById("bTag").innerText = data;
						},
		setPort		=	function($event, data){
							if(data)
								document.getElementById("pTag").innerText = data;
		};

	function Console()
	{
		brackets.arduino.dispatcher.on("arduino-event-console-log", writeLog);
		brackets.arduino.dispatcher.on("arduino-event-console-error", writeError);

		brackets.arduino.dispatcher.on("arduino-event-console-board", setBoard);
		brackets.arduino.dispatcher.on("arduino-event-console-port", setPort);

		brackets.arduino.dispatcher.on("arduino-event-console-clear", clearLog);
	}

	AppInit.htmlReady(function () {

        ExtensionUtils.loadStyleSheet(module, "css/Console.css");

		StatusBar.addIndicator("pTag", pTag, true, "", "Selected Port");
		StatusBar.addIndicator("bTag", bTag, true, "", "Selected Board");

		panel = WorkspaceManager.createBottomPanel("console.panel", $(panelHTML));
		panel.show();

	});

	return Console;

})<commit_msg>add click event in the board/port element in status bar<commit_after>/*
 * This file is part of Arduino
 *
 * Arduino is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As a special exception, you may use this file as part of a free software
 * library without restriction.  Specifically, if other files instantiate
 * templates or use macros or inline functions from this file, or you compile
 * this file and link it with other files to produce an executable, this
 * file does not by itself cause the resulting executable to be covered by
 * the GNU General Public License.  This exception does not however
 * invalidate any other reasons why the executable file might be covered by
 * the GNU General Public License.
 *
 * Copyright 2015 Arduino Srl (http://www.arduino.org/) support@arduino.org
 *
 * authors: arduino.org team
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
 maxerr: 50, browser: true */
/*global $, define, brackets */

define(function(require, exports, module){
	"use strict";

	var	AppInit = brackets.getModule("utils/AppInit"),
		WorkspaceManager = brackets.getModule("view/WorkspaceManager"),
		ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
		StatusBar = brackets.getModule("widgets/StatusBar");

	var panelHTML = require("text!./html/Console.html"),
		panel,
		bTag = $('

'),
		pTag = $('

');

	bTag.click(function(){
		brackets.arduino.dispatcher.trigger("arduino-event-menu-tool-boards","");
	});

	pTag.click(function(){
		brackets.arduino.dispatcher.trigger("arduino-event-menu-tool-ports","");
	});

	var writeLog 	= 	function($event, data){
							if(data){
								$('#logger').html($('#logger').html()+""+data+"
");
							}
						},
		writeError	=	function($event, data){
							if(data){
								$('#logger').html($('#logger').html()+""+data+"
");
							}
		},
		clearLog	=	function($event){
							$('#logger').empty();
		},
		setBoard	=	function($event, data){
							if(data)
								document.getElementById("bTag").innerText = data;
						},
		setPort		=	function($event, data){
							if(data)
								document.getElementById("pTag").innerText = data;
		};

	function Console()
	{
		brackets.arduino.dispatcher.on("arduino-event-console-log", writeLog);
		brackets.arduino.dispatcher.on("arduino-event-console-error", writeError);

		brackets.arduino.dispatcher.on("arduino-event-console-board", setBoard);
		brackets.arduino.dispatcher.on("arduino-event-console-port", setPort);

		brackets.arduino.dispatcher.on("arduino-event-console-clear", clearLog);
	}

	AppInit.htmlReady(function () {

        ExtensionUtils.loadStyleSheet(module, "css/Console.css");

		StatusBar.addIndicator("pTag", pTag, true, "", "Selected Port");
		StatusBar.addIndicator("bTag", bTag, true, "", "Selected Board");

		panel = WorkspaceManager.createBottomPanel("console.panel", $(panelHTML));
		panel.show();

	});

	return Console;

})<|endoftext|>


<commit_before>define(['js/models'], function(Models) {

    describe('A pomodoro', function() {

        var clock;

        before(function () {
            clock = sinon.useFakeTimers();
        });

        after(function () {
            clock.restore();
        });

        it('should have reasonable default values', function() {
            var pmdr = new Models.Pomodoro();
            expect(pmdr.get('duration')).to.be.equal(25 * 60 * 1000);
            expect(pmdr.get('startedAt')).to.be.null;
            expect(pmdr.get('terminatedAt')).to.be.null;
        });

        it('should have a configurable duration', function() {
            var pmdr = new Models.Pomodoro({'duration': 10 * 60 * 1000});
            expect(pmdr.get('duration')).to.be.equal(10 * 60 * 1000);
        });

        describe('start', function() {
            it('should save the started date', function() {
                var pmdr = new Models.Pomodoro();
                pmdr.start();
                expect(pmdr.get('startedAt')).to.be.equal(Date.now());
            });
        });

        describe('terminate', function() {
            it('should be called when the pomodoro is over', function() {
                var pmdr = new Models.Pomodoro({'duration': 1000});
                sinon.spy(pmdr, '_terminate');
                pmdr.start();

                clock.tick(2000);
                expect(pmdr._terminate.calledOnce).to.be.true;
            });
        });

        describe('interrupt', function() {
            it('should mark the pomodoro as manually interrupted', function() {
                var pmdr = new Models.Pomodoro();
                pmdr.start();
                pmdr.interrupt();
                expect(pmdr.get('wasInterrupted')).to.be.true;
            });
        });
    });
});
<commit_msg>Correct wrong path in test file<commit_after>define(['src/js/models'], function(Models) {

    describe('A pomodoro', function() {

        var clock;

        before(function () {
            clock = sinon.useFakeTimers();
        });

        after(function () {
            clock.restore();
        });

        it('should have reasonable default values', function() {
            var pmdr = new Models.Pomodoro();
            expect(pmdr.get('duration')).to.be.equal(25 * 60 * 1000);
            expect(pmdr.get('startedAt')).to.be.null;
            expect(pmdr.get('terminatedAt')).to.be.null;
        });

        it('should have a configurable duration', function() {
            var pmdr = new Models.Pomodoro({'duration': 10 * 60 * 1000});
            expect(pmdr.get('duration')).to.be.equal(10 * 60 * 1000);
        });

        describe('start', function() {
            it('should save the started date', function() {
                var pmdr = new Models.Pomodoro();
                pmdr.start();
                expect(pmdr.get('startedAt')).to.be.equal(Date.now());
            });
        });

        describe('terminate', function() {
            it('should be called when the pomodoro is over', function() {
                var pmdr = new Models.Pomodoro({'duration': 1000});
                sinon.spy(pmdr, '_terminate');
                pmdr.start();

                clock.tick(2000);
                expect(pmdr._terminate.calledOnce).to.be.true;
            });
        });

        describe('interrupt', function() {
            it('should mark the pomodoro as manually interrupted', function() {
                var pmdr = new Models.Pomodoro();
                pmdr.start();
                pmdr.interrupt();
                expect(pmdr.get('wasInterrupted')).to.be.true;
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict'
/* eslint no-proto: 0 */
module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties)

function setProtoOf (obj, proto) {
  obj.__proto__ = proto
  return obj
}

function mixinProperties (obj, proto) {
  for (var prop in proto) {
    if (!obj.hasOwnProperty(prop)) {
      obj[prop] = proto[prop]
    }
  }
  return obj
}
<commit_msg>Replace direct hasOwnProperty with Object.prototype access<commit_after>'use strict'
/* eslint no-proto: 0 */
module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties)

function setProtoOf (obj, proto) {
  obj.__proto__ = proto
  return obj
}

function mixinProperties (obj, proto) {
  for (var prop in proto) {
    if (!Object.prototype.hasOwnProperty.call(obj, prop)) {
      obj[prop] = proto[prop]
    }
  }
  return obj
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

var chai = require('chai');
var expect = chai.expect;
var mockPackageJson = JSON.parse(fs.readFileSync(path.join(__dirname, './mockPackageConfig.json'), 'utf8'));
var moduleUtils = require('../index.js');
var moduleUtilsInstance = moduleUtils(mockPackageJson);

var consoleLogToFile = require('./consoleLogToFile');
var mockProcessExit = require('./mockProcessExit');

chai.use(require('chai-fs'));
chai.should();

describe('As user of the module utils module', function() {

	it('should export a function', function() {
		expect(moduleUtils).to.be.an('function');
	})

	describe('When creating an instance', function() {

		it('should return an object', function() {
			expect(moduleUtilsInstance).to.be.an('object');
		})
	})

	describe('When using the logMessage function', function() {

		before(function() {
			consoleLogToFile.enable();
		})

		after(function() {
			consoleLogToFile.removeLogFile();
		})

		it('should correctly log the input', function() {
			var logInput = "Who are the patriots?"
			var expected = fs.readFileSync(path.join(__dirname, 'structs', 'logMessage.txt'), 'utf8');
			var actual;

			moduleUtilsInstance.logMessage(logInput);
			consoleLogToFile.restore();
			actual = consoleLogToFile.getFileContents();

			expect(expected).to.equal(actual);
		});

	})

	describe('When using the finishInstall function', function() {

		describe('And testing the on-screen output', function() {
			before(function() {
				consoleLogToFile.enable();
				mockProcessExit.enable();
			})

			after(function() {
				consoleLogToFile.removeLogFile();
			})

			it('should correctly log the input', function() {
				var expected = fs.readFileSync(path.join(__dirname, 'structs', 'finishInstall.txt'), 'utf8');
				var actual;

				moduleUtilsInstance.finishInstall();
				consoleLogToFile.restore();
				mockProcessExit.restore();
				actual = consoleLogToFile.getFileContents();

				expect(expected).to.equal(actual);
			})
		})

		describe('And testing if the process it exited', function() {
			before(function() {
				mockProcessExit.enable();
			})

			after(function() {
				consoleLogToFile.restore();
			})

			it('should exit the process with no error', function() {
				var exitCallInfo;

				moduleUtilsInstance.finishInstall();

				exitCallInfo = mockProcessExit.callInfo();

				expect(exitCallInfo.called).to.be.true;
				expect(exitCallInfo.errorCode).to.equal(0);
			})

		})

	})
})<commit_msg>test: Improve wording<commit_after>var fs = require('fs');
var path = require('path');

var chai = require('chai');
var expect = chai.expect;
var mockPackageJson = JSON.parse(fs.readFileSync(path.join(__dirname, './mockPackageConfig.json'), 'utf8'));
var moduleUtils = require('../index.js');
var moduleUtilsInstance = moduleUtils(mockPackageJson);

var consoleLogToFile = require('./consoleLogToFile');
var mockProcessExit = require('./mockProcessExit');

chai.use(require('chai-fs'));
chai.should();

describe('As user of the module utils module', function() {

	it('should export a function', function() {
		expect(moduleUtils).to.be.an('function');
	})

	describe('When creating an instance', function() {

		it('should return an object', function() {
			expect(moduleUtilsInstance).to.be.an('object');
		})
	})

	describe('When using the logMessage function', function() {

		before(function() {
			consoleLogToFile.enable();
		})

		after(function() {
			consoleLogToFile.removeLogFile();
		})

		it('should correctly log the input', function() {
			var logInput = "Who are the patriots?"
			var expected = fs.readFileSync(path.join(__dirname, 'structs', 'logMessage.txt'), 'utf8');
			var actual;

			moduleUtilsInstance.logMessage(logInput);
			consoleLogToFile.restore();
			actual = consoleLogToFile.getFileContents();

			expect(expected).to.equal(actual);
		});

	})

	describe('When using the finishInstall function', function() {

		describe('And testing the on-screen output', function() {
			before(function() {
				consoleLogToFile.enable();
				mockProcessExit.enable();
			})

			after(function() {
				consoleLogToFile.removeLogFile();
			})

			it('should correctly log the input', function() {
				var expected = fs.readFileSync(path.join(__dirname, 'structs', 'finishInstall.txt'), 'utf8');
				var actual;

				moduleUtilsInstance.finishInstall();
				consoleLogToFile.restore();
				mockProcessExit.restore();
				actual = consoleLogToFile.getFileContents();

				expect(expected).to.equal(actual);
			})
		})

		describe('And testing if the process it exited', function() {
			before(function() {
				mockProcessExit.enable();
			})

			after(function() {
				consoleLogToFile.restore();
			})

			it('should exit the process with error code 0 (no error)', function() {
				var exitCallInfo;

				moduleUtilsInstance.finishInstall();

				exitCallInfo = mockProcessExit.callInfo();

				expect(exitCallInfo.called).to.be.true;
				expect(exitCallInfo.errorCode).to.equal(0);
			})

		})

	})
})<|endoftext|>


<commit_before>
'use strict';

var SCUZ_SAVE_ON_EXIT = process.env.SCUZ_SAVE_ON_EXIT || false;
var SCUZ_LOAD_STORAGE = process.env.SCUZ_LOAD_STORAGE || false;
var SCUZ_STORAGE_NAME = process.env.SCUZ_STORAGE_NAME || 'scuz.json';
var SCUZ_SAVE_INTERVAL = process.env.SCUZ_SAVE_INTERVAL || false;
var SCUZ_PORT = process.env.SCUZ_PORT || process.env.PORT || 1337;

var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var express = require('express');
var morgan = require('morgan');
var cors = require('cors');
var fs = require('fs');

var scuz = express();

scuz.use(morgan('dev'));
scuz.use(cors());
scuz.use(methodOverride());
scuz.use(bodyParser.json());
scuz.use(bodyParser.urlencoded({extended: true}));
scuz.use(function(err, req, res, next) {
  if (!err) return next();
  res.status(400).json({
    error: true,
    status: 400,
    message: 'invalid json',
    body: null
  });
});

scuz.get('/', function(req, res) {
  res.status(200).json({
    error: false,
    status: 200,
    message: 'ok',
    body: scuz.get('storage')
  });
});

scuz.put('/', function(req, res) {
  scuz.set('storage', req.body || {});
  res.status(200).json({
    error: false,
    status: 200,
    message: 'ok',
    body: scuz.get('storage')
  });
});

scuz.delete('/', function(req, res) {
  scuz.set('storage', {});
  res.status(200).json({
    error: false,
    status: 200,
    message: 'ok',
    body: scuz.get('storage')
  });
});

scuz.get('/:resource', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    res.status(200).json({
      error: false,
      status: 200,
      message: 'ok',
      body: storage[req.params.resource]
    });
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

scuz.get('/:resource/:id', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    var resource = storage[req.params.resource];
    if (req.params.id in resource) {
      res.status(200).json({
        error: false,
        status: 200,
        message: 'ok',
        body: resource[req.params.id]
      });
    } else {
      res.status(404).json({
        error: true,
        status: 404,
        message: 'record not found',
        body: null
      });
    }
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

scuz.post('/:resource', function(req, res) {
  var storage = scuz.get('storage');
  var resource, id = Date.now();
  if (!(req.params.resource in storage)) {
    storage[req.params.resource] = {};
  }
  resource = storage[req.params.resource];
  resource[id] = req.body;
  res.status(201).json({
    error: false,
    status: 201,
    message: 'created',
    body: resource[id]
  });
});

scuz.put('/:resource/:id', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    var resource = storage[req.params.resource];
    if (req.params.id in resource) {
      resource[req.params.id] = req.body;
      return res.status(200).json({
        error: false,
        status: 200,
        message: 'ok',
        body: resource[req.params.id]
      });
    } else {
      res.status(404).json({
        error: true,
        status: 404,
        message: 'record not found',
        body: null
      });
    }
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

scuz.delete('/:resource', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    delete storage[req.params.resource];
    res.status(200).json({
      error: false,
      status: 200,
      message: 'ok',
      body: null
    });
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

scuz.delete('/:resource/:id', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    if (req.params.id in storage[req.params.resource]) {
      delete storage[req.params.resource][req.params.id];
      res.status(200).json({
        error: false,
        status: 200,
        message: 'ok',
        body: null
      });
    } else {
      res.status(404).json({
        error: true,
        status: 404,
        message: 'record not found',
        body: null
      });
    }
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

if (SCUZ_SAVE_INTERVAL) {
  try {
    var saveTimer = setInterval(function() {
      fs.createWriteStream(
        __dirname + '/' + SCUZ_STORAGE_NAME
      ).end(JSON.stringify(scuz.get('storage')), function() {
        console.log('[scuz info] wrote storage to disk!');
      });
    }, parseInt(SCUZ_SAVE_INTERVAL, 10));
  } catch (ex) {
    console.error('[scuz error] SCUZ_SAVE_INTERVAL (%s) is not a number!', SCUZ_SAVE_INTERVAL);
  }
}

process.on('uncaughtException', function(err) {
  console.error('[scuz error] uncaught exception', err);
}).on('unhandledRejection', function(err) {
  console.error('[scuz error] unhandled rejection', err);
}).on('exit', function(code) {
  if (!SCUZ_SAVE_ON_EXIT) return;
  console.log('[scuz info] writing json to disk...');
  fs.writeFileSync(
    __dirname + '/' + SCUZ_STORAGE_NAME,
    JSON.stringify(scuz.get('storage'))
  );
  console.log('[scuz info] ...done!')
  console.log('[scuz info] about to exit with code', code);
});

scuz.set('storage', SCUZ_LOAD_STORAGE && fs.existsSync(__dirname + '/' + SCUZ_STORAGE_NAME) ?
  require('./' + SCUZ_STORAGE_NAME) : {}
);

module.exports = scuz.listen.bind(scuz, SCUZ_PORT, function() {
  console.log('[scuz info] http://localhost:%s', SCUZ_PORT);
});
<commit_msg>using path module<commit_after>
'use strict';

var SCUZ_SAVE_ON_EXIT = process.env.SCUZ_SAVE_ON_EXIT || false;
var SCUZ_LOAD_STORAGE = process.env.SCUZ_LOAD_STORAGE || false;
var SCUZ_STORAGE_NAME = process.env.SCUZ_STORAGE_NAME || 'scuz.json';
var SCUZ_SAVE_INTERVAL = process.env.SCUZ_SAVE_INTERVAL || false;
var SCUZ_PORT = process.env.SCUZ_PORT || process.env.PORT || 1337;

var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var express = require('express');
var morgan = require('morgan');
var cors = require('cors');
var path = require('path');
var fs = require('fs');

var storagePath = path.join(__dirname, SCUZ_STORAGE_NAME);
var scuz = express();

scuz.use(morgan('dev'));
scuz.use(cors());
scuz.use(methodOverride());
scuz.use(bodyParser.json());
scuz.use(bodyParser.urlencoded({extended: true}));
scuz.use(function(err, req, res, next) {
  if (!err) return next();
  res.status(400).json({
    error: true,
    status: 400,
    message: 'invalid json',
    body: null
  });
});

scuz.get('/', function(req, res) {
  res.status(200).json({
    error: false,
    status: 200,
    message: 'ok',
    body: scuz.get('storage')
  });
});

scuz.put('/', function(req, res) {
  scuz.set('storage', req.body || {});
  res.status(200).json({
    error: false,
    status: 200,
    message: 'ok',
    body: scuz.get('storage')
  });
});

scuz.delete('/', function(req, res) {
  scuz.set('storage', {});
  res.status(200).json({
    error: false,
    status: 200,
    message: 'ok',
    body: scuz.get('storage')
  });
});

scuz.get('/:resource', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    res.status(200).json({
      error: false,
      status: 200,
      message: 'ok',
      body: storage[req.params.resource]
    });
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

scuz.get('/:resource/:id', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    var resource = storage[req.params.resource];
    if (req.params.id in resource) {
      res.status(200).json({
        error: false,
        status: 200,
        message: 'ok',
        body: resource[req.params.id]
      });
    } else {
      res.status(404).json({
        error: true,
        status: 404,
        message: 'record not found',
        body: null
      });
    }
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

scuz.post('/:resource', function(req, res) {
  var storage = scuz.get('storage');
  var resource, id = Date.now();
  if (!(req.params.resource in storage)) {
    storage[req.params.resource] = {};
  }
  resource = storage[req.params.resource];
  resource[id] = req.body;
  res.status(201).json({
    error: false,
    status: 201,
    message: 'created',
    body: resource[id]
  });
});

scuz.put('/:resource/:id', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    var resource = storage[req.params.resource];
    if (req.params.id in resource) {
      resource[req.params.id] = req.body;
      return res.status(200).json({
        error: false,
        status: 200,
        message: 'ok',
        body: resource[req.params.id]
      });
    } else {
      res.status(404).json({
        error: true,
        status: 404,
        message: 'record not found',
        body: null
      });
    }
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

scuz.delete('/:resource', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    delete storage[req.params.resource];
    res.status(200).json({
      error: false,
      status: 200,
      message: 'ok',
      body: null
    });
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

scuz.delete('/:resource/:id', function(req, res) {
  var storage = scuz.get('storage');
  if (req.params.resource in storage) {
    if (req.params.id in storage[req.params.resource]) {
      delete storage[req.params.resource][req.params.id];
      res.status(200).json({
        error: false,
        status: 200,
        message: 'ok',
        body: null
      });
    } else {
      res.status(404).json({
        error: true,
        status: 404,
        message: 'record not found',
        body: null
      });
    }
  } else {
    res.status(404).json({
      error: true,
      status: 404,
      message: 'resource type not found',
      body: null
    });
  }
});

if (SCUZ_SAVE_INTERVAL) {
  try {
    var saveTimer = setInterval(function() {
      fs.createWriteStream(
        storagePath
      ).end(
        JSON.stringify(scuz.get('storage')), function() {
        console.log('[scuz info] wrote storage to disk!');
      });
    }, parseInt(SCUZ_SAVE_INTERVAL, 10));
  } catch (ex) {
    console.error('[scuz error] SCUZ_SAVE_INTERVAL (%s) is not a number!', SCUZ_SAVE_INTERVAL);
  }
}

process.on('uncaughtException', function(err) {
  console.error('[scuz error] uncaught exception', err);
}).on('unhandledRejection', function(err) {
  console.error('[scuz error] unhandled rejection', err);
}).on('exit', function(code) {
  if (!SCUZ_SAVE_ON_EXIT) return;
  console.log('[scuz info] writing json to disk...');
  fs.writeFileSync(storagePath, JSON.stringify(scuz.get('storage')));
  console.log('[scuz info] ...done!')
  console.log('[scuz info] about to exit with code', code);
});

scuz.set('storage', SCUZ_LOAD_STORAGE && fs.existsSync(storagePath) ? require('./' + storagePath) : {});

module.exports = scuz.listen.bind(scuz, SCUZ_PORT, function() {
  console.log('[scuz info] http://localhost:%s', SCUZ_PORT);
});
<|endoftext|>


<commit_before>var React = require('react-native')
var tweenState = require('react-tween-state')
var Dimensions = require('Dimensions')
var {PanResponder, TouchableHighlight, StyleSheet, Text, View} = React
var styles = require('./styles.js')

var SwipeoutBtn = React.createClass({
  getDefaultProps: function() {
    return {
      backgroundColor: null,
      color: null,
      height: 0,
      key: null,
      onPress: null,
      text: 'Click me',
      type: '',
      width: 0,
    }
  }
, render: function() {
    var btn = this.props
    var styleSwipeoutBtn = [styles.swipeoutBtn]
    var styleSwipeoutBtnText = [styles.swipeoutBtnText]
    styleSwipeoutBtn.push([{
      height: btn.height,
      width: btn.width,
    }])
    if (btn.type === 'delete') styleSwipeoutBtn.push(styles.colorDelete)
    else if (btn.type === 'primary') styleSwipeoutBtn.push(styles.colorPrimary)
    else if (btn.type === 'secondary') styleSwipeoutBtn.push(styles.colorSecondary)
    if (btn.backgroundColor) styleSwipeoutBtn.push([{ backgroundColor: btn.backgroundColor }])
    if (btn.color) styleSwipeoutBtnText.push([{ color: btn.color }])

    return  (
      <TouchableHighlight
        onPress={this.props.onPress}
        style={styles.swipeoutBtnTouchable}
      >
        <View style={styleSwipeoutBtn}>
          <Text style={styleSwipeoutBtnText}>{btn.text}</Text>
        </View>
      </TouchableHighlight>
    )
  }
})

var Swipeout = React.createClass({
  mixins: [tweenState.Mixin]
, getInitialState: function() {
    return {
      autoClose: this.props.autoClose || false,
      btnWidth: 0,
      btnsWidth: 0,
      contentHeight: 0,
      contentPos: 0,
      contentWidth: Dimensions.get('window').width,
      exposed: false,
      swiping: false,
      tweenDuration: 160,
      timeSwipeStart: null,
    }
  }
, componentWillMount: function() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
      onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
      onPanResponderGrant: this._handlePanResponderGrant,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this._handlePanResponderEnd,
    });
  }
, _handleStartShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
    return true;
  }
, _handleMoveShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
    return true;
  }
, _handlePanResponderGrant: function(e: Object, gestureState: Object) {
    this.refs.swipeoutContent.measure((ox, oy, width, height) => {
      this.setState({
        btnWidth: (width/5),
        btnsWidth: (width/5)*this.props.btns.length,
        contentHeight: height,
        contentWidth: width,
        swiping: true,
        timeSwipeStart: (new Date()).getTime(),
      })
    })
  }
, _handlePanResponderMove: function(e: Object, gestureState: Object) {
    var posX = gestureState.dx
    if (this.state.exposed) var posX = gestureState.dx - this.state.btnsWidth
    if (this.state.swiping) this.setState({ contentPos: Math.min(posX, 0) })
  }
, _handlePanResponderEnd: function(e: Object, gestureState: Object) {
    var timeDiff = (new Date()).getTime() - this.state.timeSwipeStart < 200
    var btnsWidth = -1*(this.state.btnsWidth)
    var contentWidth = this.state.contentWidth
    var posX = gestureState.dx
    var openX = -1*(contentWidth*0.33)
    var expose = posX < openX
    if (this.state.exposed) var expose = posX+openX < openX

    if (this.state.swiping) {
      if (timeDiff) {
        var expose = posX < openX/10
        this.tweenState('contentPos', {
          easing: tweenState.easingTypes.easeInOutQuad,
          duration: this.state.tweenDuration/2,
          endValue: expose ? btnsWidth : 0
        })
        if (expose) this.setState({ contentPos: btnsWidth, exposed: true })
        else this.setState({ contentPos: 0, exposed: false })
      } else {
        this.tweenState('contentPos', {
          easing: tweenState.easingTypes.easeInOutQuad,
          duration: this.state.tweenDuration,
          endValue: expose ? btnsWidth : 0
        })
        if (expose) this.setState({ contentPos: btnsWidth, exposed: true })
        else this.setState({ contentPos: 0, exposed: false })
      }
    }
    this.setState({ swiping: false })
  }
, _rubberBandEasing: function(value, lowerLimit) {
    if(value < lowerLimit) {
      return lowerLimit - Math.pow(lowerLimit - value, 0.85);
    }
    return value;
  }
, _autoClose: function(i) {
    var onPress = this.props.btns[i].onPress
    if (onPress) onPress()
    if (this.state.autoClose) {
      this.tweenState('contentPos', {
        easing: tweenState.easingTypes.easeInOutQuad,
        duration: this.state.tweenDuration,
        endValue: 0
      })
      this.setState({ exposed: false })
    }
  }
, render: function() {
    var self = this

    var styleSwipeout = [styles.swipeout]
    if (self.props.backgroundColor) {
      styleSwipeout.push([{ backgroundColor: self.props.backgroundColor }])
    }

    var styleSwipeoutMove = StyleSheet.create({
      swipeoutBtns: {
        left: Math.abs(self.state.contentWidth+ Math.max(self.state.btnsWidth*-1, self.getTweeningValue('contentPos'))),
      },
      swipeoutContent: {
        left: self._rubberBandEasing(self.getTweeningValue('contentPos'), self.state.btnsWidth*-1),
      }
    })

    var styleSwipeoutContent = [styles.swipeoutContent]
    styleSwipeoutContent.push(styleSwipeoutMove.swipeoutContent)

    var styleSwipeoutBtns = [styles.swipeoutBtns]
    styleSwipeoutBtns.push(styleSwipeoutMove.swipeoutBtns)

    return (
      <View style={styles.swipeout}>
        <View ref="swipeoutContent" style={styleSwipeoutContent} {...self._panResponder.panHandlers}>
          {self.props.children}
        </View>
        <View style={styleSwipeoutBtns}>
          {
            self.props.btns.map(function(btn, i){
              return (
                <SwipeoutBtn
                  backgroundColor={btn.backgroundColor}
                  color={btn.color}
                  height={self.state.contentHeight}
                  key={i}
                  onPress={() => self._autoClose(i)}
                  text={btn.text}
                  type={btn.type}
                  width={self.state.btnWidth}/>
              )
            })
          }
        </View>
      </View>
    )
  }
})

module.exports = Swipeout<commit_msg>respect backgroundColor prop on Swipeout<commit_after>var React = require('react-native')
var tweenState = require('react-tween-state')
var Dimensions = require('Dimensions')
var {PanResponder, TouchableHighlight, StyleSheet, Text, View} = React
var styles = require('./styles.js')

var SwipeoutBtn = React.createClass({
  getDefaultProps: function() {
    return {
      backgroundColor: null,
      color: null,
      height: 0,
      key: null,
      onPress: null,
      text: 'Click me',
      type: '',
      width: 0,
    }
  }
, render: function() {
    var btn = this.props
    var styleSwipeoutBtn = [styles.swipeoutBtn]
    var styleSwipeoutBtnText = [styles.swipeoutBtnText]
    styleSwipeoutBtn.push([{
      height: btn.height,
      width: btn.width,
    }])
    if (btn.type === 'delete') styleSwipeoutBtn.push(styles.colorDelete)
    else if (btn.type === 'primary') styleSwipeoutBtn.push(styles.colorPrimary)
    else if (btn.type === 'secondary') styleSwipeoutBtn.push(styles.colorSecondary)
    if (btn.backgroundColor) styleSwipeoutBtn.push([{ backgroundColor: btn.backgroundColor }])
    if (btn.color) styleSwipeoutBtnText.push([{ color: btn.color }])

    return  (
      <TouchableHighlight
        onPress={this.props.onPress}
        style={styles.swipeoutBtnTouchable}
      >
        <View style={styleSwipeoutBtn}>
          <Text style={styleSwipeoutBtnText}>{btn.text}</Text>
        </View>
      </TouchableHighlight>
    )
  }
})

var Swipeout = React.createClass({
  mixins: [tweenState.Mixin]
, getInitialState: function() {
    return {
      autoClose: this.props.autoClose || false,
      btnWidth: 0,
      btnsWidth: 0,
      contentHeight: 0,
      contentPos: 0,
      contentWidth: Dimensions.get('window').width,
      exposed: false,
      swiping: false,
      tweenDuration: 160,
      timeSwipeStart: null,
    }
  }
, componentWillMount: function() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
      onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
      onPanResponderGrant: this._handlePanResponderGrant,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this._handlePanResponderEnd,
    });
  }
, _handleStartShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
    return true;
  }
, _handleMoveShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
    return true;
  }
, _handlePanResponderGrant: function(e: Object, gestureState: Object) {
    this.refs.swipeoutContent.measure((ox, oy, width, height) => {
      this.setState({
        btnWidth: (width/5),
        btnsWidth: (width/5)*this.props.btns.length,
        contentHeight: height,
        contentWidth: width,
        swiping: true,
        timeSwipeStart: (new Date()).getTime(),
      })
    })
  }
, _handlePanResponderMove: function(e: Object, gestureState: Object) {
    var posX = gestureState.dx
    if (this.state.exposed) var posX = gestureState.dx - this.state.btnsWidth
    if (this.state.swiping) this.setState({ contentPos: Math.min(posX, 0) })
  }
, _handlePanResponderEnd: function(e: Object, gestureState: Object) {
    var timeDiff = (new Date()).getTime() - this.state.timeSwipeStart < 200
    var btnsWidth = -1*(this.state.btnsWidth)
    var contentWidth = this.state.contentWidth
    var posX = gestureState.dx
    var openX = -1*(contentWidth*0.33)
    var expose = posX < openX
    if (this.state.exposed) var expose = posX+openX < openX

    if (this.state.swiping) {
      if (timeDiff) {
        var expose = posX < openX/10
        this.tweenState('contentPos', {
          easing: tweenState.easingTypes.easeInOutQuad,
          duration: this.state.tweenDuration/2,
          endValue: expose ? btnsWidth : 0
        })
        if (expose) this.setState({ contentPos: btnsWidth, exposed: true })
        else this.setState({ contentPos: 0, exposed: false })
      } else {
        this.tweenState('contentPos', {
          easing: tweenState.easingTypes.easeInOutQuad,
          duration: this.state.tweenDuration,
          endValue: expose ? btnsWidth : 0
        })
        if (expose) this.setState({ contentPos: btnsWidth, exposed: true })
        else this.setState({ contentPos: 0, exposed: false })
      }
    }
    this.setState({ swiping: false })
  }
, _rubberBandEasing: function(value, lowerLimit) {
    if(value < lowerLimit) {
      return lowerLimit - Math.pow(lowerLimit - value, 0.85);
    }
    return value;
  }
, _autoClose: function(i) {
    var onPress = this.props.btns[i].onPress
    if (onPress) onPress()
    if (this.state.autoClose) {
      this.tweenState('contentPos', {
        easing: tweenState.easingTypes.easeInOutQuad,
        duration: this.state.tweenDuration,
        endValue: 0
      })
      this.setState({ exposed: false })
    }
  }
, render: function() {
    var self = this

    var styleSwipeout = [styles.swipeout]
    if (self.props.backgroundColor) {
      styleSwipeout.push([{ backgroundColor: self.props.backgroundColor }])
    }

    var styleSwipeoutMove = StyleSheet.create({
      swipeoutBtns: {
        left: Math.abs(self.state.contentWidth+ Math.max(self.state.btnsWidth*-1, self.getTweeningValue('contentPos'))),
      },
      swipeoutContent: {
        left: self._rubberBandEasing(self.getTweeningValue('contentPos'), self.state.btnsWidth*-1),
      }
    })

    var styleSwipeoutContent = [styles.swipeoutContent]
    styleSwipeoutContent.push(styleSwipeoutMove.swipeoutContent)

    var styleSwipeoutBtns = [styles.swipeoutBtns]
    styleSwipeoutBtns.push(styleSwipeoutMove.swipeoutBtns)

    return (
      <View style={styleSwipeout}>
        <View ref="swipeoutContent" style={styleSwipeoutContent} {...self._panResponder.panHandlers}>
          {self.props.children}
        </View>
        <View style={styleSwipeoutBtns}>
          {
            self.props.btns.map(function(btn, i){
              return (
                <SwipeoutBtn
                  backgroundColor={btn.backgroundColor}
                  color={btn.color}
                  height={self.state.contentHeight}
                  key={i}
                  onPress={() => self._autoClose(i)}
                  text={btn.text}
                  type={btn.type}
                  width={self.state.btnWidth}/>
              )
            })
          }
        </View>
      </View>
    )
  }
})

module.exports = Swipeout<|endoftext|>


<commit_before>var curlyfy = require('curlyfy');
var loaderUtils = require('loader-utils');

module.exports = function curlyfyLoader(source) {
  var query = loaderUtils.parseQuery(this.query);
  var options = {
    insertSemicolons: query.insertSemicolons == 'true'
  };
  return curlyfy(source, options);
};<commit_msg>Simplify options passing<commit_after>var curlyfy = require('curlyfy');
var loaderUtils = require('loader-utils');

module.exports = function curlyfyLoader(source) {
  var options = loaderUtils.parseQuery(this.query);
  return curlyfy(source, options);
};
<|endoftext|>