<commit_before>/*
 * Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
 * Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
 * Created By:
 * Maintained By:
 */

(function(can, $) {

can.Control("CMS.Controllers.Dashboard", {
    defaults: {
        model_descriptors: null
      , menu_tree_spec: null
      //  widget_descriptors: null
      //, widget_listeners: null
      //, widget_containers: null
      //
    }

}, {
    init: function(options) {
      this.init_widget_descriptors();
      if (!this.options.menu_tree)
        this.init_menu_tree();
      if (!this.inner_nav_controller)
        this.init_inner_nav();
      this.update_inner_nav();
      if (!this.add_widget_controller)
        this.init_add_widget();
      if (!this.widget_area_controller)
        this.init_widget_area();
      this.init_default_widgets();
    }

  , init_widget_area: function() {
      this.widget_area_controller = new CMS.Controllers.SortableWidgets(
          this.element.find('.widget-area'), {
              dashboard_controller: this
          });
    }

  , init_inner_nav: function() {
      this.inner_nav_controller = new CMS.Controllers.InnerNav(
          this.element.find('.internav'), {
              dashboard_controller: this
          });
    }

  , init_add_widget: function() {
      this.add_widget_controller = new CMS.Controllers.AddWidget(
          this.element.find('.add-nav-item'), {
              dashboard_controller : this
            //, widget_descriptors : this.options.widget_descriptors
            , menu_tree : this.options.menu_tree
          });
      }

  , init_widget_descriptors: function() {
      var that = this;

      this.options.widget_descriptors = this.options.widget_descriptors || {};

      can.each(this.options.model_descriptors, function(descriptor, key) {
        that.options.widget_descriptors[key] =
          that.make_list_view_descriptor_from_model_descriptor(descriptor);
      });
    }

  , init_menu_tree: function() {
      var that = this
        , menu_tree = { categories: [] };

      can.each(this.options.menu_tree_spec, function(category) {
        var objects = can.map(category.objects, function(widget_name) {
          return that.options.widget_descriptors[widget_name];
        });

        menu_tree.categories.push({
            title: category.title
          , objects: objects
        });
      });

      this.options.menu_tree = menu_tree;
    }

  , init_default_widgets: function() {
      var that = this
        ;

      can.each(this.options.default_widgets, function(name) {
        var descriptor = that.options.widget_descriptors[name]
          ;

        that.add_dashboard_widget_from_descriptor(descriptor);
      });
    }

  , " widgets_updated" : "update_inner_nav"

  , " inner_nav_sort_updated": function(el, ev, widget_ids) {
        this.apply_widget_sort(widget_ids);
      }

  , apply_widget_sort: function(widget_ids) {
      var that = this
        ;

      can.each(this.get_active_widget_container_elements(), function(elem) {
        $(elem).trigger("apply_widget_sort", [widget_ids])
      });

      this.update_inner_nav();
    }

  , update_inner_nav: function(el, ev, data) {
      this.inner_nav_controller.update_widget_list(
        this.get_active_widget_elements());
    }

  , get_active_widget_container_elements: function() {
      return this.element.find(".widget-area").toArray();
    }

  , get_active_widget_elements: function() {
      return this.element.find("section.widget[id]:not([id=])").toArray();
    }

  , add_widget_from_descriptor: function() {
      var descriptor = {}
        , that = this
        ;

      // Construct the final descriptor from one or more arguments
      can.each(arguments, function(name_or_descriptor) {
        if (typeof(name_or_descriptor) === "string")
          name_or_descriptor =
            that.options.widget_descriptors[name_or_descriptor];
        $.extend(descriptor, name_or_descriptor || {});
      });

      // Create widget in container?
      //return this.options.widget_container[0].add_widget(descriptor);

      if ($('#' + descriptor.controller_options.widget_id + '_widget').length > 0)
        return;

      // FIXME: This should be in some Widget superclass
      if (descriptor.controller_options.widget_guard
          && !descriptor.controller_options.widget_guard())
        return;

      var $element = $("
")
        , control = new descriptor.controller(
            $element, descriptor.controller_options)
        ;

      // FIXME: Abstraction violation: Sortable/DashboardWidget/ResizableWidget
      //   controllers should maybe handle this?
      var $container = $(this.get_active_widget_container_elements()[0])
        , $last_widget = $container.find('section.widget').last()
        ;

      if ($last_widget.length > 0)
        $last_widget.after($element);
      else
        $container.append($element);

      $element
        .trigger("sortreceive")
        .trigger("section_created")
        .trigger("widgets_updated")

      return control;
    }

  , add_dashboard_widget_from_descriptor: function(descriptor) {
      return this.add_widget_from_descriptor({
        controller: CMS.Controllers.DashboardWidgets,
        controller_options: $.extend(descriptor, { dashboard_controller: this })
      });
    }

  , add_dashboard_widget_from_name: function(name) {
      var descriptor = this.options.widget_descriptors[name];
      if (!descriptor)
        console.debug("Unknown descriptor: ", name);
      else
        return this.add_dashboard_widget_from_descriptor(descriptor);
    }

  , make_list_view_descriptor_from_model_descriptor: function(descriptor) {
      return {
        content_controller: GGRC.Controllers.ListView,
        content_controller_options: descriptor,
        widget_id: descriptor.model.table_singular,
        widget_name: descriptor.model.title_plural,
        widget_icon: descriptor.model.table_singular,
        object_category: descriptor.model.category || descriptor.object_category
      }
    }
});

CMS.Controllers.Dashboard("CMS.Controllers.PageObject", {

}, {
    init: function() {
      this.options.model = this.options.instance.constructor;
      this._super();
      this.init_related_widgets();
    }

  , init_related_widgets: function() {
      var that = this
        , model_name = this.options.instance.constructor.shortName
        , relationships = GGRC.RELATIONSHIP_TYPES[model_name]
        ;

      can.each(relationships, function(value, key) {
        var related_model = CMS.Models[key]
          , descriptor = that.options.widget_descriptors[related_model.table_singular]
          ;

        that.add_dashboard_widget_from_descriptor(descriptor);
      });
    }

  , init_widget_descriptors: function() {
      var that = this;

      this.options.widget_descriptors = this.options.widget_descriptors || {};

      can.each(this.options.model_descriptors, function(descriptor, key) {
        that.options.widget_descriptors[key] =
          that.make_related_descriptor_from_model_descriptor(descriptor);
      });
    }

  , make_related_descriptor_from_model_descriptor: function(descriptor) {
      descriptor = this.make_list_view_descriptor_from_model_descriptor(descriptor);
      descriptor = $.extend({}, descriptor);
      descriptor.content_controller_options =
        $.extend({}, descriptor.content_controller_options);
      descriptor.content_controller_options.is_related = true;
      return descriptor;
    }

  , init_menu_tree: function() {
      var that = this
        , widget_descriptors = this.options.widget_descriptors
        , model_name = this.options.instance.constructor.shortName
        , categories_index = {}
        , menu_tree = { categories : [] }
        ;

      can.each(GGRC.RELATIONSHIP_TYPES[model_name], function(value, key) {
        var related_model = CMS.Models[key]
          , descriptor = widget_descriptors[related_model.table_singular]
          , category = null
          ;

        if (descriptor) {
          category = descriptor.object_category;

          if (!categories_index[category]) {
            categories_index[category] = {
                title : can.map(category.split(" "), can.capitalize).join(" ")
              , objects : []
              };
            menu_tree.categories.push(categories_index[category]);
          }
          categories_index[category].objects.push(descriptor);
        }
      });

      this.options.menu_tree = menu_tree;
    }
});

can.Control("CMS.Controllers.InnerNav", {
  defaults: {
      internav_view : "/static/mustache/dashboard/internav_list.mustache"
    , widget_list : null
  }
}, {
    init: function(options) {
      var that = this
        ;

      if (!this.options.widget_list)
        this.options.widget_list = new can.Observe.List([]);

      this.sortable();

      can.view(this.options.internav_view, this.options, function(frag) {
        that.element.append(frag);
        that.update_scrollspy();
      });
    }

  , sortable: function() {
      return this.element.sortable({
          placeholder: 'drop-placeholder'
        , items : "li"
      })
    }

  , " sortupdate": "apply_widget_list_sort"

  , apply_widget_list_sort: function() {
      var widget_ids
        ;

      widget_ids = this.element.find("li > a").map(function() {
        return $(this).attr("href");
      }).toArray();

      this.element.trigger("inner_nav_sort_updated", [widget_ids]);
    }

  , replace_widget_list : function(widget_elements) {
      var widget_list = []
        ;

      can.each(widget_elements, function(widget_element) {
        var $widget = $(widget_element);
        widget_list.push({
            selector: "#" + $widget.attr("id")
          , internav_icon: $widget.find(".header h2 i").attr("class")
          , internav_display: function() {

              var menuItem = $widget.find(".header").text().trim()
              ,   first
              ;

              var first = menuItem.substring(0,6);
              if (first === "Mapped") {
                menuItem = menuItem.substr(6);
              }
              return menuItem;
            }

          });
      });
      this.options.widget_list.replace(widget_list);
    }

  , update_scrollspy : function() {
      var $body = $(".object-area")
        , top = $body.scrollTop()
        ;

      // Some pages may not have scrollspy set up (e.g., dashboard)
      if (!$body.data("scrollspy"))
        return

      // FIXME: This is currently necessary because Bootstrap's ScrollSpy uses
      //   the `href` to determine the active element, and the element may have
      //   changed (due to view update) while keeping the same `href`.
      // So, we nullify the "current" href.
      $body.data("scrollspy").activeTarget = null;
      $body
        .scrollTop(0)
        .scrollspy("refresh")
        .scrollTop(top)
        .scrollspy("process");
    }

  , update_widget_list : function(widget_elements) {
      this.replace_widget_list(widget_elements);
      this.update_scrollspy();
    }

});

})(this.can, this.can.$);
<commit_msg>JS updates for removing redundant copy from object nav<commit_after>/*
 * Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
 * Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
 * Created By:
 * Maintained By:
 */

(function(can, $) {

can.Control("CMS.Controllers.Dashboard", {
    defaults: {
        model_descriptors: null
      , menu_tree_spec: null
      //  widget_descriptors: null
      //, widget_listeners: null
      //, widget_containers: null
      //
    }

}, {
    init: function(options) {
      this.init_widget_descriptors();
      if (!this.options.menu_tree)
        this.init_menu_tree();
      if (!this.inner_nav_controller)
        this.init_inner_nav();
      this.update_inner_nav();
      if (!this.add_widget_controller)
        this.init_add_widget();
      if (!this.widget_area_controller)
        this.init_widget_area();
      this.init_default_widgets();
    }

  , init_widget_area: function() {
      this.widget_area_controller = new CMS.Controllers.SortableWidgets(
          this.element.find('.widget-area'), {
              dashboard_controller: this
          });
    }

  , init_inner_nav: function() {
      this.inner_nav_controller = new CMS.Controllers.InnerNav(
          this.element.find('.internav'), {
              dashboard_controller: this
          });
    }

  , init_add_widget: function() {
      this.add_widget_controller = new CMS.Controllers.AddWidget(
          this.element.find('.add-nav-item'), {
              dashboard_controller : this
            //, widget_descriptors : this.options.widget_descriptors
            , menu_tree : this.options.menu_tree
          });
      }

  , init_widget_descriptors: function() {
      var that = this;

      this.options.widget_descriptors = this.options.widget_descriptors || {};

      can.each(this.options.model_descriptors, function(descriptor, key) {
        that.options.widget_descriptors[key] =
          that.make_list_view_descriptor_from_model_descriptor(descriptor);
      });
    }

  , init_menu_tree: function() {
      var that = this
        , menu_tree = { categories: [] };

      can.each(this.options.menu_tree_spec, function(category) {
        var objects = can.map(category.objects, function(widget_name) {
          return that.options.widget_descriptors[widget_name];
        });

        menu_tree.categories.push({
            title: category.title
          , objects: objects
        });
      });

      this.options.menu_tree = menu_tree;
    }

  , init_default_widgets: function() {
      var that = this
        ;

      can.each(this.options.default_widgets, function(name) {
        var descriptor = that.options.widget_descriptors[name]
          ;

        that.add_dashboard_widget_from_descriptor(descriptor);
      });
    }

  , " widgets_updated" : "update_inner_nav"

  , " inner_nav_sort_updated": function(el, ev, widget_ids) {
        this.apply_widget_sort(widget_ids);
      }

  , apply_widget_sort: function(widget_ids) {
      var that = this
        ;

      can.each(this.get_active_widget_container_elements(), function(elem) {
        $(elem).trigger("apply_widget_sort", [widget_ids])
      });

      this.update_inner_nav();
    }

  , update_inner_nav: function(el, ev, data) {
      this.inner_nav_controller.update_widget_list(
        this.get_active_widget_elements());
    }

  , get_active_widget_container_elements: function() {
      return this.element.find(".widget-area").toArray();
    }

  , get_active_widget_elements: function() {
      return this.element.find("section.widget[id]:not([id=])").toArray();
    }

  , add_widget_from_descriptor: function() {
      var descriptor = {}
        , that = this
        ;

      // Construct the final descriptor from one or more arguments
      can.each(arguments, function(name_or_descriptor) {
        if (typeof(name_or_descriptor) === "string")
          name_or_descriptor =
            that.options.widget_descriptors[name_or_descriptor];
        $.extend(descriptor, name_or_descriptor || {});
      });

      // Create widget in container?
      //return this.options.widget_container[0].add_widget(descriptor);

      if ($('#' + descriptor.controller_options.widget_id + '_widget').length > 0)
        return;

      // FIXME: This should be in some Widget superclass
      if (descriptor.controller_options.widget_guard
          && !descriptor.controller_options.widget_guard())
        return;

      var $element = $("
")
        , control = new descriptor.controller(
            $element, descriptor.controller_options)
        ;

      // FIXME: Abstraction violation: Sortable/DashboardWidget/ResizableWidget
      //   controllers should maybe handle this?
      var $container = $(this.get_active_widget_container_elements()[0])
        , $last_widget = $container.find('section.widget').last()
        ;

      if ($last_widget.length > 0)
        $last_widget.after($element);
      else
        $container.append($element);

      $element
        .trigger("sortreceive")
        .trigger("section_created")
        .trigger("widgets_updated")

      return control;
    }

  , add_dashboard_widget_from_descriptor: function(descriptor) {
      return this.add_widget_from_descriptor({
        controller: CMS.Controllers.DashboardWidgets,
        controller_options: $.extend(descriptor, { dashboard_controller: this })
      });
    }

  , add_dashboard_widget_from_name: function(name) {
      var descriptor = this.options.widget_descriptors[name];
      if (!descriptor)
        console.debug("Unknown descriptor: ", name);
      else
        return this.add_dashboard_widget_from_descriptor(descriptor);
    }

  , make_list_view_descriptor_from_model_descriptor: function(descriptor) {
      return {
        content_controller: GGRC.Controllers.ListView,
        content_controller_options: descriptor,
        widget_id: descriptor.model.table_singular,
        widget_name: descriptor.model.title_plural,
        widget_icon: descriptor.model.table_singular,
        object_category: descriptor.model.category || descriptor.object_category
      }
    }
});

CMS.Controllers.Dashboard("CMS.Controllers.PageObject", {

}, {
    init: function() {
      this.options.model = this.options.instance.constructor;
      this._super();
      this.init_related_widgets();
    }

  , init_related_widgets: function() {
      var that = this
        , model_name = this.options.instance.constructor.shortName
        , relationships = GGRC.RELATIONSHIP_TYPES[model_name]
        ;

      can.each(relationships, function(value, key) {
        var related_model = CMS.Models[key]
          , descriptor = that.options.widget_descriptors[related_model.table_singular]
          ;

        that.add_dashboard_widget_from_descriptor(descriptor);
      });
    }

  , init_widget_descriptors: function() {
      var that = this;

      this.options.widget_descriptors = this.options.widget_descriptors || {};

      can.each(this.options.model_descriptors, function(descriptor, key) {
        that.options.widget_descriptors[key] =
          that.make_related_descriptor_from_model_descriptor(descriptor);
      });
    }

  , make_related_descriptor_from_model_descriptor: function(descriptor) {
      descriptor = this.make_list_view_descriptor_from_model_descriptor(descriptor);
      descriptor = $.extend({}, descriptor);
      descriptor.content_controller_options =
        $.extend({}, descriptor.content_controller_options);
      descriptor.content_controller_options.is_related = true;
      return descriptor;
    }

  , init_menu_tree: function() {
      var that = this
        , widget_descriptors = this.options.widget_descriptors
        , model_name = this.options.instance.constructor.shortName
        , categories_index = {}
        , menu_tree = { categories : [] }
        ;

      can.each(GGRC.RELATIONSHIP_TYPES[model_name], function(value, key) {
        var related_model = CMS.Models[key]
          , descriptor = widget_descriptors[related_model.table_singular]
          , category = null
          ;

        if (descriptor) {
          category = descriptor.object_category;

          if (!categories_index[category]) {
            categories_index[category] = {
                title : can.map(category.split(" "), can.capitalize).join(" ")
              , objects : []
              };
            menu_tree.categories.push(categories_index[category]);
          }
          categories_index[category].objects.push(descriptor);
        }
      });

      this.options.menu_tree = menu_tree;
    }
});

can.Control("CMS.Controllers.InnerNav", {
  defaults: {
      internav_view : "/static/mustache/dashboard/internav_list.mustache"
    , widget_list : null
  }
}, {
    init: function(options) {
      var that = this
        ;

      if (!this.options.widget_list)
        this.options.widget_list = new can.Observe.List([]);

      this.sortable();

      can.view(this.options.internav_view, this.options, function(frag) {
        that.element.append(frag);
        that.update_scrollspy();
      });
    }

  , sortable: function() {
      return this.element.sortable({
          placeholder: 'drop-placeholder'
        , items : "li"
      })
    }

  , " sortupdate": "apply_widget_list_sort"

  , apply_widget_list_sort: function() {
      var widget_ids
        ;

      widget_ids = this.element.find("li > a").map(function() {
        return $(this).attr("href");
      }).toArray();

      this.element.trigger("inner_nav_sort_updated", [widget_ids]);
    }

  , replace_widget_list : function(widget_elements) {
      var widget_list = []
        ;

      can.each(widget_elements, function(widget_element) {
        var $widget = $(widget_element);
        widget_list.push({
            selector: "#" + $widget.attr("id")
          , internav_icon: $widget.find(".header h2 i").attr("class")
          , internav_display: function() {

              var menuItem = $widget.find(".header").text().trim()
              ,   first
              ,   last
              ;

              var first = menuItem.substring(0,6);
              var last = menuItem.slice(-12);
              if (first === "Mapped") {
                menuItem = menuItem.substr(6);
              }
              if (last === "and Controls") {
                menuItem = menuItem.slice(0,-64);
              }

              return menuItem;
            }

          });
      });
      this.options.widget_list.replace(widget_list);
    }

  , update_scrollspy : function() {
      var $body = $(".object-area")
        , top = $body.scrollTop()
        ;

      // Some pages may not have scrollspy set up (e.g., dashboard)
      if (!$body.data("scrollspy"))
        return

      // FIXME: This is currently necessary because Bootstrap's ScrollSpy uses
      //   the `href` to determine the active element, and the element may have
      //   changed (due to view update) while keeping the same `href`.
      // So, we nullify the "current" href.
      $body.data("scrollspy").activeTarget = null;
      $body
        .scrollTop(0)
        .scrollspy("refresh")
        .scrollTop(top)
        .scrollspy("process");
    }

  , update_widget_list : function(widget_elements) {
      this.replace_widget_list(widget_elements);
      this.update_scrollspy();
    }

});

})(this.can, this.can.$);
<|endoftext|>


<commit_before>// ------------------------- dependency -------------------------
var Horseman   = require('node-horseman'),
    horseman   = new Horseman(),
    fs         = require('fs-extra'),
    isUrl      = require('is-url'),
    jsonPretty = require('json-pretty'),
    program    = require('commander'),
    http       = require('http-https'),
    cssLint    = require('csslint').CSSLint,
    // css        = require('css'),
    rte        = require('readtoend');

// --------------------------- get url ---------------------------
program
    .version('0.0.1')
    .option('-u, --url [url]', 'input url')
    .option('-d, --destination [path]', 'input path to store the output')
    .parse(process.argv);

var url     = program.url,
    dest;

if ( !isUrl(url) ) {
    console.log('ERROR: this is not an url');
    horseman.close();
    process.exit(1);
}

// initialization
var resultCSSLinter = {
    name    : 'CSS Linter',
    url     : url,
    checking: []
};

fs.exists(program.destination, function (exists) {
    if ( !exists ) {
        fs.mkdirsSync( program.destination );
    }
    dest = './' + program.destination;

    // download css asset
    var filenameCSS = url.substring( url.lastIndexOf('/') + 1 , url.length );

    fs.mkdirSync('css/');
    var file = fs.createWriteStream('css/' + filenameCSS);

    var request = http.get(url , function (response) {
        response.pipe(file);

        // read the file
        rte.readToEnd(response, function (err, body) {

            // beautify css
            // var parseSource = css.parse( body );
            // var beautified  = css.stringify( parseSource );

            // css lint, if use beautified css, change 'body' into 'beautified'
            var result = cssLint.verify( body );

            if (result.messages.length === 0) {
                // Success
            } else {
                // Errors or warnings
                for ( i = 0 ; i < result.messages.length ; i++) {
                    var message = result.messages[i];
                    resultCSSLinter.checking.push(
                        {
                            messageType     : message.type,
                            messageLine     : message.line,
                            messageCol      : message.col,
                            messageMsg      : message.message
                        }
                    );
                }
            }

            //beautify json
            var toJson = jsonPretty(resultCSSLinter);

            //save file
            fs.writeFile(dest + 'resultCSS.json', toJson, function (err) {
                if (err) throw err;
            });

            // remove asset file
            fs.remove('./css/', function (err) {
                if (err) return console.log(err);
            });
        });
    });
});

// end of horseman
horseman.close();<commit_msg>make unique temp folder csslinter<commit_after>// ------------------------- dependency -------------------------
var Horseman   = require('node-horseman'),
    horseman   = new Horseman(),
    fs         = require('fs-extra'),
    isUrl      = require('is-url'),
    jsonPretty = require('json-pretty'),
    program    = require('commander'),
    http       = require('http-https'),
    cssLint    = require('csslint').CSSLint,
    // css        = require('css'),
    rte        = require('readtoend');

// --------------------------- get url ---------------------------
program
    .version('0.0.1')
    .option('-u, --url [url]', 'input url')
    .option('-d, --destination [path]', 'input path to store the output')
    .parse(process.argv);

var url     = program.url,
    dest;

if ( !isUrl(url) ) {
    console.log('ERROR: this is not an url');
    horseman.close();
    process.exit(1);
}

// initialization
var resultCSSLinter = {
    name    : 'CSS Linter',
    url     : url,
    checking: []
};

fs.exists(program.destination, function (exists) {
    if ( !exists ) {
        fs.mkdirsSync( program.destination );
    }
    dest = './' + program.destination;

    // download css asset
    var filenameCSS = url.substring( url.lastIndexOf('/') + 1 , url.length );

    var date = new Date();
    var time = date.getTime();
    var folderTemp = 'css' + time + '/';

    fs.mkdirSync(folderTemp);
    var file = fs.createWriteStream(folderTemp + filenameCSS);

    var request = http.get(url , function (response) {
        response.pipe(file);

        // read the file
        rte.readToEnd(response, function (err, body) {

            // beautify css
            // var parseSource = css.parse( body );
            // var beautified  = css.stringify( parseSource );

            // css lint, if use beautified css, change 'body' into 'beautified'
            var result = cssLint.verify( body );

            if (result.messages.length === 0) {
                // Success
            } else {
                // Errors or warnings
                for ( i = 0 ; i < result.messages.length ; i++) {
                    var message = result.messages[i];
                    resultCSSLinter.checking.push(
                        {
                            messageType     : message.type,
                            messageLine     : message.line,
                            messageCol      : message.col,
                            messageMsg      : message.message
                        }
                    );
                }
            }

            //beautify json
            var toJson = jsonPretty(resultCSSLinter);

            //save file
            fs.writeFile(dest + 'resultCSS.json', toJson, function (err) {
                if (err) throw err;
            });

            // remove asset file
            fs.remove('./' + folderTemp, function (err) {
                if (err) return console.log(err);
            });
        });
    });
});

// end of horseman
horseman.close();<|endoftext|>


<commit_before>var torque = require('../');
var cartocss = require('./cartocss_render');
var Profiler = require('../profiler');
var carto = require('carto');

  var TAU = Math.PI * 2;
  var DEFAULT_CARTOCSS = [
    '#layer {',
    '  marker-fill: #662506;',
    '  marker-width: 4;',
    '  [value > 1] { marker-fill: #FEE391; }',
    '  [value > 2] { marker-fill: #FEC44F; }',
    '  [value > 3] { marker-fill: #FE9929; }',
    '  [value > 4] { marker-fill: #EC7014; }',
    '  [value > 5] { marker-fill: #CC4C02; }',
    '  [value > 6] { marker-fill: #993404; }',
    '  [value > 7] { marker-fill: #662506; }',
    '}'
  ].join('\n');

  //
  // this renderer just render points depending of the value
  //
  function PointRenderer(canvas, options) {
    if (!canvas) {
      throw new Error("canvas can't be undefined");
    }
    this.options = options;
    this._canvas = canvas;
    this._ctx = canvas.getContext('2d');
    this._sprites = []; // sprites per layer
    this._shader = null;
    this.setCartoCSS(this.options.cartocss || DEFAULT_CARTOCSS);
    this.TILE_SIZE = 256;
  }

  PointRenderer.prototype = {

    setCanvas: function(canvas) {
      this._canvas = canvas;
      this._ctx = canvas.getContext('2d');
    },

    //
    // sets the cartocss style to render stuff
    //
    setCartoCSS: function(cartocss) {
      // clean sprites
      this.setShader(new carto.RendererJS().render(cartocss));
    },

    setShader: function(shader) {
      // clean sprites
      this._sprites = [];
      this._shader = shader;
    },

    clearSpriteCache: function() {
      this._sprites = [];
    },

    //
    // generate sprite based on cartocss style
    //
    generateSprite: function(shader, value, shaderVars) {
      var prof = Profiler.metric('torque.renderer.point.generateSprite').start();
      var st = shader.getStyle('canvas-2d', {
        value: value
      }, shaderVars);

      var pointSize = st['point-radius'];
      if (!pointSize) {
        return null;
      }

      if (st.fillOpacity === 0 && !st.strokeOpacity) {
        return null;
      }

      var canvas = document.createElement('canvas');

      // take into account the exterior ring to calculate the size
      var canvasSize = (st.lineWidth || 0) + pointSize*2;
      var ctx = canvas.getContext('2d');
      var w = ctx.width = canvas.width = ctx.height = canvas.height = Math.ceil(canvasSize);
      ctx.translate(w/2, w/2);

      if(st['point-file'] || st['marker-file']) {
        torque.cartocss.renderSprite(ctx, st);
      } else {
        var mt = st['marker-type'];
        if (mt && mt === 'rectangle') {
          torque.cartocss.renderRectangle(ctx, st);
        } else {
          torque.cartocss.renderPoint(ctx, st);
        }
      }
      prof.end(true);
      if (torque.flags.sprites_to_images) {
        var i = new Image();
        i.src = canvas.toDataURL();
        return i;
      }
      return canvas;
    },

    //
    // renders all the layers (and frames for each layer) from cartocss
    //
    renderTile: function(tile, key) {
      var prof = Profiler.metric('torque.renderer.point.renderLayers').start();
      var layers = this._shader.getLayers();
      for(var i = 0, n = layers.length; i < n; ++i ) {
        var layer = layers[i];
        if (layer.name() !== "Map") {
          var sprites = this._sprites[i] || (this._sprites[i] = {});
          // frames for each layer
          for(var fr = 0; fr < layer.frames().length; ++fr) {
            var frame = layer.frames()[fr];
            var fr_sprites = sprites[frame] || (sprites[frame] = []);
            this._renderTile(tile, key - frame, frame, fr_sprites, layer);
          }
        }
      }
      prof.end(true);
    },

    //
    // renders a tile in the canvas for key defined in
    // the torque tile
    //
    _renderTile: function(tile, key, frame_offset, sprites, shader, shaderVars) {
      if(!this._canvas) return;

      var prof = Profiler.metric('torque.renderer.point.renderTile').start();
      var ctx = this._ctx;
      var blendMode = shader.eval('comp-op') || this.options.blendmode;
      if(blendMode) {
        ctx.globalCompositeOperation = blendMode;
      }
      if (this.options.cumulative && key > tile.maxDate) {
        //TODO: precache because this tile is not going to change
        key = tile.maxDate;
      }
      var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1)
      var activePixels = tile.timeCount[key];
      if(activePixels) {
        var pixelIndex = tile.timeIndex[key];
        for(var p = 0; p < activePixels; ++p) {
          var posIdx = tile.renderDataPos[pixelIndex + p];
          var c = tile.renderData[pixelIndex + p];
          if(c) {
           var sp = sprites[c];
           if(sp === undefined) {
             sp = sprites[c] = this.generateSprite(shader, c, torque.extend({ zoom: tile.z, 'frame-offset': frame_offset }, shaderVars));
           }
           if (sp) {
             var x = tile.x[posIdx]- (sp.width >> 1);
             var y = tileMax - tile.y[posIdx]; // flip mercator
             ctx.drawImage(sp, x, y - (sp.height >> 1));
           }
          }
        }
      }
      prof.end(true);
    },

    setBlendMode: function(b) {
      this.options.blendmode = b;
    },

    /**
     * get active points for a step in active zoom
     * returns a list of bounding boxes [[sw, ne] , [], []] where ne is a {lat: .., lon: ...} obj
     * empty list if there is no active pixels
     */
    getActivePointsBBox: function(tile, step) {
      var positions = [];
      var mercator = new torque.Mercator();

      var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1);
      //this.renderer.renderTile(tile, this.key, pos.x, pos.y);
      var activePixels = tile.timeCount[step];
      var pixelIndex = tile.timeIndex[step];
      for(var p = 0; p < activePixels; ++p) {
        var posIdx = tile.renderDataPos[pixelIndex + p];
        var c = tile.renderData[pixelIndex + p];
        if (c) {
         var x = tile.x[posIdx];
         var y = tileMax - tile.y[posIdx]; // flip mercator
         positions.push(mercator.tilePixelBBox(
           tile.coord.x,
           tile.coord.y,
           tile.coord.z,
           x, y
         ));
        }
      }
      return positions;
    },

    // return the value for x, y (tile coordinates)
    // null for no value
    getValueFor: function(tile, step, px, py) {
      var mercator = new torque.Mercator();
      var res = this.options.resolution;
      var res2 = res >> 1;

      var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1);
      //this.renderer.renderTile(tile, this.key, pos.x, pos.y);
      var activePixels = tile.timeCount[step];
      var pixelIndex = tile.timeIndex[step];
      for(var p = 0; p < activePixels; ++p) {
        var posIdx = tile.renderDataPos[pixelIndex + p];
        var c = tile.renderData[pixelIndex + p];
        if (c) {
         var x = tile.x[posIdx];
         var y = tileMax - tile.y[posIdx];
         var dx = px + res2 - x;
         var dy = py + res2 - y;
         if (dx >= 0 && dx < res && dy >= 0 && dy < res) {
           return {
             value: c,
             bbox: mercator.tilePixelBBox(
               tile.coord.x,
               tile.coord.y,
               tile.coord.z,
               x - res2, y - res2, res
             )
           }
         }
        }
      }
      return null;
    }

  };

  // exports public api
module.exports = PointRenderer;
<commit_msg>Abstract canvas/image creation,  if a class is provided it will use that as constructor. Otherwise it will fallback to browser implementation.<commit_after>var torque = require('../');
var cartocss = require('./cartocss_render');
var Profiler = require('../profiler');
var carto = require('carto');

  var TAU = Math.PI * 2;
  var DEFAULT_CARTOCSS = [
    '#layer {',
    '  marker-fill: #662506;',
    '  marker-width: 4;',
    '  [value > 1] { marker-fill: #FEE391; }',
    '  [value > 2] { marker-fill: #FEC44F; }',
    '  [value > 3] { marker-fill: #FE9929; }',
    '  [value > 4] { marker-fill: #EC7014; }',
    '  [value > 5] { marker-fill: #CC4C02; }',
    '  [value > 6] { marker-fill: #993404; }',
    '  [value > 7] { marker-fill: #662506; }',
    '}'
  ].join('\n');

  //
  // this renderer just render points depending of the value
  //
  function PointRenderer(canvas, options) {
    if (!canvas) {
      throw new Error("canvas can't be undefined");
    }
    this.options = options;
    this._canvas = canvas;
    this._ctx = canvas.getContext('2d');
    this._sprites = []; // sprites per layer
    this._shader = null;
    this.setCartoCSS(this.options.cartocss || DEFAULT_CARTOCSS);
    this.TILE_SIZE = 256;
  }

  PointRenderer.prototype = {

    setCanvas: function(canvas) {
      this._canvas = canvas;
      this._ctx = canvas.getContext('2d');
    },

    //
    // sets the cartocss style to render stuff
    //
    setCartoCSS: function(cartocss) {
      // clean sprites
      this.setShader(new carto.RendererJS().render(cartocss));
    },

    setShader: function(shader) {
      // clean sprites
      this._sprites = [];
      this._shader = shader;
    },

    clearSpriteCache: function() {
      this._sprites = [];
    },

    //
    // generate sprite based on cartocss style
    //
    generateSprite: function(shader, value, shaderVars) {
      var prof = Profiler.metric('torque.renderer.point.generateSprite').start();
      var st = shader.getStyle('canvas-2d', {
        value: value
      }, shaderVars);

      var pointSize = st['point-radius'];
      if (!pointSize) {
        return null;
      }

      if (st.fillOpacity === 0 && !st.strokeOpacity) {
        return null;
      }

      var canvas = this._createCanvas();
      // take into account the exterior ring to calculate the size
      var canvasSize = (st.lineWidth || 0) + pointSize*2;
      var ctx = canvas.getContext('2d');
      var w = ctx.width = canvas.width = ctx.height = canvas.height = Math.ceil(canvasSize);
      ctx.translate(w/2, w/2);

      if(st['point-file'] || st['marker-file']) {
        torque.cartocss.renderSprite(ctx, st);
      } else {
        var mt = st['marker-type'];
        if (mt && mt === 'rectangle') {
          torque.cartocss.renderRectangle(ctx, st);
        } else {
          torque.cartocss.renderPoint(ctx, st);
        }
      }
      prof.end(true);
      if (torque.flags.sprites_to_images) {
        var i = this._createImage();
        i.src = canvas.toDataURL();
        return i;
      }
      return canvas;
    },

    //
    // renders all the layers (and frames for each layer) from cartocss
    //
    renderTile: function(tile, key) {
      var prof = Profiler.metric('torque.renderer.point.renderLayers').start();
      var layers = this._shader.getLayers();
      for(var i = 0, n = layers.length; i < n; ++i ) {
        var layer = layers[i];
        if (layer.name() !== "Map") {
          var sprites = this._sprites[i] || (this._sprites[i] = {});
          // frames for each layer
          for(var fr = 0; fr < layer.frames().length; ++fr) {
            var frame = layer.frames()[fr];
            var fr_sprites = sprites[frame] || (sprites[frame] = []);
            this._renderTile(tile, key - frame, frame, fr_sprites, layer);
          }
        }
      }
      prof.end(true);
    },

    _createCanvas: function() {
      return this.options.canvasClass
        ? new this.options.canvasClass()
        : document.createElement('canvas');
    },

    _createImage: function() {
      return this.options.imageClass
        ? new this.options.imageClass()
        : new Image();
    },

    //
    // renders a tile in the canvas for key defined in
    // the torque tile
    //
    _renderTile: function(tile, key, frame_offset, sprites, shader, shaderVars) {
      if(!this._canvas) return;

      var prof = Profiler.metric('torque.renderer.point.renderTile').start();
      var ctx = this._ctx;
      var blendMode = shader.eval('comp-op') || this.options.blendmode;
      if(blendMode) {
        ctx.globalCompositeOperation = blendMode;
      }
      if (this.options.cumulative && key > tile.maxDate) {
        //TODO: precache because this tile is not going to change
        key = tile.maxDate;
      }
      var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1)
      var activePixels = tile.timeCount[key];
      if(activePixels) {
        var pixelIndex = tile.timeIndex[key];
        for(var p = 0; p < activePixels; ++p) {
          var posIdx = tile.renderDataPos[pixelIndex + p];
          var c = tile.renderData[pixelIndex + p];
          if(c) {
           var sp = sprites[c];
           if(sp === undefined) {
             sp = sprites[c] = this.generateSprite(shader, c, torque.extend({ zoom: tile.z, 'frame-offset': frame_offset }, shaderVars));
           }
           if (sp) {
             var x = tile.x[posIdx]- (sp.width >> 1);
             var y = tileMax - tile.y[posIdx]; // flip mercator
             ctx.drawImage(sp, x, y - (sp.height >> 1));
           }
          }
        }
      }
      prof.end(true);
    },

    setBlendMode: function(b) {
      this.options.blendmode = b;
    },

    /**
     * get active points for a step in active zoom
     * returns a list of bounding boxes [[sw, ne] , [], []] where ne is a {lat: .., lon: ...} obj
     * empty list if there is no active pixels
     */
    getActivePointsBBox: function(tile, step) {
      var positions = [];
      var mercator = new torque.Mercator();

      var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1);
      //this.renderer.renderTile(tile, this.key, pos.x, pos.y);
      var activePixels = tile.timeCount[step];
      var pixelIndex = tile.timeIndex[step];
      for(var p = 0; p < activePixels; ++p) {
        var posIdx = tile.renderDataPos[pixelIndex + p];
        var c = tile.renderData[pixelIndex + p];
        if (c) {
         var x = tile.x[posIdx];
         var y = tileMax - tile.y[posIdx]; // flip mercator
         positions.push(mercator.tilePixelBBox(
           tile.coord.x,
           tile.coord.y,
           tile.coord.z,
           x, y
         ));
        }
      }
      return positions;
    },

    // return the value for x, y (tile coordinates)
    // null for no value
    getValueFor: function(tile, step, px, py) {
      var mercator = new torque.Mercator();
      var res = this.options.resolution;
      var res2 = res >> 1;

      var tileMax = this.options.resolution * (this.TILE_SIZE/this.options.resolution - 1);
      //this.renderer.renderTile(tile, this.key, pos.x, pos.y);
      var activePixels = tile.timeCount[step];
      var pixelIndex = tile.timeIndex[step];
      for(var p = 0; p < activePixels; ++p) {
        var posIdx = tile.renderDataPos[pixelIndex + p];
        var c = tile.renderData[pixelIndex + p];
        if (c) {
         var x = tile.x[posIdx];
         var y = tileMax - tile.y[posIdx];
         var dx = px + res2 - x;
         var dy = py + res2 - y;
         if (dx >= 0 && dx < res && dy >= 0 && dy < res) {
           return {
             value: c,
             bbox: mercator.tilePixelBBox(
               tile.coord.x,
               tile.coord.y,
               tile.coord.z,
               x - res2, y - res2, res
             )
           }
         }
        }
      }
      return null;
    }

  };

  // exports public api
module.exports = PointRenderer;
<|endoftext|>


<commit_before>import axios from "axios";

export function checkConnectionStatus({ id }) {
  return axios
    .get(`ajax/remote_api/status/${id}`)
    .then(({ data }) => data === "valid_token");
}
<commit_msg>chore: update JSDoc<commit_after>import axios from "axios";

/**
 * Check the status of a specific Remote API.
 * @param {number} id - identifier for the API.
 * @returns {Promise<boolean>}
 */
export function checkConnectionStatus({ id }) {
  return axios
    .get(`ajax/remote_api/status/${id}`)
    .then(({ data }) => data === "valid_token");
}
<|endoftext|>


<commit_before>import React, { useEffect, useState } from "react";
import axios from "axios";

let PagedTableContext;
const { Provider, Consumer } = (PagedTableContext = React.createContext());

/**
 * Context Provider the the Analyses Table.
 */
function PagedTableProvider({ children, url }) {
  const [tableState, setTableState] = useState({
    loading: true,
    dataSource: undefined,
    search: "",
    current: 1,
    pageSize: 10,
    order: "descend",
    column: "createdDate",
    total: undefined,
    filters: {}
  });

  useEffect(() => updateTable(), [
    tableState.search,
    tableState.current,
    tableState.order,
    tableState.column,
    tableState.filters
  ]);

  /**
   * Called whenever the table needs to be re-rendered.
   */
  const updateTable = () => {
    setTableState({ ...tableState, loading: true });

    axios
      .post(url, {
        current: tableState.current - 1,
        pageSize: tableState.pageSize,
        sortColumn: tableState.column,
        sortDirection: tableState.order,
        search: tableState.search,
        filters: tableState.filters
      })
      .then(({ data }) => {
        setTableState({
          ...tableState,
          ...{ total: data.total, dataSource: data.dataSource, loading: false }
        });
      });
  };

  /**
   * Handler for default table actions (paging, filtering, and sorting)
   *
   * @param {object} pagination
   * @param {object} filters
   * @param {object} sorter
   */
  const handleTableChange = (pagination, filters, sorter) => {
    const { pageSize, current } = pagination;
    const { order, field } = sorter;
    setTableState({
      ...tableState,
      ...{
        pageSize,
        current,
        order: order || "descend",
        column: field || "createdDate",
        filters
      }
    });
  };

  return (
    <Provider value={{ ...tableState, handleTableChange, updateTable }}>
      {children}
    </Provider>
  );
}

export { PagedTableProvider, Consumer as PagedTableConsumer, PagedTableContext };
<commit_msg>Update JSDoc<commit_after>import React, { useEffect, useState } from "react";
import axios from "axios";

let PagedTableContext;
const { Provider, Consumer } = (PagedTableContext = React.createContext());

/**
 * Provider for all ant.design server paged tables.
 * @param children Child DOM elements
 * @param {string} url - to fetch the table contents from
 * @returns {*}
 * @constructor
 */
function PagedTableProvider({ children, url }) {
  const [tableState, setTableState] = useState({
    loading: true,
    dataSource: undefined,
    search: "",
    current: 1,
    pageSize: 10,
    order: "descend",
    column: "createdDate",
    total: undefined,
    filters: {}
  });

  /*
  Table is updated whenever one of these are changed.
   */
  useEffect(() => updateTable(), [
    tableState.search,
    tableState.current,
    tableState.order,
    tableState.column,
    tableState.filters
  ]);

  /**
   * Called whenever the table needs to be re-rendered.
   */
  const updateTable = () => {
    setTableState({ ...tableState, loading: true });

    axios
      .post(url, {
        current: tableState.current - 1,
        pageSize: tableState.pageSize,
        sortColumn: tableState.column,
        sortDirection: tableState.order,
        search: tableState.search,
        filters: tableState.filters
      })
      .then(({ data }) => {
        setTableState({
          ...tableState,
          ...{ total: data.total, dataSource: data.dataSource, loading: false }
        });
      });
  };

  /**
   * Handler for default table actions (paging, filtering, and sorting)
   *
   * @param {object} pagination
   * @param {object} filters
   * @param {object} sorter
   */
  const handleTableChange = (pagination, filters, sorter) => {
    const { pageSize, current } = pagination;
    const { order, field } = sorter;
    setTableState({
      ...tableState,
      ...{
        pageSize,
        current,
        order: order || "descend",
        column: field || "createdDate",
        filters
      }
    });
  };

  return (
    <Provider value={{ ...tableState, handleTableChange, updateTable }}>
      {children}
    </Provider>
  );
}

export {
  PagedTableProvider,
  Consumer as PagedTableConsumer,
  PagedTableContext
};
<|endoftext|>


<commit_before>import React from 'react';
import series from 'async/series';
import asyncify from 'async/asyncify';
import mapSeries from 'async/mapSeries';

import { ComponentStatus, routerHookPropName } from './constants';
import getInitStatus from './getInitStatus';
import { renderPropsShape, routerHookContextShape } from './PropTypes';

const ABORT = 'abort';

export default class RouterHookContainer extends React.Component {
  static propTypes = {
    children: React.PropTypes.node.isRequired,
    locals: React.PropTypes.object.isRequired,
    renderProps: renderPropsShape.isRequired,
    routerDidEnterHooks: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
    routerWillEnterHooks: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  }

  static contextTypes = {
    routerHookContext: routerHookContextShape,
  };

  constructor(props, context) {
    super(props, context);
    this.setStatus = this.setStatus.bind(this);
    this.reloadComponent = this.reloadComponent.bind(this);
    this.mounted = false;

    this.shouldReload = false;
    this.state = {
      status: getInitStatus(
        props.children.type,
        this.props.routerWillEnterHooks,
      ),
      childProps: {},
    };
  }

  componentWillMount() {
    this.context.routerHookContext.setComponentStatus(this.Component, this.state.status);
  }

  componentDidMount() {
    this.mounted = true;
    setTimeout(() => {
      this.reloadComponent(true);
    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.renderProps.location !== nextProps.renderProps.location) {
      this.setState({
        status: getInitStatus(
          this.Component,
          this.props.routerWillEnterHooks,
        ),
        childProps: {},
      });
      this.shouldReload = true;
      if (this.mounted) {
        this.forceUpdate();
      }
      return;
    }

    if (this.mounted) {
      this.forceUpdate();
    }
  }

  componentDidUpdate() {
    if (this.shouldReload) {
      this.shouldReload = false;
      setTimeout(() => {
        this.reloadComponent(true);
      });
    }
  }

  componentWillUnmount() {
    this.mounted = false;
  }

  setStatus(status, shouldReport, err) {
    const shouldUpdate = this.state.status !== status;
    this.setState({
      status,
    });
    if (shouldReport) {
      this.context.routerHookContext.setComponentStatus(this.Component, status, err);
    }
    if (shouldUpdate) {
      if (this.mounted) {
        this.forceUpdate();
      }
    }
  }

  get Component() {
    return this.props.children.type;
  }

  reloadComponent(shouldReportStatus = false) {
    const routerHooks = this.Component[routerHookPropName];
    if (!routerHooks) {
      return;
    }
    /* eslint-disable no-unused-vars */
    const {
      children,
      locals,
      renderProps,
      routerDidEnterHooks,
      routerWillEnterHooks,
    } = this.props;
    /* eslint-enable no-unused-vars */

    const initStatus = getInitStatus(
      this.Component,
      routerWillEnterHooks,
    );

    this.setStatus(initStatus, shouldReportStatus);
    if (initStatus === ComponentStatus.DONE) {
      return;
    }

    const location = renderProps.location;

    const args = {
      ...renderProps,
      ...locals,
      getProps: () => this.state.childProps,
      setProps: (p) => {
        if (location === renderProps.location) {
          this.setState({
            childProps: {
              ...this.state.childProps,
              ...p,
            },
          });
          if (this.mounted) {
            this.forceUpdate();
          }
        }
      },
    };

    series([
      (callback) => {
        if (location !== renderProps.location) {
          callback(ABORT);
          return;
        }
        if (initStatus === 'init') {
          callback();
          return;
        }
        const willEnterHooks = routerWillEnterHooks
              .map(key => routerHooks[key])
              .filter(f => f)
              .map(f => asyncify(f));
        if (willEnterHooks.length > 0) {
          mapSeries(willEnterHooks, (hook, cb) => {
            if (location === renderProps.location) {
              hook(args, cb);
            }
          }, callback);
        } else {
          callback();
        }
      },
      (callback) => {
        if (location !== renderProps.location) {
          callback(ABORT);
          return;
        }
        this.setStatus(ComponentStatus.DEFER, shouldReportStatus);
        callback();
      },
      (callback) => {
        if (location !== renderProps.location) {
          callback(ABORT);
          return;
        }
        const didEnterHooks = routerDidEnterHooks
          .map(key => routerHooks[key])
          .filter(f => f)
              .map(f => asyncify(f));
        if (didEnterHooks.length > 0) {
          mapSeries(didEnterHooks, (hook, cb) => {
            if (location === renderProps.location) {
              hook(args, cb);
            }
          }, callback);
        } else {
          callback();
        }
      },
      (callback) => {
        if (location !== renderProps.location) {
          callback(ABORT);
          return;
        }
        this.setStatus(ComponentStatus.DONE, shouldReportStatus);
        callback();
      },
    ], (err) => {
      if (err && err === ABORT) {
        return;
      }
      this.setStatus(ComponentStatus.DONE, shouldReportStatus, err);
    });
  }

  render() {
    /* eslint-disable no-unused-vars */
    const {
      children,
      locals,
      renderProps,
      routerDidEnterHooks,
      routerWillEnterHooks,
      ...restProps
    } = this.props;
    /* eslint-enable no-unused-vars */
    const passProps = {
      ...restProps,
      ...this.state.childProps,
      componentStatus: this.state.status,
      reloadComponent: this.reloadComponent,
    };

    if (this.state.status === ComponentStatus.INIT) {
      if (!this.prevChildren) {
        return null;
      }
      return React.cloneElement(this.prevChildren, passProps);
    }

    this.prevChildren = React.cloneElement(children, passProps);
    return this.prevChildren;
  }
}
<commit_msg>[break] remove childProps<commit_after>import React from 'react';
import series from 'async/series';
import asyncify from 'async/asyncify';
import mapSeries from 'async/mapSeries';

import { ComponentStatus, routerHookPropName } from './constants';
import getInitStatus from './getInitStatus';
import { renderPropsShape, routerHookContextShape } from './PropTypes';

const ABORT = 'abort';

export default class RouterHookContainer extends React.Component {
  static propTypes = {
    children: React.PropTypes.node.isRequired,
    locals: React.PropTypes.object.isRequired,
    renderProps: renderPropsShape.isRequired,
    routerDidEnterHooks: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
    routerWillEnterHooks: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  }

  static contextTypes = {
    routerHookContext: routerHookContextShape,
  };

  constructor(props, context) {
    super(props, context);
    this.setStatus = this.setStatus.bind(this);
    this.reloadComponent = this.reloadComponent.bind(this);
    this.mounted = false;

    this.shouldReload = false;
    this.state = {
      status: getInitStatus(
        props.children.type,
        this.props.routerWillEnterHooks,
      ),
    };
  }

  componentWillMount() {
    this.context.routerHookContext.setComponentStatus(this.Component, this.state.status);
  }

  componentDidMount() {
    this.mounted = true;
    setImmediate(() => {
      this.reloadComponent(true);
    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.renderProps.location !== nextProps.renderProps.location) {
      this.setState({
        status: getInitStatus(
          this.Component,
          this.props.routerWillEnterHooks,
        ),
      });
      this.shouldReload = true;
      if (this.mounted) {
        this.forceUpdate();
      }
      return;
    }

    if (this.mounted) {
      this.forceUpdate();
    }
  }

  componentDidUpdate() {
    if (this.shouldReload) {
      this.shouldReload = false;
      setTimeout(() => {
        this.reloadComponent(true);
      });
    }
  }

  componentWillUnmount() {
    this.mounted = false;
  }

  setStatus(status, shouldReport, err) {
    const shouldUpdate = this.state.status !== status;
    this.setState({
      status,
    });
    if (shouldReport) {
      this.context.routerHookContext.setComponentStatus(this.Component, status, err);
    }
    if (shouldUpdate) {
      if (this.mounted) {
        this.forceUpdate();
      }
    }
  }

  get Component() {
    return this.props.children.type;
  }

  reloadComponent(shouldReportStatus = false) {
    const routerHooks = this.Component[routerHookPropName];
    if (!routerHooks) {
      return;
    }
    /* eslint-disable no-unused-vars */
    const {
      children,
      locals,
      renderProps,
      routerDidEnterHooks,
      routerWillEnterHooks,
    } = this.props;
    /* eslint-enable no-unused-vars */

    const initStatus = getInitStatus(
      this.Component,
      routerWillEnterHooks,
    );

    this.setStatus(initStatus, shouldReportStatus);
    if (initStatus === ComponentStatus.DONE) {
      return;
    }

    const location = renderProps.location;

    const args = {
      ...renderProps,
      ...locals,
    };

    series([
      (callback) => {
        if (location !== renderProps.location) {
          callback(ABORT);
          return;
        }
        if (initStatus === 'init') {
          callback();
          return;
        }
        const willEnterHooks = routerWillEnterHooks
              .map(key => routerHooks[key])
              .filter(f => f)
              .map(f => asyncify(f));
        if (willEnterHooks.length > 0) {
          mapSeries(willEnterHooks, (hook, cb) => {
            if (location === renderProps.location) {
              hook(args, cb);
            }
          }, callback);
        } else {
          callback();
        }
      },
      (callback) => {
        if (location !== renderProps.location) {
          callback(ABORT);
          return;
        }
        this.setStatus(ComponentStatus.DEFER, shouldReportStatus);
        callback();
      },
      (callback) => {
        if (location !== renderProps.location) {
          callback(ABORT);
          return;
        }
        const didEnterHooks = routerDidEnterHooks
          .map(key => routerHooks[key])
          .filter(f => f)
              .map(f => asyncify(f));
        if (didEnterHooks.length > 0) {
          mapSeries(didEnterHooks, (hook, cb) => {
            if (location === renderProps.location) {
              hook(args, cb);
            }
          }, callback);
        } else {
          callback();
        }
      },
      (callback) => {
        if (location !== renderProps.location) {
          callback(ABORT);
          return;
        }
        this.setStatus(ComponentStatus.DONE, shouldReportStatus);
        callback();
      },
    ], (err) => {
      if (err && err === ABORT) {
        return;
      }
      this.setStatus(ComponentStatus.DONE, shouldReportStatus, err);
    });
  }

  render() {
    /* eslint-disable no-unused-vars */
    const {
      children,
      locals,
      renderProps,
      routerDidEnterHooks,
      routerWillEnterHooks,
      ...restProps
    } = this.props;
    /* eslint-enable no-unused-vars */
    const passProps = {
      ...restProps,
      componentStatus: this.state.status,
      reloadComponent: this.reloadComponent,
    };

    if (this.state.status === ComponentStatus.INIT) {
      if (!this.prevChildren) {
        return null;
      }
      return React.cloneElement(this.prevChildren, passProps);
    }

    this.prevChildren = React.cloneElement(children, passProps);
    return this.prevChildren;
  }
}
<|endoftext|>


<commit_before>'use strict';

angular.module('vppApp')
    .controller('DatabaseCtrl', [
  '$scope',
  function ($scope) {
            //Page Controls
            //            $('.divControl').click(function () {
            //                $(".divFade").each(function () {
            //                    if ($('.divFade').css("visibility") == "hidden") {
            //                        // handle non visible state
            //                    } else {
            //                        // handle visible state
            //                        $('.divFade').fadeOut(0);
            //                    }
            //                });
            //            });
            //Summary Data URLs
            var devDataUrl = "http://localhost:3003";
            var publicDataURL = "http://vpp-data-api.elasticbeanstalk.com";

            //Data Builder
            //Load data for Study Area Search Function
            $.ajax({
                dataType: 'json',
                url: devDataUrl + '/data/studyareas',
                success: function (data) {
                    //console.clear();
                    //console.log(data);
                    for (var i = 0; i < data.length; i++) {
                        $("#studyareas-list").append('<option data-number=' + data[i].Project_ID + '>' + data[i].Name + '</option>');
                    }
                }
            });

            //THIS TOOL NEEDS TO BE WIRED UP TO THE SHOW DATA AND DOWNLOAD DATA FUNCTION
            $(".find - studyarea").change(function () {
                var param = $("#StudyAreaSearch").val();
                //                var sanValue = $('#studyareas-list option').filter(function () {
                //                    return this.value == san;
                //                    //console.log(this);
                //                }).data('number');

                //load Data for CollectionYear
                $.ajax({
                    dataType: 'json',
                    url: devDataUrl + '/data/collectionyear?sa=' + param,
                    success: function (data) {
                        //console.clear();
                        //console.log(data);
                        $scope.sa = data;
                        for (var i = 0; i < data.length; i++) {
                            $("#collectionyear-list").append('<option data-number=' + data[i].CollectionYear + '>' + data[i].CollectionYear + '</option>');
                        }
                    }
                });

            });

            $('#dbSummaryMI').click(function () {
                $("#DataSummary").fadeIn(500);
                $("#DataTable").fadeOut(0, function () {
                    $("#Policies").fadeOut(0);
                });

            });

            $('#dbPoliciesMI').click(function () {
                $("#Policies").fadeIn(500);
                $("#DataTable").fadeOut(0, function () {
                    $("#DataSummary").fadeOut(0);
                });
            });

            $('#vwDataBTN').click(function () {
                $("#DataTable").fadeIn(500);
                $("#Policies").fadeOut(0, function () {
                    $("#DataSummary").fadeOut(0);
                });
            });

            $('#vwOptionsBTN').click(function () {
                $("#DataSummary").fadeIn(500);
                $("#Policies").fadeOut(0, function () {
                    $("#DataTable").fadeOut(0);
                });
            });
            //End of Page Controls

            $("input[type=\"checkbox\"], input[type=\"radio\"]").not("[data-switch-no-init]").bootstrapSwitch();

            $("input[type=\"checkbox\"], input[type=\"radio\"]").on('switchChange.bootstrapSwitch', function (event, state) {
                //var LayerName = $(this).attr('name');

                console.log($(this).attr('name')); // DOM element
                //console.log(event); // jQuery event
                console.log(state); // true | false

                //            if (state) {
                //                switch (var) {
                //                case "":
                //
                //                    break;
                //                case "":
                //
                //                    break;
                //                case "":
                //
                //                    break;
                //
                //                }
                //            } else {
                //                switch (var) {
                //                case "":
                //
                //                    break;
                //                case "":
                //
                //                    break;
                //                case "":
                //
                //                    break;
                //                }
                //            }

            });

  }
 ]);<commit_msg>Minor Change to DB Controller<commit_after>'use strict';

angular.module('vppApp')
    .controller('DatabaseCtrl', [
  '$scope',
  function ($scope) {
            //Page Controls
            //            $('.divControl').click(function () {
            //                $(".divFade").each(function () {
            //                    if ($('.divFade').css("visibility") == "hidden") {
            //                        // handle non visible state
            //                    } else {
            //                        // handle visible state
            //                        $('.divFade').fadeOut(0);
            //                    }
            //                });
            //            });
            //Summary Data URLs
            var devDataUrl = "http://localhost:3003";
            var publicDataURL = "http://vpp-data-api.elasticbeanstalk.com";

            //Data Builder
            //Load data for Study Area Search Function
            $.ajax({
                dataType: 'json',
                url: devDataUrl + '/data/studyareas',
                success: function (data) {
                    //console.clear();
                    //console.log(data);
                    $scope.sa = data;
                    for (var i = 0; i < data.length; i++) {
                        $("#studyareas-list").append('<option data-number=' + data[i].Project_ID + '>' + data[i].Name + '</option>');
                    }
                }
            });

            //THIS TOOL NEEDS TO BE WIRED UP TO THE SHOW DATA AND DOWNLOAD DATA FUNCTION
            $(".find - studyarea").change(function () {
                var param = $("#StudyAreaSearch").val();
                //                var sanValue = $('#studyareas-list option').filter(function () {
                //                    return this.value == san;
                //                    //console.log(this);
                //                }).data('number');

                //load Data for CollectionYear
                $.ajax({
                    dataType: 'json',
                    url: devDataUrl + '/data/collectionyear?sa=' + param,
                    success: function (data) {
                        //console.clear();
                        //console.log(data);
                        $scope.cy = data;
                        for (var i = 0; i < data.length; i++) {
                            $("#collectionyear-list").append('<option data-number=' + data[i].CollectionYear + '>' + data[i].CollectionYear + '</option>');
                        }
                    }
                });

            });

            $('#dbSummaryMI').click(function () {
                $("#DataSummary").fadeIn(500);
                $("#DataTable").fadeOut(0, function () {
                    $("#Policies").fadeOut(0);
                });

            });

            $('#dbPoliciesMI').click(function () {
                $("#Policies").fadeIn(500);
                $("#DataTable").fadeOut(0, function () {
                    $("#DataSummary").fadeOut(0);
                });
            });

            $('#vwDataBTN').click(function () {
                $("#DataTable").fadeIn(500);
                $("#Policies").fadeOut(0, function () {
                    $("#DataSummary").fadeOut(0);
                });
            });

            $('#vwOptionsBTN').click(function () {
                $("#DataSummary").fadeIn(500);
                $("#Policies").fadeOut(0, function () {
                    $("#DataTable").fadeOut(0);
                });
            });
            //End of Page Controls

            $("input[type=\"checkbox\"], input[type=\"radio\"]").not("[data-switch-no-init]").bootstrapSwitch();

            $("input[type=\"checkbox\"], input[type=\"radio\"]").on('switchChange.bootstrapSwitch', function (event, state) {
                //var LayerName = $(this).attr('name');

                console.log($(this).attr('name')); // DOM element
                //console.log(event); // jQuery event
                console.log(state); // true | false

                //            if (state) {
                //                switch (var) {
                //                case "":
                //
                //                    break;
                //                case "":
                //
                //                    break;
                //                case "":
                //
                //                    break;
                //
                //                }
                //            } else {
                //                switch (var) {
                //                case "":
                //
                //                    break;
                //                case "":
                //
                //                    break;
                //                case "":
                //
                //                    break;
                //                }
                //            }

            });

  }
 ]);<|endoftext|>


<commit_before>import {
  warpPlusMethod
} from '../util'

export const getImageInfo = warpPlusMethod('io', 'getImageInfo')
<commit_msg>fix: 配置 uni.getImageInfo 临时文件路径<commit_after>import {
  warpPlusMethod
} from '../util'
import {
  TEMP_PATH
} from '../constants'

export const getImageInfo = warpPlusMethod('io', 'getImageInfo', options => {
  options.savePath = options.filename = TEMP_PATH + '/download/'
  return options
})
<|endoftext|>