<commit_before>// entry point
;(function() {

    var root = this;

    var cdb = root.cdb = {};

    cdb.VERSION = "3.11.25";
    cdb.DEBUG = false;

    cdb.CARTOCSS_VERSIONS = {
      '2.0.0': '',
      '2.1.0': ''
    };

    cdb.CARTOCSS_DEFAULT_VERSION = '2.1.1';

    cdb.CDB_HOST = {
      'http': 'api.cartocdn.com',
      'https': 'cartocdn.global.ssl.fastly.net'
    };

    root.cdb.config = {};
    root.cdb.core = {};
    root.cdb.geo = {};
    root.cdb.geo.ui = {};
    root.cdb.geo.geocoder = {};
    root.cdb.ui = {};
    root.cdb.ui.common = {};
    root.cdb.vis = {};
    root.cdb.decorators = {};
    /**
     * global variables
     */
    root.JST = root.JST || {};
    root.cartodb = cdb;

    cdb.files = [
        "../vendor/jquery.min.js",
        "../vendor/underscore-min.js",
        "../vendor/json2.js",
        "../vendor/backbone.js",

        "../vendor/leaflet.js",
        "../vendor/wax.cartodb.js",
        "../vendor/GeoJSON.js", //geojson gmaps lib

        "../vendor/jscrollpane.js",
        "../vendor/mousewheel.js",
        "../vendor/mwheelIntent.js",
        "../vendor/spin.js",
        "../vendor/lzma.js",

        'core/decorator.js',
        'core/config.js',
        'core/log.js',
        'core/profiler.js',
        'core/template.js',
        'core/model.js',
        'core/view.js',

        'geo/geocoder.js',
        'geo/geometry.js',
        'geo/map.js',
        'geo/ui/text.js',
        'geo/ui/annotation.js',
        'geo/ui/image.js',
        'geo/ui/share.js',
        'geo/ui/zoom.js',
        'geo/ui/zoom_info.js',
        'geo/ui/legend.js',
        'geo/ui/switcher.js',
        'geo/ui/infowindow.js',
        'geo/ui/header.js',
        'geo/ui/search.js',
        'geo/ui/layer_selector.js',
        'geo/ui/mobile.js',
        'geo/ui/tiles_loader.js',
        'geo/ui/infobox.js',
        'geo/ui/tooltip.js',
        'geo/ui/fullscreen.js',

        'geo/layer_definition.js',
        'geo/common.js',

        'geo/leaflet/leaflet_base.js',
        'geo/leaflet/leaflet_plainlayer.js',
        'geo/leaflet/leaflet_tiledlayer.js',
        'geo/leaflet/leaflet_gmaps_tiledlayer.js',
        'geo/leaflet/leaflet_wmslayer.js',
        'geo/leaflet/leaflet_cartodb_layergroup.js',
        'geo/leaflet/leaflet_cartodb_layer.js',
        'geo/leaflet/leaflet.js',

        'geo/gmaps/gmaps_base.js',
        'geo/gmaps/gmaps_baselayer.js',
        'geo/gmaps/gmaps_plainlayer.js',
        'geo/gmaps/gmaps_tiledlayer.js',
        'geo/gmaps/gmaps_cartodb_layergroup.js',
        'geo/gmaps/gmaps_cartodb_layer.js',
        'geo/gmaps/gmaps.js',

        'ui/common/dialog.js',
        'ui/common/share.js',
        'ui/common/notification.js',
        'ui/common/table.js',
        'ui/common/dropdown.js',

        'vis/vis.js',
        'vis/overlays.js',
        'vis/layers.js',

        // PUBLIC API
        'api/layers.js',
        'api/sql.js',
        'api/vis.js'
    ];

    cdb.init = function(ready) {
      // define a simple class
      var Class = cdb.Class = function() {};
      _.extend(Class.prototype, Backbone.Events);

      cdb._loadJST();
      root.cdb.god = new Backbone.Model();

      ready && ready();
    };

    /**
     * load all the javascript files. For testing, do not use in production
     */
    cdb.load = function(prefix, ready) {
        var c = 0;

        var next = function() {
            var script = document.createElement('script');
            script.src = prefix + cdb.files[c];
            document.body.appendChild(script);
            ++c;
            if(c == cdb.files.length) {
                if(ready) {
                    script.onload = ready;
                }
            } else {
                script.onload = next;
            }
        };

        next();

    };
})();
<commit_msg>added build<commit_after>// entry point
;(function() {

    var root = this;

    var cdb = root.cdb = {};

    cdb.VERSION = "3.11.25";
    cdb.DEBUG = false;

    cdb.CARTOCSS_VERSIONS = {
      '2.0.0': '',
      '2.1.0': ''
    };

    cdb.CARTOCSS_DEFAULT_VERSION = '2.1.1';

    cdb.CDB_HOST = {
      'http': 'api.cartocdn.com',
      'https': 'cartocdn.global.ssl.fastly.net'
    };

    root.cdb.config = {};
    root.cdb.core = {};
    root.cdb.geo = {};
    root.cdb.geo.ui = {};
    root.cdb.geo.geocoder = {};
    root.cdb.ui = {};
    root.cdb.ui.common = {};
    root.cdb.vis = {};
    root.cdb.decorators = {};
    /**
     * global variables
     */
    root.JST = root.JST || {};
    root.cartodb = cdb;

    cdb.files = [
        "../vendor/jquery.min.js",
        "../vendor/underscore-min.js",
        "../vendor/json2.js",
        "../vendor/backbone.js",

        "../vendor/leaflet.js",
        "../vendor/wax.cartodb.js",
        "../vendor/GeoJSON.js", //geojson gmaps lib

        "../vendor/jscrollpane.js",
        "../vendor/mousewheel.js",
        "../vendor/mwheelIntent.js",
        "../vendor/spin.js",
        "../vendor/lzma.js",

        'core/decorator.js',
        'core/config.js',
        'core/log.js',
        'core/profiler.js',
        'core/template.js',
        'core/model.js',
        'core/view.js',

        'geo/geocoder.js',
        'geo/geometry.js',
        'geo/map.js',
        'geo/ui/text.js',
        'geo/ui/annotation.js',
        'geo/ui/image.js',
        'geo/ui/share.js',
        'geo/ui/zoom.js',
        'geo/ui/zoom_info.js',
        'geo/ui/legend.js',
        'geo/ui/switcher.js',
        'geo/ui/infowindow.js',
        'geo/ui/header.js',
        'geo/ui/search.js',
        'geo/ui/layer_selector.js',
        'geo/ui/mobile.js',
        'geo/ui/tiles_loader.js',
        'geo/ui/infobox.js',
        'geo/ui/tooltip.js',
        'geo/ui/fullscreen.js',

        'geo/layer_definition.js',
        'geo/common.js',

        'geo/leaflet/leaflet_base.js',
        'geo/leaflet/leaflet_plainlayer.js',
        'geo/leaflet/leaflet_tiledlayer.js',
        'geo/leaflet/leaflet_gmaps_tiledlayer.js',
        'geo/leaflet/leaflet_wmslayer.js',
        'geo/leaflet/leaflet_cartodb_layergroup.js',
        'geo/leaflet/leaflet_cartodb_layer.js',
        'geo/leaflet/leaflet.js',

        'geo/gmaps/gmaps_base.js',
        'geo/gmaps/gmaps_baselayer.js',
        'geo/gmaps/gmaps_plainlayer.js',
        'geo/gmaps/gmaps_tiledlayer.js',
        'geo/gmaps/gmaps_cartodb_layergroup.js',
        'geo/gmaps/gmaps_cartodb_layer.js',
        'geo/gmaps/gmaps.js',

        'ui/common/dialog.js',
        'ui/common/share.js',
        'ui/common/notification.js',
        'ui/common/table.js',
        'ui/common/dropdown.js',

        'vis/vis.js',
        'vis/overlays.js',
        'vis/layers.js',

        // PUBLIC API
        'api/layers.js',
        'api/sql.js',
        'api/cartocss.js',
        'api/vis.js'
    ];

    cdb.init = function(ready) {
      // define a simple class
      var Class = cdb.Class = function() {};
      _.extend(Class.prototype, Backbone.Events);

      cdb._loadJST();
      root.cdb.god = new Backbone.Model();

      ready && ready();
    };

    /**
     * load all the javascript files. For testing, do not use in production
     */
    cdb.load = function(prefix, ready) {
        var c = 0;

        var next = function() {
            var script = document.createElement('script');
            script.src = prefix + cdb.files[c];
            document.body.appendChild(script);
            ++c;
            if(c == cdb.files.length) {
                if(ready) {
                    script.onload = ready;
                }
            } else {
                script.onload = next;
            }
        };

        next();

    };
})();
<|endoftext|>


<commit_before>var isLeafletAlreadyLoaded = !!window.L;

var _ = require('underscore');
var L = require('leaflet');
require('mousewheel'); // registers itself to $.event; TODO what's this required for? still relevant for supported browsers?
require('mwheelIntent'); // registers itself to $.event; TODO what's this required for? still relevant for supported browsers?

var cdb = require('cdb');
cdb.Backbone = require('backbone');
cdb.Mustache = require('mustache');
cdb.$ = require('jquery');
cdb._ = _;
cdb.L = L;

if (isLeafletAlreadyLoaded) L.noConflict();
_.extend(L, require('./geo/leaflet-extensions'));
_.extend(cdb.geo, require('./geo/leaflet'));

cdb.Image = require('./vis/image')
cdb.SQL = require('./api/sql');

cdb.config = require('cdb.config');
cdb.log = require('cdb.log');
cdb.errors = require('cdb.errors');
cdb.templates = require('cdb.templates');
cdb.decorators = require('./core/decorators');
cdb.createVis = require('./api/create-vis');
cdb.createLayer = require('./api/create-layer');

// Extracted from vis/vis.js,
// used in libs like torque and odyssey to add themselves here (or so it seems)
cdb.moduleLoad = function(name, mod) {
  cdb[name] = mod;
  cdb.config.modules.add({
    name: name,
    mod: mod
  });
};

cdb.core.Profiler = require('cdb.core.Profiler');
cdb.core.util = require('cdb.core.util');
cdb.core.Loader = cdb.vis.Loader = require('./core/loader');
cdb.core.sanitize = require('./core/sanitize')
cdb.core.Template = require('./core/template');
cdb.core.TemplateList = require('./core/template-list');
cdb.core.Model = require('./core/model');
cdb.core.View = require('./core/view');

cdb.ui.common.Dialog = require('./ui/common/dialog');
cdb.ui.common.ShareDialog = require('./ui/common/share');
cdb.ui.common.Dropdown = require('./ui/common/dropdown');
cdb.ui.common.FullScreen = require('./ui/common/fullscreen');
cdb.ui.common.Notification = require('./ui/common/notification');
cdb.ui.common.Row = require('./ui/common/table/row');
cdb.ui.common.TableData = require('./ui/common/table/table-data');
cdb.ui.common.TableProperties = require('./ui/common/table/table-properties');
cdb.ui.common.RowView = require('./ui/common/table/row-view');
cdb.ui.common.Table = require('./ui/common/table');

cdb.geo.common.CartoDBLogo = require('./geo/cartodb-logo');

cdb.geo.geocoder.NOKIA = require('./geo/geocoder/nokia-geocoder');
cdb.geo.geocoder.YAHOO = require('./geo/geocoder/yahoo-geocoder');
cdb.geo.Geometry = require('./geo/geometry');

cdb.geo.MapLayer = require('./geo/map/map-layer');
cdb.geo.TileLayer = require('./geo/map/tile-layer');
cdb.geo.GMapsBaseLayer = require('./geo/map/gmaps-base-layer');
cdb.geo.WMSLayer = require('./geo/map/wms-layer');
cdb.geo.PlainLayer = require('./geo/map/plain-layer');
cdb.geo.TorqueLayer = require('./geo/map/torque-layer');
cdb.geo.CartoDBLayer = require('./geo/map/cartodb-layer');
cdb.geo.CartoDBLayerGroupNamed = require('./geo/map/cartodb-layer-group-named');
cdb.geo.CartoDBLayerGroupAnonymous = require('./geo/map/cartodb-layer-group-anonymous');
cdb.geo.Layers = require('./geo/map/layers');
cdb.geo.Map = require('./geo/map');
cdb.geo.MapView = require('./geo/map-view');

_.extend(cdb.geo, require('./geo/gmaps'));

// overwrites the Promise defined from the core bundle
cdb.Promise = require('./api/promise');

cdb.geo.ui.Text = require('./geo/ui/text');
cdb.geo.ui.Annotation = require('./geo/ui/annotation');
cdb.geo.ui.Image = require('./geo/ui/image');
cdb.geo.ui.Share = require('./geo/ui/share');
cdb.geo.ui.Zoom = require('./geo/ui/zoom');
cdb.geo.ui.ZoomInfo = require('./geo/ui/zoom-info');

// setup expected object structure here, to avoid circular references
_.extend(cdb.geo.ui, require('./geo/ui/legend-exports'));
cdb.geo.ui.Legend = require('./geo/ui/legend');
_.extend(cdb.geo.ui.Legend, require('./geo/ui/legend/legend-view-exports'));

cdb.geo.ui.InfowindowModel = require('./geo/ui/infowindow-model');
cdb.geo.ui.Infowindow = require('./geo/ui/infowindow');

cdb.geo.ui.SlidesControllerItem = require('./geo/ui/slides-controller-item');
cdb.geo.ui.SlidesController = require('./geo/ui/slides-controller');
cdb.geo.ui.Header = require('./geo/ui/header');

cdb.geo.ui.Search = require('./geo/ui/search');

cdb.geo.ui.LayerSelector = require('./geo/ui/layer-selector');
cdb.geo.ui.LayerView = require('./geo/ui/layer-view');
cdb.geo.ui.LayerViewFromLayerGroup = require('./geo/ui/layer-view-from-layer-group');

cdb.geo.ui.MobileLayer = require('./geo/ui/mobile-layer');
cdb.geo.ui.Mobile = require('./geo/ui/mobile');
cdb.geo.ui.TilesLoader = require('./geo/ui/tiles-loader');
cdb.geo.ui.InfoBox = require('./geo/ui/infobox');
cdb.geo.ui.Tooltip = require('./geo/ui/tooltip');

cdb.vis.INFOWINDOW_TEMPLATE = require('./vis/vis/infowindow-template');
cdb.vis.Overlay = require('./vis/vis/overlay');
cdb.vis.Overlays = require('./vis/vis/overlays');
cdb.vis.Layers = require('./vis/vis/layers');
cdb.vis.Vis = require('./vis/vis');
require('./vis/overlays'); // Overlay.register calls
require('./vis/layers'); // Layers.register calls

cdb.geo.ui.Widget.View = require('./geo/ui/widget');
cdb.geo.ui.Widget.Content = require('./geo/ui/widgets/standard/widget_content_view');
cdb.geo.ui.Widget.Error = require('./geo/ui/widgets/standard/widget_error_view');
cdb.geo.ui.Widget.Loader = require('./geo/ui/widgets/standard/widget_loader_view');
cdb.geo.ui.Widget.Category.Content = require('./geo/ui/widgets/category/content_view');
cdb.geo.ui.Widget.Category.FilterView = require('./geo/ui/widgets/category/filter_view');
cdb.geo.ui.Widget.Category.ItemView = require('./geo/ui/widgets/category/item_view');
cdb.geo.ui.Widget.Category.ItemsView = require('./geo/ui/widgets/category/items_view');
cdb.geo.ui.Widget.CategoryModel = require('./geo/ui/widgets/category/model');
cdb.geo.ui.Widget.Category.PaginatorView = require('./geo/ui/widgets/category/paginator_view');
cdb.geo.ui.Widget.Category.View = require('./geo/ui/widgets/category/view');
cdb.geo.ui.Widget.Formula.Content = require('./geo/ui/widgets/formula/content_view');
cdb.geo.ui.Widget.FormulaModel = require('./geo/ui/widgets/formula/model');
cdb.geo.ui.Widget.Formula.View = require('./geo/ui/widgets/formula/view');
cdb.geo.ui.Widget.Histogram.Chart = require('./geo/ui/widgets/histogram/chart');
cdb.geo.ui.Widget.Histogram.Content = require('./geo/ui/widgets/histogram/content_view');
cdb.geo.ui.Widget.HistogramModel = require('./geo/ui/widgets/histogram/model');
cdb.geo.ui.Widget.Histogram.View = require('./geo/ui/widgets/histogram/view');
cdb.geo.ui.Widget.ListModel = require('./geo/ui/widgets/list/model');
cdb.geo.ui.Widget.List.View = require('./geo/ui/widgets/list/view');
cdb.geo.ui.Widget.List.EdgesView = require('./geo/ui/widgets/list/edges_view');
cdb.geo.ui.Widget.List.PaginatorView = require('./geo/ui/widgets/list/paginator_view');
cdb.geo.ui.Widget.List.ItemView = require('./geo/ui/widgets/list/item_view');
cdb.geo.ui.Widget.List.ItemsView = require('./geo/ui/widgets/list/items_view');
cdb.geo.ui.Widget.List.Content = require('./geo/ui/widgets/list/content_view');

cdb.windshaft.filters.FilterBase = require('./windshaft/filters/base');
cdb.windshaft.filters.BoundingBoxFilter = require('./windshaft/filters/bounding_box');
cdb.windshaft.filters.CategoryFilter = require('./windshaft/filters/category');
cdb.windshaft.filters.Collection = require('./windshaft/filters/collection');
cdb.windshaft.filters.RangeFilter = require('./windshaft/filters/range');
cdb.windshaft.Client = require('./windshaft/client');
cdb.windshaft.config = require('./windshaft/config');
cdb.windshaft.Dashboard = require('./windshaft/dashboard');
cdb.windshaft.DashboardInstance = require('./windshaft/dashboard_instance');
cdb.windshaft.PrivateDashboardConfig = require('./windshaft/private_dashboard_config');
cdb.windshaft.PublicDashboardConfig = require('./windshaft/public_dashboard_config');

module.exports = cdb;
<commit_msg>Adds d3 to the cdb object<commit_after>var isLeafletAlreadyLoaded = !!window.L;

var _ = require('underscore');
var L = require('leaflet');
var d3 = require('d3');
require('mousewheel'); // registers itself to $.event; TODO what's this required for? still relevant for supported browsers?
require('mwheelIntent'); // registers itself to $.event; TODO what's this required for? still relevant for supported browsers?

var cdb = require('cdb');
cdb.Backbone = require('backbone');
cdb.Mustache = require('mustache');
cdb.$ = require('jquery');
cdb._ = _;
cdb.L = L;
cdb.d3 = d3;

if (isLeafletAlreadyLoaded) L.noConflict();
_.extend(L, require('./geo/leaflet-extensions'));
_.extend(cdb.geo, require('./geo/leaflet'));

cdb.Image = require('./vis/image');
cdb.SQL = require('./api/sql');

cdb.config = require('cdb.config');
cdb.log = require('cdb.log');
cdb.errors = require('cdb.errors');
cdb.templates = require('cdb.templates');
cdb.decorators = require('./core/decorators');
cdb.createVis = require('./api/create-vis');
cdb.createLayer = require('./api/create-layer');

// Extracted from vis/vis.js,
// used in libs like torque and odyssey to add themselves here (or so it seems)
cdb.moduleLoad = function(name, mod) {
  cdb[name] = mod;
  cdb.config.modules.add({
    name: name,
    mod: mod
  });
};

cdb.core.Profiler = require('cdb.core.Profiler');
cdb.core.util = require('cdb.core.util');
cdb.core.Loader = cdb.vis.Loader = require('./core/loader');
cdb.core.sanitize = require('./core/sanitize')
cdb.core.Template = require('./core/template');
cdb.core.TemplateList = require('./core/template-list');
cdb.core.Model = require('./core/model');
cdb.core.View = require('./core/view');

cdb.ui.common.Dialog = require('./ui/common/dialog');
cdb.ui.common.ShareDialog = require('./ui/common/share');
cdb.ui.common.Dropdown = require('./ui/common/dropdown');
cdb.ui.common.FullScreen = require('./ui/common/fullscreen');
cdb.ui.common.Notification = require('./ui/common/notification');
cdb.ui.common.Row = require('./ui/common/table/row');
cdb.ui.common.TableData = require('./ui/common/table/table-data');
cdb.ui.common.TableProperties = require('./ui/common/table/table-properties');
cdb.ui.common.RowView = require('./ui/common/table/row-view');
cdb.ui.common.Table = require('./ui/common/table');

cdb.geo.common.CartoDBLogo = require('./geo/cartodb-logo');

cdb.geo.geocoder.NOKIA = require('./geo/geocoder/nokia-geocoder');
cdb.geo.geocoder.YAHOO = require('./geo/geocoder/yahoo-geocoder');
cdb.geo.Geometry = require('./geo/geometry');

cdb.geo.MapLayer = require('./geo/map/map-layer');
cdb.geo.TileLayer = require('./geo/map/tile-layer');
cdb.geo.GMapsBaseLayer = require('./geo/map/gmaps-base-layer');
cdb.geo.WMSLayer = require('./geo/map/wms-layer');
cdb.geo.PlainLayer = require('./geo/map/plain-layer');
cdb.geo.TorqueLayer = require('./geo/map/torque-layer');
cdb.geo.CartoDBLayer = require('./geo/map/cartodb-layer');
cdb.geo.CartoDBLayerGroupNamed = require('./geo/map/cartodb-layer-group-named');
cdb.geo.CartoDBLayerGroupAnonymous = require('./geo/map/cartodb-layer-group-anonymous');
cdb.geo.Layers = require('./geo/map/layers');
cdb.geo.Map = require('./geo/map');
cdb.geo.MapView = require('./geo/map-view');

_.extend(cdb.geo, require('./geo/gmaps'));

// overwrites the Promise defined from the core bundle
cdb.Promise = require('./api/promise');

cdb.geo.ui.Text = require('./geo/ui/text');
cdb.geo.ui.Annotation = require('./geo/ui/annotation');
cdb.geo.ui.Image = require('./geo/ui/image');
cdb.geo.ui.Share = require('./geo/ui/share');
cdb.geo.ui.Zoom = require('./geo/ui/zoom');
cdb.geo.ui.ZoomInfo = require('./geo/ui/zoom-info');

// setup expected object structure here, to avoid circular references
_.extend(cdb.geo.ui, require('./geo/ui/legend-exports'));
cdb.geo.ui.Legend = require('./geo/ui/legend');
_.extend(cdb.geo.ui.Legend, require('./geo/ui/legend/legend-view-exports'));

cdb.geo.ui.InfowindowModel = require('./geo/ui/infowindow-model');
cdb.geo.ui.Infowindow = require('./geo/ui/infowindow');

cdb.geo.ui.SlidesControllerItem = require('./geo/ui/slides-controller-item');
cdb.geo.ui.SlidesController = require('./geo/ui/slides-controller');
cdb.geo.ui.Header = require('./geo/ui/header');

cdb.geo.ui.Search = require('./geo/ui/search');

cdb.geo.ui.LayerSelector = require('./geo/ui/layer-selector');
cdb.geo.ui.LayerView = require('./geo/ui/layer-view');
cdb.geo.ui.LayerViewFromLayerGroup = require('./geo/ui/layer-view-from-layer-group');

cdb.geo.ui.MobileLayer = require('./geo/ui/mobile-layer');
cdb.geo.ui.Mobile = require('./geo/ui/mobile');
cdb.geo.ui.TilesLoader = require('./geo/ui/tiles-loader');
cdb.geo.ui.InfoBox = require('./geo/ui/infobox');
cdb.geo.ui.Tooltip = require('./geo/ui/tooltip');

cdb.vis.INFOWINDOW_TEMPLATE = require('./vis/vis/infowindow-template');
cdb.vis.Overlay = require('./vis/vis/overlay');
cdb.vis.Overlays = require('./vis/vis/overlays');
cdb.vis.Layers = require('./vis/vis/layers');
cdb.vis.Vis = require('./vis/vis');
require('./vis/overlays'); // Overlay.register calls
require('./vis/layers'); // Layers.register calls

cdb.geo.ui.Widget.View = require('./geo/ui/widget');
cdb.geo.ui.Widget.Content = require('./geo/ui/widgets/standard/widget_content_view');
cdb.geo.ui.Widget.Error = require('./geo/ui/widgets/standard/widget_error_view');
cdb.geo.ui.Widget.Loader = require('./geo/ui/widgets/standard/widget_loader_view');
cdb.geo.ui.Widget.Category.Content = require('./geo/ui/widgets/category/content_view');
cdb.geo.ui.Widget.Category.FilterView = require('./geo/ui/widgets/category/filter_view');
cdb.geo.ui.Widget.Category.ItemView = require('./geo/ui/widgets/category/item_view');
cdb.geo.ui.Widget.Category.ItemsView = require('./geo/ui/widgets/category/items_view');
cdb.geo.ui.Widget.CategoryModel = require('./geo/ui/widgets/category/model');
cdb.geo.ui.Widget.Category.PaginatorView = require('./geo/ui/widgets/category/paginator_view');
cdb.geo.ui.Widget.Category.View = require('./geo/ui/widgets/category/view');
cdb.geo.ui.Widget.Formula.Content = require('./geo/ui/widgets/formula/content_view');
cdb.geo.ui.Widget.FormulaModel = require('./geo/ui/widgets/formula/model');
cdb.geo.ui.Widget.Formula.View = require('./geo/ui/widgets/formula/view');
cdb.geo.ui.Widget.Histogram.Chart = require('./geo/ui/widgets/histogram/chart');
cdb.geo.ui.Widget.Histogram.Content = require('./geo/ui/widgets/histogram/content_view');
cdb.geo.ui.Widget.HistogramModel = require('./geo/ui/widgets/histogram/model');
cdb.geo.ui.Widget.Histogram.View = require('./geo/ui/widgets/histogram/view');
cdb.geo.ui.Widget.ListModel = require('./geo/ui/widgets/list/model');
cdb.geo.ui.Widget.List.View = require('./geo/ui/widgets/list/view');
cdb.geo.ui.Widget.List.EdgesView = require('./geo/ui/widgets/list/edges_view');
cdb.geo.ui.Widget.List.PaginatorView = require('./geo/ui/widgets/list/paginator_view');
cdb.geo.ui.Widget.List.ItemView = require('./geo/ui/widgets/list/item_view');
cdb.geo.ui.Widget.List.ItemsView = require('./geo/ui/widgets/list/items_view');
cdb.geo.ui.Widget.List.Content = require('./geo/ui/widgets/list/content_view');

cdb.windshaft.filters.FilterBase = require('./windshaft/filters/base');
cdb.windshaft.filters.BoundingBoxFilter = require('./windshaft/filters/bounding_box');
cdb.windshaft.filters.CategoryFilter = require('./windshaft/filters/category');
cdb.windshaft.filters.Collection = require('./windshaft/filters/collection');
cdb.windshaft.filters.RangeFilter = require('./windshaft/filters/range');
cdb.windshaft.Client = require('./windshaft/client');
cdb.windshaft.config = require('./windshaft/config');
cdb.windshaft.Dashboard = require('./windshaft/dashboard');
cdb.windshaft.DashboardInstance = require('./windshaft/dashboard_instance');
cdb.windshaft.PrivateDashboardConfig = require('./windshaft/private_dashboard_config');
cdb.windshaft.PublicDashboardConfig = require('./windshaft/public_dashboard_config');

module.exports = cdb;
<|endoftext|>


<commit_before>define([
	'goo/statemachine/actions/Action',
	'goo/statemachine/FSMUtil'
	],
/** @lends */

function(
	Action,
	FSMUtil
) {
	'use strict';

	function TweenAction(settings) {
		Action.apply(this, arguments);
	}

	TweenAction.prototype = Object.create(Action.prototype);
	TweenAction.prototype.constructor = TweenAction;

	TweenAction.external = {
		name: 'Tween',
		description: 'Tween anything',
		canTransition: true,
		parameters: [{
			name: 'To',
			key: 'to',
			type: 'number',
			description: 'Value to tween to',
			'default': 0
		}, {
			name: 'Object',
			key: 'objectName',
			type: 'string',
			description: 'Object',
			'default': ''
		}, {
			name: 'Property',
			key: 'propertyName',
			type: 'string',
			description: 'Property',
			'default': ''
		}, {
			name: 'Time',
			key: 'time',
			type: 'number',
			description: 'Time it takes for this tween to complete',
			'default': 1000
		}, {
			name: 'Easing 1',
			key: 'easing1',
			type: 'dropdown',
			description: 'Easing 1',
			'default': 'Linear',
			options: ['Linear', 'Quadratic', 'Exponential', 'Circular', 'Elastic', 'Back', 'Bounce']
		}, {
			name: 'Easing 2',
			key: 'easing2',
			type: 'dropdown',
			description: 'Easing 2',
			'default': 'In',
			options: ['In', 'Out', 'InOut']
		}],
		transitions: [{
			key: 'complete',
			name: 'On Completion',
			description: 'Event fired when the tween completes'
		}]
	};

	TweenAction.prototype.configure = function (settings) {
		this.to = settings.to;
		this.relative = settings.relative;
		this.time = settings.time;
		if (settings.easing1 === 'Linear') {
			this.easing = window.TWEEN.Easing.Linear.None;
		} else {
			this.easing = window.TWEEN.Easing[settings.easing1][settings.easing2];
		}
		this.eventToEmit = { channel: settings.transitions.complete };
	};

	TweenAction.prototype._run = function (fsm) {
		var entity = fsm.getOwnerEntity();

		var object = eval('entity.' + this.objectName);
		var from = object[this.propertyName];
		FSMUtil.createComposableTween(entity, this.propertyName, );
	};

	return TweenAction;
});<commit_msg>#451 Fixes in Tween action<commit_after>define([
	'goo/statemachine/actions/Action',
	'goo/statemachine/FSMUtil'
	],
/** @lends */

function(
	Action,
	FSMUtil
) {
	'use strict';

	function TweenAction(/*id, settings*/) {
		Action.apply(this, arguments);
	}

	TweenAction.prototype = Object.create(Action.prototype);
	TweenAction.prototype.constructor = TweenAction;

	TweenAction.external = {
		name: 'Tween',
		description: 'Tween anything',
		canTransition: true,
		parameters: [{
			name: 'To',
			key: 'to',
			type: 'number',
			description: 'Value to tween to',
			'default': 0
		}, {
			name: 'Object',
			key: 'objectName',
			type: 'string',
			description: 'Object',
			'default': ''
		}, {
			name: 'Property',
			key: 'propertyName',
			type: 'string',
			description: 'Property',
			'default': ''
		}, {
			name: 'Time',
			key: 'time',
			type: 'number',
			description: 'Time it takes for this tween to complete',
			'default': 1000
		}, {
			name: 'Easing 1',
			key: 'easing1',
			type: 'dropdown',
			description: 'Easing 1',
			'default': 'Linear',
			options: ['Linear', 'Quadratic', 'Exponential', 'Circular', 'Elastic', 'Back', 'Bounce']
		}, {
			name: 'Easing 2',
			key: 'easing2',
			type: 'dropdown',
			description: 'Easing 2',
			'default': 'In',
			options: ['In', 'Out', 'InOut']
		}],
		transitions: [{
			key: 'complete',
			name: 'On Completion',
			description: 'Event fired when the tween completes'
		}]
	};

	TweenAction.prototype.configure = function (settings) {
		this.to = settings.to;
		this.objectName = settings.objectName;
		this.propertyName = settings.propertyName;
		this.time = settings.time;
		if (settings.easing1 === 'Linear') {
			this.easing = window.TWEEN.Easing.Linear.None;
		} else {
			this.easing = window.TWEEN.Easing[settings.easing1][settings.easing2];
		}
		this.eventToEmit = { channel: settings.transitions.complete };
	};

	TweenAction.prototype._run = function (fsm) {
		var entity = fsm.getOwnerEntity();

		var object = eval('entity.' + this.objectName);
		var from = object[this.propertyName];
		FSMUtil.createComposableTween(entity, this.propertyName, from, this.to, this.time);
	};

	return TweenAction;
});<|endoftext|>


<commit_before>const { CJS_FOLDER } = require('../constants');

// Package: Run in root
// Workspaces: Run in each package (copied into each)
const { context, tool } = process.beemo;
const { node, react } = tool.config.settings;
const compilerOptions = {
  allowJs: false,
  allowSyntheticDefaultImports: true,
  declaration: true,
  esModuleInterop: true,
  forceConsistentCasingInFileNames: true,
  lib: ['dom', 'esnext'],
  module: 'commonjs',
  noEmitOnError: true,
  noImplicitReturns: true,
  outDir: `./${CJS_FOLDER}`,
  pretty: true,
  removeComments: false,
  sourceMap: false,
  strict: true,
  target: node ? 'es2017' : 'es5',
};

if (react) {
  compilerOptions.jsx = 'react';
}

let include = ['./src/**/*', './types/**/*'];

// When --noEmit is passed, we want to run the type checker and include test files.
// Otherwise, we do not want to emit declarations for test files.
if (context.args.noEmit) {
  include.push('./tests/**/*');
}

// When --workspaces is passed, this config is copied into each package, so use local paths.
// However, when running through Jest at the root, we need to find all packages.
// Be sure not to breat non-workspace enabled projects.
if (!context.args.workspaces && tool.package.workspaces) {
  include = include.map(path => `./packages/*${path.slice(1)}`);
}

module.exports = {
  compilerOptions,
  include,
};
<commit_msg>Add args to TS.<commit_after>const { CJS_FOLDER } = require('../constants');

// Package: Run in root
// Workspaces: Run in each package (copied into each)
const { context, tool } = process.beemo;
const { node, react } = tool.config.settings;
const compilerOptions = {
  allowJs: false,
  allowSyntheticDefaultImports: true,
  declaration: true,
  esModuleInterop: true,
  experimentalDecorators: context.args.decorators || false,
  forceConsistentCasingInFileNames: true,
  lib: ['dom', 'esnext'],
  module: 'commonjs',
  noEmitOnError: true,
  noImplicitReturns: true,
  outDir: `./${CJS_FOLDER}`,
  pretty: true,
  removeComments: false,
  sourceMap: context.args.sourceMaps || false,
  strict: true,
  target: node ? 'es2017' : 'es5',
};

if (react) {
  compilerOptions.jsx = 'react';
}

let include = ['./src/**/*', './types/**/*'];

// When --noEmit is passed, we want to run the type checker and include test files.
// Otherwise, we do not want to emit declarations for test files.
if (context.args.noEmit) {
  include.push('./tests/**/*');
}

// When --workspaces is passed, this config is copied into each package, so use local paths.
// However, when running through Jest at the root, we need to find all packages.
// Be sure not to breat non-workspace enabled projects.
if (!context.args.workspaces && tool.package.workspaces) {
  include = include.map(path => `./packages/*${path.slice(1)}`);
}

module.exports = {
  compilerOptions,
  include,
};
<|endoftext|>


<commit_before>angular.module('efg.findusView', [
	'uiGmapgoogle-maps',
	'geolocation',
	'ng'
])

.config(function($routeProvider) {
	$routeProvider.when('/findus', {
		controller: 'FindusCtrl as findus',
		templateUrl: 'efg.findusView.tpl.html'
	});
})

.controller('FindusCtrl', function(geolocation) {
	// need to create marker position twice (not as one object)
	// or marker won't update when map is moved
	var latitude = 49.49172
	  , longitude = 8.435441
	  , delta = 0.0001;

	this.map = {
		center: {
			latitude: latitude,
			longitude: longitude
		},
		zoom: 15,
		options: {
			backgroundColor: 'rgb(233,229,220)',
			scrollwheel: false
		},
		bounds: {
			northeast: {
				latitude: latitude * (1 + delta),
				longitude: longitude * (1 + delta)
			},
			southwest: {
				latitude: latitude * (1 - delta),
				longitude: longitude * (1 - delta)
			}
		}
	};
	this.we = {
		coords: {
			latitude: latitude,
			longitude: longitude
		},
		id: 0
	};
	this.you = undefined;

	geolocation.getLocation().then(angular.bind(this, function success(data) {
		this.you = {
			coords: data.coords,
			id: 1
		};
		this.map.bounds = {
			northeast: {
				// to north == +lat
				latitude: Math.max(this.we.coords.latitude, this.you.coords.latitude) * (1 + delta),
				// to east == +lng
				longitude: Math.max(this.we.coords.longitude, this.you.coords.longitude) * (1 + delta)
			},
			southwest: {
				latitude: Math.min(this.we.coords.latitude, this.you.coords.latitude) * (1 - delta),
				longitude: Math.min(this.we.coords.longitude, this.you.coords.longitude) * (1 - delta)
			}
		};
	}));
});<commit_msg>added dependencies to efg.componentDirective and ngRoute<commit_after>angular.module('efg.findusView', [
	'efg.componentDirective',
	'uiGmapgoogle-maps',
	'geolocation',
	'ng',
	'ngRoute'
])

.config(function($routeProvider) {
	$routeProvider.when('/findus', {
		controller: 'FindusCtrl as findus',
		templateUrl: 'efg.findusView.tpl.html'
	});
})

.controller('FindusCtrl', function(geolocation) {
	// need to create marker position twice (not as one object)
	// or marker won't update when map is moved
	var latitude = 49.49172
	  , longitude = 8.435441
	  , delta = 0.0001;

	this.map = {
		center: {
			latitude: latitude,
			longitude: longitude
		},
		zoom: 15,
		options: {
			backgroundColor: 'rgb(233,229,220)',
			scrollwheel: false
		},
		bounds: {
			northeast: {
				latitude: latitude * (1 + delta),
				longitude: longitude * (1 + delta)
			},
			southwest: {
				latitude: latitude * (1 - delta),
				longitude: longitude * (1 - delta)
			}
		}
	};
	this.we = {
		coords: {
			latitude: latitude,
			longitude: longitude
		},
		id: 0
	};
	this.you = undefined;

	geolocation.getLocation().then(angular.bind(this, function success(data) {
		this.you = {
			coords: data.coords,
			id: 1
		};
		this.map.bounds = {
			northeast: {
				// to north == +lat
				latitude: Math.max(this.we.coords.latitude, this.you.coords.latitude) * (1 + delta),
				// to east == +lng
				longitude: Math.max(this.we.coords.longitude, this.you.coords.longitude) * (1 + delta)
			},
			southwest: {
				latitude: Math.min(this.we.coords.latitude, this.you.coords.latitude) * (1 - delta),
				longitude: Math.min(this.we.coords.longitude, this.you.coords.longitude) * (1 - delta)
			}
		};
	}));
});<|endoftext|>


<commit_before>import React, { Component } from "react";
import { Button } from "reactstrap";
import { Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
import { UncontrolledTooltip } from "reactstrap";

import AceEditor from "react-ace";
import brace from "brace";
import "brace/mode/json";
import "brace/mode/text";
import "brace/ext/searchbox";

import "./InstanceBtnSettings.css";

class InstanceBtnSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsOpen: false,
      modalIsFS: false,
      code: ""
    };

    this.toggleIsOpen = this.toggleIsOpen.bind(this);
    this.toggleIsFS = this.toggleIsFS.bind(this);
    this.onCodeChange = this.onCodeChange.bind(this);
  }

  toggleIsOpen() {
    this.setState({
      modalIsOpen: !this.state.modalIsOpen
    });
  }

  toggleIsFS() {
    this.setState({
      modalIsFS: !this.state.modalIsFS
    });

    // need also to resize the ACE editor of it will truncate the text
    setImmediate(
      function() {
        this.refs[this.props.instance.technicalName + "-ace"].editor.resize();
      }.bind(this)
    );
  }

  onCodeChange(newValue) {
    this.setState({
      code: newValue
    });
  }

  render() {
    return (

        <Button
          color="link"
          className={this.props.classNameBtn + " ezmaster-a-cog"}
          onClick={this.toggleIsOpen}
        >

        </Button>

        <Modal
          isOpen={this.state.modalIsOpen}
          toggle={this.toggleIsOpen}
          className={this.state.modalIsFS ? "modal-fullscreen" : ""}
        >
          <ModalHeader toggle={this.toggleIsOpen}>
            Edit the {this.props.instance.technicalName}{" "}
            configuration{" "}
          </ModalHeader>
          <ModalBody>
            <AceEditor
              mode={Math.random() > 0.5 ? "text" : "json"}
              theme="github"
              width="100%"
              height=""
              focus={true}
              wrapEnabled={true}
              tabSize={2}
              ref={this.props.instance.technicalName + "-ace"}
              name={this.props.instance.technicalName + "-ace"}
              enableBasicAutocompletion={true}
              enableLiveAutocompletion={true}
              enableSnippets={true}
              fontSize={"1.5rem"}
              onChange={this.onCodeChange}
              value={this.state.code}
            />
          </ModalBody>
          <ModalFooter>
            <Button
              color="link"
              onClick={this.toggleIsFS}
              className="modal-fullscreen-btn"
            >

            </Button>
            <UncontrolledTooltip
              placement="top"
              target={this.props.instance.technicalName + "-settings-fs"}
            >
              Edit the configuration in fullscreen mode.
            </UncontrolledTooltip>
            <Button color="primary" onClick={this.toggleIsOpen}>
              XXXX
            </Button>{" "}
            <Button color="secondary" onClick={this.toggleIsOpen}>
              YYY
            </Button>
          </ModalFooter>
        </Modal>

        <UncontrolledTooltip
          placement="top"
          target={this.props.instance.technicalName + "-cog"}
        >
          Edit settings of {this.props.instance.technicalName}
        </UncontrolledTooltip>

    );
  }
}

export default InstanceBtnSettings;
<commit_msg>better code update system in the ace editor<commit_after>import React, { Component } from "react";
import { Button } from "reactstrap";
import { Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
import { UncontrolledTooltip } from "reactstrap";

import AceEditor from "react-ace";
import brace from "brace";
import "brace/mode/json";
import "brace/mode/text";
import "brace/ext/searchbox";
import "brace/theme/github";

import "./InstanceBtnSettings.css";

class InstanceBtnSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsOpen: false,
      modalIsFS: false,
      code: ""
    };
    this.currentCode = "";
    this.toggleIsOpen = this.toggleIsOpen.bind(this);
    this.toggleIsFS = this.toggleIsFS.bind(this);
    this.onCodeChange = this.onCodeChange.bind(this);
  }

  toggleIsOpen() {
    this.setState({
      modalIsOpen: !this.state.modalIsOpen
    });
  }

  toggleIsFS() {
    this.setState({
      modalIsFS: !this.state.modalIsFS,
      code: this.currentCode
    });

    // need also to resize the ACE editor of it will truncate the text
    // we also re-focus to the edit area
    setImmediate(
      function() {
        this.refs[this.props.instance.technicalName + "-ace"].editor.resize();
        this.refs[this.props.instance.technicalName + "-ace"].editor.focus();
      }.bind(this)
    );
  }

  onCodeChange(newValue) {
    // Do not store the new value in the store now because it will
    // re-render the react component and it will generates stranges error
    // in the ace editor.
    // This is why we use the currentCode temp variable and push it in
    // the store just when switching to fullscreen (because re-render will occurs).
    this.currentCode = newValue;
  }

  render() {
    return (

        <Button
          color="link"
          className={this.props.classNameBtn + " ezmaster-a-cog"}
          onClick={this.toggleIsOpen}
        >

        </Button>

        <Modal
          isOpen={this.state.modalIsOpen}
          toggle={this.toggleIsOpen}
          className={this.state.modalIsFS ? "modal-fullscreen" : ""}
        >
          <ModalHeader toggle={this.toggleIsOpen}>
            Edit the {this.props.instance.technicalName}{" "}
            configuration{" "}
          </ModalHeader>
          <ModalBody>
            <AceEditor
              mode={Math.random() > 0.5 ? "text" : "json"}
              theme="github"
              width="100%"
              height=""
              focus={true}
              wrapEnabled={true}
              tabSize={2}
              ref={this.props.instance.technicalName + "-ace"}
              name={this.props.instance.technicalName + "-ace"}
              enableBasicAutocompletion={true}
              enableLiveAutocompletion={true}
              enableSnippets={true}
              fontSize={"1.5rem"}
              onChange={this.onCodeChange}
              value={this.state.code}
            />
          </ModalBody>
          <ModalFooter>
            <Button
              color="link"
              onClick={this.toggleIsFS}
              className="modal-fullscreen-btn"
            >

            </Button>
            <UncontrolledTooltip
              placement="top"
              target={this.props.instance.technicalName + "-settings-fs"}
            >
              Edit the configuration in fullscreen mode.
            </UncontrolledTooltip>
            <Button color="primary" onClick={this.toggleIsOpen}>
              XXXX
            </Button>{" "}
            <Button color="secondary" onClick={this.toggleIsOpen}>
              YYY
            </Button>
          </ModalFooter>
        </Modal>

        <UncontrolledTooltip
          placement="top"
          target={this.props.instance.technicalName + "-cog"}
        >
          Edit settings of {this.props.instance.technicalName}
        </UncontrolledTooltip>

    );
  }
}

export default InstanceBtnSettings;
<|endoftext|>


<commit_before>import React, { Component } from "react";
import { Button } from "reactstrap";
import { Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
import { UncontrolledTooltip } from "reactstrap";
import { toast } from "react-toastify";

import AceEditor from "react-ace";
import "brace/mode/json";
import "brace/mode/text";
import "brace/ext/searchbox";
import "brace/theme/github";

import "./InstanceBtnSettings.css";

import { updateInstanceConfig } from "./ModelInstances2.js";

class InstanceBtnSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsOpen: false,
      modalIsFS: false,
      code: ""
    };
    this.currentCode = "";
    this.toggleIsOpen = this.toggleIsOpen.bind(this);
    this.toggleIsFS = this.toggleIsFS.bind(this);
    this.onCodeChange = this.onCodeChange.bind(this);
    this.doUpdateInstanceConfig = this.doUpdateInstanceConfig.bind(this);
  }

  toggleIsOpen() {
    this.setState({
      modalIsOpen: !this.state.modalIsOpen
    });
  }

  toggleIsFS() {
    this.setState({
      modalIsFS: !this.state.modalIsFS,
      code: this.currentCode
    });

    // need also to resize the ACE editor of it will truncate the text
    // we also re-focus to the edit area
    setImmediate(
      function() {
        this.refs[this.props.instance.technicalName + "-ace"].editor.resize();
        this.refs[this.props.instance.technicalName + "-ace"].editor.focus();
      }.bind(this)
    );
  }

  onCodeChange(newValue) {
    // Do not store the new value in the store now because it will
    // re-render the react component and it will generates stranges error
    // in the ace editor.
    // This is why we use the currentCode temp variable and push it in
    // the store just when switching to fullscreen (because re-render will occurs).
    this.currentCode = newValue;
  }

  doUpdateInstanceConfig() {
    const self = this;

    // async instance config update
    updateInstanceConfig(
      self.props.instance.containerId,
      self.currentCode,
      function(err) {
        if (err) {
          toast.error(

              {self.props.instance.technicalName} config update error:{" "}
              {"" + err}

          );
        } else {
          toast.info(

              {self.props.instance.technicalName} config has been
              updated

          );
        }
      }
    );

    // hide the popup
    self.setState({
      modalIsOpen: !self.state.modalIsOpen
    });
  }

  render() {
    return (

        <Button
          color="link"
          className={this.props.classNameBtn + " ezmaster-a-cog"}
          onClick={this.toggleIsOpen}
        >

        </Button>

        <Modal
          isOpen={this.state.modalIsOpen}
          toggle={this.toggleIsOpen}
          className={
            this.state.modalIsFS
              ? "ezmaster-modal-settings modal-fullscreen"
              : "ezmaster-modal-settings"
          }
        >
          <ModalHeader toggle={this.toggleIsOpen}>
            Edit the {this.props.instance.technicalName}{" "}
            configuration{" "}
          </ModalHeader>
          <ModalBody>
            <AceEditor
              mode={Math.random() > 0.5 ? "text" : "json"}
              theme="github"
              width="100%"
              height=""
              focus={true}
              wrapEnabled={true}
              tabSize={2}
              ref={this.props.instance.technicalName + "-ace"}
              name={this.props.instance.technicalName + "-ace"}
              enableBasicAutocompletion={true}
              enableLiveAutocompletion={true}
              enableSnippets={true}
              fontSize={"1.5rem"}
              onChange={this.onCodeChange}
              value={this.state.code}
            />
          </ModalBody>
          <ModalFooter>
            <Button
              color="link"
              onClick={this.toggleIsFS}
              className="modal-fullscreen-btn"
            >

            </Button>
            <UncontrolledTooltip
              placement="top"
              target={this.props.instance.technicalName + "-settings-fs"}
            >
              Edit the configuration in fullscreen mode.
            </UncontrolledTooltip>
            <Button color="secondary" onClick={this.toggleIsOpen}>
              Cancel
            </Button>
            <Button color="primary" onClick={this.doUpdateInstanceConfig}>
              Update
            </Button>
          </ModalFooter>
        </Modal>

        <UncontrolledTooltip
          placement="top"
          target={this.props.instance.technicalName + "-cog"}
        >
          Edit settings of {this.props.instance.technicalName}
        </UncontrolledTooltip>

    );
  }
}

export default InstanceBtnSettings;
<commit_msg>load instance config from ajax in the modal editor<commit_after>import React, { Component } from "react";
import { Button } from "reactstrap";
import { Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
import { UncontrolledTooltip } from "reactstrap";
import { toast } from "react-toastify";

import AceEditor from "react-ace";
import "brace/mode/json";
import "brace/mode/text";
import "brace/ext/searchbox";
import "brace/theme/github";

import "./InstanceBtnSettings.css";

import { updateInstanceConfig } from "./ModelInstances2.js";
import { fetchInstanceDetail } from "./ModelInstances2.js";

class InstanceBtnSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsOpen: false,
      modalIsFS: false,
      code: "",
      codeFormat: "json"
    };
    this.currentCode = "";
    this.toggleModal = this.toggleModal.bind(this);
    this.toggleIsFS = this.toggleIsFS.bind(this);
    this.onCodeChange = this.onCodeChange.bind(this);
    this.doUpdateInstanceConfig = this.doUpdateInstanceConfig.bind(this);
  }

  toggleModal() {
    const self = this;

    self.setState({
      modalIsOpen: !this.state.modalIsOpen
    });

    // fetch the instance config just when the popup is open
    if (!self.state.modalIsOpen) {
      fetchInstanceDetail(self.props.instance.containerId, function(err, data) {
        try {
          JSON.parse(data.config);
          self.setState({ code: data.config, codeFormat: "json" });
        } catch (err2) {
          self.setState({ code: data.config, codeFormat: "text" });
        }
        //{Math.random() > 0.5 ? "text" : "json"}
      });
    }
  }

  toggleIsFS() {
    this.setState({
      modalIsFS: !this.state.modalIsFS,
      code: this.currentCode
    });

    // need also to resize the ACE editor of it will truncate the text
    // we also re-focus to the edit area
    setImmediate(
      function() {
        this.refs[this.props.instance.technicalName + "-ace"].editor.resize();
        this.refs[this.props.instance.technicalName + "-ace"].editor.focus();
      }.bind(this)
    );
  }

  onCodeChange(newValue) {
    // Do not store the new value in the store now because it will
    // re-render the react component and it will generates stranges error
    // in the ace editor.
    // This is why we use the currentCode temp variable and push it in
    // the store just when switching to fullscreen (because re-render will occurs).
    this.currentCode = newValue;
  }

  doUpdateInstanceConfig() {
    const self = this;

    // async instance config update
    updateInstanceConfig(
      self.props.instance.containerId,
      self.currentCode,
      function(err) {
        if (err) {
          toast.error(

              {self.props.instance.technicalName} config update error:{" "}
              {"" + err}

          );
        } else {
          toast.info(

              {self.props.instance.technicalName} config has been
              updated

          );
        }
      }
    );

    // hide the popup
    self.setState({
      modalIsOpen: !self.state.modalIsOpen
    });
  }

  render() {
    return (

        <Button
          color="link"
          className={this.props.classNameBtn + " ezmaster-a-cog"}
          onClick={this.toggleModal}
        >

        </Button>

        <Modal
          isOpen={this.state.modalIsOpen}
          toggle={this.toggleModal}
          className={
            this.state.modalIsFS
              ? "ezmaster-modal-settings modal-fullscreen"
              : "ezmaster-modal-settings"
          }
        >
          <ModalHeader toggle={this.toggleModal}>
            Edit the {this.props.instance.technicalName}{" "}
            configuration{" "}
          </ModalHeader>
          <ModalBody>
            <AceEditor
              mode={this.state.codeFormat}
              theme="github"
              width="100%"
              height=""
              focus={true}
              wrapEnabled={true}
              tabSize={2}
              ref={this.props.instance.technicalName + "-ace"}
              name={this.props.instance.technicalName + "-ace"}
              enableBasicAutocompletion={true}
              enableLiveAutocompletion={true}
              enableSnippets={true}
              fontSize={"1.5rem"}
              onChange={this.onCodeChange}
              value={this.state.code}
            />
          </ModalBody>
          <ModalFooter>
            <Button
              color="link"
              onClick={this.toggleIsFS}
              className="modal-fullscreen-btn"
            >

            </Button>
            <UncontrolledTooltip
              placement="top"
              target={this.props.instance.technicalName + "-settings-fs"}
            >
              Edit the configuration in fullscreen mode.
            </UncontrolledTooltip>
            <Button color="secondary" onClick={this.toggleModal}>
              Cancel
            </Button>
            <Button color="primary" onClick={this.doUpdateInstanceConfig}>
              Update
            </Button>
          </ModalFooter>
        </Modal>

        <UncontrolledTooltip
          placement="top"
          target={this.props.instance.technicalName + "-cog"}
        >
          Edit settings of {this.props.instance.technicalName}
        </UncontrolledTooltip>

    );
  }
}

export default InstanceBtnSettings;
<|endoftext|>


<commit_before>/* eslint-disable import/prefer-default-export */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import {
  CellActionsLookup,
  editCountedQuantityWithReason,
  editStocktakeBatchCountedQuantityWithReason,
} from './cellActions';
import { RowActionsLookup } from './rowActions';
import { TableActionsLookup } from './tableActions';
import { PageActionsLookup } from './pageActions';

/**
 * Serves a page the actions it requires given it's routeName.
 *
 * Actions can be overriden if different behaviour is required for
 * a particular action in a given circumstance.
 *
 * I.E When reasons are defined, `editCountedQuantity` should be
 * replaced with the action `editCountedQuantityWithReason`.
 *
 */

/**
 * Standard base page actions.
 */
const BasePageActions = {
  ...CellActionsLookup,
  ...RowActionsLookup,
  ...TableActionsLookup,
  ...PageActionsLookup,
};

/**
 * Actions for `stocktakeEditPage` when reasons are defined.
 */
const stocktakeEditorWithReasons = {
  ...BasePageActions,
  editCountedQuantity: editCountedQuantityWithReason,
};

const stocktakeBatchEditModalWithReasons = {
  ...BasePageActions,
  editCountedQuantity: editStocktakeBatchCountedQuantityWithReason,
};

/**
 * If actions need to be overriden for a particular routeName,
 * adding them here will pass that new set of actions to the
 * screen when navigating.
 */
const NON_DEFAULT_PAGE_ACTIONS = {
  stocktakeEditorWithReasons,
  stocktakeBatchEditModalWithReasons,
};

/**
 * Fetches the actions object for a given route.
 *
 * @param {String} routeName Name of the route being navigated to.
 */
export const getPageActions = routeName => NON_DEFAULT_PAGE_ACTIONS[routeName] || BasePageActions;
<commit_msg>Add updated override for reasons counted total quantity<commit_after>/* eslint-disable import/prefer-default-export */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import {
  CellActionsLookup,
  editCountedQuantityWithReason,
  editStocktakeBatchCountedQuantityWithReason,
} from './cellActions';
import { RowActionsLookup } from './rowActions';
import { TableActionsLookup } from './tableActions';
import { PageActionsLookup } from './pageActions';

/**
 * Serves a page the actions it requires given it's routeName.
 *
 * Actions can be overriden if different behaviour is required for
 * a particular action in a given circumstance.
 *
 * I.E When reasons are defined, `editCountedQuantity` should be
 * replaced with the action `editCountedQuantityWithReason`.
 *
 */

/**
 * Standard base page actions.
 */
const BasePageActions = {
  ...CellActionsLookup,
  ...RowActionsLookup,
  ...TableActionsLookup,
  ...PageActionsLookup,
};

/**
 * Actions for `stocktakeEditPage` when reasons are defined.
 */
const stocktakeEditorWithReasons = {
  ...BasePageActions,
  editCountedQuantity: editCountedQuantityWithReason,
};

const stocktakeBatchEditModalWithReasons = {
  ...BasePageActions,
  editStocktakeBatchCountedQuantity: editStocktakeBatchCountedQuantityWithReason,
};

/**
 * If actions need to be overriden for a particular routeName,
 * adding them here will pass that new set of actions to the
 * screen when navigating.
 */
const NON_DEFAULT_PAGE_ACTIONS = {
  stocktakeEditorWithReasons,
  stocktakeBatchEditModalWithReasons,
};

/**
 * Fetches the actions object for a given route.
 *
 * @param {String} routeName Name of the route being navigated to.
 */
export const getPageActions = routeName => NON_DEFAULT_PAGE_ACTIONS[routeName] || BasePageActions;
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { newSortDataBy } from '../../../utilities';

/**
 * Immutably clears the current focus
 * @param {object} currState  the copy of state you want affected
 * @return {object}           New state with no cell focused
 */
const clearFocus = state => {
  const { dataState, currentFocusedRowKey } = state;
  if (!currentFocusedRowKey) {
    return state;
  }

  const newDataState = new Map(dataState);
  const currentRowState = newDataState.get(currentFocusedRowKey);
  newDataState.set(currentFocusedRowKey, {
    ...currentRowState,
    focusedColumn: null,
  });

  return { ...state, dataState: newDataState, currentFocusedRowKey: null };
};

/**
 * Immutably sets the current focus to the cell identified by `rowKey` and `columnKey`
 * @param {object} state  The copy of state to affect
 * @param {string} rowKey     The key of the row the cell to focus is in
 * @param {string} columnKey  The key of the column the cell to focus is in
 * @return {object}           A new object with a cell focused
 */
const setFocus = (state, rowKey, columnKey) => {
  const { dataState, currentFocusedRowKey } = state;
  const newDataState = new Map(dataState);

  // Clear previous focus if in a different row
  if (currentFocusedRowKey && rowKey !== currentFocusedRowKey) {
    const currentRowState = newDataState.get(currentFocusedRowKey);
    newDataState.set(currentFocusedRowKey, {
      ...currentRowState,
      focusedColumn: null,
    });
  }

  // Update focusedColumn in specified row
  const nextRowState = newDataState.get(rowKey);
  newDataState.set(rowKey, {
    ...nextRowState,
    focusedColumn: columnKey,
  });

  return {
    ...state,
    dataState: newDataState,
    currentFocusedRowKey: rowKey,
  };
};

/**
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 */
export const filterData = (state, action) => {
  const { backingData, filterDataKeys, sortBy, isAscending } = state;
  const { searchTerm } = action;

  const columnKeyToDataType = {
    itemCode: 'string',
    itemName: 'string',
    availableQuantity: 'number',
    totalQuantity: 'number',
  };

  const queryString = filterDataKeys
    .map(filterTerm => `${filterTerm} BEGINSWITH[c]  $0`)
    .join(' OR ');

  const newData = newSortDataBy(
    backingData.filtered(queryString, searchTerm).slice(),
    sortBy,
    columnKeyToDataType[sortBy],
    isAscending
  );
  return { ...state, data: newData };
};

export const editTotalQuantity = (state, action) => {
  const { rowKey } = action;
  const { dataState } = state;

  // Change object reference of row in `dataState` to trigger rerender of that row.
  // Realm object reference in `data` can't be affected in any tidy manner.
  const newDataState = new Map(dataState);
  const nextRowState = newDataState.get(rowKey);
  newDataState.set(rowKey, {
    ...nextRowState,
  });

  return {
    ...state,
    dataState: newDataState,
  };
};

/**
 * Focus the next appropriate cell after the current cell provided in action
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 */
export const focusNextCell = (state, action) => {
  const { data, columns, keyExtractor } = state;
  const { rowKey, columnKey } = action;

  // Handle finding next cell to focus
  let nextEditableColKey;
  const currentColIndex = columns.findIndex(col => col.key === columnKey);
  for (let index = currentColIndex + 1; index < columns.length; index++) {
    if (columns[index].type === 'editable') {
      nextEditableColKey = columns[index].key;
      break;
    }
  }

  if (nextEditableColKey) {
    // Focus next editable cell in row
    return setFocus(state, rowKey, nextEditableColKey);
  }

  // Attempt moving focus to next row
  const nextRowIndex = data.findIndex(row => keyExtractor(row) === rowKey) + 1;

  if (nextRowIndex < data.length) {
    // Focus first editable cell in next row
    const nextRowKey = keyExtractor(data[nextRowIndex]);
    const firstEditableColKey = columns.find(col => col.type === 'editable').key;
    return setFocus(state, nextRowKey, firstEditableColKey);
  }

  // We were on the last row and last column, so unfocus current cell
  return clearFocus(state);
};

/**
 * Sets the provided row in action as selected
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'selectRow', rowKey }
 */
export const selectRow = (state, action) => {
  const { dataState } = state;
  const { rowKey } = action;
  const newDataState = new Map(dataState);

  const rowState = newDataState.get(rowKey);
  newDataState.set(rowKey, {
    ...rowState,
    isSelected: true,
  });

  return { ...state, dataState: newDataState, hasSelection: true };
};

/**
 * Removes the provided row in action from being
 * selected.
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'deselectRow', rowKey }
 */
export const deselectRow = (state, action) => {
  const { dataState } = state;
  const { rowKey } = action;
  const newDataState = new Map(dataState);

  const rowState = newDataState.get(rowKey);
  newDataState.set(rowKey, {
    ...rowState,
    isSelected: false,
  });

  let hasSelection = false;
  // eslint-disable-next-line no-restricted-syntax
  for (const row of newDataState.values()) {
    if (row.isSelected) {
      hasSelection = true;
      break;
    }
  }

  return { ...state, dataState: newDataState, hasSelection };
};

/**
 * Removes all rows from being selected.
 * @param {Object} state  The current state
 * Action: { type: 'deselectAll' }
 */
export const deselectAll = state => {
  const { dataState } = state;
  const newDataState = new Map(dataState);

  // eslint-disable-next-line no-restricted-syntax
  for (const [rowKey, rowState] of newDataState.entries()) {
    if (rowState.isSelected) {
      newDataState.set(rowKey, {
        ...rowState,
        isSelected: false,
      });
    }
  }
  return { ...state, dataState: newDataState, hasSelection: false };
};

/**
 * Focuses the cell provided in the action passed
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * action: { type: 'focusCell', rowKey, columnKey }
 */
export const focusCell = (state, action) => {
  // Clear any existing focus and focus cell specified in action
  const { rowKey, columnKey } = action;
  return setFocus(state, rowKey, columnKey);
};

/**
 * Sorts the current set of data by the provided
 * key and direction in action.
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'sortData', sortBy }
 * sortBy: String key of the field of the objects to sort by.
 */
export const sortData = (state, action) => {
  const { data, isAscending, sortBy } = state;
  const { sortBy: newSortBy } = action;
  const columnKeyToDataType = {
    itemCode: 'string',
    itemName: 'string',
    availableQuantity: 'number',
    totalQuantity: 'number',
  };

  // If the new sortBy is the same as the sortBy in state, then invert isAscending
  // that was set by the last sortBy action. Otherwise, default to true.
  const newIsAscending = newSortBy === sortBy ? !isAscending : true;

  const newData = newSortDataBy(data, newSortBy, columnKeyToDataType[newSortBy], newIsAscending);
  return { ...state, data: newData, sortBy: newSortBy, isAscending: newIsAscending };
};

/**
 * Opens a basic modal which does not require any other value
 * to be set upon opening. i.e. text editors
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'openBasicModal', modalKey }
 */
export const openBasicModal = (state, action) => {
  const { modalKey } = action;
  return { ...state, modalKey };
};

/**
 * Sets the modal open state to false, closing any
 * modal that is open.
 *
 * @param {Object} state  The current state
 * Action: { type: 'closeBasicModal' }
 */
export const closeBasicModal = state => ({ ...state, modalKey: '' });

/**
 * Adds all items from a master list to the pageObject held
 * in state - either a Requisition or Transaction.
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'addMasterListItems', objectType }
 */
export const addMasterListItems = state => {
  const { backingData } = state;
  const newData = backingData.slice();

  return { ...state, data: newData };
};

/**
 * Creates an Item (Either Requisition or Transaction), and appends
 * this item to the data array for a page.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'addItem', item, addedItemType }
 */
export const addItem = (state, action) => {
  const { data } = state;
  const { item } = action;

  return { ...state, data: [item, ...data], modalKey: '' };
};

/**
 * Reducer helper method for editing a non-setter field on a
 * realm object. Should be called by more explicit reducer
 * methods and not exported to avoid misuse. To create a reducer
 * method for setting a simple value for a realm object, create a
 * more explicit reducer method with logic specific to that field
 * contained, and call this method. See editTheirRef.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'editPageObject', value, field, pageObjectType }
 */
const editPageObject = state => ({ ...state, modalKey: '' });

/**
 * Edits the passed pageObject 'theirRef' field with the value supplied.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'editPageObject', value, pageObjectType }
 */
export const editTheirRef = (state, action) => {
  const { pageObject } = state;
  const { value } = action;

  const { theirRef } = pageObject;

  if (theirRef !== value) return { ...editPageObject(state, { ...action, field: 'theirRef' }) };
  return state;
};

/**
 * Edits the passed pageObject 'comment' field with the value supplied.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'editPageObject', value, pageObjectType }
 */
export const editComment = (state, action) => {
  const { pageObject } = state;
  const { value } = action;

  const { comment } = pageObject;

  if (comment !== value) return { ...editPageObject(state, { ...action, field: 'comment' }) };
  return state;
};

/**
 * Deletes the selected RequisitionItems or
 * TransactionItems held in state. Where each selected
 * item is indicated by DataState[rowKey].isSelected.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 */
export const deleteItemsById = state => {
  const { data } = state;

  const newDataState = new Map();
  const newData = data.filter(item => item.isValid());

  return {
    ...state,
    data: newData,
    dataState: newDataState,
    hasSelection: false,
    modalKey: '',
  };
};

/**
 * Simply refresh's the data object in state to
 * correctly match the backingData when side effects
 * such as finalizing manipulate the state of a page
 * from outside the reducer. Should only be used when
 * there are no other options.
 *
 * @param {Object} state  The current state
 */
export const refreshData = state => {
  const { backingData } = state;
  return { ...state, data: backingData.slice() };
};
<commit_msg>Add correct updating of sort state after adding an item<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { newSortDataBy } from '../../../utilities';

/**
 * Immutably clears the current focus
 * @param {object} currState  the copy of state you want affected
 * @return {object}           New state with no cell focused
 */
const clearFocus = state => {
  const { dataState, currentFocusedRowKey } = state;
  if (!currentFocusedRowKey) {
    return state;
  }

  const newDataState = new Map(dataState);
  const currentRowState = newDataState.get(currentFocusedRowKey);
  newDataState.set(currentFocusedRowKey, {
    ...currentRowState,
    focusedColumn: null,
  });

  return { ...state, dataState: newDataState, currentFocusedRowKey: null };
};

/**
 * Immutably sets the current focus to the cell identified by `rowKey` and `columnKey`
 * @param {object} state  The copy of state to affect
 * @param {string} rowKey     The key of the row the cell to focus is in
 * @param {string} columnKey  The key of the column the cell to focus is in
 * @return {object}           A new object with a cell focused
 */
const setFocus = (state, rowKey, columnKey) => {
  const { dataState, currentFocusedRowKey } = state;
  const newDataState = new Map(dataState);

  // Clear previous focus if in a different row
  if (currentFocusedRowKey && rowKey !== currentFocusedRowKey) {
    const currentRowState = newDataState.get(currentFocusedRowKey);
    newDataState.set(currentFocusedRowKey, {
      ...currentRowState,
      focusedColumn: null,
    });
  }

  // Update focusedColumn in specified row
  const nextRowState = newDataState.get(rowKey);
  newDataState.set(rowKey, {
    ...nextRowState,
    focusedColumn: columnKey,
  });

  return {
    ...state,
    dataState: newDataState,
    currentFocusedRowKey: rowKey,
  };
};

/**
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 */
export const filterData = (state, action) => {
  const { backingData, filterDataKeys, sortBy, isAscending } = state;
  const { searchTerm } = action;

  const columnKeyToDataType = {
    itemCode: 'string',
    itemName: 'string',
    availableQuantity: 'number',
    totalQuantity: 'number',
  };

  const queryString = filterDataKeys
    .map(filterTerm => `${filterTerm} BEGINSWITH[c]  $0`)
    .join(' OR ');

  const newData = newSortDataBy(
    backingData.filtered(queryString, searchTerm).slice(),
    sortBy,
    columnKeyToDataType[sortBy],
    isAscending
  );
  return { ...state, data: newData };
};

export const editTotalQuantity = (state, action) => {
  const { rowKey } = action;
  const { dataState } = state;

  // Change object reference of row in `dataState` to trigger rerender of that row.
  // Realm object reference in `data` can't be affected in any tidy manner.
  const newDataState = new Map(dataState);
  const nextRowState = newDataState.get(rowKey);
  newDataState.set(rowKey, {
    ...nextRowState,
  });

  return {
    ...state,
    dataState: newDataState,
  };
};

/**
 * Focus the next appropriate cell after the current cell provided in action
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 */
export const focusNextCell = (state, action) => {
  const { data, columns, keyExtractor } = state;
  const { rowKey, columnKey } = action;

  // Handle finding next cell to focus
  let nextEditableColKey;
  const currentColIndex = columns.findIndex(col => col.key === columnKey);
  for (let index = currentColIndex + 1; index < columns.length; index++) {
    if (columns[index].type === 'editable') {
      nextEditableColKey = columns[index].key;
      break;
    }
  }

  if (nextEditableColKey) {
    // Focus next editable cell in row
    return setFocus(state, rowKey, nextEditableColKey);
  }

  // Attempt moving focus to next row
  const nextRowIndex = data.findIndex(row => keyExtractor(row) === rowKey) + 1;

  if (nextRowIndex < data.length) {
    // Focus first editable cell in next row
    const nextRowKey = keyExtractor(data[nextRowIndex]);
    const firstEditableColKey = columns.find(col => col.type === 'editable').key;
    return setFocus(state, nextRowKey, firstEditableColKey);
  }

  // We were on the last row and last column, so unfocus current cell
  return clearFocus(state);
};

/**
 * Sets the provided row in action as selected
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'selectRow', rowKey }
 */
export const selectRow = (state, action) => {
  const { dataState } = state;
  const { rowKey } = action;
  const newDataState = new Map(dataState);

  const rowState = newDataState.get(rowKey);
  newDataState.set(rowKey, {
    ...rowState,
    isSelected: true,
  });

  return { ...state, dataState: newDataState, hasSelection: true };
};

/**
 * Removes the provided row in action from being
 * selected.
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'deselectRow', rowKey }
 */
export const deselectRow = (state, action) => {
  const { dataState } = state;
  const { rowKey } = action;
  const newDataState = new Map(dataState);

  const rowState = newDataState.get(rowKey);
  newDataState.set(rowKey, {
    ...rowState,
    isSelected: false,
  });

  let hasSelection = false;
  // eslint-disable-next-line no-restricted-syntax
  for (const row of newDataState.values()) {
    if (row.isSelected) {
      hasSelection = true;
      break;
    }
  }

  return { ...state, dataState: newDataState, hasSelection };
};

/**
 * Removes all rows from being selected.
 * @param {Object} state  The current state
 * Action: { type: 'deselectAll' }
 */
export const deselectAll = state => {
  const { dataState } = state;
  const newDataState = new Map(dataState);

  // eslint-disable-next-line no-restricted-syntax
  for (const [rowKey, rowState] of newDataState.entries()) {
    if (rowState.isSelected) {
      newDataState.set(rowKey, {
        ...rowState,
        isSelected: false,
      });
    }
  }
  return { ...state, dataState: newDataState, hasSelection: false };
};

/**
 * Focuses the cell provided in the action passed
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * action: { type: 'focusCell', rowKey, columnKey }
 */
export const focusCell = (state, action) => {
  // Clear any existing focus and focus cell specified in action
  const { rowKey, columnKey } = action;
  return setFocus(state, rowKey, columnKey);
};

/**
 * Sorts the current set of data by the provided
 * key and direction in action.
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'sortData', sortBy }
 * sortBy: String key of the field of the objects to sort by.
 */
export const sortData = (state, action) => {
  const { data, isAscending, sortBy } = state;
  const { sortBy: newSortBy } = action;
  const columnKeyToDataType = {
    itemCode: 'string',
    itemName: 'string',
    availableQuantity: 'number',
    totalQuantity: 'number',
  };

  // If the new sortBy is the same as the sortBy in state, then invert isAscending
  // that was set by the last sortBy action. Otherwise, default to true.
  const newIsAscending = newSortBy === sortBy ? !isAscending : true;

  const newData = newSortDataBy(data, newSortBy, columnKeyToDataType[newSortBy], newIsAscending);
  return { ...state, data: newData, sortBy: newSortBy, isAscending: newIsAscending };
};

/**
 * Opens a basic modal which does not require any other value
 * to be set upon opening. i.e. text editors
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'openBasicModal', modalKey }
 */
export const openBasicModal = (state, action) => {
  const { modalKey } = action;
  return { ...state, modalKey };
};

/**
 * Sets the modal open state to false, closing any
 * modal that is open.
 *
 * @param {Object} state  The current state
 * Action: { type: 'closeBasicModal' }
 */
export const closeBasicModal = state => ({ ...state, modalKey: '' });

/**
 * Adds all items from a master list to the pageObject held
 * in state - either a Requisition or Transaction.
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'addMasterListItems', objectType }
 */
export const addMasterListItems = state => {
  const { backingData } = state;
  const newData = backingData.slice();

  return { ...state, data: newData };
};

/**
 * Creates an Item (Either Requisition or Transaction), and appends
 * this item to the data array for a page.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'addItem', item, addedItemType }
 */
export const addItem = (state, action) => {
  const { data } = state;
  const { item } = action;

  return { ...state, data: [item, ...data], modalKey: '', sortBy: '', isAscending: null };
};

/**
 * Reducer helper method for editing a non-setter field on a
 * realm object. Should be called by more explicit reducer
 * methods and not exported to avoid misuse. To create a reducer
 * method for setting a simple value for a realm object, create a
 * more explicit reducer method with logic specific to that field
 * contained, and call this method. See editTheirRef.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'editPageObject', value, field, pageObjectType }
 */
const editPageObject = state => ({ ...state, modalKey: '' });

/**
 * Edits the passed pageObject 'theirRef' field with the value supplied.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'editPageObject', value, pageObjectType }
 */
export const editTheirRef = (state, action) => {
  const { pageObject } = state;
  const { value } = action;

  const { theirRef } = pageObject;

  if (theirRef !== value) return { ...editPageObject(state, { ...action, field: 'theirRef' }) };
  return state;
};

/**
 * Edits the passed pageObject 'comment' field with the value supplied.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 * Action: { type: 'editPageObject', value, pageObjectType }
 */
export const editComment = (state, action) => {
  const { pageObject } = state;
  const { value } = action;

  const { comment } = pageObject;

  if (comment !== value) return { ...editPageObject(state, { ...action, field: 'comment' }) };
  return state;
};

/**
 * Deletes the selected RequisitionItems or
 * TransactionItems held in state. Where each selected
 * item is indicated by DataState[rowKey].isSelected.
 *
 * @param {Object} state  The current state
 * @param {Object} action The action to act upon
 */
export const deleteItemsById = state => {
  const { data } = state;

  const newDataState = new Map();
  const newData = data.filter(item => item.isValid());

  return {
    ...state,
    data: newData,
    dataState: newDataState,
    hasSelection: false,
    modalKey: '',
  };
};

/**
 * Simply refresh's the data object in state to
 * correctly match the backingData when side effects
 * such as finalizing manipulate the state of a page
 * from outside the reducer. Should only be used when
 * there are no other options.
 *
 * @param {Object} state  The current state
 */
export const refreshData = state => {
  const { backingData } = state;
  return { ...state, data: backingData.slice() };
};
<|endoftext|>


<commit_before>import extractContainerUnitStylesFromRule from './extractContainerUnitStylesFromRule';
import Node from "../../__mocks__/Node";
import {
    HEIGHT_UNIT,
    WIDTH_UNIT,
    DEFINE_CONTAINER_NAME,
} from "../constants";

test('should only accept rule nodes', () => {
    expect(() => {
        extractContainerUnitStylesFromRule({});
    }).toThrowError(/^`ruleNode` must be of type "rule".$/);
});

test('should throw if container units are used on a container with width or height properties', () => {
    const errorMessageRegex = /^A container cannot use container units for its width and\/or height properties.$/;

    expect(() => {
        extractContainerUnitStylesFromRule(
            new Node({
                type: 'rule',
                selector: '.container',
            })
                .addNode(new Node({
                    type: 'atrule',
                    name: DEFINE_CONTAINER_NAME,
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'width',
                    value: '42' + WIDTH_UNIT,
                }))
        );
    }).toThrowError(errorMessageRegex);

    expect(() => {
        extractContainerUnitStylesFromRule(
            new Node({
                type: 'rule',
                selector: '.container',
            })
                .addNode(new Node({
                    type: 'atrule',
                    name: DEFINE_CONTAINER_NAME,
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'height',
                    value: '42' + HEIGHT_UNIT,
                }))
        );
    }).toThrowError(errorMessageRegex);
});
<commit_msg>Finished the extractContainerUnitStylesFromRule specs<commit_after>import extractContainerUnitStylesFromRule from './extractContainerUnitStylesFromRule';
import Node from "../../__mocks__/Node";
import {
    HEIGHT_UNIT,
    WIDTH_UNIT,
    DEFINE_CONTAINER_NAME,
} from "../constants";

test('should only accept rule nodes', () => {
    expect(() => {
        extractContainerUnitStylesFromRule({});
    }).toThrowError(/^`ruleNode` must be of type "rule".$/);
});

test('should throw if container units are used on a container with width or height properties', () => {
    const errorMessageRegex = /^A container cannot use container units for its width and\/or height properties.$/;

    expect(() => {
        extractContainerUnitStylesFromRule(
            new Node({
                type: 'rule',
                selector: '.container',
            })
                .addNode(new Node({
                    type: 'atrule',
                    name: DEFINE_CONTAINER_NAME,
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'width',
                    value: '42' + WIDTH_UNIT,
                }))
        );
    }).toThrowError(errorMessageRegex);

    expect(() => {
        extractContainerUnitStylesFromRule(
            new Node({
                type: 'rule',
                selector: '.container',
            })
                .addNode(new Node({
                    type: 'atrule',
                    name: DEFINE_CONTAINER_NAME,
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'height',
                    value: '42' + HEIGHT_UNIT,
                }))
        );
    }).toThrowError(errorMessageRegex);
});

test('should extract all container unit styles', () => {
    expect(
        extractContainerUnitStylesFromRule(
            new Node({
                type: 'rule',
                selector: '.container',
            })
        )
    ).toEqual({});

    expect(
        extractContainerUnitStylesFromRule(
            new Node({
                type: 'rule',
                selector: '.container',
            })
                .addNode(new Node({
                    type: 'atrule',
                    name: DEFINE_CONTAINER_NAME,
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'height',
                    value: '42px',
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'width',
                    value: '42px',
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'font-size',
                    value: '5' + HEIGHT_UNIT,
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'line-height',
                    value: '42' + WIDTH_UNIT,
                }))
                .addNode(new Node({
                    type: 'decl',
                    prop: 'border',
                    value: 'none',
                }))
        )
    ).toEqual({
        lineHeight: '42' + WIDTH_UNIT,
        fontSize: '5' + HEIGHT_UNIT,
    });
});
<|endoftext|>


<commit_before>'use strict';

(function() {
	var _           = require('underscore')
	  , jsonxml     = require('jsontoxml')
	  , qtmrt       = require('./qtmrt')
	  , Packet      = require('./packet')
	  , Component   = require('./component')
	  , writeUInt32 = require('./helpers').writeUInt32
	;

	var Command = {
		createPacket: function(cmdStr) {
			var buf = new Buffer(qtmrt.HEADER_SIZE + cmdStr.length);

			writeUInt32(buf, buf.length, 0);
			writeUInt32(buf, qtmrt.COMMAND, qtmrt.UINT32_SIZE);
			buf.write(cmdStr, qtmrt.HEADER_SIZE, cmdStr.length, 'utf8');

			return new Packet(buf);
		},

		qtmVersion:      function()             { return this.createPacket('QTMVersion'); },
		byteOrder:       function()             { return this.createPacket('ByteOrder'); },
		getState:        function()             { return this.createPacket('GetState'); },
		releaseControl:  function()             { return this.createPacket('ReleaseControl'); },
		newMeasurement:  function()             { return this.createPacket('New'); },
		close:           function()             { return this.createPacket('Close'); },
		start:           function()             { return this.createPacket('Start'); },
		stop:            function()             { return this.createPacket('Stop'); },
		getCaptureC3D:   function()             { return this.createPacket('GetCaptureC3D'); },
		getCaptureQtm:   function()             { return this.createPacket('GetCaptureQtm'); },
		trig:            function()             { return this.createPacket('Trig'); },
		stopStreaming:   function()             { return this.createPacket('StreamFrames Stop'); },
		setQtmEvent:     function(label)        { return this.createPacket('SetQTMEvent ' + label); },
		takeControl:     function(pass)         { return this.createPacket('TakeControl ' + (_.isUndefined(pass) ? '' : pass)); },
		load:            function(filename)     { return this.createPacket('Load ' + filename); },
		loadProject:     function(projectPath)  { return this.createPacket('LoadProject ' + projectPath); },
		version:         function(major, minor) { return this.createPacket('Version ' + major + '.' + minor); },

		getParameters: function() {
			var predicate = function(component) {
					return _.contains(['All', 'General', '3D', '6D', 'Analog', 'Force', 'Image'], component);
				}
			   , components = _.filter(arguments, predicate)
			;

			if (_.contains(components, 'All'))
				components = ['All'];

			return this.createPacket('GetParameters ' + components.join(' '));
		},

		setParameters: function(params) {
			var xml = jsonxml({ 'QTM_Settings': params }) + '\0'
			  , buf = new Buffer(qtmrt.HEADER_SIZE + xml.length + 1)
			;

			writeUInt32(buf, buf.length, 0);
			writeUInt32(buf, qtmrt.XML, qtmrt.UINT32_SIZE);
			buf.write(xml, qtmrt.HEADER_SIZE);

			return Packet.create(buf);
		},

		getCurrentFrame: function(component) {
			var predicate = function(component) {
					return _.contains(_.values(qtmrt.COMPONENTS), component);
				}
			   , components = _.filter(arguments, predicate)
			;

			if (_.contains(arguments, qtmrt.COMPONENT_ALL))
				components = [qtmrt.COMPONENT_ALL];

			return this.createPacket('GetCurrentFrame ' + components.map(Component.typeToString).join(' '));
		},

		streamFrames: function(options) {
			if (!arguments.length)
				options = {};

			options = _.defaults(options, {
				frequency: 100,
				components: ['All'],
			});

			var udp        = _.isUndefined(options.udpPort) ? '' : ' UDP:' + (_.isUndefined(options.udpAddress) ? '' : options.udpAddress + ':') + options.udpPort
			  , frequency  = ''
			  , predicate  = function(component) { return _.contains(_.union(['All'], Object.keys(qtmrt.COMPONENTS)), component); }
			  , components = _.filter(options.components, predicate)
			;

			if (options.frequency < 1)
				frequency = 'FrequencyDivisor:' + (1 / options.frequency);
			else if (isNaN(options.frequency))
				frequency = 'AllFrames';
			else
				frequency = 'Frequency:' + options.frequency;

			if (_.isEmpty(components))
				throw new TypeError('No valid components specified');

			if (_.contains(components, 'All'))
				components = ['All'];

			var cmdStr = 'StreamFrames ' + frequency + udp + ' ' + components.join(' ');
			return this.createPacket(cmdStr);
		},

		save: function(filename, overwrite) {
			var cmdStr = 'Save ' + filename + (_.isUndefined(overwrite) ? '' : (' ' + overwrite));
			return this.createPacket(cmdStr);
		},

	};

	module.exports = Command;
})();
<commit_msg>Converted Command to class.<commit_after>'use strict';

(function() {
	var _           = require('underscore')
	  , jsonxml     = require('jsontoxml')
	  , qtmrt       = require('./qtmrt')
	  , Packet      = require('./packet')
	  , Component   = require('./component')
	  , writeUInt32 = require('./helpers').writeUInt32
	;

	class Command {
		static createPacket(cmdStr) {
			var buf = new Buffer(qtmrt.HEADER_SIZE + cmdStr.length);

			writeUInt32(buf, buf.length, 0);
			writeUInt32(buf, qtmrt.COMMAND, qtmrt.UINT32_SIZE);
			buf.write(cmdStr, qtmrt.HEADER_SIZE, cmdStr.length, 'utf8');

			return new Packet(buf);
		}

		static qtmVersion()             { return this.createPacket('QTMVersion'); }
		static byteOrder()              { return this.createPacket('ByteOrder'); }
		static getState()               { return this.createPacket('GetState'); }
		static releaseControl()         { return this.createPacket('ReleaseControl'); }
		static newMeasurement()         { return this.createPacket('New'); }
		static close()                  { return this.createPacket('Close'); }
		static start()                  { return this.createPacket('Start'); }
		static stop()                   { return this.createPacket('Stop'); }
		static getCaptureC3D()          { return this.createPacket('GetCaptureC3D'); }
		static getCaptureQtm()          { return this.createPacket('GetCaptureQtm'); }
		static trig()                   { return this.createPacket('Trig'); }
		static stopStreaming()          { return this.createPacket('StreamFrames Stop'); }
		static setQtmEvent(label)       { return this.createPacket('SetQTMEvent ' + label); }
		static takeControl(pass)        { return this.createPacket('TakeControl ' + (_.isUndefined(pass) ? '' : pass)); }
		static load(filename)           { return this.createPacket('Load ' + filename); }
		static loadProject(projectPath) { return this.createPacket('LoadProject ' + projectPath); }
		static version(major, minor)    { return this.createPacket('Version ' + major + '.' + minor); }

		static getParameters() {
			var predicate = (component) => {
					return _.contains(['All', 'General', '3D', '6D', 'Analog', 'Force', 'Image'], component);
				}
			   , components = _.filter(arguments, predicate)
			;

			if (_.contains(components, 'All'))
				components = ['All'];

			return this.createPacket('GetParameters ' + components.join(' '));
		}

		static setParameters(params) {
			var xml = jsonxml({ 'QTM_Settings': params }) + '\0'
			  , buf = new Buffer(qtmrt.HEADER_SIZE + xml.length + 1)
			;

			writeUInt32(buf, buf.length, 0);
			writeUInt32(buf, qtmrt.XML, qtmrt.UINT32_SIZE);
			buf.write(xml, qtmrt.HEADER_SIZE);

			return Packet.create(buf);
		}

		static getCurrentFrame(component) {
			var predicate = function(component) {
					return _.contains(_.values(qtmrt.COMPONENTS), component);
				}
			   , components = _.filter(arguments, predicate)
			;

			if (_.contains(arguments, qtmrt.COMPONENT_ALL))
				components = [qtmrt.COMPONENT_ALL];

			return this.createPacket('GetCurrentFrame ' + components.map(Component.typeToString).join(' '));
		}

		static streamFrames(options) {
			if (!arguments.length)
				options = {};

			options = _.defaults(options, {
				frequency: 100,
				components: ['All'],
			});

			var udp        = _.isUndefined(options.udpPort) ? '' : ' UDP:' + (_.isUndefined(options.udpAddress) ? '' : options.udpAddress + ':') + options.udpPort
			  , frequency  = ''
			  , predicate  = function(component) { return _.contains(_.union(['All'], Object.keys(qtmrt.COMPONENTS)), component); }
			  , components = _.filter(options.components, predicate)
			;

			if (options.frequency < 1)
				frequency = 'FrequencyDivisor:' + (1 / options.frequency);
			else if (isNaN(options.frequency))
				frequency = 'AllFrames';
			else
				frequency = 'Frequency:' + options.frequency;

			if (_.isEmpty(components))
				throw new TypeError('No valid components specified');

			if (_.contains(components, 'All'))
				components = ['All'];

			var cmdStr = 'StreamFrames ' + frequency + udp + ' ' + components.join(' ');
			return this.createPacket(cmdStr);
		}

		static save(filename, overwrite) {
			var cmdStr = 'Save ' + filename + (_.isUndefined(overwrite) ? '' : (' ' + overwrite));
			return this.createPacket(cmdStr);
		}
	}

	module.exports = Command;
})();<|endoftext|>