<commit_before>;(function() {
  "use strict";
  angular
    .module('RDash')
    .controller('commpropExtraController', ['$scope', '$stateParams', 'goodsHTTP', 'commpropGoodsHTTP', function($scope, $stateParams, goodsHTTP, commpropGoodsHTTP) {

      $scope.currencyTypes = [{ type: 'RUB', text: 'руб' },{ type: 'EUR', text: '€' },{ type: 'USD', text: '$' }];
      $scope.entry = {};
      $scope.refreshGoods = function(goods) {
        var criteria;
        if (goods) {
          criteria = {
            search: goods
          };
        }
        goodsHTTP.read(criteria).success(function(response) {
          $scope.goods = response;
        });
      };

      $scope.onSelectGood = function(item, model) {
        $scope.entry.goodId = item.id;
        $scope.entry.currency = item.currency;
        $scope.entry.price = item.price;
        $scope.entry.quantity = 1;
        $scope.entry.delivery_period = '10 дней';
      };

      $scope.totalPriceRUB = 0;
      $scope.totalPriceUSD = 0;
      $scope.totalPriceEUR = 0;

      $scope.totalQuantity = 0;

      $scope.entry.quantity = 0;
      $scope.entry.price = 0;
      $scope.entry.currency = '';
      $scope.entry.delivery_period = '10 дней';
      $scope.entry.goodId = 0;
      $scope.entry.commercialProposalId = parseInt($stateParams.id, 10);
      commpropGoodsHTTP.setCommercialProposalId($scope.entry.commercialProposalId);

      $scope.entriesGoods = [];

      commpropGoodsHTTP.read().success(function(response) {
        $scope.entriesCommpropGoods = response;
        for (var i = 0; i < $scope.entriesCommpropGoods.length; i++) {
          $scope.totalQuantity += $scope.entriesCommpropGoods[i].quantity;

          if ($scope.entriesCommpropGoods[i].currency === "RUB") {
            $scope.totalPriceRUB += $scope.entriesCommpropGoods[i].price * $scope.entriesCommpropGoods[i].quantity;
          }
          if ($scope.entriesCommpropGoods[i].currency === "USD") {
            $scope.totalPriceUSD += $scope.entriesCommpropGoods[i].price * $scope.entriesCommpropGoods[i].quantity;
          }
          if ($scope.entriesCommpropGoods[i].currency === "EUR") {
            $scope.totalPriceEUR += $scope.entriesCommpropGoods[i].price * $scope.entriesCommpropGoods[i].quantity;
          }

        }
      });

      $scope.onAddCommpropGoods = function() {
        commpropGoodsHTTP.add($scope.entry).success(function(response) {
          response.good = {
            name: $scope.entry.good.name
          };
          $scope.entriesCommpropGoods.push(response);
          $scope.entry = {};
        });

      };

      $scope.onRemoveCommpropGoods = function(entry) {
        commpropGoodsHTTP.remove(entry).success(function(response) {
          var l = $scope.entriesCommpropGoods.length, i, found = false;
          for (i = 0; i < l; i++) {
            if ($scope.entriesCommpropGoods[i].id === entry.id) {
              found = true;
              break;
            }
          };
          if (found)
            $scope.entriesCommpropGoods.splice(i, 1);
        });
      };

    }]);
})();
<commit_msg>fixed multiple addition of goods in KP<commit_after>;(function() {
  "use strict";
  angular
    .module('RDash')
    .controller('commpropExtraController', ['$scope', '$stateParams', 'goodsHTTP', 'commpropGoodsHTTP', function($scope, $stateParams, goodsHTTP, commpropGoodsHTTP) {

      $scope.currencyTypes = [{ type: 'RUB', text: 'руб' },{ type: 'EUR', text: '€' },{ type: 'USD', text: '$' }];
      $scope.entry = {};
      $scope.refreshGoods = function(goods) {
        var criteria;
        if (goods) {
          criteria = {
            search: goods
          };
        }
        goodsHTTP.read(criteria).success(function(response) {
          $scope.goods = response;
        });
      };

      $scope.onSelectGood = function(item, model) {
        $scope.entry.goodId = item.id;
        $scope.entry.currency = item.currency;
        $scope.entry.price = item.price;
        $scope.entry.quantity = 1;
        $scope.entry.delivery_period = '10 дней';
        $scope.entry.commercialProposalId = parseInt($stateParams.id, 10);
        commpropGoodsHTTP.setCommercialProposalId($scope.entry.commercialProposalId);
      };

      $scope.totalPriceRUB = 0;
      $scope.totalPriceUSD = 0;
      $scope.totalPriceEUR = 0;

      $scope.totalQuantity = 0;

      $scope.entry.quantity = 0;
      $scope.entry.price = 0;
      $scope.entry.currency = '';
      $scope.entry.delivery_period = '10 дней';
      $scope.entry.goodId = 0;

      $scope.entriesGoods = [];

      commpropGoodsHTTP.read().success(function(response) {
        $scope.entriesCommpropGoods = response;
        for (var i = 0; i < $scope.entriesCommpropGoods.length; i++) {
          $scope.totalQuantity += $scope.entriesCommpropGoods[i].quantity;

          if ($scope.entriesCommpropGoods[i].currency === "RUB") {
            $scope.totalPriceRUB += $scope.entriesCommpropGoods[i].price * $scope.entriesCommpropGoods[i].quantity;
          }
          if ($scope.entriesCommpropGoods[i].currency === "USD") {
            $scope.totalPriceUSD += $scope.entriesCommpropGoods[i].price * $scope.entriesCommpropGoods[i].quantity;
          }
          if ($scope.entriesCommpropGoods[i].currency === "EUR") {
            $scope.totalPriceEUR += $scope.entriesCommpropGoods[i].price * $scope.entriesCommpropGoods[i].quantity;
          }

        }
      });

      $scope.onAddCommpropGoods = function() {
        commpropGoodsHTTP.add($scope.entry).success(function(response) {
          response.good = {
            name: $scope.entry.good.name
          };
          $scope.entriesCommpropGoods.push(response);
          $scope.entry = {};
        });

      };

      $scope.onRemoveCommpropGoods = function(entry) {
        commpropGoodsHTTP.remove(entry).success(function(response) {
          var l = $scope.entriesCommpropGoods.length, i, found = false;
          for (i = 0; i < l; i++) {
            if ($scope.entriesCommpropGoods[i].id === entry.id) {
              found = true;
              break;
            }
          };
          if (found)
            $scope.entriesCommpropGoods.splice(i, 1);
        });
      };

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


<commit_before>/***********************************************************************
 * The fact that all tested JS engines (Gecko, Presto and WebKit) store
 * the properties in-order is abused to generate a proper Ruby-ish YAML.
 **********************************************************************/

function rubyObject(type, data) {
  this.rubyobject = type.replace("!ruby/object:", "");
  for(x in data) {
    this[x] = data[x];
  }
}

constructRubyObject = function constructRubyObject(node) {
  //console.log(node.tag);
  if (node.constructor.id == "scalar")
    return new rubyObject(node.tag, null);
  return new rubyObject(node.tag, this.constructMapping(node, true));
};

jsyaml.addConstructor('!ruby/object:Box', constructRubyObject );
jsyaml.addConstructor('!ruby/object:Question', constructRubyObject );
jsyaml.addConstructor('!ruby/object:Section', constructRubyObject );
jsyaml.addConstructor('!ruby/object:Page', constructRubyObject );
jsyaml.addConstructor('!ruby/object:AbstractForm', constructRubyObject );

/***********************************************************************
 * JSON 2 Rubyish-YAML exporter
 *
 * Based on https://github.com/jeffsu/json2yaml
 * License is MIT
 **********************************************************************/
(function (self) {
  var spacing = "  ";

  function getType(obj) {
    var type = typeof obj;
    if (obj instanceof Array) {
      return 'array';
    } else if (type == 'string') {
      return 'string';
    } else if (type == 'boolean') {
      return 'boolean';
    } else if (type == 'number') {
      return 'number';
    } else if (type == 'undefined' || obj === null) {
      return 'null';
    } else {
      return 'hash';
    }
  }

  function convert(obj, ret) {
    var type = getType(obj);

    switch(type) {
      case 'array':
        convertArray(obj, ret);
        break;
      case 'hash':
        convertHash(obj, ret);
        break;
      case 'string':
        convertString(obj, ret);
        break;
      case 'null':
        ret.push('null');
        break;
      case 'number':
        ret.push(obj.toString());
        break;
      case 'boolean':
        ret.push(obj ? 'true' : 'false');
        break;
    }
  }

  function convertArray(obj, ret) {
    for (var i=0; i<obj.length; i++) {
      var ele = obj[i];
      var recurse = [];
      convert(ele, recurse);

      for (var j=0; j<recurse.length; j++) {
        ret.push((j == 0 ? "- " : spacing) + recurse[j]);
      }
    }
  }

  function convertHash(obj, ret) {
    for (var k in obj) {
      var recurse = [];
      if (obj.hasOwnProperty(k)) {
        var ele = obj[k];
        convert(ele, recurse);
        var type = getType(ele);
        var name = normalizeString(k);
        if (type == 'null') {
          // don’t add, as we can simply emit null or nil values for
          // Rubyish-YAML.
          //console.log("Skipping value " + name + " because it’s null");
        } else if (type == 'string' || type == 'number' || type == 'boolean') {
          name = (name == "rubyobject" ? '!ruby/object:' : name+': ');
          if(recurse[0] == "AbstractForm") name = "--- " + name;
          ret.push(name + recurse[0]);
        } else {
          ret.push(name + ': ');
          for (var i=0; i<recurse.length; i++) {
            ret.push(spacing + recurse[i]);
          }
        }
      }
    }
  }

  function normalizeString(str) {
    // allow Ruby symbols to appear without quotes
    if (str.match(/^:?\w+$/)) {
      return str;
    } else {
      return JSON.stringify(str);
    }
  }

  function convertString(obj, ret) {
    ret.push(normalizeString(obj));
  }

  self.json2yaml = function(obj) {
    if (typeof obj == 'string') {
      obj = JSON.parse(obj);
    }

    var ret = [];
    convert(obj, ret);
    // clean up trailing whitespace
    return ret.join("\n").replace(/\s+\n/g, "\n");
  };

})(this);
<commit_msg>be more restrictive when converting to YAML without quotes<commit_after>/***********************************************************************
 * The fact that all tested JS engines (Gecko, Presto and WebKit) store
 * the properties in-order is abused to generate a proper Ruby-ish YAML.
 **********************************************************************/

function rubyObject(type, data) {
  this.rubyobject = type.replace("!ruby/object:", "");
  for(x in data) {
    this[x] = data[x];
  }
}

constructRubyObject = function constructRubyObject(node) {
  //console.log(node.tag);
  if (node.constructor.id == "scalar")
    return new rubyObject(node.tag, null);
  return new rubyObject(node.tag, this.constructMapping(node, true));
};

jsyaml.addConstructor('!ruby/object:Box', constructRubyObject );
jsyaml.addConstructor('!ruby/object:Question', constructRubyObject );
jsyaml.addConstructor('!ruby/object:Section', constructRubyObject );
jsyaml.addConstructor('!ruby/object:Page', constructRubyObject );
jsyaml.addConstructor('!ruby/object:AbstractForm', constructRubyObject );

/***********************************************************************
 * JSON 2 Rubyish-YAML exporter
 *
 * Based on https://github.com/jeffsu/json2yaml
 * License is MIT
 **********************************************************************/
(function (self) {
  var spacing = "  ";

  function getType(obj) {
    var type = typeof obj;
    if (obj instanceof Array) {
      return 'array';
    } else if (type == 'string') {
      return 'string';
    } else if (type == 'boolean') {
      return 'boolean';
    } else if (type == 'number') {
      return 'number';
    } else if (type == 'undefined' || obj === null) {
      return 'null';
    } else {
      return 'hash';
    }
  }

  function convert(obj, ret) {
    var type = getType(obj);

    switch(type) {
      case 'array':
        convertArray(obj, ret);
        break;
      case 'hash':
        convertHash(obj, ret);
        break;
      case 'string':
        convertString(obj, ret);
        break;
      case 'null':
        ret.push('null');
        break;
      case 'number':
        ret.push(obj.toString());
        break;
      case 'boolean':
        ret.push(obj ? 'true' : 'false');
        break;
    }
  }

  function convertArray(obj, ret) {
    for (var i=0; i<obj.length; i++) {
      var ele = obj[i];
      var recurse = [];
      convert(ele, recurse);

      for (var j=0; j<recurse.length; j++) {
        ret.push((j == 0 ? "- " : spacing) + recurse[j]);
      }
    }
  }

  function convertHash(obj, ret) {
    for (var k in obj) {
      var recurse = [];
      if (obj.hasOwnProperty(k)) {
        var ele = obj[k];
        convert(ele, recurse);
        var type = getType(ele);
        var name = normalizeString(k, true);
        if (type == 'null') {
          // don’t add, as we can simply emit null or nil values for
          // Rubyish-YAML.
          //console.log("Skipping value " + name + " because it’s null");
        } else if (type == 'string' || type == 'number' || type == 'boolean') {
          if(name == "rubyobject") {
            name ='!ruby/object:';
            // cut off quotation marks added by convertString
            recurse[0] = recurse[0].slice(1, -1);
            if(recurse[0] == 'AbstractForm') name = "--- " + name;
          } else {
            name = name + ': ';
          }
          ret.push(name + recurse[0]);
        } else {
          ret.push(name + ': ');
          for (var i=0; i<recurse.length; i++) {
            ret.push(spacing + recurse[i]);
          }
        }
      }
    }
  }

  function normalizeString(str, isKey) {
    // allow Ruby symbols to appear without quotes
    if (str.match(/^:?\w+$/) && isKey) {
      return str;
    } else {
      return JSON.stringify(str);
    }
  }

  function convertString(obj, ret) {
    ret.push(normalizeString(obj));
  }

  self.json2yaml = function(obj) {
    if (typeof obj == 'string') {
      obj = JSON.parse(obj);
    }

    var ret = [];
    convert(obj, ret);
    // clean up trailing whitespace
    return ret.join("\n").replace(/\s+\n/g, "\n");
  };

})(this);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';
import Nav from '../../components/Nav/Nav.js';
import { ConnectedCart } from '../../containers/Cart/Cart.js';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])
@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: push})
export default class App extends Component {
  static propTypes = {
    children: PropTypes.object.isRequired,
    user: PropTypes.object,
    logout: PropTypes.func.isRequired,
    pushState: PropTypes.func.isRequired
  };

  static contextTypes = {
    store: PropTypes.object.isRequired
  };

  componentWillReceiveProps(nextProps) {
    if (!this.props.user && nextProps.user) {
      // login
      this.props.pushState('/loginSuccess');
    } else if (this.props.user && !nextProps.user) {
      // logout
      this.props.pushState('/');
    }
  }

  handleLogout = (event) => {
    event.preventDefault();
    this.props.logout();
  };

  render() {
    const {user} = this.props;
    const styles = {};// require('./App.scss');
    require('./App.css');

    return (

          <ConnectedCart />

        <Helmet {...config.app.head}/>

            {this.props.children}

            Company name — 2016

    );
  }
}
<commit_msg>remove unused var<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';
import Nav from '../../components/Nav/Nav.js';
import { ConnectedCart } from '../../containers/Cart/Cart.js';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])
@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: push})
export default class App extends Component {
  static propTypes = {
    children: PropTypes.object.isRequired,
    user: PropTypes.object,
    logout: PropTypes.func.isRequired,
    pushState: PropTypes.func.isRequired
  };

  static contextTypes = {
    store: PropTypes.object.isRequired
  };

  componentWillReceiveProps(nextProps) {
    if (!this.props.user && nextProps.user) {
      // login
      this.props.pushState('/loginSuccess');
    } else if (this.props.user && !nextProps.user) {
      // logout
      this.props.pushState('/');
    }
  }

  handleLogout = (event) => {
    event.preventDefault();
    this.props.logout();
  };

  render() {
    const {user} = this.props;
    const styles = {};// require('./App.scss');
    require('./App.css');

    return (

          <ConnectedCart />

        <Helmet {...config.app.head}/>

            {this.props.children}

            Company name — 2016

    );
  }
}
<|endoftext|>


<commit_before>import { join } from 'path'
import { expect } from 'chai'
import plugin from './archetype-library'

const saguiPath = join(__dirname, '../../../../')
const projectPath = join(saguiPath, 'spec/fixtures/library-project')
const projectWithoutPeerDependenciesPath = join(saguiPath, 'spec/fixtures/library-project-without-peer-dependencies')

describe('configure webpack library', function () {
  describe('simple name configuration', function () {
    const baseConfiguration = {
      library: 'FancyLibrary',
      projectPath
    }

    it('should have a single entry pointing to index.js', function () {
      const webpackConfig = plugin.configure(baseConfiguration)
      expect(webpackConfig.entry).eql('./index.js')
    })

    it('should have the default exporting target of commonjs2 (module.exports = xxx)', function () {
      const webpackConfig = plugin.configure(baseConfiguration)
      expect(webpackConfig.output.libraryTarget).eql('commonjs2')
    })

    it('should NOT SET the exporting target if buildTarget is test (a browser wont understand commonjs modules)', function () {
      const webpackConfig = plugin.configure({ ...baseConfiguration, buildTarget: 'test' })
      expect(webpackConfig.output.libraryTarget).undefined
    })

    it('should have the filename as index.js', function () {
      const webpackConfig = plugin.configure(baseConfiguration)
      expect(webpackConfig.output.filename).eql('index.js')
    })

    it('should have the output path configured as the dist folder', function () {
      const webpackConfig = plugin.configure(baseConfiguration)
      expect(webpackConfig.output.path).eql(join(projectPath, 'dist'))
    })

    describe('externals', function () {
      it('should infer the externals based on the packgage.json peerDependencies', function () {
        const webpackConfig = plugin.configure(baseConfiguration)
        expect(webpackConfig.externals).eql(['react', 'react-dom'])
      })

      it('should have an empty externals if the buildTarget is test', function () {
        const webpackConfig = configure({ ...baseConfiguration, buildTarget: 'test' })
        expect(webpackConfig.externals).eql([])
      })

      it('should have an empty externals if the packgage.json does not have a peerDependencies', function () {
        const webpackConfig = plugin.configure({ ...baseConfiguration, projectPath: projectWithoutPeerDependenciesPath })
        expect(webpackConfig.externals).eql([])
      })
    })
  })
})
<commit_msg>Fix lint error introduced after merge<commit_after>import { join } from 'path'
import { expect } from 'chai'
import plugin from './archetype-library'

const saguiPath = join(__dirname, '../../../../')
const projectPath = join(saguiPath, 'spec/fixtures/library-project')
const projectWithoutPeerDependenciesPath = join(saguiPath, 'spec/fixtures/library-project-without-peer-dependencies')

describe('configure webpack library', function () {
  describe('simple name configuration', function () {
    const baseConfiguration = {
      library: 'FancyLibrary',
      projectPath
    }

    it('should have a single entry pointing to index.js', function () {
      const webpackConfig = plugin.configure(baseConfiguration)
      expect(webpackConfig.entry).eql('./index.js')
    })

    it('should have the default exporting target of commonjs2 (module.exports = xxx)', function () {
      const webpackConfig = plugin.configure(baseConfiguration)
      expect(webpackConfig.output.libraryTarget).eql('commonjs2')
    })

    it('should NOT SET the exporting target if buildTarget is test (a browser wont understand commonjs modules)', function () {
      const webpackConfig = plugin.configure({ ...baseConfiguration, buildTarget: 'test' })
      expect(webpackConfig.output.libraryTarget).undefined
    })

    it('should have the filename as index.js', function () {
      const webpackConfig = plugin.configure(baseConfiguration)
      expect(webpackConfig.output.filename).eql('index.js')
    })

    it('should have the output path configured as the dist folder', function () {
      const webpackConfig = plugin.configure(baseConfiguration)
      expect(webpackConfig.output.path).eql(join(projectPath, 'dist'))
    })

    describe('externals', function () {
      it('should infer the externals based on the packgage.json peerDependencies', function () {
        const webpackConfig = plugin.configure(baseConfiguration)
        expect(webpackConfig.externals).eql(['react', 'react-dom'])
      })

      it('should have an empty externals if the buildTarget is test', function () {
        const webpackConfig = plugin.configure({ ...baseConfiguration, buildTarget: 'test' })
        expect(webpackConfig.externals).eql([])
      })

      it('should have an empty externals if the packgage.json does not have a peerDependencies', function () {
        const webpackConfig = plugin.configure({ ...baseConfiguration, projectPath: projectWithoutPeerDependenciesPath })
        expect(webpackConfig.externals).eql([])
      })
    })
  })
})
<|endoftext|>


<commit_before>
import React from 'react';
import PureComponent from 'react-pure-render/component';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

// Actions
import * as SurveysActions from '../../actions/surveys';
import * as QuestionsActions from '../../actions/questions';
import * as EditSubjectActions from '../../actions/editSubject';
import * as PreviewActions from '../../actions/preview';

import ControlBtn from '../../components/List/ControlBtn';
import SurveyList from '../../components/List/SurveyList';

class List extends PureComponent {

    constructor(props) {
        super(props);

        const { surveysActions } = props;
        surveysActions.getSurveys();
    }

    render() {
        const { surveys, selectedSurveys,
            surveysActions, questionsActions, editSubjectActions, previewActions } = this.props;

        return (

                <ControlBtn
                    selectedSurveys={selectedSurveys}
                    editSubjectActions={editSubjectActions}
                    surveysActions={surveysActions}
                    previewActions={previewActions}
                />
                <SurveyList
                    surveys={surveys}
                    selectedSurveys={selectedSurveys}
                    questionsActions={questionsActions}
                    surveysActions={surveysActions}
                />

        );
    }
}

function mapStateToProps(state) {
    return {
        surveys: state.surveys,
        selectedSurveys: state.selectedSurveys
    };
}

function mapDispatchToProps(dispatch) {
    return {
        surveysActions: bindActionCreators(SurveysActions, dispatch),
        questionsActions: bindActionCreators(QuestionsActions, dispatch),
        editSubjectActions: bindActionCreators(EditSubjectActions, dispatch),
        previewActions: bindActionCreators(PreviewActions, dispatch)
    };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(List);
<commit_msg>Dispatch action in componentWillMount instead of constructor<commit_after>
import React from 'react';
import PureComponent from 'react-pure-render/component';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

// Actions
import * as SurveysActions from '../../actions/surveys';
import * as QuestionsActions from '../../actions/questions';
import * as EditSubjectActions from '../../actions/editSubject';
import * as PreviewActions from '../../actions/preview';

import ControlBtn from '../../components/List/ControlBtn';
import SurveyList from '../../components/List/SurveyList';

class List extends PureComponent {

    componentWillMount() {
        const { surveysActions } = this.props;
        surveysActions.getSurveys();
    }

    render() {
        const { surveys, selectedSurveys,
            surveysActions, questionsActions, editSubjectActions, previewActions } = this.props;

        return (

                <ControlBtn
                    selectedSurveys={selectedSurveys}
                    editSubjectActions={editSubjectActions}
                    surveysActions={surveysActions}
                    previewActions={previewActions}
                />
                <SurveyList
                    surveys={surveys}
                    selectedSurveys={selectedSurveys}
                    questionsActions={questionsActions}
                    surveysActions={surveysActions}
                />

        );
    }
}

function mapStateToProps(state) {
    return {
        surveys: state.surveys,
        selectedSurveys: state.selectedSurveys
    };
}

function mapDispatchToProps(dispatch) {
    return {
        surveysActions: bindActionCreators(SurveysActions, dispatch),
        questionsActions: bindActionCreators(QuestionsActions, dispatch),
        editSubjectActions: bindActionCreators(EditSubjectActions, dispatch),
        previewActions: bindActionCreators(PreviewActions, dispatch)
    };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(List);
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    var backbone = require('backbone');
    var marionette = require('marionette');
    var app = require('app/app');
    var $ = require('jquery');

    var Session = require('app/models/session').Session;

    var LandingLayout = require('app/layouts/landing-layout').LandingLayout;

    var SignupView = require('app/views/signup-view').SignupView;
    var FooterView = require('app/views/footer-view').FooterView;
    var LoginView = require('app/views/login-view').LoginView;

    var AppController = marionette.Controller.extend({
        initialize: function() {
            this.app = app;
            this.app.session = new Session({}, {
                remote: false
            });
            // Logic for auth check.
            if (this.app.session.has('token')) {
                console.log("User logged in");
                $.ajaxSetup({
                    headers: {'Authorization' : this.app.session.get('token')}
                })
                // user is authed, redirect home
                this.app.mainRegion.show(new HomeLayout({
                    session: this.app.session
                }));
                // Initialize header view after logged in
            this.app.session = app.session;
            };
        },
        // Needed for AppRouter to initialize index route.
        index: function() {
            console.log(this.app.session)
            if (this.app.session.hasAuth()) {
                this.showHomeLayout();
            } else {
                this.app.mainRegion.show(new LandingLayout({
                    session: this.app.session
                }));
            }
        }
    });
    exports.AppController = AppController;
});
<commit_msg>Modified controller for auth<commit_after>define(function(require, exports, module) {
    var backbone = require('backbone');
    var marionette = require('marionette');
    var app = require('app/app');
    var $ = require('jquery');

    var Session = require('app/models/session').Session;

    var LandingLayout = require('app/layouts/landing-layout').LandingLayout;
    var HomeLayout = require('app/layouts/home-layout').HomeLayout;

    var SignupView = require('app/views/signup-view').SignupView;
    var FooterView = require('app/views/footer-view').FooterView;
    var LoginView = require('app/views/login-view').LoginView;
    var NavbarView = require('app/views/navbar-view').NavbarView

    var AppController = marionette.Controller.extend({
        initialize: function() {
            this.app = app;
            this.app.session = new Session({}, {
                remote: false
            });
            // Logic for auth check.
            if (this.app.session.has('token')) {
                console.log("User logged in");
                $.ajaxSetup({
                    headers: {'Authorization' : this.app.session.get('token')}
                })
                this.app.session = app.session;
                // user is authed, redirect home
                this.showHomeLayout();
            };
        },
        // Needed for AppRouter to initialize index route.
        index: function() {
            console.log(this.app.session)
            if (this.app.session.hasAuth()) {
                this.showHomeLayout();
            } else {
                this.app.mainRegion.show(new LandingLayout({
                    session: this.app.session
                }));
            }
        },

        showHomeLayout:function() {
            if (!this.app.session.hasAuth()) {
                this.index();
            } else {
                this.app.headerRegion.show(new NavbarView({
                    session: this.app.session
                }));
                this.app.mainRegion.show(new HomeLayout({
                    session: this.app.session
                }));
            }
        }
    });
    exports.AppController = AppController;
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'

import { Form, Segment, Header, Button } from 'semantic-ui-react'

import { submitOnlinePost, openNewPostDialog, updatePostText } from '../actions.js'
import { onlinePostsSelector, userSelector, followersSelector } from '../selectors.js'
import Post from './Post.js'

const mapStateToProps = state => {
  const { posts } = onlinePostsSelector(state)
  return {
    posts,
    followers: followersSelector(state),
    user: userSelector(state)
  }
}

const actionCreators = {
  submitOnlinePost,
  openNewPostDialog,
  updatePostText
}

class OnlinePosts extends Component {
  constructor(props) {
    super(props)
    this.submit = this.submit.bind(this)
    this.handleChangeText = this.handleChangeText.bind(this)
    this.handleKeyDown = this.handleKeyDown.bind(this)
    this.state = {
      text: ''
    }
  }

  reset() {
    this.setState({
      text: ''
    })
  }

  submit(e) {
    e.preventDefault()
    const { submitOnlinePost } = this.props
    const { text } = this.state
    if (text.length >= 1) {
      submitOnlinePost({text})
      this.reset()
    }
  }

  handleChangeText(event) {
    this.setState({text: event.target.value})
  }

  handleKeyDown(event) {
    if (event.keyCode === 13 && (event.ctrlKey || event.metaKey) && !(event.ctrlKey && event.metaKey)) {
      this.submit(event)
    }
  }

  handleClickWrite(post) {
    const { openNewPostDialog, updatePostText } = this.props
    updatePostText(post.text)
    openNewPostDialog()
  }

  render() {
    const { posts, user, followers } = this.props
    const { text } = this.state
    return (

        <Segment vertical>
          Online
        </Segment>
        <Segment vertical>
          <Form onSubmit={this.submit}>
            <Form.TextArea name='text' value={text} rows='3' placeholder={'What\'s in your head?'}
              onChange={this.handleChangeText} onKeyDown={this.handleKeyDown} autoFocus />
            <Form.Button disabled={text.length == 0} primary>Submit</Form.Button>
          </Form>
        </Segment>
        {posts.length == 0 ? (
          <Segment vertical>

Nothing to show

          </Segment>
        ) : null}
        {posts.map(post => (
          <Post
            key={post.id}
            postLink={false}
            followButton={false}
            favButton={false}
            replyButton={false}
            attributeIcon={followers.includes(post.user.id) ? 'exchange' : null}
            prefix={post.user.name == user.name ? (
              <Button icon='write' size='mini' onClick={() => this.handleClickWrite(post)} />
            ) : null}
            post={post}
          />
        ))}

    )
  }
}

export default connect(mapStateToProps, actionCreators)(OnlinePosts)
<commit_msg>Enhance appearance<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'

import { Form, Segment, Header, Button } from 'semantic-ui-react'

import { submitOnlinePost, openNewPostDialog, updatePostText } from '../actions.js'
import { onlinePostsSelector, userSelector, followersSelector } from '../selectors.js'
import Post from './Post.js'

const mapStateToProps = state => {
  const { posts } = onlinePostsSelector(state)
  return {
    posts,
    followers: followersSelector(state),
    user: userSelector(state)
  }
}

const actionCreators = {
  submitOnlinePost,
  openNewPostDialog,
  updatePostText
}

class OnlinePosts extends Component {
  constructor(props) {
    super(props)
    this.submit = this.submit.bind(this)
    this.handleChangeText = this.handleChangeText.bind(this)
    this.handleKeyDown = this.handleKeyDown.bind(this)
    this.state = {
      text: ''
    }
  }

  reset() {
    this.setState({
      text: ''
    })
  }

  submit(e) {
    e.preventDefault()
    const { submitOnlinePost } = this.props
    const { text } = this.state
    if (text.length >= 1) {
      submitOnlinePost({text})
      this.reset()
    }
  }

  handleChangeText(event) {
    this.setState({text: event.target.value})
  }

  handleKeyDown(event) {
    if (event.keyCode === 13 && (event.ctrlKey || event.metaKey) && !(event.ctrlKey && event.metaKey)) {
      this.submit(event)
    }
  }

  handleClickWrite(post) {
    const { openNewPostDialog, updatePostText } = this.props
    updatePostText(post.text)
    openNewPostDialog()
  }

  render() {
    const { posts, user, followers } = this.props
    const { text } = this.state
    return (

        <Segment vertical>
          Online
        </Segment>
        <Segment vertical>
          <Form onSubmit={this.submit}>
            <Form.TextArea name='text' value={text} rows='3' placeholder={'What\'s in your head?'}
              onChange={this.handleChangeText} onKeyDown={this.handleKeyDown} autoFocus />
            <Form.Button disabled={text.length == 0} primary>Submit</Form.Button>
          </Form>
        </Segment>
        {posts.length == 0 ? (
          <Segment vertical>

Nothing to show

          </Segment>
        ) : null}
        {posts.map(post => (
          <Post
            key={post.id}
            postLink={false}
            followButton={false}
            favButton={false}
            replyButton={false}
            attributeIcon={followers.includes(post.user.id) ? 'exchange' : null}
            prefix={post.user.name == user.name ? (
              <Button icon='clone' size='mini' onClick={() => this.handleClickWrite(post)} />
            ) : null}
            post={post}
          />
        ))}

    )
  }
}

export default connect(mapStateToProps, actionCreators)(OnlinePosts)
<|endoftext|>


<commit_before>/*
 * Please rename this file to "stations-custom.js" if you actually want to use it :-)
 * This file contains all your custom stations.
 *
 * How it works:
 * The stations_custom object contains several country arrays.
 * Each array contains the stations for that country.
 * Each station is an object containing a name, logo and url property.
 * It follows the basic JavaScript object notation.
 *
 * You may want to peek at the stations-america.js and stations-europe.js files as to how it works.
 * Please make sure that you use the country name that is used in-game as well,
 * and please make sure the URL is the actual radio stream.
 * Please note that for the logo to show in the overlay, it needs to be referenced as a relative path from the web folder
 * (e.g. stations/images-custom/My custom station.png). The website supports both.
 * You can test that by opening the URL in VLC media player, if it plays, it is probably the right URL.
 *
 * Additionally, you can also put stations under the "global" country. These stations will be available everywhere.
 * You can see TruckersFM and Dagnys Jukebox added here as an example.
 */

var stations_custom = {
    "Country name": [
        {
            name: "Station name",
            logo: "Logo URL",
            url: "Stream URL"
        }
    ],
    "global": [
        {
            name: "TruckersFM",
            logo: "http://i.imgur.com/fKTlA58.png",
            url: "http://radio.truckers.fm/"
        },
        {
            name: "Dagnys Jukebox",
            logo: "http://static.radio.net/images/broadcasts/3f/79/32940/c175.png",
            url: "http://streaming2.nordblommedia.se:443/dagny.mp3"
        },
    ]
};<commit_msg>Apparently I made some mistakes and completely looked over them... Whoops.<commit_after>/*
 * Please rename this file to "stations-custom.js" if you actually want to use it :-)
 * This file contains all your custom stations.
 *
 * How it works:
 * The stations_custom object contains several country arrays.
 * Each array contains the stations for that country.
 * Each station is an object containing a name, logo and url property.
 * It follows the basic JavaScript object notation.
 *
 * You may want to peek at the stations-america.js and stations-europe.js files as to how it works.
 * Please make sure that you use the country name that is used in-game as well,
 * and please make sure the URL is the actual radio stream.
 * You can test that by opening the URL in VLC media player, if it plays, it is probably the right URL.
 * Please note that for the logo to show in the overlay, it needs to be referenced as a relative path from the web folder
 * (e.g. stations/images-custom/My custom station.png). The website supports full URLs too.
 *
 * Additionally, you can also put stations under the "global" country. These stations will be available everywhere.
 * You can see TruckersFM and Dagnys Jukebox added here as an example.
 */

var stations_custom = {
    "Country name": [
        {
            name: "Station name",
            logo: "Logo URL",
            url: "Stream URL"
        }
    ],
    "global": [
        {
            name: "TruckersFM",
            logo: "http://i.imgur.com/fKTlA58.png",
            url: "http://radio.truckers.fm/"
        },
        {
            name: "Dagnys Jukebox",
            logo: "http://static.radio.net/images/broadcasts/3f/79/32940/c175.png",
            url: "http://streaming2.nordblommedia.se:443/dagny.mp3"
        },
    ]
};<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { Link } from 'react-router'
import classnames from 'classnames'

import Date from '../../components/Date'
import Tag from '../../components/Tag'
import styles from './PostItem.scss'

const PostItem = ({__url, date, title, draft, tags, description}) => {
  const articleClass = classnames({
    [styles.article]: true,
    [styles.draft]: draft
  })

  const linkClass = classnames({
    [styles.title]: true,
    [styles.titleDraft]: draft
  })

  return (

      <Link
        to={__url}
        className={linkClass}
      >
        {title}
      </Link>

        {
          tags &&
          Array.isArray(tags) &&
            tags.map((tag) =>
              <Tag key={tag} name={tag} />
            )
        }
        <Date date={date} className={styles.date} />

      {
        description &&

{description}

      }

  )
}

PostItem.propTypes = {
  __url: PropTypes.string.isRequired,
  date: PropTypes.string.isRequired,
  title: PropTypes.string.isRequired,
  description: PropTypes.string,
  draft: PropTypes.boolean,
  tags: PropTypes.array
}

export default PostItem
<commit_msg>chore: Refactor classnames usage a little bit<commit_after>import React, { PropTypes } from 'react'
import { Link } from 'react-router'
import classnames from 'classnames'

import Date from '../../components/Date'
import Tag from '../../components/Tag'
import styles from './PostItem.scss'

const PostItem = ({__url, date, title, draft, tags, description}) => {
  const articleClass = classnames(styles.article, {
    [styles.draft]: draft
  })

  const linkClass = classnames(styles.title, {
    [styles.titleDraft]: draft
  })

  return (

      <Link
        to={__url}
        className={linkClass}
      >
        {title}
      </Link>

        {
          tags &&
          Array.isArray(tags) &&
            tags.map((tag) =>
              <Tag key={tag} name={tag} />
            )
        }
        <Date date={date} className={styles.date} />

      {
        description &&

{description}

      }

  )
}

PostItem.propTypes = {
  __url: PropTypes.string.isRequired,
  date: PropTypes.string.isRequired,
  title: PropTypes.string.isRequired,
  description: PropTypes.string,
  draft: PropTypes.boolean,
  tags: PropTypes.array
}

export default PostItem
<|endoftext|>


<commit_before>import {
  invoke
} from 'uni-core/service/bridge'

import {
  onMethod,
  invokeMethod
} from '../../platform'

class DownloadTask {
  constructor (downloadTaskId, callbackId) {
    this.id = downloadTaskId
    this._callbackId = callbackId
    this._callbacks = []
  }

  abort () {
    invokeMethod('operateRequestTask', {
      downloadTaskId: this.id,
      operationType: 'abort'
    })
  }

  onProgressUpdate (callback) {
    if (typeof callback !== 'function') {
      return
    }
    this._callbacks.push(callback)
  }

  onHeadersReceived () {

  }

  offProgressUpdate (callback) {
    const index = this._callbacks.indexOf(callback)
    if (index >= 0) {
      this._callbacks.splice(index, 1)
    }
  }

  offHeadersReceived () {

  }
}
const downloadTasks = Object.create(null)
onMethod('onDownloadTaskStateChange', ({
  downloadTaskId,
  state,
  tempFilePath,
  statusCode,
  progress,
  totalBytesWritten,
  totalBytesExpectedToWrite,
  errMsg
}) => {
  const downloadTask = downloadTasks[downloadTaskId]
  const callbackId = downloadTask._callbackId

  switch (state) {
    case 'progressUpdate':
      downloadTask._callbacks.forEach(callback => {
        callback({
          progress,
          totalBytesWritten,
          totalBytesExpectedToWrite
        })
      })
      break
    case 'success':
      invoke(callbackId, {
        tempFilePath,
        statusCode,
        errMsg: 'request:ok'
      })
      // eslint-disable-next-line no-fallthrough
    case 'fail':
      invoke(callbackId, {
        errMsg: 'request:fail ' + errMsg
      })
      // eslint-disable-next-line no-fallthrough
    default:
      // progressUpdate 可能晚于 success
      setTimeout(() => {
        delete downloadTasks[downloadTaskId]
      }, 100)
      break
  }
})
export function downloadFile (args, callbackId) {
  const {
    downloadTaskId
  } = invokeMethod('createDownloadTask', args)
  const task = new DownloadTask(downloadTaskId, callbackId)
  downloadTasks[downloadTaskId] = task
  return task
}
<commit_msg>fix: App平台 修复 downloadTask.abort不生效的bug askId: 93342<commit_after>import {
  invoke
} from 'uni-core/service/bridge'

import {
  onMethod,
  invokeMethod
} from '../../platform'

class DownloadTask {
  constructor (downloadTaskId, callbackId) {
    this.id = downloadTaskId
    this._callbackId = callbackId
    this._callbacks = []
  }

  abort () {
    invokeMethod('operateDownloadTask', {
      downloadTaskId: this.id,
      operationType: 'abort'
    })
  }

  onProgressUpdate (callback) {
    if (typeof callback !== 'function') {
      return
    }
    this._callbacks.push(callback)
  }

  onHeadersReceived () {

  }

  offProgressUpdate (callback) {
    const index = this._callbacks.indexOf(callback)
    if (index >= 0) {
      this._callbacks.splice(index, 1)
    }
  }

  offHeadersReceived () {

  }
}
const downloadTasks = Object.create(null)
onMethod('onDownloadTaskStateChange', ({
  downloadTaskId,
  state,
  tempFilePath,
  statusCode,
  progress,
  totalBytesWritten,
  totalBytesExpectedToWrite,
  errMsg
}) => {
  const downloadTask = downloadTasks[downloadTaskId]
  const callbackId = downloadTask._callbackId

  switch (state) {
    case 'progressUpdate':
      downloadTask._callbacks.forEach(callback => {
        callback({
          progress,
          totalBytesWritten,
          totalBytesExpectedToWrite
        })
      })
      break
    case 'success':
      invoke(callbackId, {
        tempFilePath,
        statusCode,
        errMsg: 'request:ok'
      })
      // eslint-disable-next-line no-fallthrough
    case 'fail':
      invoke(callbackId, {
        errMsg: 'request:fail ' + errMsg
      })
      // eslint-disable-next-line no-fallthrough
    default:
      // progressUpdate 可能晚于 success
      setTimeout(() => {
        delete downloadTasks[downloadTaskId]
      }, 100)
      break
  }
})
export function downloadFile (args, callbackId) {
  const {
    downloadTaskId
  } = invokeMethod('createDownloadTask', args)
  const task = new DownloadTask(downloadTaskId, callbackId)
  downloadTasks[downloadTaskId] = task
  return task
}
<|endoftext|>


<commit_before>'use strict';

const isNil = require('lodash.isnil');

/**
 * A shape which has already been indexed in another index and/or index
 * type. This is particularly useful for when you have a pre-defined list of
 * shapes which are useful to your application and you want to reference this
 * using a logical name (for example 'New Zealand') rather than having to
 * provide their coordinates each time.
 *
 * @example
 * const shape = bob.indexedShape('DEU', 'countries')
 *     .index('shapes')
 *     .path('location');
 *
 * const shape = bob.indexedShape()
 *     .id('DEU')
 *     .type('countries')
 *     .index('shapes')
 *     .path('location');
 *
 * @param {string} id The document id of the shape.
 * @param {string} type The name of the type where the shape is indexed.
 */
class IndexedShape {
    // eslint-disable-next-line require-jsdoc
    constructor(id, type) {
        this._body = {};

        if (!isNil(id)) this._body.id = id;
        if (!isNil(type)) this._body.type = type;
    }

    /**
     * Sets the ID of the document that containing the pre-indexed shape.
     *
     * @param {string} id The document id of the shape.
     * @returns {IndexedShape} returns `this` so that calls can be chained.
     */
    id(id) {
        this._body.id = id;
        return this;
    }

    /**
     * Sets the index type where the pre-indexed shape is.
     *
     * @param {string} type The name of the type where the shape is indexed.
     * @returns {IndexedShape} returns `this` so that calls can be chained.
     */
    type(type) {
        this._body.type = type;
        return this;
    }

    /**
     * Sets the name of the index where the pre-indexed shape is. Defaults to `shapes`.
     *
     * @param {string} index A valid index name
     * @returns {IndexedShape} returns `this` so that calls can be chained.
     */
    index(index) {
        this._body.index = index;
        return this;
    }

    /**
     * Sets the field specified as path containing the pre-indexed shape.
     * Defaults to `shape`.
     *
     * @param {string} path field name.
     * @returns {IndexedShape} returns `this` so that calls can be chained.
     */
    path(path) {
        this._body.path = path;
        return this;
    }

    /**
     * Override default `toJSON` to return DSL representation of the geo shape
     * class instance.
     *
     * @override
     * @returns {Object} returns an Object which maps to the elasticsearch query DSL
     */
    toJSON() {
        return this._body;
    }
}

module.exports = IndexedShape;
<commit_msg>docs(IndexedShape): Annotate params to constructor as optional<commit_after>'use strict';

const isNil = require('lodash.isnil');

/**
 * A shape which has already been indexed in another index and/or index
 * type. This is particularly useful for when you have a pre-defined list of
 * shapes which are useful to your application and you want to reference this
 * using a logical name (for example 'New Zealand') rather than having to
 * provide their coordinates each time.
 *
 * @example
 * const shape = bob.indexedShape('DEU', 'countries')
 *     .index('shapes')
 *     .path('location');
 *
 * const shape = bob.indexedShape()
 *     .id('DEU')
 *     .type('countries')
 *     .index('shapes')
 *     .path('location');
 *
 * @param {string=} id The document id of the shape.
 * @param {string=} type The name of the type where the shape is indexed.
 */
class IndexedShape {
    // eslint-disable-next-line require-jsdoc
    constructor(id, type) {
        this._body = {};

        if (!isNil(id)) this._body.id = id;
        if (!isNil(type)) this._body.type = type;
    }

    /**
     * Sets the ID of the document that containing the pre-indexed shape.
     *
     * @param {string} id The document id of the shape.
     * @returns {IndexedShape} returns `this` so that calls can be chained.
     */
    id(id) {
        this._body.id = id;
        return this;
    }

    /**
     * Sets the index type where the pre-indexed shape is.
     *
     * @param {string} type The name of the type where the shape is indexed.
     * @returns {IndexedShape} returns `this` so that calls can be chained.
     */
    type(type) {
        this._body.type = type;
        return this;
    }

    /**
     * Sets the name of the index where the pre-indexed shape is. Defaults to `shapes`.
     *
     * @param {string} index A valid index name
     * @returns {IndexedShape} returns `this` so that calls can be chained.
     */
    index(index) {
        this._body.index = index;
        return this;
    }

    /**
     * Sets the field specified as path containing the pre-indexed shape.
     * Defaults to `shape`.
     *
     * @param {string} path field name.
     * @returns {IndexedShape} returns `this` so that calls can be chained.
     */
    path(path) {
        this._body.path = path;
        return this;
    }

    /**
     * Override default `toJSON` to return DSL representation of the geo shape
     * class instance.
     *
     * @override
     * @returns {Object} returns an Object which maps to the elasticsearch query DSL
     */
    toJSON() {
        return this._body;
    }
}

module.exports = IndexedShape;
<|endoftext|>


<commit_before>/**
 * This JS file is for additional new JS built over the existing theme
 * ...so as to avoid breaking anything unexpectedly
 */
(function ($) {
  $(document).ready(function () {
    /**
     * Dropdown menu
     */
    var triggers = document.querySelectorAll(
      ".main-nav li.menu-item-has-children"
    );
    var background = document.querySelector(".dropdownBackground");
    var nav = document.querySelector(".main-nav");

    function handleEnter() {
      this.classList.add("trigger-enter");
      setTimeout(
        () =>
          this.classList.contains("trigger-enter") &&
          this.classList.add("trigger-enter-active"),
        150
      );
      background.classList.add("open");

      var dropdown = this.querySelector(".main-nav .sub-menu");
      var dropdownCoords = dropdown.getBoundingClientRect();
      var navCoords = nav.getBoundingClientRect();

      var coords = {
        height: dropdownCoords.height,
        width: dropdownCoords.width,
        top: dropdownCoords.top - navCoords.top + 5,
        left: dropdownCoords.left - navCoords.left,
      };

      background.style.setProperty("width", `${coords.width}px`);
      background.style.setProperty("height", `${coords.height}px`);
      background.style.setProperty(
        "transform",
        `translate(${coords.left}px, ${coords.top}px)`
      );
    }

    function handleLeave() {
      this.classList.remove("trigger-enter", "trigger-enter-active");
      background.classList.remove("open");
    }

    triggers.forEach((trigger) =>
      trigger.addEventListener("mouseenter", handleEnter)
    );
    triggers.forEach((trigger) =>
      trigger.addEventListener("mouseleave", handleLeave)
    );

    /**
     * Set height on sidebar
     */
    var viewportHeight = Math.max(
      document.documentElement.clientHeight,
      window.innerHeight || 0
    );
    var $sidebar = $(".bs-docs-sidebar");
    $sidebar.css("max-height", `${viewportHeight - 40}px`);
  });

  $(document).ready(function () {
    $("form#ratingForm").submit(function (e) {
      e.preventDefault(); // prevent the default click action from being performed
      if ($("#ratingForm :radio:checked").length == 0) {
        $("#ratingStatus").html("Select rating");
        return false;
      } else {
        $("#ratingStatus").html("Thank you for your feedback!");
        $("#ratingVote").prop("disabled", true);
        analytics.track(
          "Stars Rating: " + $("input:radio[name=rating]:checked").val()
        );
      }
    });
  });

  function headerSize() {
    var doc = document.documentElement;
    var w = window;

    var curScroll;
    var prevScroll = w.scrollY || doc.scrollTop;
    var curDirection = 0;
    var prevDirection = 0;

    var header = document.getElementById("top");
    var toggled;
    var threshold = 200;

    var menuHeight = $("#top").outerHeight();
    var notifbarHeight = $(".notification-banner").outerHeight();
    var totalHeight = menuHeight + notifbarHeight;

    if ($("body.notif-bar-enabled")) {
      $(".notif-bar-enabled .body-container-wrapper").css(
        "padding-top",
        totalHeight + "px"
      );
      $(".notif-bar-enabled .w-canvas").css("padding-top", totalHeight + "px");
      $(".notif-bar-enabled header.header").css(
        "margin-top",
        notifbarHeight + "px"
      );
      $(".notif-bar-enabled header.header-nav").css(
        "margin-top",
        notifbarHeight + "px"
      );
    }

    if (!$("body").hasClass("notif-bar-enabled")) {
      $(".body-container-wrapper").css("padding-top", menuHeight + "px");
      $("body .w-canvas").css("padding-top", menuHeight + "px");
    }

    var checkScroll = function () {
      curScroll = w.scrollY || doc.scrollTop;
      if (curScroll > prevScroll) {
        // scrolled down
        curDirection = 2;
      } else {
        //scrolled up
        curDirection = 1;
      }

      if (curDirection !== prevDirection) {
        toggled = toggleHeader();
      }

      prevScroll = curScroll;
      if (toggled) {
        prevDirection = curDirection;
      }
    };

    var toggleHeader = function () {
      toggled = true;
      promobar = document.getElementById("top");
      if (curDirection === 2 && curScroll > threshold) {
        //header.classList.add('disappear');
        if (promobar) {
          promobar.style.top = "-" + menuHeight + "px";
        }
      } else if (curDirection === 1) {
        //header.classList.remove('disappear');
        if (promobar) {
          document.getElementById("top").style.top = "0px";
        }
      } else {
        toggled = false;
      }
      return toggled;
    };

    window.addEventListener("scroll", checkScroll);
  }

  jQuery(function ($) {
    // Register for window resize
    $(window).resize(headerSize);
    // Do initial resize
    headerSize();
  });

  $(document).ready(function () {
    setTimeout(function checkHash() {
      var menuHeight = document.querySelector('#top').offsetHeight;
      document.getElementById("top").style.top = "-" + menuHeight + "px";
    }, 1000);
  });

})(jQuery);
<commit_msg>readded check for hash<commit_after>/**
 * This JS file is for additional new JS built over the existing theme
 * ...so as to avoid breaking anything unexpectedly
 */
(function ($) {
  $(document).ready(function () {
    /**
     * Dropdown menu
     */
    var triggers = document.querySelectorAll(
      ".main-nav li.menu-item-has-children"
    );
    var background = document.querySelector(".dropdownBackground");
    var nav = document.querySelector(".main-nav");

    function handleEnter() {
      this.classList.add("trigger-enter");
      setTimeout(
        () =>
          this.classList.contains("trigger-enter") &&
          this.classList.add("trigger-enter-active"),
        150
      );
      background.classList.add("open");

      var dropdown = this.querySelector(".main-nav .sub-menu");
      var dropdownCoords = dropdown.getBoundingClientRect();
      var navCoords = nav.getBoundingClientRect();

      var coords = {
        height: dropdownCoords.height,
        width: dropdownCoords.width,
        top: dropdownCoords.top - navCoords.top + 5,
        left: dropdownCoords.left - navCoords.left,
      };

      background.style.setProperty("width", `${coords.width}px`);
      background.style.setProperty("height", `${coords.height}px`);
      background.style.setProperty(
        "transform",
        `translate(${coords.left}px, ${coords.top}px)`
      );
    }

    function handleLeave() {
      this.classList.remove("trigger-enter", "trigger-enter-active");
      background.classList.remove("open");
    }

    triggers.forEach((trigger) =>
      trigger.addEventListener("mouseenter", handleEnter)
    );
    triggers.forEach((trigger) =>
      trigger.addEventListener("mouseleave", handleLeave)
    );

    /**
     * Set height on sidebar
     */
    var viewportHeight = Math.max(
      document.documentElement.clientHeight,
      window.innerHeight || 0
    );
    var $sidebar = $(".bs-docs-sidebar");
    $sidebar.css("max-height", `${viewportHeight - 40}px`);
  });

  $(document).ready(function () {
    $("form#ratingForm").submit(function (e) {
      e.preventDefault(); // prevent the default click action from being performed
      if ($("#ratingForm :radio:checked").length == 0) {
        $("#ratingStatus").html("Select rating");
        return false;
      } else {
        $("#ratingStatus").html("Thank you for your feedback!");
        $("#ratingVote").prop("disabled", true);
        analytics.track(
          "Stars Rating: " + $("input:radio[name=rating]:checked").val()
        );
      }
    });
  });

  function headerSize() {
    var doc = document.documentElement;
    var w = window;

    var curScroll;
    var prevScroll = w.scrollY || doc.scrollTop;
    var curDirection = 0;
    var prevDirection = 0;

    var header = document.getElementById("top");
    var toggled;
    var threshold = 200;

    var menuHeight = $("#top").outerHeight();
    var notifbarHeight = $(".notification-banner").outerHeight();
    var totalHeight = menuHeight + notifbarHeight;

    if ($("body.notif-bar-enabled")) {
      $(".notif-bar-enabled .body-container-wrapper").css(
        "padding-top",
        totalHeight + "px"
      );
      $(".notif-bar-enabled .w-canvas").css("padding-top", totalHeight + "px");
      $(".notif-bar-enabled header.header").css(
        "margin-top",
        notifbarHeight + "px"
      );
      $(".notif-bar-enabled header.header-nav").css(
        "margin-top",
        notifbarHeight + "px"
      );
    }

    if (!$("body").hasClass("notif-bar-enabled")) {
      $(".body-container-wrapper").css("padding-top", menuHeight + "px");
      $("body .w-canvas").css("padding-top", menuHeight + "px");
    }

    var checkScroll = function () {
      curScroll = w.scrollY || doc.scrollTop;
      if (curScroll > prevScroll) {
        // scrolled down
        curDirection = 2;
      } else {
        //scrolled up
        curDirection = 1;
      }

      if (curDirection !== prevDirection) {
        toggled = toggleHeader();
      }

      prevScroll = curScroll;
      if (toggled) {
        prevDirection = curDirection;
      }
    };

    var toggleHeader = function () {
      toggled = true;
      promobar = document.getElementById("top");
      if (curDirection === 2 && curScroll > threshold) {
        //header.classList.add('disappear');
        if (promobar) {
          promobar.style.top = "-" + menuHeight + "px";
        }
      } else if (curDirection === 1) {
        //header.classList.remove('disappear');
        if (promobar) {
          document.getElementById("top").style.top = "0px";
        }
      } else {
        toggled = false;
      }
      return toggled;
    };

    window.addEventListener("scroll", checkScroll);
  }

  jQuery(function ($) {
    // Register for window resize
    $(window).resize(headerSize);
    // Do initial resize
    headerSize();
  });

  $(document).ready(function () {
    if (window.location.hash) {
      setTimeout(function checkHash() {
        var menuHeight = document.querySelector("#top").offsetHeight;
        document.getElementById("top").style.top = "-" + menuHeight + "px";
      }, 1000);
    }
  });

})(jQuery);
<|endoftext|>


<commit_before>
"use strict";

export $http => {
    delete $http.defaults.headers.common['X-Requested-With'];
    $http.defaults.withCredentials = true;
    $http.defaults.headers.post["Content-Type"] = 'application/x-www-form-urlencoded;charset=utf-8';

    // http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
    function param(obj) {
        var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
        for (name in obj) {
            value = obj[name];
            if (value instanceof Array) {
                for (i = 0; i < value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value instanceof Object) {
                for (subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value !== undefined && value !== null) {
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
            }
        }
        return query.length ? query.substr(0, query.length - 1) : query;
    };
    // Override $http service's default transformRequest
    $http.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
};

<commit_msg>needs default<commit_after>
"use strict";

export default $http => {
    delete $http.defaults.headers.common['X-Requested-With'];
    $http.defaults.withCredentials = true;
    $http.defaults.headers.post["Content-Type"] = 'application/x-www-form-urlencoded;charset=utf-8';

    // http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
    function param(obj) {
        var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
        for (name in obj) {
            value = obj[name];
            if (value instanceof Array) {
                for (i = 0; i < value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value instanceof Object) {
                for (subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value !== undefined && value !== null) {
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
            }
        }
        return query.length ? query.substr(0, query.length - 1) : query;
    };
    // Override $http service's default transformRequest
    $http.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
};

<|endoftext|>


<commit_before>// @flow

import React, { Fragment, useContext } from 'react';
import ProfilerStore from 'src/devtools/ProfilerStore';
import { ProfilerContext } from './ProfilerContext';
import { formatDuration, formatTime } from './utils';
import { StoreContext } from '../context';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';

import styles from './SidebarSelectedFiberInfo.css';

export type Props = {||};

export default function SidebarSelectedFiberInfo(_: Props) {
  const { profilerStore } = useContext(StoreContext);
  const {
    rootID,
    selectCommitIndex,
    selectedCommitIndex,
    selectedFiberID,
    selectedFiberName,
    selectFiber,
  } = useContext(ProfilerContext);
  const { profilingCache } = profilerStore;

  const commitIndices = profilingCache.getFiberCommits({
    fiberID: ((selectedFiberID: any): number),
    rootID: ((rootID: any): number),
  });

  const listItems = [];
  for (let i = 0; i < commitIndices.length; i++) {
    const commitIndex = commitIndices[i];

    const { duration, timestamp } = profilerStore.getCommitData(
      ((rootID: any): number),
      commitIndex
    );

    listItems.push(
      <button
        key={commitIndex}
        className={
          selectedCommitIndex === commitIndex
            ? styles.CurrentCommit
            : styles.Commit
        }
        onClick={() => selectCommitIndex(commitIndex)}
      >
        {formatTime(timestamp)}s for {formatDuration(duration)}ms
      </button>
    );
  }

  return (
    <Fragment>

          {selectedFiberName || 'Selected component'}

        <Button
          className={styles.IconButton}
          onClick={() => selectFiber(null, null)}
          title="Back to commit view"
        >
          <ButtonIcon type="close" />
        </Button>

      <WhatChanged
        commitIndex={((selectedCommitIndex: any): number)}
        fiberID={((selectedFiberID: any): number)}
        profilerStore={profilerStore}
        rootID={((rootID: any): number)}
      />

        Rendered at: {listItems}

    </Fragment>
  );
}

type WhatChangedProps = {|
  commitIndex: number,
  fiberID: number,
  profilerStore: ProfilerStore,
  rootID: number,
|};

function WhatChanged({
  commitIndex,
  fiberID,
  profilerStore,
  rootID,
}: WhatChangedProps) {
  const { changeDescriptions } = profilerStore.getCommitData(
    ((rootID: any): number),
    commitIndex
  );
  if (changeDescriptions === null) {
    return null;
  }

  const changeDescription = changeDescriptions.get(fiberID);
  if (changeDescription == null) {
    return null;
  }

  if (changeDescription.isFirstMount) {
    return (

        Why did this render?

          This is the first time the component rendered.

    );
  }

  const changes = [];

  if (changeDescription.context === true) {
    changes.push(

        • Context changed

    );
  } else if (
    typeof changeDescription.context === 'object' &&
    changeDescription.context !== null &&
    changeDescription.context.length !== 0
  ) {
    changes.push(

        • Context changed:
        {changeDescription.context.map(key => (

            {key}

        ))}

    );
  }

  if (changeDescription.didHooksChange) {
    changes.push(

        • Hooks changed

    );
  }

  if (
    changeDescription.props !== null &&
    changeDescription.props.length !== 0
  ) {
    changes.push(

        • Props changed:
        {changeDescription.props.map(key => (

            {key}

        ))}

    );
  }

  if (
    changeDescription.state !== null &&
    changeDescription.state.length !== 0
  ) {
    changes.push(

        • State changed:
        {changeDescription.state.map(key => (

            {key}

        ))}

    );
  }

  if (changes.length === 0) {
    changes.push(

        The parent component rendered.

    );
  }

  return (

      Why did this render?
      {changes}

  );
}
<commit_msg>Only show "rendered at" if selected Fiber committed at least once<commit_after>// @flow

import React, { Fragment, useContext } from 'react';
import ProfilerStore from 'src/devtools/ProfilerStore';
import { ProfilerContext } from './ProfilerContext';
import { formatDuration, formatTime } from './utils';
import { StoreContext } from '../context';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';

import styles from './SidebarSelectedFiberInfo.css';

export type Props = {||};

export default function SidebarSelectedFiberInfo(_: Props) {
  const { profilerStore } = useContext(StoreContext);
  const {
    rootID,
    selectCommitIndex,
    selectedCommitIndex,
    selectedFiberID,
    selectedFiberName,
    selectFiber,
  } = useContext(ProfilerContext);
  const { profilingCache } = profilerStore;

  const commitIndices = profilingCache.getFiberCommits({
    fiberID: ((selectedFiberID: any): number),
    rootID: ((rootID: any): number),
  });

  const listItems = [];
  for (let i = 0; i < commitIndices.length; i++) {
    const commitIndex = commitIndices[i];

    const { duration, timestamp } = profilerStore.getCommitData(
      ((rootID: any): number),
      commitIndex
    );

    listItems.push(
      <button
        key={commitIndex}
        className={
          selectedCommitIndex === commitIndex
            ? styles.CurrentCommit
            : styles.Commit
        }
        onClick={() => selectCommitIndex(commitIndex)}
      >
        {formatTime(timestamp)}s for {formatDuration(duration)}ms
      </button>
    );
  }

  return (
    <Fragment>

          {selectedFiberName || 'Selected component'}

        <Button
          className={styles.IconButton}
          onClick={() => selectFiber(null, null)}
          title="Back to commit view"
        >
          <ButtonIcon type="close" />
        </Button>

      <WhatChanged
        commitIndex={((selectedCommitIndex: any): number)}
        fiberID={((selectedFiberID: any): number)}
        profilerStore={profilerStore}
        rootID={((rootID: any): number)}
      />

        {listItems.length > 0 && (
          <Fragment>
            Rendered at: {listItems}
          </Fragment>
        )}

    </Fragment>
  );
}

type WhatChangedProps = {|
  commitIndex: number,
  fiberID: number,
  profilerStore: ProfilerStore,
  rootID: number,
|};

function WhatChanged({
  commitIndex,
  fiberID,
  profilerStore,
  rootID,
}: WhatChangedProps) {
  const { changeDescriptions } = profilerStore.getCommitData(
    ((rootID: any): number),
    commitIndex
  );
  if (changeDescriptions === null) {
    return null;
  }

  const changeDescription = changeDescriptions.get(fiberID);
  if (changeDescription == null) {
    return null;
  }

  if (changeDescription.isFirstMount) {
    return (

        Why did this render?

          This is the first time the component rendered.

    );
  }

  const changes = [];

  if (changeDescription.context === true) {
    changes.push(

        • Context changed

    );
  } else if (
    typeof changeDescription.context === 'object' &&
    changeDescription.context !== null &&
    changeDescription.context.length !== 0
  ) {
    changes.push(

        • Context changed:
        {changeDescription.context.map(key => (

            {key}

        ))}

    );
  }

  if (changeDescription.didHooksChange) {
    changes.push(

        • Hooks changed

    );
  }

  if (
    changeDescription.props !== null &&
    changeDescription.props.length !== 0
  ) {
    changes.push(

        • Props changed:
        {changeDescription.props.map(key => (

            {key}

        ))}

    );
  }

  if (
    changeDescription.state !== null &&
    changeDescription.state.length !== 0
  ) {
    changes.push(

        • State changed:
        {changeDescription.state.map(key => (

            {key}

        ))}

    );
  }

  if (changes.length === 0) {
    changes.push(

        The parent component rendered.

    );
  }

  return (

      Why did this render?
      {changes}

  );
}
<|endoftext|>


<commit_before>"use strict";

// the users input is scanned for these keywords
// and can trigger the messages below
// chance controls the frequency the result will be echoed back by the camper

// using js rather than json so we can have functions and comments

var Utils = require('../../lib/utils/Utils');
var BotCommands = require('../../lib/bot/BotCommands');
var _ = require('lodash-node');

// TODO - add these to all of the rooms
// this is easier for people to add content to as they don't have to add to two lists
var AllRoomMessages = [
    {
        // regex: /help.*bonfire:?s?[.?]$/i,
        regex: /.*help.*bonfire:?s?/i,
        text: " > type `bonfire name` to get some info on that bonfire. And check [HelpBonfires chatroom](https://gitter.im/FreeCodeCamp/HelpBonfires)",
        not: 'freecodecamp/HelpBonfires'  // optional to skip for this room
    },

    {
        regex: /botx/i,
        text: "> you called?",
    },

    {
        regex: /troll/i,
        text: "> :trollface: troll problems? [notify admins here](https://gitter.im/camperbot/admins)",
    },
    {
        regex: /allyourbase/,
        text: "![all your base](https://files.gitter.im/FreeCodeCamp/CoreTeam/Bw51/imgres.jpg)",
    },
    {
        regex: /'''/,
        text: "> :bulb: to format code use backticks! ``` [more info](https://github.com/freecodecamp/freecodecamp/wiki/code-formatting)",
    },
    {
        regex: /holler/i,
        text: "> holler back!",
        chance: 1   // only say this 50% of the time
    },
    {
        regex: /(?:thanks)/,
        func: BotCommands.thanks
    }
]

var RoomMessages = {

    scanInput: function(input, roomName, chance) {
        if (Math.random() > chance) {
            return null;   // dont always reply
        }
        var oneMessage;
        var chat = input.message.model.text.toLowerCase();
        chance = chance || 1;
        roomName = roomName.toLowerCase();

        // some messages are only for certain rooms so exclude them here
        var thisRoomMessages = AllRoomMessages.filter(function(msg) {
            if (msg.not) {
                return (msg.not != roomName);
            } else {
                return true;
            }
        });
        if (!thisRoomMessages) { return false; }

        var msgList = thisRoomMessages.filter(function(item) {
            if(!item) { return null; }

            if (item.regex) {
              var flag = item.regex.test(chat);
            }

            if(flag) {
                //Utils.clog(chat, item.word, "flag:" + flag);
            }
            return flag;
        });

        // now check if chance is high enough
        if (msgList.length > 0) {

            oneMessage = _.sample(msgList);  // if we have multiple messages, make sure to choose just one
            chance = oneMessage.chance || 1; // check if the chance is high enough so we can have % of time messages
            if (Math.random() < (chance)) {
                // we have a winner!
                return oneMessage;
            }
        } else {
            return null;
        }

    }

};

module.exports = RoomMessages;
<commit_msg>Update RoomMessages.js<commit_after>"use strict";

// the users input is scanned for these keywords
// and can trigger the messages below
// chance controls the frequency the result will be echoed back by the camper

// using js rather than json so we can have functions and comments

var Utils = require('../../lib/utils/Utils');
var BotCommands = require('../../lib/bot/BotCommands');
var _ = require('lodash-node');

// TODO - add these to all of the rooms
// this is easier for people to add content to as they don't have to add to two lists
var AllRoomMessages = [
    {
        // regex: /help.*bonfire:?s?[.?]$/i,
        regex: /.*help.*bonfire:?s?/i,
        text: " > type `bonfire name` to get some info on that bonfire. And check [HelpBonfires chatroom](https://gitter.im/FreeCodeCamp/HelpBonfires)",
        not: 'freecodecamp/HelpBonfires'  // optional to skip for this room
    },

    {
        regex: /botx/i,
        text: "> you called?",
    },

    {
        regex: /troll/i,
        text: "> :trollface: troll problems? [notify admins here](https://gitter.im/camperbot/admins)",
    },
    {
        regex: /allyourbase/,
        text: "![all your base](https://files.gitter.im/FreeCodeCamp/CoreTeam/Bw51/imgres.jpg)",
    },
    {
        regex: /'''/,
        text: "> :bulb: to format code use backticks! ``` [more info](https://github.com/freecodecamp/freecodecamp/wiki/code-formatting)",
    },
    {
        regex: /holler/i,
        text: "> holler back!",
        chance: 1   // only say this 50% of the time
    },
    {
        regex: /thank|thanx/,
        func: BotCommands.thanks
    }
]

var RoomMessages = {

    scanInput: function(input, roomName, chance) {
        if (Math.random() > chance) {
            return null;   // dont always reply
        }
        var oneMessage;
        var chat = input.message.model.text.toLowerCase();
        chance = chance || 1;
        roomName = roomName.toLowerCase();

        // some messages are only for certain rooms so exclude them here
        var thisRoomMessages = AllRoomMessages.filter(function(msg) {
            if (msg.not) {
                return (msg.not != roomName);
            } else {
                return true;
            }
        });
        if (!thisRoomMessages) { return false; }

        var msgList = thisRoomMessages.filter(function(item) {
            if(!item) { return null; }

            if (item.regex) {
              var flag = item.regex.test(chat);
            }

            if(flag) {
                //Utils.clog(chat, item.word, "flag:" + flag);
            }
            return flag;
        });

        // now check if chance is high enough
        if (msgList.length > 0) {

            oneMessage = _.sample(msgList);  // if we have multiple messages, make sure to choose just one
            chance = oneMessage.chance || 1; // check if the chance is high enough so we can have % of time messages
            if (Math.random() < (chance)) {
                // we have a winner!
                return oneMessage;
            }
        } else {
            return null;
        }

    }

};

module.exports = RoomMessages;
<|endoftext|>


<commit_before>/*
 require(["dojo/ready", "dijit/layout/AccordionContainer", "dijit/layout/ContentPane"], function(ready, AccordionContainer, ContentPane){
 ready(function(){
 var aContainer = new AccordionContainer({style:"height: 300px"}, "markup");
 aContainer.addChild(new ContentPane({
 title: "This is a content pane",
 content: "Hi!"
 }));
 aContainer.addChild(new ContentPane({
 title:"This is as well",
 content:"Hi how are you?"
 }));
 aContainer.addChild(new ContentPane({
 title:"This too",
 content:"Hello im fine.. thnx"
 }));
 aContainer.startup();
 });
 });
 */
define([
    "smithy/declare",
    "smithy/ToolGadget",
    "dijit/form/Button",
    "dijit/_Container",
    "dijit/layout/ContentPane",
    "dijit/layout/AccordionContainer"
], function (
    declare,
    ToolGadget,
    Button,
    Container,
    ContentPane,
    AccordionContainer
) {

/**
 * @class SimpleGadget
 * A simple gadget for test purposes.
 */

    return declare([AccordionContainer, ToolGadget], {

        constructor: function (config) {
            this.style = "width: 30%";
        },

        name: "NavigationGadget",

        title: "NavigationGadget",

        setupView: function () {
            var that = this,
                gs = this.gadgetSpace,
                container = declare([Container, ContentPane], {}),
                loadGadgets = new container({
                    title: "Load Gadgets"
                });

            gs.enumerateGadgetDescriptors(function (descriptor) {
                loadGadgets.addChild(new Button({
                    label: "Load " + descriptor.name,
                    onClick: function () {
                        // If you want to do adhoc routing do the following.
//                        var center = gs.getArea("/windows[0]/center");
//                        center.removeGadget();
//                        center = gs.loadGadgetTo(descriptor.name, "/windows[0]/center", false);
//                        gs.routePage();
                        // If you are using a custom routing specification do the following
                        // to route to a particular entry.
                        gs.routeTo(descriptor.name, {applicationTitle: "Loaded From Navigator"});
                    }
                }));
            }, this);
            this.addChild(loadGadgets);
            this.startup();
        }
    });
});
<commit_msg>Fix to only pass param to title gadget.<commit_after>/*
 */
define([
    "smithy/declare",
    "smithy/ToolGadget",
    "dijit/form/Button",
    "dijit/_Container",
    "dijit/layout/ContentPane",
    "dijit/layout/AccordionContainer"
], function (
    declare,
    ToolGadget,
    Button,
    Container,
    ContentPane,
    AccordionContainer
) {

/**
 * @class SimpleGadget
 * A simple gadget for test purposes.
 */

    return declare([AccordionContainer, ToolGadget], {

        constructor: function (config) {
            this.style = "width: 30%";
        },

        name: "NavigationGadget",

        title: "NavigationGadget",

        setupView: function () {
            var that = this,
                gs = this.gadgetSpace,
                container = declare([Container, ContentPane], {}),
                loadGadgets = new container({
                    title: "Load Gadgets"
                });

            gs.enumerateGadgetDescriptors(function (descriptor) {
                loadGadgets.addChild(new Button({
                    label: "Load " + descriptor.name,
                    onClick: function () {
                        // If you want to do adhoc routing do the following.
//                        var center = gs.getArea("/windows[0]/center");
//                        center.removeGadget();
//                        center = gs.loadGadgetTo(descriptor.name, "/windows[0]/center", false);
//                        gs.routePage();
                        // If you are using a custom routing specification do the following
                        // to route to a particular entry.
                        if (descriptor.gadget === "TitleGadget") {
                            gs.routeTo(descriptor.name, {applicationTitle: "Loaded From Navigator"});
                        } else {
                            gs.routeTo(descriptor.name);
                        }
                    }
                }));
            }, this);
            this.addChild(loadGadgets);
            this.startup();
        }
    });
});
<|endoftext|>