<commit_before>/**
 * Created by yash on 3/3/16.
 */
$(document).ready(function() {

    var dps = []; // dataPoints

    var chart = new CanvasJS.Chart("chart1",{
        title :{
            text: "Live Temperature vs Time Graph "
        },
        axisX: {
            title: "Time (Seconds)"
        },
        axisY: {
            title: "Temperature (Celsius)"
        },
        data: [{
            type: "line",
            dataPoints: dps
        }]
    });

    var xVal = 0;
    var yVal = 0;
    var updateInterval = 1000;
    var dataLength = 50; // number of dataPoints visible at any point

    var updateChart = function (count) {
        count = count || 1;
        // count is number of times loop runs to generate random dataPoints.

        //for (var j = 0; j < count; j++) {
        //    yVal = yVal +  Math.round(5 + Math.random() *(-5-5));
        //    dps.push({
        //        x: xVal,
        //        y: yVal
        //    });
        //    xVal++;
        //};

        $.get( base+"data/get_temp", function( data ) {

            //alert( data);
            dps.push({
                        x: xVal,
                        y: data
                    });
            if (dps.length > dataLength)
            {
                dps.shift();
            }
            chart.render();
            xVal++;
        });

    };

    // generates first set of dataPoints
    updateChart(dataLength);

    // update chart after specified time.
    setInterval(function(){updateChart()}, updateInterval);

    $.simpleWeather({
        location: 'Santa Clara,CA',
        woeid: '',
        unit: 'f',
        success: function(weather) {
            html = '
 '+weather.temp+'°'+weather.units.temp+'
';
            html += '

'+weather.city+', '+weather.region+'
';
            html += '
'+weather.currently+'
';
            html += '
'+weather.wind.direction+' '+weather.wind.speed+' '+weather.units.speed+'

';

            $("#weather-box").html(html);
        },
        error: function(error) {
            $("#weather").html('
'+error+'
');
        }
    });

});<commit_msg>current_value<commit_after>/**
 * Created by yash on 3/3/16.
 */
$(document).ready(function() {

    var dps = []; // dataPoints

    var chart = new CanvasJS.Chart("chart1",{
        title :{
            text: "Live Temperature vs Time Graph "
        },
        axisX: {
            title: "Time (Seconds)"
        },
        axisY: {
            title: "Temperature (Celsius)"
        },
        data: [{
            type: "line",
            dataPoints: dps
        }]
    });

    var xVal = 0;
    var yVal = 0;
    var updateInterval = 1000;
    var dataLength = 50; // number of dataPoints visible at any point

    var updateChart = function (count) {
        count = count || 1;
        // count is number of times loop runs to generate random dataPoints.

        //for (var j = 0; j < count; j++) {
        //    yVal = yVal +  Math.round(5 + Math.random() *(-5-5));
        //    dps.push({
        //        x: xVal,
        //        y: yVal
        //    });
        //    xVal++;
        //};

        $.get( base+"data/get_temp/", function( data ) {

            //alert( data);
            dps.push({
                        x: xVal,
                        y: data
                    });
            if (dps.length > dataLength)
            {
                dps.shift();
            }
            chart.render();
            xVal++;
        });

    };

    // generates first set of dataPoints
    updateChart(dataLength);

    // update chart after specified time.
    setInterval(function(){updateChart()}, updateInterval);

    $.simpleWeather({
        location: 'Santa Clara,CA',
        woeid: '',
        unit: 'f',
        success: function(weather) {
            html = '
 '+weather.temp+'°'+weather.units.temp+'
';
            html += '

'+weather.city+', '+weather.region+'
';
            html += '
'+weather.currently+'
';
            html += '
'+weather.wind.direction+' '+weather.wind.speed+' '+weather.units.speed+'

';

            $("#weather-box").html(html);
        },
        error: function(error) {
            $("#weather").html('
'+error+'
');
        }
    });

});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Autosuggest from 'react-autosuggest';
import Radium from 'radium';
import themeable from 'react-themeable';

import theme from './theme';
import Chip from './Chip';
import CallLimiter from './CallLimiter';
import { chipTheme } from './theme'

class Chips extends Component {

  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      value: "",
      chipSelected: false,
      suggestions: []
    };

    this.asyncSuggestLimiter =
      new CallLimiter(this.callFetchSuggestions.bind(this), 1000 / props.fetchSuggestionsThrushold);
  }

  componentWillReceiveProps = (nextProps) => {
    this.asyncSuggestLimiter.interval = (1000 / nextProps.fetchSuggestionsThrushold);
  }

  onBlur = e => {
    this.refs.wrapper.focus();
  }

  onFocus = e => {
    this.refs.wrapper.blur();
  }

  handleKeyDown = e => {
    if (e.keyCode === 13 && this.lastEvent === e) {
      this.lastEvent = null;
      return;
    }
    if (!this.props.fromSuggestionsOnly && (this.props.createChipKeys.includes(e.keyCode) || this.props.createChipKeys.includes(e.key))) {
      e.preventDefault();
      if (this.state.value.trim()) this.addChip(this.state.value);
    }
    if (e.keyCode === 8) {
      this.onBackspace();
    } else if (this.state.chipSelected) {
      this.setState({chipSelected: false});
    }
  }

  onBackspace = (code) => {
    if (this.state.value === "" && this.props.value.length > 0) {
      if (this.state.chipSelected) {
        const nextChips = this.props.value.slice(0, -1);
        this.setState({
          chipSelected: false,
          chips: nextChips,
        });
        this.props.onChange(nextChips);
      } else {
        this.setState({chipSelected: true})
      }
    }
  }

  addChip = (value) => {
    if (this.props.uniqueChips && this.props.value.indexOf(value) !== -1) {
      this.setState({value: ""});
      return;
    }
    let chips = [...this.props.value, value]
    this.props.onChange(chips);
    this.setState({ value: "" })
  }

  removeChip = idx => () => {
    let left = this.props.value.slice(0, idx);
    let right = this.props.value.slice(idx + 1);
    const nextChips = [...left, ...right];
    this.props.onChange(nextChips);
  }

  renderChips = () => {
    return this.props.value.map((chip, idx) => {
      return (
        React.cloneElement(this.props.renderChip(chip), {
          selected: this.state.chipSelected && idx === this.props.value.length - 1,
          onRemove: this.removeChip(idx),
          index: idx,
          key: `chip${idx}`,
        })
      );
    });
  }

  filterUniqueChips = suggestions => {
    let { value, getChipValue, getSuggestionValue } = this.props;

    return suggestions
      .filter(suggestion => !value.some(chip => getChipValue(chip) == getSuggestionValue(suggestion)));
  }

  callFetchSuggestions = (fetchSuggestions, value, canceled) => {
    let { uniqueChips } = this.props;

    let callback = suggestions => {
      if(!canceled.isCancaled()){
        this.setState({
          loading: false,
          suggestions: (uniqueChips ? this.filterUniqueChips(suggestions) : suggestions)
        });
      }
    }

    let suggestionResult =
      fetchSuggestions.call(this, value, callback);

    if(suggestionResult && 'then' in suggestionResult){ // To Support Promises
      suggestionResult.then(callback);
    }
  }

  onSuggestionsFetchRequested = ({ value }) => {
    let { uniqueChips, suggestions, fetchSuggestions, suggestionsFilter } = this.props;

    if( fetchSuggestions ){
      this.setState({loading: true});

      this.asyncSuggestLimiter.invoke(fetchSuggestions, value);
    } else {
      this.setState({
        suggestions: (uniqueChips ? this.filterUniqueChips(suggestions) : suggestions).filter(opts => suggestionsFilter(opts, value))
      });
    }
  }

  onSuggestionsClearRequested = () => {
    this.setState({suggestions: []})
  }

  onSuggestionSelected = (e, { suggestion }) => {
    this.lastEvent = e;
    this.addChip(suggestion);
    this.setState({ value: '' });
  }

  onChange = (e, { newValue }) => {
    if (!this.props.fromSuggestionsOnly && newValue.indexOf(',') !== -1 && this.props.createChipKeys.includes(9)) {
      let chips = newValue.split(",").map((val) => val.trim()).filter((val) => val !== "");
      chips.forEach(chip => {
        this.addChip(chip)
      });
    } else {
      this.setState({value: newValue});
    }
  }

  render() {

    const { loading, value, suggestions } = this.state;
    const { placeholder, renderLoading } = this.props;
    const themr = themeable(this.props.theme);

    const inputProps = {
      placeholder,
      value,
      onChange: this.onChange,
      onKeyDown: this.handleKeyDown,
      onBlur: this.onBlur,
      onFocus: this.onFocus
    };

    return (

        {this.renderChips()}
        <Autosuggest
          {...this.props}
          theme={this.props.theme}
          suggestions={this.state.suggestions}
          onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
          onSuggestionsClearRequested={this.onSuggestionsClearRequested}
          getSuggestionValue={val => this.state.value}
          inputProps={inputProps}
          onSuggestionSelected={this.onSuggestionSelected}
        />
        { loading ? renderLoading() : null }

    );
  }
}

Chips.propTypes = {
  value: PropTypes.array.isRequired,
  onChange: PropTypes.func,
  placeholder: PropTypes.string,
  theme: PropTypes.object,
  chipTheme: PropTypes.object,
  suggestions: PropTypes.array,
  fetchSuggestions: PropTypes.func,
  fetchSuggestionsThrushold: PropTypes.number,
  fromSuggestionsOnly: PropTypes.bool,
  uniqueChips: PropTypes.bool,
  renderChip: PropTypes.func,
  suggestionsFilter: PropTypes.func,
  getChipValue: PropTypes.func,
  createChipKeys: PropTypes.array,
  getSuggestionValue: PropTypes.func,
  renderSuggestion: PropTypes.func,
  shouldRenderSuggestions: PropTypes.func,
  alwaysRenderSuggestions: PropTypes.bool,
  highlightFirstSuggestion: PropTypes.bool,
  focusInputOnSuggestionClick: PropTypes.bool,
  multiSection: PropTypes.bool,
  renderSectionTitle: PropTypes.func,
  getSectionSuggestions: PropTypes.func,
};

Chips.defaultProps = {
  placeholder: '',
  theme: theme,
  chipTheme: chipTheme,
  suggestions: [],
  fetchSuggestions: null,
  fetchSuggestionsThrushold: 10,
  createChipKeys: [9],
  fromSuggestionsOnly: false,
  uniqueChips: true,
  getSuggestionValue: s => s,
  value: [],
  onChange: () => {},
  renderChip: (value) => (<Chip chipTheme={this.props.chipTheme}>{value}</Chip>),
  renderLoading: () => (Loading...),
  renderSuggestion: (suggestion, { query }) => {suggestion},
  suggestionsFilter: (opt, val) => opt.toLowerCase().indexOf(val.toLowerCase()) !== -1,
  getChipValue: (item) => item,
};

export default Radium(Chips);
<commit_msg>removed props reference from defaultProps<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Autosuggest from 'react-autosuggest';
import Radium from 'radium';
import themeable from 'react-themeable';

import theme from './theme';
import Chip from './Chip';
import CallLimiter from './CallLimiter';
import { chipTheme } from './theme'

class Chips extends Component {

  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      value: "",
      chipSelected: false,
      suggestions: []
    };

    this.asyncSuggestLimiter =
      new CallLimiter(this.callFetchSuggestions.bind(this), 1000 / props.fetchSuggestionsThrushold);
  }

  componentWillReceiveProps = (nextProps) => {
    this.asyncSuggestLimiter.interval = (1000 / nextProps.fetchSuggestionsThrushold);
  }

  onBlur = e => {
    this.refs.wrapper.focus();
  }

  onFocus = e => {
    this.refs.wrapper.blur();
  }

  handleKeyDown = e => {
    if (e.keyCode === 13 && this.lastEvent === e) {
      this.lastEvent = null;
      return;
    }
    if (!this.props.fromSuggestionsOnly && (this.props.createChipKeys.includes(e.keyCode) || this.props.createChipKeys.includes(e.key))) {
      e.preventDefault();
      if (this.state.value.trim()) this.addChip(this.state.value);
    }
    if (e.keyCode === 8) {
      this.onBackspace();
    } else if (this.state.chipSelected) {
      this.setState({chipSelected: false});
    }
  }

  onBackspace = (code) => {
    if (this.state.value === "" && this.props.value.length > 0) {
      if (this.state.chipSelected) {
        const nextChips = this.props.value.slice(0, -1);
        this.setState({
          chipSelected: false,
          chips: nextChips,
        });
        this.props.onChange(nextChips);
      } else {
        this.setState({chipSelected: true})
      }
    }
  }

  addChip = (value) => {
    if (this.props.uniqueChips && this.props.value.indexOf(value) !== -1) {
      this.setState({value: ""});
      return;
    }
    let chips = [...this.props.value, value]
    this.props.onChange(chips);
    this.setState({ value: "" })
  }

  removeChip = idx => () => {
    let left = this.props.value.slice(0, idx);
    let right = this.props.value.slice(idx + 1);
    const nextChips = [...left, ...right];
    this.props.onChange(nextChips);
  }

  renderChips = () => {
    return this.props.value.map((chip, idx) => {
      return (
        React.cloneElement(this.props.renderChip(chip, this.props.chipTheme), {
          selected: this.state.chipSelected && idx === this.props.value.length - 1,
          onRemove: this.removeChip(idx),
          index: idx,
          key: `chip${idx}`,
        })
      );
    });
  }

  filterUniqueChips = suggestions => {
    let { value, getChipValue, getSuggestionValue } = this.props;

    return suggestions
      .filter(suggestion => !value.some(chip => getChipValue(chip) == getSuggestionValue(suggestion)));
  }

  callFetchSuggestions = (fetchSuggestions, value, canceled) => {
    let { uniqueChips } = this.props;

    let callback = suggestions => {
      if(!canceled.isCancaled()){
        this.setState({
          loading: false,
          suggestions: (uniqueChips ? this.filterUniqueChips(suggestions) : suggestions)
        });
      }
    }

    let suggestionResult =
      fetchSuggestions.call(this, value, callback);

    if(suggestionResult && 'then' in suggestionResult){ // To Support Promises
      suggestionResult.then(callback);
    }
  }

  onSuggestionsFetchRequested = ({ value }) => {
    let { uniqueChips, suggestions, fetchSuggestions, suggestionsFilter } = this.props;

    if( fetchSuggestions ){
      this.setState({loading: true});

      this.asyncSuggestLimiter.invoke(fetchSuggestions, value);
    } else {
      this.setState({
        suggestions: (uniqueChips ? this.filterUniqueChips(suggestions) : suggestions).filter(opts => suggestionsFilter(opts, value))
      });
    }
  }

  onSuggestionsClearRequested = () => {
    this.setState({suggestions: []})
  }

  onSuggestionSelected = (e, { suggestion }) => {
    this.lastEvent = e;
    this.addChip(suggestion);
    this.setState({ value: '' });
  }

  onChange = (e, { newValue }) => {
    if (!this.props.fromSuggestionsOnly && newValue.indexOf(',') !== -1 && this.props.createChipKeys.includes(9)) {
      let chips = newValue.split(",").map((val) => val.trim()).filter((val) => val !== "");
      chips.forEach(chip => {
        this.addChip(chip)
      });
    } else {
      this.setState({value: newValue});
    }
  }

  render() {

    const { loading, value, suggestions } = this.state;
    const { placeholder, renderLoading } = this.props;
    const themr = themeable(this.props.theme);

    const inputProps = {
      placeholder,
      value,
      onChange: this.onChange,
      onKeyDown: this.handleKeyDown,
      onBlur: this.onBlur,
      onFocus: this.onFocus
    };

    return (

        {this.renderChips()}
        <Autosuggest
          {...this.props}
          theme={this.props.theme}
          suggestions={this.state.suggestions}
          onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
          onSuggestionsClearRequested={this.onSuggestionsClearRequested}
          getSuggestionValue={val => this.state.value}
          inputProps={inputProps}
          onSuggestionSelected={this.onSuggestionSelected}
        />
        { loading ? renderLoading() : null }

    );
  }
}

Chips.propTypes = {
  value: PropTypes.array.isRequired,
  onChange: PropTypes.func,
  placeholder: PropTypes.string,
  theme: PropTypes.object,
  chipTheme: PropTypes.object,
  suggestions: PropTypes.array,
  fetchSuggestions: PropTypes.func,
  fetchSuggestionsThrushold: PropTypes.number,
  fromSuggestionsOnly: PropTypes.bool,
  uniqueChips: PropTypes.bool,
  renderChip: PropTypes.func,
  suggestionsFilter: PropTypes.func,
  getChipValue: PropTypes.func,
  createChipKeys: PropTypes.array,
  getSuggestionValue: PropTypes.func,
  renderSuggestion: PropTypes.func,
  shouldRenderSuggestions: PropTypes.func,
  alwaysRenderSuggestions: PropTypes.bool,
  highlightFirstSuggestion: PropTypes.bool,
  focusInputOnSuggestionClick: PropTypes.bool,
  multiSection: PropTypes.bool,
  renderSectionTitle: PropTypes.func,
  getSectionSuggestions: PropTypes.func,
};

Chips.defaultProps = {
  placeholder: '',
  theme: theme,
  chipTheme: chipTheme,
  suggestions: [],
  fetchSuggestions: null,
  fetchSuggestionsThrushold: 10,
  createChipKeys: [9],
  fromSuggestionsOnly: false,
  uniqueChips: true,
  getSuggestionValue: s => s,
  value: [],
  onChange: () => {},
  renderChip: (value, chipTheme) => (<Chip chipTheme={chipTheme}>{value}</Chip>),
  renderLoading: () => (Loading...),
  renderSuggestion: (suggestion, { query }) => {suggestion},
  suggestionsFilter: (opt, val) => opt.toLowerCase().indexOf(val.toLowerCase()) !== -1,
  getChipValue: (item) => item,
};

export default Radium(Chips);
<|endoftext|>


<commit_before>import minify from '../packages/core/src/core';
import { filesJS, filesCSS, filesHTML } from './files-path';

const runOneTest = ({ options, compressorLabel, compressor, sync }) => {
  options = JSON.parse(JSON.stringify(options));

  options.minify.compressor = compressor;

  if (sync) {
    options.minify.sync = true;
  }

  test(options.it.replace('{compressor}', compressorLabel), done => {
    return new Promise(resolve => {
      options.minify.callback = (err, min) => {
        done();
        resolve(err, min);
      };

      minify(options.minify);
    }).then((err, min) => {
      done();
      expect(err).toBeNull();
      expect(min).not.toBeNull();
    });
  });
};

const tests = {
  concat: [
    {
      it: 'should concat javascript and no compress and an array of file',
      minify: {
        input: filesJS.filesArray,
        output: filesJS.fileJSOut
      }
    },
    {
      it: 'should concat javascript and no compress and a single file',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut
      }
    }
  ],
  commoncss: [
    {
      it: 'should compress css with {compressor} and a single file',
      minify: {
        input: filesCSS.fileCSS,
        output: filesCSS.fileCSSOut,
        type: 'css'
      }
    },
    {
      it: 'should compress css with {compressor} and a single file with a custom public folder',
      minify: {
        input: filesCSS.fileCSSWithoutPath,
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    },
    {
      it: 'should compress css with {compressor} and a single file with a custom public folder and full path',
      minify: {
        input: filesCSS.fileCSS,
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    },
    {
      it: 'should compress css with {compressor} and a single file with a custom buffer size',
      minify: {
        input: filesCSS.fileCSS,
        output: filesCSS.fileCSSOut,
        type: 'css',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress css with {compressor} and a single file with some options',
      minify: {
        input: filesCSS.fileCSS,
        output: filesCSS.fileCSSOut,
        type: 'css',
        options: {
          charset: 'utf8'
        }
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file',
      minify: {
        input: filesCSS.fileCSSArray,
        output: filesCSS.fileCSSOut,
        type: 'css'
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file with a custom public folder',
      minify: {
        input: filesCSS.fileCSSArrayWithoutPath,
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file with a custom buffer size',
      minify: {
        input: filesCSS.fileCSSArray,
        output: filesCSS.fileCSSOut,
        type: 'css',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress css with {compressor} and wildcards path',
      minify: {
        input: filesCSS.fileCSSWithWildcards,
        output: filesCSS.fileCSSOut,
        type: 'css'
      }
    },
    {
      it: 'should compress css with {compressor} and wildcards path with a custom public folder',
      minify: {
        input: '**/*.css',
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    },
    {
      it: 'should compress css with {compressor} and wildcards path with a custom buffer size',
      minify: {
        input: filesCSS.fileCSSWithWildcards,
        output: filesCSS.fileCSSOut,
        type: 'css',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress css with {compressor} and an array of strings and wildcards path',
      minify: {
        input: filesCSS.fileCSSArrayWithWildcards2,
        output: filesCSS.fileCSSOut,
        type: 'css'
      }
    },
    {
      it:
        'should compress css with {compressor} and an array of strings and wildcards path' +
        ' with a custom public folder',
      minify: {
        input: filesCSS.fileCSSArrayWithWildcards,
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    }
  ],
  commonjs: [
    {
      it: 'should compress javascript with {compressor} and a single file',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file and output $1',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOutReplace
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom public folder',
      minify: {
        input: filesJS.oneFileWithoutPath,
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom public folder and full path',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom buffer size',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with empty options',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        options: {}
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file',
      minify: {
        input: filesJS.filesArray,
        output: filesJS.fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file and output $1',
      minify: {
        input: filesJS.filesArray,
        output: filesJS.fileJSOutReplace
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file with a custom public folder',
      minify: {
        input: filesJS.filesArrayWithoutPath,
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file with a custom buffer size',
      minify: {
        input: filesJS.filesArray,
        output: filesJS.fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path with a custom public folder',
      minify: {
        input: '**/*.js',
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path with a custom buffer size',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of strings and wildcards path',
      minify: {
        input: filesJS.filesArrayWithWildcards2,
        output: filesJS.fileJSOut
      }
    },
    {
      it:
        'should compress javascript with {compressor} and an array of strings and wildcards path' +
        ' with a custom public folder',
      minify: {
        input: filesJS.filesArrayWithWildcards,
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    }
  ],
  babelMinify: [
    {
      it: 'should compress javascript with {compressor} and a single file with a babelrc',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        options: {
          babelrc: filesJS.babelrc
        }
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a preset',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        options: {
          presets: ['env']
        }
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a babelrc and preset',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        options: {
          babelrc: filesJS.babelrc,
          presets: ['env']
        }
      }
    },
    {
      it: 'should compress with {compressor} and some options',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut,
        options: {
          charset: 'utf8'
        }
      }
    }
  ],
  uglifyjs: [
    {
      it: 'should create a source map with {compressor}',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut,
        options: {
          sourceMap: {
            filename: `${filesJS.fileJSOut}.map`,
            url: `${filesJS.fileJSOut}.map`
          }
        }
      }
    },
    {
      it: 'should compress with some options with {compressor}',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut,
        options: {
          mangle: false
        }
      }
    }
  ],
  commonhtml: [
    {
      it: 'should compress html with {compressor} and a single file',
      minify: {
        input: filesHTML.oneFileHTML,
        output: filesHTML.fileHTMLOut
      }
    },
    {
      it: 'should compress html with {compressor} and a single file with a custom public folder',
      minify: {
        input: filesHTML.oneFileHTMLWithoutPath,
        output: filesHTML.fileHTMLOut,
        publicFolder: filesHTML.publicFolderHTML
      }
    },
    {
      it: 'should compress html with {compressor} and a single file with empty options',
      minify: {
        input: filesHTML.oneFileHTML,
        output: filesHTML.fileHTMLOut,
        options: {}
      }
    },
    {
      it: 'should compress html with {compressor} and an array of file',
      minify: {
        input: filesHTML.filesHTMLArray,
        output: filesHTML.fileHTMLOut
      }
    },
    {
      it: 'should compress html with {compressor} and an array of file with a custom public folder',
      minify: {
        input: filesHTML.filesHTMLArrayWithoutPath,
        output: filesHTML.fileHTMLOut,
        publicFolder: filesHTML.publicFolderHTML
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path',
      minify: {
        input: filesHTML.fileHTMLWithWildcards,
        output: filesHTML.fileHTMLOut
      }
    },
    {
      it: 'should compress html with {compressor} and wildcards path with a custom public folder',
      minify: {
        input: '**/*.html',
        output: filesHTML.fileHTMLOut,
        publicFolder: filesHTML.publicFolderHTML
      }
    },
    {
      it: 'should compress html with {compressor} and an array of strings and wildcards path',
      minify: {
        input: filesHTML.filesHTMLArrayWithWildcards,
        output: filesHTML.fileHTMLOut
      }
    },
    {
      it:
        'should compress html with {compressor} and an array of strings and wildcards path' +
        ' with a custom public folder',
      minify: {
        input: filesHTML.filesHTMLArrayWithWildcards2,
        output: filesHTML.fileHTMLOut,
        publicFolder: filesHTML.publicFolderHTML
      }
    }
  ]
};

export { runOneTest, tests };
<commit_msg>Revert "tests(cssnano): fix cssnano timeout"<commit_after>import minify from '../packages/core/src/core';
import { filesJS, filesCSS, filesHTML } from './files-path';

const runOneTest = ({ options, compressorLabel, compressor, sync }) => {
  options = JSON.parse(JSON.stringify(options));

  options.minify.compressor = compressor;

  if (sync) {
    options.minify.sync = true;
  }

  test(options.it.replace('{compressor}', compressorLabel), () => {
    return new Promise(resolve => {
      options.minify.callback = (err, min) => {
        resolve(err, min);
      };

      minify(options.minify);
    }).then((err, min) => {
      expect(err).toBeNull();
      expect(min).not.toBeNull();
    });
  });
};

const tests = {
  concat: [
    {
      it: 'should concat javascript and no compress and an array of file',
      minify: {
        input: filesJS.filesArray,
        output: filesJS.fileJSOut
      }
    },
    {
      it: 'should concat javascript and no compress and a single file',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut
      }
    }
  ],
  commoncss: [
    {
      it: 'should compress css with {compressor} and a single file',
      minify: {
        input: filesCSS.fileCSS,
        output: filesCSS.fileCSSOut,
        type: 'css'
      }
    },
    {
      it: 'should compress css with {compressor} and a single file with a custom public folder',
      minify: {
        input: filesCSS.fileCSSWithoutPath,
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    },
    {
      it: 'should compress css with {compressor} and a single file with a custom public folder and full path',
      minify: {
        input: filesCSS.fileCSS,
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    },
    {
      it: 'should compress css with {compressor} and a single file with a custom buffer size',
      minify: {
        input: filesCSS.fileCSS,
        output: filesCSS.fileCSSOut,
        type: 'css',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress css with {compressor} and a single file with some options',
      minify: {
        input: filesCSS.fileCSS,
        output: filesCSS.fileCSSOut,
        type: 'css',
        options: {
          charset: 'utf8'
        }
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file',
      minify: {
        input: filesCSS.fileCSSArray,
        output: filesCSS.fileCSSOut,
        type: 'css'
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file with a custom public folder',
      minify: {
        input: filesCSS.fileCSSArrayWithoutPath,
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    },
    {
      it: 'should compress css with {compressor} and an array of file with a custom buffer size',
      minify: {
        input: filesCSS.fileCSSArray,
        output: filesCSS.fileCSSOut,
        type: 'css',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress css with {compressor} and wildcards path',
      minify: {
        input: filesCSS.fileCSSWithWildcards,
        output: filesCSS.fileCSSOut,
        type: 'css'
      }
    },
    {
      it: 'should compress css with {compressor} and wildcards path with a custom public folder',
      minify: {
        input: '**/*.css',
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    },
    {
      it: 'should compress css with {compressor} and wildcards path with a custom buffer size',
      minify: {
        input: filesCSS.fileCSSWithWildcards,
        output: filesCSS.fileCSSOut,
        type: 'css',
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress css with {compressor} and an array of strings and wildcards path',
      minify: {
        input: filesCSS.fileCSSArrayWithWildcards2,
        output: filesCSS.fileCSSOut,
        type: 'css'
      }
    },
    {
      it:
        'should compress css with {compressor} and an array of strings and wildcards path' +
        ' with a custom public folder',
      minify: {
        input: filesCSS.fileCSSArrayWithWildcards,
        output: filesCSS.fileCSSOut,
        type: 'css',
        publicFolder: filesCSS.publicFolderCSS
      }
    }
  ],
  commonjs: [
    {
      it: 'should compress javascript with {compressor} and a single file',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file and output $1',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOutReplace
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom public folder',
      minify: {
        input: filesJS.oneFileWithoutPath,
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom public folder and full path',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a custom buffer size',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with empty options',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        options: {}
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file',
      minify: {
        input: filesJS.filesArray,
        output: filesJS.fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file and output $1',
      minify: {
        input: filesJS.filesArray,
        output: filesJS.fileJSOutReplace
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file with a custom public folder',
      minify: {
        input: filesJS.filesArrayWithoutPath,
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of file with a custom buffer size',
      minify: {
        input: filesJS.filesArray,
        output: filesJS.fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path with a custom public folder',
      minify: {
        input: '**/*.js',
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path with a custom buffer size',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut,
        buffer: 2000 * 1024
      }
    },
    {
      it: 'should compress javascript with {compressor} and an array of strings and wildcards path',
      minify: {
        input: filesJS.filesArrayWithWildcards2,
        output: filesJS.fileJSOut
      }
    },
    {
      it:
        'should compress javascript with {compressor} and an array of strings and wildcards path' +
        ' with a custom public folder',
      minify: {
        input: filesJS.filesArrayWithWildcards,
        output: filesJS.fileJSOut,
        publicFolder: filesJS.publicFolderES5
      }
    }
  ],
  babelMinify: [
    {
      it: 'should compress javascript with {compressor} and a single file with a babelrc',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        options: {
          babelrc: filesJS.babelrc
        }
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a preset',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        options: {
          presets: ['env']
        }
      }
    },
    {
      it: 'should compress javascript with {compressor} and a single file with a babelrc and preset',
      minify: {
        input: filesJS.oneFile,
        output: filesJS.fileJSOut,
        options: {
          babelrc: filesJS.babelrc,
          presets: ['env']
        }
      }
    },
    {
      it: 'should compress with {compressor} and some options',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut,
        options: {
          charset: 'utf8'
        }
      }
    }
  ],
  uglifyjs: [
    {
      it: 'should create a source map with {compressor}',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut,
        options: {
          sourceMap: {
            filename: `${filesJS.fileJSOut}.map`,
            url: `${filesJS.fileJSOut}.map`
          }
        }
      }
    },
    {
      it: 'should compress with some options with {compressor}',
      minify: {
        input: filesJS.oneFileWithWildcards,
        output: filesJS.fileJSOut,
        options: {
          mangle: false
        }
      }
    }
  ],
  commonhtml: [
    {
      it: 'should compress html with {compressor} and a single file',
      minify: {
        input: filesHTML.oneFileHTML,
        output: filesHTML.fileHTMLOut
      }
    },
    {
      it: 'should compress html with {compressor} and a single file with a custom public folder',
      minify: {
        input: filesHTML.oneFileHTMLWithoutPath,
        output: filesHTML.fileHTMLOut,
        publicFolder: filesHTML.publicFolderHTML
      }
    },
    {
      it: 'should compress html with {compressor} and a single file with empty options',
      minify: {
        input: filesHTML.oneFileHTML,
        output: filesHTML.fileHTMLOut,
        options: {}
      }
    },
    {
      it: 'should compress html with {compressor} and an array of file',
      minify: {
        input: filesHTML.filesHTMLArray,
        output: filesHTML.fileHTMLOut
      }
    },
    {
      it: 'should compress html with {compressor} and an array of file with a custom public folder',
      minify: {
        input: filesHTML.filesHTMLArrayWithoutPath,
        output: filesHTML.fileHTMLOut,
        publicFolder: filesHTML.publicFolderHTML
      }
    },
    {
      it: 'should compress javascript with {compressor} and wildcards path',
      minify: {
        input: filesHTML.fileHTMLWithWildcards,
        output: filesHTML.fileHTMLOut
      }
    },
    {
      it: 'should compress html with {compressor} and wildcards path with a custom public folder',
      minify: {
        input: '**/*.html',
        output: filesHTML.fileHTMLOut,
        publicFolder: filesHTML.publicFolderHTML
      }
    },
    {
      it: 'should compress html with {compressor} and an array of strings and wildcards path',
      minify: {
        input: filesHTML.filesHTMLArrayWithWildcards,
        output: filesHTML.fileHTMLOut
      }
    },
    {
      it:
        'should compress html with {compressor} and an array of strings and wildcards path' +
        ' with a custom public folder',
      minify: {
        input: filesHTML.filesHTMLArrayWithWildcards2,
        output: filesHTML.fileHTMLOut,
        publicFolder: filesHTML.publicFolderHTML
      }
    }
  ]
};

export { runOneTest, tests };
<|endoftext|>


<commit_before>import React, { Component } from 'react';

class Fetch extends Component {
  state = {
    fetch: this.fetch.bind(this),
    loading: null
  };
  cache = {};

  componentDidMount() {
    this.mounted = true;
    if (this.props.url && !this.props.manual) {
      this.fetch();
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.url !== prevProps.url && !this.props.manual) {
      this.fetch();
    }
  }

  componentWillUnmount() {
    this.mounted = false;
  }

  fetch() {
    let { url, options, as='json', cache } = this.props;

    if (cache && this.cache[url]) {
      // Restore cached state
      this.promise = this.cache[url];
      this.promise.then(cachedState => this.setStateIfMounted({
        request: { ...this.props },
        ...cachedState
      }));
    } else {
      this.setStateIfMounted({
        loading: true,
        request: { ...this.props },
      });

      this.promise = fetch(url, options)
        .then(response => {
          return response[as]()
            .then(data   => ({ response, data }))
            .catch(error => ({ response, data: error }))
        })
        .then(({ response, data }) => {
          const newState = {
            loading: false,
            [response.ok ? 'error' : 'data' ]: undefined, // Clear last response
            [response.ok ? 'data'  : 'error']: data,
            response
          }

          this.setStateIfMounted(newState);
          return newState;
        })
        .catch(error => {
          // Catch request errors with no response (CORS issues, etc)
          const newState = {
            data: undefined,
            error,
            loading: false
          }
          this.setStateIfMounted(newState)
          return newState
        });

      if (cache) {
        this.cache[url] = this.promise;
      }
    }
  }

  setStateIfMounted(nextState, callback) {
    // Ignore passing state down if no longer mounted
    if (this.mounted) {
      this.setState(nextState, callback);
    }
  }

  render() {
    return this.props.children(this.state);
  }
}

export default Fetch;<commit_msg>Destructure props<commit_after>import React, { Component } from 'react';

class Fetch extends Component {
  state = {
    fetch: this.fetch.bind(this),
    loading: null
  };
  cache = {};

  componentDidMount() {
    const { url, manual, onChange } = this.props;
    this.mounted = true;
    if (url && !manual) {
      this.fetch();
    }
  }

  componentDidUpdate(prevProps) {
    const { url, manual } = this.props;
    if (url !== prevProps.url && !manual) {
      this.fetch();
    }
  }

  componentWillUnmount() {
    this.mounted = false;
  }

  fetch() {
    let { url, options, as='json', cache } = this.props;

    if (cache && this.cache[url]) {
      // Restore cached state
      this.promise = this.cache[url];
      this.promise.then(cachedState => this.setStateIfMounted({
        request: { ...this.props },
        ...cachedState
      }));
    } else {
      this.setStateIfMounted({
        loading: true,
        request: { ...this.props },
      });

      this.promise = fetch(url, options)
        .then(response => {
          return response[as]()
            .then(data   => ({ response, data }))
            .catch(error => ({ response, data: error }))
        })
        .then(({ response, data }) => {
          const newState = {
            loading: false,
            [response.ok ? 'error' : 'data' ]: undefined, // Clear last response
            [response.ok ? 'data'  : 'error']: data,
            response
          }

          this.setStateIfMounted(newState);
          return newState;
        })
        .catch(error => {
          // Catch request errors with no response (CORS issues, etc)
          const newState = {
            data: undefined,
            error,
            loading: false
          }
          this.setStateIfMounted(newState)
          return newState
        });

      if (cache) {
        this.cache[url] = this.promise;
      }
    }
  }

  setStateIfMounted(nextState, callback) {
    // Ignore passing state down if no longer mounted
    if (this.mounted) {
      this.setState(nextState, callback);
    }
  }

  render() {
    return this.props.children(this.state);
  }
}

export default Fetch;<|endoftext|>


<commit_before>exports.config = {

  specs: [
    './scenarios/nodes-spec.js'
  ],

  capabilities: {
    'browserName': 'chrome'
  },

  baseUrl: 'http://192.168.1.207/ebikko-angular',

  framework: 'jasmine'
};
<commit_msg>Added all scenarios to e2e tests<commit_after>exports.config = {

  specs: [
    './scenarios/*.js'
  ],

  capabilities: {
    'browserName': 'chrome'
  },

  baseUrl: 'http://192.168.1.207/ebikko-angular',

  framework: 'jasmine'
};
<|endoftext|>


<commit_before>/*
Show that promise chaining takes priority over setImmediate().

*/

setImmediate(() => {
  console.log('Inside setImmediate callback')
})

Promise.resolve(1)
.then(value => {
  console.log(value)
  return 2
})
.then(value => {
  console.log(value)
  return 3
})
.then(value => {
  console.log(value)
  return 42
})
.then(value => {
  console.log(`Final value ${value}`)
})
<commit_msg>Use much longer promise chain<commit_after>/*
Show that promise chaining takes priority over setImmediate().

Note that calling setImmediate() once in the middle of the chain will allow the
first setImmediate() callback to run before the chain finishes.
*/

setImmediate(() => {
  // You won't see this until the rest of the program has completed.
  console.log('Inside setImmediate callback')
})

let promise = Promise.resolve(1)
for (let i=2; i < 1000; i++) {
  promise = promise.then(value => {
    console.log(value)
    // if (i === 970) {
    //   return new Promise(resolve => setImmediate(resolve, i))
    // }
    return i
  })
}
promise.then(value => {
  console.log(`Final value ${value}`)
})
<|endoftext|>


<commit_before>(function() {
  var Human = {
    choiceSpot: function(e, board, currentPlayer) {
      var chosenSpot;
      chosenSpot = e.target.id;
      if ($("#" + chosenSpot).text() == "") {
        this.markChosenSpot(board, chosenSpot, currentPlayer);
      }
      else {
        UI.spotErrorMessage();
        this.choiceSpot(e, board, currentPlayer);
      }
    },

    markChosenSpot: function(board, chosenSpot, currentPlayer) {
      $("#" + chosenSpot).text(currentPlayer);
      board.spots[chosenSpot] = currentPlayer;
    }
  };
  window.Human = Human;
})();
<commit_msg>delete duplication declare<commit_after>(function() {
  var Human = {
    choiceSpot: function(e, board, currentPlayer) {
      var chosenSpot = e.target.id;
      if ($("#" + chosenSpot).text() == "") {
        this.markChosenSpot(board, chosenSpot, currentPlayer);
      }
      else {
        UI.spotErrorMessage();
        this.choiceSpot(e, board, currentPlayer);
      }
    },

    markChosenSpot: function(board, chosenSpot, currentPlayer) {
      $("#" + chosenSpot).text(currentPlayer);
      board.spots[chosenSpot] = currentPlayer;
    }
  };
  window.Human = Human;
})();
<|endoftext|>


<commit_before>module.exports = {
  BarChart: require('./components/BarChart'),
  Button: require('./components/Button'),
  ButtonGroup: require('./components/ButtonGroup'),
  Calendar: require('./components/Calendar'),
  Column: require('./components/grid/Column'),
  Container: require('./components/grid/Container'),
  DatePicker: require('./components/DatePicker'),
  DatePickerFullScreen: require('./components/DatePickerFullScreen'),
  DateRangePicker: require('./components/DateRangePicker'),
  DateTimePicker: require('./components/DateTimePicker'),
  DisplayInput: require('./components/DisplayInput'),
  DonutChart: require('./components/DonutChart'),
  Drawer: require('./components/Drawer'),
  FileUpload: require('./components/FileUpload'),
  Gauge: require('./components/Gauge'),
  Icon: require('./components/Icon'),
  Loader: require('./components/Loader'),
  Menu: require('./components/Menu'),
  Modal: require('./components/Modal'),
  PageIndicator: require('./components/PageIndicator'),
  ProgressBar: require('./components/ProgressBar'),
  RadioButton: require('./components/RadioButton'),
  RajaIcon: require('./components/RajaIcon'),
  Row: require('./components/grid/Row'),
  RangeSelector: require('./components/RangeSelector'),
  SearchInput: require('./components/SearchInput'),
  Select: require('./components/Select'),
  SelectFullScreen: require('./components/SelectFullScreen'),
  SimpleInput: require('./components/SimpleInput'),
  SimpleSelect: require('./components/SimpleSelect'),
  Spin: require('./components/Spin'),
  Tabs: require('./components/Tabs'),
  TextArea: require('./components/TextArea'),
  TimeBasedLineChart: require('./components/TimeBasedLineChart'),
  ToggleSwitch: require('./components/ToggleSwitch'),
  Tooltip: require('./components/Tooltip'),
  TypeAhead: require('./components/TypeAhead'),

  // D3 components
  AxisGroup: require('./components/d3/AxisGroup'),
  BreakPointGroup: require('./components/d3/BreakPointGroup'),
  CirclesGroup: require('./components/d3/CirclesGroup'),
  GridLinesGroup: require('./components/d3/GridLinesGroup'),
  LineGroup: require('./components/d3/LineGroup'),
  ShadedAreaRectangleGroup: require('./components/d3/ShadedAreaRectangleGroup'),
  ShadedHatchPatternRectangleGroup: require('./components/d3/ShadedHatchPatternRectangleGroup'),
  SlicesGroup: require('./components/d3/SlicesGroup'),
  TimeXAxisGroup: require('./components/d3/TimeXAxisGroup'),

  AppConstants: require('./constants/App'),
  Styles: require('./constants/Style')
};
<commit_msg>Adds comment for App constants section<commit_after>module.exports = {
  BarChart: require('./components/BarChart'),
  Button: require('./components/Button'),
  ButtonGroup: require('./components/ButtonGroup'),
  Calendar: require('./components/Calendar'),
  Column: require('./components/grid/Column'),
  Container: require('./components/grid/Container'),
  DatePicker: require('./components/DatePicker'),
  DatePickerFullScreen: require('./components/DatePickerFullScreen'),
  DateRangePicker: require('./components/DateRangePicker'),
  DateTimePicker: require('./components/DateTimePicker'),
  DisplayInput: require('./components/DisplayInput'),
  DonutChart: require('./components/DonutChart'),
  Drawer: require('./components/Drawer'),
  FileUpload: require('./components/FileUpload'),
  Gauge: require('./components/Gauge'),
  Icon: require('./components/Icon'),
  Loader: require('./components/Loader'),
  Menu: require('./components/Menu'),
  Modal: require('./components/Modal'),
  PageIndicator: require('./components/PageIndicator'),
  ProgressBar: require('./components/ProgressBar'),
  RadioButton: require('./components/RadioButton'),
  RajaIcon: require('./components/RajaIcon'),
  Row: require('./components/grid/Row'),
  RangeSelector: require('./components/RangeSelector'),
  SearchInput: require('./components/SearchInput'),
  Select: require('./components/Select'),
  SelectFullScreen: require('./components/SelectFullScreen'),
  SimpleInput: require('./components/SimpleInput'),
  SimpleSelect: require('./components/SimpleSelect'),
  Spin: require('./components/Spin'),
  Tabs: require('./components/Tabs'),
  TextArea: require('./components/TextArea'),
  TimeBasedLineChart: require('./components/TimeBasedLineChart'),
  ToggleSwitch: require('./components/ToggleSwitch'),
  Tooltip: require('./components/Tooltip'),
  TypeAhead: require('./components/TypeAhead'),

  // D3 components
  AxisGroup: require('./components/d3/AxisGroup'),
  BreakPointGroup: require('./components/d3/BreakPointGroup'),
  CirclesGroup: require('./components/d3/CirclesGroup'),
  GridLinesGroup: require('./components/d3/GridLinesGroup'),
  LineGroup: require('./components/d3/LineGroup'),
  ShadedAreaRectangleGroup: require('./components/d3/ShadedAreaRectangleGroup'),
  ShadedHatchPatternRectangleGroup: require('./components/d3/ShadedHatchPatternRectangleGroup'),
  SlicesGroup: require('./components/d3/SlicesGroup'),
  TimeXAxisGroup: require('./components/d3/TimeXAxisGroup'),

  // App constants
  AppConstants: require('./constants/App'),
  Styles: require('./constants/Style')
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import { PHASE_START_EVENT_TYPE, PHASE_END_EVENT_TYPE } from 'common/fabricateBossPhaseEvents';
import { captureException } from 'common/errorLogger';
import { findByBossId } from 'raids';

import { EventsParseError } from './EventParser';

export const SELECTION_ALL_PHASES = "ALL";

class PhaseParser extends React.PureComponent {
  static propTypes = {
    report: PropTypes.shape({
      title: PropTypes.string.isRequired,
      code: PropTypes.string.isRequired,
    }).isRequired,
    fight: PropTypes.shape({
      start_time: PropTypes.number.isRequired,
      end_time: PropTypes.number.isRequired,
      boss: PropTypes.number.isRequired,
    }).isRequired,
    player: PropTypes.shape({
      name: PropTypes.string.isRequired,
      id: PropTypes.number.isRequired,
      guid: PropTypes.number.isRequired,
      type: PropTypes.string.isRequired,
    }).isRequired,
    phase: PropTypes.string.isRequired,
    combatants: PropTypes.arrayOf(PropTypes.shape({
      sourceID: PropTypes.number.isRequired,
    })),
    parserClass: PropTypes.func.isRequired,
    characterProfile: PropTypes.object,
    bossPhaseEvents: PropTypes.array,
    events: PropTypes.array.isRequired,
    children: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
    };
  }

  componentDidMount() {
    // noinspection JSIgnoredPromiseFromCall
    this.parse();
  }
  componentDidUpdate(prevProps, prevState, prevContext) {
    const changed = this.props.report !== prevProps.report
      || this.props.fight !== prevProps.fight
      || this.props.player !== prevProps.player
      || this.props.combatants !== prevProps.combatants
      || this.props.parserClass !== prevProps.parserClass
      || this.props.characterProfile !== prevProps.characterProfile
      || this.props.bossPhaseEvents !== prevProps.bossPhaseEvents
      || this.props.phase !== prevProps.phase
      || this.props.events !== prevProps.events;
    if (changed) {
      this.setState({
        isLoading: true,
      });
      // noinspection JSIgnoredPromiseFromCall
      this.parse();
    }
  }

  makePhases(){
    const { bossPhaseEvents, fight } = this.props;
    if(!bossPhaseEvents){
      return null;
    }
    const phaseStarts = [...new Set(bossPhaseEvents.filter(e => e.type === PHASE_START_EVENT_TYPE).map(e => e.phase.key))]; //distinct phase starts
    const phaseEnds = [...new Set(bossPhaseEvents.filter(e => e.type === PHASE_END_EVENT_TYPE).map(e => e.phase.key))]; //distinct phase ends
    const phaseKeys = phaseStarts.filter(e => phaseEnds.includes(e)); //only include phases that contain start and end event
    const bossPhases = findByBossId(fight.boss).fight.phases;
    return Object.keys(bossPhases)
    .filter(e => phaseKeys.includes(e)) //only include boss phases that have a valid phase key
    .reduce((obj, key) => {
      return {
        ...obj,
        [key]: bossPhases[key],
      };
    }, {});
  }

  makeEvents(phases) {
    const { bossPhaseEvents, events, phase } = this.props;
    const startEvent = bossPhaseEvents.find(e => e.type === PHASE_START_EVENT_TYPE && e.phase.key === phase);
    const endEvent = bossPhaseEvents.find(e => e.type === PHASE_END_EVENT_TYPE && e.phase.key === phase);
    if(!(bossPhaseEvents instanceof Array)
      || !(Object.keys(phases).includes(phase))
      || phase === SELECTION_ALL_PHASES
    ){
      return {start: this.props.fight.start_time, events: bossPhaseEvents ? [...bossPhaseEvents, ...events] : events, end: this.props.fight.end_time};
    }
    const phaseEvents = events.filter(event =>
        event.timestamp >= startEvent.timestamp
        && event.timestamp <= endEvent.timestamp
      );
      //TODO: find events before the phase that are relevant in this phase (aka cooldowns)
    return {start: startEvent.timestamp, events: [startEvent, ...phaseEvents, endEvent], end: endEvent.timestamp};
  }

  async parse() {
    try {
      const phases = this.makePhases();
      const eventFilter = this.makeEvents(phases);
      this.setState({
        phases: phases,
        events: eventFilter.events,
        fight: {
          start_time: eventFilter.start,
          end_time: eventFilter.end,
          boss: this.props.fight.boss,
        },
        isLoading: false,
      });
    } catch (err) {
      captureException(err);
      throw new EventsParseError(err);
    }

  }

  render() {
    return this.props.children(this.state.isLoading, this.state.phases, this.state.events, this.state.fight);
  }

}

export default PhaseParser;
<commit_msg>todo<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import { PHASE_START_EVENT_TYPE, PHASE_END_EVENT_TYPE } from 'common/fabricateBossPhaseEvents';
import { captureException } from 'common/errorLogger';
import { findByBossId } from 'raids';

import { EventsParseError } from './EventParser';

export const SELECTION_ALL_PHASES = "ALL";

class PhaseParser extends React.PureComponent {
  static propTypes = {
    report: PropTypes.shape({
      title: PropTypes.string.isRequired,
      code: PropTypes.string.isRequired,
    }).isRequired,
    fight: PropTypes.shape({
      start_time: PropTypes.number.isRequired,
      end_time: PropTypes.number.isRequired,
      boss: PropTypes.number.isRequired,
    }).isRequired,
    player: PropTypes.shape({
      name: PropTypes.string.isRequired,
      id: PropTypes.number.isRequired,
      guid: PropTypes.number.isRequired,
      type: PropTypes.string.isRequired,
    }).isRequired,
    phase: PropTypes.string.isRequired,
    combatants: PropTypes.arrayOf(PropTypes.shape({
      sourceID: PropTypes.number.isRequired,
    })),
    parserClass: PropTypes.func.isRequired,
    characterProfile: PropTypes.object,
    bossPhaseEvents: PropTypes.array,
    events: PropTypes.array.isRequired,
    children: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
    };
  }

  componentDidMount() {
    // noinspection JSIgnoredPromiseFromCall
    this.parse();
  }
  componentDidUpdate(prevProps, prevState, prevContext) {
    const changed = this.props.report !== prevProps.report
      || this.props.fight !== prevProps.fight
      || this.props.player !== prevProps.player
      || this.props.combatants !== prevProps.combatants
      || this.props.parserClass !== prevProps.parserClass
      || this.props.characterProfile !== prevProps.characterProfile
      || this.props.bossPhaseEvents !== prevProps.bossPhaseEvents
      || this.props.phase !== prevProps.phase
      || this.props.events !== prevProps.events;
    if (changed) {
      this.setState({
        isLoading: true,
      });
      // noinspection JSIgnoredPromiseFromCall
      this.parse();
    }
  }

  makePhases(){
    const { bossPhaseEvents, fight } = this.props;
    if(!bossPhaseEvents){
      return null;
    }
    const phaseStarts = [...new Set(bossPhaseEvents.filter(e => e.type === PHASE_START_EVENT_TYPE).map(e => e.phase.key))]; //distinct phase starts
    const phaseEnds = [...new Set(bossPhaseEvents.filter(e => e.type === PHASE_END_EVENT_TYPE).map(e => e.phase.key))]; //distinct phase ends
    const phaseKeys = phaseStarts.filter(e => phaseEnds.includes(e)); //only include phases that contain start and end event
    const bossPhases = findByBossId(fight.boss).fight.phases;
    return Object.keys(bossPhases)
    .filter(e => phaseKeys.includes(e)) //only include boss phases that have a valid phase key
    .reduce((obj, key) => {
      return {
        ...obj,
        [key]: bossPhases[key],
      };
    }, {});
  }

  makeEvents(phases) {
    const { bossPhaseEvents, events, phase } = this.props;
    const startEvent = bossPhaseEvents.find(e => e.type === PHASE_START_EVENT_TYPE && e.phase.key === phase);
    const endEvent = bossPhaseEvents.find(e => e.type === PHASE_END_EVENT_TYPE && e.phase.key === phase);
    if(!(bossPhaseEvents instanceof Array)
      || !(Object.keys(phases).includes(phase))
      || phase === SELECTION_ALL_PHASES
    ){
      return {start: this.props.fight.start_time, events: bossPhaseEvents ? [...bossPhaseEvents, ...events] : events, end: this.props.fight.end_time};
    }
    const phaseEvents = events.filter(event =>
        event.timestamp >= startEvent.timestamp
        && event.timestamp <= endEvent.timestamp
      );
      //TODO: find events before the phase that are relevant in this phase (aka cooldowns and buffs) and include them in analysis
    return {start: startEvent.timestamp, events: [startEvent, ...phaseEvents, endEvent], end: endEvent.timestamp};
  }

  async parse() {
    try {
      const phases = this.makePhases();
      const eventFilter = this.makeEvents(phases);
      this.setState({
        phases: phases,
        events: eventFilter.events,
        fight: {
          start_time: eventFilter.start,
          end_time: eventFilter.end,
          boss: this.props.fight.boss,
        },
        isLoading: false,
      });
    } catch (err) {
      captureException(err);
      throw new EventsParseError(err);
    }

  }

  render() {
    return this.props.children(this.state.isLoading, this.state.phases, this.state.events, this.state.fight);
  }

}

export default PhaseParser;
<|endoftext|>


<commit_before>angular.module("hyloControllers").controller('CommunityCtrl', ['$scope', '$rootScope', 'Post', 'growl', '$timeout', '$http', '$q', '$modal', '$analytics', '$state',
  function($scope, $rootScope, Post, growl, $timeout, $http, $q, $modal, $analytics, $state) {

    $scope.state = $state;

    $scope.$watch('community', function watchCommunity(communityPromise) {
      console.log(communityPromise)
      if (communityPromise) {
        communityPromise.$promise.then(function () {
          $analytics.eventTrack('Community: Load Community', {community_id: $scope.community.id, community_name: $scope.community.name, community_slug: $scope.community.slug});
        });
      }
    });

    var startTour = function() {
      guiders.createGuider({
        buttons: [{name: "Next"}],
        description: "Hylo is a resource sharing network for your community.",
        id: "first",
        next: "second",
        overlay: true,
        title: "Let's Get Started!"
      }).show();

      guiders.createGuider({
        attachTo: document.querySelectorAll(".post-header")[0],
        buttons: [{name: "Next"}],
        description: "Here are the seeds from your community.  You can heart a seed by clicking the , or comment on it by clicking the ",
        id: "second",
        next: 'third',
        position: 7,
        title: "Let’s create together!"
      });

      guiders.createGuider({
        attachTo: document.querySelectorAll(".filter-buttons")[0],
        buttons: [{name: "Next"}],
        description: "Filter the seeds by intention, request, offer or all.",
        id: "third",
        next: "fourth",
        position: 5,
        title: "Filter seeds by type"
      });

      guiders.createGuider({
        attachTo: "#community-addSeedButton",
        buttons: [{name: "Done", onclick: function() {
          guiders.hideAll();
        }}],
        description: "Click here to add a seed of your own.",
        id: "fourth",
        //next: "fifth",
        position: 7,
        title: "Plant a New Seed",
        onHide: function() {
          $http.post('/endtour', {}, {params: {tour:'communityTour'}});
          $rootScope.currentUser.communityTour = false;
        }
      });

      //guiders.createGuider({
      //  attachTo: "#menu-user",
      //  buttons: [{name: "Done", onclick: function() {
      //    guiders.hideAll();
      //  }}],
      //  description: "Click here to access your profile.",
      //  id: "fifth",
      //  position: 3,
      //  title: "Your Profile",
      //  onHide: function() {
      //    $http.post('/endtour', {}, {params: {tour:'communityTour'}});
      //    $rootScope.currentUser.communityTour = false;
      //  }
      //});
    }

    var startOnboarding = function() {
      var modalInstance = $modal.open({
        templateUrl: '/ui/app/onboarding.tpl.html',
        controller: "OnboardingCtrl",
        keyboard: false,
        backdrop: 'static'
      });

      modalInstance.result.then(function () {
        $rootScope.currentUser.finishedOnboarding = true;
        $http.post('/endtour', {}, {params: {tour:'onboarding'}});

        // Start the community tour if the user hasn't started yet
        if ($rootScope.currentUser.communityTour) {
          $timeout(startTour, 500);
        }

      }, function () {
        // Dismissed Modal...Do nothing
      });
    }

    $scope.currentUser.$promise.then(function(user) {
      // Start the community tour/onboarding if the user hasn't finished it.
      if (!user.finishedOnboarding) {
        $timeout(startOnboarding, 100)
      } else if (user.communityTour) {
        $timeout(startTour, 500);
      }
    });
  }]);
<commit_msg>oops... remove the console.log statement<commit_after>angular.module("hyloControllers").controller('CommunityCtrl', ['$scope', '$rootScope', 'Post', 'growl', '$timeout', '$http', '$q', '$modal', '$analytics', '$state',
  function($scope, $rootScope, Post, growl, $timeout, $http, $q, $modal, $analytics, $state) {

    $scope.state = $state;

    $scope.$watch('community', function watchCommunity(communityPromise) {
      if (communityPromise) {
        communityPromise.$promise.then(function () {
          $analytics.eventTrack('Community: Load Community', {community_id: $scope.community.id, community_name: $scope.community.name, community_slug: $scope.community.slug});
        });
      }
    });

    var startTour = function() {
      guiders.createGuider({
        buttons: [{name: "Next"}],
        description: "Hylo is a resource sharing network for your community.",
        id: "first",
        next: "second",
        overlay: true,
        title: "Let's Get Started!"
      }).show();

      guiders.createGuider({
        attachTo: document.querySelectorAll(".post-header")[0],
        buttons: [{name: "Next"}],
        description: "Here are the seeds from your community.  You can heart a seed by clicking the , or comment on it by clicking the ",
        id: "second",
        next: 'third',
        position: 7,
        title: "Let’s create together!"
      });

      guiders.createGuider({
        attachTo: document.querySelectorAll(".filter-buttons")[0],
        buttons: [{name: "Next"}],
        description: "Filter the seeds by intention, request, offer or all.",
        id: "third",
        next: "fourth",
        position: 5,
        title: "Filter seeds by type"
      });

      guiders.createGuider({
        attachTo: "#community-addSeedButton",
        buttons: [{name: "Done", onclick: function() {
          guiders.hideAll();
        }}],
        description: "Click here to add a seed of your own.",
        id: "fourth",
        //next: "fifth",
        position: 7,
        title: "Plant a New Seed",
        onHide: function() {
          $http.post('/endtour', {}, {params: {tour:'communityTour'}});
          $rootScope.currentUser.communityTour = false;
        }
      });

      //guiders.createGuider({
      //  attachTo: "#menu-user",
      //  buttons: [{name: "Done", onclick: function() {
      //    guiders.hideAll();
      //  }}],
      //  description: "Click here to access your profile.",
      //  id: "fifth",
      //  position: 3,
      //  title: "Your Profile",
      //  onHide: function() {
      //    $http.post('/endtour', {}, {params: {tour:'communityTour'}});
      //    $rootScope.currentUser.communityTour = false;
      //  }
      //});
    }

    var startOnboarding = function() {
      var modalInstance = $modal.open({
        templateUrl: '/ui/app/onboarding.tpl.html',
        controller: "OnboardingCtrl",
        keyboard: false,
        backdrop: 'static'
      });

      modalInstance.result.then(function () {
        $rootScope.currentUser.finishedOnboarding = true;
        $http.post('/endtour', {}, {params: {tour:'onboarding'}});

        // Start the community tour if the user hasn't started yet
        if ($rootScope.currentUser.communityTour) {
          $timeout(startTour, 500);
        }

      }, function () {
        // Dismissed Modal...Do nothing
      });
    }

    $scope.currentUser.$promise.then(function(user) {
      // Start the community tour/onboarding if the user hasn't finished it.
      if (!user.finishedOnboarding) {
        $timeout(startOnboarding, 100)
      } else if (user.communityTour) {
        $timeout(startTour, 500);
      }
    });
  }]);
<|endoftext|>


<commit_before>import {cell} from '../../utils/Dom';
import {convertGlobalToLocal} from '../../utils/Event';

//
//  CALLBACKS FOR EACH TYPE OF HANDLE
//

    const HANDLES = Object.freeze([
        (pos, dim, opts) => { //  TOP LEFT
            HANDLES[7](pos, dim, opts);

            if (!opts.fixed_size) HANDLES[4](pos, dim, opts);
        },
        (pos, dim, opts) => { //  TOP RIGHT
            HANDLES[5](pos, dim, opts);

            if (!opts.fixed_size) HANDLES[4](pos, dim, opts);
        },
        (pos, dim, opts) => { //  BOTTOM RIGHT
            HANDLES[5](pos, dim, opts);

            if (!opts.fixed_size) HANDLES[6](pos, dim, opts);
        },
        (pos, dim, opts) => { //  BOTTOM LEFT
            HANDLES[7](pos, dim, opts);

            if (!opts.fixed_size) HANDLES[6](pos, dim, opts);
        },
        //  TOP
        (pos, dim, opts) => dim.y = (dim.y2 - pos.y < opts.min_crop_height)
            ? dim.y2 - opts.min_crop_height
            : pos.y,
        //  RIGHT
        (pos, dim, opts) => dim.x2 = (pos.x - dim.x < opts.min_crop_width)
            ? dim.x + opts.min_crop_width
            : pos.x,
        //  BOTTOM
        (pos, dim, opts) => dim.y2 = (pos.y - dim.y < opts.min_crop_height)
            ? dim.y + opts.min_crop_height
            : pos.y,
        //  LEFT
        (pos, dim, opts) => dim.x = (dim.x2 - pos.x < opts.min_crop_width)
            ? dim.x2 - opts.min_crop_width
            : pos.x,
    ]);

//
//  PUBLIC
//

    export default class Handle {
        constructor (parent, type, scope) {
            this.$$view = cell('span', ['imgc-handles-el', `imgc-handles-el-${~~(type / 4)}-${type % 4}`], {}, parent);

            //  Down handler
            function handleMouseDown (evt) {
                evt.stopPropagation();

                document.addEventListener('mouseup', handleMouseUp);
                document.addEventListener('mousemove', handleMouseMove);
            }

            //  Up handler
            function handleMouseUp (evt) {
                evt.stopPropagation();

                document.removeEventListener('mouseup', handleMouseUp);
                document.removeEventListener('mousemove', handleMouseMove);
            }

            //  Move handler
            function handleMouseMove (evt) {
                evt.stopPropagation();

                HANDLES[type](
                    convertGlobalToLocal(evt, scope.$$parent.getBoundingClientRect()),
                    scope.meta.dimensions,
                    scope.options
                );

                parent.dispatchEvent(new CustomEvent('source:dimensions'));
            }

            //  Bootstrap element
            this.$$view.addEventListener('mousedown', handleMouseDown);
        }
    }
<commit_msg>re-enable fixed mode handlers<commit_after>import {cell} from '../../utils/Dom';
import {convertGlobalToLocal} from '../../utils/Event';

//
//  CALLBACKS FOR EACH TYPE OF HANDLE
//

    const HANDLES = Object.freeze([
        (pos, dim, opts) => { //  TOP LEFT
            const {x} = dim;

            HANDLES[7](pos, dim, opts);

            if (!opts.fixed_size) HANDLES[4](pos, dim, opts);
            else {
                if (dim.y + dim.x - x < 0) {
                    dim.x = x - dim.y;
                    dim.y = 0;
                } else {
                    dim.y += dim.x - x;
                }
            }
        },
        (pos, dim, opts) => { //  TOP RIGHT
            const {x2} = dim;

            HANDLES[5](pos, dim, opts);

            if (!opts.fixed_size) HANDLES[4](pos, dim, opts);
            else {
                if (dim.y - dim.x2 + x2 < 0) {
                    dim.x2 = x2 + dim.y;
                    dim.y = 0;
                } else {
                    dim.y -= dim.x2 - x2;
                }
            }
        },
        (pos, dim, opts) => { //  BOTTOM RIGHT
            const {x2} = dim;

            HANDLES[5](pos, dim, opts);

            if (!opts.fixed_size) HANDLES[6](pos, dim, opts);
            else {
                if (dim.y2 + dim.x2 - x2 > dim.h) {
                    dim.x2 = x2 + (dim.h - dim.y2);
                    dim.y2 = dim.h;
                } else {
                    dim.y2 += dim.x2 - x2;
                }
            }
        },
        (pos, dim, opts) => { //  BOTTOM LEFT
            const {x} = dim;

            HANDLES[7](pos, dim, opts);

            if (!opts.fixed_size) HANDLES[6](pos, dim, opts);
            else {
                if (dim.y2 + (x - dim.x) > dim.h) {
                    dim.x = x - (dim.h - dim.y2);
                    dim.y2 = dim.h;
                } else {
                    dim.y2 -= dim.x - x;
                }
            }
        },
        //  TOP
        (pos, dim, opts) => dim.y = (dim.y2 - pos.y < opts.min_crop_height)
            ? dim.y2 - opts.min_crop_height
            : pos.y,
        //  RIGHT
        (pos, dim, opts) => dim.x2 = (pos.x - dim.x < opts.min_crop_width)
            ? dim.x + opts.min_crop_width
            : pos.x,
        //  BOTTOM
        (pos, dim, opts) => dim.y2 = (pos.y - dim.y < opts.min_crop_height)
            ? dim.y + opts.min_crop_height
            : pos.y,
        //  LEFT
        (pos, dim, opts) => dim.x = (dim.x2 - pos.x < opts.min_crop_width)
            ? dim.x2 - opts.min_crop_width
            : pos.x,
    ]);

//
//  PUBLIC
//

    export default class Handle {
        constructor (parent, type, scope) {
            this.$$view = cell('span', ['imgc-handles-el', `imgc-handles-el-${~~(type / 4)}-${type % 4}`], {}, parent);

            //  Down handler
            function handleMouseDown (evt) {
                evt.stopPropagation();

                document.addEventListener('mouseup', handleMouseUp);
                document.addEventListener('mousemove', handleMouseMove);
            }

            //  Up handler
            function handleMouseUp (evt) {
                evt.stopPropagation();

                document.removeEventListener('mouseup', handleMouseUp);
                document.removeEventListener('mousemove', handleMouseMove);
            }

            //  Move handler
            function handleMouseMove (evt) {
                evt.stopPropagation();

                HANDLES[type](
                    convertGlobalToLocal(evt, scope.$$parent.getBoundingClientRect()),
                    scope.meta.dimensions,
                    scope.options
                );

                parent.dispatchEvent(new CustomEvent('source:dimensions'));
            }

            //  Bootstrap element
            this.$$view.addEventListener('mousedown', handleMouseDown);
        }
    }
<|endoftext|>


<commit_before>'use strict';

//
// Constants
//

var NOTIFICATION_SENT_TIMEOUT = 2000;

//
// Controller
//

var NavigationCtrl = function($scope, $location, account, email, outbox, notification, appConfig, dialog, dummy) {
    if (!$location.search().dev && !account.isLoggedIn()) {
        $location.path('/'); // init app
        return;
    }

    var str = appConfig.string,
        config = appConfig.config;

    //
    // scope state
    //

    $scope.state.nav = {
        open: false,
        toggle: function(to) {
            this.open = to;
        }
    };

    //
    // url/history handling
    //

    $scope.loc = $location;

    /**
     * Close read mode and go to folder
     */
    $scope.navigate = function(folderIndex) {
        $location.search('uid', null); // close the read mode
        $location.search('folder', folderIndex); // open the n-th folder
    };

    // folder index url watcher
    $scope.$watch('(loc.search()).folder', function(folderIndex) {
        if (!$scope.account.folders || !$scope.account.folders.length) {
            // there's no folder to navigate to
            return;
        }

        // normalize folder index to [0 ; $scope.account.folders.length - 1]
        folderIndex = parseInt(folderIndex, 10);
        if (isNaN(folderIndex) || folderIndex < 0 || folderIndex > ($scope.account.folders.length - 1)) {
            // array index out of bounds or nonsensical data
            $location.search('folder', 0);
            return;
        }

        // navigate to folder[folderIndex]
        if ($scope.account.folders && $scope.account.folders.length > folderIndex) {
            // navigate to the selected folder index
            $scope.state.nav.currentFolder = $scope.account.folders[folderIndex];
            $scope.state.nav.toggle(false);
        }
    });

    // nav open/close state url watcher
    $scope.$watch('(loc.search()).nav', function(open) {
        // synchronize the url to the scope state
        $scope.state.nav.toggle(!!open);
    });
    $scope.$watch('state.nav.open', function(value) {
        // synchronize the scope state to the url
        $location.search('nav', value ? true : null);
    });

    // lightbox state url watcher
    $scope.$watch('(loc.search()).lightbox', function(value) {
        // synchronize the url to the scope state
        $scope.state.lightbox = (value) ? value : undefined;
    });
    $scope.$watch('state.lightbox', function(value) {
        // synchronize the scope state to the url
        $location.search('lightbox', value ? value : null);
    });

    //
    // scope functions
    //

    $scope.onOutboxUpdate = function(err, count) {
        if (err) {
            dialog.error(err);
            return;
        }

        // update the outbox mail count
        var ob = _.findWhere($scope.account.folders, {
            type: config.outboxMailboxType
        });
        ob.count = count;

        email.refreshFolder({
            folder: ob
        }, dialog.error);
    };

    $scope.logout = function() {
        dialog.confirm({
            title: str.logoutTitle,
            message: str.logoutMessage,
            callback: function(confirm) {
                if (confirm) {
                    account.logout();
                }
            }
        });
    };

    //
    // Start
    //

    // init folders
    initializeFolders();

    // connect imap/smtp clients on first startup
    account.onConnect(function(err) {
        if (err) {
            dialog.error(err);
            return;
        }

        // select inbox if not yet selected
        if (!$scope.state.nav.currentFolder) {
            $location.search('folder', 0);
        }
    });

    //
    // helper functions
    //

    function initializeFolders() {
        // create dummy folder in dev environment only
        if ($location.search().dev) {
            $scope.$root.account = {};
            $scope.account.folders = dummy.listFolders();
            return;
        }

        // get pointer to account/folder/message tree on root scope
        $scope.$root.account = account.list()[0];

        // set notificatio handler for sent messages
        outbox.onSent = function(message) {
            notification.create({
                title: 'Message sent',
                message: message.subject,
                timeout: NOTIFICATION_SENT_TIMEOUT
            }, function() {});
        };

        // start checking outbox periodically
        outbox.startChecking($scope.onOutboxUpdate);
    }
};

module.exports = NavigationCtrl;<commit_msg>Review navigation<commit_after>'use strict';

//
// Constants
//

var NOTIFICATION_SENT_TIMEOUT = 2000;

//
// Controller
//

var NavigationCtrl = function($scope, $location, account, email, outbox, notification, appConfig, dialog, dummy) {
    if (!$location.search().dev && !account.isLoggedIn()) {
        $location.path('/'); // init app
        return;
    }

    var str = appConfig.string,
        config = appConfig.config;

    //
    // scope state
    //

    $scope.state.nav = {
        open: false,
        toggle: function(to) {
            this.open = to;
        }
    };

    //
    // url/history handling
    //

    $scope.loc = $location;

    /**
     * Close read mode and go to folder
     */
    $scope.navigate = function(folderIndex) {
        $location.search('uid', null); // close the read mode
        $location.search('folder', folderIndex); // open the n-th folder
    };

    // folder index url watcher
    $scope.$watch('(loc.search()).folder', function(folderIndex) {
        if (!$scope.account.folders || !$scope.account.folders.length) {
            // there's no folder to navigate to
            return;
        }

        // normalize folder index to [0 ; $scope.account.folders.length - 1]
        folderIndex = parseInt(folderIndex, 10);
        if (isNaN(folderIndex) || folderIndex < 0 || folderIndex > ($scope.account.folders.length - 1)) {
            // array index out of bounds or nonsensical data
            $location.search('folder', 0);
            return;
        }

        // navigate to folder[folderIndex]
        // navigate to the selected folder index
        $scope.state.nav.currentFolder = $scope.account.folders[folderIndex];
        $scope.state.nav.toggle(false);
    });

    // nav open/close state url watcher
    $scope.$watch('(loc.search()).nav', function(open) {
        // synchronize the url to the scope state
        $scope.state.nav.toggle(!!open);
    });
    $scope.$watch('state.nav.open', function(value) {
        // synchronize the scope state to the url
        $location.search('nav', value ? true : null);
    });

    // lightbox state url watcher
    $scope.$watch('(loc.search()).lightbox', function(value) {
        // synchronize the url to the scope state
        $scope.state.lightbox = (value) ? value : undefined;
    });
    $scope.$watch('state.lightbox', function(value) {
        // synchronize the scope state to the url
        $location.search('lightbox', value ? value : null);
    });

    //
    // scope functions
    //

    $scope.onOutboxUpdate = function(err, count) {
        if (err) {
            dialog.error(err);
            return;
        }

        // update the outbox mail count
        var ob = _.findWhere($scope.account.folders, {
            type: config.outboxMailboxType
        });
        ob.count = count;

        email.refreshFolder({
            folder: ob
        }, dialog.error);
    };

    $scope.logout = function() {
        dialog.confirm({
            title: str.logoutTitle,
            message: str.logoutMessage,
            callback: function(confirm) {
                if (confirm) {
                    account.logout();
                }
            }
        });
    };

    //
    // Start
    //

    // init folders
    initializeFolders();

    // connect imap/smtp clients on first startup
    account.onConnect(function(err) {
        if (err) {
            dialog.error(err);
            return;
        }

        // select inbox if not yet selected
        if (!$scope.state.nav.currentFolder) {
            $scope.navigate(0);
        }
    });

    //
    // helper functions
    //

    function initializeFolders() {
        // create dummy folder in dev environment only
        if ($location.search().dev) {
            $scope.$root.account = {};
            $scope.account.folders = dummy.listFolders();
            return;
        }

        // get pointer to account/folder/message tree on root scope
        $scope.$root.account = account.list()[0];

        // set notificatio handler for sent messages
        outbox.onSent = function(message) {
            notification.create({
                title: 'Message sent',
                message: message.subject,
                timeout: NOTIFICATION_SENT_TIMEOUT
            }, function() {});
        };

        // start checking outbox periodically
        outbox.startChecking($scope.onOutboxUpdate);
    }
};

module.exports = NavigationCtrl;<|endoftext|>


<commit_before>/*

@param menuTrigger: One or more elements that have menus attached. Typically
this will be .va-btn-sidebarnav-trigger
*/

class SideBarMenu {
   constructor(menuTrigger) {
    this.menuTrigger = Array.from(menuTrigger);
    this.init = this.init.bind(this);
    this.getMenu = this.getMenu.bind(this);
    this.openMenu = this.openMenu.bind(this);
    this.closeMenu = this.closeMenu.bind(this);
    this.menu = null;
    this.init();
  }

  init() {
    this.menuTrigger.map((mt) => {
      mt.addEventListener('click', (domEvent) => {
        this.openMenu(domEvent.currentTarget);
      });
    });
  }

  getMenu(element) {
    const el = document.querySelector(`#${element.getAttribute('aria-controls')}`);
    this.menu = el;
    return this.menu;
  }

  openMenu(trigger) {
    const menu = this.getMenu(trigger);

    menu.classList.add('va-sidebarnav--opened');
    document.body.classList.add('va-pos-fixed');

    // Delay the animation classes slightly so that switching the display property
    // to block doesn't cause the animations to skip.
    setTimeout(() => {
      menu.classList.remove('out');
      menu.classList.add('in');
    }, 10);

    this.closeMenu(trigger);
  }

  closeMenu(trigger) {
    const close = this.menu.querySelector('.va-sidebarnav-close');
    close.addEventListener('click', (domEvent) => {

      this.menu.classList.remove('in');
      this.menu.classList.add('out');

      // Give the animations time to complete before removing the display classes.
      setTimeout(() => {
        this.menu.classList.remove('va-sidebarnav--opened');
        document.body.classList.remove('va-pos-fixed');
      }, 300)

    })
  }
}

document.addEventListener('DOMContentLoaded', () => {
  new SideBarMenu(document.querySelectorAll('.va-btn-sidebarnav-trigger'));
});
<commit_msg>Add semicolon<commit_after>/*

@param menuTrigger: One or more elements that have menus attached. Typically
this will be .va-btn-sidebarnav-trigger
*/

class SideBarMenu {
   constructor(menuTrigger) {
    this.menuTrigger = Array.from(menuTrigger);
    this.init = this.init.bind(this);
    this.getMenu = this.getMenu.bind(this);
    this.openMenu = this.openMenu.bind(this);
    this.closeMenu = this.closeMenu.bind(this);
    this.menu = null;
    this.init();
  }

  init() {
    this.menuTrigger.map((mt) => {
      mt.addEventListener('click', (domEvent) => {
        this.openMenu(domEvent.currentTarget);
      });
    });
  }

  getMenu(element) {
    const el = document.querySelector(`#${element.getAttribute('aria-controls')}`);
    this.menu = el;
    return this.menu;
  }

  openMenu(trigger) {
    const menu = this.getMenu(trigger);

    menu.classList.add('va-sidebarnav--opened');
    document.body.classList.add('va-pos-fixed');

    // Delay the animation classes slightly so that switching the display property
    // to block doesn't cause the animations to skip.
    setTimeout(() => {
      menu.classList.remove('out');
      menu.classList.add('in');
    }, 10);

    this.closeMenu(trigger);
  }

  closeMenu(trigger) {
    const close = this.menu.querySelector('.va-sidebarnav-close');
    close.addEventListener('click', (domEvent) => {

      this.menu.classList.remove('in');
      this.menu.classList.add('out');

      // Give the animations time to complete before removing the display classes.
      setTimeout(() => {
        this.menu.classList.remove('va-sidebarnav--opened');
        document.body.classList.remove('va-pos-fixed');
      }, 300);

    })
  }
}

document.addEventListener('DOMContentLoaded', () => {
  new SideBarMenu(document.querySelectorAll('.va-btn-sidebarnav-trigger'));
});
<|endoftext|>


<commit_before>import util from '../../util.js';
import _ from 'lodash';
export default {
  type: 'charset',

  definedProperties: {
    _anchor: {
      get: function() {
        var matrix = this.transform().localMatrix;

        return {
          ay: matrix.y(0, this.partContainer.getBBox().cy)
        };
      }
    }
  },

  _render() {
    this.partContainer = this.container.group();

    return Promise.all(_.map(this.elements, part => {
      return part.render(this.partContainer.group());
    }))
      .then(() => {
        util.spaceVertically(this.elements, {
          padding: 5
        });

        return this.renderLabeledBox(this.label, this.partContainer, {
          padding: 5
        });
      });
  },

  setup() {
    this.label = (this.properties.invert.textValue === '^') ? 'None of:' : 'One of:';
    this.elements = _.unique(this.properties.parts.elements, part => {
      return [part.type, part.textValue].join(':');
    });

    if (this.textValue.match(/\\c[^a-zA-Z]/)) {
      this.state.warnings.push(`The character set "${this.textValue}" contains the \\c escape followed by a character other than A-Z. This can lead to different behavior depending on browser. The representation here is the most common interpretation.`);
    }
  }
}
<commit_msg>Replacing an array join with a JS template<commit_after>import util from '../../util.js';
import _ from 'lodash';
export default {
  type: 'charset',

  definedProperties: {
    _anchor: {
      get: function() {
        var matrix = this.transform().localMatrix;

        return {
          ay: matrix.y(0, this.partContainer.getBBox().cy)
        };
      }
    }
  },

  _render() {
    this.partContainer = this.container.group();

    return Promise.all(_.map(this.elements, part => {
      return part.render(this.partContainer.group());
    }))
      .then(() => {
        util.spaceVertically(this.elements, {
          padding: 5
        });

        return this.renderLabeledBox(this.label, this.partContainer, {
          padding: 5
        });
      });
  },

  setup() {
    this.label = (this.properties.invert.textValue === '^') ? 'None of:' : 'One of:';
    this.elements = _.unique(this.properties.parts.elements, part => {
      return `${part.type}:${part.textValue}`;
    });

    if (this.textValue.match(/\\c[^a-zA-Z]/)) {
      this.state.warnings.push(`The character set "${this.textValue}" contains the \\c escape followed by a character other than A-Z. This can lead to different behavior depending on browser. The representation here is the most common interpretation.`);
    }
  }
}
<|endoftext|>