<commit_before>/**
 * Axes Module
 * -----------
 * Add x/y axis.
 *
 */
var p_axes = PClass.extend({

  deps: [
    'scale'
  ],

  _subscriptions: [{
    /**
     * Update the axes when the scales have changed.
     */
    'Scale/updated': function() {
      if (!this._status) {return;}
      _.each(this._status.axes, this._updateAxis, this);
    }
  }],

  initialize: function() {
    if (!this._$scope.dataAvailable) {return;}
    this._status = {
      axes: this._initAxesModel()
    };
    _.each(this._status.axes, this._renderAxis, this);
  },

  _renderAxis: function(model, orient) {
    switch(orient) {
      case 'bottom': this._renderBottom(model); break;
      case 'left': this._renderLeft(model); break;
      case 'right': this._renderRight(model); break;}
    this._afterAxisChanges();
  },

  _getDataResolution: function() {
    var resolution;

    var getRes = function(valuesList) {
      var res;

      for (var i = valuesList.length - 1; i >= 0; i--) {
        var values = valuesList[i];
        var maxIteration = values.length;
        if (maxIteration > 24) {maxIteration = 24;}

        for (var j = 1; j < maxIteration; j++) {
          var resTmp = values[j].x - values[j-1].x;
          if (!res || resTmp < res) {
            res = resTmp;
          }
        }
      }
      return res;
    };

    _.each(this.data, function(d) {
      var resTmp = getRes(d.values ?
        [d.values] : _.pluck(d.data, 'values'));

      if (!resolution || resTmp < resolution) {
        resolution = resTmp;
      }
    });

    return resolution/1000;
  },

  _renderBottom: function(model) {
    var localeFormatter = d3.locale(h_getLocale(this.opts.locale));
    // The first predicate function that returns true will
    // determine how the specified date is formatted.
    // For more info in time formatting directives go to:
    // https://github.com/mbostock/d3/wiki/Time-Formatting
    var customTimeformats = [
      // milliseconds for all other times, such as ".012"
      ['.%L', function(d) { return d.getMilliseconds(); }],
      // for second boundaries, such as ":45"
      [':%S', function(d) { return d.getSeconds(); }],
      // for minute boundaries, such as "01:23"
      ['%H:%M', function(d) { return d.getMinutes(); }],
      // for hour boundaries, such as "01"
      ['%H', function(d) { return d.getHours(); }],
      // for day boundaries, such as "Mon 7"
      ['%a %d', function(d) { return d.getDay() && d.getDate() !== 1; }],
      // for week boundaries, such as "Feb 06"
      ['%b %d', function(d) { return d.getDate() !== 1; }],
      // for month boundaries, such as "February"
      ['%B', function(d) { return d.getMonth(); }],
      // for year boundaries, such as "2011".
      ['%Y', function() { return true; }]
    ];
    var tickFormat = localeFormatter.timeFormat.multi(customTimeformats);

    // Generate axis
    model.axis = d3.svg.axis()
      .scale(this.scale.x)
      .orient('bottom')
      .tickSize(this.opts.xaxis.bottom.tickLines ? 14 : 5, 0)
      .tickFormat(this.opts.xaxis.bottom.tickFormat || tickFormat);
    var ticks = this.opts.xaxis.ticks;

    if (ticks) {
      model.axis.ticks.apply(model.axis, ticks);
    } else {
      var domain = this.scale.x.domain();
      var start = domain[0].getTime();
      var end = domain[1].getTime();
      var diff = end - start;
      var minPxStep = 100;
      var width = this.opts.fullWidth;
      var maxValues = Math.ceil(width/minPxStep)+1;
      var tickValues = [];
      var ranges = ['year', 'month', 'day', 'hour', 'minutes'];

      var startDate = moment(start);
      var endDate = moment(end);

      var fillRange = function (start, min, max, range, numValues) {
        var diff = max.diff(min, range);
        var step = Math.ceil(diff/(numValues+1));
        var inserted = 0;

        if (step === 0) {step = 1;}

        while (inserted < numValues &&
          (start.isSame(min) || start.startOf(range).isBetween(min, max) || start.isSame(max)) &&
          tickValues.length < maxValues) {
          var time = start.toDate().getTime();
          if (tickValues.indexOf(time) === -1) {
            tickValues.push(time);
            inserted++;
          }
          start.add(step, range);
        }
        return inserted;
      };

      var min = startDate.clone();
      var max = endDate.clone();

      for (var j in ranges) {
        if (_.isString(ranges[j]) && !tickValues.length) {
          var inserted = fillRange(startDate.clone(), min, max, ranges[j], maxValues);
        }
      }

      var totalInserted = tickValues.length;
      while(tickValues.length < maxValues && totalInserted) {
        var tickValuesCloned = tickValues.slice();
        var numIntervals = tickValues.length;
        var intervalWidth = width/numIntervals;
        var maxValuesRemaining = Math.floor((maxValues - numIntervals)/numIntervals);
        totalInserted = 0;

        for (var i = 0; i < numIntervals; i++) {
          var minA;
          var minB;

          if (tickValuesCloned[i-1]) {
            minA = moment(tickValuesCloned[i]);
          } else {
            minA = min;
          }

          var maxValuesPerIntervalPx;
          var maxValuesPerInterval;

          if (tickValuesCloned[i+1]) {
            minB = moment(tickValuesCloned[i+1]);
            // maxValuesPerIntervalPx = Math.floor(intervalWidth/minPxStep);
          } else {
            minB = max;
          }

          var stepsize = this.scale.x(minB.toDate()) - this.scale.x(minA.toDate());
          var intervalWidth = ((minB.toDate().getTime() - minA.toDate().getTime())
            * stepsize) / (minB.toDate() - minA.toDate());

          maxValuesPerIntervalPx = Math.floor(intervalWidth/minPxStep);
          maxValuesPerInterval = d3.min([maxValuesRemaining, maxValuesPerIntervalPx]);

          inserted = 0;
          for (var k in ranges) {
            if (_.isString(ranges[k]) && !inserted) {
              inserted = fillRange(minA.clone(), minA, minB, ranges[k], maxValuesPerInterval);
              totalInserted += inserted;
            }
          }
        }
      }

      tickValues.sort(function(a, b){return a-b;});
      tickValues = _.map(tickValues, function(a) {return new Date(a);});

      model.axis.tickValues(tickValues);
    }

    // Render axis
    model.el = this.$svg.append('g')
        .attr('class', 'xaxis bottom')
        .attr('transform', 'translate(0,'+(this.opts.height+1)+')')
        .call(model.axis);

    if (this.opts.xaxis.bottom.tickLines) {
      model.el.selectAll('text')
        .attr('y', 0)
        .attr('x', 6)
        .style('text-anchor', 'start');
    } else {
      model.el.selectAll('text')
        .attr('y', 9);
    }

    // Append baseline
    model.el.append('rect')
      .attr('class', 'baseline')
      .attr('y', -1)
      .attr('x', -this.opts.margin.left)
      .attr('height', 1)
      .attr('width', this.opts.fullWidth);

    this._renderXLabel('bottom');
  },

  _renderLeft: function(model) {
    var tickFormat = this.opts.yaxis.left.tickFormat;
    var ticks = this.opts.yaxis.ticks || [];

    // Generate axis
    model.axis = d3.svg.axis()
      .scale(this.scale.y)
      .orient('left')
      .tickSize(-this.opts.width)
      .tickPadding(this.opts.margin.left)
      .tickFormat(tickFormat);
    model.axis.ticks.apply(model.axis, ticks);

    // Render axis
    model.el = this.$svg.append('g')
      .attr('class', 'yaxis left')
      .call(model.axis);

    this._renderYLabel('left');
  },

  _renderRight: function(model) {
    var tickFormat = this.opts.yaxis.right.tickFormat;
    var ticks = this.opts.yaxis.ticks || [];
    var self = this;

    // Generate axis
    model.axis = d3.svg.axis()
      .scale(this.scale.y)
      .orient('right')
      .tickSize(this.opts.width, 10)
      .tickPadding(0) // defaults to 3
      .tickFormat(function(d) {
        if (self.scale.y2) {
          var px = self.scale.y(d);
          var value = Math.round(self.scale.y2.invert(px));
          value = _.isNaN(value) ? '' : value.toLocaleString();
          return value;
        }
        return tickFormat(d);
      });
    model.axis.ticks.apply(model.axis, ticks);

    // Render axis
    model.el = this.$svg.append('g')
      .attr('class', 'yaxis right')
      .call(model.axis);

    this._renderYLabel('right');
  },

  /**
   * Update given axis when the scales changes.
   */
  _updateAxis: function(model, orient) {
    var scale = (orient === 'top' || orient === 'bottom') ?
      this.scale.x : this.scale.y;

    model.el
      // .transition()
      // .duration(500)
      // .ease('linear')
      .call(model.axis.scale(scale));

    this._afterAxisChanges(model);
  },

  /**
   * Set axes object in status model.
   */
  _initAxesModel: function() {
    var self = this,
        axes = {};

    var axesEnabled = {
      left: this.opts.yaxis.left.enabled,
      right: this.opts.yaxis.right.enabled || !!this.scale.y2,
      top: this.opts.xaxis.top.enabled,
      bottom: this.opts.xaxis.bottom.enabled
    };

    _.each(axesEnabled, function(enabled, orient) {
      if (!enabled) {return;}
      axes[orient] = {};
    });

    return axes;
  },

  _renderXLabel: function(orient) {
    if (!this.opts.xaxis[orient].label) {return;}
    this.$svg.select('.xaxis.' + orient).append('text')
      .attr('class', 'label')
      .attr('transform', h_getTranslate(-this.opts.margin.left, 0))
      .attr('y', 16)
      .attr('x', 0)
      .attr('text-anchor', 'start')
      .text(this.opts.xaxis[orient].label);
  },

  _renderYLabel: function(orient) {
    var label;
    var scaleUnits = this._$scope.scaleUnits.y;

    if (orient === 'left') {
      scaleUnits = (scaleUnits === 'default') ? false : scaleUnits;
      label = scaleUnits || this.opts.yaxis[orient].label;
    } else if (orient === 'right') {
      label = this._$scope.scaleUnits.y2 || this.opts.yaxis[orient].label;
    }
    if (!label || label === 'default') {return;}

    this.$svg.select('.yaxis.' + orient).append('text')
      .attr('class', 'label')
      .attr('transform', h_getTranslate(orient === 'left' ? -this.opts.margin.left :
        this.opts.width + this.opts.margin.right, this.opts.yaxis.textMarginTop))
      .attr('y', -10)
      .attr('x', 0)
      .attr('text-anchor', orient === 'left' ? 'start' : 'end')
      .text(label);
  },

  /**
   * Stuff to do when the axes have been
   * rendered or updated.
   */
  _afterAxisChanges: function(model) {
    // remove domain
    this.$svg.select('.yaxis .domain').remove();
    this.$svg.select('.xaxis .domain').remove();

    this.$svg.selectAll('.yaxis.left .tick text')
      .style('text-anchor', 'start', 'important');

    this.$svg.selectAll('.yaxis.right .tick text')
      .style('text-anchor', 'end', 'important')
      .attr('transform', h_getTranslate(this.opts.margin.right, this.opts.yaxis.textMarginTop));

    if (this.opts.yaxis.textMarginTop) {
      this.$svg.selectAll('.yaxis.left .tick text')
        .attr('transform', h_getTranslate(0, this.opts.yaxis.textMarginTop));
    }

    if (this.opts.xaxis.bottom.tickLines) {
      this.$svg.selectAll('.xaxis.bottom .tick text')
        .attr('transform', h_getTranslate(0,4))
        .attr('y', 0)
        .attr('x', 6)
        .style('text-anchor', 'start');
    } else {
      this.$svg.selectAll('.xaxis.bottom .tick text')
        .attr('y', 9);
    }

    // yaxis full grid
    if (this.opts.yaxis.fullGrid) {
      this.$svg.selectAll('.yaxis line')
        .attr('transform', h_getTranslate(+this.opts.margin.left , 0))
        .attr('x1', -this.opts.margin.left * 2);
    }

    // add zeroline
    this.$svg.selectAll('.yaxis line').each(function(d,i) {
      if (d !== 0) {return;}
      d3.select(this).attr('class', 'zeroline');
    });
  }

});

  // var tickCharacters: {
  //   year: 4,
  //   month: 2,
  //   hour: 2
  // };
<commit_msg>labels xaxes updated<commit_after>/**
 * Axes Module
 * -----------
 * Add x/y axis.
 *
 */
var p_axes = PClass.extend({

  deps: [
    'scale'
  ],

  _subscriptions: [{
    /**
     * Update the axes when the scales have changed.
     */
    'Scale/updated': function() {
      if (!this._status) {return;}
      _.each(this._status.axes, this._updateAxis, this);
    }
  }],

  initialize: function() {
    if (!this._$scope.dataAvailable) {return;}
    this._status = {
      axes: this._initAxesModel()
    };
    _.each(this._status.axes, this._renderAxis, this);
  },

  _renderAxis: function(model, orient) {
    switch(orient) {
      case 'bottom': this._renderBottom(model); break;
      case 'left': this._renderLeft(model); break;
      case 'right': this._renderRight(model); break;}
    this._afterAxisChanges();
  },

  _getDataResolution: function() {
    var resolution;

    var getRes = function(valuesList) {
      var res;

      for (var i = valuesList.length - 1; i >= 0; i--) {
        var values = valuesList[i];
        var maxIteration = values.length;
        if (maxIteration > 24) {maxIteration = 24;}

        for (var j = 1; j < maxIteration; j++) {
          var resTmp = values[j].x - values[j-1].x;
          if (!res || resTmp < res) {
            res = resTmp;
          }
        }
      }
      return res;
    };

    _.each(this.data, function(d) {
      var resTmp = getRes(d.values ?
        [d.values] : _.pluck(d.data, 'values'));

      if (!resolution || resTmp < resolution) {
        resolution = resTmp;
      }
    });

    return resolution/1000;
  },

  _renderBottom: function(model) {
    var localeFormatter = d3.locale(h_getLocale(this.opts.locale));
    // The first predicate function that returns true will
    // determine how the specified date is formatted.
    // For more info in time formatting directives go to:
    // https://github.com/mbostock/d3/wiki/Time-Formatting
    var customTimeformats = [
      // milliseconds for all other times, such as ".012"
      ['.%L', function(d) { return d.getMilliseconds(); }],
      // for second boundaries, such as ":45"
      [':%S', function(d) { return d.getSeconds(); }],
      // for minute boundaries, such as "01:23"
      ['%H:%M', function(d) { return d.getMinutes(); }],
      // for hour boundaries, such as "01"
      ['%H', function(d) { return d.getHours(); }],
      // for day boundaries, such as "Mon 7"
      ['%a %d', function(d) { return d.getDay() && d.getDate() !== 1; }],
      // for week boundaries, such as "Feb 06"
      ['%b %d', function(d) { return d.getDate() !== 1; }],
      // for month boundaries, such as "February"
      ['%B', function(d) { return d.getMonth(); }],
      // for year boundaries, such as "2011".
      ['%Y', function() { return true; }]
    ];
    var tickFormat = localeFormatter.timeFormat.multi(customTimeformats);

    // Generate axis
    model.axis = d3.svg.axis()
      .scale(this.scale.x)
      .orient('bottom')
      .tickSize(this.opts.xaxis.bottom.tickLines ? 7 : 5, 0)
      .tickFormat(this.opts.xaxis.bottom.tickFormat || tickFormat);
    var ticks = this.opts.xaxis.ticks;

    if (ticks) {
      model.axis.ticks.apply(model.axis, ticks);
    } else {
      var domain = this.scale.x.domain();
      var start = domain[0].getTime();
      var end = domain[1].getTime();
      var diff = end - start;
      var minStepSize = 90;
      var graphWidth = this.opts.fullWidth;
      var numValues = Math.ceil(graphWidth/minStepSize)+1;
      var stepIntervalMinutes = (end - start)/numValues/1000/60;
      var range;
      var stepInterval;

      // 10 minutes
      if (stepIntervalMinutes <= 10) {range = 'minutes';stepInterval = 10;}
      // 30 minutes
      else if (stepIntervalMinutes <= 30) {range = 'minutes';stepInterval = 30;}
      // 1 hours
      else if (stepIntervalMinutes <= 60) {range = 'hours';stepInterval = 1;}
      // 2 hours
      else if (stepIntervalMinutes <= 2*60) {range = 'hours';stepInterval = 2;}
      // 4 hours
      else if (stepIntervalMinutes <= 4*60) {range = 'hours';stepInterval = 4;}
      // 6 hours
      else if (stepIntervalMinutes <= 6*60) {range = 'hours';stepInterval = 6;}
      // 12 hours
      else if (stepIntervalMinutes <= 12*60) {range = 'hours';stepInterval = 12;}
      // 1 day
      else if (stepIntervalMinutes <= 24*60) {range = 'days';stepInterval = 1;}
      // 2 day
      else if (stepIntervalMinutes <= 2*24*60) {range = 'days';stepInterval = 2;}
      // 4 day
      else if (stepIntervalMinutes <= 4*24*60) {range = 'days';stepInterval = 4;}
      // 1 semana
      else if (stepIntervalMinutes <= 7*24*60) {range = 'weeks';stepInterval = 1;}
      // 2 semanas
      else if (stepIntervalMinutes <= 2*7*24*60) {range = 'weeks';stepInterval = 2;}
      // 1 mes
      else if (stepIntervalMinutes <= (365/12)*24*60) {range = 'months';stepInterval = 1;}
      // 2 mes
      else if (stepIntervalMinutes <= (365/12)*2*24*60) {range = 'months';stepInterval = 2;}
      // 3 mes
      else if (stepIntervalMinutes <= (365/12)*3*24*60) {range = 'months';stepInterval = 3;}
      // 4 mes
      else if (stepIntervalMinutes <= (365/12)*4*24*60) {range = 'months';stepInterval = 4;}
      // 6 mes
      else if (stepIntervalMinutes <= (365/12)*6*24*60) {range = 'months';stepInterval = 6;}
      // years
      else {range = 'years';stepInterval = 1;}

      var tickValues = [];
      var from = moment(start).startOf(range);
      var t = from.toDate().getTime();
      while (t <= end) {
        if (t >= start && tickValues.indexOf(t) === -1) {
          tickValues.push(t);
        }
        from.add(stepInterval, range);
        t = from.toDate().getTime();
      }

      tickValues = _.map(tickValues, function(a) {return new Date(a);});
      model.axis.tickValues(tickValues);
    }

    // Render axis
    model.el = this.$svg.append('g')
        .attr('class', 'xaxis bottom')
        .attr('transform', 'translate(0,'+(this.opts.height+1)+')')
        .call(model.axis);

    if (this.opts.xaxis.bottom.tickLines) {
      model.el.selectAll('text')
        .attr('y', 0)
        .attr('x', 6)
        .style('text-anchor', 'start');
    } else {
      model.el.selectAll('text')
        .attr('y', 9);
    }

    // Append baseline
    model.el.append('rect')
      .attr('class', 'baseline')
      .attr('y', -1)
      .attr('x', -this.opts.margin.left)
      .attr('height', 1)
      .attr('width', this.opts.fullWidth);

    this._renderXLabel('bottom');
  },

  _renderLeft: function(model) {
    var tickFormat = this.opts.yaxis.left.tickFormat;
    var ticks = this.opts.yaxis.ticks || [];

    // Generate axis
    model.axis = d3.svg.axis()
      .scale(this.scale.y)
      .orient('left')
      .tickSize(-this.opts.width)
      .tickPadding(this.opts.margin.left)
      .tickFormat(tickFormat);
    model.axis.ticks.apply(model.axis, ticks);

    // Render axis
    model.el = this.$svg.append('g')
      .attr('class', 'yaxis left')
      .call(model.axis);

    this._renderYLabel('left');
  },

  _renderRight: function(model) {
    var tickFormat = this.opts.yaxis.right.tickFormat;
    var ticks = this.opts.yaxis.ticks || [];
    var self = this;

    // Generate axis
    model.axis = d3.svg.axis()
      .scale(this.scale.y)
      .orient('right')
      .tickSize(this.opts.width, 10)
      .tickPadding(0) // defaults to 3
      .tickFormat(function(d) {
        if (self.scale.y2) {
          var px = self.scale.y(d);
          var value = Math.round(self.scale.y2.invert(px));
          value = _.isNaN(value) ? '' : value.toLocaleString();
          return value;
        }
        return tickFormat(d);
      });
    model.axis.ticks.apply(model.axis, ticks);

    // Render axis
    model.el = this.$svg.append('g')
      .attr('class', 'yaxis right')
      .call(model.axis);

    this._renderYLabel('right');
  },

  /**
   * Update given axis when the scales changes.
   */
  _updateAxis: function(model, orient) {
    var scale = (orient === 'top' || orient === 'bottom') ?
      this.scale.x : this.scale.y;

    model.el
      // .transition()
      // .duration(500)
      // .ease('linear')
      .call(model.axis.scale(scale));

    this._afterAxisChanges(model);
  },

  /**
   * Set axes object in status model.
   */
  _initAxesModel: function() {
    var self = this,
        axes = {};

    var axesEnabled = {
      left: this.opts.yaxis.left.enabled,
      right: this.opts.yaxis.right.enabled || !!this.scale.y2,
      top: this.opts.xaxis.top.enabled,
      bottom: this.opts.xaxis.bottom.enabled
    };

    _.each(axesEnabled, function(enabled, orient) {
      if (!enabled) {return;}
      axes[orient] = {};
    });

    return axes;
  },

  _renderXLabel: function(orient) {
    if (!this.opts.xaxis[orient].label) {return;}
    this.$svg.select('.xaxis.' + orient).append('text')
      .attr('class', 'label')
      .attr('transform', h_getTranslate(-this.opts.margin.left, 0))
      .attr('y', 16)
      .attr('x', 0)
      .attr('text-anchor', 'start')
      .text(this.opts.xaxis[orient].label);
  },

  _renderYLabel: function(orient) {
    var label;
    var scaleUnits = this._$scope.scaleUnits.y;

    if (orient === 'left') {
      scaleUnits = (scaleUnits === 'default') ? false : scaleUnits;
      label = scaleUnits || this.opts.yaxis[orient].label;
    } else if (orient === 'right') {
      label = this._$scope.scaleUnits.y2 || this.opts.yaxis[orient].label;
    }
    if (!label || label === 'default') {return;}

    this.$svg.select('.yaxis.' + orient).append('text')
      .attr('class', 'label')
      .attr('transform', h_getTranslate(orient === 'left' ? -this.opts.margin.left :
        this.opts.width + this.opts.margin.right, this.opts.yaxis.textMarginTop))
      .attr('y', -10)
      .attr('x', 0)
      .attr('text-anchor', orient === 'left' ? 'start' : 'end')
      .text(label);
  },

  /**
   * Stuff to do when the axes have been
   * rendered or updated.
   */
  _afterAxisChanges: function(model) {
    // remove domain
    this.$svg.select('.yaxis .domain').remove();
    this.$svg.select('.xaxis .domain').remove();

    this.$svg.selectAll('.yaxis.left .tick text')
      .style('text-anchor', 'start', 'important');

    this.$svg.selectAll('.yaxis.right .tick text')
      .style('text-anchor', 'end', 'important')
      .attr('transform', h_getTranslate(this.opts.margin.right, this.opts.yaxis.textMarginTop));

    if (this.opts.yaxis.textMarginTop) {
      this.$svg.selectAll('.yaxis.left .tick text')
        .attr('transform', h_getTranslate(0, this.opts.yaxis.textMarginTop));
    }

    if (this.opts.xaxis.bottom.tickLines) {
      this.$svg.selectAll('.xaxis.bottom .tick text')
        .attr('transform', h_getTranslate(0,4))
        .attr('y', 0)
        .attr('x', 6)
        .style('text-anchor', 'start');
    } else {
      this.$svg.selectAll('.xaxis.bottom .tick text')
        .attr('y', 9);
    }

    // yaxis full grid
    if (this.opts.yaxis.fullGrid) {
      this.$svg.selectAll('.yaxis line')
        .attr('transform', h_getTranslate(+this.opts.margin.left , 0))
        .attr('x1', -this.opts.margin.left * 2);
    }

    // add zeroline
    this.$svg.selectAll('.yaxis line').each(function(d,i) {
      if (d !== 0) {return;}
      d3.select(this).attr('class', 'zeroline');
    });
  }

});

  // var tickCharacters: {
  //   year: 4,
  //   month: 2,
  //   hour: 2
  // };
<|endoftext|>


<commit_before>import IDSequence from './id-sequence';

class CommentBuilder {
  constructor() {
    this._id = 0;
    this._path = 'first.txt';
    this._position = 0;
    this._authorLogin = 'someone';
    this._authorAvatarUrl = 'https://avatars3.githubusercontent.com/u/17565?s=32&v=4';
    this._url = 'https://github.com/atom/github/pull/1829/files#r242224689';
    this._createdAt = '2018-12-27T17:51:17Z';
    this._body = 'Lorem ipsum dolor sit amet, te urbanitas appellantur est.';
    this._replyTo = null;
    this._isMinimized = false;
  }

  id(i) {
    this._id = i;
    return this;
  }

  minimized(m) {
    this._isMinimized = m;
    return this;
  }

  path(p) {
    this._path = p;
    return this;
  }

  position(pos) {
    this._position = pos;
    return this;
  }

  authorLogin(login) {
    this._authorLogin = login;
    return this;
  }

  authorAvatarUrl(url) {
    this._authorAvatarUrl = url;
    return this;
  }

  url(u) {
    this._url = u;
    return this;
  }

  createdAt(ts) {
    this._createdAt = ts;
    return this;
  }

  body(text) {
    this._body = text;
    return this;
  }

  replyTo(replyToId) {
    this._replyTo = {id: replyToId};
    return this;
  }

  build() {
    return {
      id: this._id,
      author: {
        login: this._authorLogin,
        avatarUrl: this._authorAvatarUrl,
      },
      body: this._body,
      path: this._path,
      position: this._position,
      createdAt: this._createdAt,
      url: this._url,
      replyTo: this._replyTo,
      isMinimized: this._isMinimized,
    };
  }
}

class ReviewThreadBuilder {
  constructor(commentIDs = new IDSequence()) {
    this._isResolved = false;
    this._comments = [];

    this.commentIDs = commentIDs;
  }

  resolved() {
    this._isResolved = true;
    return this;
  }

  addComment(block = () => {}) {
    const builder = new CommentBuilder();
    builder.id(this.commentIDs.nextID());

    block(builder);

    this._comments.push(builder.build());

    return this;
  }

  build() {
    return {
      isResolved: this._isResolved,
      comments: {edges: this._comments.map(comment => ({node: comment}))},
    };
  }
}

class ReviewBuilder {
  constructor(commentIDs = new IDSequence()) {
    this.commentIDs = commentIDs;
    this._id = 0;
    this._comments = [];
    this._submittedAt = '2018-12-28T20:40:55Z';
  }

  id(i) {
    this._id = i;
    return this;
  }

  submittedAt(timestamp) {
    this._submittedAt = timestamp;
    return this;
  }

  addComment(block = () => {}) {
    const builder = new CommentBuilder();
    builder.id(this.commentIDs.nextID());

    block(builder);
    this._comments.push(builder.build());

    return this;
  }

  build() {
    const comments = this._comments.map(comment => {
      return {node: comment};
    });
    return {
      id: this._id,
      submittedAt: this._submittedAt,
      comments: {edges: comments},
    };
  }
}

class PullRequestBuilder {
  constructor() {
    this.commentIDs = new IDSequence();
    this.reviewIDs = new IDSequence();
    this._reviews = [];
    this._reviewThreads = [];
  }

  addReview(block = () => {}) {
    const builder = new ReviewBuilder(this.commentIDs);
    builder.id(this.reviewIDs.nextID());

    block(builder);
    this._reviews.push(builder.build());
    return this;
  }

  addReviewThread(block = () => {}) {
    const builder = new ReviewThreadBuilder(this.commentIDs);
    block(builder);
    this._reviewThreads.push(builder.build());
    return this;
  }

  build() {
    return {
      reviews: {edges: this._reviews.map(r => ({node: r}))},
      reviewThreads: {edges: this._reviewThreads.map(t => ({node: t}))},
    };
  }
}

export function reviewBuilder() {
  return new ReviewBuilder();
}

export function reviewThreadBuilder() {
  return new ReviewThreadBuilder();
}

export function pullRequestBuilder() {
  return new PullRequestBuilder();
}
<commit_msg>:fire: unused PR builder<commit_after><|endoftext|>


<commit_before>describe("Classes", function () {
    before(function () {
        fixture.setBase("test/fixtures");
    });

    beforeEach(function () {
        fixture.load('basic_elements.html');
        this.el = document.getElementById("id1");
        this.$el = $(this.el);
        this.el2 = document.getElementById("id2");
        this.$el2 = $(this.el2);
        this.el3 = document.getElementById("id3");
        this.$el3 = $(this.el3);
        this.newClass1 = "new1";
        this.newClass2 = "new2";
    });

    afterEach(function () {
        fixture.cleanup();
    });

    describe("addClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.addClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.addClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.addClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.addClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should not create an empty class attribute with an empty string", function () {
            this.$el.addClass("");

            expect(this.el).to.not.have.attribute("class");
        });

        it("should add the class name to the element", function () {
            this.$el.addClass(this.newClass1);

            expect(this.el).to.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            this.$el.addClass(" " + this.newClass1 + " ");

            expect(this.el).to.have.class(this.newClass1);
        });

        it("should keep the original class names of the element", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);
            this.$el2.addClass(this.newClass1);

            for (let className of originalClassNames) {
                expect(this.el2).to.have.class(className);
            }
            expect(this.el2).to.have.class(this.newClass1);
        });

        it("should add space-separated class names to the element", function () {
            this.$el.addClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            this.$el.addClass(" " + this.newClass1 + "  " + this.newClass2 + "   ");

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
            expect(this.el.classList).to.have.lengthOf(2);
        });

        it("shouldn't add an already existing class name", function () {
            this.el.className = this.newClass1;
            this.$el.addClass(this.newClass1);

            expect(this.el.className).to.equal(this.newClass1);
        });

        it("shouldn't add duplicate class names in one call", function () {
            this.$el.addClass(this.newClass1 + " " + this.newClass1);

            expect(this.el.className).to.equal(this.newClass1);
        });

        it("should add class names to multiple elements", function () {
            var $els = $$("#id1, #id2");
            $els.addClass(this.newClass1);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass1);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.addClass(this.newClass1);

            expect(returnValue).to.equal(this.$el);
        });
    });

    describe("removeClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.removeClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should not remove class attribute", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(this.newClass1);

            expect(this.el).to.have.attribute("class");
        });

        it("should remove the class name from the element", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(this.newClass1);

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(" " + this.newClass1 + " ");

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should remove space-separated class names from the element", function () {
            this.el.classList.add(this.newClass1, this.newClass2);
            this.$el.removeClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.not.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);

            this.$el2.removeClass(" " + originalClassNames.join("   ") + "  ");

            expect(this.el2.classList).to.have.lengthOf(0);

        });

        it("should keep the original class names of the element", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);
            var newClassNames;
            this.el2.classList.add(this.newClass1);
            this.$el2.removeClass(this.newClass1);

            expect(originalClassNames.length).to.equal(this.el2.classList.length);
            for (let className of originalClassNames) {
                expect(this.el2).to.have.class(className);
            }
        });

        it("shouldn't throw error on duplicate class names in one call", function () {
            var duplicateNames = this.newClass1 + " " + this.newClass1;
            this.el.classList.add(this.newClass1);

            expect(calling(this.$el.removeClass).on(this.$el).with(duplicateNames)).to.not.throw(Error);
        });

        it("should work on multiple elements", function () {
            var $els = $$("#" + this.el2.id + ", #" + this.el3.id);

            this.el2.classList.add(this.newClass1);
            this.el3.classList.add(this.newClass1);
            $els.removeClass(this.newClass1);

            expect(this.el2).to.not.have.class(this.newClass1);
            expect(this.el3).to.not.have.class(this.newClass1);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.removeClass("");

            expect(returnValue).to.equal(this.$el);
        });

    });

    describe("toggleClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.toggleClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should remove an existing class name", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass1);
            expect(this.el2).to.not.have.class(this.newClass1);
        });

        it("should add a nonexistent class name", function () {
            this.$el.toggleClass(this.newClass1);
            expect(this.el).to.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            var whiteSpacedClass = "  " + this.newClass1 + "  ";
            this.$el.toggleClass(whiteSpacedClass);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el.className).to.not.include(whiteSpacedClass);

            this.$el.toggleClass(whiteSpacedClass);

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should work with space-separated class names", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass("  " + this.newClass1 + "   " + this.newClass2 + "  ");

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should keep the original class names of the element", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass2);

            expect(this.el).to.have.class(this.newClass1);

            this.$el.toggleClass(this.newClass2);

            expect(this.el).to.have.class(this.newClass1);
        });

        it("shouldn't throw error on duplicate class names in one call", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with(this.newClass1 + " " + this.newClass1)).to.not.throw(Error);
        });

        it("should work on multiple elements", function () {
            var $els = $$("#" + this.el2.id + ", #" + this.el3.id);

            $els.toggleClass(this.newClass1);

            expect(this.el2).to.have.class(this.newClass1);
            expect(this.el3).to.have.class(this.newClass1);

            $els.toggleClass(this.newClass1);

            expect(this.el2).to.not.have.class(this.newClass1);
            expect(this.el3).to.not.have.class(this.newClass1);
        });
    });

    describe("hasClass()", function () {

    });

    describe("show()", function () {

    });

    describe("hide()", function () {

    });

     describe("toggle()", function () {

    });

});

<commit_msg>Tests for hasClass()<commit_after>describe("Classes", function () {
    before(function () {
        fixture.setBase("test/fixtures");
    });

    beforeEach(function () {
        fixture.load('basic_elements.html');
        this.el = document.getElementById("id1");
        this.$el = $(this.el);
        this.el2 = document.getElementById("id2");
        this.$el2 = $(this.el2);
        this.el3 = document.getElementById("id3");
        this.$el3 = $(this.el3);
        this.newClass1 = "new1";
        this.newClass2 = "new2";
    });

    afterEach(function () {
        fixture.cleanup();
    });

    describe("addClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.addClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.addClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.addClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.addClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should not create an empty class attribute with an empty string", function () {
            this.$el.addClass("");

            expect(this.el).to.not.have.attribute("class");
        });

        it("should add the class name to the element", function () {
            this.$el.addClass(this.newClass1);

            expect(this.el).to.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            this.$el.addClass(" " + this.newClass1 + " ");

            expect(this.el).to.have.class(this.newClass1);
        });

        it("should keep the original class names of the element", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);
            this.$el2.addClass(this.newClass1);

            for (let className of originalClassNames) {
                expect(this.el2).to.have.class(className);
            }
            expect(this.el2).to.have.class(this.newClass1);
        });

        it("should add space-separated class names to the element", function () {
            this.$el.addClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            this.$el.addClass(" " + this.newClass1 + "  " + this.newClass2 + "   ");

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
            expect(this.el.classList).to.have.lengthOf(2);
        });

        it("shouldn't add an already existing class name", function () {
            this.el.className = this.newClass1;
            this.$el.addClass(this.newClass1);

            expect(this.el.className).to.equal(this.newClass1);
        });

        it("shouldn't add duplicate class names in one call", function () {
            this.$el.addClass(this.newClass1 + " " + this.newClass1);

            expect(this.el.className).to.equal(this.newClass1);
        });

        it("should add class names to multiple elements", function () {
            var $els = $$("#id1, #id2");
            $els.addClass(this.newClass1);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass1);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.addClass(this.newClass1);

            expect(returnValue).to.equal(this.$el);
        });
    });

    describe("removeClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.removeClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string", function () {
            expect(calling(this.$el.removeClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should not remove class attribute", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(this.newClass1);

            expect(this.el).to.have.attribute("class");
        });

        it("should remove the class name from the element", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(this.newClass1);

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            this.el.classList.add(this.newClass1);
            this.$el.removeClass(" " + this.newClass1 + " ");

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should remove space-separated class names from the element", function () {
            this.el.classList.add(this.newClass1, this.newClass2);
            this.$el.removeClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.not.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);

            this.$el2.removeClass(" " + originalClassNames.join("   ") + "  ");

            expect(this.el2.classList).to.have.lengthOf(0);

        });

        it("should keep the original class names of the element", function () {
            var originalClassNames = Array.prototype.slice.call(this.el2.classList);
            var newClassNames;
            this.el2.classList.add(this.newClass1);
            this.$el2.removeClass(this.newClass1);

            expect(originalClassNames.length).to.equal(this.el2.classList.length);
            for (let className of originalClassNames) {
                expect(this.el2).to.have.class(className);
            }
        });

        it("shouldn't throw error on duplicate class names in one call", function () {
            var duplicateNames = this.newClass1 + " " + this.newClass1;
            this.el.classList.add(this.newClass1);

            expect(calling(this.$el.removeClass).on(this.$el).with(duplicateNames)).to.not.throw(Error);
        });

        it("should work on multiple elements", function () {
            var $els = $$("#" + this.el2.id + ", #" + this.el3.id);

            this.el2.classList.add(this.newClass1);
            this.el3.classList.add(this.newClass1);
            $els.removeClass(this.newClass1);

            expect(this.el2).to.not.have.class(this.newClass1);
            expect(this.el3).to.not.have.class(this.newClass1);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.removeClass("");

            expect(returnValue).to.equal(this.$el);
        });

    });

    describe("toggleClass()", function () {
        it("should throw reference error without arguments", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with()).to.throw(ReferenceError);
        });

        it("should throw type error with invalid type arguments", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with(null)).to.throw(TypeError);
            expect(calling(this.$el.toggleClass).on(this.$el).with({})).to.throw(TypeError);
        });

        it("should not throw error with an empty string argument", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with("")).to.not.throw(Error);
        });

        it("should remove an existing class name", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass1);
            expect(this.el2).to.not.have.class(this.newClass1);
        });

        it("should add a nonexistent class name", function () {
            this.$el.toggleClass(this.newClass1);
            expect(this.el).to.have.class(this.newClass1);
        });

        it("should trim whitespace from the class name", function () {
            var whiteSpacedClass = "  " + this.newClass1 + "  ";
            this.$el.toggleClass(whiteSpacedClass);

            expect(this.el).to.have.class(this.newClass1);
            expect(this.el.className).to.not.include(whiteSpacedClass);

            this.$el.toggleClass(whiteSpacedClass);

            expect(this.el).to.not.have.class(this.newClass1);
        });

        it("should work with space-separated class names", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass1 + " " + this.newClass2);

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should work with class names with excess whitespace", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass("  " + this.newClass1 + "   " + this.newClass2 + "  ");

            expect(this.el).to.not.have.class(this.newClass1);
            expect(this.el).to.have.class(this.newClass2);
        });

        it("should keep the original class names of the element", function () {
            this.el.classList.add(this.newClass1);
            this.$el.toggleClass(this.newClass2);

            expect(this.el).to.have.class(this.newClass1);

            this.$el.toggleClass(this.newClass2);

            expect(this.el).to.have.class(this.newClass1);
        });

        it("shouldn't throw error on duplicate class names in one call", function () {
            expect(calling(this.$el.toggleClass).on(this.$el).with(this.newClass1 + " " + this.newClass1)).to.not.throw(Error);
        });

        it("should work on multiple elements", function () {
            var $els = $$("#" + this.el2.id + ", #" + this.el3.id);

            $els.toggleClass(this.newClass1);

            expect(this.el2).to.have.class(this.newClass1);
            expect(this.el3).to.have.class(this.newClass1);

            $els.toggleClass(this.newClass1);

            expect(this.el2).to.not.have.class(this.newClass1);
            expect(this.el3).to.not.have.class(this.newClass1);
        });

        it("should return the Jamón instance", function () {
            var returnValue = this.$el.toggleClass("");

            expect(returnValue).to.equal(this.$el);
        });
    });

    describe("hasClass()", function () {
        it("should not throw error without arguments", function () {
            expect(calling(this.$el.hasClass).on(this.$el).with()).to.not.throw(Error);
        });

        it("should throw error with space character in argument", function () {
            expect(calling(this.$el.hasClass).on(this.$el).with(this.newClass1 + " ")).to.throw(Error);
        });

        it("should not throw error with an empty string argument", function () {
            expect(calling(this.$el.hasClass).on(this.$el).with("")).to.throw(Error);
        });

        it("should return true for an existing class name", function () {
            this.el.classList.add(this.newClass1);

            expect(this.$el.hasClass(this.newClass1)).to.be.true;
        });

        it("should return false for a nonexisting class name", function () {
            expect(this.$el.hasClass(this.newClass1)).to.be.false;
        });

        it("should work on multiple elements", function () {
            var $els = $$("#" + this.el2.id + ", #" + this.el3.id);

            expect(calling($els.hasClass).on($els).with()).to.not.throw(Error);
        });

        it("should return the existence of the class name on the first element", function () {
            var $els = $$("#" + this.el2.id + ", #" + this.el3.id);
            this.el3.classList.add(this.newClass1);

            expect(this.$el.hasClass(this.newClass1)).to.be.false;

            this.el2.classList.add(this.newClass2);

            expect(this.$el.hasClass(this.newClass2)).to.be.false;
        });
    });

    describe("show()", function () {
        it("should remove the hidden class name from the element");
        it("should work on multiple elements");
        it("should return the Jamón instance");
    });

    describe("hide()", function () {
        it("should add the hidden class name to the element");
        it("should work on multiple elements");
        it("should return the Jamón instance");
    });

     describe("toggle()", function () {
        it("should toggle the hidden class name on the element");
        it("should work on multiple elements");
        it("should return the Jamón instance");
    });

    describe("Jamon.hiddenClassName", function () {
        it("should change the class name used by show()");
        it("should change the class name used by hide()");
        it("should change the class name used by toggle()");
    });

});

<|endoftext|>


<commit_before>import {
  waitForConnected
  , connectToEnvironment
} from './kuzzleWrapper'
import store from '../vuex/store'
import { reset } from '../vuex/actions'
import {
  environments
  , currentEnvironmentId
  , currentEnvironment
} from '../vuex/modules/common/kuzzle/getters'
import * as kuzzleActions from '../vuex/modules/common/kuzzle/actions'
import {
  loginByToken
  , checkFirstAdmin
} from '../vuex/modules/auth/actions'

export const LAST_CONNECTED = 'lastConnectedEnv'
const ENVIRONMENTS = 'environments'
export const DEFAULT_COLOR = '#00757F'
export const DEFAULT = 'default'
export const defaultEnvironment = {
  name: 'localhost',
  host: 'localhost',
  ioPort: 7512,
  wsPort: 7513
}

export const persistEnvironments = (environments) => {
  // eslint-disable-next-line no-undef
  localStorage.setItem(ENVIRONMENTS, JSON.stringify(environments))
}
/**
 * Loads the environment definitions stored in localStorage, stores them in
 * the Vuex store, then returns the id of the last connected
 * environment if available, or the first environment id available otherwise.
 *
 * @return {String} the id of the last connected environment.
 */
export const loadEnvironments = () => {
  // eslint-disable-next-line no-undef
  let loadedEnv = JSON.parse(localStorage.getItem(ENVIRONMENTS) || '{}')
  if (Object.keys(loadedEnv).length === 0) {
    loadedEnv = {
      [DEFAULT]: defaultEnvironment
    }
  }

  return loadedEnv
}

/**
 * Creates an environment objects, stores it in the Vuex store and returns it.
 *
 * @param  {String} The name of the environment (displayed in the list).
 * @param  {String} The HEX color code of the main header bar when connected.
 * @param  {String} The hostname.
 * @param  {int} The port number for the Socket.IO protocol.
 * @param  {int} The port number for the Websocket protocol.
 *
 * @return {Object} The environment object.
 */
export const createEnvironment = (name, color, host, ioPort, wsPort) => {
  if (!color) {
    color = DEFAULT_COLOR
  }

  let newEnvironment = {
    name,
    color,
    host,
    ioPort,
    wsPort
  }

  kuzzleActions.addEnvironment(store, name, newEnvironment)
  return newEnvironment
}

export const loadLastConnectedEnvId = () => {
  // eslint-disable-next-line no-undef
  return localStorage.getItem(LAST_CONNECTED)
}

export const deleteEnvironment = (id) => {
  kuzzleActions.deleteEnvironment(store, id)
  persistEnvironments()
}

export const updateEnvironment = (id, name, color, host, ioPort, wsPort) => {
  let envToUpdate = environments(store.state)[id]
  if (!envToUpdate) {
    throw new Error(`The provided id ${id} does not correspond to any existing
      environment`)
  }

  envToUpdate = {
    ...envToUpdate, name, color, host, ioPort, wsPort
  }

  kuzzleActions.updateEnvironment(store, id, envToUpdate)
  return envToUpdate
}

export const setTokenToCurrentEnvironment = (token) => {
  kuzzleActions.updateEnvironment(
    store,
    currentEnvironmentId(store.state),
    {
      ...currentEnvironment(store.state),
      token: token
    }
  )

  return currentEnvironment(store.state)
}

export const switchEnvironment = (id) => {
  if (!id) {
    throw new Error(`cannot switch to ${id} environment`)
  }

  let environment = environments(store.state)[id]
  if (!environment) {
    throw new Error(`Id ${id} does not match any environment`)
  }

  reset(store)

  connectToEnvironment(environment)
  return waitForConnected(10000)
    .then(() => {
      kuzzleActions.setConnection(store, id)

      return loginByToken(store, environment.token)
        .then(user => {
          if (!user.id) {
            console.log(`Checking for first admin on ${environment.name} environment`)
            return checkFirstAdmin(store)
          }
          return Promise.resolve()
        })
    })
}
<commit_msg>remove console.log ops<commit_after>import {
  waitForConnected
  , connectToEnvironment
} from './kuzzleWrapper'
import store from '../vuex/store'
import { reset } from '../vuex/actions'
import {
  environments
  , currentEnvironmentId
  , currentEnvironment
} from '../vuex/modules/common/kuzzle/getters'
import * as kuzzleActions from '../vuex/modules/common/kuzzle/actions'
import {
  loginByToken
  , checkFirstAdmin
} from '../vuex/modules/auth/actions'

export const LAST_CONNECTED = 'lastConnectedEnv'
const ENVIRONMENTS = 'environments'
export const DEFAULT_COLOR = '#00757F'
export const DEFAULT = 'default'
export const defaultEnvironment = {
  name: 'localhost',
  host: 'localhost',
  ioPort: 7512,
  wsPort: 7513
}

export const persistEnvironments = (environments) => {
  // eslint-disable-next-line no-undef
  localStorage.setItem(ENVIRONMENTS, JSON.stringify(environments))
}
/**
 * Loads the environment definitions stored in localStorage, stores them in
 * the Vuex store, then returns the id of the last connected
 * environment if available, or the first environment id available otherwise.
 *
 * @return {String} the id of the last connected environment.
 */
export const loadEnvironments = () => {
  // eslint-disable-next-line no-undef
  let loadedEnv = JSON.parse(localStorage.getItem(ENVIRONMENTS) || '{}')
  if (Object.keys(loadedEnv).length === 0) {
    loadedEnv = {
      [DEFAULT]: defaultEnvironment
    }
  }

  return loadedEnv
}

/**
 * Creates an environment objects, stores it in the Vuex store and returns it.
 *
 * @param  {String} The name of the environment (displayed in the list).
 * @param  {String} The HEX color code of the main header bar when connected.
 * @param  {String} The hostname.
 * @param  {int} The port number for the Socket.IO protocol.
 * @param  {int} The port number for the Websocket protocol.
 *
 * @return {Object} The environment object.
 */
export const createEnvironment = (name, color, host, ioPort, wsPort) => {
  if (!color) {
    color = DEFAULT_COLOR
  }

  let newEnvironment = {
    name,
    color,
    host,
    ioPort,
    wsPort
  }

  kuzzleActions.addEnvironment(store, name, newEnvironment)
  return newEnvironment
}

export const loadLastConnectedEnvId = () => {
  // eslint-disable-next-line no-undef
  return localStorage.getItem(LAST_CONNECTED)
}

export const deleteEnvironment = (id) => {
  kuzzleActions.deleteEnvironment(store, id)
  persistEnvironments()
}

export const updateEnvironment = (id, name, color, host, ioPort, wsPort) => {
  let envToUpdate = environments(store.state)[id]
  if (!envToUpdate) {
    throw new Error(`The provided id ${id} does not correspond to any existing
      environment`)
  }

  envToUpdate = {
    ...envToUpdate, name, color, host, ioPort, wsPort
  }

  kuzzleActions.updateEnvironment(store, id, envToUpdate)
  return envToUpdate
}

export const setTokenToCurrentEnvironment = (token) => {
  kuzzleActions.updateEnvironment(
    store,
    currentEnvironmentId(store.state),
    {
      ...currentEnvironment(store.state),
      token: token
    }
  )

  return currentEnvironment(store.state)
}

export const switchEnvironment = (id) => {
  if (!id) {
    throw new Error(`cannot switch to ${id} environment`)
  }

  let environment = environments(store.state)[id]
  if (!environment) {
    throw new Error(`Id ${id} does not match any environment`)
  }

  reset(store)

  connectToEnvironment(environment)
  return waitForConnected(10000)
    .then(() => {
      kuzzleActions.setConnection(store, id)

      return loginByToken(store, environment.token)
        .then(user => {
          if (!user.id) {
            return checkFirstAdmin(store)
          }
          return Promise.resolve()
        })
    })
}
<|endoftext|>


<commit_before>var _ = require('lodash');
var cheerio = require('cheerio');
var moment = require('moment');
var debug = require('debug')('parser:imageAltTag');
var parse = require('./lib/parse');

/*
 * Extract alt text from img tags
 */

var PARSER_COMPLETED_SUCCESSFULLY = false;

function implementation(snippet) {

    debug("→ %j", _.omit(snippet, ['html']));

    var $ = cheerio.load(snippet.html);

    var altTagFounds = $('img[alt]');
    altTagFounds = _.map(altTagFounds, function (e) {
      return e.attribs.alt;
    });
    altTagFounds = _.flatten(altTagFounds);
    altTagFounds = _.uniq(altTagFounds);

    PARSER_COMPLETED_SUCCESSFULLY = true;
    return {
        imageAltTag: PARSER_COMPLETED_SUCCESSFULLY,
        altTexts: altTagFounds
    }
};

return parse.please({
    'name': 'imageAltTag',
    'requirements': { hrefType: 'photo' },
    'implementation': implementation,
    'since': "2017-02-23",
    'until': moment().toISOString(),
});
<commit_msg>update imageAltTag since<commit_after>var _ = require('lodash');
var cheerio = require('cheerio');
var moment = require('moment');
var debug = require('debug')('parser:imageAltTag');
var parse = require('./lib/parse');

/*
 * Extract alt text from img tags
 */

var PARSER_COMPLETED_SUCCESSFULLY = false;

function implementation(snippet) {

    debug("→ %j", _.omit(snippet, ['html']));

    var $ = cheerio.load(snippet.html);

    var altTagFounds = $('img[alt]');
    altTagFounds = _.map(altTagFounds, function (e) {
      return e.attribs.alt;
    });
    altTagFounds = _.flatten(altTagFounds);
    altTagFounds = _.uniq(altTagFounds);

    PARSER_COMPLETED_SUCCESSFULLY = true;
    return {
        imageAltTag: PARSER_COMPLETED_SUCCESSFULLY,
        altTexts: altTagFounds
    }
};

return parse.please({
    'name': 'imageAltTag',
    'requirements': { hrefType: 'photo' },
    'implementation': implementation,
    'since': "2017-03-15",
    'until': moment().toISOString(),
});
<|endoftext|>


<commit_before>const chai = require("chai"),
	mocha = require("mocha"),
	expect = chai.expect,
	assert = chai.assert,
	superagent = require("superagent");

describe("Your Book Library App", function(){

	beforeeach(function(){

		let port = port || 3000;
		let app = app || {};

	});

	describe('Book Model', function() {
		xit("should create a new Book instance", function(){
			let book = new app.BookModel({});
			expect(book).to.be.an.instance.of(app.BookModel);
		});
	});

	describe('Book View', function() {
		xit("should create a new Book View instance", function(){
			let bookView = new app.BookView({});
			expect(bookView).to.be.an.instance.of(app.BookView);
		});
	});

	describe('Book Collection', function() {
		xit("should create a new Book Collection instance", function(){
			let bookCollection = new app.BookCollection({});
			expect(bookCollection).to.be.an.instance.of(app.BookCollection);
		});
	});

	describe('Book Collection View', function() {
		xit("should create a new Book Collection View instance", function(){
			let bookCollectionView = new app.BookCollectionView({});
			expect(bookCollectionView).to.be.an.instance.of(app.BookCollectionView);
		});
	});

	describe('Routes', function() {

		xit("/", function(done){
			xit("GET", function(){
				xit("should be successful", function(done){
					superagent
					.get('http://localhost: ' + port)
					.end(function(res){
						expect(res.status).to.equal(200);
						done();
					});
				});
				xit("should redirect to '/api/books'", function(done){
					superagent
					.get('http://localhost: ' + port)
					.end(function(res){
						expect(res.redirect).to.equal('/api/books');
						done();
					});
				});
			});

		});

		xit("'/api/books' Route", function(done){
			xit("GET", function(){
				xit("should be successful", function(){
					superagent
						.get('http://localhost: ' + port + '/api/books')
						.end(function(res){
							expect(res.status).to.equal(200);
							done();
						});
				});
				xit("respond with JSON of all books", function(){
					superagent
						.get('http://localhost: ' + port + '/api/books')
						.end(function(res){
							expect(res.data).to.be.typeof("json");
							done();
						});
				});
			});

		});

		xit("'/api/books/:id' Route", function(done){
			xit("GET", function(){});
			xit("PUT", function(){});
			xit("DELETE", function(){});
			done();
		});

	});

});<commit_msg>removed ES2015 syntax<commit_after>const chai = require("chai"),
	mocha = require("mocha"),
	expect = chai.expect,
	assert = chai.assert,
	superagent = require("superagent");

describe("Your Book Library App", function(){

	beforeeach(function(){

		var port = port || 3000;
		var app = app || {};

	});

	describe('Book Model', function() {
		xit("should create a new Book instance", function(){
			var book = new app.BookModel({});
			expect(book).to.be.an.instance.of(app.BookModel);
		});
	});

	describe('Book View', function() {
		xit("should create a new Book View instance", function(){
			var bookView = new app.BookView({});
			expect(bookView).to.be.an.instance.of(app.BookView);
		});
	});

	describe('Book Collection', function() {
		xit("should create a new Book Collection instance", function(){
			var bookCollection = new app.BookCollection({});
			expect(bookCollection).to.be.an.instance.of(app.BookCollection);
		});
	});

	describe('Book Collection View', function() {
		xit("should create a new Book Collection View instance", function(){
			var bookCollectionView = new app.BookCollectionView({});
			expect(bookCollectionView).to.be.an.instance.of(app.BookCollectionView);
		});
	});

	describe('Routes', function() {

		xit("/", function(done){
			xit("GET", function(){
				xit("should be successful", function(done){
					superagent
					.get('http://localhost: ' + port)
					.end(function(res){
						expect(res.status).to.equal(200);
						done();
					});
				});
				xit("should redirect to '/api/books'", function(done){
					superagent
					.get('http://localhost: ' + port)
					.end(function(res){
						expect(res.redirect).to.equal('/api/books');
						done();
					});
				});
			});

		});

		xit("/api/books", function(done){
			xit("GET", function(){
				xit("should be successful", function(){
					superagent
						.get('http://localhost: ' + port + '/api/books')
						.end(function(res){
							expect(res.status).to.equal(200);
							done();
						});
				});
				xit("respond with JSON of all books", function(){
					superagent
						.get('http://localhost: ' + port + '/api/books')
						.end(function(res){
							expect(res.data).to.be.typeof("json");
							done();
						});
				});
			});

		});

		xit("/api/books/:id", function(done){
			xit("GET", function(){});
			xit("PUT", function(){});
			xit("DELETE", function(){});
			done();
		});

	});

});<|endoftext|>


<commit_before>describe("client", function(){
  it("works with BDW", function(){
    expect(BDW).not.toBeUndefined();
  });
  it("works with jquery", function(){
    expect($).not.toBeUndefined();
  });
  describe("init", function(){
    beforeEach(function(){
       spyOn(BDW, 'events');
       spyOn(BDW, 'getBalance');
       spyOn(BDW, 'highchartStart');
    });
    BDW.init();
    it("sets the api key", function(){
       expect(BDW.api_key).toBe("add yours here");
    });
    it("sets the base uril", function(){
       expect(BDW.coinbase_uri).toBe('https://coinbase.com/api/v1');
    });
    it("calls events", function(){
       expect(BDW.events).toHaveBeenCalled();
    });
    it("calls geBalance", function(){
       expect(BDW.getBalance).toHaveBeenCalled();
    });
    it("calls highchartStart", function(){
       expect(BDW.highchartStart).toHaveBeenCalled();
    });
  });
});<commit_msg>all tests now pass<commit_after>describe("client", function(){
  it("works with BDW", function(){
    expect(BDW).not.toBeUndefined();
  });
  it("works with jquery", function(){
    expect($).not.toBeUndefined();
  });
  describe("init", function(){
    beforeEach(function(){
       spyOn(BDW, 'events');
       spyOn(BDW, 'getBalance');
       spyOn(BDW, 'highchartStart');
    });
    it("sets the api key", function(){
       BDW.init();
       expect(BDW.api_key).toBe("add yours here");
    });
    it("sets the base uril", function(){
       BDW.init();
       expect(BDW.coinbase_uri).toBe('https://coinbase.com/api/v1');
    });
    it("calls events", function(){
       BDW.init();
       expect(BDW.events).toHaveBeenCalled();
    });
    it("calls geBalance", function(){
       BDW.init();
       expect(BDW.getBalance).toHaveBeenCalled();
    });
    it("calls highchartStart", function(){
       BDW.init();
       expect(BDW.highchartStart).toHaveBeenCalled();
    });
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router'
import { FluxMixins, RouterMixins } from '../mixins';
import { Strings } from '../constants';

let noavatarImage = require('../../images/containers/login/noavatar.png');

export default React.createClass({
  mixins: [ FluxMixins, RouterMixins ],

  handleCancel(){
    this.transitionTo("/");
  },

  componentDidMount(){

  },

  render() {
    let style ={
      height: '100%',
      width: '100%'
    };

    let styleLogin = {
      maxWidth:'400px',
      marginRight: 'auto',
      marginLeft: 'auto',
      marginTop: '50px',
      marginBottom: '50px'
    };

    let headerStyle = {
      fontSize: '20px'
    };

    return (

            {Strings.App.Name}

              <form className="login-form">

{Strings.Login.FormTitle}

                    <input className="validate" id="email" type="email" />
                    Email

                    <input id="password" type="password" />
                    Senha

                      <input type="checkbox" id="remember-me" />
                      Mantenha-me conectado

                    <Link to='/home' className="btn-large waves-effect waves-light blue col s12">{Strings.Login.LoginAction}</Link>

{Strings.Login.SignUpText}

{Strings.Login.PasswordRecovery}

              </form>

    );
  }

});
<commit_msg>Deploy to Heroku<commit_after>import React from 'react';
import { Link } from 'react-router'
import { FluxMixins, RouterMixins } from '../mixins';
import { Strings } from '../constants';

let noavatarImage = require('../../images/containers/login/noavatar.png');

export default React.createClass({
  mixins: [ FluxMixins, RouterMixins ],

  handleCancel(){
    this.transitionTo("/");
  },

  componentDidMount(){

  },

  render() {
    let style ={
      height: '100%',
      width: '100%'
    };

    let styleLogin = {
      maxWidth:'400px',
      marginRight: 'auto',
      marginLeft: 'auto',
      marginTop: '20px',
      marginBottom: '50px'
    };

    let avatarStyle = {
      width: '120px',
      height: '120px',
      marginTop: '25px'
    };

    let headerStyle = {
      fontSize: '20px'
    };

    return (

            {Strings.App.Name}

              <form className="login-form">

{Strings.Login.FormTitle}

                    <input className="validate" id="email" type="email" />
                    Email

                    <input id="password" type="password" />
                    Senha

                      <input type="checkbox" id="remember-me" />
                      Mantenha-me conectado

                    <Link to='/home' className="btn-large waves-effect waves-light blue col s12">{Strings.Login.LoginAction}</Link>

{Strings.Login.SignUpText}

{Strings.Login.PasswordRecovery}

              </form>

    );
  }

});
<|endoftext|>


<commit_before>/* global x, equal, ok */
/* jshint multistr: true */
(function() {
    "use strict";
    var testVariable;

    x.Component.extend({
        id: "aaa",
        init: function () {
            testVariable = 123;
        }
    });

    x.Component.extend({
        id: "yyy",
        init: function () {
            testVariable = this.data("value") || 222;
        }
    });

    test('Components: custom call of init', function() {
        x.Component.initById("aaa");
        equal(
            testVariable,
            123,
            "The result must be 123"
        );
    });

    if (typeof document !== "undefined") {
        test('Components: initByHTML', function() {
            x.Component.initByHTML();
            equal(
                testVariable,
                "olollo",
                "The result must be 123"
            );
        });
    }

})();<commit_msg>problem with phantomjs<commit_after>/* global x, equal, ok */
/* jshint multistr: true */
(function() {
    "use strict";
    var testVariable;

    x.Component.extend({
        id: "aaa",
        init: function () {
            testVariable = 123;
        }
    });

    x.Component.extend({
        id: "yyy",
        init: function () {
            testVariable = this.data("value") || 222;
        }
    });

    test('Components: custom call of init', function() {
        x.Component.initById("aaa");
        equal(
            testVariable,
            123,
            "The result must be 123"
        );
    });

    /*
    if (typeof document !== "undefined") {
        test('Components: initByHTML', function() {
            x.Component.initByHTML();
            equal(
                testVariable,
                "olollo",
                "The result must be 123"
            );
        });
    }
    */

})();
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import {spy, stub} from 'sinon';
import ansiStyles from 'ansi-styles';
import chalk from 'chalk';
import test from 'ava';
import {h, build, Text, Component} from '..';
import renderToString from '../lib/render-to-string';
import {rerender} from '../lib/render-queue';

test('render text', t => {
	class A extends Component {
		render() {
			return 'Hello';
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('receive props', t => {
	class A extends Component {
		render() {
			return this.props.message;
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('receive props in render arguments', t => {
	class A extends Component {
		render(props) {
			return props.message;
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('receive props with default props', t => {
	class Test extends Component {
		render(props) {
			return `${props.a} ${props.b} ${props.c}`;
		}
	}

	Test.defaultProps = {
		a: 'a',
		b: 'b'
	};

	const tree = build(<Test b="z" c="c"/>);
	t.is(renderToString(tree), 'a z c');
	t.is(renderToString(build(<Test c="c"/>, tree)), 'a b c');
});

test('rerender on new props', t => {
	class Hi extends Component {
		render(props) {
			return `Hello, ${props.name}`;
		}
	}

	const initialTree = build(<Hi name="John"/>);
	t.is(renderToString(initialTree), 'Hello, John');

	const finalTree = build(<Hi name="Michael"/>, initialTree);
	t.is(renderToString(finalTree), 'Hello, Michael');
});

test.serial('check prop types', t => {
	stub(console, 'error');

	const Child = () => '';
	const Parent = () => '';

	Parent.defaultProps = {
		message: 'Test'
	};

	Parent.propTypes = {
		message: PropTypes.string,
		children: PropTypes.node
	};

	build((
		<Parent>
			<Child/>
		</Parent>
	));

	t.false(console.error.called);

	build(<Parent message={123}/>);

	t.true(console.error.calledOnce);
	t.is(console.error.firstCall.args[0], 'Warning: Failed prop type: Invalid prop `message` of type `number` supplied to `Parent`, expected `string`.');

	console.error.restore();
});

test('render nested component', t => {
	class B extends Component {
		render() {
			return 'Hello';
		}
	}

	class A extends Component {
		render() {
			return ;
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('rerender nested components', t => {
	class C extends Component {
		render() {
			return 'C';
		}
	}

	class B extends Component {
		render() {
			return 'B';
		}
	}

	class A extends Component {
		render(props) {
			const X = props.component === 'B' ? B : C;
			return <X/>;
		}
	}

	const initialTree = build();
	t.is(renderToString(initialTree), 'B');

	const finalTree = build(, initialTree);
	t.is(renderToString(finalTree), 'C');
});

test('render children', t => {
	class World extends Component {
		render() {
			return ' World';
		}
	}

	class Hello extends Component {
		render() {
			return 'Hello';
		}
	}

	class HelloWorld extends Component {
		render(props) {
			return (

					{props.children}

			);
		}
	}

	const tree = build((
		<HelloWorld>
			<Hello/>
			<World/>
		</HelloWorld>
	));

	t.is(renderToString(tree), 'Hello World');
});

test('update children', t => {
	class A extends Component {
		render() {
			return 'A';
		}
	}

	class B extends Component {
		render() {
			return 'B';
		}
	}

	class C extends Component {
		render() {
			return 'C';
		}
	}

	const firstTree = build((

	));

	t.is(renderToString(firstTree), 'AB');

	const secondTree = build((

			<C/>

	), firstTree);

	t.is(renderToString(secondTree), 'ABC');

	const thirdTree = build((

	), secondTree);

	t.is(renderToString(thirdTree), 'A');
});

test('render component with missing children', t => {
	class A extends Component {
		render(props) {
			return props.children;
		}
	}

	t.is(renderToString(build()), '');
});

test('render optional children', t => {
	class A extends Component {
		render() {
			return 'A';
		}
	}

	class B extends Component {
		render() {
			return 'B';
		}
	}

	class Root extends Component {
		render(props) {
			return (

					{props.a && }
					{props.b && }

			);
		}
	}

	const firstTree = build(<Root a b/>);
	t.is(renderToString(firstTree), 'AB');

	const secondTree = build(<Root a/>, firstTree);
	t.is(renderToString(secondTree), 'A');

	const thirdTree = build(<Root/>, secondTree);
	t.is(renderToString(thirdTree), '');
});

test('render different root components', t => {
	class A extends Component {
		render() {
			return 'A';
		}
	}

	class B extends Component {
		render() {
			return 'B';
		}
	}

	// Component -> Component
	t.is(renderToString(build(, build())), 'A');

	// String -> Component
	t.is(renderToString(build(, build('text'))), 'A');

	// Number -> Component
	t.is(renderToString(build(, build(10))), 'A');

	// Boolean -> Component
	t.is(renderToString(build(, build(false))), 'A');

	// Component -> String
	t.is(renderToString(build('text', build())), 'text');

	// Component -> Number
	t.is(renderToString(build(10, build())), '10');

	// Component -> Boolean
	t.is(renderToString(build(false, build())), '');

	// String -> Number
	t.is(renderToString(build(10, build('text'))), '10');

	// String -> Boolean
	t.is(renderToString(build(false, build('text'))), '');

	// Number -> String
	t.is(renderToString(build('text', build(10))), 'text');

	// Number -> Boolean
	t.is(renderToString(build(false, build('text'))), '');
});

test('render with initial state', t => {
	class A extends Component {
		constructor() {
			super();

			this.state = {
				message: 'Hello'
			};
		}

		render() {
			return this.state.message;
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('receive state in render arguments', t => {
	class A extends Component {
		constructor(props) {
			super(props);

			this.state = {
				message: 'Hello'
			};
		}

		render(props, state) {
			return `${state.message} to ${props.name}`;
		}
	}

	t.is(renderToString(build()), 'Hello to Joe');
});

test('rerender when state updates', t => {
	let component;

	class A extends Component {
		constructor() {
			super();

			this.state = {
				message: 'Hello'
			};

			component = this;
		}

		render(props, state) {
			return state.message;
		}
	}

	const onUpdate = spy();
	const firstTree = build(, null, onUpdate);
	t.is(renderToString(firstTree), 'Hello');

	component.setState({message: 'Goodbye'});
	rerender();
	t.true(onUpdate.calledOnce);

	const secondTree = build(, firstTree);
	t.is(renderToString(secondTree), 'Goodbye');
});

test('store next state and set it only on rerender', t => {
	let component;

	class A extends Component {
		constructor(props) {
			super(props);

			this.state = {
				message: 'Hello'
			};

			component = this;
		}

		render(props, state) {
			return state.message;
		}
	}

	const firstTree = build(, null);
	t.is(renderToString(firstTree), 'Hello');

	component.setState({message: 'Goodbye'});
	t.is(renderToString(firstTree), 'Hello');

	const secondTree = build(, firstTree);
	t.is(renderToString(secondTree), 'Goodbye');
});

test('merge pending states', t => {
	let component;

	class A extends Component {
		constructor() {
			super();

			this.state = {
				first: 'Hello',
				second: 'Joe'
			};

			component = this;
		}

		render(props, state) {
			return `${state.first} ${state.second}`;
		}
	}

	const firstTree = build(, null);
	t.is(renderToString(firstTree), 'Hello Joe');

	const firstCallback = spy();
	const secondCallback = spy();

	component.setState({first: 'Bye'}, firstCallback);
	component.setState({second: 'Ross'}, secondCallback);

	const secondTree = build(, firstTree);
	t.is(renderToString(secondTree), 'Bye Ross');

	t.true(firstCallback.calledOnce);
	t.true(secondCallback.calledOnce);
	t.true(firstCallback.calledBefore(secondCallback));
});

test('state callbacks', t => {
	let component;

	class A extends Component {
		constructor(props) {
			super(props);

			this.state = {
				message: 'Hello'
			};

			component = this;
		}

		render(props, state) {
			return state.message;
		}
	}

	spy(A.prototype, 'componentDidUpdate');

	const firstTree = build();
	t.is(renderToString(firstTree), 'Hello');

	const callback = spy(() => {
		component.setState({
			message: 'Ciao'
		});
	});

	component.setState({
		message: 'Bonjour'
	}, callback);

	const secondTree = build(, firstTree);
	t.is(renderToString(secondTree), 'Bonjour');
	t.true(callback.calledOnce);
	t.true(callback.calledAfter(A.prototype.componentDidUpdate));

	const thirdTree = build(, secondTree);
	t.is(renderToString(thirdTree), 'Ciao');
	t.true(callback.calledOnce);
});

test('force render', t => {
	let component;
	let renders = 0;

	class A extends Component {
		constructor() {
			super();

			component = this;
		}

		render() {
			renders++;

			return 'A';
		}
	}

	let tree; // eslint-disable-line prefer-const
	const onUpdate = spy(() => {
		build(, tree, onUpdate);
	});

	tree = build(, null, onUpdate);
	t.is(renders, 1);

	component.forceUpdate();
	t.is(renders, 1);

	rerender();
	t.true(onUpdate.calledOnce);
	t.is(renders, 2);
});

test('dont render falsey values', t => {
	class A extends Component {
		render() {
			return (

					{null},{undefined},{false},{0},{NaN}

			);
		}
	}

	t.is(renderToString(build()), ',,,0,NaN');
});

test('dont render null', t => {
	t.is(renderToString(build(null)), '');
});

test('dont render undefined', t => {
	t.is(renderToString(build(undefined)), '');
});

test('dont render boolean', t => {
	t.is(renderToString(build(false)), '');
	t.is(renderToString(build(true)), '');
});

test('render NaN as text', t => {
	t.is(renderToString(build(NaN)), 'NaN');
});

test('render numbers as text', t => {
	t.is(renderToString(build(0)), '0');
	t.is(renderToString(build(1)), '1');
});

test('render string', t => {
	t.is(renderToString(build('A')), 'A');
});

test('render functional component', t => {
	const A = () => 'A';

	t.is(renderToString(build()), 'A');
});

test('render nested functional components', t => {
	const A = () => 'A';
	const B = () => ;
	const C = () => ;

	t.is(renderToString(build(<C/>)), 'A');
});

test('receive props in functional component', t => {
	const Hi = ({name}) => {
		return `Hi, ${name}`;
	};

	t.is(renderToString(build(<Hi name="John"/>)), 'Hi, John');
});

test('render br', t => {
	t.is(renderToString(build(
)), '\n');
});

test('render span', t => {
	t.is(renderToString(build(Test)), 'Test');
});

test('render div', t => {
	t.is(renderToString(build(
Test
)), 'Test\n');
});

test('render styled text', t => {
	const styles = Object.keys(ansiStyles);

	for (const style of styles) {
		const props = {
			[style]: true
		};

		t.is(renderToString(build(<Text {...props}>Test</Text>)), chalk[style]('Test'));
	}

	t.is(renderToString(build(<Text rgb={[40, 42, 54]}>Test</Text>)), chalk.rgb(40, 42, 54)('Test'));
});
<commit_msg>test <Indent> component<commit_after>import PropTypes from 'prop-types';
import {spy, stub} from 'sinon';
import ansiStyles from 'ansi-styles';
import chalk from 'chalk';
import test from 'ava';
import {h, build, Indent, Text, Component} from '..';
import renderToString from '../lib/render-to-string';
import {rerender} from '../lib/render-queue';

test('render text', t => {
	class A extends Component {
		render() {
			return 'Hello';
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('receive props', t => {
	class A extends Component {
		render() {
			return this.props.message;
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('receive props in render arguments', t => {
	class A extends Component {
		render(props) {
			return props.message;
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('receive props with default props', t => {
	class Test extends Component {
		render(props) {
			return `${props.a} ${props.b} ${props.c}`;
		}
	}

	Test.defaultProps = {
		a: 'a',
		b: 'b'
	};

	const tree = build(<Test b="z" c="c"/>);
	t.is(renderToString(tree), 'a z c');
	t.is(renderToString(build(<Test c="c"/>, tree)), 'a b c');
});

test('rerender on new props', t => {
	class Hi extends Component {
		render(props) {
			return `Hello, ${props.name}`;
		}
	}

	const initialTree = build(<Hi name="John"/>);
	t.is(renderToString(initialTree), 'Hello, John');

	const finalTree = build(<Hi name="Michael"/>, initialTree);
	t.is(renderToString(finalTree), 'Hello, Michael');
});

test.serial('check prop types', t => {
	stub(console, 'error');

	const Child = () => '';
	const Parent = () => '';

	Parent.defaultProps = {
		message: 'Test'
	};

	Parent.propTypes = {
		message: PropTypes.string,
		children: PropTypes.node
	};

	build((
		<Parent>
			<Child/>
		</Parent>
	));

	t.false(console.error.called);

	build(<Parent message={123}/>);

	t.true(console.error.calledOnce);
	t.is(console.error.firstCall.args[0], 'Warning: Failed prop type: Invalid prop `message` of type `number` supplied to `Parent`, expected `string`.');

	console.error.restore();
});

test('render nested component', t => {
	class B extends Component {
		render() {
			return 'Hello';
		}
	}

	class A extends Component {
		render() {
			return ;
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('rerender nested components', t => {
	class C extends Component {
		render() {
			return 'C';
		}
	}

	class B extends Component {
		render() {
			return 'B';
		}
	}

	class A extends Component {
		render(props) {
			const X = props.component === 'B' ? B : C;
			return <X/>;
		}
	}

	const initialTree = build();
	t.is(renderToString(initialTree), 'B');

	const finalTree = build(, initialTree);
	t.is(renderToString(finalTree), 'C');
});

test('render children', t => {
	class World extends Component {
		render() {
			return ' World';
		}
	}

	class Hello extends Component {
		render() {
			return 'Hello';
		}
	}

	class HelloWorld extends Component {
		render(props) {
			return (

					{props.children}

			);
		}
	}

	const tree = build((
		<HelloWorld>
			<Hello/>
			<World/>
		</HelloWorld>
	));

	t.is(renderToString(tree), 'Hello World');
});

test('update children', t => {
	class A extends Component {
		render() {
			return 'A';
		}
	}

	class B extends Component {
		render() {
			return 'B';
		}
	}

	class C extends Component {
		render() {
			return 'C';
		}
	}

	const firstTree = build((

	));

	t.is(renderToString(firstTree), 'AB');

	const secondTree = build((

			<C/>

	), firstTree);

	t.is(renderToString(secondTree), 'ABC');

	const thirdTree = build((

	), secondTree);

	t.is(renderToString(thirdTree), 'A');
});

test('render component with missing children', t => {
	class A extends Component {
		render(props) {
			return props.children;
		}
	}

	t.is(renderToString(build()), '');
});

test('render optional children', t => {
	class A extends Component {
		render() {
			return 'A';
		}
	}

	class B extends Component {
		render() {
			return 'B';
		}
	}

	class Root extends Component {
		render(props) {
			return (

					{props.a && }
					{props.b && }

			);
		}
	}

	const firstTree = build(<Root a b/>);
	t.is(renderToString(firstTree), 'AB');

	const secondTree = build(<Root a/>, firstTree);
	t.is(renderToString(secondTree), 'A');

	const thirdTree = build(<Root/>, secondTree);
	t.is(renderToString(thirdTree), '');
});

test('render different root components', t => {
	class A extends Component {
		render() {
			return 'A';
		}
	}

	class B extends Component {
		render() {
			return 'B';
		}
	}

	// Component -> Component
	t.is(renderToString(build(, build())), 'A');

	// String -> Component
	t.is(renderToString(build(, build('text'))), 'A');

	// Number -> Component
	t.is(renderToString(build(, build(10))), 'A');

	// Boolean -> Component
	t.is(renderToString(build(, build(false))), 'A');

	// Component -> String
	t.is(renderToString(build('text', build())), 'text');

	// Component -> Number
	t.is(renderToString(build(10, build())), '10');

	// Component -> Boolean
	t.is(renderToString(build(false, build())), '');

	// String -> Number
	t.is(renderToString(build(10, build('text'))), '10');

	// String -> Boolean
	t.is(renderToString(build(false, build('text'))), '');

	// Number -> String
	t.is(renderToString(build('text', build(10))), 'text');

	// Number -> Boolean
	t.is(renderToString(build(false, build('text'))), '');
});

test('render with initial state', t => {
	class A extends Component {
		constructor() {
			super();

			this.state = {
				message: 'Hello'
			};
		}

		render() {
			return this.state.message;
		}
	}

	t.is(renderToString(build()), 'Hello');
});

test('receive state in render arguments', t => {
	class A extends Component {
		constructor(props) {
			super(props);

			this.state = {
				message: 'Hello'
			};
		}

		render(props, state) {
			return `${state.message} to ${props.name}`;
		}
	}

	t.is(renderToString(build()), 'Hello to Joe');
});

test('rerender when state updates', t => {
	let component;

	class A extends Component {
		constructor() {
			super();

			this.state = {
				message: 'Hello'
			};

			component = this;
		}

		render(props, state) {
			return state.message;
		}
	}

	const onUpdate = spy();
	const firstTree = build(, null, onUpdate);
	t.is(renderToString(firstTree), 'Hello');

	component.setState({message: 'Goodbye'});
	rerender();
	t.true(onUpdate.calledOnce);

	const secondTree = build(, firstTree);
	t.is(renderToString(secondTree), 'Goodbye');
});

test('store next state and set it only on rerender', t => {
	let component;

	class A extends Component {
		constructor(props) {
			super(props);

			this.state = {
				message: 'Hello'
			};

			component = this;
		}

		render(props, state) {
			return state.message;
		}
	}

	const firstTree = build(, null);
	t.is(renderToString(firstTree), 'Hello');

	component.setState({message: 'Goodbye'});
	t.is(renderToString(firstTree), 'Hello');

	const secondTree = build(, firstTree);
	t.is(renderToString(secondTree), 'Goodbye');
});

test('merge pending states', t => {
	let component;

	class A extends Component {
		constructor() {
			super();

			this.state = {
				first: 'Hello',
				second: 'Joe'
			};

			component = this;
		}

		render(props, state) {
			return `${state.first} ${state.second}`;
		}
	}

	const firstTree = build(, null);
	t.is(renderToString(firstTree), 'Hello Joe');

	const firstCallback = spy();
	const secondCallback = spy();

	component.setState({first: 'Bye'}, firstCallback);
	component.setState({second: 'Ross'}, secondCallback);

	const secondTree = build(, firstTree);
	t.is(renderToString(secondTree), 'Bye Ross');

	t.true(firstCallback.calledOnce);
	t.true(secondCallback.calledOnce);
	t.true(firstCallback.calledBefore(secondCallback));
});

test('state callbacks', t => {
	let component;

	class A extends Component {
		constructor(props) {
			super(props);

			this.state = {
				message: 'Hello'
			};

			component = this;
		}

		render(props, state) {
			return state.message;
		}
	}

	spy(A.prototype, 'componentDidUpdate');

	const firstTree = build();
	t.is(renderToString(firstTree), 'Hello');

	const callback = spy(() => {
		component.setState({
			message: 'Ciao'
		});
	});

	component.setState({
		message: 'Bonjour'
	}, callback);

	const secondTree = build(, firstTree);
	t.is(renderToString(secondTree), 'Bonjour');
	t.true(callback.calledOnce);
	t.true(callback.calledAfter(A.prototype.componentDidUpdate));

	const thirdTree = build(, secondTree);
	t.is(renderToString(thirdTree), 'Ciao');
	t.true(callback.calledOnce);
});

test('force render', t => {
	let component;
	let renders = 0;

	class A extends Component {
		constructor() {
			super();

			component = this;
		}

		render() {
			renders++;

			return 'A';
		}
	}

	let tree; // eslint-disable-line prefer-const
	const onUpdate = spy(() => {
		build(, tree, onUpdate);
	});

	tree = build(, null, onUpdate);
	t.is(renders, 1);

	component.forceUpdate();
	t.is(renders, 1);

	rerender();
	t.true(onUpdate.calledOnce);
	t.is(renders, 2);
});

test('dont render falsey values', t => {
	class A extends Component {
		render() {
			return (

					{null},{undefined},{false},{0},{NaN}

			);
		}
	}

	t.is(renderToString(build()), ',,,0,NaN');
});

test('dont render null', t => {
	t.is(renderToString(build(null)), '');
});

test('dont render undefined', t => {
	t.is(renderToString(build(undefined)), '');
});

test('dont render boolean', t => {
	t.is(renderToString(build(false)), '');
	t.is(renderToString(build(true)), '');
});

test('render NaN as text', t => {
	t.is(renderToString(build(NaN)), 'NaN');
});

test('render numbers as text', t => {
	t.is(renderToString(build(0)), '0');
	t.is(renderToString(build(1)), '1');
});

test('render string', t => {
	t.is(renderToString(build('A')), 'A');
});

test('render functional component', t => {
	const A = () => 'A';

	t.is(renderToString(build()), 'A');
});

test('render nested functional components', t => {
	const A = () => 'A';
	const B = () => ;
	const C = () => ;

	t.is(renderToString(build(<C/>)), 'A');
});

test('receive props in functional component', t => {
	const Hi = ({name}) => {
		return `Hi, ${name}`;
	};

	t.is(renderToString(build(<Hi name="John"/>)), 'Hi, John');
});

test('render br', t => {
	t.is(renderToString(build(
)), '\n');
});

test('render span', t => {
	t.is(renderToString(build(Test)), 'Test');
});

test('render div', t => {
	t.is(renderToString(build(
Test
)), 'Test\n');
});

test('render styled text', t => {
	const styles = Object.keys(ansiStyles);

	for (const style of styles) {
		const props = {
			[style]: true
		};

		t.is(renderToString(build(<Text {...props}>Test</Text>)), chalk[style]('Test'));
	}

	t.is(renderToString(build(<Text rgb={[40, 42, 54]}>Test</Text>)), chalk.rgb(40, 42, 54)('Test'));
});

test('indent text', t => {
	t.is(renderToString(build(<Indent size={2}>Test</Indent>)), '  Test');
	t.is(renderToString(build(<Indent size={2} indent="_">Test</Indent>)), '__Test');
});
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    Log = mongoose.model('Log'),
    util = require('util'),
    moment = require('moment');

exports.query = function(req, res) {
    if (req.query.c == null) {
	return res.send(400, 'No c (channel) parameter');
    }

    var channel = '#' + req.query.c;

    var sType = 'YYYY-MM-DD';
    var uType = 'X';

    var sRegex = /\d{4}-\d{2}-\d{2}/;
    var uRegex = /\d+/;

    var ready = {
	from: null,
	to: null
    };

    var query = {
	from: req.query.f || moment().format(sType),
	to: req.query.t || moment().format(sType)
    };

    for (var ft in query) {
	if (sRegex.exec(query[ft])) {
	    console.log('yay');
	    ready[ft] = moment(query[ft], sType);
	} else if (uRegex.exec(query[ft])) {
	    console.log('nay');
	    ready[ft] = moment.unix(query[ft]);
	} else {
	    return res.send(400, util.format('Invalid %s (%s) parameter', ft.charAt(0), ft));
	}
    }

    var from = ready.from;
    var to = ready.to;

    console.log(from);
    console.log(to);

    if (from.isAfter(to)) {
	return res.send(400, util.format('f (from) "%s" is after t (to) "%s"', from.format(sType)), to.format(sType));
    }

    Log.getLogsFrom(channel, from, to, function(logs) {
	res.render('logs/query', {
	    channel: channel,
	    from: from.utc().format(),
	    to: to.utc().format(),
	    logs: logs
	});
    });
};
<commit_msg>remove debug logs<commit_after>var mongoose = require('mongoose'),
    Log = mongoose.model('Log'),
    util = require('util'),
    moment = require('moment');

exports.query = function(req, res) {
    if (req.query.c == null) {
	return res.send(400, 'No c (channel) parameter');
    }

    var channel = '#' + req.query.c;

    var sType = 'YYYY-MM-DD';
    var uType = 'X';

    var sRegex = /\d{4}-\d{2}-\d{2}/;
    var uRegex = /\d+/;

    var ready = {
	from: null,
	to: null
    };

    var query = {
	from: req.query.f || moment().format(sType),
	to: req.query.t || moment().format(sType)
    };

    for (var ft in query) {
	if (sRegex.exec(query[ft])) {
	    ready[ft] = moment(query[ft], sType);
	} else if (uRegex.exec(query[ft])) {
	    ready[ft] = moment.unix(query[ft]);
	} else {
	    return res.send(400, util.format('Invalid %s (%s) parameter', ft.charAt(0), ft));
	}
    }

    var from = ready.from;
    var to = ready.to;

    if (from.isAfter(to)) {
	return res.send(400, util.format('f (from) "%s" is after t (to) "%s"', from.format(sType)), to.format(sType));
    }

    Log.getLogsFrom(channel, from, to, function(logs) {
	res.render('logs/query', {
	    channel: channel,
	    from: from.utc().format(),
	    to: to.utc().format(),
	    logs: logs
	});
    });
};
<|endoftext|>