<commit_before>describe('#Geometry', function () {

    var container;
    var map;
    var center = new maptalks.Coordinate(118.846825, 32.046534);
    var layer;
    var context = {
        map:map,
        layer:layer
    };

    beforeEach(function () {
        var setups = COMMON_CREATE_MAP(center);
        container = setups.container;
        map = setups.map;
        layer = new maptalks.VectorLayer('canvas');
        map.addLayer(layer);
        context.map = map;
        context.layer = layer;
    });

    afterEach(function () {
        map.removeLayer(layer);
        REMOVE_CONTAINER(container);
    });

    it('constructor options', function () {
        it('some common options', function () {
            var symbol = {
                markerFile : 'file',
                markerWidth : 10,
                markerHeight : 15
            };
            var properties = {
                foo1 : 1,
                foo2 : 'test',
                foo3 : true
            };
            var id = '1';
            var marker = new maptalks.Marker([0, 0], {
                id : id,
                symbol : symbol,
                properties : properties
            });

            expect(marker.getProperties()).to.be.eql(properties);
            expect(marker.getSymbol()).to.be.eql(symbol);
            expect(marker.getId()).to.be.eql(id);
        });
    });

    // 测试所有类型Geometry的公共方法
    var geometries = GEN_GEOMETRIES_OF_ALL_TYPES();

    for (var i = 0, len = geometries.length; i < len; i++) {
        registerGeometryCommonTest.call(this, geometries[i], context);
    }

});
//测试Geometry的公共方法
function registerGeometryCommonTest(geometry, _context) {
    function setupGeometry() {
        // var layer = new maptalks.VectorLayer('common_test_layer');
        if (geometry.getLayer()) {
            geometry.remove();
        }
        _context.layer.addGeometry(geometry);
        // map.addLayer(layer);
    }

    function teardownGeometry() {
        geometry.remove();
        // map.removeLayer('common_test_layer');
    }

    var type = geometry.getType();
    context(type + ':getter and setters.', function () {
        it('id', function () {
            geometry.setId('id');
            var id = geometry.getId();
            expect(id).to.be('id');
            geometry.setId(null);
            expect(geometry.getId()).to.not.be.ok();
        });

        it('Layer', function () {
            expect(geometry.getLayer()).to.not.be.ok();
            var layer = new maptalks.VectorLayer('id');
            layer.addGeometry(geometry);
            expect(geometry.getLayer()).to.be.ok();
            //delete
            geometry.remove();
            expect(geometry.getLayer()).to.not.be.ok();
        });

        it('Map', function () {
            setupGeometry();

            expect(geometry.getMap()).to.be.ok();

            teardownGeometry();

            expect(geometry.getMap()).to.not.be.ok();
        });

        it('Type', function () {
            var type = geometry.getType();
            expect(type).to.not.be.empty();
        });

        it('flash', function (done) {
            geometry.flash(100, 4, function () {
                done();
            });
        });

        it('Properties', function () {
            var oldProps = geometry.getProperties();

            var props = { 'foo_num':1, 'foo_str':'str', 'foo_bool':false };
            geometry.setProperties(props);

            props = geometry.getProperties();
            expect(props).to.eql(props);

            geometry.setProperties(oldProps);
            expect(geometry.getProperties()).to.not.eql(props);
        });

    });

    context(type + ':can be measured.', function () {
        it('it has geodesic length', function () {
            var length = geometry.getLength();
            if (geometry instanceof maptalks.Marker) {
                expect(length === 0).to.be.ok();
            } else {
                expect(length > 0).to.be.ok();
            }

        });

        it('it has geodesic area', function () {
            var types = [maptalks.Polygon, maptalks.MultiPolygon];
            var area = geometry.getArea();
            var hit = false;
            for (var i = 0, len = types.length; i < len; i++) {
                if (geometry instanceof types[i]) {
                    hit = true;
                    break;
                }
            }
            if (!hit) {
                expect(area === 0).to.be.ok();
            } else {
                expect(area > 0).to.be.ok();
            }

        });

        it('it has extent', function () {
            setupGeometry();

            var extent = geometry.getExtent();
            expect(extent).to.be.a(maptalks.Extent);
            expect(extent).to.not.be.empty();

            teardownGeometry();
        });

        it('it has size', function () {
            setupGeometry();

            var size = geometry.getSize();
            expect(size).to.be.a(maptalks.Size);
            expect(size.width).to.be.above(0);
            expect(size.height).to.be.above(0);

            teardownGeometry();
        });

        it('it has center', function () {
            var center = geometry.getCenter();
            expect(center).to.be.a(maptalks.Coordinate);
            expect(center.x).to.be.a('number');
            expect(center.y).to.be.a('number');

            setupGeometry();

            center = geometry.getCenter();
            expect(center).to.be.a(maptalks.Coordinate);
            expect(center.x).to.be.a('number');
            expect(center.y).to.be.a('number');

            teardownGeometry();
        });
    });

    context(type + ':can show and hide.', function () {
        it('show and hide', function () {
            geometry.show();
            expect(geometry.isVisible()).to.be.ok();
            geometry.hide();
            expect(geometry.isVisible()).to.not.be.ok();

            setupGeometry();

            geometry.show();
            expect(geometry.isVisible()).to.be.ok();
            geometry.hide();
            expect(geometry.isVisible()).to.not.be.ok();

            teardownGeometry();

            geometry.show();
            expect(geometry.isVisible()).to.be.ok();
        });
    });

    context(type + ':copy', function () {
        it('copy', function () {
            var json = geometry.toJSON();

            var cloned = geometry.copy();

            var clonedJson = cloned.toJSON();

            expect(clonedJson).to.eql(json);
        });
    });

    // context(type+':has crs',function() {
    //     it ('can read crs from json',function() {
    //         var json = geometry.toGeoJSON();
    //         json.crs = {
    //             "type" : "cnCoordinateType",
    //             "properties" : {
    //                 "name" : "gcj02"
    //             }
    //         };
    //         var parsed = maptalks.GeoJSON.toGeometry(json);

    //         expect(parsed.getCRS()).to.eql(json.crs);
    //     });

    //     it ('has crs',function() {
    //         var coordinateType = maptalks.CRS.GCJ02;
    //         var json = geometry.setCRS(coordinateType).toGeoJSON();
    //         expect(json['crs']).to.be.ok();
    //         expect(json['crs']).to.eql({"type":"cnCoordinateType","properties":{"name":"gcj02"}});
    //     });
    // });

    context(type + ':remove', function () {
        it('remove from layer', function () {
            //layer not on map
            var layer = new maptalks.VectorLayer('svg');
            layer.addGeometry(geometry);
            expect(geometry.getLayer()).to.be.ok();
            expect(geometry.getMap()).to.not.be.ok();
            geometry.remove();
            expect(geometry.getLayer()).to.not.be.ok();

            setupGeometry();

            expect(geometry.getLayer()).to.be.ok();
            expect(geometry.getMap()).to.be.ok();
            geometry.remove();
            expect(geometry.getLayer()).to.not.be.ok();

            var canvasLayer = new maptalks.VectorLayer('event_test_canvas', { 'render':'canvas' });
            canvasLayer.addGeometry(geometry);
            _context.map.addLayer(canvasLayer);

            expect(geometry.getLayer()).to.be.ok();
            expect(geometry.getMap()).to.be.ok();
            geometry.remove();
            expect(geometry.getLayer()).to.not.be.ok();

            teardownGeometry();
        });
    });

    context(type + ':some internal methods should be tested.', function () {
        it('painter', function () {
            setupGeometry();

            var painter = geometry._getPainter();
            expect(painter).to.be.ok();
            geometry.remove();

            var canvasLayer = new maptalks.VectorLayer('event_test_canvas', { 'render':'canvas' });
            canvasLayer.addGeometry(geometry);
            _context.map.addLayer(canvasLayer);

            painter = geometry._getPainter();
            expect(painter).to.be.ok();

            teardownGeometry();
        });

        it('getExternalResources', function () {
            var symbol, resource;
            var type = geometry.getType();
            if (type === 'Point') {
                symbol = {
                    'markerFile':'http://foo.com/foo.png'
                };
                geometry.setSymbol(symbol);
                resource = geometry._getExternalResources();
                expect(resource).to.have.length(1);
                expect(resource[0][0]).to.be(symbol['markerFile']);
            } else {
                symbol = {
                    'polygonPatternFile':'url(\'http://foo.com/foo.png\')',
                    'linePatternFile':'url(\'http://foo.com/foo2.png\')',
                };
                geometry.setSymbol(symbol);
                resource = geometry._getExternalResources();
                expect(resource).to.have.length(2);
                expect(resource[0][0]).to.be('http://foo.com/foo.png');
                expect(resource[1][0]).to.be('http://foo.com/foo2.png');
            }
        });

        it('getProjection', function () {
            var projection = geometry._getProjection();
            expect(projection).not.to.be.ok();

            setupGeometry();

            projection = geometry._getProjection();
            expect(projection.code).to.be(_context.map.getProjection().code);

            teardownGeometry();
        });

        it('getMeasurer', function () {
            var measurer = geometry._getMeasurer();
            expect(measurer).to.be(maptalks.measurer.WGS84Sphere);

            geometry.config('measure', 'identity');

            measurer = geometry._getMeasurer();
            expect(measurer).to.be(maptalks.measurer.Identity);

            geometry.config('measure', 'baidu');

            measurer = geometry._getMeasurer();
            expect(measurer).to.be(maptalks.measurer.BaiduSphere);
        });
    });
    var spy;
    context(type + ':map events listeners', function () {
        it('removeZoomCache', function () {
            var map = _context.map;
            map.config('zoomAnimation', false);
            setupGeometry();
            spy = sinon.spy(geometry, '_removeZoomCache');
            map.zoomOut();
            expect(spy.called).to.be.ok();
        });
    });
}
<commit_msg>fix spec<commit_after>describe('#Geometry', function () {

    var container;
    var map;
    var center = new maptalks.Coordinate(118.846825, 32.046534);
    var layer;
    var context = {
        map:map,
        layer:layer
    };

    beforeEach(function () {
        var setups = COMMON_CREATE_MAP(center);
        container = setups.container;
        map = setups.map;
        layer = new maptalks.VectorLayer('canvas');
        map.addLayer(layer);
        context.map = map;
        context.layer = layer;
    });

    afterEach(function () {
        map.removeLayer(layer);
        REMOVE_CONTAINER(container);
    });

    it('constructor options', function () {
        it('some common options', function () {
            var symbol = {
                markerFile : 'file',
                markerWidth : 10,
                markerHeight : 15
            };
            var properties = {
                foo1 : 1,
                foo2 : 'test',
                foo3 : true
            };
            var id = '1';
            var marker = new maptalks.Marker([0, 0], {
                id : id,
                symbol : symbol,
                properties : properties
            });

            expect(marker.getProperties()).to.be.eql(properties);
            expect(marker.getSymbol()).to.be.eql(symbol);
            expect(marker.getId()).to.be.eql(id);
        });
    });

    // 测试所有类型Geometry的公共方法
    var geometries = GEN_GEOMETRIES_OF_ALL_TYPES();

    for (var i = 0, len = geometries.length; i < len; i++) {
        registerGeometryCommonTest.call(this, geometries[i], context);
    }

});
//测试Geometry的公共方法
function registerGeometryCommonTest(geometry, _context) {
    function setupGeometry() {
        // var layer = new maptalks.VectorLayer('common_test_layer');
        if (geometry.getLayer()) {
            geometry.remove();
        }
        _context.layer.addGeometry(geometry);
        // map.addLayer(layer);
    }

    function teardownGeometry() {
        geometry.remove();
        // map.removeLayer('common_test_layer');
    }

    var type = geometry.getType();
    context(type + ':getter and setters.', function () {
        it('id', function () {
            geometry.setId('id');
            var id = geometry.getId();
            expect(id).to.be('id');
            geometry.setId(null);
            expect(geometry.getId()).to.not.be.ok();
        });

        it('Layer', function () {
            expect(geometry.getLayer()).to.not.be.ok();
            var layer = new maptalks.VectorLayer('id');
            layer.addGeometry(geometry);
            expect(geometry.getLayer()).to.be.ok();
            //delete
            geometry.remove();
            expect(geometry.getLayer()).to.not.be.ok();
        });

        it('Map', function () {
            setupGeometry();

            expect(geometry.getMap()).to.be.ok();

            teardownGeometry();

            expect(geometry.getMap()).to.not.be.ok();
        });

        it('Type', function () {
            var type = geometry.getType();
            expect(type).to.not.be.empty();
        });

        it('flash', function (done) {
            geometry.flash(100, 4, function () {
                done();
            });
        });

        it('Properties', function () {
            var oldProps = geometry.getProperties();

            var props = { 'foo_num':1, 'foo_str':'str', 'foo_bool':false };
            geometry.setProperties(props);

            props = geometry.getProperties();
            expect(props).to.eql(props);

            geometry.setProperties(oldProps);
            expect(geometry.getProperties()).to.not.eql(props);
        });

    });

    context(type + ':can be measured.', function () {
        it('it has geodesic length', function () {
            var length = geometry.getLength();
            if (geometry instanceof maptalks.Marker) {
                expect(length === 0).to.be.ok();
            } else {
                expect(length > 0).to.be.ok();
            }

        });

        it('it has geodesic area', function () {
            var types = [maptalks.Polygon, maptalks.MultiPolygon];
            var area = geometry.getArea();
            var hit = false;
            for (var i = 0, len = types.length; i < len; i++) {
                if (geometry instanceof types[i]) {
                    hit = true;
                    break;
                }
            }
            if (!hit) {
                expect(area === 0).to.be.ok();
            } else {
                expect(area > 0).to.be.ok();
            }

        });

        it('it has extent', function () {
            setupGeometry();

            var extent = geometry.getExtent();
            expect(extent).to.be.a(maptalks.Extent);
            expect(extent).to.not.be.empty();

            teardownGeometry();
        });

        it('it has size', function () {
            setupGeometry();

            var size = geometry.getSize();
            expect(size).to.be.a(maptalks.Size);
            expect(size.width).to.be.above(0);
            expect(size.height).to.be.above(0);

            teardownGeometry();
        });

        it('it has center', function () {
            var center = geometry.getCenter();
            expect(center).to.be.a(maptalks.Coordinate);
            expect(center.x).to.be.a('number');
            expect(center.y).to.be.a('number');

            setupGeometry();

            center = geometry.getCenter();
            expect(center).to.be.a(maptalks.Coordinate);
            expect(center.x).to.be.a('number');
            expect(center.y).to.be.a('number');

            teardownGeometry();
        });
    });

    context(type + ':can show and hide.', function () {
        it('show and hide', function () {
            geometry.show();
            expect(geometry.isVisible()).to.be.ok();
            geometry.hide();
            expect(geometry.isVisible()).to.not.be.ok();

            setupGeometry();

            geometry.show();
            expect(geometry.isVisible()).to.be.ok();
            geometry.hide();
            expect(geometry.isVisible()).to.not.be.ok();

            teardownGeometry();

            geometry.show();
            expect(geometry.isVisible()).to.be.ok();
        });
    });

    context(type + ':copy', function () {
        it('copy', function () {
            var json = geometry.toJSON();

            var cloned = geometry.copy();

            var clonedJson = cloned.toJSON();

            expect(clonedJson).to.eql(json);
        });
    });

    // context(type+':has crs',function() {
    //     it ('can read crs from json',function() {
    //         var json = geometry.toGeoJSON();
    //         json.crs = {
    //             "type" : "cnCoordinateType",
    //             "properties" : {
    //                 "name" : "gcj02"
    //             }
    //         };
    //         var parsed = maptalks.GeoJSON.toGeometry(json);

    //         expect(parsed.getCRS()).to.eql(json.crs);
    //     });

    //     it ('has crs',function() {
    //         var coordinateType = maptalks.CRS.GCJ02;
    //         var json = geometry.setCRS(coordinateType).toGeoJSON();
    //         expect(json['crs']).to.be.ok();
    //         expect(json['crs']).to.eql({"type":"cnCoordinateType","properties":{"name":"gcj02"}});
    //     });
    // });

    context(type + ':remove', function () {
        it('remove from layer', function () {
            //layer not on map
            var layer = new maptalks.VectorLayer('svg');
            layer.addGeometry(geometry);
            expect(geometry.getLayer()).to.be.ok();
            expect(geometry.getMap()).to.not.be.ok();
            geometry.remove();
            expect(geometry.getLayer()).to.not.be.ok();

            setupGeometry();

            expect(geometry.getLayer()).to.be.ok();
            expect(geometry.getMap()).to.be.ok();
            geometry.remove();
            expect(geometry.getLayer()).to.not.be.ok();

            var canvasLayer = new maptalks.VectorLayer('event_test_canvas', { 'render':'canvas' });
            canvasLayer.addGeometry(geometry);
            _context.map.addLayer(canvasLayer);

            expect(geometry.getLayer()).to.be.ok();
            expect(geometry.getMap()).to.be.ok();
            geometry.remove();
            expect(geometry.getLayer()).to.not.be.ok();

            teardownGeometry();
        });
    });

    context(type + ':some internal methods should be tested.', function () {
        it('painter', function () {
            setupGeometry();

            var painter = geometry._getPainter();
            expect(painter).to.be.ok();
            geometry.remove();

            var canvasLayer = new maptalks.VectorLayer('event_test_canvas', { 'render':'canvas' });
            canvasLayer.addGeometry(geometry);
            _context.map.addLayer(canvasLayer);

            painter = geometry._getPainter();
            expect(painter).to.be.ok();

            teardownGeometry();
        });

        it('getExternalResources', function () {
            var symbol, resource;
            var type = geometry.getType();
            if (type === 'Point') {
                symbol = {
                    'markerFile':'http://foo.com/foo.png'
                };
                geometry.setSymbol(symbol);
                resource = geometry._getExternalResources();
                expect(resource).to.have.length(1);
                expect(resource[0][0]).to.be(symbol['markerFile']);
            } else {
                symbol = {
                    'polygonPatternFile':'url(\'http://foo.com/foo.png\')',
                    'linePatternFile':'url(\'http://foo.com/foo2.png\')',
                };
                geometry.setSymbol(symbol);
                resource = geometry._getExternalResources();
                expect(resource).to.have.length(2);
                expect(resource[0][0]).to.be('http://foo.com/foo.png');
                expect(resource[1][0]).to.be('http://foo.com/foo2.png');
            }
        });

        it('getProjection', function () {
            var projection = geometry._getProjection();
            expect(projection).not.to.be.ok();

            setupGeometry();

            projection = geometry._getProjection();
            expect(projection.code).to.be(_context.map.getProjection().code);

            teardownGeometry();
        });

        it('getMeasurer', function () {
            var measurer = geometry._getMeasurer();
            expect(measurer).to.be(maptalks.measurer.WGS84Sphere);

            geometry.config('measure', 'identity');

            measurer = geometry._getMeasurer();
            expect(measurer).to.be(maptalks.measurer.Identity);

            geometry.config('measure', 'baidu');

            measurer = geometry._getMeasurer();
            expect(measurer).to.be(maptalks.measurer.BaiduSphere);
        });
    });
}
<|endoftext|>


<commit_before>module.exports = function(generator) {
  const { props } = generator;
  const lib = props.src;
  const [ packager, version ] = props.packager.split('@');
  const pkg = {
    name: props.name,
    description: props.description,
    version: '0.0.0',
    homepage: '',
    main: lib,
    keywords: [
      'feathers'
    ],
    author: {
      name: generator.user.git.name(),
      email: generator.user.git.email()
    },
    contributors: [],
    bugs: {},
    directories: {
      lib,
      test: 'test/'
    },
    engines: {
      node: '>= 6.0.0',
      [packager]: version
    },
    'scripts': {
      test: 'npm run eslint && npm run mocha',
      eslint: `eslint ${lib}/. test/. --config .eslintrc.json`,
      start: `node ${lib}/`,
      mocha: 'mocha test/ --recursive --exit'
    }
  };

  return pkg;
};
<commit_msg>Use the selected packager to run commands (#297)<commit_after>module.exports = function(generator) {
  const { props } = generator;
  const lib = props.src;
  const [ packager, version ] = props.packager.split('@');
  const pkg = {
    name: props.name,
    description: props.description,
    version: '0.0.0',
    homepage: '',
    main: lib,
    keywords: [
      'feathers'
    ],
    author: {
      name: generator.user.git.name(),
      email: generator.user.git.email()
    },
    contributors: [],
    bugs: {},
    directories: {
      lib,
      test: 'test/'
    },
    engines: {
      node: '>= 6.0.0',
      [packager]: version
    },
    'scripts': {
      test: `${packager} run eslint && ${packager} run mocha`,
      eslint: `eslint ${lib}/. test/. --config .eslintrc.json`,
      start: `node ${lib}/`,
      mocha: 'mocha test/ --recursive --exit'
    }
  };

  return pkg;
};
<|endoftext|>


<commit_before>define([
    'jquery',
    '/customize/login.js',
    '/common/cryptpad-common.js',
    '/common/test.js',
    '/customize/credential.js', // preloaded for login.js
    '/common/common-interface.js',
    '/common/common-util.js',
    '/common/common-realtime.js',
    '/common/common-constants.js',
    '/common/common-feedback.js',
    '/common/outer/local-store.js',

    'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
], function ($, Login, Cryptpad, Test, Cred, UI, Util, Realtime, Constants, Feedback, LocalStore) {
    var Messages = Cryptpad.Messages;

    $(function () {
        var $main = $('#mainBlock');

        // main block is hidden in case javascript is disabled
        $main.removeClass('hidden');

        // Make sure we don't display non-translated content (empty button)
        $main.find('#data').removeClass('hidden');

        if (LocalStore.isLoggedIn()) {
            // already logged in, redirect to drive
            document.location.href = '/drive/';
            return;
        } else {
            $main.find('#userForm').removeClass('hidden');
        }

        // text and password input fields
        var $uname = $('#username');
        var $passwd = $('#password');
        var $confirm = $('#password-confirm');

        if (sessionStorage.login_user) {
            delete sessionStorage.login_user;
            $uname.val(sessionStorage.login_user);
        }

        [ $uname, $passwd, $confirm]
        .some(function ($el) { if (!$el.val()) { $el.focus(); return true; } });

        // checkboxes
        var $checkImport = $('#import-recent');
        var $checkAcceptTerms = $('#accept-terms');

        var $register = $('button#register');

        var registering = false;
        var test;

        var I_REALLY_WANT_TO_USE_MY_EMAIL_FOR_MY_USERNAME = false;

        var registerClick = function () {
            var uname = $uname.val();
            var passwd = $passwd.val();
            var confirmPassword = $confirm.val();

            var shouldImport = $checkImport[0].checked;
            var doesAccept = $checkAcceptTerms[0].checked;

            if (Cred.isEmail(uname) && !I_REALLY_WANT_TO_USE_MY_EMAIL_FOR_MY_USERNAME) {
                var warning = [
                    Messages.register_emailWarning0,
                    Messages.register_emailWarning1,
                    Messages.register_emailWarning2,
                    Messages.register_emailWarning3,
                ].join('

');

                Feedback.send("EMAIL_USERNAME_WARNING", true);

                return void UI.confirm(warning, function (yes) {
                    if (!yes) { return; }
                    I_REALLY_WANT_TO_USE_MY_EMAIL_FOR_MY_USERNAME = true;
                    registerClick();
                }, {}, true);
            }

            /* basic validation */
            if (!Cred.isLongEnoughPassword(passwd)) {
                var warning = Messages._getKey('register_passwordTooShort', [
                    Cred.MINIMUM_PASSWORD_LENGTH
                ]);
                return void UI.alert(warning, function () {
                    registering = false;
                });
            }

            if (passwd !== confirmPassword) { // do their passwords match?
                return void UI.alert(Messages.register_passwordsDontMatch);
            }

            if (!doesAccept) { // do they accept the terms of service?
                return void UI.alert(Messages.register_mustAcceptTerms);
            }

            setTimeout(function () {
            UI.confirm("
" + Messages.register_warning + "
",
            function (yes) {
                if (!yes) { return; }

                Login.loginOrRegisterUI(uname, passwd, true, shouldImport, Test.testing, function () {
                    if (test) {
                        localStorage.clear();
                        test.pass();
                        return true;
                    }
                });
                registering = true;
            }, {
                ok: Messages.register_writtenPassword,
                cancel: Messages.register_cancel,
                cancelClass: 'safe',
                okClass: 'danger',
                reverseOrder: true,
                done: function ($dialog) {
                    $dialog.find('> div').addClass('half');
                },
            }, true);
            }, 150);
        };

        $register.click(registerClick);

        var clickRegister = Util.notAgainForAnother(function () {
            $register.click();
        }, 500);

        $register.on('keypress', function (e) {
            if (e.which === 13) {
                e.preventDefault();
                e.stopPropagation();
                return clickRegister();
            }
        });

        Test(function (t) {
            test = t;
            $uname.val('testuser');
            $passwd.val('testtest');
            $confirm.val('testtest');
            $checkImport[0].checked = true;
            $checkAcceptTerms[0].checked = true;
            $register.click();

            window.setTimeout(function () {
                UI.findOKButton().click();
            }, 1000);
        });
    });
});
<commit_msg>lint compliance<commit_after>define([
    'jquery',
    '/customize/login.js',
    '/common/cryptpad-common.js',
    '/common/test.js',
    '/customize/credential.js', // preloaded for login.js
    '/common/common-interface.js',
    '/common/common-util.js',
    '/common/common-realtime.js',
    '/common/common-constants.js',
    '/common/common-feedback.js',
    '/common/outer/local-store.js',

    'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
], function ($, Login, Cryptpad, Test, Cred, UI, Util, Realtime, Constants, Feedback, LocalStore) {
    var Messages = Cryptpad.Messages;

    $(function () {
        var $main = $('#mainBlock');

        // main block is hidden in case javascript is disabled
        $main.removeClass('hidden');

        // Make sure we don't display non-translated content (empty button)
        $main.find('#data').removeClass('hidden');

        if (LocalStore.isLoggedIn()) {
            // already logged in, redirect to drive
            document.location.href = '/drive/';
            return;
        } else {
            $main.find('#userForm').removeClass('hidden');
        }

        // text and password input fields
        var $uname = $('#username');
        var $passwd = $('#password');
        var $confirm = $('#password-confirm');

        if (sessionStorage.login_user) {
            delete sessionStorage.login_user;
            $uname.val(sessionStorage.login_user);
        }

        [ $uname, $passwd, $confirm]
        .some(function ($el) { if (!$el.val()) { $el.focus(); return true; } });

        // checkboxes
        var $checkImport = $('#import-recent');
        var $checkAcceptTerms = $('#accept-terms');

        var $register = $('button#register');

        var registering = false;
        var test;

        var I_REALLY_WANT_TO_USE_MY_EMAIL_FOR_MY_USERNAME = false;

        var registerClick = function () {
            var uname = $uname.val();
            var passwd = $passwd.val();
            var confirmPassword = $confirm.val();

            var shouldImport = $checkImport[0].checked;
            var doesAccept = $checkAcceptTerms[0].checked;

            if (Cred.isEmail(uname) && !I_REALLY_WANT_TO_USE_MY_EMAIL_FOR_MY_USERNAME) {
                var emailWarning = [
                    Messages.register_emailWarning0,
                    Messages.register_emailWarning1,
                    Messages.register_emailWarning2,
                    Messages.register_emailWarning3,
                ].join('

');

                Feedback.send("EMAIL_USERNAME_WARNING", true);

                return void UI.confirm(emailWarning, function (yes) {
                    if (!yes) { return; }
                    I_REALLY_WANT_TO_USE_MY_EMAIL_FOR_MY_USERNAME = true;
                    registerClick();
                }, {}, true);
            }

            /* basic validation */
            if (!Cred.isLongEnoughPassword(passwd)) {
                var warning = Messages._getKey('register_passwordTooShort', [
                    Cred.MINIMUM_PASSWORD_LENGTH
                ]);
                return void UI.alert(warning, function () {
                    registering = false;
                });
            }

            if (passwd !== confirmPassword) { // do their passwords match?
                return void UI.alert(Messages.register_passwordsDontMatch);
            }

            if (!doesAccept) { // do they accept the terms of service?
                return void UI.alert(Messages.register_mustAcceptTerms);
            }

            setTimeout(function () {
            UI.confirm("
" + Messages.register_warning + "
",
            function (yes) {
                if (!yes) { return; }

                Login.loginOrRegisterUI(uname, passwd, true, shouldImport, Test.testing, function () {
                    if (test) {
                        localStorage.clear();
                        test.pass();
                        return true;
                    }
                });
                registering = true;
            }, {
                ok: Messages.register_writtenPassword,
                cancel: Messages.register_cancel,
                cancelClass: 'safe',
                okClass: 'danger',
                reverseOrder: true,
                done: function ($dialog) {
                    $dialog.find('> div').addClass('half');
                },
            }, true);
            }, 150);
        };

        $register.click(registerClick);

        var clickRegister = Util.notAgainForAnother(function () {
            $register.click();
        }, 500);

        $register.on('keypress', function (e) {
            if (e.which === 13) {
                e.preventDefault();
                e.stopPropagation();
                return clickRegister();
            }
        });

        Test(function (t) {
            test = t;
            $uname.val('testuser');
            $passwd.val('testtest');
            $confirm.val('testtest');
            $checkImport[0].checked = true;
            $checkAcceptTerms[0].checked = true;
            $register.click();

            window.setTimeout(function () {
                UI.findOKButton().click();
            }, 1000);
        });
    });
});
<|endoftext|>


<commit_before>var hasTagGenerator = require('../src/hashTagGenerator');
require('chai').should();

describe.only('Hash tag generator', function () {
    it('should start with #', function () {
        var actual = hasTagGenerator('wow');

        actual.charAt(0).should.be.equal('#')
    });

    it('should concat words', function () {
        var actual = hasTagGenerator('Привет Dump 2016');

        actual.should.be.equal('#ПриветDump2016');
    });

    it('should normalize words', function () {
        var actual = hasTagGenerator('hello DUMP');

        actual.should.be.equal('#HelloDump');
    });

    it('should clean extra symbols', function () {
        var actual = hasTagGenerator('#@%my-ha-ha!');

        actual.should.be.equal('#MyHaHa');
    });

    it('should failed', function () {
        true.should.be.false;
    });
});
<commit_msg>presentation example<commit_after>var hasTagGenerator = require('../src/hashTagGenerator');
require('chai').should();

describe.only('Hash tag generator', function () {
    it('should start with #', function () {
        var actual = hasTagGenerator('wow');

        actual.charAt(0).should.be.equal('#')
    });

    it('should concat words', function () {
        var actual = hasTagGenerator('Привет Dump 2016');

        actual.should.be.equal('#ПриветDump2016');
    });

    it('should normalize words', function () {
        var actual = hasTagGenerator('hello DUMP');

        actual.should.be.equal('#HelloDump');
    });

    it('should clean extra symbols', function () {
        var actual = hasTagGenerator('#@%my-ha-ha!');

        actual.should.be.equal('#MyHaHa');
    });

    // it('should failed', function () {
    //     true.should.be.false;
    // });
});
<|endoftext|>


<commit_before>const express = require('express');
const db = require('../models');
const router = express.Router();

router.post('/', (req, res) => {
  const { dishesName, dishesDescription, RestaurantId } = req.body;

  models.Dish.build({ name: dishesName, discription: dishesDescription, RestaurantId }).save()
    .then(() => res.json({ success: true }))
    .catch((err) => res.status(500).json({ errors: err }));
});

router.put('/', (req, res) => {
  console.log(req.body)
  const { id, name, description, img  } = req.body;
  db.Dish.findById(id).then(
    function(dish){
      dish.update({
        name: name,
        description: description,
      }).then((dish) => res.status(200).json({dish: dish}));
    }
  );
})

module.exports = router;
<commit_msg>remove console.log<commit_after>const express = require('express');
const db = require('../models');
const router = express.Router();

router.post('/', (req, res) => {
  const { dishesName, dishesDescription, RestaurantId } = req.body;

  models.Dish.build({ name: dishesName, discription: dishesDescription, RestaurantId }).save()
    .then(() => res.json({ success: true }))
    .catch((err) => res.status(500).json({ errors: err }));
});

router.put('/', (req, res) => {
  const { id, name, description, img  } = req.body;
  db.Dish.findById(id).then(
    function(dish){
      dish.update({
        name: name,
        description: description,
      }).then((dish) => res.status(200).json({dish: dish}));
    }
  );
})

module.exports = router;
<|endoftext|>


<commit_before>import {compose} from 'compose'
import {connect, select} from 'store'
import {msg} from 'translate'
import React from 'react'
import format from 'format'
import styles from './userResources.module.css'

const mapStateToProps = () => ({
    userReport: select('user.currentUserReport'),
})

class UserResources extends React.Component {
    render() {
        const {spending} = this.props.userReport
        return (

                        {msg('user.report.resources.quota')}
                        {msg('user.report.resources.used')}

                        {msg('user.report.resources.monthlyInstance')}
                        {format.dollars(spending.monthlyInstanceBudget)}
                        {format.dollars(spending.monthlyInstanceSpending)}
                        <PercentCell used={spending.monthlyInstanceSpending} budget={spending.monthlyInstanceBudget}/>

                        {msg('user.report.resources.monthlyStorage')}
                        {format.dollars(spending.monthlyStorageBudget)}
                        {format.dollars(spending.monthlyStorageSpending)}
                        <PercentCell
                            used={spending.monthlyStorageSpending}
                            budget={spending.monthlyStorageBudget}
                            level={spending.projectedStorageSpending > spending.monthlyStorageBudget
                                ? 'medium'
                                : undefined
                            }/>

                        {msg('user.report.resources.storage')}
                        {format.number({value: spending.storageQuota, scale: 'G', unit: 'B'})}
                        {format.number({value: spending.storageUsed, scale: 'G', unit: 'B'})}
                        <PercentCell used={spending.storageUsed} budget={spending.storageQuota}/>

        )
    }
}

export default compose(
    UserResources,
    connect(mapStateToProps)
)

const PercentCell = ({used, budget, level=null}) => {
    const ratio = used / budget
    if (!level) {
        level = 'high'
        if (ratio < 0.75)
            level = 'low'
        else if (ratio < 1)
            level = 'medium'
    }
    return
        {format.percent(used, budget, 0)}

}
<commit_msg>Made sure highest level of spending warning is used.<commit_after>import {compose} from 'compose'
import {connect, select} from 'store'
import {msg} from 'translate'
import React from 'react'
import format from 'format'
import styles from './userResources.module.css'

const mapStateToProps = () => ({
    userReport: select('user.currentUserReport'),
})

class UserResources extends React.Component {
    render() {
        const {spending} = this.props.userReport
        return (

                        {msg('user.report.resources.quota')}
                        {msg('user.report.resources.used')}

                        {msg('user.report.resources.monthlyInstance')}
                        {format.dollars(spending.monthlyInstanceBudget)}
                        {format.dollars(spending.monthlyInstanceSpending)}
                        <PercentCell used={spending.monthlyInstanceSpending} budget={spending.monthlyInstanceBudget}/>

                        {msg('user.report.resources.monthlyStorage')}
                        {format.dollars(spending.monthlyStorageBudget)}
                        {format.dollars(spending.monthlyStorageSpending)}
                        <PercentCell
                            used={spending.monthlyStorageSpending}
                            budget={spending.monthlyStorageBudget}
                            level={spending.projectedStorageSpending > spending.monthlyStorageBudget
                                ? 'medium'
                                : undefined
                            }/>

                        {msg('user.report.resources.storage')}
                        {format.number({value: spending.storageQuota, scale: 'G', unit: 'B'})}
                        {format.number({value: spending.storageUsed, scale: 'G', unit: 'B'})}
                        <PercentCell used={spending.storageUsed} budget={spending.storageQuota}/>

        )
    }
}

export default compose(
    UserResources,
    connect(mapStateToProps)
)

const PercentCell = ({used, budget, level=null}) => {
    const ratio = used / budget
        if (ratio >= 1)
            level = 'high'
        else if (ratio > 0.75 && level !== 'high')
            level = 'medium'
        else if (!level)
            level = 'low'
    return
        {format.percent(used, budget, 0)}

}
<|endoftext|>


<commit_before>/**
 * Grunt tasks:
 * - grunt                   : The default task. Alias for `grunt serve` task below
 * - grunt serve             : watch files and run a static server
 * - grunt watcher           : watch files without static server
 * - grunt compile           : compile scss, js & compress images
 * - grunt compile --release : same as above, but compress CSS as well
 * - grunt images            : compress all non-grunticon images & then run `grunt icons`
 * - grunt test              : run jshint and scsslint
 */

module.exports = function (grunt) {
	'use strict';

	require('time-grunt')(grunt); // Record how long tasks take

	var options = {
		pkg: require('./package'), // <%%=pkg.name%>
		<%
		if (statix) { %>
		site: grunt.file.readYAML('statix/src/data/site.yml'),<%
		} %>

		// Global Grunt vars. Edit this file to change vars
		config : require('./_grunt-configs/config.js')
	};

	// Load grunt tasks automatically
	require('load-grunt-tasks')(grunt, {pattern: ["grunt-*"<%
		if (statix) {
			%>, "assemble"<%
		}%>
	]});

	// Load grunt configurations automatically
	var configs = require('load-grunt-configs')(grunt, options);

	// Define the configuration for all the tasks
	grunt.initConfig(configs);

	/**
	 * The tasks
	 */

	// grunt
	grunt.registerTask('default', ['serve']);

	// grunt serve
	grunt.registerTask('serve', [
		'compile',
		'browserSync:serve',
		'watch',
	]);

	// grunt watcher
	grunt.registerTask('watcher', [
		'compile',
		'watch',
	]);

	// grunt compile
	grunt.registerTask('compile', [
		'browserify',
		'postscss',
		'images',<%
		if (statix) {%>
		'copy:statix',
		'assemble',<%
		} %><%
		if (shims) {%>,
		'shimly',<%
		} %><%
		if (modernizr || shims) {%>
		'copy:jsStandalone',<%
		} %>
	]);

	// grunt start
	grunt.registerTask('start', function() {
		var opn = require('opn');
		opn('http://trykickoff.com/learn/checklist.html');
	});<%

	if (styleguide) { %>

	// grunt styleguide
	grunt.registerTask('styleguide', [
		'compile',
		'browserSync:styleguide',
		'watch',
	]);<%
	} %>

	// grunt images
	grunt.registerTask('images', [
		'newer:imagemin:images',
	]);

	/**
	 * grunt test
	 */
	grunt.registerTask('test', [
		'eslint',
		'scsslint',
	]);
};
<commit_msg>docs: fix gruntfile comments<commit_after>/**
 * Grunt tasks:
 * - grunt                   : The default task. Alias for `grunt serve` task below
 * - grunt serve             : watch files and run a static server
 * - grunt watcher           : watch files without static server
 * - grunt compile           : compile scss, js & compress images
 * - grunt compile --release : same as above, but compress CSS as well
 * - grunt styleguide        : shortcut to preview the styleguide
 * - grunt images            : compress all images
 * - grunt test              : run jshint and scsslint
 */

module.exports = function (grunt) {
	'use strict';

	require('time-grunt')(grunt); // Record how long tasks take

	var options = {
		pkg: require('./package'), // <%%=pkg.name%>
		<%
		if (statix) { %>
		site: grunt.file.readYAML('statix/src/data/site.yml'),<%
		} %>

		// Global Grunt vars. Edit this file to change vars
		config : require('./_grunt-configs/config.js')
	};

	// Load grunt tasks automatically
	require('load-grunt-tasks')(grunt, {pattern: ["grunt-*"<%
		if (statix) {
			%>, "assemble"<%
		}%>
	]});

	// Load grunt configurations automatically
	var configs = require('load-grunt-configs')(grunt, options);

	// Define the configuration for all the tasks
	grunt.initConfig(configs);

	/**
	 * The tasks
	 */

	// grunt
	grunt.registerTask('default', ['serve']);

	// grunt serve
	grunt.registerTask('serve', [
		'compile',
		'browserSync:serve',
		'watch',
	]);

	// grunt watcher
	grunt.registerTask('watcher', [
		'compile',
		'watch',
	]);

	// grunt compile
	grunt.registerTask('compile', [
		'browserify',
		'postscss',
		'images',<%
		if (statix) {%>
		'copy:statix',
		'assemble',<%
		} %><%
		if (shims) {%>,
		'shimly',<%
		} %><%
		if (modernizr || shims) {%>
		'copy:jsStandalone',<%
		} %>
	]);

	// grunt start
	grunt.registerTask('start', function() {
		var opn = require('opn');
		opn('http://trykickoff.com/learn/checklist.html');
	});<%

	if (styleguide) { %>

	// grunt styleguide
	grunt.registerTask('styleguide', [
		'compile',
		'browserSync:styleguide',
		'watch',
	]);<%
	} %>

	// grunt images
	grunt.registerTask('images', [
		'newer:imagemin:images',
	]);

	/**
	 * grunt test
	 */
	grunt.registerTask('test', [
		'eslint',
		'scsslint',
	]);
};
<|endoftext|>


<commit_before>define(function(require) {

    'use strict';

    var Renderable = require('./Renderable');
    var glenum = require('./core/glenum');
    var Texture2D = require('./Texture2D');

    /**
     * @constructor qtek.Mesh
     * @extends qtek.Renderable
     */
    var Mesh = Renderable.extend(
    /** @lends qtek.Mesh# */
    {
        /**
         * Used when it is a skinned mesh
         * @type {qtek.Skeleton}
         */
        skeleton: null,
        /**
         * Joints indices Meshes can share the one skeleton instance and each mesh can use one part of joints. Joints indices indicate the index of joint in the skeleton instance
         * @type {number[]}
         */
        joints: null,

        /**
         * If store the skin matrices in vertex texture
         */
        useSkinMatricesTexture: false

    }, function () {
        if (!this.joints) {
            this.joints = [];
        }
    }, {
        render: function (_gl, shader) {
            shader = shader || this.material.shader;
            // Set pose matrices of skinned mesh
            if (this.skeleton) {
                var skinMatricesArray = this.skeleton.getSubSkinMatrices(this.__GUID__, this.joints);

                if (this.useSkinMatricesTexture) {
                    var size;
                    var numJoints = this.joints.length;
                    if (numJoints > 256) {
                        size = 64;
                    }
                    else if (numJoints > 64) {
                        size = 32;
                    }
                    else if (numJoints > 16) {
                        size = 16;
                    }
                    else {
                        size = 8;
                    }

                    var texture = this.getSkinMatricesTexture();
                    texture.width = size;
                    texture.height = size;

                    if (!texture.pixels || texture.pixels.length !== size * size * 4) {
                        texture.pixels = new Float32Array(size * size * 4);
                    }
                    texture.pixels.set(skinMatricesArray);
                    texture.dirty();

                    shader.setUniform(_gl, '1f', 'skinMatricesTextureSize', size);
                }
                else {
                    shader.setUniformOfSemantic(_gl, 'SKIN_MATRIX', skinMatricesArray);
                }
            }

            return Renderable.prototype.render.call(this, _gl, shader);
        },

        getSkinMatricesTexture: function () {
            this._skinMatricesTexture = this._skinMatricesTexture || new Texture2D({
                type: glenum.FLOAT,
                minFilter: glenum.NEAREST,
                magFilter: glenum.NEAREST,
                useMipmap: false,
                flipY: false
            });

            return this._skinMatricesTexture;
        }
    });

    // Enums
    Mesh.POINTS = glenum.POINTS;
    Mesh.LINES = glenum.LINES;
    Mesh.LINE_LOOP = glenum.LINE_LOOP;
    Mesh.LINE_STRIP = glenum.LINE_STRIP;
    Mesh.TRIANGLES = glenum.TRIANGLES;
    Mesh.TRIANGLE_STRIP = glenum.TRIANGLE_STRIP;
    Mesh.TRIANGLE_FAN = glenum.TRIANGLE_FAN;

    Mesh.BACK = glenum.BACK;
    Mesh.FRONT = glenum.FRONT;
    Mesh.FRONT_AND_BACK = glenum.FRONT_AND_BACK;
    Mesh.CW = glenum.CW;
    Mesh.CCW = glenum.CCW;

    return Mesh;
});<commit_msg>Auto update skeleton before render mesh<commit_after>define(function(require) {

    'use strict';

    var Renderable = require('./Renderable');
    var glenum = require('./core/glenum');
    var Texture2D = require('./Texture2D');

    /**
     * @constructor qtek.Mesh
     * @extends qtek.Renderable
     */
    var Mesh = Renderable.extend(
    /** @lends qtek.Mesh# */
    {
        /**
         * Used when it is a skinned mesh
         * @type {qtek.Skeleton}
         */
        skeleton: null,
        /**
         * Joints indices Meshes can share the one skeleton instance and each mesh can use one part of joints. Joints indices indicate the index of joint in the skeleton instance
         * @type {number[]}
         */
        joints: null,

        /**
         * If store the skin matrices in vertex texture
         */
        useSkinMatricesTexture: false

    }, function () {
        if (!this.joints) {
            this.joints = [];
        }
    }, {
        render: function (_gl, shader) {
            shader = shader || this.material.shader;
            // Set pose matrices of skinned mesh
            if (this.skeleton) {
                // TODO Multiple mesh share same skeleton
                this.skeleton.update();

                var skinMatricesArray = this.skeleton.getSubSkinMatrices(this.__GUID__, this.joints);

                if (this.useSkinMatricesTexture) {
                    var size;
                    var numJoints = this.joints.length;
                    if (numJoints > 256) {
                        size = 64;
                    }
                    else if (numJoints > 64) {
                        size = 32;
                    }
                    else if (numJoints > 16) {
                        size = 16;
                    }
                    else {
                        size = 8;
                    }

                    var texture = this.getSkinMatricesTexture();
                    texture.width = size;
                    texture.height = size;

                    if (!texture.pixels || texture.pixels.length !== size * size * 4) {
                        texture.pixels = new Float32Array(size * size * 4);
                    }
                    texture.pixels.set(skinMatricesArray);
                    texture.dirty();

                    shader.setUniform(_gl, '1f', 'skinMatricesTextureSize', size);
                }
                else {
                    shader.setUniformOfSemantic(_gl, 'SKIN_MATRIX', skinMatricesArray);
                }
            }

            return Renderable.prototype.render.call(this, _gl, shader);
        },

        getSkinMatricesTexture: function () {
            this._skinMatricesTexture = this._skinMatricesTexture || new Texture2D({
                type: glenum.FLOAT,
                minFilter: glenum.NEAREST,
                magFilter: glenum.NEAREST,
                useMipmap: false,
                flipY: false
            });

            return this._skinMatricesTexture;
        }
    });

    // Enums
    Mesh.POINTS = glenum.POINTS;
    Mesh.LINES = glenum.LINES;
    Mesh.LINE_LOOP = glenum.LINE_LOOP;
    Mesh.LINE_STRIP = glenum.LINE_STRIP;
    Mesh.TRIANGLES = glenum.TRIANGLES;
    Mesh.TRIANGLE_STRIP = glenum.TRIANGLE_STRIP;
    Mesh.TRIANGLE_FAN = glenum.TRIANGLE_FAN;

    Mesh.BACK = glenum.BACK;
    Mesh.FRONT = glenum.FRONT;
    Mesh.FRONT_AND_BACK = glenum.FRONT_AND_BACK;
    Mesh.CW = glenum.CW;
    Mesh.CCW = glenum.CCW;

    return Mesh;
});<|endoftext|>


<commit_before>const exec = require('child_process').exec;
const spawn = require('child_process').spawn;
const fs = require('fs-extra');
const utils = require('../utils');

module.exports = {
	name: 'run',
	description: 'Run development server',
	usage: '- wee run [options]',
	options: [
		['-l, --local', 'wrap proxy around local dev domain'],
		['-s, --static', 'serve static files']
	],
	action(config, options) {
		let project = config.project,
			projectUpdated = false;

		if (options.local) {
			if (! project.server.proxy) {
				utils.notify({icon: 'error', message: 'Set proxy domain in wee.json'}, 'error');
				process.exit();
			}

			project.server.static = false;
			projectUpdated = true;
		}

		if (options.static && ! project.server.static) {
			project.server.static = true;
			projectUpdated = true;
		}

		// Update wee.json
		if (projectUpdated) {
			fs.writeJsonSync(config.rootPath + '/wee.json', project);
		}

		// Execute npm run
		let child = spawn('npm', ['start', '--ansi'], {
			cwd: config.rootPath,
			stdio: 'inherit'
		});

		child.on('error', data => {
			console.log(data);
		});

		child.on('close', (code) => {
			console.log(`child process exited with code ${code}`);
		});
	}
};<commit_msg>remove close function<commit_after>const exec = require('child_process').exec;
const spawn = require('child_process').spawn;
const fs = require('fs-extra');
const utils = require('../utils');

module.exports = {
	name: 'run',
	description: 'Run development server',
	usage: '- wee run [options]',
	options: [
		['-l, --local', 'wrap proxy around local dev domain'],
		['-s, --static', 'serve static files']
	],
	action(config, options) {
		let project = config.project,
			projectUpdated = false;

		if (options.local) {
			if (! project.server.proxy) {
				utils.notify({icon: 'error', message: 'Set proxy domain in wee.json'}, 'error');
				process.exit();
			}

			project.server.static = false;
			projectUpdated = true;
		}

		if (options.static && ! project.server.static) {
			project.server.static = true;
			projectUpdated = true;
		}

		// Update wee.json
		if (projectUpdated) {
			fs.writeJsonSync(config.rootPath + '/wee.json', project);
		}

		// Execute npm run
		let child = spawn('npm', ['start', '--ansi'], {
			cwd: config.rootPath,
			stdio: 'inherit'
		});

		child.on('error', data => {
			console.log(data);
		});
	}
};<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var test = require('tape');
var TChannel = require('../../');

var HyperbahnClient = require('../../hyperbahn/index.js');

test('getting client subChannel without serviceName', function t(assert) {
    var client = HyperbahnClient({
        tchannel: TChannel(),
        serviceName: 'foo',
        callerName: 'foo-test',
        hostPortList: []
    });

    assert.throws(function throwIt() {
        client.getClientChannel();
    }, /must pass serviceName/);

    assert.throws(function throwIt() {
        client.getClientChannel({});
    }, /must pass serviceName/);

    assert.end();
});

test('getting a client subChannel', function t(assert) {
    var client = HyperbahnClient({
        tchannel: TChannel(),
        serviceName: 'foo',
        callerName: 'foo-test',
        hostPortList: []
    });

    var subChannel = client.getClientChannel({
        serviceName: 'bar'
    });

    assert.equal(subChannel.topChannel, client.tchannel);

    assert.end();
});

test('double getting a client subChannel', function t(assert) {
    var client = HyperbahnClient({
        tchannel: TChannel(),
        serviceName: 'foo',
        callerName: 'foo-test',
        hostPortList: []
    });

    var subChannel1 = client.getClientChannel({
        serviceName: 'bar'
    });
    var subChannel2 = client.getClientChannel({
        serviceName: 'bar'
    });

    assert.equal(subChannel1, subChannel2);

    assert.end();
});
<commit_msg>test/hyperbahn/sub-channel: close client channels<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var test = require('tape');
var TChannel = require('../../');

var HyperbahnClient = require('../../hyperbahn/index.js');

test('getting client subChannel without serviceName', function t(assert) {
    var client = HyperbahnClient({
        tchannel: TChannel(),
        serviceName: 'foo',
        callerName: 'foo-test',
        hostPortList: []
    });

    assert.throws(function throwIt() {
        client.getClientChannel();
    }, /must pass serviceName/);

    assert.throws(function throwIt() {
        client.getClientChannel({});
    }, /must pass serviceName/);

    client.tchannel.close();
    assert.end();
});

test('getting a client subChannel', function t(assert) {
    var client = HyperbahnClient({
        tchannel: TChannel(),
        serviceName: 'foo',
        callerName: 'foo-test',
        hostPortList: []
    });

    var subChannel = client.getClientChannel({
        serviceName: 'bar'
    });

    assert.equal(subChannel.topChannel, client.tchannel);

    client.tchannel.close();
    assert.end();
});

test('double getting a client subChannel', function t(assert) {
    var client = HyperbahnClient({
        tchannel: TChannel(),
        serviceName: 'foo',
        callerName: 'foo-test',
        hostPortList: []
    });

    var subChannel1 = client.getClientChannel({
        serviceName: 'bar'
    });
    var subChannel2 = client.getClientChannel({
        serviceName: 'bar'
    });

    assert.equal(subChannel1, subChannel2);

    client.tchannel.close();
    assert.end();
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Actions } from 'react-native-router-flux';
import ListItem from 'react-native-elements/src/list/ListItem';
import List from 'react-native-elements/src/list/List';
import { ScrollView, Platform } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import Share from 'react-native-share';
import * as StoreReview from 'react-native-store-review';

import Helper from '../../utils/helper';

class UserCenter extends Component {
  static componentName = 'UserCenter';

  static shareToFriend() {
    const option = {
      title: 'Growth：带你成为顶尖开发者',
      message: '我现在使用Growth，这是一款专注于Web开发者成长的应用，涵盖Web开发的流程及技术栈，Web开发的学习路线、成长衡量等各方面。快来下载吧!',
      url: 'http://growth.ren/',
    };
    Share.open(option);
  }

  static ratingApp() {
    let link = 'market://details?id=ren.growth';

    if (Platform.OS === 'ios') {
      if (StoreReview.isAvailable) {
        return StoreReview.requestReview();
      }

      link = 'itms://itunes.apple.com/us/app/apple-store/myiosappid?mt=8';
    }

    return Helper.openLink(link);
  }

  constructor(render) {
    super(render);
    this.state = {
      version: DeviceInfo.getVersion(),
    };
    UserCenter.shareToFriend = UserCenter.shareToFriend.bind(this);
  }

  render = () => (
    <ScrollView>
      <List containerStyle={{ borderTopWidth: 0 }}>
        <ListItem
          title={'我的书签'}
          leftIcon={{ name: 'bookmark' }}
          onPress={() => Actions.comingSoon('我的书签')}
        />
        <ListItem
          title={'我的技能分布'}
          leftIcon={{ name: 'trending-up' }}
          onPress={() => Actions.comingSoon('我的技能分布')}
        />
      </List>
      <List containerStyle={{ borderTopWidth: 0 }}>
        <ListItem
          title={'关于'}
          leftIcon={{ name: 'info' }}
          onPress={Actions.aboutUs}
        />
        <ListItem
          title={'分享给好友'}
          leftIcon={{ name: 'group-work' }}
          onPress={() => UserCenter.shareToFriend()}
        />
        <ListItem
          title={'觉得不错，给个好评'}
          onPress={() => UserCenter.ratingApp()}
          leftIcon={{ name: 'thumb-up' }}
        />
        <ListItem
          title={'发现Bug'}
          rightIcon={{ name: 'open-in-new' }}
          onPress={() => Helper.openLink('https://github.com/phodal/growth/issues')}
          leftIcon={{ name: 'bug-report' }}
        />
        <ListItem
          title={'我想要个功能'}
          rightIcon={{ name: 'open-in-new' }}
          onPress={() => Helper.openLink('https://jinshuju.net/f/aZ4CAS')}
          leftIcon={{ name: 'feedback' }}
        />
      </List>
      <List containerStyle={{ borderTopWidth: 0 }}>
        <ListItem
          title={'版权声明'}
          leftIcon={{ name: 'copyright' }}
          onPress={() => Actions.copyrightView()}
        />
        <ListItem
          title={'微信公众号'}
          onPress={() => Helper.openLink('https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MjM5Mjg4NDMwMA==&scene=124')}
          leftIcon={{ name: 'code' }}
          rightIcon={{ name: 'open-in-new' }}
          subtitle={'phodal-weixin'}
        />
        <ListItem
          hideChevron
          title={'当前构建版本'}
          leftIcon={{ name: 'perm-device-information' }}
          subtitle={this.state.version}
        />
      </List>
    </ScrollView>
  );
}

export default UserCenter;
<commit_msg>Update UserCenter.js<commit_after>import React, { Component } from 'react';
import { Actions } from 'react-native-router-flux';
import ListItem from 'react-native-elements/src/list/ListItem';
import List from 'react-native-elements/src/list/List';
import { ScrollView, Platform } from 'react-native';
import DeviceInfo from 'react-native-device-info';
import Share from 'react-native-share';
import * as StoreReview from 'react-native-store-review';

import Helper from '../../utils/helper';

class UserCenter extends Component {
  static componentName = 'UserCenter';

  static shareToFriend() {
    const option = {
      title: 'Growth：带你成为顶尖开发者',
      message: '我现在使用Growth，这是一款专注于Web开发者成长的应用，涵盖Web开发的流程及技术栈，Web开发的学习路线、成长衡量等各方面。快来下载吧!',
      url: 'http://growth.ren/',
    };
    Share.open(option);
  }

  static ratingApp() {
    let link = 'market://details?id=ren.growth';

    if (Platform.OS === 'ios') {
      if (StoreReview.isAvailable) {
        return StoreReview.requestReview();
      }

      link = 'itms://itunes.apple.com/cn/app/apple-store/id1078807522?mt=8';
    }

    return Helper.openLink(link);
  }

  constructor(render) {
    super(render);
    this.state = {
      version: DeviceInfo.getVersion(),
    };
    UserCenter.shareToFriend = UserCenter.shareToFriend.bind(this);
  }

  render = () => (
    <ScrollView>
      <List containerStyle={{ borderTopWidth: 0 }}>
        <ListItem
          title={'我的书签'}
          leftIcon={{ name: 'bookmark' }}
          onPress={() => Actions.comingSoon('我的书签')}
        />
        <ListItem
          title={'我的技能分布'}
          leftIcon={{ name: 'trending-up' }}
          onPress={() => Actions.comingSoon('我的技能分布')}
        />
      </List>
      <List containerStyle={{ borderTopWidth: 0 }}>
        <ListItem
          title={'关于'}
          leftIcon={{ name: 'info' }}
          onPress={Actions.aboutUs}
        />
        <ListItem
          title={'分享给好友'}
          leftIcon={{ name: 'group-work' }}
          onPress={() => UserCenter.shareToFriend()}
        />
        <ListItem
          title={'觉得不错，给个好评'}
          onPress={() => UserCenter.ratingApp()}
          leftIcon={{ name: 'thumb-up' }}
        />
        <ListItem
          title={'发现Bug'}
          rightIcon={{ name: 'open-in-new' }}
          onPress={() => Helper.openLink('https://github.com/phodal/growth/issues')}
          leftIcon={{ name: 'bug-report' }}
        />
        <ListItem
          title={'我想要个功能'}
          rightIcon={{ name: 'open-in-new' }}
          onPress={() => Helper.openLink('https://jinshuju.net/f/aZ4CAS')}
          leftIcon={{ name: 'feedback' }}
        />
      </List>
      <List containerStyle={{ borderTopWidth: 0 }}>
        <ListItem
          title={'版权声明'}
          leftIcon={{ name: 'copyright' }}
          onPress={() => Actions.copyrightView()}
        />
        <ListItem
          title={'微信公众号'}
          onPress={() => Helper.openLink('https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MjM5Mjg4NDMwMA==&scene=124')}
          leftIcon={{ name: 'code' }}
          rightIcon={{ name: 'open-in-new' }}
          subtitle={'phodal-weixin'}
        />
        <ListItem
          hideChevron
          title={'当前构建版本'}
          leftIcon={{ name: 'perm-device-information' }}
          subtitle={this.state.version}
        />
      </List>
    </ScrollView>
  );
}

export default UserCenter;
<|endoftext|>


<commit_before>import UIBase from '../utils/ui-component-base.js';
import { defineUIComponent, document, global } from '../utils/dom.js';
import extractType from '../../node_modules/extracttype/extracttype.js';
import { parseURL, toQueryString } from '../utils/url.js';
import { mix } from '../../node_modules/mixwith/src/mixwith.js';

// TODO ui-component-ready handler being called more than once on each route?
// weird skips in the back button handling?

export const Router = (() => {
  let historyManager = null;
  let localNavigationCounter = -2;
  const reflectedAttrs = [
    // updates-history: whether or not the router manages the navigation history. NOTE: can only be
    // set on one router element per page. Attempting to set more than one throws an error.
    'updates-history',

    // current-path: the current path of the router.
    'current-path',

    // base-path: automatically prepended to all paths, i.e. use if the document root is not '/'.
    // For example, if you have a test page at /tests/index.html and load up e.g.
    // localhost:8080/tests then router elements on that page should have a base-path set to
    // '/tests'.
    // 'base-path',

    // renders-current: whether or not the router renders the child element associated with the
    // current path. Routers do not render their children by default.
    'renders-current',

    // hash-bang: whether or not the history updates use hash-bang urls for client-side routing
    'hash-bang',
  ];

  const template = document.createElement('template');
  template.innerHTML = `<slot name="router-content"></slot>`;

  return defineUIComponent({
    name: 'ui-router',
    template,
    reflectedAttrs,
    definition: class Router extends UIBase {
      constructor () {
        super();
        this._contentSlot = null;
        this._routes = {};
        this._currentRoute = null;
        this._managingHistory = false;
        this._popstateListener = ({ state: data }) => {
          // localNavigationCounter -= 2;
          // const { path } = parseURL(window.location.href);
          // const routePath = this.basePath ? path.replace(this.basePath, '') : path;
          // this.route(routePath, data);
          // if (!localNavigationCounter) {
          //   window.removeEventListener('popstate', this._popstateListener);
          //   this._managingHistory = false;
          // }
        };
      }

      get currentRoute () {
        return this._currentRoute;
      }

      appendChild (node) {
        if (node.matches && node.matches('[route-path]')) {
          this._routes[node.getAttribute('route-path')] = node;
          super.appendChild(node);
        }
      }

      _updatePath (val) {
        let { data, path, route, queryString } = parseURL(val);

        if (!route) {
          if ('/' in this._routes) route = '/';
          if (!route || !this._routes[route]) throw new Error(`Unknown route ${route || 'empty'}.`);
        }

        const elem = this._routes[route];
        if (elem && elem !== this.selected) {
          if (this.selected) {
            this.selected.removeAttribute('is-selected');
            this.selected.removeAttribute('slot');
          }

          if (this.rendersCurrent) {
            elem.setAttribute('slot', 'router-content');
          }

          this.selected = elem;
          this._currentRoute = route;
          if (data && Object.keys(data).length) elem.update(data);
          elem.setAttribute('is-selected', true);

          const evt = new Event('change');
          evt.data = elem.data;
          evt.value = route;
          evt.targetComponent = elem;

          this.dispatchEvent(evt);
          return [path, route, evt, queryString];
        } else {
          if (elem && route !== '/') console.warn(`No element matches path ${route},
            perhaps the ui-route has no path set?`);
          return [];
        }
      }

      route (val, data) {
        const type = extractType(val);
        let path = null;
        if (type === 'String') path = val;
        if (type.match(/HTML\w*Element/)) path = val.getAttribute('route-path');
        if (path && path in this._routes) {
          if (data) this._routes[path].update(data);
          this.currentPath = path;
        }
        return this;
      }

      init () {
        super.init();
        this._contentSlot = this.shadowRoot.querySelector('slot');

        this.on('attribute-change', ({ changed: { now, name, was } }) => {
          switch (name) {
            case 'current-path':
              if (now !== was) {
                localNavigationCounter++;
                if (this.updatesHistory && !this._managingHistory) {
                  window.addEventListener('popstate', this._popstateListener);
                }
                const [path, route, evt, queryString] = this._updatePath(now);
                const { protocol, fullDomain } = parseURL(window.location.href);
                if (this.updatesHistory && route) {
                  console.log(`${path}#!${route}`);
                  history.pushState(this._routes[route].data, '', `${path}#!${route}`);
                  window.dispatchEvent(evt);
                }

                // TODO: makes maps work, need to fix this
                global.dispatchEvent(new Event('resize'));
              }
              break;

            case 'renders-current':
              if (this.selected) {
                if (now) {
                  this.selected.setAttribute('slot', 'router-content');
                } else {
                  this.selected.removeAttribute('slot');
                }
              }
              break;

            case 'updates-history':
              if (now) {
                if (historyManager) {
                  throw new Error(
                    `Only one router per page can manage the navigation history
                     at a time. Please listen for that router's route-changed
                     event to update other elements.`
                  );
                }
                historyManager = this;
                this._managingHistory = true;
                window.addEventListener('popstate', this._popstateListener);
              } else {
                historyManager = null;
                this._managingHistory = false;
                window.removeEventListener('popstate', this._popstateListener);
              }
          }
        });

        let selected = null;
        this.selectAll('[route-path]').forEach((el, i) => {
          const path = el.getAttribute('route-path');
          this._routes[path] = el;
          if (!i && !selected) selected = path;
          if (el.matches && el.matches('[selected]')) selected = path;
          el.on('component-selected', e => {
            this.route(el);
          });
        });
        this.route(selected);
      }
    }
  });
})();

export const Route = (() => {
  const reflectedAttrs = [
    // updates-history: whether or not the route's data is converted to a url query string
    // and added to the current browser url if the parent router manages the navigation history.
    'updates-history',

    // route-path: The url path associated with the element.
    'route-path',

    // selected: if the route is the current route of it's parent router.
    'is-selected',

    // warns-on-unload: whether or not data-changes to the route prompt user before leaving the
    // current page.
    'warns-on-unload',
  ];

  return defineUIComponent({
    name: 'ui-route',
    reflectedAttrs,
    definition: class Route extends UIBase {
      constructor () {
        super();
        this._data = null;
        this._dataElements = [];
        this._fromChangeHandler = false;
        this._unloadListener = e => {
          if (this.data) localStorage.setItem(this.routePath, JSON.stringify(elem.data));
        };
      }

      get data () {
        return this._data;
      }

      update (data) {
        this._data = data;
        const evt = new CustomEvent('data-changed');
        evt.data = data;
        localStorage.setItem(this.routePath, JSON.stringify(this.data));

        if (!this._fromChangeHandler) {
          this._dataElements.forEach(el => el.data = data);
        }
        this._fromChangeHandler = false;

        if (this.updatesHistory) {
          const qs = toQueryString(data);
          if (qs !== '?') {
            history.replaceState(data, '', window.location.href, window.location.href + qs);
          }
        }
        this.dispatchEvent(evt);
        return this;
      }

      appendChild (node) {
        if (node.matches && node.matches('[is-data-element]')) this._dataElements.push(node);
        super.appendChild();
      }

      init () {
        super.init();

        this.on('ui-component-ready', _ => {
          this._dataElements = this.shadowRoot ?
            [
              ...this.shadowRoot.querySelectorAll('[is-data-element]'),
              ...this.selectAll('[is-data-element]')
            ] :
            this.selectAll('[is-data-element]');

          this._dataElements.forEach(el => {
            el.on('change', _ => {
              this._fromChangeHandler = true;
              this.update(this._dataElements.reduce((acc, el) => {
                const data = el.serialize();
                Object.entries(data).forEach(([k, v]) => {
                  if (k in acc) {
                    console.warn(`Overwriting duplicate data-element property ${k}.`);
                  }
                  acc[k] = v;
                });
                return acc;
              }, {}));
            });
          });

          let data = localStorage.getItem(this.routePath);

          // Check to see if it was written from query string first.
          if (!this.data && data != null) this.update(JSON.parse(data));
        });

        this.on('attribute-change', ({ changed: { now, name } }) => {
          switch (name) {
            case 'is-selected':
              const evtName = now ? 'component-selected' : 'component-deselected';
              this.dispatchEvent(new CustomEvent(evtName));
              break;
          }
        });
      }
    }
  });
})();
<commit_msg>Fixed router with hashbangs<commit_after>import UIBase from '../utils/ui-component-base.js';
import { defineUIComponent, document, global } from '../utils/dom.js';
import extractType from '../../node_modules/extracttype/extracttype.js';
import { parseURL, toQueryString } from '../utils/url.js';
import { mix } from '../../node_modules/mixwith/src/mixwith.js';

// TODO ui-component-ready handler being called more than once on each route?
// weird skips in the back button handling?

export const Router = (() => {
  let historyManager = null;
  let localNavigationCounter = -1;
  let historyStack = [];
  const reflectedAttrs = [
    // updates-history: whether or not the router manages the navigation history. NOTE: can only be
    // set on one router element per page. Attempting to set more than one throws an error.
    'updates-history',

    // renders-current: whether or not the router renders the child element associated with the
    // current path. Routers do not render their children by default.
    'renders-current',

    // hash-bang: whether or not the history updates use hash-bang urls for client-side routing
    'hash-bang',
  ];

  const template = document.createElement('template');
  template.innerHTML = `<slot name="router-content"></slot>`;

  return defineUIComponent({
    name: 'ui-router',
    template,
    reflectedAttrs,
    definition: class Router extends UIBase {
      constructor () {
        super();
        this._contentSlot = null;
        this._routes = {};
        this._currentRoute = null;
        this._managingHistory = false;
        this._popstateListener = ({ state: data }) => {
          // here we ignore querystring data, it may be stale
          const { route } = parseURL(window.location.href);

          // detect if it was back or forward button:
          if (route === historyStack[historyStack.length - 2]) {
            historyStack.pop();
          }

          this._updateRoute(route);
          if (!historyStack.length || (historyStack.length === 1 && historyStack[0] === '/')) {
            global.removeEventListener('popstate', this._popstateListener);
            this._managingHistory = false;
          }
        };
      }

      get currentRoute () {
        return this._currentRoute;
      }

      set currentRoute (route) {
        if (route in this._routes) {
          return this.route(route);
        }

        return null;
      }

      appendChild (node) {
        if (node.matches && node.matches('[route-path]')) {
          this._routes[node.getAttribute('route-path')] = node;
          super.appendChild(node);
        }
      }

      _updateRoute (route, data) {
        if (!route) {
          if ('/' in this._routes) route = '/';
          if (!route || !this._routes[route]) throw new Error(`Unknown route ${route || 'empty'}.`);
        }

        console.log(`changing route to ${route}`);

        const elem = this._routes[route];
        if (!elem && route !== '/') {
          console.warn(`No element matches path ${route},
            perhaps the ui-route has no path set?`);

          return null;
        }

        if (elem !== this.selected) {
          if (this.selected) {
            this.selected.removeAttribute('is-selected');
            this.selected.removeAttribute('slot');
          }

          if (this.rendersCurrent) {
            elem.setAttribute('slot', 'router-content');
          }

          this.selected = elem;
          this._currentRoute = route;
          this.attr('current-route', route);
          if (data && Object.keys(data).length) elem.update(data);
          elem.setAttribute('is-selected', true);

          const evt = new Event('change');
          evt.data = elem.data;
          evt.value = route;
          evt.targetComponent = elem;

          this.dispatchEvent(evt);
        }

        return elem;
      }

      route (val, outsidedata) {
        let { data: urldata, path } = parseURL(window.location.href);
        const data = outsidedata || urldata;
        const type = extractType(val);
        let route = null;
        if (type === 'String') route = val;
        if (type.match(/HTML\w*Element/)) route = val.getAttribute('route-path');
        if (route && route in this._routes && route !== this.currentRoute) {
          if (data && Object.keys(data).length) this._routes[route].update(data);
          if (this.updatesHistory) {
            const base = path.match(/\/$/) ? path : `${path}/`;
            const url = this.hashBang ? `${base}#!${route}` : `${base}${route}`;
            global.history.pushState(data, '', url);
            historyStack.push(route);
          }
          return this._updateRoute(route, data);
        }
        return this;
      }

      init () {
        super.init();
        this._contentSlot = this.shadowRoot.querySelector('slot');

        this.on('attribute-change', ({ changed: { now, name, was } }) => {
          switch (name) {
            case 'renders-current':
              if (this.selected) {
                if (now) {
                  this.selected.setAttribute('slot', 'router-content');
                } else {
                  this.selected.removeAttribute('slot');
                }
              }
              break;

            case 'updates-history':
              if (now) {
                if (historyManager) {
                  throw new Error(
                    `Only one router per page can manage the navigation history
                     at a time. Please listen for that router's route-changed
                     event to update other elements.`
                  );
                }
                historyManager = this;
                this._managingHistory = true;
                window.addEventListener('popstate', this._popstateListener);
              } else {
                historyManager = null;
                this._managingHistory = false;
                window.removeEventListener('popstate', this._popstateListener);
              }
          }
        });

        let selected = null;
        let { route, data } = parseURL(window.location.href);
        if (route) selected = route;
        this.selectAll('[route-path]').forEach((el, i) => {
          const path = el.getAttribute('route-path');
          this._routes[path] = el;
          if (!i && !selected) selected = path;
          if (el.matches && el.matches('[selected]')) selected = path;
          el.on('component-selected', e => {
            this.route(el);
          });
        });
        this.route(selected);
      }
    }
  });
})();

export const Route = (() => {
  const reflectedAttrs = [
    // updates-history: whether or not the route's data is converted to a url query string
    // and added to the current browser url if the parent router manages the navigation history.
    'updates-history',

    // route-path: The url path associated with the element.
    'route-path',

    // selected: if the route is the current route of it's parent router.
    'is-selected',

    // warns-on-unload: whether or not data-changes to the route prompt user before leaving the
    // current page.
    'warns-on-unload',
  ];

  return defineUIComponent({
    name: 'ui-route',
    reflectedAttrs,
    definition: class Route extends UIBase {
      constructor () {
        super();
        this._data = null;
        this._dataElements = [];
        this._fromChangeHandler = false;
        this._unloadListener = e => {
          if (this.data) localStorage.setItem(this.routePath, JSON.stringify(elem.data));
        };
      }

      get data () {
        return this._data;
      }

      update (data) {
        this._data = data;
        const evt = new CustomEvent('data-changed');
        evt.data = data;
        localStorage.setItem(this.routePath, JSON.stringify(this.data));

        if (!this._fromChangeHandler) {
          this._dataElements.forEach(el => el.data = data);
        }
        this._fromChangeHandler = false;

        if (this.updatesHistory) {
          const qs = toQueryString(data);
          if (qs !== '?') {
            history.replaceState(data, '', window.location.href, window.location.href + qs);
          }
        }
        this.dispatchEvent(evt);
        return this;
      }

      appendChild (node) {
        if (node.matches && node.matches('[is-data-element]')) this._dataElements.push(node);
        super.appendChild();
      }

      init () {
        super.init();

        this.on('ui-component-ready', _ => {
          this._dataElements = this.shadowRoot ?
            [
              ...this.shadowRoot.querySelectorAll('[is-data-element]'),
              ...this.selectAll('[is-data-element]')
            ] :
            this.selectAll('[is-data-element]');

          this._dataElements.forEach(el => {
            el.on('change', _ => {
              this._fromChangeHandler = true;
              this.update(this._dataElements.reduce((acc, el) => {
                const data = el.serialize();
                Object.entries(data).forEach(([k, v]) => {
                  if (k in acc) {
                    console.warn(`Overwriting duplicate data-element property ${k}.`);
                  }
                  acc[k] = v;
                });
                return acc;
              }, {}));
            });
          });

          let data = localStorage.getItem(this.routePath);

          // Check to see if it was written from query string first.
          if (!this.data && data != null) this.update(JSON.parse(data));
        });

        this.on('attribute-change', ({ changed: { now, name } }) => {
          switch (name) {
            case 'is-selected':
              const evtName = now ? 'component-selected' : 'component-deselected';
              this.dispatchEvent(new CustomEvent(evtName));
              break;
          }
        });
      }
    }
  });
})();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import UserProfile from '../components/user-profile'

class UserProfileContainer extends Component {
  render() {
    if (!this.props.loggedIn) {
      return(

          Please <Link to='/login'>log in</Link> to access your profile!

      );
    }
    return <UserProfile user={this.props.user} />

  }
}

function mapStateToProps(state) {
  return {
    user: state.auth.user,
    loggedIn: state.auth.loggedIn,
  };
}

export default connect(mapStateToProps)(UserProfileContainer);
<commit_msg>Add missing semicolon<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import UserProfile from '../components/user-profile';

class UserProfileContainer extends Component {
  render() {
    if (!this.props.loggedIn) {
      return(

          Please <Link to='/login'>log in</Link> to access your profile!

      );
    }
    return <UserProfile user={this.props.user} />

  }
}

function mapStateToProps(state) {
  return {
    user: state.auth.user,
    loggedIn: state.auth.loggedIn,
  };
}

export default connect(mapStateToProps)(UserProfileContainer);
<|endoftext|>