<commit_before>window.ENV = window.ENV || {};
window.ENV['simple-auth-oauth2'] = {
    serverTokenEndpoint: 'http://localhost:7000/oauth/token',
    serverTokenRevocationEndpoint: 'http://localhost:7000/oauth/revoke',
};

var App = Ember.Application.create({
    LOG_TRANSITIONS: true
});

App.Router.map(function() {
    this.resource('projects', function() {
        this.resource('project', { path: '/:project_id' });
    });
    this.resource('about');
    this.route('login');
});

var layersStore = Ember.Object.create({
  loaded: []
});

// Controllers

App.ProjectsIndexController = Ember.ArrayController.extend({
    sortProperties: ['name'],

    //newProject: '',

    actions : {

        createProject: function() {

            time = (new Date()).toTimeString();

            var project = this.store.createRecord('project', {
                name: time,
            });

            var self = this;

            var onSuccess = function(project) {

                var newProject = DS.PromiseObject.create({
                    promise: App.Project.store.fetch('project', { name: time })
                });

                newProject.then(function() {
                    console.log(newProject)
                    self.transitionToRoute('project', newProject.get('content.content.0.id'));
                });
            };
            project.save().then(onSuccess);

        },

        deleteProject: function(project) {
            console.log(project);
            this.store.find('project', project).then(function (project) {
                project.destroyRecord();
            });

        }
    }

});

App.ProjectController = Ember.ObjectController.extend({
    showLayers: function() {
        var layers = this.get("model.layer_ids.content.content")
        var added_layers = [];
        $(layers).each(function(){
            added_layers.push(this.id)
        })
        layersStore.set("loaded",added_layers)

        return this.get('model.layer_ids')

    }.property('model.layer_ids.@each'),

    // Empty property for the input filed so we can clear it later.
    projectName: '',

    getLayers: function(){
        loaded_layers = this.get("model.layer_ids").content.content.length;
        // Needs to be changed to this if with go with ember data beta 14
        //loaded_layers = this.get("model.layer_ids").content.length;
        var i = this.incrementProperty('i'),
            c = loadCount.get("count");

        if(i !== c ){
          this.get("model").reload();
        }

        loadCount.set("count",i);

    }.property("model"),

    savedStatus: function() {
        //console.log(this);
    }.property(),

    actions: {
        reload: function() {
          this.get('model').reload().then(function(model) {
            // do something with the reloaded model
            console.log('hello');
          });
        },

        updateProject: function() {
            var project = this.get('model')
            project.set('name', this.get('projectName'))
            project.set('saved', true);

            // perserve this so we can clear the projectName field after save.
            var controller = this;
            project.save().then(function(project){
                // Clear the projectName filed.
                controller.set('projectName', '');
            });
        },
    }
});

App.AddLayerModalController = Ember.ArrayController.extend({
   sortProperties: ['layer_type', 'name'],
});

App.LoginController  = Ember.Controller.extend(SimpleAuth.LoginControllerMixin, {
    authenticator: 'simple-auth-authenticator:oauth2-password-grant'
});

// Routes

App.ApplicationRoute = Ember.Route.extend(SimpleAuth.ApplicationRouteMixin);

App.IndexRoute = Ember.Route.extend({});

// Is this needed?
App.AddLayerModalRoute = Ember.Route.extend({
    model: function() {
        // return this.store.find('layer');
    },
});

App.ProjectsIndexRoute = Ember.Route.extend({
    model: function() {
        console.log(this.session)
        return this.store.find('project');
    },

});

//App.ProjectRoute = Ember.Route.extend(SimpleAuth.AuthenticatedRouteMixin,{
App.ProjectRoute = Ember.Route.extend({

    model: function(params) {
        return this.store.find('project', params.project_id);
    },

    afterModel: function(model) {
        model.reload();
    },

    actions: {
        addLayer: function(layer, model) {
            var layerID = layer.get('id');
            var _this = this;
            var projectID = _this.get('controller.model.id');
            var projectlayer = this.store.createRecord('projectlayer', {
                project_id: projectID,
                layer_id: layerID
            });
            projectlayer.save().then(function(){
              _this.get("controller.model").reload();
            });
        },

        removeLayer: function(layer, project) {
            var layerID = layer.get('id');
            var layerClass = layer.get('layer');
            var _this = this;
            var project = project || this.get("controller.model.id");

            var projectLayer = DS.PromiseObject.create({
                promise: this.store.find('projectlayer', { layer_id: layerID, project_id: project })
            });

            projectLayer.then(function() {
                var projectLayerID = projectLayer.get('content.content.0.id');
                    console.log(projectLayer);

                App.Projectlayer.store.find('projectlayer', projectLayerID).then(function(projectlayer){
                    console.log(projectlayer)
                    projectlayer.destroyRecord().then(function(){
                        _this.get("controller.model").reload();
                    });
                });

            });

            $("."+layerClass).fadeOut( 500, function() {
                $(this).remove();
            });

        },

        // Modal
        showModal: function(name) {
            var content = this.store.find('layer');
            this.controllerFor(name).set('content', content);
            this.render(name, {
                into: 'application',
                outlet: 'modal'
            });
        },
        removeModal: function() {
            this.disconnectOutlet({
                outlet: 'modal',
                parentView: 'application'
            });
        }
    },

});

var loadCount = Ember.Object.create({
  count: 0
});

App.LoginRoute = Ember.Route.extend(SimpleAuth.UnauthenticatedRouteMixin);

App.Map = Ember.Object.extend();
var store = App.Map.create();

// Views

// Components

App.BaseMapComponent = Ember.Component.extend({
    didInsertElement: function() {

        var map = L.map('map', {
            center: [33.7489954,-84.3879824],
            zoom: 14,
            zoomControl:false
        });

        var osm = L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors Georgia State University and Emory University',
        }).addTo(map);

        var MapQuestOpen_Aerial = L.tileLayer('http://oatile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg', {
            attribution: 'Tiles Courtesy of MapQuest — Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency contributors Georgia State University and Emory University',
            subdomains: '1234'
        });

        var toner = L.tileLayer('http://d.tile.stamen.com/toner/{z}/{x}/{y}.png', {
          attribution: '© Stamen Toner Map contributors Georgia State University and Emory University'
        });

        var baseMaps = {
            "Street": osm,
            "Satellite": MapQuestOpen_Aerial,
            "Toner": toner
        };

        L.control.zoom({ position: 'topright' }).addTo(map);
        L.control.layers(baseMaps).addTo(map);

        store.set('map', map);
        // save map instance
        this.controller.set('map', map);
    },
});

App.OpacitySliderComponent = Ember.Component.extend({
    opacityslider: function() {

                var layer = DS.PromiseObject.create({
                    promise: App.Layer.store.find('layer', this.layerID)
                });

                layer.then(function() {

                    var layerName = layer.get('layer');
                    var slider = $("input.slider, input ."+layerName).slider({
                        value: 10,
                        reversed: true,
                    });

                });
    }.property(),

    actions: {
        opacityChange: function() {
            var layerName = this.layer
            var value = $("input."+layerName).val();
            var opacity = value / 10;
            $("div."+layerName+",img."+layerName).css({'opacity': opacity});
        }
    }
});

App.AddRemoveLayerButtonComponent = Ember.Component.extend({
    layerAdded: function(layer){
      return false
    }.property(),
    actions: {
        buttonAddLayer: function(layer) {
          this.toggleProperty("layerAdded");
          this.set('action','addLayer');
          this.sendAction('action', this.get('param'));
        },
        buttonRemoveLayer: function(layer) {
          this.toggleProperty("layerAdded")
          this.set('action','removeLayer');
          this.sendAction('action', this.get('param'));
        },
    }
});

Ember.Handlebars.helper('is_active', function(layer) {
    var loaded_layers = layersStore.get("loaded"),
        this_layer = this.get("param.id");

    if (loaded_layers.indexOf(this_layer) > -1){
      this.set("layerAdded",true)
      return
    }
    this.set("layerAdded",false)
    return
});

App.RemoveLayerButtonComponent = Ember.Component.extend({
    actions: {
        removeLayer: function() {
            this.sendAction('action', this.get('param'));
        }
    }
});

App.ListAddedLayersComponent = Ember.Component.extend({

    model: function() {
        return this.store.find('project');
    },

});

App.MyModalComponent = Ember.Component.extend({
    actions: {
        ok: function() {
            this.$('.modal').modal('hide');
            this.sendAction('ok');
        }
    },
    show: function() {
        this.$('.modal').modal().on('hidden.bs.modal', function() {
            this.sendAction('close');
        }.bind(this));
    }.on('didInsertElement')
});

App.MapLayersComponent = Ember.Component.extend({
    mappedLayers: function() {

        var mappedLayer = DS.PromiseObject.create({
            promise: App.Layer.store.find('layer', this.layerID)
        });

        mappedLayer.then(function() {

            var slug = mappedLayer.get('layer');
            var map = store.get('map');

            institution = mappedLayer.get('institution');

            switch(mappedLayer.get('layer_type')) {
                case 'planningatlanta':

                    var tile = L.tileLayer('http://static.library.gsu.edu/ATLmaps/tiles/' + mappedLayer.get('layer') + '/{z}/{x}/{y}.png', {
                        layer: mappedLayer.get('layer'),
                        tms: true,
                        minZoom: 13,
                        maxZoom: 19,
                        //attribution: 'GSU'
                    }).addTo(map).setZIndex(10).getContainer();

                    $(tile).addClass(slug);

                    break;

                case 'wms':

                    var wmsLayer = L.tileLayer.wms(institution.geoserver + mappedLayer.get('url') + '/wms', {
                        layers: mappedLayer.get('url') + ':' + mappedLayer.get('layer'),
                        format: 'image/png',
                        CRS: 'EPSG:900913',
                        transparent: true
                    }).addTo(map).bringToFront().getContainer();

                    $(wmsLayer).addClass(slug);

                    break;

                case 'geojson':
                    var slug = mappedLayer.get('layer')
                    function viewData(feature, layer) {
                        var popupContent = "
"+feature.properties.name+"
"+
                        "
"+feature.properties.description+"
";
                        if (feature.properties.image) {
                            popupContent += ""+
                                            "Photo Credit: "+feature.properties.image.credit+"";
                        };
                        //layer.bindPopup(popupContent);
                        layer.on('click', function(marker) {
                            console.log(marker);
                            $(".shuffle-items li.item.info").remove();
                            var $content = $("
").attr("class","content").html(popupContent)
                            var $info = $('
').attr("class","item info").append($content);
                            $info.appendTo($(".shuffle-items"))
                            shuffle.click($info);
                        });

                    }
                    function setIcon(url, class_name){
                      return iconObj = L.icon({
                                            iconUrl: url,
                                            //iconSize: [50, 65],
                                            iconAnchor: [16, 37],
                                            //popupAnchor: [0, -28],
                                            className: class_name
                                        });
                    }

                    if(mappedLayer.get('url')){
                      var points = new L.GeoJSON.AJAX(mappedLayer.get('url'), {
                          pointToLayer: function (feature, latlng) {
                            // console.log("slug",slug);
                            var marker = L.marker(latlng, {icon: setIcon("images/marker2.png", slug)});
                            return marker
                          },
                          onEachFeature: viewData,
                      }).addTo(map);
                      break;
                    }
            }

            shuffle.init();
        });
        //return mappedLayer
    }.property(),

    actions: {

    }
});

// Adapter

App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://api.atlmaps-dev.com:7000',
    namespace: 'v1',
    suffix: '.json',
    buildURL: function(record, suffix) {
      var s = this._super(record, suffix);
      return s + this.get('suffix');
    }
});

App.Store = DS.Store.extend({
  adapter: App.ApplicationAdapter
});

// Models
App.Layer = DS.Model.extend({
    name: DS.attr('string'),
    slug: DS.attr('string'),
    keywords: DS.attr('string'),
    description: DS.attr('string'),
    url: DS.attr('string'),
    layer: DS.attr('string'),
    date: DS.attr('date'),
    layer_type: DS.attr('string'),
    zoomlevels: DS.attr('string'),
    minx: DS.attr('number'),
    miny: DS.attr('number'),
    maxx: DS.attr('number'),
    maxy: DS.attr('number'),
    project_ids: DS.hasMany('project', {async: true}),
    institution: DS.attr()
});

App.Project = DS.Model.extend({
    name: DS.attr('string'),
    description: DS.attr('string'),
    saved: DS.attr('boolean'),
    published: DS.attr('boolean'),
    //user: DS.attr('number'),
    layer_ids: DS.hasMany('layer', {async: true}),
})

App.Projectlayer = DS.Model.extend({
    layer_id: DS.attr(),
    project_id: DS.attr()
});

$(document).ready(function(){
  $.material.ripples(".btn, .navbar a");
  (function(){
  // init on shuffle items
    shuffle.init();
  })()

  // document events
  $(document).on('click','#hide-layer-options',function(){
    $(".layer-controls").animate({"left":"-100%"},500,"easeInQuint",function(){
      $("#show-layer-options").fadeIn(500);
    });
  })
  .on('click','#show-layer-options',function(){
    $(".layer-controls").animate({"left":"0%"},500,"easeOutQuint");
    $("#show-layer-options").fadeOut(500);
  })
  .on('click','.shuffle-items li.item',function(){
    if ($(this).hasClass('info') == false){
      $(".shuffle-items li.item.info").remove();
    }
    shuffle.click(this);
  })

})
<commit_msg>Route specific classes<commit_after>window.ENV = window.ENV || {};
window.ENV['simple-auth-oauth2'] = {
    serverTokenEndpoint: 'http://localhost:7000/oauth/token',
    serverTokenRevocationEndpoint: 'http://localhost:7000/oauth/revoke',
};

var App = Ember.Application.create({
    LOG_TRANSITIONS: true
});

App.Router.map(function() {
    this.resource('projects', function() {
        this.resource('project', { path: '/:project_id' });
    });
    this.resource('about');
    this.route('login');
});

var layersStore = Ember.Object.create({
  loaded: []
});

// Controllers

App.ProjectsIndexController = Ember.ArrayController.extend({
    sortProperties: ['name'],

    //newProject: '',

    actions : {

        createProject: function() {

            time = (new Date()).toTimeString();

            var project = this.store.createRecord('project', {
                name: time,
            });

            var self = this;

            var onSuccess = function(project) {

                var newProject = DS.PromiseObject.create({
                    promise: App.Project.store.fetch('project', { name: time })
                });

                newProject.then(function() {
                    console.log(newProject)
                    self.transitionToRoute('project', newProject.get('content.content.0.id'));
                });
            };
            project.save().then(onSuccess);

        },

        deleteProject: function(project) {
            console.log(project);
            this.store.find('project', project).then(function (project) {
                project.destroyRecord();
            });

        }
    }

});

App.ProjectController = Ember.ObjectController.extend({
    showLayers: function() {
        var layers = this.get("model.layer_ids.content.content")
        var added_layers = [];
        $(layers).each(function(){
            added_layers.push(this.id)
        })
        layersStore.set("loaded",added_layers)

        return this.get('model.layer_ids')

    }.property('model.layer_ids.@each'),

    // Empty property for the input filed so we can clear it later.
    projectName: '',

    getLayers: function(){
        loaded_layers = this.get("model.layer_ids").content.content.length;
        // Needs to be changed to this if with go with ember data beta 14
        //loaded_layers = this.get("model.layer_ids").content.length;
        var i = this.incrementProperty('i'),
            c = loadCount.get("count");

        if(i !== c ){
          this.get("model").reload();
        }

        loadCount.set("count",i);

    }.property("model"),

    savedStatus: function() {
        //console.log(this);
    }.property(),

    actions: {
        reload: function() {
          this.get('model').reload().then(function(model) {
            // do something with the reloaded model
            console.log('hello');
          });
        },

        updateProject: function() {
            var project = this.get('model')
            project.set('name', this.get('projectName'))
            project.set('saved', true);

            // perserve this so we can clear the projectName field after save.
            var controller = this;
            project.save().then(function(project){
                // Clear the projectName filed.
                controller.set('projectName', '');
            });
        },
    }
});

App.AddLayerModalController = Ember.ArrayController.extend({
   sortProperties: ['layer_type', 'name'],
});

App.LoginController  = Ember.Controller.extend(SimpleAuth.LoginControllerMixin, {
    authenticator: 'simple-auth-authenticator:oauth2-password-grant'
});

// Routes

Ember.Route.reopen({
  activate: function() {
    var cssClass = this.toCssClass();
    // you probably don't need the application class
    // to be added to the body
    if (cssClass != 'application') {
      Ember.$('body').addClass(cssClass);
    }
  },
  deactivate: function() {
    Ember.$('body').removeClass(this.toCssClass());
  },
  toCssClass: function() {
    return this.routeName.replace(/\./g, '-').dasherize();
  }
});

App.ApplicationRoute = Ember.Route.extend(SimpleAuth.ApplicationRouteMixin);

App.IndexRoute = Ember.Route.extend({});

// Is this needed?
App.AddLayerModalRoute = Ember.Route.extend({
    model: function() {
        // return this.store.find('layer');
    },
});

App.ProjectsIndexRoute = Ember.Route.extend({
    model: function() {
        console.log(this.session)
        return this.store.find('project');
    },

});

//App.ProjectRoute = Ember.Route.extend(SimpleAuth.AuthenticatedRouteMixin,{
App.ProjectRoute = Ember.Route.extend({

    model: function(params) {
        return this.store.find('project', params.project_id);
    },

    afterModel: function(model) {
        model.reload();
    },

    actions: {
        addLayer: function(layer, model) {
            var layerID = layer.get('id');
            var _this = this;
            var projectID = _this.get('controller.model.id');
            var projectlayer = this.store.createRecord('projectlayer', {
                project_id: projectID,
                layer_id: layerID
            });
            projectlayer.save().then(function(){
              _this.get("controller.model").reload();
            });
        },

        removeLayer: function(layer, project) {
            var layerID = layer.get('id');
            var layerClass = layer.get('layer');
            var _this = this;
            var project = project || this.get("controller.model.id");

            var projectLayer = DS.PromiseObject.create({
                promise: this.store.find('projectlayer', { layer_id: layerID, project_id: project })
            });

            projectLayer.then(function() {
                var projectLayerID = projectLayer.get('content.content.0.id');
                    console.log(projectLayer);

                App.Projectlayer.store.find('projectlayer', projectLayerID).then(function(projectlayer){
                    console.log(projectlayer)
                    projectlayer.destroyRecord().then(function(){
                        _this.get("controller.model").reload();
                    });
                });

            });

            $("."+layerClass).fadeOut( 500, function() {
                $(this).remove();
            });

        },

        // Modal
        showModal: function(name) {
            var content = this.store.find('layer');
            this.controllerFor(name).set('content', content);
            this.render(name, {
                into: 'application',
                outlet: 'modal'
            });
        },
        removeModal: function() {
            this.disconnectOutlet({
                outlet: 'modal',
                parentView: 'application'
            });
        }
    },

});

var loadCount = Ember.Object.create({
  count: 0
});

App.LoginRoute = Ember.Route.extend(SimpleAuth.UnauthenticatedRouteMixin);

App.Map = Ember.Object.extend();
var store = App.Map.create();

// Views

// Components

App.BaseMapComponent = Ember.Component.extend({
    didInsertElement: function() {

        var map = L.map('map', {
            center: [33.7489954,-84.3879824],
            zoom: 14,
            zoomControl:false
        });

        var osm = L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors Georgia State University and Emory University',
        }).addTo(map);

        var MapQuestOpen_Aerial = L.tileLayer('http://oatile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg', {
            attribution: 'Tiles Courtesy of MapQuest — Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency contributors Georgia State University and Emory University',
            subdomains: '1234'
        });

        var toner = L.tileLayer('http://d.tile.stamen.com/toner/{z}/{x}/{y}.png', {
          attribution: '© Stamen Toner Map contributors Georgia State University and Emory University'
        });

        var baseMaps = {
            "Street": osm,
            "Satellite": MapQuestOpen_Aerial,
            "Toner": toner
        };

        L.control.zoom({ position: 'topright' }).addTo(map);
        L.control.layers(baseMaps).addTo(map);

        store.set('map', map);
        // save map instance
        this.controller.set('map', map);
    },
});

App.OpacitySliderComponent = Ember.Component.extend({
    opacityslider: function() {

                var layer = DS.PromiseObject.create({
                    promise: App.Layer.store.find('layer', this.layerID)
                });

                layer.then(function() {

                    var layerName = layer.get('layer');
                    var slider = $("input.slider, input ."+layerName).slider({
                        value: 10,
                        reversed: true,
                    });

                });
    }.property(),

    actions: {
        opacityChange: function() {
            var layerName = this.layer
            var value = $("input."+layerName).val();
            var opacity = value / 10;
            $("div."+layerName+",img."+layerName).css({'opacity': opacity});
        }
    }
});

App.AddRemoveLayerButtonComponent = Ember.Component.extend({
    layerAdded: function(layer){
      return false
    }.property(),
    actions: {
        buttonAddLayer: function(layer) {
          this.toggleProperty("layerAdded");
          this.set('action','addLayer');
          this.sendAction('action', this.get('param'));
        },
        buttonRemoveLayer: function(layer) {
          this.toggleProperty("layerAdded")
          this.set('action','removeLayer');
          this.sendAction('action', this.get('param'));
        },
    }
});

Ember.Handlebars.helper('is_active', function(layer) {
    var loaded_layers = layersStore.get("loaded"),
        this_layer = this.get("param.id");

    if (loaded_layers.indexOf(this_layer) > -1){
      this.set("layerAdded",true)
      return
    }
    this.set("layerAdded",false)
    return
});

App.RemoveLayerButtonComponent = Ember.Component.extend({
    actions: {
        removeLayer: function() {
            this.sendAction('action', this.get('param'));
        }
    }
});

App.ListAddedLayersComponent = Ember.Component.extend({

    model: function() {
        return this.store.find('project');
    },

});

App.MyModalComponent = Ember.Component.extend({
    actions: {
        ok: function() {
            this.$('.modal').modal('hide');
            this.sendAction('ok');
        }
    },
    show: function() {
        this.$('.modal').modal().on('hidden.bs.modal', function() {
            this.sendAction('close');
        }.bind(this));
    }.on('didInsertElement')
});

App.MapLayersComponent = Ember.Component.extend({
    mappedLayers: function() {

        var mappedLayer = DS.PromiseObject.create({
            promise: App.Layer.store.find('layer', this.layerID)
        });

        mappedLayer.then(function() {

            var slug = mappedLayer.get('layer');
            var map = store.get('map');

            institution = mappedLayer.get('institution');

            switch(mappedLayer.get('layer_type')) {
                case 'planningatlanta':

                    var tile = L.tileLayer('http://static.library.gsu.edu/ATLmaps/tiles/' + mappedLayer.get('layer') + '/{z}/{x}/{y}.png', {
                        layer: mappedLayer.get('layer'),
                        tms: true,
                        minZoom: 13,
                        maxZoom: 19,
                        //attribution: 'GSU'
                    }).addTo(map).setZIndex(10).getContainer();

                    $(tile).addClass(slug);

                    break;

                case 'wms':

                    var wmsLayer = L.tileLayer.wms(institution.geoserver + mappedLayer.get('url') + '/wms', {
                        layers: mappedLayer.get('url') + ':' + mappedLayer.get('layer'),
                        format: 'image/png',
                        CRS: 'EPSG:900913',
                        transparent: true
                    }).addTo(map).bringToFront().getContainer();

                    $(wmsLayer).addClass(slug);

                    break;

                case 'geojson':
                    var slug = mappedLayer.get('layer')
                    function viewData(feature, layer) {
                        var popupContent = "
"+feature.properties.name+"
"+
                        "
"+feature.properties.description+"
";
                        if (feature.properties.image) {
                            popupContent += ""+
                                            "Photo Credit: "+feature.properties.image.credit+"";
                        };
                        //layer.bindPopup(popupContent);
                        layer.on('click', function(marker) {
                            console.log(marker);
                            $(".shuffle-items li.item.info").remove();
                            var $content = $("
").attr("class","content").html(popupContent)
                            var $info = $('
').attr("class","item info").append($content);
                            $info.appendTo($(".shuffle-items"))
                            shuffle.click($info);
                        });

                    }
                    function setIcon(url, class_name){
                      return iconObj = L.icon({
                                            iconUrl: url,
                                            //iconSize: [50, 65],
                                            iconAnchor: [16, 37],
                                            //popupAnchor: [0, -28],
                                            className: class_name
                                        });
                    }

                    if(mappedLayer.get('url')){
                      var points = new L.GeoJSON.AJAX(mappedLayer.get('url'), {
                          pointToLayer: function (feature, latlng) {
                            // console.log("slug",slug);
                            var marker = L.marker(latlng, {icon: setIcon("images/marker2.png", slug)});
                            return marker
                          },
                          onEachFeature: viewData,
                      }).addTo(map);
                      break;
                    }
            }

            shuffle.init();
        });
        //return mappedLayer
    }.property(),

    actions: {

    }
});

// Adapter

App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://api.atlmaps-dev.com:7000',
    namespace: 'v1',
    suffix: '.json',
    buildURL: function(record, suffix) {
      var s = this._super(record, suffix);
      return s + this.get('suffix');
    }
});

App.Store = DS.Store.extend({
  adapter: App.ApplicationAdapter
});

// Models
App.Layer = DS.Model.extend({
    name: DS.attr('string'),
    slug: DS.attr('string'),
    keywords: DS.attr('string'),
    description: DS.attr('string'),
    url: DS.attr('string'),
    layer: DS.attr('string'),
    date: DS.attr('date'),
    layer_type: DS.attr('string'),
    zoomlevels: DS.attr('string'),
    minx: DS.attr('number'),
    miny: DS.attr('number'),
    maxx: DS.attr('number'),
    maxy: DS.attr('number'),
    project_ids: DS.hasMany('project', {async: true}),
    institution: DS.attr()
});

App.Project = DS.Model.extend({
    name: DS.attr('string'),
    description: DS.attr('string'),
    saved: DS.attr('boolean'),
    published: DS.attr('boolean'),
    //user: DS.attr('number'),
    layer_ids: DS.hasMany('layer', {async: true}),
})

App.Projectlayer = DS.Model.extend({
    layer_id: DS.attr(),
    project_id: DS.attr()
});

$(document).ready(function(){
  $.material.ripples(".btn, .navbar a");
  (function(){
  // init on shuffle items
    shuffle.init();
  })()

  // document events
  $(document).on('click','#hide-layer-options',function(){
    $(".layer-controls").animate({"left":"-100%"},500,"easeInQuint",function(){
      $("#show-layer-options").fadeIn(500);
    });
  })
  .on('click','#show-layer-options',function(){
    $(".layer-controls").animate({"left":"0%"},500,"easeOutQuint");
    $("#show-layer-options").fadeOut(500);
  })
  .on('click','.shuffle-items li.item',function(){
    if ($(this).hasClass('info') == false){
      $(".shuffle-items li.item.info").remove();
    }
    shuffle.click(this);
  })

})
<|endoftext|>


<commit_before>#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const fetch = require("./fetch");

const dir = path.join(__dirname, "./jsters");
fs.readdir(dir, (err, list) => {
  const files = list.map(file => {
    const filePath = path.join(dir, file);

    return {
      file,
      filePath: filePath,
      stats: fs.statSync(filePath) // mtime/ctime
    };
  });

  // Sort to find the last. In-place sort :(
  files.sort((a, b) => b.stats.mtimeMs - a.stats.mtimeMs);

  const newest = files[0];
  const jsterNumber = parseInt(
    newest.file
      .split("jster")
      .filter(a => a)[0]
      .split(".")[0],
    10
  );
  const parseFrom = new Date();
  parseFrom.setDate(parseFrom.getDate() - 17);

  fetch(
    {
      config: "./jster_config.js",
      date: parseFrom
    },
    (err, output) => {
      if (err) {
        return console.error('Failed to fetch a new jster dump');
      }

      fs.writeFileSync(
        path.join(dir, `jster${jsterNumber + 1}.json`),
        JSON.stringify(output, null, 4)
      );
      process.exit();
    }
  );
});
<commit_msg>feat: Print jster output path<commit_after>#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const fetch = require("./fetch");

const dir = path.join(__dirname, "./jsters");
fs.readdir(dir, (err, list) => {
  const files = list.map(file => {
    const filePath = path.join(dir, file);

    return {
      file,
      filePath: filePath,
      stats: fs.statSync(filePath), // mtime/ctime
    };
  });

  // Sort to find the last. In-place sort :(
  files.sort((a, b) => b.stats.mtimeMs - a.stats.mtimeMs);

  const newest = files[0];
  const jsterNumber = parseInt(
    newest.file
      .split("jster")
      .filter(a => a)[0]
      .split(".")[0],
    10
  );
  const parseFrom = new Date();
  parseFrom.setDate(parseFrom.getDate() - 17);

  fetch(
    {
      config: "./jster_config.js",
      date: parseFrom,
    },
    (err, output) => {
      if (err) {
        return console.error("Failed to fetch a new jster dump");
      }

      const outputPath = path.join(dir, `jster${jsterNumber + 1}.json`);

      fs.writeFileSync(outputPath, JSON.stringify(output, null, 4));

      console.log(outputPath);

      process.exit();
    }
  );
});
<|endoftext|>


<commit_before>var App = Ember.Application.create({
    LOG_TRANSITIONS: true
});

App.Router.map(function() {
    //this.resource('layers');
    this.resource('createMap');
    this.resource('projects');
    this.resource('project', { path: 'project/:project_id' });

});

// Controllers

App.CreateMapController = Ember.ArrayController.extend({
    sortProperties: ['layer_type', 'name'],

    actions : {

        createProject: function() {
            var project = this.store.createRecord('project', {
                name: (new Date()).toTimeString(),
                status: 'UNSAVED'
            });
            project.save()
        }
    }

});

App.AddLayerModalController = Ember.ArrayController.extend({
   sortProperties: ['layer_type', 'name'],
});

// Routers

App.IndexRoute = Ember.Route.extend({});

App.AddLayerModalRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('layer');
    },
});

App.ProjectsRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('project');
    },
})

App.ProjectRoute = Ember.Route.extend({
    model: function(params) {
        var project = this.store.find('project',  params.project_id);
        return project;
    },

    layers: function() {
        return this.store.find('layer');
    },//.property('@each.layer'),

    actions: {
        addLayer: function(layer, model) {
            console.log(layer.get('id'));
            console.log(this.get('controller.id'));
            //App.Project.store.find('project', this.get('controller.id')).then(function (project) {
            //var projectlayer = App.Projectlayer.store.createRecord('projectlayer', {
            //    project_id: this.get('controller.id'),
            //    layer_id: layer.get('id')
            //});
            //projectayer.save();

        },

        // Modal
        showModal: function(name) {
            var content = this.store.find('layer');
            this.controllerFor(name).set('content', content);
            this.render(name, {
                into: 'application',
                outlet: 'modal'
            });
        },
        removeModal: function() {
            this.disconnectOutlet({
                outlet: 'modal',
                parentView: 'application'
            });
        }
    },

    didInsertElement: function() {
        $('#ex1').slider({
            formatter: function(value) {
                return 'Current value: ' + value;
            }
        });
    }

});

App.CreateMapRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('layer');
    },

    actions: {
        addLayer: function(layer) {
            var slug = layer.get('layer');
            if ($("."+slug).length!==1){
                var map = store.get('map');
                var tile = L.tileLayer('http://static.library.gsu.edu/ATLmaps/tiles/' + layer.get('layer') + '/{z}/{x}/{y}.png', {
                    layer: layer.get('layer'),
                    tms: true,
                    minZoom: 13,
                    maxZoom: 19,
                    //attribution: 'GSU'
                }).addTo(map).getContainer();

                $(tile).addClass(slug);
            }
            else{
                $("."+slug).fadeOut( 500, function() {
                    $(this).remove();
                });
            }

        },

        // Modal
        showModal: function(name, content) {
            console.log(content)
            this.controllerFor(name).set('content', content);
            this.render(name, {
                into: 'application',
                outlet: 'modal'
            });
        },
        removeModal: function() {
            this.disconnectOutlet({
                outlet: 'modal',
                parentView: 'application'
            });
        }

    }
});

App.Map = Ember.Object.extend();
var store = App.Map.create();

// Views

// Components

App.BaseMapComponent = Ember.Component.extend({
    didInsertElement: function() {
        var map = L.map('map', {zoomControl:false}).setView([33.7489954,-84.3879824], 14);
        L.control.zoom({ position: 'topright' }).addTo(map);
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors',
        }).addTo(map);

        store.set('map', map);
        // save map instance
        this.controller.set('map', map);
    },
});

App.OpacitySliderComponent = Ember.Component.extend({
    opacityslider: function() {

                var layer = DS.PromiseObject.create({
                    promise: App.Layer.store.find('layer', this.layerID)
                });

                layer.then(function() {

                    var layerName = layer.get('layer');
                    console.log(layer.get('layer_type'));
                    switch(layer.get('layer_type')) {
                        case 'planningatlanta':
                        var slider = $("input.slider, input ."+layerName).slider({
                                    //precision: 2,
                                    value: 10,
                        });
                        break;
                    }

                });
    }.property(),

    actions: {
        opacityChange: function() {
            console.log(this.layer);
            value = $("input."+this.layer).val();
            var opacity = value / 10;
            console.log(opacity);
            $("div."+this.layer).css({'opacity': opacity});
        }
    }
});

App.AddRemoveLayerButtonComponent = Ember.Component.extend({
    actions: {
        buttonToggle: function() {
            this.toggleProperty('layerAdded');
            console.log(this);
            this.sendAction('action', this.get('param'));
        },
    }
});

App.ListAddedLayersComponent = Ember.Component.extend({

    model: function() {
        return this.store.find('project');
    },

});

App.MyModalComponent = Ember.Component.extend({
    actions: {
        ok: function() {
            this.$('.modal').modal('hide');
            this.sendAction('ok');
        }
    },
    show: function() {
        this.$('.modal').modal().on('hidden.bs.modal', function() {
            this.sendAction('close');
        }.bind(this));
    }.on('didInsertElement')
});

App.MapLayersComponent = Ember.Component.extend({
    mappedLayers: function() {

        var mappedLayer = DS.PromiseObject.create({
            promise: App.Layer.store.find('layer', this.layerID)
        })

        mappedLayer.then(function() {

            var slug = mappedLayer.get('layer');
            var map = store.get('map');

            switch(mappedLayer.get('layer_type')) {
                case 'planningatlanta':
                    if ($("."+slug).length!==1){
                        var tile = L.tileLayer('http://static.library.gsu.edu/ATLmaps/tiles/' + mappedLayer.get('layer') + '/{z}/{x}/{y}.png', {
                            layer: mappedLayer.get('layer'),
                            tms: true,
                            minZoom: 13,
                            maxZoom: 19,
                            //attribution: 'GSU'
                        }).addTo(map).getContainer();

                        $(tile).addClass(slug);
                    }
                    else{
                        $("."+slug).fadeOut( 500, function() {
                            $(this).remove();
                        });
                    }
                    break;

                case 'geojson':
                    console.log(mappedLayer.get('layer'));
                    var points = new L.GeoJSON.AJAX(mappedLayer.get('layer'), {
                        pointToLayer: function (feature, latlng) {
                          return L.marker(latlng);
                        },
                        //onEachFeature: popUp
                    }).addTo(map);
                    //points.addTo(map).getContainer();
                    break;
            }
        });
        //return mappedLayer
    }.property(),

    actions: {

    }
})

// Adapter

App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://api.atlmaps-dev.com:7000',
    namespace: 'v1',
    suffix: '.json',
    buildURL: function(record, suffix) {
      var s = this._super(record, suffix);
      return s + this.get('suffix');
    }
});

App.Store = DS.Store.extend({
  adapter: App.ApplicationAdapter
});

// Models
App.Layer = DS.Model.extend({
    name: DS.attr('string'),
    slug: DS.attr('string'),
    keywords: DS.attr('string'),
    description: DS.attr('string'),
    url: DS.attr('string'),
    layer: DS.attr('string'),
    date: DS.attr('date'),
    layer_type: DS.attr('string'),
    zoomlevels: DS.attr('string'),
    minx: DS.attr('number'),
    miny: DS.attr('number'),
    maxx: DS.attr('number'),
    maxy: DS.attr('number'),
    project_ids: DS.hasMany('project', {async: true})
});

App.Project = DS.Model.extend({
    name: DS.attr('string'),
    description: DS.attr('string'),
    status: DS.attr('string'),
    //user: DS.attr('number'),
    layer_ids: DS.hasMany('layer', {async: true}),
});

App.Projectlayer = DS.Model.extend({
    layer_id: DS.attr('number'),
    project_id: DS.attr('number')
});

$(document).ready(function(){
  $(document).on('click','#hide-layer-options',function(){
    $(".card.layer-controls").animate({"left":"-100%"},function(){
      $("#show-layer-options").fadeIn(500);
    });
  })
  .on('click','#show-layer-options',function(){
    $(".card.layer-controls").animate({"left":"0%"});
    $("#show-layer-options").fadeOut(500);
  })

})
<commit_msg>Fixing conflict.<commit_after>var App = Ember.Application.create({
    LOG_TRANSITIONS: true
});

App.Router.map(function() {
    //this.resource('layers');
    this.resource('createMap');
    this.resource('projects');
    this.resource('project', { path: 'project/:project_id' });

});

// Controllers

App.CreateMapController = Ember.ArrayController.extend({
    sortProperties: ['layer_type', 'name'],

    actions : {

        createProject: function() {
            var project = this.store.createRecord('project', {
                name: (new Date()).toTimeString(),
                status: 'UNSAVED'
            });
            project.save()
        }
    }

});

App.AddLayerModalController = Ember.ArrayController.extend({
   sortProperties: ['layer_type', 'name'],
});

// Routers

App.IndexRoute = Ember.Route.extend({});

App.AddLayerModalRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('layer');
    },
});

App.ProjectsRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('project');
    },
})

App.ProjectRoute = Ember.Route.extend({
    model: function(params) {
        var project = this.store.find('project',  params.project_id);
        return project;
    },

    layers: function() {
        return this.store.find('layer');
    },//.property('@each.layer'),

    actions: {
        addLayer: function(layer, model) {
            var layerID = String(layer.get('id'));
            var projectID = String(this.get('controller.id'));
            //App.Project.store.find('project', this.get('controller.id')).then(function (project) {
                var projectlayer = this.store.createRecord('projectlayer', {
                    project_id: '1',
                    layer_id: '4'
                });
                projectlayer.save();
            //});

        },

        // Modal
        showModal: function(name) {
            var content = this.store.find('layer');
            this.controllerFor(name).set('content', content);
            this.render(name, {
                into: 'application',
                outlet: 'modal'
            });
        },
        removeModal: function() {
            this.disconnectOutlet({
                outlet: 'modal',
                parentView: 'application'
            });
        }
    },

    didInsertElement: function() {
        $('#ex1').slider({
            formatter: function(value) {
                return 'Current value: ' + value;
            }
        });
    }

});

App.CreateMapRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('layer');
    },

    actions: {
        addLayer: function(layer) {
            var slug = layer.get('layer');
            if ($("."+slug).length!==1){
                var map = store.get('map');
                var tile = L.tileLayer('http://static.library.gsu.edu/ATLmaps/tiles/' + layer.get('layer') + '/{z}/{x}/{y}.png', {
                    layer: layer.get('layer'),
                    tms: true,
                    minZoom: 13,
                    maxZoom: 19,
                    //attribution: 'GSU'
                }).addTo(map).getContainer();

                $(tile).addClass(slug);
            }
            else{
                $("."+slug).fadeOut( 500, function() {
                    $(this).remove();
                });
            }

        },

        // Modal
        showModal: function(name, content) {
            console.log(content)
            this.controllerFor(name).set('content', content);
            this.render(name, {
                into: 'application',
                outlet: 'modal'
            });
        },
        removeModal: function() {
            this.disconnectOutlet({
                outlet: 'modal',
                parentView: 'application'
            });
        }

    }
});

App.Map = Ember.Object.extend();
var store = App.Map.create();

// Views

// Components

App.BaseMapComponent = Ember.Component.extend({
    didInsertElement: function() {
        var map = L.map('map', {zoomControl:false}).setView([33.7489954,-84.3879824], 14);
        L.control.zoom({ position: 'topright' }).addTo(map);
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors',
        }).addTo(map);

        store.set('map', map);
        // save map instance
        this.controller.set('map', map);
    },
});

App.OpacitySliderComponent = Ember.Component.extend({
    opacityslider: function() {

                var layer = DS.PromiseObject.create({
                    promise: App.Layer.store.find('layer', this.layerID)
                });

                layer.then(function() {

                    var layerName = layer.get('layer');
                    console.log(layer.get('layer_type'));
                    switch(layer.get('layer_type')) {
                        case 'planningatlanta':
                        var slider = $("input.slider, input ."+layerName).slider({
                                    //precision: 2,
                                    value: 10,
                        });
                        break;
                    }

                });
    }.property(),

    actions: {
        opacityChange: function() {
            console.log(this.layer);
            value = $("input."+this.layer).val();
            var opacity = value / 10;
            console.log(opacity);
            $("div."+this.layer).css({'opacity': opacity});
        }
    }
});

App.AddRemoveLayerButtonComponent = Ember.Component.extend({
    actions: {
        buttonToggle: function() {
            this.toggleProperty('layerAdded');
            console.log(this);
            this.sendAction('action', this.get('param'));
        },
    }
});

App.ListAddedLayersComponent = Ember.Component.extend({

    model: function() {
        return this.store.find('project');
    },

});

App.MyModalComponent = Ember.Component.extend({
    actions: {
        ok: function() {
            this.$('.modal').modal('hide');
            this.sendAction('ok');
        }
    },
    show: function() {
        this.$('.modal').modal().on('hidden.bs.modal', function() {
            this.sendAction('close');
        }.bind(this));
    }.on('didInsertElement')
});

App.MapLayersComponent = Ember.Component.extend({
    mappedLayers: function() {

        var mappedLayer = DS.PromiseObject.create({
            promise: App.Layer.store.find('layer', this.layerID)
        })

        mappedLayer.then(function() {

            var slug = mappedLayer.get('layer');
            var map = store.get('map');

            switch(mappedLayer.get('layer_type')) {
                case 'planningatlanta':
                    if ($("."+slug).length!==1){
                        var tile = L.tileLayer('http://static.library.gsu.edu/ATLmaps/tiles/' + mappedLayer.get('layer') + '/{z}/{x}/{y}.png', {
                            layer: mappedLayer.get('layer'),
                            tms: true,
                            minZoom: 13,
                            maxZoom: 19,
                            //attribution: 'GSU'
                        }).addTo(map).getContainer();

                        $(tile).addClass(slug);
                    }
                    else{
                        $("."+slug).fadeOut( 500, function() {
                            $(this).remove();
                        });
                    }
                    break;

                case 'geojson':
                    console.log(mappedLayer.get('layer'));
                    var points = new L.GeoJSON.AJAX(mappedLayer.get('layer'), {
                        pointToLayer: function (feature, latlng) {
                          return L.marker(latlng);
                        },
                        //onEachFeature: popUp
                    }).addTo(map);
                    //points.addTo(map).getContainer();
                    break;
            }
        });
        //return mappedLayer
    }.property(),

    actions: {

    }
})

// Adapter

App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://api.atlmaps-dev.com:7000',
    namespace: 'v1',
    suffix: '.json',
    buildURL: function(record, suffix) {
      var s = this._super(record, suffix);
      return s + this.get('suffix');
    }
});

App.Store = DS.Store.extend({
  adapter: App.ApplicationAdapter
});

// Models
App.Layer = DS.Model.extend({
    name: DS.attr('string'),
    slug: DS.attr('string'),
    keywords: DS.attr('string'),
    description: DS.attr('string'),
    url: DS.attr('string'),
    layer: DS.attr('string'),
    date: DS.attr('date'),
    layer_type: DS.attr('string'),
    zoomlevels: DS.attr('string'),
    minx: DS.attr('number'),
    miny: DS.attr('number'),
    maxx: DS.attr('number'),
    maxy: DS.attr('number'),
    project_ids: DS.hasMany('project', {async: true})
});

App.Project = DS.Model.extend({
    name: DS.attr('string'),
    description: DS.attr('string'),
    status: DS.attr('string'),
    //user: DS.attr('number'),
    layer_ids: DS.hasMany('layer', {async: true}),
});

App.Projectlayer = DS.Model.extend({
    layer_id: DS.attr('number'),
    project_id: DS.attr('number')
});

$(document).ready(function(){
  $(document).on('click','#hide-layer-options',function(){
    $(".card.layer-controls").animate({"left":"-100%"},function(){
      $("#show-layer-options").fadeIn(500);
    });
  })
  .on('click','#show-layer-options',function(){
    $(".card.layer-controls").animate({"left":"0%"});
    $("#show-layer-options").fadeOut(500);
  })

})
<|endoftext|>


<commit_before><commit_msg>adding the currencies<commit_after><|endoftext|>


<commit_before>var path = require('path');
var helper = require('./pluginhelper');
var Promise = require('bluebird');
var filter = helper.filter;
var fs = Promise.promisifyAll(require('fs'));

var _disable = helper.disable;
var _enable = helper.enable;

module.exports = function(sails) {
    return {
        loadedPlugins: [],

        initialize: function(cb) {
            var self = this;
            var waitFor = ['hook:app:loaded', 'hook:chat:loaded'];
            var plugins = filter(sails.config.plugins);
            var waiting = [];
            sails.afterAsync(waitFor).then(function() {
                return Promise.map(plugins, function(pluginInfo) {
                    sails.log.info('Loading plugin with id `' + pluginInfo.name + '` ...');
                    var pluginMain;
                    if(pluginInfo.source === 'npm') {
                        pluginMain = require(pluginInfo.name);
                    } else if(pluginInfo.source === 'local') {
                        pluginMain = require(path.join(sails.config.rootPath, pluginInfo.path));
                    }

                    var result = Promise.promisifyAll(pluginMain(sails.app, sails.chat));
                    if(!result.name)
                        result.name = pluginInfo.name;

                    result.log = PluginService.createPluginLogger(result.name);
                    return Promise.resolve().then(function() {
                        /*if(!_.has(sails.config.plugin, result.name)) {
                            return PluginService.generateDefaultConfig(result);
                        }*/
                    }).then(function() {
                        if(typeof(result.init) === "function") {
                            return result.initAsync().then(function() {
                                self.loadedPlugins.push(result);
                                return result;
                            });
                        } else {
                            self.loadedPlugins.push(result);
                            return result;
                        }
                    }).then(function(plugin) {
                        plugin.loaded = true;
                        sails.app.plugins[plugin.name] = plugin;
                        sails.emit('plugin:' + plugin.name + ':init');
                        plugin.log.verbose('Finished initializing.');
                        PluginService.registerCustomModels(plugin);
                        return plugin;
                    }).catch(function(err) {
                        result.log.error("Error initializing: " + err.message);
                    });
                }, { concurrency: 5 }).then(function(initializedPlugins) {
                    sails.emit('hook:pluginloader:pluginsinit');
                    sails.log.verbose('Initialized all plugins.');
                    sails.emit('hook:pluginloader:custommodels');
                    return _.filter(initializedPlugins);
                });
            }).then(function(initialized) {
                cb(null, initialized);
            }).catch(function(err) {
                sails.log.error(err);
                cb();
            });
        },
        enableAll: function() {
            return Promise.map(this.loadedPlugins, _enable).then(function() {
                sails.emit('hook:pluginloader:pluginsenable');
                sails.log.info('Loaded all plugins.');
            });
        },
        enable: function(name) {
            var plugin = _.find(this.loadedPlugins, function(plugin) { plugin.name === name });
            if(plugin)
                return _enable(plugin);
        },

        disablePlugin: function(name) {
            var plugin = _.find(this.loadedPlugins, function(plugin) { plugin.name === name });
            if(plugin)
                _disable(plugin);
        },
        disableAll: function() {
            this.loadedPlugins.forEach(_disable);
        },

        teardown: function(cb) {
            this.disableAll();
        }
    };
};
<commit_msg>Set root path in loader if not present.<commit_after>var path = require('path');
var helper = require('./pluginhelper');
var Promise = require('bluebird');
var filter = helper.filter;
var fs = Promise.promisifyAll(require('fs'));

var _disable = helper.disable;
var _enable = helper.enable;

module.exports = function(sails) {
    return {
        loadedPlugins: [],

        initialize: function(cb) {
            if(!sails.config.rootPath) {
                sails.config.rootPath = path.join(sails.config.paths.config, '..');
            }

            var self = this;
            var waitFor = ['hook:app:loaded', 'hook:chat:loaded'];
            var plugins = filter(sails.config.plugins);
            var waiting = [];
            sails.afterAsync(waitFor).then(function() {
                return Promise.map(plugins, function(pluginInfo) {
                    sails.log.info('Loading plugin with id `' + pluginInfo.name + '` ...');
                    var pluginMain;
                    if(pluginInfo.source === 'npm') {
                        pluginMain = require(pluginInfo.name);
                    } else if(pluginInfo.source === 'local') {
                        pluginMain = require(path.join(sails.config.rootPath, pluginInfo.path));
                    }

                    var result = Promise.promisifyAll(pluginMain(sails.app, sails.chat));
                    if(!result.name)
                        result.name = pluginInfo.name;

                    result.log = PluginService.createPluginLogger(result.name);
                    return Promise.resolve().then(function() {
                        /*if(!_.has(sails.config.plugin, result.name)) {
                            return PluginService.generateDefaultConfig(result);
                        }*/
                    }).then(function() {
                        if(typeof(result.init) === "function") {
                            return result.initAsync().then(function() {
                                self.loadedPlugins.push(result);
                                return result;
                            });
                        } else {
                            self.loadedPlugins.push(result);
                            return result;
                        }
                    }).then(function(plugin) {
                        plugin.loaded = true;
                        sails.app.plugins[plugin.name] = plugin;
                        sails.emit('plugin:' + plugin.name + ':init');
                        plugin.log.verbose('Finished initializing.');
                        PluginService.registerCustomModels(plugin);
                        return plugin;
                    }).catch(function(err) {
                        result.log.error("Error initializing: " + err.message);
                    });
                }, { concurrency: 5 }).then(function(initializedPlugins) {
                    sails.emit('hook:pluginloader:pluginsinit');
                    sails.log.verbose('Initialized all plugins.');
                    sails.emit('hook:pluginloader:custommodels');
                    return _.filter(initializedPlugins);
                });
            }).then(function(initialized) {
                cb(null, initialized);
            }).catch(function(err) {
                sails.log.error(err);
                cb();
            });
        },
        enableAll: function() {
            return Promise.map(this.loadedPlugins, _enable).then(function() {
                sails.emit('hook:pluginloader:pluginsenable');
                sails.log.info('Loaded all plugins.');
            });
        },
        enable: function(name) {
            var plugin = _.find(this.loadedPlugins, function(plugin) { plugin.name === name });
            if(plugin)
                return _enable(plugin);
        },

        disablePlugin: function(name) {
            var plugin = _.find(this.loadedPlugins, function(plugin) { plugin.name === name });
            if(plugin)
                _disable(plugin);
        },
        disableAll: function() {
            this.loadedPlugins.forEach(_disable);
        },

        teardown: function(cb) {
            this.disableAll();
        }
    };
};
<|endoftext|>


<commit_before>var assert = require('assert'),
    tilestream = require('tilestream')({
        tiles: __dirname + '/fixtures/tiles',
        uiHost: 'http://locahost:8888',
        tileHost: 'http://localhost:8888',
        uiPort: 8888,
        tilePort: 8888
    });

module.exports = {
    'tile': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/1.0.0/control_room/3/4/5.png' },
            { status: 200 },
            function(res) {
                assert.equal(res.headers['content-length'], 63554);
                assert.equal(res.headers['content-type'], 'image/png');
                assert.equal(res.headers['cache-control'], 'max-age=31536000');
                assert.ok(res.headers['last-modified']);
                assert.ok(res.headers['e-tag']);
            }
        );
    },
    'error tile': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/1.0.0/control_room/-1/-1/-1.png' },
            { status: 404 }
        );
    },
    'grid tile': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/1.0.0/waxtest/0/0/0.grid.json' },
            { status: 200, body: /grid\(/ }
        );
    },
    'layer json': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/1.0.0/waxtest/layer.json' },
            { status: 200, body: /grid\(/ }
        );
    },
    'mbtiles download': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/download/control_room.mbtiles' },
            { status: 200 },
            function(res) {
                // @TODO: determine why download is sometimes off by 1 (or more?) byte(s)
                assert.ok(res.body.length >= 2976208 || res.body.length <= 2976209);
            }
        );
    },
    'load map': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/api/Tileset/control_room' },
            { status: 200 },
            function(res) {
                var map;
                assert.doesNotThrow(function() {
                    map = JSON.parse(res.body);
                }, SyntaxError);
                assert.equal(map.id, 'control_room');
                assert.equal(map.type, 'baselayer');
                assert.equal(map.bounds, "-180,-85.05112877980659,180,89.99075251648905");
            }
        );
    },
    'load maps': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/api/Tileset' },
            { status: 200 },
            function(res) {
                var maps;
                assert.doesNotThrow(function() {
                    maps = JSON.parse(res.body);
                }, SyntaxError);
                assert.equal(maps.length, 2);
                assert.equal(maps[0].id, 'control_room');
                assert.equal(maps[0].type, 'baselayer');
                assert.equal(maps[0].bounds, "-180,-85.05112877980659,180,89.99075251648905");
            }
        );
    },
    'ssviews list': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/' },
            { status: 200, body: /name\">control_room/ }
        );
    },
    'ssviews map': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/map/control_room' },
            { status: 200, body: /control_room<\/a/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/?_escaped_fragment_=/map/control_room' },
            { status: 200, body: /control_room<\/a/ }
        );
    },
    'settings': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/settings.js' },
            { status: 200 }
        );
    },
    'wax endpoint': function() {
        var fs = require('fs'),
            fixtures = {
                layers: JSON.parse(fs.readFileSync(__dirname + '/fixtures/wax/wax.layers.json', 'utf8')),
                el:     JSON.parse(fs.readFileSync(__dirname + '/fixtures/wax/wax.el.json', 'utf8')),
                center: JSON.parse(fs.readFileSync(__dirname + '/fixtures/wax/wax.center.json', 'utf8')),
                options: JSON.parse(fs.readFileSync(__dirname + '/fixtures/wax/wax.options.json', 'utf8'))
            };
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?api=foo' },
            { status: 400, body: /`api` is invalid/ }
        );

        assert.response(
            tilestream.uiServer,
            { url: '/wax.json' },
            { status: 400, body: /`layers` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers=foo' },
            { status: 400, body: /`layers` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=foo' },
            { status: 400, body: /`layers` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room' },
            { status: 200 },
            function(res) {
                assert.deepEqual(fixtures.layers, JSON.parse(res.body));
            }
        );

        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&el[]=foo' },
            { status: 400, body: /`el` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&el=foo' },
            { status: 200 },
            function(res) {
                assert.deepEqual(fixtures.el, JSON.parse(res.body));
            }
        );

        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&center=foo' },
            { status: 400, body: /`center` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&center[]=0' },
            { status: 400, body: /`center` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&center[]=0&center[]=0&center[]=foo' },
            { status: 400, body: /`center` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&center[]=40&center[]=40&center[]=2' },
            { status: 200 },
            function(res) {
                assert.deepEqual(fixtures.center, JSON.parse(res.body));
            }
        );

        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&options=foo' },
            { status: 400, body: /`options` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&options[]=foo' },
            { status: 400, body: /`options` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&options[]=tooltips' },
            { status: 200 },
            function(res) {
                assert.deepEqual(fixtures.options, JSON.parse(res.body));
            }
        );
    }
}

<commit_msg>Fix max-age header in tilestream test.<commit_after>var assert = require('assert'),
    tilestream = require('tilestream')({
        tiles: __dirname + '/fixtures/tiles',
        uiHost: 'http://locahost:8888',
        tileHost: 'http://localhost:8888',
        uiPort: 8888,
        tilePort: 8888
    });

module.exports = {
    'tile': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/1.0.0/control_room/3/4/5.png' },
            { status: 200 },
            function(res) {
                assert.equal(res.headers['content-length'], 63554);
                assert.equal(res.headers['content-type'], 'image/png');
                assert.equal(res.headers['cache-control'], 'max-age=3600');
                assert.ok(res.headers['last-modified']);
                assert.ok(res.headers['e-tag']);
            }
        );
    },
    'error tile': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/1.0.0/control_room/-1/-1/-1.png' },
            { status: 404 }
        );
    },
    'grid tile': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/1.0.0/waxtest/0/0/0.grid.json' },
            { status: 200, body: /grid\(/ }
        );
    },
    'layer json': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/1.0.0/waxtest/layer.json' },
            { status: 200, body: /grid\(/ }
        );
    },
    'mbtiles download': function() {
        assert.response(
            tilestream.tileServer,
            { url: '/download/control_room.mbtiles' },
            { status: 200 },
            function(res) {
                // @TODO: determine why download is sometimes off by 1 (or more?) byte(s)
                assert.ok(res.body.length >= 2976208 || res.body.length <= 2976209);
            }
        );
    },
    'load map': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/api/Tileset/control_room' },
            { status: 200 },
            function(res) {
                var map;
                assert.doesNotThrow(function() {
                    map = JSON.parse(res.body);
                }, SyntaxError);
                assert.equal(map.id, 'control_room');
                assert.equal(map.type, 'baselayer');
                assert.equal(map.bounds, "-180,-85.05112877980659,180,89.99075251648905");
            }
        );
    },
    'load maps': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/api/Tileset' },
            { status: 200 },
            function(res) {
                var maps;
                assert.doesNotThrow(function() {
                    maps = JSON.parse(res.body);
                }, SyntaxError);
                assert.equal(maps.length, 2);
                assert.equal(maps[0].id, 'control_room');
                assert.equal(maps[0].type, 'baselayer');
                assert.equal(maps[0].bounds, "-180,-85.05112877980659,180,89.99075251648905");
            }
        );
    },
    'ssviews list': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/' },
            { status: 200, body: /name\">control_room/ }
        );
    },
    'ssviews map': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/map/control_room' },
            { status: 200, body: /control_room<\/a/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/?_escaped_fragment_=/map/control_room' },
            { status: 200, body: /control_room<\/a/ }
        );
    },
    'settings': function() {
        assert.response(
            tilestream.uiServer,
            { url: '/settings.js' },
            { status: 200 }
        );
    },
    'wax endpoint': function() {
        var fs = require('fs'),
            fixtures = {
                layers: JSON.parse(fs.readFileSync(__dirname + '/fixtures/wax/wax.layers.json', 'utf8')),
                el:     JSON.parse(fs.readFileSync(__dirname + '/fixtures/wax/wax.el.json', 'utf8')),
                center: JSON.parse(fs.readFileSync(__dirname + '/fixtures/wax/wax.center.json', 'utf8')),
                options: JSON.parse(fs.readFileSync(__dirname + '/fixtures/wax/wax.options.json', 'utf8'))
            };
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?api=foo' },
            { status: 400, body: /`api` is invalid/ }
        );

        assert.response(
            tilestream.uiServer,
            { url: '/wax.json' },
            { status: 400, body: /`layers` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers=foo' },
            { status: 400, body: /`layers` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=foo' },
            { status: 400, body: /`layers` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room' },
            { status: 200 },
            function(res) {
                assert.deepEqual(fixtures.layers, JSON.parse(res.body));
            }
        );

        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&el[]=foo' },
            { status: 400, body: /`el` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&el=foo' },
            { status: 200 },
            function(res) {
                assert.deepEqual(fixtures.el, JSON.parse(res.body));
            }
        );

        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&center=foo' },
            { status: 400, body: /`center` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&center[]=0' },
            { status: 400, body: /`center` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&center[]=0&center[]=0&center[]=foo' },
            { status: 400, body: /`center` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&center[]=40&center[]=40&center[]=2' },
            { status: 200 },
            function(res) {
                assert.deepEqual(fixtures.center, JSON.parse(res.body));
            }
        );

        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&options=foo' },
            { status: 400, body: /`options` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&options[]=foo' },
            { status: 400, body: /`options` is invalid/ }
        );
        assert.response(
            tilestream.uiServer,
            { url: '/wax.json?layers[]=control_room&options[]=tooltips' },
            { status: 200 },
            function(res) {
                assert.deepEqual(fixtures.options, JSON.parse(res.body));
            }
        );
    }
}

<|endoftext|>


<commit_before>module.exports = Zeppelin.CollectionView.extend({
  tagName: 'ol',

  className: 'cards-list list-unstyled clearfix',

  subscriptions: {
    'cardsList:layout': 'triggerLayout'
  },

  addMethod: 'prepend',

  wall: null,

  layoutTimer: null,

  itemView: function(model) {
    return require('account/views/' + model.get('type'));
  },

  collection: function() {
    return App.Cards;
  },

  initialize: function() {
    _.bindAll(this, ['layout']);
  },

  triggerLayout: function() {
    this.layoutTimer = _.delay(this.layout, 1);
  },

  layout: function() {
    if (this.collection.isEmpty()) return this;
    if (!this.wall) this.wall = new freewall(this.$list);

    this.wall.reset({
      delay: 0,
      cellW: 222,
      cellH: 222,
      gutterX: 15,
      gutterY: 15,
      animate: false,
      fixSize: 0,
      selector: 'li.card',
      onResize: _.bind(function() {
        this.wall.fitWidth();
      }, this)
    });

    this.wall.fitWidth();

    return this;
  },

  onRenderItems: function() {
    this.triggerLayout();
  },

  onPrependItem: function() {
    if (!this.isFirstCollectionRender()) this.triggerLayout();
  },

  onUnplug: function() {
    clearTimeout(this.layoutTimer);
    if (this.$list.data('masonry')) this.$list.masonry('destroy');
  }
});

<commit_msg>Remove old masonry plugin code.<commit_after>module.exports = Zeppelin.CollectionView.extend({
  tagName: 'ol',

  className: 'cards-list list-unstyled clearfix',

  subscriptions: {
    'cardsList:layout': 'triggerLayout'
  },

  addMethod: 'prepend',

  wall: null,

  layoutTimer: null,

  itemView: function(model) {
    return require('account/views/' + model.get('type'));
  },

  collection: function() {
    return App.Cards;
  },

  initialize: function() {
    _.bindAll(this, ['layout']);
  },

  triggerLayout: function() {
    this.layoutTimer = _.delay(this.layout, 1);
  },

  layout: function() {
    if (this.collection.isEmpty()) return this;
    if (!this.wall) this.wall = new freewall(this.$list);

    this.wall.reset({
      delay: 0,
      cellW: 222,
      cellH: 222,
      gutterX: 15,
      gutterY: 15,
      animate: false,
      fixSize: 0,
      selector: 'li.card',
      onResize: _.bind(function() {
        this.wall.fitWidth();
      }, this)
    });

    this.wall.fitWidth();

    return this;
  },

  onRenderItems: function() {
    this.triggerLayout();
  },

  onPrependItem: function() {
    if (!this.isFirstCollectionRender()) this.triggerLayout();
  },

  onUnplug: function() {
    clearTimeout(this.layoutTimer);
  }
});

<|endoftext|>


<commit_before>import { assert } from 'chai';
import sinon from 'sinon';
import Shape from '../../src/Shape';

describe('Shape', () => {
  it('Should properly initialize shape instance with no arguments', () => {
    const shape = new Shape();

    assert.instanceOf(shape, Shape);
  });

  it('Should properly initialize shape instance with arguments', () => {
    const shape = new Shape({text: 'test'});

    assert.instanceOf(shape, Shape);
    assert.equal(shape.getText(), 'test');
  });

  it('Should properly get/set property from the shape', () => {
    const shape = new Shape();

    assert.equal(shape.get('text'), '');
    assert.instanceOf(shape.set('animation.name', 'print'), Shape);
    assert.equal(shape.get('animation.name'), 'print');
    assert.instanceOf(shape.set('animation.name', 'test'), Shape);
    assert.equal(shape.get('animation.name'), 'test');
  });

  it('Should properly get/set text', () => {
    const shape = new Shape();

    assert.equal(shape.getText(), '');
    assert.instanceOf(shape.setText('test'), Shape);
    assert.equal(shape.getText(), 'test');
  });

  it('Should properly get/set width', () => {
    const shape = new Shape();

    assert.equal(shape.getWidth(), 15);
    assert.instanceOf(shape.setWidth(5), Shape);
    assert.equal(shape.getWidth(), 5);
    assert.instanceOf(shape.setWidth('50%'), Shape);
    assert.equal(shape.getWidth(), Math.ceil(process.stdout.columns / 2));
  });

  it('Should properly get/set height', () => {
    const shape = new Shape();

    assert.equal(shape.getHeight(), 5);
    assert.instanceOf(shape.setHeight(15), Shape);
    assert.equal(shape.getHeight(), 15);
    assert.instanceOf(shape.setHeight('50%'), Shape);
    assert.equal(shape.getHeight(), Math.floor(process.stdout.rows / 2));
  });

  it('Should properly get/set x coordinate', () => {
    const shape = new Shape();

    assert.equal(shape.getX(), 10);
    assert.instanceOf(shape.setX(20), Shape);
    assert.equal(shape.getX(), 20);
    assert.instanceOf(shape.setX('left'), Shape);
    assert.equal(shape.getX(), 0);
    assert.instanceOf(shape.setX('center'), Shape);
    assert.equal(shape.getX(), Math.floor(process.stdout.columns / 2 - shape.getWidth() / 2));
    assert.instanceOf(shape.setX('right'), Shape);
    assert.equal(shape.getX(), Math.floor(process.stdout.columns - shape.getWidth()));
    assert.instanceOf(shape.setX('50%'), Shape);
    assert.equal(shape.getX(), Math.floor(process.stdout.columns / 2));
  });

  it('Should properly get/set y coordinate', () => {
    const shape = new Shape();

    assert.equal(shape.getY(), 10);
    assert.instanceOf(shape.setY(20), Shape);
    assert.equal(shape.getY(), 20);
    assert.instanceOf(shape.setY('top'), Shape);
    assert.equal(shape.getY(), 0);
    assert.instanceOf(shape.setY('middle'), Shape);
    assert.equal(shape.getY(), Math.floor(process.stdout.rows / 2 - shape.getHeight() / 2));
    assert.instanceOf(shape.setY('bottom'), Shape);
    assert.equal(shape.getY(), Math.floor(process.stdout.rows - shape.getHeight()));
    assert.instanceOf(shape.setY('50%'), Shape);
    assert.equal(shape.getY(), Math.floor(process.stdout.rows / 2));
  });

  it('Should properly get/set background', () => {
    const shape = new Shape();

    assert.notOk(shape.getBackground());
    assert.instanceOf(shape.setBackground('red'), Shape);
    assert.equal(shape.getBackground(), 'red');
  });

  it('Should properly get/set foreground', () => {
    const shape = new Shape();

    assert.notOk(shape.getBackground());
    assert.instanceOf(shape.setForeground('yellow'), Shape);
    assert.equal(shape.getForeground(), 'yellow');
  });

  it('Should properly throw exception if render is not overridden', () => {
    const shape = new Shape();

    assert.throws(() => shape.render(), Error, 'render() method must be implemented');
  });

  it('Should properly serialize shape to object', () => {
    const shape = new Shape();
    const obj = shape.toObject();

    assert.deepEqual(obj, {
      type: 'Shape',
      options: {
        text: '',
        width: 15,
        height: 5,
        x: 10,
        y: 10,
        background: false,
        foreground: false
      }
    });
  });

  it('Should properly serialize shape to object with custom options', () => {
    const shape = new Shape({text: 'test', x: 0, y: 0, width: 30, height: 50, background: 'red', foreground: 'black'});
    const obj = shape.toObject();

    assert.deepEqual(obj, {
      type: 'Shape',
      options: {
        text: 'test',
        width: 30,
        height: 50,
        x: 0,
        y: 0,
        background: 'red',
        foreground: 'black'
      }
    });
  });

  it('Should properly serialize shape to JSON', () => {
    const shape = new Shape();
    const json = shape.toJSON();

    assert.equal(json, '{"type":"Shape","options":{"text":"","width":15,"height":5,"x":10,"y":10,"background":false,"foreground":false}}');
  });

  it('Should properly serialize shape to JSON with custom options', () => {
    const shape = new Shape({text: 'test', x: 0, y: 0, width: 30, height: 50});
    const json = shape.toJSON();

    assert.equal(json, '{"type":"Shape","options":{"text":"test","width":30,"height":50,"x":0,"y":0,"background":false,"foreground":false}}');
  });

  it('Should properly create Shape instance from static create()', () => {
    const shape = Shape.create({text: 'test'});

    assert.equal(shape.getText(), 'test');
    assert.instanceOf(shape, Shape);
  });

  it('Should properly throw error if trying to create Shape not from Object representation', () => {
    const obj = {};

    assert.throws(() => Shape.fromObject(obj), Error, 'It looks like it is not an Object representation of the shape');
  });

  it('Should properly throw error if trying to create Shape not from its representation', () => {
    const obj = {type: 'Rectangle', options: {}};

    assert.throws(() => Shape.fromObject(obj), Error, 'Rectangle is not an Object representation of the Shape');
  });

  it('Should properly create Shape instance from Object representation', () => {
    const obj = {
      type: 'Shape',
      options: {
        text: 'test',
        width: 30,
        height: 50,
        x: 1,
        y: 1,
        background: 'red',
        foreground: 'black'
      }
    };

    const shape = Shape.fromObject(obj);

    assert.instanceOf(shape, Shape);
    assert.equal(shape.getText(), 'test');
    assert.equal(shape.getWidth(), 30);
    assert.equal(shape.getHeight(), 50);
    assert.equal(shape.getX(), 1);
    assert.equal(shape.getY(), 1);
    assert.equal(shape.getBackground(), 'red');
    assert.equal(shape.getForeground(), 'black');
  });

  it('Should properly create Shape instance from JSON representation', () => {
    const json = '{"type":"Shape","options":{"text":"test","width":30,"height":50,"x":1,"y":1}}';
    const shape = Shape.fromJSON(json);

    assert.instanceOf(shape, Shape);
    assert.equal(shape.getText(), 'test');
    assert.equal(shape.getWidth(), 30);
    assert.equal(shape.getHeight(), 50);
    assert.equal(shape.getX(), 1);
    assert.equal(shape.getY(), 1);
    assert.notOk(shape.getBackground());
    assert.notOk(shape.getForeground());
  });
});
<commit_msg>test(shape): Fix tests<commit_after>import {assert} from 'chai';
import Cursor from 'kittik-cursor';
import Shape from '../../src/Shape';

const cursor = Cursor.create();

describe('Shape', () => {
  it('Should properly initialize shape instance with no arguments', () => {
    const shape = new Shape(cursor);

    assert.instanceOf(shape, Shape);
  });

  it('Should properly initialize shape instance with arguments', () => {
    const shape = new Shape(cursor, {text: 'test'});

    assert.instanceOf(shape, Shape);
    assert.equal(shape.getText(), 'test');
  });

  it('Should properly get/set property from the shape', () => {
    const shape = new Shape(cursor);

    assert.equal(shape.get('text'), '');
    assert.instanceOf(shape.set('animation.name', 'print'), Shape);
    assert.equal(shape.get('animation.name'), 'print');
    assert.instanceOf(shape.set('animation.name', 'test'), Shape);
    assert.equal(shape.get('animation.name'), 'test');
  });

  it('Should properly get/set text', () => {
    const shape = new Shape(cursor);

    assert.equal(shape.getText(), '');
    assert.instanceOf(shape.setText('test'), Shape);
    assert.equal(shape.getText(), 'test');
  });

  it('Should properly get/set width', () => {
    const shape = new Shape(cursor);

    assert.equal(shape.getWidth(), 15);
    assert.instanceOf(shape.setWidth(5), Shape);
    assert.equal(shape.getWidth(), 5);
    assert.instanceOf(shape.setWidth('50%'), Shape);
    assert.equal(shape.getWidth(), Math.ceil(cursor._width / 2));
  });

  it('Should properly get/set height', () => {
    const shape = new Shape(cursor);

    assert.equal(shape.getHeight(), 5);
    assert.instanceOf(shape.setHeight(15), Shape);
    assert.equal(shape.getHeight(), 15);
    assert.instanceOf(shape.setHeight('50%'), Shape);
    assert.equal(shape.getHeight(), Math.floor(cursor._height / 2));
  });

  it('Should properly get/set x coordinate', () => {
    const shape = new Shape(cursor);

    assert.equal(shape.getX(), 10);
    assert.instanceOf(shape.setX(20), Shape);
    assert.equal(shape.getX(), 20);
    assert.instanceOf(shape.setX('left'), Shape);
    assert.equal(shape.getX(), 0);
    assert.instanceOf(shape.setX('center'), Shape);
    assert.equal(shape.getX(), Math.floor(cursor._width / 2 - shape.getWidth() / 2));
    assert.instanceOf(shape.setX('right'), Shape);
    assert.equal(shape.getX(), Math.floor(cursor._width - shape.getWidth()));
    assert.instanceOf(shape.setX('50%'), Shape);
    assert.equal(shape.getX(), Math.floor(cursor._width / 2));
  });

  it('Should properly get/set y coordinate', () => {
    const shape = new Shape(cursor);

    assert.equal(shape.getY(), 10);
    assert.instanceOf(shape.setY(20), Shape);
    assert.equal(shape.getY(), 20);
    assert.instanceOf(shape.setY('top'), Shape);
    assert.equal(shape.getY(), 0);
    assert.instanceOf(shape.setY('middle'), Shape);
    assert.equal(shape.getY(), Math.floor(cursor._height / 2 - shape.getHeight() / 2));
    assert.instanceOf(shape.setY('bottom'), Shape);
    assert.equal(shape.getY(), Math.floor(cursor._height - shape.getHeight()));
    assert.instanceOf(shape.setY('50%'), Shape);
    assert.equal(shape.getY(), Math.floor(cursor._height / 2));
  });

  it('Should properly get/set background', () => {
    const shape = new Shape(cursor);

    assert.notOk(shape.getBackground());
    assert.instanceOf(shape.setBackground('red'), Shape);
    assert.equal(shape.getBackground(), 'red');
  });

  it('Should properly get/set foreground', () => {
    const shape = new Shape(cursor);

    assert.notOk(shape.getBackground());
    assert.instanceOf(shape.setForeground('yellow'), Shape);
    assert.equal(shape.getForeground(), 'yellow');
  });

  it('Should properly throw exception if render is not overridden', () => {
    const shape = new Shape(cursor);

    assert.throws(() => shape.render(), Error, 'render() method must be implemented');
  });

  it('Should properly serialize shape to object', () => {
    const shape = new Shape(cursor);
    const obj = shape.toObject();

    assert.deepEqual(obj, {
      type: 'Shape',
      options: {
        text: '',
        width: 15,
        height: 5,
        x: 10,
        y: 10,
        background: false,
        foreground: false
      }
    });
  });

  it('Should properly serialize shape to object with custom options', () => {
    const shape = new Shape(cursor, {
      text: 'test',
      x: 0,
      y: 0,
      width: 30,
      height: 50,
      background: 'red',
      foreground: 'black'
    });
    const obj = shape.toObject();

    assert.deepEqual(obj, {
      type: 'Shape',
      options: {
        text: 'test',
        width: 30,
        height: 50,
        x: 0,
        y: 0,
        background: 'red',
        foreground: 'black'
      }
    });
  });

  it('Should properly serialize shape to JSON', () => {
    const shape = new Shape(cursor);
    const json = shape.toJSON();

    assert.equal(json, '{"type":"Shape","options":{"text":"","width":15,"height":5,"x":10,"y":10,"background":false,"foreground":false}}');
  });

  it('Should properly serialize shape to JSON with custom options', () => {
    const shape = new Shape(cursor, {text: 'test', x: 0, y: 0, width: 30, height: 50});
    const json = shape.toJSON();

    assert.equal(json, '{"type":"Shape","options":{"text":"test","width":30,"height":50,"x":0,"y":0,"background":false,"foreground":false}}');
  });

  it('Should properly create Shape instance from static create()', () => {
    const shape = Shape.create(cursor, {text: 'test'});

    assert.equal(shape.getText(), 'test');
    assert.instanceOf(shape, Shape);
  });

  it('Should properly throw error if trying to create Shape not from Object representation', () => {
    const obj = {};

    assert.throws(() => Shape.fromObject(obj), Error, 'It looks like it is not an Object representation of the shape');
  });

  it('Should properly throw error if trying to create Shape not from its representation', () => {
    const obj = {type: 'Rectangle', options: {}};

    assert.throws(() => Shape.fromObject(obj), Error, 'Rectangle is not an Object representation of the Shape');
  });

  it('Should properly create Shape instance from Object representation', () => {
    const obj = {
      type: 'Shape',
      options: {
        text: 'test',
        width: 30,
        height: 50,
        x: 1,
        y: 1,
        background: 'red',
        foreground: 'black'
      }
    };

    const shape = Shape.fromObject(obj, cursor);

    assert.instanceOf(shape, Shape);
    assert.instanceOf(shape.getCursor(), Cursor);
    assert.equal(shape.getText(), 'test');
    assert.equal(shape.getWidth(), 30);
    assert.equal(shape.getHeight(), 50);
    assert.equal(shape.getX(), 1);
    assert.equal(shape.getY(), 1);
    assert.equal(shape.getBackground(), 'red');
    assert.equal(shape.getForeground(), 'black');
  });

  it('Should properly create Shape instance from JSON representation', () => {
    const json = '{"type":"Shape","options":{"text":"test","width":30,"height":50,"x":1,"y":1}}';
    const shape = Shape.fromJSON(json, cursor);

    assert.instanceOf(shape, Shape);
    assert.instanceOf(shape.getCursor(), Cursor);
    assert.equal(shape.getText(), 'test');
    assert.equal(shape.getWidth(), 30);
    assert.equal(shape.getHeight(), 50);
    assert.equal(shape.getX(), 1);
    assert.equal(shape.getY(), 1);
    assert.notOk(shape.getBackground());
    assert.notOk(shape.getForeground());
  });
});
<|endoftext|>