<commit_before>export default function (marks){
  let rawData = this.raw_data;
  let config = this.config;

  let bar_supergroups = this.svg.selectAll('.bar-supergroup').data(marks, (d,i) => i+'-'+d.per.join('-'));
  bar_supergroups.enter().append('g').attr('class', 'bar-supergroup');
  bar_supergroups.exit().remove();

  let bar_groups = bar_supergroups.selectAll('.bar-group').data(d => d.data, d => d.key);
  let old_bar_groups = bar_groups.exit();

  let nu_bar_groups;
  let bars;

  if(config.x.type === 'ordinal'){
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0);
    old_bar_groups.transition().remove();

    nu_bar_groups = bar_groups.enter().append('g').attr('class', d => 'bar-group '+d.key );
    nu_bar_groups.append('title');

    bars = bar_groups.selectAll("rect").data(d => d.values instanceof Array ? d.values : [d], d => d.key);
    bars.exit()
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0)
      .remove();
    bars.enter().append('rect')
      .attr('class', d => 'wc-data-mark bar '+d.key )
      .style('clip-path', 'url(#'+this.id+')')
      .attr('y', this.y(0))
      .attr('height', 0)
      .append('title');

    bars
      .attr('shape-rendering', 'crispEdges')
      .attr('stroke',  d => this.colorScale(d.values.raw[0][config.color_by]) )
      .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]) );

    bars.each(function(d){
      let mark = d3.select(this.parentNode.parentNode).datum();
      d.tooltip = mark.tooltip;
      d.arrange = mark.split ? mark.arrange : null;
      d.subcats = mark.values && mark.values[mark.split] ? mark.values[mark.split] : d3.set(rawData.map(m => m[mark.split])).values();
      d3.select(this).attr(mark.attributes);
    });

    let xformat = config.marks.map(m => m.summarizeX === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.x.format);
    let yformat = config.marks.map(m => m.summarizeY === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.y.format);
    bars.select('title').text(d => {
      let tt = d.tooltip || '';
      return tt.replace(/\$x/g, xformat(d.values.x))
        .replace(/\$y/g, yformat(d.values.y))
        .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig] );
    });

    bars.transition()
      .attr('x', d => {
        let position;
        if(!d.arrange || d.arrange === 'stacked'){
          return this.x(d.values.x);
        }
        else if(d.arrange === 'nested'){
          position = d.subcats.indexOf(d.key);
          let offset = position ? this.x.rangeBand()/(d.subcats.length*(position)*0.5)/2 : this.x.rangeBand()/2;
          return this.x(d.values.x) + this.x.rangeBand()/2 - offset;
        }
        else{
          position = d.subcats.indexOf(d.key);
          return this.x(d.values.x)+this.x.rangeBand()/d.subcats.length*position;
        }
      })
      .attr('y', d => {
        if(d.arrange !== 'stacked'){
          return this.y(d.values.y);
        }
        else{
          return this.y(d.values.start);
        }
      })
      .attr('width', d => {
        if(d.arrange === 'stacked'){
          return this.x.rangeBand();
        }
        else if(d.arrange === 'nested'){
          let position = d.subcats.indexOf(d.key);
          return position ? this.x.rangeBand()/(d.subcats.length*(position)*0.5) : this.x.rangeBand();
        }
        else{
          return this.x.rangeBand()/d.subcats.length;
        }
      })
      .attr('height', d => this.y(0) - this.y(d.values.y) );

  }
  else if(config.y.type === 'ordinal'){
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('x', this.x(0))
      .attr('width', 0);
    old_bar_groups.transition().remove();

    nu_bar_groups = bar_groups.enter().append('g').attr('class', d => 'bar-group '+d.key );
    nu_bar_groups.append('title');

    bars = bar_groups.selectAll('rect').data(d => d.values instanceof Array ? d.values : [d], d => d.key );
    bars.exit()
      .transition()
      .attr('x', this.x(0))
      .attr('width', 0)
      .remove();
    bars.enter().append('rect')
      .attr('class', d => 'wc-data-mark bar '+d.key )
      .style('clip-path', 'url(#'+this.id+')')
      .attr('x', this.x(0))
      .attr('width', 0)
      .append('title');

    bars
      .attr('stroke',  d => this.colorScale(d.values.raw[0][config.color_by]) )
      .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]) );

    bars.each(function(d){
      let mark = d3.select(this.parentNode.parentNode).datum();
      d.arrange = mark.split && mark.arrange ? mark.arrange : mark.split ? 'grouped' : null;
      d.subcats = mark.values && mark.values[mark.split] ? mark.values[mark.split] : d3.set(rawData.map(m => m[mark.split])).values();
      d.tooltip = mark.tooltip;
    });

    let xformat = config.marks.map(m => m.summarizeX === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.x.format);
    let yformat = config.marks.map(m => m.summarizeY === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.y.format);
    bars.select('title').text(d => {
      let tt = d.tooltip || '';
      return tt.replace(/\$x/g, xformat(d.values.x))
        .replace(/\$y/g, yformat(d.values.y))
        .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig] );
    });

    bars.transition()
      .attr('x', d => {
        if(d.arrange === 'stacked' || !d.arrange){
          return d.values.start !== undefined ? this.x(d.values.start) : this.x(0);
        }
        else{
          return this.x(0);
        }
      })
      .attr('y', d => {
        if(d.arrange === 'nested'){
          let position = d.subcats.indexOf(d.key);
          let offset = position ? this.y.rangeBand()/(d.subcats.length*0.75)/(position) : this.y.rangeBand();
          return this.y(d.values.y) + (this.y.rangeBand() - offset)/2;
        }
        else if(d.arrange === 'grouped'){
          let position = d.subcats.indexOf(d.key);
          return this.y(d.values.y) + this.y.rangeBand()/d.subcats.length * position;
        }
        else{
          return this.y(d.values.y);
        }
      })
      .attr('width', d => this.x(d.values.x) - this.x(0) )
      .attr('height', d => {
        if(config.y.type === 'quantile'){
          return 20;
        }
        else if(d.arrange === 'nested'){
          let position = d.subcats.indexOf(d.key);
          return position ? this.y.rangeBand()/(d.subcats.length*0.75)/(position) : this.y.rangeBand();
        }
        else if(d.arrange === 'grouped'){
          return this.y.rangeBand()/d.subcats.length;
        }
        else{
          return this.y.rangeBand();
        }
      });
  }
  else if(config.x.type === 'linear' && config.x.bin){
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0);
    old_bar_groups.transition().remove();

    nu_bar_groups = bar_groups.enter().append('g').attr('class', d => 'bar-group '+d.key );
    nu_bar_groups.append('title');

    bars = bar_groups.selectAll('rect').data(d => d.values instanceof Array ? d.values : [d], d => d.key );
    bars.exit()
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0)
      .remove();
    bars.enter().append('rect')
      .attr('class', d =>'wc-data-mark bar '+d.key )
      .style('clip-path', 'url(#'+this.id+')')
      .attr('y', this.y(0))
      .attr('height', 0)
      .append('title');

    bars
      .attr('stroke',  d => this.colorScale(d.values.raw[0][config.color_by]) )
      .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]) );

    bars.each(function(d){
      let mark = d3.select(this.parentNode.parentNode).datum();
      d.arrange = mark.split ? mark.arrange : null;
      d.subcats = mark.values && mark.values[mark.split] ? mark.values[mark.split] : d3.set(rawData.map(m => m[mark.split])).values();
      d3.select(this).attr(mark.attributes);
      let parent = d3.select(this.parentNode).datum();
      let rangeSet = parent.key.split(',').map(m => +m);
      d.rangeLow = d3.min(rangeSet);
      d.rangeHigh = d3.max(rangeSet);
      d.tooltip = mark.tooltip;
    });

    let xformat = config.marks.map(m => m.summarizeX === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.x.format);
    let yformat = config.marks.map(m => m.summarizeY === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.y.format);
    bars.select('title').text(d => {
      let tt = d.tooltip || '';
      return tt.replace(/\$x/g, xformat(d.values.x))
        .replace(/\$y/g, yformat(d.values.y))
        .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig] );
    });

    bars.transition()
      .attr('x', d => this.x(d.rangeLow) )
      .attr('y', d => {
        if(d.arrange !== 'stacked'){
          return this.y(d.values.y);
        }
        else{
          return this.y(d.values.start);
        }
      })
      .attr('width', d => this.x(d.rangeHigh) - this.x(d.rangeLow) )
      .attr('height', d => this.y(0) - this.y(d.values.y) );

  }
  else if(config.y.type === 'linear' && config.y.bin){
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('x', this.x(0))
      .attr('width', 0);
    old_bar_groups.transition().remove();

    nu_bar_groups = bar_groups.enter().append('g').attr('class', d => 'bar-group '+d.key );
    nu_bar_groups.append('title');

    bars = bar_groups.selectAll('rect').data(d => d.values instanceof Array ? d.values : [d], d => d.key );
    bars.exit()
      .transition()
      .attr('x', this.x(0))
      .attr('width', 0)
      .remove();
    bars.enter().append('rect')
      .attr('class', d => 'wc-data-mark bar '+d.key )
      .style('clip-path', 'url(#'+this.id+')')
      .attr('x', this.x(0))
      .attr('width', 0)
      .append('title');

    bars
      .attr('stroke',  d => this.colorScale(d.values.raw[0][config.color_by]) )
      .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]) );

    bars.each(function(d){
      let mark = d3.select(this.parentNode.parentNode).datum();
      d.arrange = mark.split ? mark.arrange : null;
      d.subcats = mark.values && mark.values[mark.split] ? mark.values[mark.split] : d3.set(rawData.map(m => m[mark.split] )).values();
      let parent = d3.select(this.parentNode).datum();
      let rangeSet = parent.key.split(',').map(m => +m);
      d.rangeLow = d3.min(rangeSet);
      d.rangeHigh = d3.max(rangeSet);
      d.tooltip = mark.tooltip;
    });

    let xformat = config.marks.map(m => m.summarizeX === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.x.format);
    let yformat = config.marks.map(m => m.summarizeY === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.y.format);
    bars.select('title').text(d => {
      let tt = d.tooltip || '';
      return tt.replace(/\$x/g, xformat(d.values.x))
        .replace(/\$y/g, yformat(d.values.y))
        .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig] );
    });

    bars.transition()
      .attr('x', d => {
        if(d.arrange === 'stacked'){
          return this.x(d.values.start);
        }
        else{
          return this.x(0);
        }
      })
      .attr('y', d => this.y(d.rangeHigh))
      .attr('width', d => this.x(d.values.x) )
      .attr('height', d => this.y(d.rangeLow) - this.y(d.rangeHigh) );
  }
  else{
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0);
    old_bar_groups.transition().remove();
    bar_supergroups.remove();
  }

}
<commit_msg>adding crispEdges to horizontal bars<commit_after>export default function (marks){
  let rawData = this.raw_data;
  let config = this.config;

  let bar_supergroups = this.svg.selectAll('.bar-supergroup').data(marks, (d,i) => i+'-'+d.per.join('-'));
  bar_supergroups.enter().append('g').attr('class', 'bar-supergroup');
  bar_supergroups.exit().remove();

  let bar_groups = bar_supergroups.selectAll('.bar-group').data(d => d.data, d => d.key);
  let old_bar_groups = bar_groups.exit();

  let nu_bar_groups;
  let bars;

  if(config.x.type === 'ordinal'){
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0);
    old_bar_groups.transition().remove();

    nu_bar_groups = bar_groups.enter().append('g').attr('class', d => 'bar-group '+d.key );
    nu_bar_groups.append('title');

    bars = bar_groups.selectAll("rect").data(d => d.values instanceof Array ? d.values : [d], d => d.key);
    bars.exit()
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0)
      .remove();
    bars.enter().append('rect')
      .attr('class', d => 'wc-data-mark bar '+d.key )
      .style('clip-path', 'url(#'+this.id+')')
      .attr('y', this.y(0))
      .attr('height', 0)
      .append('title');

    bars
      .attr('shape-rendering', 'crispEdges')
      .attr('stroke',  d => this.colorScale(d.values.raw[0][config.color_by]) )
      .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]) );

    bars.each(function(d){
      let mark = d3.select(this.parentNode.parentNode).datum();
      d.tooltip = mark.tooltip;
      d.arrange = mark.split ? mark.arrange : null;
      d.subcats = mark.values && mark.values[mark.split] ? mark.values[mark.split] : d3.set(rawData.map(m => m[mark.split])).values();
      d3.select(this).attr(mark.attributes);
    });

    let xformat = config.marks.map(m => m.summarizeX === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.x.format);
    let yformat = config.marks.map(m => m.summarizeY === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.y.format);
    bars.select('title').text(d => {
      let tt = d.tooltip || '';
      return tt.replace(/\$x/g, xformat(d.values.x))
        .replace(/\$y/g, yformat(d.values.y))
        .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig] );
    });

    bars.transition()
      .attr('x', d => {
        let position;
        if(!d.arrange || d.arrange === 'stacked'){
          return this.x(d.values.x);
        }
        else if(d.arrange === 'nested'){
          position = d.subcats.indexOf(d.key);
          let offset = position ? this.x.rangeBand()/(d.subcats.length*(position)*0.5)/2 : this.x.rangeBand()/2;
          return this.x(d.values.x) + this.x.rangeBand()/2 - offset;
        }
        else{
          position = d.subcats.indexOf(d.key);
          return this.x(d.values.x)+this.x.rangeBand()/d.subcats.length*position;
        }
      })
      .attr('y', d => {
        if(d.arrange !== 'stacked'){
          return this.y(d.values.y);
        }
        else{
          return this.y(d.values.start);
        }
      })
      .attr('width', d => {
        if(d.arrange === 'stacked'){
          return this.x.rangeBand();
        }
        else if(d.arrange === 'nested'){
          let position = d.subcats.indexOf(d.key);
          return position ? this.x.rangeBand()/(d.subcats.length*(position)*0.5) : this.x.rangeBand();
        }
        else{
          return this.x.rangeBand()/d.subcats.length;
        }
      })
      .attr('height', d => this.y(0) - this.y(d.values.y) );

  }
  else if(config.y.type === 'ordinal'){
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('x', this.x(0))
      .attr('width', 0);
    old_bar_groups.transition().remove();

    nu_bar_groups = bar_groups.enter().append('g').attr('class', d => 'bar-group '+d.key );
    nu_bar_groups.append('title');

    bars = bar_groups.selectAll('rect').data(d => d.values instanceof Array ? d.values : [d], d => d.key );
    bars.exit()
      .transition()
      .attr('x', this.x(0))
      .attr('width', 0)
      .remove();
    bars.enter().append('rect')
      .attr('class', d => 'wc-data-mark bar '+d.key )
      .style('clip-path', 'url(#'+this.id+')')
      .attr('x', this.x(0))
      .attr('width', 0)
      .append('title');

    bars
      .attr('shape-rendering', 'crispEdges')
      .attr('stroke',  d => this.colorScale(d.values.raw[0][config.color_by]) )
      .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]) );

    bars.each(function(d){
      let mark = d3.select(this.parentNode.parentNode).datum();
      d.arrange = mark.split && mark.arrange ? mark.arrange : mark.split ? 'grouped' : null;
      d.subcats = mark.values && mark.values[mark.split] ? mark.values[mark.split] : d3.set(rawData.map(m => m[mark.split])).values();
      d.tooltip = mark.tooltip;
    });

    let xformat = config.marks.map(m => m.summarizeX === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.x.format);
    let yformat = config.marks.map(m => m.summarizeY === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.y.format);
    bars.select('title').text(d => {
      let tt = d.tooltip || '';
      return tt.replace(/\$x/g, xformat(d.values.x))
        .replace(/\$y/g, yformat(d.values.y))
        .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig] );
    });

    bars.transition()
      .attr('x', d => {
        if(d.arrange === 'stacked' || !d.arrange){
          return d.values.start !== undefined ? this.x(d.values.start) : this.x(0);
        }
        else{
          return this.x(0);
        }
      })
      .attr('y', d => {
        if(d.arrange === 'nested'){
          let position = d.subcats.indexOf(d.key);
          let offset = position ? this.y.rangeBand()/(d.subcats.length*0.75)/(position) : this.y.rangeBand();
          return this.y(d.values.y) + (this.y.rangeBand() - offset)/2;
        }
        else if(d.arrange === 'grouped'){
          let position = d.subcats.indexOf(d.key);
          return this.y(d.values.y) + this.y.rangeBand()/d.subcats.length * position;
        }
        else{
          return this.y(d.values.y);
        }
      })
      .attr('width', d => this.x(d.values.x) - this.x(0) )
      .attr('height', d => {
        if(config.y.type === 'quantile'){
          return 20;
        }
        else if(d.arrange === 'nested'){
          let position = d.subcats.indexOf(d.key);
          return position ? this.y.rangeBand()/(d.subcats.length*0.75)/(position) : this.y.rangeBand();
        }
        else if(d.arrange === 'grouped'){
          return this.y.rangeBand()/d.subcats.length;
        }
        else{
          return this.y.rangeBand();
        }
      });
  }
  else if(config.x.type === 'linear' && config.x.bin){
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0);
    old_bar_groups.transition().remove();

    nu_bar_groups = bar_groups.enter().append('g').attr('class', d => 'bar-group '+d.key );
    nu_bar_groups.append('title');

    bars = bar_groups.selectAll('rect').data(d => d.values instanceof Array ? d.values : [d], d => d.key );
    bars.exit()
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0)
      .remove();
    bars.enter().append('rect')
      .attr('class', d =>'wc-data-mark bar '+d.key )
      .style('clip-path', 'url(#'+this.id+')')
      .attr('y', this.y(0))
      .attr('height', 0)
      .append('title');

    bars
      .attr('stroke',  d => this.colorScale(d.values.raw[0][config.color_by]) )
      .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]) );

    bars.each(function(d){
      let mark = d3.select(this.parentNode.parentNode).datum();
      d.arrange = mark.split ? mark.arrange : null;
      d.subcats = mark.values && mark.values[mark.split] ? mark.values[mark.split] : d3.set(rawData.map(m => m[mark.split])).values();
      d3.select(this).attr(mark.attributes);
      let parent = d3.select(this.parentNode).datum();
      let rangeSet = parent.key.split(',').map(m => +m);
      d.rangeLow = d3.min(rangeSet);
      d.rangeHigh = d3.max(rangeSet);
      d.tooltip = mark.tooltip;
    });

    let xformat = config.marks.map(m => m.summarizeX === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.x.format);
    let yformat = config.marks.map(m => m.summarizeY === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.y.format);
    bars.select('title').text(d => {
      let tt = d.tooltip || '';
      return tt.replace(/\$x/g, xformat(d.values.x))
        .replace(/\$y/g, yformat(d.values.y))
        .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig] );
    });

    bars.transition()
      .attr('x', d => this.x(d.rangeLow) )
      .attr('y', d => {
        if(d.arrange !== 'stacked'){
          return this.y(d.values.y);
        }
        else{
          return this.y(d.values.start);
        }
      })
      .attr('width', d => this.x(d.rangeHigh) - this.x(d.rangeLow) )
      .attr('height', d => this.y(0) - this.y(d.values.y) );

  }
  else if(config.y.type === 'linear' && config.y.bin){
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('x', this.x(0))
      .attr('width', 0);
    old_bar_groups.transition().remove();

    nu_bar_groups = bar_groups.enter().append('g').attr('class', d => 'bar-group '+d.key );
    nu_bar_groups.append('title');

    bars = bar_groups.selectAll('rect').data(d => d.values instanceof Array ? d.values : [d], d => d.key );
    bars.exit()
      .transition()
      .attr('x', this.x(0))
      .attr('width', 0)
      .remove();
    bars.enter().append('rect')
      .attr('class', d => 'wc-data-mark bar '+d.key )
      .style('clip-path', 'url(#'+this.id+')')
      .attr('x', this.x(0))
      .attr('width', 0)
      .append('title');

    bars
      .attr('stroke',  d => this.colorScale(d.values.raw[0][config.color_by]) )
      .attr('fill', d => this.colorScale(d.values.raw[0][config.color_by]) );

    bars.each(function(d){
      let mark = d3.select(this.parentNode.parentNode).datum();
      d.arrange = mark.split ? mark.arrange : null;
      d.subcats = mark.values && mark.values[mark.split] ? mark.values[mark.split] : d3.set(rawData.map(m => m[mark.split] )).values();
      let parent = d3.select(this.parentNode).datum();
      let rangeSet = parent.key.split(',').map(m => +m);
      d.rangeLow = d3.min(rangeSet);
      d.rangeHigh = d3.max(rangeSet);
      d.tooltip = mark.tooltip;
    });

    let xformat = config.marks.map(m => m.summarizeX === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.x.format);
    let yformat = config.marks.map(m => m.summarizeY === 'percent').indexOf(true) > -1 ? d3.format('0%') : d3.format(config.y.format);
    bars.select('title').text(d => {
      let tt = d.tooltip || '';
      return tt.replace(/\$x/g, xformat(d.values.x))
        .replace(/\$y/g, yformat(d.values.y))
        .replace(/\[(.+?)\]/g, (str, orig) => d.values.raw[0][orig] );
    });

    bars.transition()
      .attr('x', d => {
        if(d.arrange === 'stacked'){
          return this.x(d.values.start);
        }
        else{
          return this.x(0);
        }
      })
      .attr('y', d => this.y(d.rangeHigh))
      .attr('width', d => this.x(d.values.x) )
      .attr('height', d => this.y(d.rangeLow) - this.y(d.rangeHigh) );
  }
  else{
    old_bar_groups.selectAll('.bar')
      .transition()
      .attr('y', this.y(0))
      .attr('height', 0);
    old_bar_groups.transition().remove();
    bar_supergroups.remove();
  }

}
<|endoftext|>


<commit_before>
  console.log('sanity check!');
//
// var sentiment = require('sentiment');
//
// var deerok = sentiment('hate hate high');
// var krist = sentiment('love high hate');
// var ryan = sentiment('high high high');
//
//
// let inputString = "hate hate hate";
// let sentInput = sentiment(inputString);
// let len = inputString.split(" ");
// let numOfWords = len.length;
// const adjScore = sentInput.score/numOfWords + 5;

$('#stop-btn').on('click', function (e) {
  e.preventDefault();
  let testString = 'how bad will this string register';
  console.log('testing hit it');
  $.ajax({
    type: 'GET',
    url: `/string/${testString}/`,
    success: function(result) {
      console.log(result.rows[0].youtube_id);
      const youtube_id = result.rows[0].youtube_id;

      console.log('uid',youtube_id);
      $('.carousel-inner').html('');

    },
    error: function(error) {
      console.log(':(');
    }
  });
});

// module.exports = {
//   sentiment
// };
<commit_msg>changed video<commit_after>
  console.log('sanity check!');
//
// var sentiment = require('sentiment');
//
// var deerok = sentiment('hate hate high');
// var krist = sentiment('love high hate');
// var ryan = sentiment('high high high');
//
//
// let inputString = "hate hate hate";
// let sentInput = sentiment(inputString);
// let len = inputString.split(" ");
// let numOfWords = len.length;
// const adjScore = sentInput.score/numOfWords + 5;

$('#stop-btn').on('click', function (e) {
  e.preventDefault();
  let testString = 'how bad will this string register';
  console.log('testing hit it');
  $.ajax({
    type: 'GET',
    url: `/string/${testString}/`,
    success: function(result) {
      console.log(result.rows[0].youtube_id);
      const youtube_id = result.rows[0].youtube_id;

      console.log('uid',youtube_id);
      $('.carousel-inner').html(``);

    },
    error: function(error) {
      console.log(':(');
    }
  });
});

// module.exports = {
//   sentiment
// };
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Form } from 'antd';
import { unflatten, slugify } from 'olymp';
import { Tabs } from 'antd';
import { Panel, SectionH } from 'olymp/ui';
import { queryPage, queryPages, mutatePage } from './gql';
import { Input, SlateTree, PageType, State } from '../collection';
import { Parent } from './edits';

export class PageForm extends Component {
  handleNameChange = (e) => { // set slug if unset
    const { form } = this.props;
    const value = e.target.value;
    form.setFieldsValue({ slug: `/${slugify(value, true)}` });
  }
  render() {
    const { form, item, items } = this.props;

    let tree = unflatten(items.map(({ id, name, parentId }) => ({
      value: id,
      label: name,
      parent: parentId,
      children: [],
    })), { id: 'value', parentId: 'parent' });

    return (

        <Tabs defaultActiveKey="1" size="small">
          <Tabs.TabPane tab="Basis" key="1">
            {/*<Panel minWidth={560} margin="0 30px" padding={16}>*/}
            <Panel paddingX={16} alignLabel="left">
              <Input form={form} item={item} field="name" label="Name" onChange={this.handleNameChange} rules={['required']} type="text" size="large" />
              <Input form={form} item={item} field="slug" label="Slug" type="text" size="large" />
              <State form={form} item={item} field="state" label="Status" rules={['required']} />
              <Parent form={form} treeData={tree} item={item} field="parentId" label="Menü" placeholder="Übergeordnetes Menü" size="large" />
              <SectionH title="Verwendung" description="Seite, Link, Alias, Platzhalter, Menü" />
              <PageType form={form} item={item} field="type" label="Art" size="large" />
              <Input form={form} item={item} field="href" label="Ext. Link" type="text" size="large" />
              <Parent form={form} treeData={tree} item={item} field="aliasId" label="Alias" placeholder="Alias zu.." size="large" />
              <SectionH title="Erweitert" description="Datenanbindung und Sortierung der Elemente" />
              <Input form={form} item={item} field="binding" placeholder="typ id name" label="Bindung" type="text" size="large" />
              <Input form={form} item={item} field="sorting" placeholder="+name, -id" label="Sortieren" type="text" size="large" />
            </Panel>
          </Tabs.TabPane>
          <Tabs.TabPane tab="Text" key="2">
            <Panel paddingX={16}>
              <SlateTree form={form} item={item} field="blocks" label={null} />
            </Panel>
          </Tabs.TabPane>
        </Tabs>

    );
  }
}
PageForm.propTypes = {
  item: PropTypes.object,
  form: PropTypes.object,
  items: PropTypes.arrayOf(PropTypes.object),
};
PageForm.defaultProps = {
  item: {},
  items: [],
};
export const PageFormGql = queryPages(queryPage(mutatePage(Form.create(PageForm))));
<commit_msg>Cleanup page form<commit_after>import React, { Component, PropTypes } from 'react';
import { Form } from 'antd';
import { unflatten, slugify } from 'olymp';
import { Tabs } from 'antd';
import { Panel, SectionH } from 'olymp/ui';
import { queryPage, queryPages, mutatePage } from './gql';
import { Input, SlateTree, PageType, State } from '../collection';
import { Parent } from './edits';

export class PageForm extends Component {
  handleNameChange = (e) => { // set slug if unset
    const { form } = this.props;
    const value = e.target.value;
    form.setFieldsValue({ slug: `/${slugify(value, true)}` });
  }
  handleTypeChange = (e) => { // set slug if unset
    const { form } = this.props;
    if (e === 'MENU') {
      form.setFieldsValue({ parentId: null });
    }
  }
  render() {
    const { form, item, items } = this.props;

    let tree = unflatten(items.map(({ id, name, parentId }) => ({
      value: id,
      label: name,
      parent: parentId,
      children: [],
    })), { id: 'value', parentId: 'parent' });

    return (

        <Tabs defaultActiveKey="1" size="small">
          <Tabs.TabPane tab="Basis" key="1">
            {/*<Panel minWidth={560} margin="0 30px" padding={16}>*/}
            <Panel paddingX={16} alignLabel="left">
              <Input form={form} item={item} field="name" label="Name" onChange={this.handleNameChange} rules={['required']} type="text" size="large" />
              <Input form={form} item={item} field="slug" label="Slug" type="text" size="large" />
              <State form={form} item={item} field="state" label="Status" rules={['required']} />
              <Parent form={form} treeData={tree} item={item} field="parentId" label="Menü" placeholder="Übergeordnetes Menü" size="large" />
              <SectionH title="Verwendung" description="Seite, Link, Alias, Platzhalter, Menü" />
              <PageType form={form} item={item} field="type" label="Art" size="large" onChange={this.handleTypeChange} />
              {form.getFieldValue('type') === 'LINK' && <Input form={form} item={item} field="href" label="Ext. Link" type="text" size="large" />}
              {form.getFieldValue('type') === 'ALIAS' && <Parent form={form} treeData={tree} item={item} field="aliasId" label="Alias" placeholder="Alias zu.." size="large" />}
              <SectionH title="Erweitert" description="Datenanbindung und Sortierung der Elemente" />
              <Input form={form} item={item} field="binding" placeholder="typ id name" label="Bindung" type="text" size="large" />
              <Input form={form} item={item} field="sorting" placeholder="+name, -id" label="Sortieren" type="text" size="large" />
            </Panel>
          </Tabs.TabPane>
          <Tabs.TabPane tab="Text" key="2">
            <Panel paddingX={16}>
              <SlateTree form={form} item={item} field="blocks" label={null} />
            </Panel>
          </Tabs.TabPane>
        </Tabs>

    );
  }
}
PageForm.propTypes = {
  item: PropTypes.object,
  form: PropTypes.object,
  items: PropTypes.arrayOf(PropTypes.object),
};
PageForm.defaultProps = {
  item: {},
  items: [],
};
export const PageFormGql = queryPages(queryPage(mutatePage(Form.create(PageForm))));
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {CONFIGS_DIR} from "../paths"
import {join} from "path"
import {runBinary} from "../binaries"

const PRESET_LOCATION = join(CONFIGS_DIR, "babel-preset", "index.js")
const BABEL_ARGS = [
  "src",
  "-d",
  "build",
  "--ignore",
  "**/__*__/**",
  "-s",
  `--presets=${PRESET_LOCATION}`
]

function buildLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "both",
    ...getBuildOptions(args)
  })
}

function buildNodeApp(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "node",
    ...getBuildOptions(args)
  })
}

function buildNodeLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "node",
    ...getBuildOptions(args)
  })
}

function buildWebApp(args) {
  console.log("TODO")
}

function buildWebLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "web",
    ...getBuildOptions(args)
  })
}

function cleanup() {
  runBinary("rimraf", ['"build"'])
}

/**
 * Returns the options affects which plugins are enabled.
 */
function getBuildOptions(args) {
  let result = {}
  if (args.commentFlow) result.commentFlow = true
  if (args.flow) result.flow = true
  if (args.production) result.production = true
  if (args.removeFlow) result.removeFlow = true
  if (args.typescript) result.typescript = true
  return result
}

export default {
  command: "build",
  description: "Build the project.",
  builder: yargs => {
    return yargs
      .command({
        command: "lib",
        description: "Build a library to be used on node or web app.",
        handler: buildLib
      })
      .command({
        command: "node-app",
        description: "Build a node app.",
        handler: buildNodeApp
      })
      .command({
        command: "node-lib",
        description: "Build a library to be used on node apps.",
        handler: buildNodeLib
      })
      .command({
        command: "web-app",
        description: "Build a web app.",
        handler: buildWebApp
      })
      .command({
        command: "web-lib",
        description: "Build a library to be used on web apps.",
        handler: buildWebLib
      })
      .demandCommand()
  }
}
<commit_msg>Fix build options not being exported<commit_after>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {CONFIGS_DIR} from "../paths"
import {join} from "path"
import {runBinary} from "../binaries"

const PRESET_LOCATION = join(CONFIGS_DIR, "babel-preset", "index.js")
const BABEL_ARGS = [
  "src",
  "-d",
  "build",
  "--ignore",
  "**/__*__/**",
  "-s",
  `--presets=${PRESET_LOCATION}`
]

function buildLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "both",
    ...getBuildOptions(args)
  })
}

function buildNodeApp(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "node",
    ...getBuildOptions(args)
  })
}

function buildNodeLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "node",
    ...getBuildOptions(args)
  })
}

function buildWebApp(args) {
  console.log("TODO")
}

function buildWebLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "web",
    ...getBuildOptions(args)
  })
}

function cleanup() {
  runBinary("rimraf", ['"build"'])
}

/**
 * Returns the options affects which plugins are enabled.
 */
export function getBuildOptions(args) {
  let result = {}
  if (args.commentFlow) result.commentFlow = true
  if (args.flow) result.flow = true
  if (args.production) result.production = true
  if (args.removeFlow) result.removeFlow = true
  if (args.typescript) result.typescript = true
  return result
}

export default {
  command: "build",
  description: "Build the project.",
  builder: yargs => {
    return yargs
      .command({
        command: "lib",
        description: "Build a library to be used on node or web app.",
        handler: buildLib
      })
      .command({
        command: "node-app",
        description: "Build a node app.",
        handler: buildNodeApp
      })
      .command({
        command: "node-lib",
        description: "Build a library to be used on node apps.",
        handler: buildNodeLib
      })
      .command({
        command: "web-app",
        description: "Build a web app.",
        handler: buildWebApp
      })
      .command({
        command: "web-lib",
        description: "Build a library to be used on web apps.",
        handler: buildWebLib
      })
      .demandCommand()
  }
}
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {CONFIGS_DIR} from "../paths"
import {join} from "path"
import {runBinary} from "../binaries"

const PRESET_LOCATION = join(CONFIGS_DIR, "babel-preset", "index.js")
const BABEL_ARGS = [
  "src",
  "-d",
  "build",
  "--ignore",
  "**/__*__/**",
  "-s",
  `--presets=${PRESET_LOCATION}`
]

function buildLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "both",
    ...getBuildOptions(args)
  })
}

function buildNodeApp(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "node",
    ...getBuildOptions(args)
  })
}

function buildNodeLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "node",
    ...getBuildOptions(args)
  })
}

function buildWebApp(args) {
  console.log("TODO")
}

function buildWebLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "web",
    ...getBuildOptions(args)
  })
}

function cleanup() {
  runBinary("rimraf", ['"build"'])
}

/**
 * Returns the options affects which plugins are enabled.
 */
function getBuildOptions(args) {
  return {
    commentFlow: args.commentFlow,
    flow: args.flow,
    production: args.production,
    react: args.react,
    removeFlow: args.removeFlow,
    typescript: args.typescript
  }
}

export default {
  command: "build",
  description: "Build the project.",
  builder: yargs => {
    return yargs
      .command({
        command: "lib",
        description: "Build a library to be used on node or web app.",
        handler: buildLib
      })
      .command({
        command: "node-app",
        description: "Build a node app.",
        handler: buildNodeApp
      })
      .command({
        command: "node-lib",
        description: "Build a library to be used on node apps.",
        handler: buildNodeLib
      })
      .command({
        command: "web-app",
        description: "Build a web app.",
        handler: buildWebApp
      })
      .command({
        command: "web-lib",
        description: "Build a library to be used on web apps.",
        handler: buildWebLib
      })
      .demandCommand()
  }
}
<commit_msg>Fix build options function<commit_after>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {CONFIGS_DIR} from "../paths"
import {join} from "path"
import {runBinary} from "../binaries"

const PRESET_LOCATION = join(CONFIGS_DIR, "babel-preset", "index.js")
const BABEL_ARGS = [
  "src",
  "-d",
  "build",
  "--ignore",
  "**/__*__/**",
  "-s",
  `--presets=${PRESET_LOCATION}`
]

function buildLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "both",
    ...getBuildOptions(args)
  })
}

function buildNodeApp(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "node",
    ...getBuildOptions(args)
  })
}

function buildNodeLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "node",
    ...getBuildOptions(args)
  })
}

function buildWebApp(args) {
  console.log("TODO")
}

function buildWebLib(args) {
  cleanup()
  runBinary("babel", BABEL_ARGS, {
    target: "web",
    ...getBuildOptions(args)
  })
}

function cleanup() {
  runBinary("rimraf", ['"build"'])
}

/**
 * Returns the options affects which plugins are enabled.
 */
function getBuildOptions(args) {
  let result = {}
  if (args.commentFlow) result.commentFlow = true
  if (args.flow) result.flow = true
  if (args.production) result.production = true
  if (args.removeFlow) result.removeFlow = true
  if (args.typescript) result.typescript = true
  return result
}

export default {
  command: "build",
  description: "Build the project.",
  builder: yargs => {
    return yargs
      .command({
        command: "lib",
        description: "Build a library to be used on node or web app.",
        handler: buildLib
      })
      .command({
        command: "node-app",
        description: "Build a node app.",
        handler: buildNodeApp
      })
      .command({
        command: "node-lib",
        description: "Build a library to be used on node apps.",
        handler: buildNodeLib
      })
      .command({
        command: "web-app",
        description: "Build a web app.",
        handler: buildWebApp
      })
      .command({
        command: "web-lib",
        description: "Build a library to be used on web apps.",
        handler: buildWebLib
      })
      .demandCommand()
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2017-present, Callstack.
 * All rights reserved.
 *
 * @flow
 */
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const clear = require('clear');
const chalk = require('chalk');

const logger = require('../logger');
const createServer = require('../server');
const messages = require('../messages');
const exec = require('../utils/exec');
const { MessageError } = require('../errors');

const makeReactNativeConfig = require('../utils/makeReactNativeConfig');

/**
 * Starts development server
 */
async function start(opts: *) {
  const directory = process.cwd();
  const configPath = path.join(directory, 'webpack.haul.js');

  if (!fs.existsSync(configPath)) {
    throw new MessageError(
      messages.webpackConfigNotFound({
        directory,
      }),
    );
  }

  // eslint-disable-next-line prefer-const
  let [config, platforms] = makeReactNativeConfig(
    // $FlowFixMe: Dynamic require
    require(configPath),
    {
      dev: opts.dev,
      cwd: directory,
    },
  );

  if (opts.platform !== 'all' && platforms.includes(opts.platform)) {
    config = config[platforms.indexOf(opts.platform)];
  }

  clear();

  const compiler = webpack(config);

  const app = createServer(
    compiler,
    didHaveIssues => {
      clear();
      if (didHaveIssues) {
        logger.warn(messages.bundleBuilding(didHaveIssues));
      } else {
        logger.info(messages.bundleBuilding(didHaveIssues));
      }
    },
    stats => {
      clear();
      if (stats.hasErrors()) {
        logger.error(messages.bundleFailed());
      } else {
        logger.done(
          messages.bundleBuilt({
            stats,
            platform: opts.platform,
          }),
        );
      }
    },
  );

  // Run `adb reverse` on Android
  if (opts.platform === 'android') {
    const args = `reverse tcp:${opts.port} tcp:${opts.port}`;
    const adb = process.env.ANDROID_HOME
      ? `${process.env.ANDROID_HOME}/platform-tools/adb`
      : 'adb';

    try {
      await exec(`${adb} ${args}`);
      logger.info(
        messages.commandSuccess({
          command: `${path.basename(adb)} ${args}`,
        }),
      );
    } catch (error) {
      logger.warn(
        messages.commandFailed({
          command: `${path.basename(adb)} ${args}`,
          error,
        }),
      );
    }
  }

  // $FlowFixMe Seems to have issues with `http.Server`
  app.listen(8081, '127.0.0.1', () => {
    logger.info(
      messages.initialStartInformation({
        entries: Array.isArray(config)
          ? config.map(c => c.entry)
          : [config.entry],
        port: opts.port,
      }),
    );
  });
}

module.exports = {
  name: 'start',
  description: 'Starts a new webpack server',
  action: start,
  options: [
    {
      name: 'port',
      description: 'Port to run your webpack server',
      default: '8081',
      parse: Number,
    },
    {
      name: 'dev',
      description: 'Whether to build in development mode',
      default: 'true',
      parse: (val: string) => JSON.parse(val),
      choices: [
        {
          value: 'true',
          description: 'Builds in development mode',
        },
        {
          value: 'false',
          description: 'Builds in production mode',
        },
      ],
    },
    {
      name: 'platform',
      description: 'Platform to bundle for',
      example: 'haul start --platform ios',
      note: `${chalk.bold('--platform=all')} is similar to how React Native packager works - you can run iOS and Android versions of your app at the same time. It will become the default value in future after we fix the performance issues.`,
      required: true,
      choices: [
        {
          value: 'ios',
          description: 'Servers iOS bundle',
        },
        {
          value: 'android',
          description: 'Serves Android bundle',
        },
        {
          value: 'all',
          description: 'Serves both platforms',
        },
      ],
    },
  ],
};
<commit_msg>Use `port` from CLI arguments (#51)<commit_after>/**
 * Copyright 2017-present, Callstack.
 * All rights reserved.
 *
 * @flow
 */
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const clear = require('clear');
const chalk = require('chalk');

const logger = require('../logger');
const createServer = require('../server');
const messages = require('../messages');
const exec = require('../utils/exec');
const { MessageError } = require('../errors');

const makeReactNativeConfig = require('../utils/makeReactNativeConfig');

/**
 * Starts development server
 */
async function start(opts: *) {
  const directory = process.cwd();
  const configPath = path.join(directory, 'webpack.haul.js');

  if (!fs.existsSync(configPath)) {
    throw new MessageError(
      messages.webpackConfigNotFound({
        directory,
      }),
    );
  }

  // eslint-disable-next-line prefer-const
  let [config, platforms] = makeReactNativeConfig(
    // $FlowFixMe: Dynamic require
    require(configPath),
    {
      dev: opts.dev,
      cwd: directory,
    },
  );

  if (opts.platform !== 'all' && platforms.includes(opts.platform)) {
    config = config[platforms.indexOf(opts.platform)];
  }

  clear();

  const compiler = webpack(config);

  const app = createServer(
    compiler,
    didHaveIssues => {
      clear();
      if (didHaveIssues) {
        logger.warn(messages.bundleBuilding(didHaveIssues));
      } else {
        logger.info(messages.bundleBuilding(didHaveIssues));
      }
    },
    stats => {
      clear();
      if (stats.hasErrors()) {
        logger.error(messages.bundleFailed());
      } else {
        logger.done(
          messages.bundleBuilt({
            stats,
            platform: opts.platform,
          }),
        );
      }
    },
  );

  // Run `adb reverse` on Android
  if (opts.platform === 'android') {
    const args = `reverse tcp:${opts.port} tcp:${opts.port}`;
    const adb = process.env.ANDROID_HOME
      ? `${process.env.ANDROID_HOME}/platform-tools/adb`
      : 'adb';

    try {
      await exec(`${adb} ${args}`);
      logger.info(
        messages.commandSuccess({
          command: `${path.basename(adb)} ${args}`,
        }),
      );
    } catch (error) {
      logger.warn(
        messages.commandFailed({
          command: `${path.basename(adb)} ${args}`,
          error,
        }),
      );
    }
  }

  // $FlowFixMe Seems to have issues with `http.Server`
  app.listen(opts.port, '127.0.0.1', () => {
    logger.info(
      messages.initialStartInformation({
        entries: Array.isArray(config)
          ? config.map(c => c.entry)
          : [config.entry],
        port: opts.port,
      }),
    );
  });
}

module.exports = {
  name: 'start',
  description: 'Starts a new webpack server',
  action: start,
  options: [
    {
      name: 'port',
      description: 'Port to run your webpack server',
      default: '8081',
      parse: Number,
    },
    {
      name: 'dev',
      description: 'Whether to build in development mode',
      default: 'true',
      parse: (val: string) => JSON.parse(val),
      choices: [
        {
          value: 'true',
          description: 'Builds in development mode',
        },
        {
          value: 'false',
          description: 'Builds in production mode',
        },
      ],
    },
    {
      name: 'platform',
      description: 'Platform to bundle for',
      example: 'haul start --platform ios',
      note: `${chalk.bold('--platform=all')} is similar to how React Native packager works - you can run iOS and Android versions of your app at the same time. It will become the default value in future after we fix the performance issues.`,
      required: true,
      choices: [
        {
          value: 'ios',
          description: 'Servers iOS bundle',
        },
        {
          value: 'android',
          description: 'Serves Android bundle',
        },
        {
          value: 'all',
          description: 'Serves both platforms',
        },
      ],
    },
  ],
};
<|endoftext|>


<commit_before>exports.run = function (client, msg, args, guilds) {

	if (msg.author.id !== "180093157554388993") return;

	if (!args[0]) return msg.channel.createMessage({embed: {
		color: 0x1E90FF,
		title: "Specify an action",
		description: "< farm | leave | lookup | blacklist | hm | mi >"
	}});

	if (args[0] === "farm") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a bot % threshold"
		}});

		let g = client.guilds.filter(g => g.members.filter(m => m.bot).length / g.members.size * 100 >= args[1])
		msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: `Matches Found (${g.length})`,
			fields: [
				{ name: "\u200B", value: (g.length > 0 ? g.slice(0, 10).map(s => `**${s.name}** (${s.id})`).join("\n") : "None"), inline: true }
			]
		}});

	};

	if (args[0] === "leave") {
		if (!args[1] || isNaN(args[1])) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify an ID"
		}});

		if (!client.guilds.get(args[1])) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: ":warning: Not found"
		}});

		client.guilds.get(args[1]).leave();

		msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			description: "<:oktrump:284357092859707392>"
		}});
	};

	if (args[0] === "mi") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a server ID"
		}});

		if (!client.guilds.get(args[1])) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: ":warning: Not found"
		}});

		client.guilds.get(args[1]).defaultChannel.createInvite({ maxAge: 15 }).then(inv => {
			msg.channel.createMessage("discord.gg/" + inv.code)
		}).catch(err => {
			msg.channel.createMessage("Failed to generate invite")
		});

	};

	if (args[0] === "db") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a server ID"
		}});

		rethonk.db("data").table("guilds").get(args[1]).run()
		.then(data => {
    		msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: `${client.guilds.get(args[1]).name} database`,
				fields: [
					{ name: "Admins", value: data.admins.length > 0 ? data.admins.join("\n") : "None", inline: true },
					{ name: "Blocked", value: data.blocked.length > 0 ? data.blocked.join("\n") : "None", inline: true },
					{ name: "Whitelist", value: data.whitelist.length > 0 ? data.whitelist.join("\n") : "None", inline: true },
					{ name: "Prefix", value: data.prefix, inline: true}
				]
			}})
		}).catch(err => {
			msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: "RethinkDB Error",
				description: err.message
			}})
		})
	}

	if (args[0] === "hm") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a member ID"
		}});

		let servers = client.guilds.filter(g => g.members.has(args[1]));
		msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: `Servers with member: ${args[1]}`,
			fields: [
				{ name: `${servers.length} results`, value: servers.map(s => s.name).join("\n"), inline: true }
			]
		}});

	};

	if (args[0] === "lookup") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a name or ID"
		}});

		if (isNaN(args[1])) {

			let search = client.guilds.filter(g => g.name.toLowerCase().includes(args.slice(1).join(" ").toLowerCase()))
			return msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: `Search Results (${search.length})`,
				fields: [
					{ name: "\u200B", value: (search.length > 0 ? search.slice(0, 10).map(s => `**${s.name}** (${s.id})`).join("\n") : "None"), inline: true }
				]
			}});

		} else {
			if (!client.guilds.get(args[1])) return msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: ":warning: Not found"
			}});

			let g = client.guilds.get(args[1])
			let bp = (g.members.filter(m => m.bot).length / g.members.size * 100).toFixed(2)
			msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: g.name,
				description: `Owner: ${client.users.get(g.ownerID) ? client.users.get(g.ownerID).username + client.users.get(g.ownerID).discriminator + " (" + g.ownerID + ")" : "Unknown"}`,
				fields: [
					{ name: "Overall Users", value: g.members.size, inline: true },
					{ name: "Bots", value: g.members.filter(m => m.bot).length, inline: true },
					{ name: "Users", value: g.members.filter(m => !m.bot).length, inline: true },
					{ name: "%", value: `${bp}% (${bp > 75 ? "NO" : "OK"})`, inline: true },
				]
			}});
		};
	}

	if (args[0] === "blacklist") {
		if (!args[1] || isNaN(args[1])) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify an ID"
		}});

		msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: ":warning: Command not finished."
		}});
	};
}

exports.usage = {
	main: "{prefix}{command}",
	args: "[ DEVELOPER COMMAND ]"
};
<commit_msg>stuff<commit_after>exports.run = function (client, msg, args, guilds) {

	if (msg.author.id !== "180093157554388993" && msg.author.id !== "284122164582416385" && msg.author.id !== "172571295077105664") return;

	if (!args[0]) return msg.channel.createMessage({embed: {
		color: 0x1E90FF,
		title: "Specify an action",
		description: "< farm | leave | find | black | member | inv | db >"
	}});

	if (args[0] === "farm") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a bot % threshold"
		}});

		let g = client.guilds.filter(g => g.members.filter(m => m.bot).length / g.members.size * 100 >= args[1])
		msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: `Matches Found (${g.length})`,
			fields: [
				{ name: "\u200B", value: (g.length > 0 ? g.slice(0, 10).map(s => `**${s.name}** (${s.id})`).join("\n") : "None"), inline: true }
			]
		}});

	};

	if (args[0] === "leave") {
		if (msg.author.id !== "180093157554388993") return;
		if (!args[1] || isNaN(args[1])) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify an ID"
		}});

		if (!client.guilds.get(args[1])) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: ":warning: Not found"
		}});

		client.guilds.get(args[1]).leave();

		msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			description: "<:oktrump:284357092859707392>"
		}});
	};

	if (args[0] === "inv") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a server ID"
		}});

		if (!client.guilds.get(args[1])) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: ":warning: Not found"
		}});

		client.guilds.get(args[1]).defaultChannel.createInvite({ maxAge: 15 }).then(inv => {
			msg.channel.createMessage("discord.gg/" + inv.code)
		}).catch(err => {
			msg.channel.createMessage("Failed to generate invite")
		});

	};

	if (args[0] === "db") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a server ID"
		}});

		rethonk.db("data").table("guilds").get(args[1]).run()
		.then(data => {
    		msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: `${client.guilds.get(args[1]).name} Database`,
				fields: [
					{ name: "Admins", value: data.admins.length > 0 ? data.admins.join("\n") : "None", inline: true },
					{ name: "Blocked", value: data.blocked.length > 0 ? data.blocked.join("\n") : "None", inline: true },
					{ name: "Whitelist", value: data.whitelist.length > 0 ? data.whitelist.join("\n") : "None", inline: true },
					{ name: "Prefix", value: data.prefix, inline: true}
				]
			}})
		}).catch(err => {
			msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: "RethinkDB Error",
				description: err.message
			}})
		})
	}

	if (args[0] === "member") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a member ID"
		}});

		let servers = client.guilds.filter(g => g.members.has(args[1]));
		msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: `Servers with member: ${args[1]}`,
			fields: [
				{ name: `${servers.length} results`, value: servers.map(s => s.name).join("\n"), inline: true }
			]
		}});

	};

	if (args[0] === "find") {
		if (!args[1]) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify a name or ID"
		}});

		if (isNaN(args[1])) {

			let search = client.guilds.filter(g => g.name.toLowerCase().includes(args.slice(1).join(" ").toLowerCase()))
			return msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: `Search Results (${search.length})`,
				fields: [
					{ name: "\u200B", value: (search.length > 0 ? search.slice(0, 10).map(s => `**${s.name}** (${s.id})`).join("\n") : "None"), inline: true }
				]
			}});

		} else {
			if (!client.guilds.get(args[1])) return msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: ":warning: Not found"
			}});

			let g = client.guilds.get(args[1])
			let bp = (g.members.filter(m => m.bot).length / g.members.size * 100).toFixed(2)
			msg.channel.createMessage({ embed: {
				color: 0x1E90FF,
				title: g.name,
				description: `Owner: ${client.users.get(g.ownerID) ? client.users.get(g.ownerID).username + client.users.get(g.ownerID).discriminator + " (" + g.ownerID + ")" : "Unknown"}`,
				fields: [
					{ name: "Overall Users", value: g.members.size, inline: true },
					{ name: "Bots", value: g.members.filter(m => m.bot).length, inline: true },
					{ name: "Users", value: g.members.filter(m => !m.bot).length, inline: true },
					{ name: "%", value: `${bp}% (${bp > 75 ? "NO" : "OK"})`, inline: true },
				]
			}});
		};
	}

	if (args[0] === "black") {
		if (!args[1] || isNaN(args[1])) return msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: "You need to specify an ID"
		}});

		msg.channel.createMessage({ embed: {
			color: 0x1E90FF,
			title: ":warning: Command not finished."
		}});
	};
}

exports.usage = {
	main: "{prefix}{command}",
	args: "[ DEVELOPER COMMAND ]"
};
<|endoftext|>


<commit_before>'use strict';

window.DebugNS = '*';

// Dependencies
import IframeBridge from 'iframe-bridge';
import React from 'react';
import Visualizer from 'react-visualizer';
import {Tabs as BTabs, Tab, Button} from 'react-bootstrap';

// Components
import TabTitle from './TabTitle';
import Login from './Login';

// Other
import Tabs from '../main/Tabs';
import iframeMessageHandler from '../main/iframeMessageHandler';
import iframeBridge from '../main/iframe-bridge';
import tabStorage from '../main/tabStorage';
import {rewriteURL} from '../util';

const conf = require('../config/config.js');

// Setting this to true should load all the tabs on page load
// It is discouraged to do this because loading hidden iframes
// lead to layout issues. Especially in Firefox.
const loadHidden = conf.loadHidden || false;

const possibleViews = conf.possibleViews;
const forbiddenPossibleViews = Object.keys(possibleViews);

let tabInit = Promise.resolve();
let currentIframe;

function getParameterByName(name) {
    const match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

class App extends React.Component {
    constructor() {
        super();

        IframeBridge.registerHandler('tab', iframeMessageHandler);
        IframeBridge.registerHandler('admin', (data, [level2]) => {
            if (level2 === 'connect' && data.windowID !== undefined) {
                possibleViews[currentIframe.id].windowID = data.windowID;
                currentIframe.resolve();
            }
        });

        Tabs.on('openTab', (obj) => {
            const options = {};
            ['noFocus', 'noFocusEvent', 'noData', 'load'].forEach(prop => {
                options[prop] = obj[prop];
                delete obj[prop];
            });
            this.doTab(obj, options);
        });
        Tabs.on('status', this.setTabStatus.bind(this));
        Tabs.on('message', this.sendTabMessage.bind(this));
        Tabs.on('focus', this.focusTab.bind(this));

        this.visualizerVersion = getParameterByName('v');

        this.state = {
            viewsList: [],
            activeTabKey: 0
        };

        this.loadTabs();
    }

    async loadTabs() {
        let firstTab;
        const loadTab = async (view) => {
            if (!firstTab) firstTab = view.id;
            await this.doTab(view, {
                noFocus: true,
                load: loadHidden,
                noFocusEvent: true
            });
        };
        const data = tabStorage.load();
        // Load possible views first
        for (let key in possibleViews) {
            possibleViews[key].id = key;
            let saved;
            if (saved = data.find(el => el.id === key)) {
                await loadTab(saved);
            } else {
                await loadTab(possibleViews[key]);
            }
        }

        for (let i = 0; i < data.length; i++) {
            if (!possibleViews[data[i].id]) {
                await loadTab(data[i]);
            }
        }

        // Nothing is focused at this point
        const lastSelected = tabStorage.getSelected();
        if (this.state.viewsList.find(el => el.id === lastSelected)) {
            await this.showTab(lastSelected);
        } else {
            await this.showTab(firstTab);
        }

    }

    setTabStatus(data) {
        // Find view with given window ID
        const ids = Object.keys(possibleViews);
        let id = ids.find(id => possibleViews[id].windowID === data.windowID);
        if (!id) return;
        let view = possibleViews[id];

        view = this.state.viewsList.find(el => el.id === view.id);
        if (!view) return;

        view.status = Object.assign({}, view.status, data.message);
        this.setState({
            viewsList: this.state.viewsList
        });
    }

    sendTabMessage(data) {
        const viewInfo = possibleViews[data.id];
        if (viewInfo) {
            IframeBridge.postMessage('tab.message', data.message, viewInfo.windowID);
        }
    }

    async focusTab(tabId) {
        if (this.state.viewsList.find(el => el.id === tabId)) {
            await this.showTab(tabId, {
                noData: true
            });
        }
    }

    async doTab(obj, options) {
        if (!possibleViews[obj.id]) {
            possibleViews[obj.id] = {
                id: obj.id,
                url: obj.url,
                data: obj.data,
                closable: obj.closable
            };
        } else {
            possibleViews[obj.id].data = obj.data;
        }

        if (conf.rewriteRules) {
            let newURL = rewriteURL(conf.rewriteRules, possibleViews[obj.id].url);
            if (newURL) {
                possibleViews[obj.id].rewrittenUrl = newURL;
            }
        }

        await this.showTab(obj.id, options);
    }

    async showTab(id, options) {
        options = options || {};
        const sameTab = this.state.activeTabKey === id;
        if (sameTab && !options.force) return;

        const noFocus = options.noFocus;
        let viewFromList = this.state.viewsList.find(el => el.id === id);
        const newTab = !viewFromList;
        const viewInfo = possibleViews[id];

        if (!viewInfo) throw new Error('unreachable');
        if (!viewFromList) {
            viewFromList = {
                id: id,
                url: viewInfo.url,
                rewrittenUrl: viewInfo.rewrittenUrl,
                closable: viewInfo.closable
            };
            this.state.viewsList.push(viewFromList)
        }
        const firstRender = (options.load || !noFocus) && (newTab || !viewFromList.rendered);
        await tabInit;
        if (firstRender) { // We should map the tab id with the window ID generated by IframeBridge
            tabInit = new Promise(resolve => {
                viewFromList.rendered = true;
                this.setState({
                    activeTabKey: options.noFocus ? undefined : id,
                    viewsList: this.state.viewsList
                });

                setTimeout(() => {
                    // This will have an effect only if Promise is not yet resolved
                    return resolve();
                }, 3000);
                currentIframe = {
                    resolve,
                    id
                };
            });
            await tabInit;
        } else { // Either it has already been renderer, or it is not to be focused
            this.setState({
                activeTabKey: noFocus ? undefined : id,
                viewsList: this.state.viewsList
            });
        }
        if (viewInfo.data && (!options.noData || firstRender)) { // always send data on first render
            IframeBridge.postMessage('tab.data', viewInfo.data, viewInfo.windowID);
        }
        tabStorage.save(id, viewInfo);
        if (!options.noFocus) {
            tabStorage.saveSelected(id);
        }
        if (!options.noFocusEvent && !sameTab) {
            this.sendTabFocusEvent();
        }

    }

    async removeTab(id) {
        tabStorage.remove(id);
        if (forbiddenPossibleViews.indexOf(id) === -1) {
            delete possibleViews[id];
        }
        let idx = this.state.viewsList.findIndex(el => el.id === id);
        if (idx === -1) return;
        this.state.viewsList.splice(idx, 1);

        let newActiveTab;
        if (id !== this.state.activeTabKey) {
            newActiveTab = this.state.activeTabKey;
        } else {
            const viewsLength = this.state.viewsList.length;
            // Set next active tab
            if (viewsLength > 0) {
                if (idx < viewsLength) {
                    newActiveTab = this.state.viewsList[idx].id;
                } else {
                    newActiveTab = this.state.viewsList[viewsLength - 1].id;
                }
            }
        }

        await this.showTab(newActiveTab, {
            noData: true,
            force: true
        });
    }

    sendTabFocusEvent() {
        const key = this.state.activeTabKey;
        if (possibleViews[key]) {
            IframeBridge.postMessage('tab.focus', {}, possibleViews[key].windowID);
        }
    }

    async onActiveTab(key) {
        await this.showTab(key, {
            noData: true
        });
    }

    render() {
        const arr = [];

        for (let view of this.state.viewsList) {
            const closable = view.closable === undefined ? true : view.closable;
            const saved = !view.status || view.status.saved === undefined ? true : view.status.saved;

            const textStyle = {};
            if (!saved) {
                textStyle.color = 'red';
            }
            const shouldRender = view.rendered || view.id === this.state.activeTabKey;
            arr.push(
                <Tab
                    title={<TabTitle textTitle={saved ? null : 'Not saved'} textStyle={textStyle} name={view.id}
                                     onTabClosed={closable ? this.removeTab.bind(this, view.id) : null}/>}
                    key={view.id} eventKey={view.id}>
                    {shouldRender ?
                        <Visualizer
                            fallbackVersion={conf.visualizerFallbackVersion || 'latest'}
                            cdn="https://www.lactame.com/visualizer"
                            viewURL={view.rewrittenUrl || view.url}
                            version={this.visualizerVersion || conf.visualizerVersion || 'auto'}
                            config={conf.visualizerConfig}
                            scripts={[iframeBridge]}
                            style={{position: 'static', flex: 2, border: 'none'}}
                        />
                        :
Not rendered
 }
                </Tab>
            );
        }

        return (

                <Login></Login>

                    <BTabs style={{flex: 2, display: 'flex', flexFlow: 'column'}} activeKey={this.state.activeTabKey}
                           onSelect={this.onActiveTab.bind(this)} animation={false}>
                        {arr}
                    </BTabs>

        );
    }

}

export default App;
<commit_msg>edit some comments<commit_after>'use strict';

window.DebugNS = '*';

// Dependencies
import IframeBridge from 'iframe-bridge';
import React from 'react';
import Visualizer from 'react-visualizer';
import {Tabs as BTabs, Tab, Button} from 'react-bootstrap';

// Components
import TabTitle from './TabTitle';
import Login from './Login';

// Other
import Tabs from '../main/Tabs';
import iframeMessageHandler from '../main/iframeMessageHandler';
import iframeBridge from '../main/iframe-bridge';
import tabStorage from '../main/tabStorage';
import {rewriteURL} from '../util';

const conf = require('../config/config.js');

// Setting this to true should load all the tabs on page load
// It is discouraged to do this because loading hidden iframes
// lead to layout issues. Especially in Firefox.
const loadHidden = conf.loadHidden || false;

const possibleViews = conf.possibleViews;
const forbiddenPossibleViews = Object.keys(possibleViews);

let tabInit = Promise.resolve();
let currentIframe;

function getParameterByName(name) {
    const match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

class App extends React.Component {
    constructor() {
        super();

        IframeBridge.registerHandler('tab', iframeMessageHandler);
        IframeBridge.registerHandler('admin', (data, [level2]) => {
            if (level2 === 'connect' && data.windowID !== undefined) {
                possibleViews[currentIframe.id].windowID = data.windowID;
                currentIframe.resolve();
            }
        });

        Tabs.on('openTab', (obj) => {
            const options = {};
            ['noFocus', 'noFocusEvent', 'noData', 'load'].forEach(prop => {
                options[prop] = obj[prop];
                delete obj[prop];
            });
            this.doTab(obj, options);
        });
        Tabs.on('status', this.setTabStatus.bind(this));
        Tabs.on('message', this.sendTabMessage.bind(this));
        Tabs.on('focus', this.focusTab.bind(this));

        this.visualizerVersion = getParameterByName('v');

        this.state = {
            viewsList: [],
            activeTabKey: 0
        };

        this.loadTabs();
    }

    async loadTabs() {
        let firstTab;
        const loadTab = async (view) => {
            if (!firstTab) firstTab = view.id;
            await this.doTab(view, {
                noFocus: true,
                load: loadHidden,
                noFocusEvent: true
            });
        };
        const data = tabStorage.load();
        // Load possible views first
        for (let key in possibleViews) {
            possibleViews[key].id = key;
            let saved;
            if (saved = data.find(el => el.id === key)) {
                await loadTab(saved);
            } else {
                await loadTab(possibleViews[key]);
            }
        }

        for (let i = 0; i < data.length; i++) {
            if (!possibleViews[data[i].id]) {
                await loadTab(data[i]);
            }
        }

        // Nothing is focused at this point
        const lastSelected = tabStorage.getSelected();
        if (this.state.viewsList.find(el => el.id === lastSelected)) {
            await this.showTab(lastSelected);
        } else {
            await this.showTab(firstTab);
        }

    }

    setTabStatus(data) {
        // Find view with given window ID
        const ids = Object.keys(possibleViews);
        let id = ids.find(id => possibleViews[id].windowID === data.windowID);
        if (!id) return;
        let view = possibleViews[id];

        view = this.state.viewsList.find(el => el.id === view.id);
        if (!view) return;

        view.status = Object.assign({}, view.status, data.message);
        this.setState({
            viewsList: this.state.viewsList
        });
    }

    sendTabMessage(data) {
        const viewInfo = possibleViews[data.id];
        if (viewInfo) {
            IframeBridge.postMessage('tab.message', data.message, viewInfo.windowID);
        }
    }

    async focusTab(tabId) {
        if (this.state.viewsList.find(el => el.id === tabId)) {
            await this.showTab(tabId, {
                noData: true
            });
        }
    }

    async doTab(obj, options) {
        if (!possibleViews[obj.id]) {
            possibleViews[obj.id] = {
                id: obj.id,
                url: obj.url,
                data: obj.data,
                closable: obj.closable
            };
        } else {
            possibleViews[obj.id].data = obj.data;
        }

        if (conf.rewriteRules) {
            let newURL = rewriteURL(conf.rewriteRules, possibleViews[obj.id].url);
            if (newURL) {
                possibleViews[obj.id].rewrittenUrl = newURL;
            }
        }

        await this.showTab(obj.id, options);
    }

    async showTab(id, options) {
        options = options || {};
        const sameTab = this.state.activeTabKey === id;
        if (sameTab && !options.force) return;

        const noFocus = options.noFocus;
        let viewFromList = this.state.viewsList.find(el => el.id === id);
        const newTab = !viewFromList;
        const viewInfo = possibleViews[id];

        if (!viewInfo) throw new Error('unreachable');
        if (!viewFromList) {
            viewFromList = {
                id: id,
                url: viewInfo.url,
                rewrittenUrl: viewInfo.rewrittenUrl,
                closable: viewInfo.closable
            };
            this.state.viewsList.push(viewFromList)
        }
        const firstRender = (options.load || !noFocus) && (newTab || !viewFromList.rendered);
        await tabInit;
        // First render means we expect the render function to initialize a new iframe
        // We need to get the IframeBridge ID of that frame and prevent any other iframes
        // to load during that time
        if (firstRender) {
            tabInit = new Promise(resolve => {
                viewFromList.rendered = true;
                this.setState({
                    activeTabKey: options.noFocus ? undefined : id,
                    viewsList: this.state.viewsList
                });

                setTimeout(() => {
                    // This will have an effect only if Promise is not yet resolved
                    // It prevents completely blocking the interface if there is a problem
                    // with that tab
                    return resolve();
                }, 3000);
                currentIframe = {
                    resolve,
                    id
                };
            });
            await tabInit;
        } else {
            this.setState({
                activeTabKey: noFocus ? undefined : id,
                viewsList: this.state.viewsList
            });
        }
        // always send data on first render
        if (viewInfo.data && (!options.noData || firstRender)) {
            IframeBridge.postMessage('tab.data', viewInfo.data, viewInfo.windowID);
        }
        tabStorage.save(id, viewInfo);
        if (!options.noFocus) {
            tabStorage.saveSelected(id);
        }
        if (!options.noFocusEvent && !sameTab) {
            this.sendTabFocusEvent();
        }

    }

    async removeTab(id) {
        tabStorage.remove(id);
        if (forbiddenPossibleViews.indexOf(id) === -1) {
            delete possibleViews[id];
        }
        let idx = this.state.viewsList.findIndex(el => el.id === id);
        if (idx === -1) return;
        this.state.viewsList.splice(idx, 1);

        let newActiveTab;
        if (id !== this.state.activeTabKey) {
            newActiveTab = this.state.activeTabKey;
        } else {
            const viewsLength = this.state.viewsList.length;
            // Set next active tab
            if (viewsLength > 0) {
                if (idx < viewsLength) {
                    newActiveTab = this.state.viewsList[idx].id;
                } else {
                    newActiveTab = this.state.viewsList[viewsLength - 1].id;
                }
            }
        }

        await this.showTab(newActiveTab, {
            noData: true,
            force: true
        });
    }

    sendTabFocusEvent() {
        const key = this.state.activeTabKey;
        if (possibleViews[key]) {
            IframeBridge.postMessage('tab.focus', {}, possibleViews[key].windowID);
        }
    }

    async onActiveTab(key) {
        await this.showTab(key, {
            noData: true
        });
    }

    render() {
        const arr = [];

        for (let view of this.state.viewsList) {
            const closable = view.closable === undefined ? true : view.closable;
            const saved = !view.status || view.status.saved === undefined ? true : view.status.saved;

            const textStyle = {};
            if (!saved) {
                textStyle.color = 'red';
            }
            const shouldRender = view.rendered || view.id === this.state.activeTabKey;
            arr.push(
                <Tab
                    title={<TabTitle textTitle={saved ? null : 'Not saved'} textStyle={textStyle} name={view.id}
                                     onTabClosed={closable ? this.removeTab.bind(this, view.id) : null}/>}
                    key={view.id} eventKey={view.id}>
                    {shouldRender ?
                        <Visualizer
                            fallbackVersion={conf.visualizerFallbackVersion || 'latest'}
                            cdn="https://www.lactame.com/visualizer"
                            viewURL={view.rewrittenUrl || view.url}
                            version={this.visualizerVersion || conf.visualizerVersion || 'auto'}
                            config={conf.visualizerConfig}
                            scripts={[iframeBridge]}
                            style={{position: 'static', flex: 2, border: 'none'}}
                        />
                        :
Not rendered
 }
                </Tab>
            );
        }

        return (

                <Login></Login>

                    <BTabs style={{flex: 2, display: 'flex', flexFlow: 'column'}} activeKey={this.state.activeTabKey}
                           onSelect={this.onActiveTab.bind(this)} animation={false}>
                        {arr}
                    </BTabs>

        );
    }

}

export default App;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ContentPageContainer from './content-page-container/ContentPageContainer'
import Access from '../pages/access/Access'
import FamilyPlanning from '../pages/family-planning/FamilyPlanning'
import Violence from '../pages/violence/Violence'
import FamilyHealth from '../pages/family-health/FamilyHealth'
import WomensHealth from '../pages/family-health/womens-health/WomensHealth'
import PregnancyNewborn from '../pages/pregnancy-newborn/PregnancyNewborn'
import SexualHealth from '../pages/sexual-health/SexualHealth'
import HealthyRelationships from '../pages/sexual-health/healthy-relationships/HealthyRelationships'
import SafeSex from '../pages/sexual-health/safe-sex/SafeSex'
import Contraception from '../pages/family-planning/contraception/Contraception'
import HealthSystemOverview from '../pages/access/health-system-overview/HealthSystemOverview'
import AustralianNorms from '../pages/access/australian-norms/AustralianNorms'
import BirthSpacing from '../pages/family-planning/birth-spacing/BirthSpacing'
import Pregnancy from '../pages/pregnancy-newborn/pregnancy/Pregnancy'
import Postnatal from '../pages/pregnancy-newborn/postnatal/Postnatal'
import Complications from '../pages/pregnancy-newborn/complications/Complications'
import Birth from '../pages/pregnancy-newborn/birth/Birth'
import PregnancyNewbornOneYear from '../pages/pregnancy-newborn/pregnancy-newborn/PregnancyNewbornOneYear'
import Nav from './nav/Nav'
import NavMenu from './navmenu/NavMenu'
import Footer from './footer/Footer'
import './App.css';
var ReactRouter = require('react-router-dom');
var Router = ReactRouter.BrowserRouter;
var Route = ReactRouter.Route;
var Switch = ReactRouter.Switch;
var Redirect = ReactRouter.Redirect;

class App extends Component {
  constructor() {
    super()
    this.state = {
      lang: 'en'
    }
    this.toggleLanguage = this.toggleLanguage.bind(this)
  }

  toggleLanguage() {
    this.setState({
      lang: this.state.lang === 'en' ? 'ar' : 'en'
    })
  }

  componentDidMount() {
    window.analytics.identify('testUserId', {
      username: 'testUsername'
    })
  }

  render() {
    return (
      <Router>

          <NavMenu lang={this.state.lang} />

            <Switch>
              <Route exact path="/" render={() => (
                <Redirect to="/access"/>
              )}/>

              <Route exact path='/access' component={Access} lang={this.state.lang} />
              <Route exact path='/access/health-system-overview' component={HealthSystemOverview} lang={this.state.lang} />
              <Route exact path='/access/australian-norms' component={AustralianNorms} lang={this.state.lang} />
              {/* Medicare and Centrelink  */}
              {/* Your Rights and Responsibilities  */}
              {/* Disability Access  */}
              {/* Private vs. Public Health Services */}

              <Route exact path='/family-planning' component={FamilyPlanning} lang={this.state.lang} />
              <Route
                exact path='/family-planning/birth-spacing'
                component={(props) => <ContentPageContainer {...props} filePath='/Content/birth-spacing.json' lang={this.state.lang} />} />
              <Route exact path='/family-planning/contraception' component={Contraception} lang={this.state.lang} />
              {/* Unplanned Pregnancy */}
              {/* Fertility and Infertility */}

              <Route exact path='/pregnancy-newborn' component={PregnancyNewborn} lang={this.state.lang} />
              <Route
                exact path='/pregnancy-newborn/pregnancy'
                component={(props) => <ContentPageContainer {...props} filePath='/Content/pregnancy.json' lang={this.state.lang} />} />
              <Route
                exact path='/pregnancy-newborn/complications'
                component={(props) => <ContentPageContainer {...props} filePath='/Content/complications-of-pregnancy.json' lang={this.state.lang} />} />
              <Route exact path='/pregnancy-newborn/birth' component={Birth} lang={this.state.lang} />
              <Route
                exact path="/pregnancy-newborn/postnatal"
                component={(props) => <ContentPageContainer {...props} filePath='/Content/postnatal.json' lang={this.state.lang} />} />
              <Route
                exact path='/pregnancy-newborn/newborn'
                component={(props) => <ContentPageContainer {...props} filePath='/Content/newborn.json' lang={this.state.lang} />} />

              <Route exact path='/sexual-health' component={SexualHealth} lang={this.state.lang} />
              <Route exact path='/sexual-health/healthy-relationships' component={HealthyRelationships} lang={this.state.lang} />
              <Route exact path='/sexual-health/safe-sex' component={SafeSex} lang={this.state.lang} />
              {/* STIs/HIV  */}
              {/* Sexuality  */}

              <Route exact path='/family-health' component={FamilyHealth} lang={this.state.lang} />
              <Route exact path='/family-health/womens-health' component={WomensHealth} lang={this.state.lang} />

              <Route render={function() {
                return
Not Found

              }} />
            </Switch>

      </Router>
    );
  }
}

export default App;
<commit_msg>removed unused imports<commit_after>import React, { Component } from 'react';
import ContentPageContainer from './content-page-container/ContentPageContainer'
import Access from '../pages/access/Access'
import FamilyPlanning from '../pages/family-planning/FamilyPlanning'
import FamilyHealth from '../pages/family-health/FamilyHealth'
import WomensHealth from '../pages/family-health/womens-health/WomensHealth'
import PregnancyNewborn from '../pages/pregnancy-newborn/PregnancyNewborn'
import SexualHealth from '../pages/sexual-health/SexualHealth'
import HealthyRelationships from '../pages/sexual-health/healthy-relationships/HealthyRelationships'
import SafeSex from '../pages/sexual-health/safe-sex/SafeSex'
import Contraception from '../pages/family-planning/contraception/Contraception'
import HealthSystemOverview from '../pages/access/health-system-overview/HealthSystemOverview'
import AustralianNorms from '../pages/access/australian-norms/AustralianNorms'
import Birth from '../pages/pregnancy-newborn/birth/Birth'
import Nav from './nav/Nav'
import NavMenu from './navmenu/NavMenu'
import Footer from './footer/Footer'
import './App.css';
var ReactRouter = require('react-router-dom');
var Router = ReactRouter.BrowserRouter;
var Route = ReactRouter.Route;
var Switch = ReactRouter.Switch;
var Redirect = ReactRouter.Redirect;

class App extends Component {
  constructor() {
    super()
    this.state = {
      lang: 'en'
    }
    this.toggleLanguage = this.toggleLanguage.bind(this)
  }

  toggleLanguage() {
    this.setState({
      lang: this.state.lang === 'en' ? 'ar' : 'en'
    })
  }

  componentDidMount() {
    window.analytics.identify('testUserId', {
      username: 'testUsername'
    })
  }

  render() {
    return (
      <Router>

          <NavMenu lang={this.state.lang} />

            <Switch>
              <Route exact path="/" render={() => (
                <Redirect to="/access"/>
              )}/>

              <Route exact path='/access' component={Access} lang={this.state.lang} />
              <Route exact path='/access/health-system-overview' component={HealthSystemOverview} lang={this.state.lang} />
              <Route exact path='/access/australian-norms' component={AustralianNorms} lang={this.state.lang} />
              {/* Medicare and Centrelink  */}
              {/* Your Rights and Responsibilities  */}
              {/* Disability Access  */}
              {/* Private vs. Public Health Services */}

              <Route exact path='/family-planning' component={FamilyPlanning} lang={this.state.lang} />
              <Route
                exact path='/family-planning/birth-spacing'
                component={(props) => <ContentPageContainer {...props} filePath='/Content/birth-spacing.json' lang={this.state.lang} />} />
              <Route exact path='/family-planning/contraception' component={Contraception} lang={this.state.lang} />
              {/* Unplanned Pregnancy */}
              {/* Fertility and Infertility */}

              <Route exact path='/pregnancy-newborn' component={PregnancyNewborn} lang={this.state.lang} />
              <Route
                exact path='/pregnancy-newborn/pregnancy'
                component={(props) => <ContentPageContainer {...props} filePath='/Content/pregnancy.json' lang={this.state.lang} />} />
              <Route
                exact path='/pregnancy-newborn/complications'
                component={(props) => <ContentPageContainer {...props} filePath='/Content/complications-of-pregnancy.json' lang={this.state.lang} />} />
              <Route exact path='/pregnancy-newborn/birth' component={Birth} lang={this.state.lang} />
              <Route
                exact path="/pregnancy-newborn/postnatal"
                component={(props) => <ContentPageContainer {...props} filePath='/Content/postnatal.json' lang={this.state.lang} />} />
              <Route
                exact path='/pregnancy-newborn/newborn'
                component={(props) => <ContentPageContainer {...props} filePath='/Content/newborn.json' lang={this.state.lang} />} />

              <Route exact path='/sexual-health' component={SexualHealth} lang={this.state.lang} />
              <Route exact path='/sexual-health/healthy-relationships' component={HealthyRelationships} lang={this.state.lang} />
              <Route exact path='/sexual-health/safe-sex' component={SafeSex} lang={this.state.lang} />
              {/* STIs/HIV  */}
              {/* Sexuality  */}

              <Route exact path='/family-health' component={FamilyHealth} lang={this.state.lang} />
              <Route exact path='/family-health/womens-health' component={WomensHealth} lang={this.state.lang} />

              <Route render={function() {
                return
Not Found

              }} />
            </Switch>

      </Router>
    );
  }
}

export default App;
<|endoftext|>


<commit_before>import React, { Component } from "react"; // eslint-disable-line no-unused-vars
import Auth from "./Auth";
import autobind from "autobind-decorator";
import config from "../config.js";
import { Link } from "react-router";

@autobind
class App extends Component {
	constructor() {
		super();

		this.state = {
			token: localStorage.getItem( "token" ),
			uid: localStorage.getItem( "uid" )
		};
	}

	setAuth( data ) {
		localStorage.setItem( "token", data.token );
		localStorage.setItem( "uid", data.uid );
		this.setState( data );
		this.props.history.pushState( this.props.location );
	}

	removeAuth() {
		localStorage.removeItem( "token" );
		localStorage.removeItem( "uid" );
		this.setState( {
			token: "",
			uid: ""
		} );
	}

	logIn() {
		location.replace( config.authProvider );
	}

	componentWillMount() {
		let query = this.props.location.query;

		if ( !this.state.token && query.hasOwnProperty( "access_token" ) ) {
			this.setAuth( {
				token: query.access_token,
				uid: query.id
			} );

			delete query.access_token;
			delete query.id;
		}
	}

	render() {
		return (

<Link to="/">Hello, World!</Link>

				<Auth
					token={ this.state.token }
					logIn={ this.logIn.bind( this ) }
					logOut={ this.removeAuth.bind( this ) }
				/>
				<Link to="/about">About</Link>
				{this.props.children}

		);
	}
}

export default App;
<commit_msg>Use replaceState and remove unnecessary code<commit_after>import React, { Component } from "react"; // eslint-disable-line no-unused-vars
import Auth from "./Auth";
import autobind from "autobind-decorator";
import config from "../config.js";
import { Link } from "react-router";

@autobind
class App extends Component {
	constructor() {
		super();

		this.state = {
			token: localStorage.getItem( "token" ),
			uid: localStorage.getItem( "uid" )
		};
	}

	setAuth( data ) {
		localStorage.setItem( "token", data.token );
		localStorage.setItem( "uid", data.uid );
		this.setState( data );
		this.props.history.replaceState( this.props.location );
	}

	removeAuth() {
		localStorage.removeItem( "token" );
		localStorage.removeItem( "uid" );
		this.setState( {
			token: "",
			uid: ""
		} );
	}

	logIn() {
		location.replace( config.authProvider );
	}

	componentWillMount() {
		let query = this.props.location.query;

		if ( !this.state.token && query.hasOwnProperty( "access_token" ) ) {
			this.setAuth( {
				token: query.access_token,
				uid: query.id
			} );
		}
	}

	render() {
		return (

<Link to="/">Hello, World!</Link>

				<Auth
					token={ this.state.token }
					logIn={ this.logIn.bind( this ) }
					logOut={ this.removeAuth.bind( this ) }
				/>
				<Link to="/about">About</Link>
				{this.props.children}

		);
	}
}

export default App;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import cx from 'classnames';

module.exports = React.createClass({
  displayName: 'Tab',

  propTypes: {
    className: PropTypes.string,
    id: PropTypes.string,
    focus: PropTypes.bool,
    selected: PropTypes.bool,
    disabled: PropTypes.bool,
    activeTabClassName: PropTypes.string,
    disabledTabClassName: PropTypes.string,
    panelId: PropTypes.string,
    children: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object,
      PropTypes.string,
    ]),
  },

  getDefaultProps() {
    return {
      focus: false,
      selected: false,
      id: null,
      panelId: null,
      activeTabClassName: 'ReactTabs__Tab--selected',
      disabledTabClassName: 'ReactTabs__Tab--disabled',
    };
  },

  componentDidMount() {
    this.checkFocus();
  },

  componentDidUpdate() {
    this.checkFocus();
  },

  checkFocus() {
    if (this.props.selected && this.props.focus) {
      findDOMNode(this).focus();
    }
  },

  render() {
    const {
      selected,
      disabled,
      panelId,
      activeTabClassName,
      disabledTabClassName,
      className,
      children,
      id,
      ...attributes } = this.props;

    delete attributes.focus;

    return (
      <li
        {...attributes}
        className={cx(
          'ReactTabs__Tab',
          className,
          {
            [activeTabClassName]: selected,
            [disabledTabClassName]: disabled,
          }
        )}
        role="tab"
        id={id}
        aria-selected={selected ? 'true' : 'false'}
        aria-disabled={disabled ? 'true' : 'false'}
        aria-controls={panelId}
        tabIndex={selected ? '0' : null}
      >
        {children}
      </li>
    );
  },
});
<commit_msg> add tab<commit_after>import React, { PropTypes, Component } from 'react';
import { findDOMNode } from 'react-dom';
import cx from 'classnames';

class Tab extends Component {

  static propTypes = {
    className: PropTypes.string,
    id: PropTypes.string,
    focus: PropTypes.bool,
    selected: PropTypes.bool,
    disabled: PropTypes.bool,
    activeTabClassName: PropTypes.string,
    disabledTabClassName: PropTypes.string,
    panelId: PropTypes.string,
    children: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.object,
      PropTypes.string,
    ]),
  };

  static defaultProps = {
    focus: false,
    selected: false,
    id: null,
    panelId: null,
    activeTabClassName: 'ReactTabs__Tab--selected',
    disabledTabClassName: 'ReactTabs__Tab--disabled',
  };

  componentDidMount() {
    this.checkFocus();
  }

  componentDidUpdate() {
    this.checkFocus();
  }

  checkFocus() {
    if (this.props.selected && this.props.focus) {
      findDOMNode(this).focus();
    }
  }

  render() {
    const {
      selected,
      disabled,
      panelId,
      activeTabClassName,
      disabledTabClassName,
      className,
      children,
      id,
      ...attributes } = this.props;

    delete attributes.focus;

    return (
      <li
        {...attributes}
        className={cx(
          'ReactTabs__Tab',
          className,
          {
            [activeTabClassName]: selected,
            [disabledTabClassName]: disabled,
          }
        )}
        role="tab"
        id={id}
        aria-selected={selected ? 'true' : 'false'}
        aria-disabled={disabled ? 'true' : 'false'}
        aria-controls={panelId}
        tabIndex={selected ? '0' : null}
      >
        {children}
      </li>
    );
  }
}

export default Tab;
<|endoftext|>