<commit_before>import Ember from 'ember';
import { getValueFromLocales } from 'ember-flexberry-data/utils/model-functions';

export default Ember.Mixin.create({
  _userSettingsService: Ember.inject.service('user-settings'),
  /**
    Default cell component that will be used to display values in columns cells.

    @property {Object} cellComponent
    @property {String} [cellComponent.componentName='object-list-view-cell']
    @property {String} [cellComponent.componentProperties=null]
  */
  cellComponent: {
    componentName: 'object-list-view-cell',
    componentProperties: null,
  },

  actions: {
    showConfigDialog: function(componentName, settingName) {
      let colsOrder = this.get('_userSettingsService').getCurrentColsOrder(componentName, settingName);
      let sorting = this.get('_userSettingsService').getCurrentSorting(componentName, settingName);
      let columnWidths = this.get('userSettingsService').getCurrentColumnWidths(componentName, settingName);
      let propName;
      let colDesc;  //Column description
      let colDescs = [];  //Columns description
      let projectionAttributes = this.modelProjection.attributes;
      let colList = this._generateColumns(projectionAttributes);
      let namedColList = {};
      for (let i = 0; i < colList.length; i++) {
        colDesc = colList[i];
        propName = colDesc.propName;
        namedColList[propName] = colDesc;
      }

      if (Ember.isArray(colsOrder)) {
        /*
         Remove propName, that are not in colList
         */
        let reliableColsOrder = [];
        for (let i = 0; i < colsOrder.length; i++) {
          let colOrder = colsOrder[i];
          propName = colOrder.propName;
          if ((propName in namedColList) && ('header' in  namedColList[propName])) {
            reliableColsOrder.push(colOrder);
          }
        }

        colsOrder = reliableColsOrder;
      } else {
        colsOrder = colList;
      }

      let namedSorting = {};
      let sortPriority = 0;
      if (sorting === undefined) {
        sorting = [];
      }

      for (let i = 0; i < sorting.length; i++) {
        colDesc = sorting[i];
        colDesc.sortPriority = ++sortPriority;
        propName = colDesc.propName;
        namedSorting[propName] = colDesc;
      }

      if (columnWidths === undefined) {
        columnWidths = [];
      }

      let namedColWidth = {};
      for (let i = 0; i < columnWidths.length; i++) {
        colDesc = columnWidths[i];
        propName = colDesc.propName;
        namedColWidth[propName] = colDesc.width;
      }

      for (let i = 0; i < colsOrder.length; i++) {
        let colOrder = colsOrder[i];
        propName = colOrder.propName;
        if (!(propName in namedColList) || !('header' in  namedColList[propName])) {
          delete namedColList[propName];
          continue;
        }

        let name = namedColList[propName].header;
        delete namedColList[propName];
        colDesc = { name: name, propName: propName, hide: colOrder.hide };
        if (propName in namedSorting) {
          let sortColumn = namedSorting[propName];
          colDesc.sortOrder = sortColumn.direction === 'asc' ? 1 : -1;
          colDesc.sortPriority = sortColumn.sortPriority;
        } else {
          colDesc.sortOrder = 0;
        }

        if (propName in namedColWidth) {
          colDesc.columnWidth = namedColWidth[propName];
        }

        colDescs[i] = colDesc;
      }

      for (propName in namedColList) {
        colDescs[colDescs.length] = { propName: propName, name: namedColList[propName].header, hide: false, sortOrder: 0 };
      }

      let controller = this.get('colsconfigController');

      let loadingParams = {
        view: 'application',
        outlet: 'modal'
      };
      this.send('showModalDialog', 'colsconfig-dialog');

      loadingParams = {
        view: 'colsconfig-dialog',
        outlet: 'modal-content'
      };
      this.send('showModalDialog', 'colsconfig-dialog-content',
                { controller: controller, model: { colDescs: colDescs, componentName: componentName, settingName: settingName } },
                loadingParams);
    }

  },

  /**
    Generate the columns.

    @method _generateColumns
    @private
  */
  _generateColumns(attributes, columnsBuf, relationshipPath) {
    columnsBuf = columnsBuf || [];
    relationshipPath = relationshipPath || '';

    for (let attrName in attributes) {
      let currentRelationshipPath = relationshipPath;
      if (!attributes.hasOwnProperty(attrName)) {
        continue;
      }

      let attr = attributes[attrName];
      switch (attr.kind) {
        case 'hasMany':
          break;

        case 'belongsTo':
          if (!attr.options.hidden) {
            let bindingPath = currentRelationshipPath + attrName;
            let column = this._createColumn(attr, attrName, bindingPath);

            if (column.cellComponent.componentName === 'object-list-view-cell') {
              if (attr.options.displayMemberPath) {
                column.propName += '.' + attr.options.displayMemberPath;
              } else {
                column.propName += '.id';
              }
            }

            columnsBuf.push(column);
          }

          currentRelationshipPath += attrName + '.';
          this._generateColumns(attr.attributes, columnsBuf, currentRelationshipPath);
          break;

        case 'attr':
          if (attr.options.hidden) {
            break;
          }

          let bindingPath = currentRelationshipPath + attrName;
          let column = this._createColumn(attr, attrName, bindingPath);
          columnsBuf.push(column);
          break;

        default:
          Ember.Logger.error(`Unknown kind of projection attribute: ${attr.kind}`);
      }
    }

    return columnsBuf;
  },

  /**
    Create the key from locales.
  */
  _createKey(bindingPath) {
    let projection = this.get('modelProjection');
    let modelName = projection.modelName;
    let key;

    let mainModelProjection = this.get('mainModelProjection');
    if (mainModelProjection) {
      let modelClass = this.get('store').modelFor(modelName);
      let nameRelationship;
      let mainModelName;

      modelClass.eachRelationship(function(name, descriptor) {
        if (descriptor.kind === 'belongsTo' && descriptor.options.inverse) {
          nameRelationship = descriptor.options.inverse;
          mainModelName = descriptor.type;
        }
      });
      key = 'models.' + mainModelName + '.projections.' + mainModelProjection.projectionName + '.' + nameRelationship + '.' + bindingPath + '.caption';
    } else {
      key = 'models.' + modelName + '.projections.' + projection.projectionName + '.' + bindingPath + '.caption';
    }

    return key;
  },

  /**
    Create the column.

    @method _createColumn
    @private
  */
  _createColumn(attr, attrName, bindingPath) {
    // We get the 'getCellComponent' function directly from the controller,
    // and do not pass this function as a component attrubute,
    // to avoid 'Ember.Object.create no longer supports defining methods that call _super' error,
    // if controller's 'getCellComponent' method call its super method from the base controller.
    let currentController = this.get('currentController');
    let getCellComponent = Ember.get(currentController || {}, 'getCellComponent');
    let cellComponent = this.get('cellComponent');

    if (!this.get('editOnSeparateRoute') && Ember.typeOf(getCellComponent) === 'function') {
      let recordModel =  (this.get('content') || {}).type || null;
      cellComponent = getCellComponent.call(currentController, attr, bindingPath, recordModel);
    }

    let key = this._createKey(bindingPath);
    let valueFromLocales = getValueFromLocales(this.get('i18n'), key);

    let column = {
      header: valueFromLocales || attr.caption || Ember.String.capitalize(attrName),
      propName: bindingPath, // TODO: rename column.propName
      cellComponent: cellComponent,
    };

    if (valueFromLocales) {
      column.keyLocale = key;
    }

    let customColumnAttributesFunc = this.get('customColumnAttributes');
    if (customColumnAttributesFunc) {
      let customColAttr = customColumnAttributesFunc(attr, bindingPath);
      if (customColAttr && (typeof customColAttr === 'object')) {
        Ember.$.extend(true, column, customColAttr);
      }
    }

    if (this.get('enableFilters')) {
      this._addFilterForColumn(column, attr, bindingPath);
    }

    let sortDef;
    let sorting = this.get('sorting');
    if (sorting && (sortDef = sorting[bindingPath])) {
      column.sorted = true;
      column.sortAscending = sortDef.sortAscending;
      column.sortNumber = sortDef.sortNumber;
    }

    return column;
  }
});
<commit_msg>Correct behaviour on incorrect sorting settings<commit_after>import Ember from 'ember';
import { getValueFromLocales } from 'ember-flexberry-data/utils/model-functions';

export default Ember.Mixin.create({
  _userSettingsService: Ember.inject.service('user-settings'),
  /**
    Default cell component that will be used to display values in columns cells.

    @property {Object} cellComponent
    @property {String} [cellComponent.componentName='object-list-view-cell']
    @property {String} [cellComponent.componentProperties=null]
  */
  cellComponent: {
    componentName: 'object-list-view-cell',
    componentProperties: null,
  },

  actions: {
    showConfigDialog: function(componentName, settingName) {
      let colsOrder = this.get('_userSettingsService').getCurrentColsOrder(componentName, settingName);
      let sorting = this.get('_userSettingsService').getCurrentSorting(componentName, settingName);
      let columnWidths = this.get('userSettingsService').getCurrentColumnWidths(componentName, settingName);
      let propName;
      let colDesc;  //Column description
      let colDescs = [];  //Columns description
      let projectionAttributes = this.modelProjection.attributes;
      let colList = this._generateColumns(projectionAttributes);
      let namedColList = {};
      for (let i = 0; i < colList.length; i++) {
        colDesc = colList[i];
        propName = colDesc.propName;
        namedColList[propName] = colDesc;
      }

      if (Ember.isArray(colsOrder)) {
        /*
         Remove propName, that are not in colList
         */
        let reliableColsOrder = [];
        for (let i = 0; i < colsOrder.length; i++) {
          let colOrder = colsOrder[i];
          propName = colOrder.propName;
          if ((propName in namedColList) && ('header' in  namedColList[propName])) {
            reliableColsOrder.push(colOrder);
          }
        }

        colsOrder = reliableColsOrder;
      } else {
        colsOrder = colList;
      }

      let namedSorting = {};
      let sortPriority = 0;
      if (sorting === undefined) {
        sorting = [];
      }

      for (let i = 0; i < sorting.length; i++) {
        colDesc = sorting[i];
        propName = colDesc.propName;
        if (propName in namedColList) {
          colDesc.sortPriority = ++sortPriority;
          namedSorting[propName] = colDesc;
        }
      }

      if (columnWidths === undefined) {
        columnWidths = [];
      }

      let namedColWidth = {};
      for (let i = 0; i < columnWidths.length; i++) {
        colDesc = columnWidths[i];
        propName = colDesc.propName;
        namedColWidth[propName] = colDesc.width;
      }

      for (let i = 0; i < colsOrder.length; i++) {
        let colOrder = colsOrder[i];
        propName = colOrder.propName;
        if (!(propName in namedColList) || !('header' in  namedColList[propName])) {
          delete namedColList[propName];
          continue;
        }

        let name = namedColList[propName].header;
        delete namedColList[propName];
        colDesc = { name: name, propName: propName, hide: colOrder.hide };
        if (propName in namedSorting) {
          let sortColumn = namedSorting[propName];
          colDesc.sortOrder = sortColumn.direction === 'asc' ? 1 : -1;
          colDesc.sortPriority = sortColumn.sortPriority;
        } else {
          colDesc.sortOrder = 0;
        }

        if (propName in namedColWidth) {
          colDesc.columnWidth = namedColWidth[propName];
        }

        colDescs.push(colDesc);
      }

      for (propName in namedColList) {
        colDescs.push({ propName: propName, name: namedColList[propName].header, hide: false, sortOrder: 0 });
      }

      let controller = this.get('colsconfigController');

      let loadingParams = {
        view: 'application',
        outlet: 'modal'
      };
      this.send('showModalDialog', 'colsconfig-dialog');

      loadingParams = {
        view: 'colsconfig-dialog',
        outlet: 'modal-content'
      };
      this.send('showModalDialog', 'colsconfig-dialog-content',
                { controller: controller, model: { colDescs: colDescs, componentName: componentName, settingName: settingName } },
                loadingParams);
    }

  },

  /**
    Generate the columns.

    @method _generateColumns
    @private
  */
  _generateColumns(attributes, columnsBuf, relationshipPath) {
    columnsBuf = columnsBuf || [];
    relationshipPath = relationshipPath || '';

    for (let attrName in attributes) {
      let currentRelationshipPath = relationshipPath;
      if (!attributes.hasOwnProperty(attrName)) {
        continue;
      }

      let attr = attributes[attrName];
      switch (attr.kind) {
        case 'hasMany':
          break;

        case 'belongsTo':
          if (!attr.options.hidden) {
            let bindingPath = currentRelationshipPath + attrName;
            let column = this._createColumn(attr, attrName, bindingPath);

            if (column.cellComponent.componentName === 'object-list-view-cell') {
              if (attr.options.displayMemberPath) {
                column.propName += '.' + attr.options.displayMemberPath;
              } else {
                column.propName += '.id';
              }
            }

            columnsBuf.push(column);
          }

          currentRelationshipPath += attrName + '.';
          this._generateColumns(attr.attributes, columnsBuf, currentRelationshipPath);
          break;

        case 'attr':
          if (attr.options.hidden) {
            break;
          }

          let bindingPath = currentRelationshipPath + attrName;
          let column = this._createColumn(attr, attrName, bindingPath);
          columnsBuf.push(column);
          break;

        default:
          Ember.Logger.error(`Unknown kind of projection attribute: ${attr.kind}`);
      }
    }

    return columnsBuf;
  },

  /**
    Create the key from locales.
  */
  _createKey(bindingPath) {
    let projection = this.get('modelProjection');
    let modelName = projection.modelName;
    let key;

    let mainModelProjection = this.get('mainModelProjection');
    if (mainModelProjection) {
      let modelClass = this.get('store').modelFor(modelName);
      let nameRelationship;
      let mainModelName;

      modelClass.eachRelationship(function(name, descriptor) {
        if (descriptor.kind === 'belongsTo' && descriptor.options.inverse) {
          nameRelationship = descriptor.options.inverse;
          mainModelName = descriptor.type;
        }
      });
      key = 'models.' + mainModelName + '.projections.' + mainModelProjection.projectionName + '.' + nameRelationship + '.' + bindingPath + '.caption';
    } else {
      key = 'models.' + modelName + '.projections.' + projection.projectionName + '.' + bindingPath + '.caption';
    }

    return key;
  },

  /**
    Create the column.

    @method _createColumn
    @private
  */
  _createColumn(attr, attrName, bindingPath) {
    // We get the 'getCellComponent' function directly from the controller,
    // and do not pass this function as a component attrubute,
    // to avoid 'Ember.Object.create no longer supports defining methods that call _super' error,
    // if controller's 'getCellComponent' method call its super method from the base controller.
    let currentController = this.get('currentController');
    let getCellComponent = Ember.get(currentController || {}, 'getCellComponent');
    let cellComponent = this.get('cellComponent');

    if (!this.get('editOnSeparateRoute') && Ember.typeOf(getCellComponent) === 'function') {
      let recordModel =  (this.get('content') || {}).type || null;
      cellComponent = getCellComponent.call(currentController, attr, bindingPath, recordModel);
    }

    let key = this._createKey(bindingPath);
    let valueFromLocales = getValueFromLocales(this.get('i18n'), key);

    let column = {
      header: valueFromLocales || attr.caption || Ember.String.capitalize(attrName),
      propName: bindingPath, // TODO: rename column.propName
      cellComponent: cellComponent,
    };

    if (valueFromLocales) {
      column.keyLocale = key;
    }

    let customColumnAttributesFunc = this.get('customColumnAttributes');
    if (customColumnAttributesFunc) {
      let customColAttr = customColumnAttributesFunc(attr, bindingPath);
      if (customColAttr && (typeof customColAttr === 'object')) {
        Ember.$.extend(true, column, customColAttr);
      }
    }

    if (this.get('enableFilters')) {
      this._addFilterForColumn(column, attr, bindingPath);
    }

    let sortDef;
    let sorting = this.get('sorting');
    if (sorting && (sortDef = sorting[bindingPath])) {
      column.sorted = true;
      column.sortAscending = sortDef.sortAscending;
      column.sortNumber = sortDef.sortNumber;
    }

    return column;
  }
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular
    .module('atlasDetail')
    .directive('atlasPartialSelect', atlasPartialSelectDirective);

  atlasPartialSelectDirective.$inject = ['pluginDetailService'];

  function atlasPartialSelectDirective (pluginDetailService) {
    return {
      restrict: 'E',
      scope: {
        apiData: '=',
        partial: '@'
      },
      link: linkFunction
    };

    function linkFunction(scope, element) {
      var partialPath,
      partialRoot;

      partialRoot = 'modules/detail/components/partial-select/partials/';

      partialPath = partialRoot + scope.partial + '.html';

      pluginDetailService.compileTemplate(scope, element, partialPath);
    }
  }
})();<commit_msg>load more toegevoegd<commit_after>(function () {
  'use strict';

  angular
    .module('atlasDetail')
    .directive('atlasPartialSelect', atlasPartialSelectDirective);

  atlasPartialSelectDirective.$inject = ['api', 'pluginDetailService'];

  function atlasPartialSelectDirective (api, pluginDetailService) {
    return {
      restrict: 'E',
      scope: {
        apiData: '=',
        partial: '@'
      },
      link: linkFunction
    };

    function linkFunction(scope, element) {
      var partialPath,
      partialRoot;

      partialRoot = 'modules/detail/components/partial-select/partials/';

      partialPath = partialRoot + scope.partial + '.html';

      pluginDetailService.compileTemplate(scope, element, partialPath);

      scope.loadMore = function () {
        if (!scope.apiData.next) {
          return;
        }

        api.getByUrl(scope.apiData.next).then(function (response) {
          scope.apiData.next = response._links.next.href;
          scope.apiData.results.push.apply(scope.apiData.results, response.results);
          // push results to end of scope.apiData.results
        });
      };
    }
  }
})();<|endoftext|>


<commit_before>// Assumes that rethinkdb is loaded already in whichever environment we happen to be running in

function print(msg) {
    console.log(msg);
}

var q = rethinkdb.query;
var tab = q.table('Welcome-rdb');

var conn;
function testConnect() {
    wait();
    conn = rethinkdb.net.connect('newton', function() {
        done();
    }, function() {
        fail("Could not connect");
    });
}

function testBasic() {
    q(1).run(aeq(1));
    q(true).run(aeq(true));
    q('bob').run(aeq('bob'));

    q.expr(1).run(aeq(1));
    q.expr(true).run(aeq(true));
}

function testArith() {
    q(1).add(2).run(aeq(3));
    q(1).sub(2).run(aeq(-1));
    q(5).mul(8).run(aeq(40));
    q(8).div(2).run(aeq(4));

    q(12).div(3).add(2).mul(3).run(aeq(18));
}

function testCompare() {
    q(1).eq(1).run(aeq(true));
    q(1).eq(2).run(aeq(false));
    q(1).lt(2).run(aeq(true));
    q(8).lt(-4).run(aeq(false));
    q(8).le(8).run(aeq(true));
    q(8).gt(7).run(aeq(true));
    q(8).gt(8).run(aeq(false));
    q(8).ge(8).run(aeq(true));
}

function testBool() {
    q(true).not().run(aeq(false));
    q(true).and(true).run(aeq(true));
    q(true).and(false).run(aeq(false));
    q(true).or(false).run(aeq(true));

    // Test DeMorgan's rule!
    q(true).and(false).eq(q(true).not().or(q(false).not()).not()).run(aeq(true));
}

function testInsert() {
    for (var i = 0; i < 10; i++) {
        tab.insert({id:i, num:20-i}).run(objeq({inserted:1}));
    }
}

function testGet() {
    for (var i = 0; i < 10; i++) {
        tab.get(i).run(objeq({id:i,num:20-i}));
    }
}

function testSlices() {
    tab.length().run(aeq(10));
    tab.limit(5).length().run(aeq(5));
    tab.skip(4).length().run(aeq(6));
    tab.slice(1,4).length().run(aeq(3));
    tab.nth(8).run(objeq({id:7,num:13}));
}

function testMap() {
    tab.map(q.R('num')).nth(2).run(aeq(19));
}

function testReduce() {
    tab.reduce(q(0), q.fn('a', 'b', q.R('$a').add(q.R('$b')))).run(aeq(155));
}

function testClose() {
    conn.close();
}

runTests([
    testConnect,
    testBasic,
    testCompare,
    testArith,
    testBool,
    testInsert,
    testGet,
    testSlices,
    testMap,
    testReduce,
    testClose,
]);
<commit_msg>fixes slices test<commit_after>// Assumes that rethinkdb is loaded already in whichever environment we happen to be running in

function print(msg) {
    console.log(msg);
}

var q = rethinkdb.query;
var tab = q.table('Welcome-rdb');

var conn;
function testConnect() {
    wait();
    conn = rethinkdb.net.connect('newton', function() {
        done();
    }, function() {
        fail("Could not connect");
    });
}

function testBasic() {
    q(1).run(aeq(1));
    q(true).run(aeq(true));
    q('bob').run(aeq('bob'));

    q.expr(1).run(aeq(1));
    q.expr(true).run(aeq(true));
}

function testArith() {
    q(1).add(2).run(aeq(3));
    q(1).sub(2).run(aeq(-1));
    q(5).mul(8).run(aeq(40));
    q(8).div(2).run(aeq(4));

    q(12).div(3).add(2).mul(3).run(aeq(18));
}

function testCompare() {
    q(1).eq(1).run(aeq(true));
    q(1).eq(2).run(aeq(false));
    q(1).lt(2).run(aeq(true));
    q(8).lt(-4).run(aeq(false));
    q(8).le(8).run(aeq(true));
    q(8).gt(7).run(aeq(true));
    q(8).gt(8).run(aeq(false));
    q(8).ge(8).run(aeq(true));
}

function testBool() {
    q(true).not().run(aeq(false));
    q(true).and(true).run(aeq(true));
    q(true).and(false).run(aeq(false));
    q(true).or(false).run(aeq(true));

    // Test DeMorgan's rule!
    q(true).and(false).eq(q(true).not().or(q(false).not()).not()).run(aeq(true));
}

function testInsert() {
    for (var i = 0; i < 10; i++) {
        tab.insert({id:i, num:20-i}).run(objeq({inserted:1}));
    }
}

function testGet() {
    for (var i = 0; i < 10; i++) {
        tab.get(i).run(objeq({id:i,num:20-i}));
    }
}

function testSlices() {
    var arr = q([1,2,3,4,5,6]);

    arr.length().run(aeq(6));
    arr.limit(5).length().run(aeq(5));
    arr.skip(4).length().run(aeq(2));
    arr.slice(1,4).length().run(aeq(3));
    arr.nth(2).run(aeq(3));
}

function testMap() {
    tab.map(q.R('num')).nth(2).run(aeq(19));
}

function testReduce() {
    tab.reduce(q(0), q.fn('a', 'b', q.R('$a').add(q.R('$b')))).run(aeq(155));
}

function testClose() {
    conn.close();
}

runTests([
    testConnect,
    testBasic,
    testCompare,
    testArith,
    testBool,
    testInsert,
    testGet,
    testSlices,
    testMap,
    testReduce,
    testClose,
]);
<|endoftext|>


<commit_before>import React from 'react';
import {
  Linking,
  StyleSheet,
  Text,
  View,
} from 'react-native';

import ParsedText from 'react-native-parsed-text';
import Communications from 'react-native-communications';

export default class MessageText extends React.Component {
  constructor(props) {
    super(props);
    this.onUrlPress = this.onUrlPress.bind(this);
    this.onPhonePress = this.onPhonePress.bind(this);
    this.onEmailPress = this.onEmailPress.bind(this);
  }

  onUrlPress(url) {
    Linking.openURL(url);
  }

  onPhonePress(phone) {
    const options = [
      'Text',
      'Call',
      'Cancel',
    ];
    const cancelButtonIndex = options.length - 1;
    this.context.actionSheet().showActionSheetWithOptions({
      options,
      cancelButtonIndex,
    },
    (buttonIndex) => {
      switch (buttonIndex) {
        case 0:
          Communications.phonecall(phone, true);
          break;
        case 1:
          Communications.text(phone);
          break;
      }
    });
  }

  onEmailPress(email) {
    Communications.email(email, null, null, null, null);
  }

  render() {
    return (
      <View style={[styles[this.props.position].container, this.props.containerStyle[this.props.position]]}>
        <ParsedText
          style={[styles[this.props.position].text, this.props.textStyle[this.props.position]]}
          parse={[
            {type: 'url', style: StyleSheet.flatten([styles[this.props.position].link, this.props.linkStyle[this.props.position]]), onPress: this.onUrlPress},
            {type: 'phone', style: StyleSheet.flatten([styles[this.props.position].link, this.props.linkStyle[this.props.position]]), onPress: this.onPhonePress},
            {type: 'email', style: StyleSheet.flatten([styles[this.props.position].link, this.props.linkStyle[this.props.position]]), onPress: this.onEmailPress},
          ]}
        >
          {this.props.currentMessage.text}
        </ParsedText>
      </View>
    );
  }
}

const textStyle = {
  fontSize: 14,
  // lineHeight: 20,
  marginTop: 5,
  marginBottom: 5,
  marginLeft: 10,
  marginRight: 10,
};

const styles = {
  left: StyleSheet.create({
    container: {
    },
    text: {
      color: '#7e7e7e',
      ...textStyle,
    },
    link: {
      color: '#7e7e7e',
      textDecorationLine: 'underline',
    },
  }),
  right: StyleSheet.create({
    container: {
    },
    text: {
      color: 'white',
      ...textStyle,
    },
    link: {
      color: 'white',
      textDecorationLine: 'underline',
    },
  }),
  center: StyleSheet.create({
    container: {
    },
    text: {
      color: '#2c2721',
      ...textStyle,
    },
    link: {
      color: '#2c2721',
      textDecorationLine: 'underline',
    },
  }),
  center2: StyleSheet.create({
    container: {
    },
    text: {
      color: '#2c2721',
      ...textStyle,
    },
    link: {
      color: '#2c2721',
      textDecorationLine: 'underline',
    },
  }),
  center3: StyleSheet.create({
    container: {
    },
    text: {
      color: '#2c2721',
      ...textStyle,
    },
    link: {
      color: '#2c2721',
      textDecorationLine: 'underline',
    },
  }),
};

MessageText.contextTypes = {
  actionSheet: React.PropTypes.func,
};

MessageText.defaultProps = {
  position: 'left',
  currentMessage: {
    text: '',
  },
  containerStyle: {},
  textStyle: {},
  linkStyle: {},
};

MessageText.propTypes = {
  position: React.PropTypes.oneOf(['left', 'right', 'center', 'center2', 'center3']),
  currentMessage: React.PropTypes.object,
  containerStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
  textStyle: React.PropTypes.shape({
    left: Text.propTypes.style,
    right: Text.propTypes.style,
  }),
  linkStyle: React.PropTypes.shape({
    left: Text.propTypes.style,
    right: Text.propTypes.style,
  }),
};
<commit_msg>fix color<commit_after>import React from 'react';
import {
  Linking,
  StyleSheet,
  Text,
  View,
} from 'react-native';

import ParsedText from 'react-native-parsed-text';
import Communications from 'react-native-communications';

export default class MessageText extends React.Component {
  constructor(props) {
    super(props);
    this.onUrlPress = this.onUrlPress.bind(this);
    this.onPhonePress = this.onPhonePress.bind(this);
    this.onEmailPress = this.onEmailPress.bind(this);
  }

  onUrlPress(url) {
    Linking.openURL(url);
  }

  onPhonePress(phone) {
    const options = [
      'Text',
      'Call',
      'Cancel',
    ];
    const cancelButtonIndex = options.length - 1;
    this.context.actionSheet().showActionSheetWithOptions({
      options,
      cancelButtonIndex,
    },
    (buttonIndex) => {
      switch (buttonIndex) {
        case 0:
          Communications.phonecall(phone, true);
          break;
        case 1:
          Communications.text(phone);
          break;
      }
    });
  }

  onEmailPress(email) {
    Communications.email(email, null, null, null, null);
  }

  render() {
    return (
      <View style={[styles[this.props.position].container, this.props.containerStyle[this.props.position]]}>
        <ParsedText
          style={[styles[this.props.position].text, this.props.textStyle[this.props.position]]}
          parse={[
            {type: 'url', style: StyleSheet.flatten([styles[this.props.position].link, this.props.linkStyle[this.props.position]]), onPress: this.onUrlPress},
            {type: 'phone', style: StyleSheet.flatten([styles[this.props.position].link, this.props.linkStyle[this.props.position]]), onPress: this.onPhonePress},
            {type: 'email', style: StyleSheet.flatten([styles[this.props.position].link, this.props.linkStyle[this.props.position]]), onPress: this.onEmailPress},
          ]}
        >
          {this.props.currentMessage.text}
        </ParsedText>
      </View>
    );
  }
}

const textStyle = {
  fontSize: 14,
  // lineHeight: 20,
  marginTop: 5,
  marginBottom: 5,
  marginLeft: 10,
  marginRight: 10,
};

const styles = {
  left: StyleSheet.create({
    container: {
    },
    text: {
      color: '#7e7e7e',
      ...textStyle,
    },
    link: {
      color: '#7e7e7e',
      textDecorationLine: 'underline',
    },
  }),
  right: StyleSheet.create({
    container: {
    },
    text: {
      color: 'white',
      ...textStyle,
    },
    link: {
      color: 'white',
      textDecorationLine: 'underline',
    },
  }),
  center: StyleSheet.create({
    container: {
    },
    text: {
      color: '#2c2721',
      ...textStyle,
    },
    link: {
      color: '#2c2721',
      textDecorationLine: 'underline',
    },
  }),
  center2: StyleSheet.create({
    container: {
    },
    text: {
      color: 'white',
      ...textStyle,
    },
    link: {
      color: 'white',
      textDecorationLine: 'underline',
    },
  }),
  center3: StyleSheet.create({
    container: {
    },
    text: {
      color: 'white',
      ...textStyle,
    },
    link: {
      color: 'white',
      textDecorationLine: 'underline',
    },
  }),
};

MessageText.contextTypes = {
  actionSheet: React.PropTypes.func,
};

MessageText.defaultProps = {
  position: 'left',
  currentMessage: {
    text: '',
  },
  containerStyle: {},
  textStyle: {},
  linkStyle: {},
};

MessageText.propTypes = {
  position: React.PropTypes.oneOf(['left', 'right', 'center', 'center2', 'center3']),
  currentMessage: React.PropTypes.object,
  containerStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
  textStyle: React.PropTypes.shape({
    left: Text.propTypes.style,
    right: Text.propTypes.style,
  }),
  linkStyle: React.PropTypes.shape({
    left: Text.propTypes.style,
    right: Text.propTypes.style,
  }),
};
<|endoftext|>


<commit_before>define([
    'uijet_dir/uijet',
    'resources',
    'api',
    'd3'
], function (uijet, resources, api) {

    var d3 = window.d3,
        period = uijet.Utils.prop('period'),
        amount = uijet.Utils.prop('amount');

    uijet.Widget('TimelineChart', {
        options         : {
            type_class  : ['uijet_chart', 'uijet_timelinechart']
        },
        init            : function () {
            this._super.apply(this, arguments);
            this.colors = d3.scale.category20();
        },
        prepareElement  : function () {
            this._super();
            var element = this.$element[0],
                width = element.offsetWidth,
                height = element.offsetHeight,
//                x = d3.time.scale()
                x = d3.scale.linear()
                    .range([0, width]),
                y = d3.scale.linear()
                    .range([height, 0]),
                x_axis = d3.svg.axis()
                    .scale(x)
                    .orient('bottom'),
                y_axis = d3.svg.axis()
                    .scale(y)
                    .orient('left');

            this.width = width;
            this.height = height;
            this.x_scale = x;
            this.y_scale = y;

            this.line = d3.svg.line()
//                .interpolate('basis')
                .x( function(d) { return x(d.period); } )
                .y( function(d) { return y(d.amount); } );

            this.svg = d3.select(this.$element[0]).append('svg')
                .attr('width', width)
                .attr('height', height)
                .append('g');
//                    .attr('transform', 'translate(20,20)');

            this.svg.append('g')
                .attr('class', 'x_axis')
                .attr('transform', 'translate(0,' + (this.height - 20) + ')')
                .call(x_axis);

            this.svg.append('g')
                .attr('class', 'y_axis')
                .attr('transform', 'translate(20,0)')
                .call(y_axis);
        },
        render          : function () {
            this._super();
            this.set(uijet.Resource('LegendItems').models).then(function () {
                this.draw(this.resource.models);
            }.bind(this));
            return this;
        },
        draw            : function (series) {
            var line = this.line,
                ids = [],
                data = [],
                colors = this.colors;

            series.forEach(function (item) {
                var id = item.cid,
                    actual_id = id + '-actual',
                    budget_id = id + '-budget',
                    title = item.get('title'),
                    item_series = item.toSeries();
                ids.push(actual_id, budget_id);
                data.push({
                    id      : actual_id,
                    name    : title + ' actual',
                    values  : item_series[0]
                }, {
                    id      : budget_id,
                    name    : title + ' budget',
                    values  : item_series[1]
                });
            });
            console.log(ids);
            this.colors.domain(ids);

            this.x_scale.domain([
                d3.min(data, function (d) { return d3.min(d.values, period); }),
                d3.max(data, function (d) { return d3.max(d.values, period); })
            ]);
            this.y_scale.domain([
                d3.min(data, function (d) { return d3.min(d.values, amount); }),
                d3.max(data, function (d) { return d3.max(d.values, amount); })
            ]);

            var timeline = this.svg.selectAll('.timeline')
                .data(data)
                .enter()
                .append('g')
                    .attr('class', 'timeline');

            timeline.append('path')
                .attr('class', 'line')
                .attr('d', function(d) {
                    return line(d.values);
                })
                .style('stroke', function(d) { return colors(d.id); });
        }
    });

});
<commit_msg>Fixed  x axis as time scale with proper yearly ticks; Fixed y axis ticks<commit_after>define([
    'uijet_dir/uijet',
    'resources',
    'api',
    'd3'
], function (uijet, resources, api) {

    var d3 = window.d3,
        period = uijet.Utils.prop('period'),
        amount = uijet.Utils.prop('amount'),
        dateParser = d3.time.format('%Y').parse,
        periodParser = function (d) {
            d.period = dateParser(d.period);
        };

    uijet.Widget('TimelineChart', {
        options         : {
            type_class  : ['uijet_chart', 'uijet_timelinechart']
        },
        init            : function () {
            this._super.apply(this, arguments);
            this.colors = d3.scale.category20();
        },
        prepareElement  : function () {
            this._super();
            var element = this.$element[0],
                width = element.offsetWidth,
                height = element.offsetHeight,
//                x = d3.time.scale()
                x = d3.time.scale()
                    .range([0, width]),
                y = d3.scale.linear()
                    .range([height, 0]),
                x_axis = d3.svg.axis()
                    .scale(x)
                    .orient('bottom')
                    .ticks(d3.time.years),
                y_axis = d3.svg.axis()
                    .scale(y)
                    .orient('left');

            this.width = width;
            this.height = height;
            this.x_axis = x_axis;
            this.y_axis = y_axis;
            this.x_scale = x;
            this.y_scale = y;

            this.line = d3.svg.line()
//                .interpolate('basis')
                .x( function(d) { return x(d.period); } )
                .y( function(d) { return y(d.amount); } );

            this.svg = d3.select(this.$element[0]).append('svg')
                .attr('width', width)
                .attr('height', height)
                .append('g');
//                    .attr('transform', 'translate(20,20)');
        },
        render          : function () {
            this._super();
            this.set(uijet.Resource('LegendItems').models).then(function () {
                this.draw(this.resource.models);
            }.bind(this));
            return this;
        },
        draw            : function (series) {
            var line = this.line,
                ids = [],
                data = [],
                colors = this.colors;

            series.forEach(function (item) {
                var id = item.cid,
                    actual_id = id + '-actual',
                    budget_id = id + '-budget',
                    title = item.get('title'),
                    item_series = item.toSeries();
                item_series[0].forEach(periodParser);
                item_series[1].forEach(periodParser);
                ids.push(actual_id, budget_id);
                data.push({
                    id      : actual_id,
                    name    : title + ' actual',
                    values  : item_series[0]
                }, {
                    id      : budget_id,
                    name    : title + ' budget',
                    values  : item_series[1]
                });
            });

            this.colors.domain(ids);

            this.x_scale.domain([
                d3.min(data, function (d) { return d3.min(d.values, period); }),
                d3.max(data, function (d) { return d3.max(d.values, period); })
            ]);
            this.y_scale.domain([
                d3.min(data, function (d) { return d3.min(d.values, amount); }),
                d3.max(data, function (d) { return d3.max(d.values, amount); })
            ]);

            this.svg.append('g')
                .attr('class', 'x_axis')
                .attr('transform', 'translate(0,' + (this.height - 20) + ')')
                .call(this.x_axis);

            this.svg.append('g')
                .attr('class', 'y_axis')
                .attr('transform', 'translate(20,0)')
                .call(this.y_axis);

            var timeline = this.svg.selectAll('.timeline')
                .data(data)
                .enter()
                .append('g')
                    .attr('class', 'timeline');

            timeline.append('path')
                .attr('class', 'line')
                .attr('d', function(d) {
                    return line(d.values);
                })
                .style('stroke', function(d) { return colors(d.id); });
        }
    });

});
<|endoftext|>


<commit_before>Elm.Native.Json = {};
Elm.Native.Json.make = function(elm) {

    elm.Native = elm.Native || {};
    elm.Native.Json = elm.Native.Json || {};
    if (elm.Native.Json.values) return elm.Native.Json.values;

    var Result = Elm.Result.make(elm);
    var Dict = Elm.Dict.make(elm);
    var List = Elm.Native.List.make(elm);
    var Utils = Elm.Native.Utils.make(elm);

    function toJS(v) {
        switch (v.ctor) {
        case 'Null'   : return null;
        case 'String' : return v._0;
        case 'Number' : return v._0;
        case 'Boolean': return v._0;
        case 'Object' :
            var obj = {};
            var array = List.toArray(Dict.toList(v._0));
            for (var i = array.length; i--; ) {
                var entry = array[i];
                obj[entry._0] = toJS(entry._1);
            }
            return obj;
        case 'Array'  :
            var array = List.toArray(v._0);
            for (var i = array.length; i--; ) {
                array[i] = toJS(array[i]);
            }
            return array;
        }
    }

    function toString(sep, value) {
        return JSON.stringify(toJS(value), null, sep);
    }

    function fromJS(v) {
        switch (typeof v) {
        case 'string' : return { ctor:"String" , _0: v };
        case 'number' : return { ctor:"Number" , _0: v };
        case 'boolean': return { ctor:"Boolean", _0: v };
        case 'object' :
            if (v === null) return { ctor:"Null" };
            if (v instanceof Array) {
                var array = new Array(v.length);
                for (var i = v.length; i--; ) {
                    array[i] = fromJS(v[i]);
                }
                return {
                    ctor:"Array",
                    _0: List.fromArray(array)
                };
            }
            var array = [];
            for (var key in v) {
                var value = fromJS(v[key]);
                array.push(Utils.Tuple2(key, value));
            }
            var list = List.fromArray(array);
            return {
                ctor:"Object",
                _0: Dict.fromList(list)
            };
        }
    }

    function fromString(str) {
        try {
            return Result.Ok(fromJS(JSON.parse(str)));
        } catch (err) {
            return Result.Err(err.message + ' when parsing JSON: ' + str);
        }
    }

    return elm.Native.Json.values = {
        toString   : F2(toString),
        fromString : fromString,
        fromJS     : fromJS,
        toJS       : toJS
    };

};
<commit_msg>Get rid of old JSON implementation<commit_after><|endoftext|>


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

import SpaceItem from '@ciscospark/react-component-space-item';

const propTypes = {
  activeSpaceId: PropTypes.string,
  currentUser: PropTypes.shape({
    id: PropTypes.string.isRequired
  }).isRequired,
  hasCalling: PropTypes.bool,
  onCallClick: PropTypes.func,
  onClick: PropTypes.func,
  spaces: PropTypes.oneOfType([
    PropTypes.arrayOf(
      PropTypes.shape({
        avatarUrl: PropTypes.string,
        activityText: PropTypes.oneOfType([
          PropTypes.string,
          PropTypes.element
        ]),
        callStartTime: PropTypes.number,
        id: PropTypes.string,
        isDecrypting: PropTypes.bool,
        isUnread: PropTypes.bool,
        lastActivityTime: PropTypes.string,
        name: PropTypes.string,
        teamColor: PropTypes.string,
        teamName: PropTypes.string,
        type: PropTypes.string
      })
    ),
    // Can accept an object that can iterated with `forEach`
    PropTypes.object
  ])
};

const defaultProps = {
  activeSpaceId: '',
  hasCalling: false,
  onCallClick: () => {},
  onClick: () => {},
  spaces: []
};

export default function SpacesList({
  activeSpaceId,
  currentUser,
  hasCalling,
  onCallClick,
  onClick,
  spaces
}) {
  const recents = [];
  spaces.forEach((space) => recents.push(<SpaceItem
    active={space.id === activeSpaceId}
    currentUser={currentUser}
    hasCalling={hasCalling}
    key={space.id}
    onCallClick={onCallClick}
    onClick={onClick}
    {...space}
  />));

  return (

      {recents}

  );
}

SpacesList.propTypes = propTypes;
SpacesList.defaultProps = defaultProps;
<commit_msg>feat(spaces-list): remove unused currentUser prop<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import SpaceItem from '@ciscospark/react-component-space-item';

const propTypes = {
  activeSpaceId: PropTypes.string,
  hasCalling: PropTypes.bool,
  onCallClick: PropTypes.func,
  onClick: PropTypes.func,
  spaces: PropTypes.oneOfType([
    PropTypes.arrayOf(
      PropTypes.shape({
        avatarUrl: PropTypes.string,
        activityText: PropTypes.oneOfType([
          PropTypes.string,
          PropTypes.element
        ]),
        callStartTime: PropTypes.number,
        id: PropTypes.string,
        isDecrypting: PropTypes.bool,
        isUnread: PropTypes.bool,
        lastActivityTime: PropTypes.string,
        name: PropTypes.string,
        teamColor: PropTypes.string,
        teamName: PropTypes.string,
        type: PropTypes.string
      })
    ),
    // Can accept an object that can iterated with `forEach`
    PropTypes.object
  ])
};

const defaultProps = {
  activeSpaceId: '',
  hasCalling: false,
  onCallClick: () => {},
  onClick: () => {},
  spaces: []
};

export default function SpacesList({
  activeSpaceId,
  hasCalling,
  onCallClick,
  onClick,
  spaces
}) {
  const recents = [];
  spaces.forEach((space) => recents.push(<SpaceItem
    active={space.id === activeSpaceId}
    hasCalling={hasCalling}
    key={space.id}
    onCallClick={onCallClick}
    onClick={onClick}
    {...space}
  />));

  return (

      {recents}

  );
}

SpacesList.propTypes = propTypes;
SpacesList.defaultProps = defaultProps;
<|endoftext|>


<commit_before>const Card = require('../../card/card')
const { Command } = require('discord.js-commando')

const winston = require('winston')

const SOUND_KINDS = ['play', 'attack', 'trigger', 'death']

class SoundCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'sound',
            aliases: ['snd', 's'],
            group: 'card',
            memberName: 'sound',
            guildOnly: true,
            description: 'Plays card sound in your voice channel.',
            details: '`[soundKind]` can be one of `play`, `attack`, `death` or `trigger`. Optional.',
            format:'[soundKind] <cardName>',
            examples: [
                'sound tirion',
                'sound attack jaraxxus',
                'snd death refreshment vendor',
                's trigger antonaidas'
            ],
            args: [
                {
                    key: 'soundKind',
                    prompt: '',
                    type: 'string',
                    parse: value => { return value.toLowerCase() },
                    default: 'play'
                },
                {
                    key: 'cardName',
                    prompt: 'what card are you searching for?\n',
                    type: 'string',
                    default: ''
                }
            ]
        })
        this.queue = []
    }

    async run(msg, args) {
        if (!SOUND_KINDS.includes(args.soundKind)) {
            args.cardName = `${args.soundKind} ${args.cardName}`.trim()
            args.soundKind = 'play'
        }
        if (!args.cardName) {
            this.args[1].default = null
            args.cardName = await this.args[1].obtain(msg).catch(winston.error)
            this.args[1].default = ''
        }
        if (!args.soundKind || !args.cardName) { return msg.reply('cancelled command.').catch(winston.error) }

        if (!msg.channel.typing) { msg.channel.startTyping() }
        let reply, sounds
        const card = await Card.findByName(args.cardName).catch(winston.error)
        if (!card) { reply = `sorry, I couldn't find a card with a name like '${args.cardName}'` }
        else {
            sounds = card.getSoundParts(args.soundKind)
            if (!sounds || sounds.length < 1) { reply = `sorry, I don't know the ${args.soundKind} sound for ${card.name}.` }
        }

        return msg.reply(reply || `I'll join your voice channel and play the ${args.soundKind} sound for ${card.name} in a moment.`)
            .then(m => { if (m.channel.typing) { m.channel.stopTyping() } })
            .then(() => {
                if (reply) { return }
                this.queue.push({ message: msg, card: card, soundKind: args.soundKind })
                if (this.queue.length === 1) { this.handleSound().catch(winston.error) }
            }).catch(winston.error)
    }

    async handleSound() {
        const message = this.queue[0].message
        const card = this.queue[0].card
        const soundKind = this.queue[0].soundKind

        let reply, connection
        const file = await card.getSound(soundKind).catch(winston.error)
        if (!file) { reply = `sorry, I wasn't able to get the ${soundKind} sound for ${card.name}.` }
        else {
            connection = await this.joinVoiceChannel(message.member.voiceChannel).catch(winston.error)
            if (!connection || typeof connection === 'string') {
                if (message.member.voiceChannel) { message.member.voiceChannel.leave() }
                reply = `sorry, there was an error joining your voice channel, ${connection || 'unkown'}`
            }
        }

        if (reply) {
            return message.reply(reply)
                .then(() => {
                    this.queue.shift()
                    if (this.queue.length > 0) { this.handleSound() }
                }).catch(winston.error)
        }

        connection.playFile(file).on('end', () => {
            this.queue.shift()
            if (this.queue.length > 0) {
                if (this.queue[0].message.member.voiceChannel !== connection.channel) { connection.channel.leave() }
                this.handleSound()
            } else { connection.channel.leave() }
        })
    }

    async joinVoiceChannel(voiceChannel) {
        if (!voiceChannel || voiceChannel.type !== 'voice') { return 'you\'re not in one' }
        const connection = this.client.voiceConnections.find(conn => conn.channel === voiceChannel)
        if (connection) { return connection }
        return await voiceChannel.join().catch(err => { return err.message.replace('You', 'I') })
    }
}

module.exports = SoundCommand
<commit_msg>Update queue property and playSound method to be static<commit_after>const Card = require('../../card/card')
const { Command } = require('discord.js-commando')

const winston = require('winston')

const SOUND_KINDS = ['play', 'attack', 'trigger', 'death']

class SoundCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'sound',
            aliases: ['snd', 's'],
            group: 'card',
            memberName: 'sound',
            guildOnly: true,
            description: 'Plays card sound in your voice channel.',
            details: '`[soundKind]` can be one of `play`, `attack`, `death` or `trigger`. Optional.',
            format:'[soundKind] <cardName>',
            examples: [
                'sound tirion',
                'sound attack jaraxxus',
                'snd death refreshment vendor',
                's trigger antonaidas'
            ],
            args: [
                {
                    key: 'soundKind',
                    prompt: '',
                    type: 'string',
                    parse: value => { return value.toLowerCase() },
                    default: 'play'
                },
                {
                    key: 'cardName',
                    prompt: 'what card are you searching for?\n',
                    type: 'string',
                    default: ''
                }
            ]
        })
    }

    async run(msg, args) {
        if (!SOUND_KINDS.includes(args.soundKind)) {
            args.cardName = `${args.soundKind} ${args.cardName}`.trim()
            args.soundKind = 'play'
        }
        if (!args.cardName) {
            this.args[1].default = null
            args.cardName = await this.args[1].obtain(msg).catch(winston.error)
            this.args[1].default = ''
        }
        if (!args.soundKind || !args.cardName) { return msg.reply('cancelled command.').catch(winston.error) }

        if (!msg.channel.typing) { msg.channel.startTyping() }
        let reply, sounds
        const card = await Card.findByName(args.cardName).catch(winston.error)
        if (!card) { reply = `sorry, I couldn't find a card with a name like '${args.cardName}'` }
        else {
            sounds = card.getSoundParts(args.soundKind)
            if (!sounds || sounds.length < 1) { reply = `sorry, I don't know the ${args.soundKind} sound for ${card.name}.` }
        }

        return msg.reply(reply || `I'll join your voice channel and play the ${args.soundKind} sound for ${card.name} in a moment.`)
            .then(m => { if (m.channel.typing) { m.channel.stopTyping() } })
            .then(() => {
                if (reply) { return }
                SoundCommand.queue.push({ message: msg, card: card, soundKind: args.soundKind })
                if (SoundCommand.queue.length === 1) { SoundCommand.playSound(this.client).catch(winston.error) }
            }).catch(winston.error)
    }

    static get queue() {
        if (!this._queue) { this._queue = [] }
        return this._queue
    }

    static async playSound(client) {
        const message = this.queue[0].message
        const card = this.queue[0].card
        const soundKind = this.queue[0].soundKind

        let reply, connection
        const file = await card.getSound(soundKind).catch(winston.error)
        if (!file) { reply = `sorry, I wasn't able to get the ${soundKind} sound for ${card.name}.` }
        else {
            connection = await this.joinVoiceChannel(message.member.voiceChannel).catch(winston.error)
            if (!connection || typeof connection === 'string') {
                if (message.member.voiceChannel) { message.member.voiceChannel.leave() }
                reply = `sorry, there was an error joining your voice channel, ${connection || 'unkown'}`
            }
        }

        if (reply) {
            return message.reply(reply)
                .then(() => {
                    this.queue.shift()
                    if (this.queue.length > 0) { this.playSound(client) }
                }).catch(winston.error)
        }

        connection.playFile(file).on('end', () => {
            this.queue.shift()
            if (this.queue.length > 0) {
                if (this.queue[0].message.member.voiceChannel !== connection.channel) { connection.channel.leave() }
                this.playSound(client)
            } else { connection.channel.leave() }
        })
    }

    async joinVoiceChannel(voiceChannel) {
        if (!voiceChannel || voiceChannel.type !== 'voice') { return 'you\'re not in one' }
        const connection = this.client.voiceConnections.find(conn => conn.channel === voiceChannel)
        if (connection) { return connection }
        return await voiceChannel.join().catch(err => { return err.message.replace('You', 'I') })
    }
}

module.exports = SoundCommand
<|endoftext|>


<commit_before>const MSS = require("./../../functions/");
const meta = require("./meta.json");

module.exports = function yt(message) {
	let input = message.content.replace (/\n/g, "").split(" ");

	input.shift();
	input.shift();
	let items = input.join(" ");
	let vote = items.split(";");

	if(vote.length < 1) {
		return message.channel.send("Too few options!");
	} else if (vote.length > 9) {
		return message.channel.send("Too many options!");
	}

	let reply = meta[message.data.lang] && meta[message.data.lang].message_message_vote || "message_vote";

	vote.forEach((item, iterator) => {
		message.react(`\u003${iterator + 1}\u20e3`);
		reply += `\n${iterator + 1} - ${item}`
	});

	message.channel.send(reply);
}
<commit_msg>Add iterator to \u0030<commit_after>const MSS = require("./../../functions/");
const meta = require("./meta.json");

module.exports = function yt(message) {
	let input = message.content.replace (/\n/g, "").split(" ");

	input.shift();
	input.shift();
	let items = input.join(" ");
	let vote = items.split(";");

	if(vote.length < 1) {
		return message.channel.send("Too few options!");
	} else if (vote.length > 9) {
		return message.channel.send("Too many options!");
	}

	let reply = meta[message.data.lang] && meta[message.data.lang].message_message_vote || "message_vote";

	vote.forEach((item, iterator) => {
		message.react(`${\u0030 + iterator}\u20e3`);
		reply += `\n${iterator + 1} - ${item}`
	});

	message.channel.send(reply);
}
<|endoftext|>


<commit_before>"use strict";

let smConfig = require(__dirname + '/package.json');

let bunyan  = require('bunyan');
let request = require('request');
let path = require('path');
let logstream = require('./logstream');

let logger  = bunyan.createLogger({
    name: 'Samanage.js v' + smConfig.version,
    streams: [{
        path: path.join(__dirname, "/logs/Samanage.js.log"),
        level: "debug"
    },{
        type: "raw",
        stream: logstream,
        level: "info"
    }]
});

let Samanage = function (config) {
    this._verbose   = 0;
    //this._debug     = config.debug || 0;

    this._api = {
        version: [
            'application/vnd.samanage.v1.1+json',
            'application/vnd.samanage.v1.2+json',
            'application/vnd.samanage.v1.3+json',
            'application/vnd.samanage.v2.1+json'
        ],
        header: { accept: 'application/vnd.samanage.v2.1+json' }, // Use latest version by default.
        url:    {
            app:  (config && config.app) ? config.app : 'api', // Default to api, settable to owned application name
            base: 'samanage.com',
            type: null
        }
    };

    this._options = {
        waitTime:       (config && config.waitTime)      ? config.waitTime      : 5000,
        sendEmail:      (config && config.sendEmail)     ? config.sendEmail     : true,
        layout:         (config && config.layout)        ? config.layout        : "long",
        incidentRetry:  (config && config.incidentRetry) ? config.incidentRetry : true,
        stateID: {
            "resolved":       (config && config.stateID.resolved)       ? config.stateID.resolved        : '',
            "assigned":       (config && config.stateID.assigned)       ? config.stateID.assigned        : '',
            "awaiting_input": (config && config.stateID.awaiting_input) ? config.stateID.awaiting_input  : '',
            "on_hold":        (config && config.stateID.on_hold)        ? config.stateID.on_hold         : '',
            "new":            (config && config.stateID["new"])         ? config.stateID["new"]          : ''
        },
        template: {
            solution: "solution",
            incident: "incident"
        }
    };

    this._auth = null;

    this._buildURL = function (localApi) {
        let url = (localApi || this._api).url;

        return "https://" + url.app + "." + url.base + (url.type ? '/' + url.type : '');
    };

    this._request = request.defaults({
        baseUrl: this._buildURL(),
        headers: {
            accept: this._api.header.accept
        },
        json: true
    });
};

Samanage.prototype.auth = function(auth) {

    let self = this;

    if ((auth.username && auth.password)) {
         self._request = self._request.defaults({
            auth: { auth }
        });
    }  else if (auth.bearer) {
        self._request = self._request.defaults({
            headers: {
                "X-Samanage-Authorization": "Bearer "+auth.bearer,
                accept: self._api.header.accept
            }
        });
    } else {
        logger.fatal('Username/password or bearer token now found. Please check your code and try again')
    }
};

Samanage.prototype.config =  function(options) {

    let type = Object.prototype.toString.call(options);
    if (type === "[object Object]") {
        return this.config().set(options);
    } else if (type === "[object String]") {
        return this.config().get(options);
    }

    let self = this;
    let get = function (option) {
        return (option && self._options[option]) ? self._options[option] : self._options;
    };

    let set = function (options) {
        if (options) {
            let keys = Object.keys(options);
            for (let i = 0; i < keys.length; i++) {
                let key = keys[i];
                if (self._options.hasOwnProperty(key)) {
                    self._options[key] = options[key];
                } else {
                    logger.warn('Option ' + key + ' is not a valid option, please check your code')
                }
            }
        } else {
            logger.warn("Can't SET anything if you don't give me arguments...");
        }
    };

    return {
        get: get,
        set: set
    }
};

Samanage.prototype.utils = {

    checkErrorCodes: function(res) {
        let code = res.statusCode;
        let codes = {
            400: `${code}, Please check your URL and try again`,
            401: `${code}, Please check your credentials are correct`,
            403: `${code}, Not allowed to access this page`,
            404: `${code}, ${res.body}`
        };

        return codes[res.statusCode] || (res.statusMessage !== '' ? res.statusMessage : res.body);
    }
};

/**
 *  Takes a query string or URL directly from Samanage and converts it to an object. This object can then be used
 * with the 'qs' option for request. incidents.search() calls this function if 'config' is a string.
 *
 * @param {String} qString query string to convert to an object for searching
 * @returns {Object}
 */
Samanage.prototype.createSearchObject = function(qString) {

    let y = qString.split("?");

    if (y.length > 1) { qString = y[1]; }

    let x = decodeURIComponent(qString).split("&").filter(Boolean);

    let len = x.length;
    let out = { };

    for (let i = 0; i < len; i++) {
        let curs = x[i].split("=");

        if (out[curs[0]]) {
            out[curs[0]].push(curs[1]);
        } else {
            out[curs[0]] = [curs[1]];
        }
    }

    return out;
};

Samanage.prototype.MessageTemplate    = require(__dirname + '/lib/MessageTemplate'      );

Samanage.prototype.categories         = require(__dirname + '/lib/categories'           );
Samanage.prototype.changes            = require(__dirname + '/lib/changes'              );
Samanage.prototype.comments           = require(__dirname + '/lib/comments'             );
Samanage.prototype.configurationItems = require(__dirname + '/lib/configurationItems'   );
Samanage.prototype.contracts          = require(__dirname + '/lib/contracts'            );
Samanage.prototype.departments        = require(__dirname + '/lib/departments'          );
Samanage.prototype.groups             = require(__dirname + '/lib/groups'               );
Samanage.prototype.hardware           = require(__dirname + '/lib/hardware'             );
Samanage.prototype.incidents          = require(__dirname + '/lib/incidents'            );
Samanage.prototype.items              = require(__dirname + '/lib/items'                );
Samanage.prototype.memberships        = require(__dirname + '/lib/memberships'          );
Samanage.prototype.mobileDevices      = require(__dirname + '/lib/mobileDevices'        );
Samanage.prototype.otherAssets        = require(__dirname + '/lib/otherAssets'          );
Samanage.prototype.printers           = require(__dirname + '/lib/printers'             );
Samanage.prototype.problems           = require(__dirname + '/lib/problems'             );
Samanage.prototype.purchases          = require(__dirname + '/lib/purchases'            );
Samanage.prototype.purchaseOrders     = require(__dirname + '/lib/purchaseOrders'       );
Samanage.prototype.releases           = require(__dirname + '/lib/releases'             );
Samanage.prototype.risks              = require(__dirname + '/lib/risks'                );
Samanage.prototype.roles              = require(__dirname + '/lib/roles'                );
Samanage.prototype.serviceRequests    = require(__dirname + '/lib/serviceRequests'      );
Samanage.prototype.sites              = require(__dirname + '/lib/sites'                );
Samanage.prototype.software           = require(__dirname + '/lib/software'             );
Samanage.prototype.solutions          = require(__dirname + '/lib/solutions'            );
Samanage.prototype.tasks              = require(__dirname + '/lib/tasks'                );
Samanage.prototype.timeTracks         = require(__dirname + '/lib/timeTracks'           );
Samanage.prototype.users              = require(__dirname + '/lib/users'                );
Samanage.prototype.vendors            = require(__dirname + '/lib/vendors'              );

module.exports = Samanage;<commit_msg>updated some files<commit_after>"use strict";

let smConfig = require(__dirname + '/package.json');

let bunyan  = require('bunyan');
let request = require('request');
let path = require('path');
let logstream = require('./logstream');

let logger  = bunyan.createLogger({
    name: 'Samanage.js v' + smConfig.version,
    streams: [{
        path: path.join(__dirname, "/logs/Samanage.js.log"),
        level: "debug"
    },{
        type: "raw",
        stream: logstream,
        level: "info"
    }]
});

let Samanage = function (config) {
    this._verbose   = 0;
    //this._debug     = config.debug || 0;

    this._api = {
        version: [
            'application/vnd.samanage.v1.1+json',
            'application/vnd.samanage.v1.2+json',
            'application/vnd.samanage.v1.3+json',
            'application/vnd.samanage.v2.1+json'
        ],
        header: { accept: 'application/vnd.samanage.v2.1+json' }, // Use latest version by default.
        url:    {
            app:  (config && config.app) ? config.app : 'api', // Default to api, settable to owned application name
            base: 'samanage.com',
            type: null
        }
    };

    this._options = {
        waitTime:       (config && config.waitTime)      ? config.waitTime      : 5000,
        sendEmail:      (config && config.sendEmail)     ? config.sendEmail     : true,
        layout:         (config && config.layout)        ? config.layout        : "long",
        incidentRetry:  (config && config.incidentRetry) ? config.incidentRetry : true,
        stateID: {
            "resolved":       (config && config.stateID.resolved)       ? config.stateID.resolved        : '',
            "assigned":       (config && config.stateID.assigned)       ? config.stateID.assigned        : '',
            "awaiting_input": (config && config.stateID.awaiting_input) ? config.stateID.awaiting_input  : '',
            "on_hold":        (config && config.stateID.on_hold)        ? config.stateID.on_hold         : '',
            "new":            (config && config.stateID["new"])         ? config.stateID["new"]          : ''
        },
        template: {
            solution: "solution",
            incident: "incident"
        }
    };

    this._auth = null;

    this._buildURL = function (localApi) {
        let url = (localApi || this._api).url;

        return "https://" + url.app + "." + url.base + (url.type ? '/' + url.type : '');
    };

    this._request = request.defaults({
        baseUrl: this._buildURL(),
        headers: {
            accept: this._api.header.accept
        },
        json: true
    });
};

Samanage.prototype.auth = function(auth) {

    let self = this;

    if ((auth.username && auth.password)) {
         self._request = self._request.defaults({
            auth: { auth }
        });
    }  else if (auth.bearer) {
        self._request = self._request.defaults({
            headers: {
                "X-Samanage-Authorization": "Bearer "+auth.bearer,
                accept: self._api.header.accept
            }
        });
    } else {
        logger.fatal('Username/password or bearer token now found. Please check your code and try again')
    }
};

Samanage.prototype.config =  function(options) {

    let type = Object.prototype.toString.call(options);
    if (type === "[object Object]") {
        return this.config().set(options);
    } else if (type === "[object String]") {
        return this.config().get(options);
    }

    let self = this;
    let get = function (option) {
        return (option && self._options[option]) ? self._options[option] : self._options;
    };

    let set = function (options) {
        if (options) {
            let keys = Object.keys(options);
            for (let i = 0; i < keys.length; i++) {
                let key = keys[i];
                if (self._options.hasOwnProperty(key)) {
                    self._options[key] = options[key];
                } else {
                    logger.warn('Option ' + key + ' is not a valid option, please check your code')
                }
            }
        } else {
            logger.warn("Can't SET anything if you don't give me arguments...");
        }
    };

    return {
        get: get,
        set: set
    }
};

Samanage.prototype.utils = {

    checkErrorCodes: function(res) {
        let code = res.statusCode;
        let codes = {
            400: `${code}, Please check your URL and try again`,
            401: `${code}, Please check your credentials are correct`,
            403: `${code}, Not allowed to access this page`,
            404: `${code}, ${res.body}`
        };

        return codes[res.statusCode] || (res.statusMessage !== '' ? res.statusMessage : res.body);
    }
};

/**
 *  Takes a query string or URL directly from Samanage and converts it to an object. This object can then be used
 * with the 'qs' option for request. incidents.search() calls this function if 'config' is a string.
 *
 * @param {String} qString query string to convert to an object for searching
 * @returns {Object}
 */
Samanage.prototype.createSearchObject = function(qString) {

    let y = qString.split("?");

    if (y.length > 1) { qString = y[1]; }

    let x = decodeURIComponent(qString).split("&").filter(Boolean);

    let len = x.length;
    let out = { };

    for (let i = 0; i < len; i++) {
        let curs = x[i].split("=");

        if (out[curs[0]]) {
            out[curs[0]].push(curs[1]);
        } else {
            out[curs[0]] = [curs[1]];
        }
    }

    return out;
};

Samanage.prototype.MessageTemplate    = require(__dirname + '/lib/MessageTemplate.js'      );
Samanage.prototype.categories         = require(__dirname + '/lib/categories.js'           );
Samanage.prototype.changes            = require(__dirname + '/lib/changes.js'              );
Samanage.prototype.comments           = require(__dirname + '/lib/comments.js'             );
Samanage.prototype.configurationItems = require(__dirname + '/lib/configurationItems.js'   );
Samanage.prototype.contracts          = require(__dirname + '/lib/contracts.js'            );
Samanage.prototype.departments        = require(__dirname + '/lib/departments.js'          );
Samanage.prototype.groups             = require(__dirname + '/lib/groups.js'               );
Samanage.prototype.hardware           = require(__dirname + '/lib/hardware.js'             );
Samanage.prototype.incidents          = require(__dirname + '/lib/incidents.js'            );
Samanage.prototype.items              = require(__dirname + '/lib/items.js'                );
Samanage.prototype.memberships        = require(__dirname + '/lib/memberships.js'          );
Samanage.prototype.mobileDevices      = require(__dirname + '/lib/mobileDevices.js'        );
Samanage.prototype.otherAssets        = require(__dirname + '/lib/otherAssets.js'          );
Samanage.prototype.printers           = require(__dirname + '/lib/printers.js'             );
Samanage.prototype.problems           = require(__dirname + '/lib/problems.js'             );
Samanage.prototype.purchases          = require(__dirname + '/lib/purchases.js'            );
Samanage.prototype.purchaseOrders     = require(__dirname + '/lib/purchaseOrders.js'       );
Samanage.prototype.releases           = require(__dirname + '/lib/releases.js'             );
Samanage.prototype.risks              = require(__dirname + '/lib/risks.js'                );
Samanage.prototype.roles              = require(__dirname + '/lib/roles.js'                );
Samanage.prototype.serviceRequests    = require(__dirname + '/lib/serviceRequests.js'      );
Samanage.prototype.sites              = require(__dirname + '/lib/sites.js'                );
Samanage.prototype.software           = require(__dirname + '/lib/software.js'             );
Samanage.prototype.solutions          = require(__dirname + '/lib/solutions.js'            );
Samanage.prototype.tasks              = require(__dirname + '/lib/tasks.js'                );
Samanage.prototype.timeTracks         = require(__dirname + '/lib/timeTracks.js'           );
Samanage.prototype.users              = require(__dirname + '/lib/users.js'                );
Samanage.prototype.vendors            = require(__dirname + '/lib/vendors.js'              );

module.exports = Samanage;<|endoftext|>


<commit_before>import React from 'react';

const Gamecard = React.createClass({
	render: function() {
		const CardTitle = {
			background: 'url("' + this.props.image + '") center / cover'
		};

		return (

{ this.props.title }

					{ this.props.description }

						HOW-TO

						START send

		);
	}
});

export default Gamecard;
<commit_msg>Comments<commit_after>import React from 'react';

// Card for showing available games
const Gamecard = React.createClass({
	render: function() {
		// CSS with card image
		const CardTitle = {
			background: 'url("' + this.props.image + '") center / cover'
		};

		return (

{ this.props.title }

					{ this.props.description }

						HOW-TO

						START send

		);
	}
});

export default Gamecard;
<|endoftext|>


<commit_before>/**
*  NewItem.js
*  Description: container item for new feed
*  Modules: React and React Native Modules
*  Dependencies: styles.js Title
*  Author: Tiffany Tse
*/
import React, { Component, PropTypes } from 'react';
import {
    View,
    TouchableOpacity,
    StyleSheet
} from 'react-native';
import Byline from './Byline';
import AppText from './AppText';
import Thumbnail from './Thumbnail';
import * as globalStyles from '../styles/global';

export default class NewsItem extends Component {

  constructor(props) {
    super(props);

    this.onLongPress = this.onLongPress.bind(this);
  }

  onLongPress() {
    ActionSheetIOS.showActionSheetWithOptions({
      options: ['Bookmark', 'Cancel'],
      cancelButtonIndex: 1,
      title: this.props.title
    }, buttonIndex => console.log('Button selected', buttonIndex));
  }

  render() {
    const {
      style,
      imageUrl,
      title,
      author,
      date,
      location,
      description,
      onPress
    } = this.props;
    const accentColor = globalStyles.ACCENT_COLORS[
      this.props.index % globalStyles.ACCENT_COLORS.length
    ];
    return (
      <TouchableOpacity
        style={style}
        onLongPress={this.onLongPress}
        onPress={onPress}
      >
        <View>
          <Thumbnail
            url={imageUrl}
            titleText={title}
            accentColor={accentColor}
            style={styles.thumbnail}
          />
          <View style={styles.content}>
            <Byline
              author={author}
              date={date}
              location={location}
            />
            <AppText>
              {description}
            </AppText>
          </View>
        </View>
      </TouchableOpacity>
    );
  }
}

NewsItem.propTypes = {
  imageUrl: PropTypes.string,
  title: PropTypes.string.isRequired,
  description: PropTypes.string,
  date: PropTypes.instanceOf(Date).isRequired,
  author: PropTypes.string.isRequired,
  location: PropTypes.string,
  index: PropTypes.number.isRequired,
  onPress: PropTypes.func.isRequired,
  style: View.propTypes.style
};

const styles = StyleSheet.create({
  thumbnail: {
    marginBottom: 5
  },
  content: {
    paddingHorizontal: 5
  }
});<commit_msg>corrected comments, since currently iOS platform is developed first for project<commit_after>/**
*  NewItem.js
*  Description: container item for new feed (ios version)
*  Modules: React and React Native Modules
*  Dependencies: styles.js Title
*  Author: Tiffany Tse
*/
import React, { Component, PropTypes } from 'react';
import {
    View,
    TouchableOpacity,
    StyleSheet
} from 'react-native';
import Byline from './Byline';
import AppText from './AppText';
import Thumbnail from './Thumbnail';
import * as globalStyles from '../styles/global';

export default class NewsItem extends Component {

  constructor(props) {
    super(props);

    this.onLongPress = this.onLongPress.bind(this);
  }

  onLongPress() {
    ActionSheetIOS.showActionSheetWithOptions({
      options: ['Bookmark', 'Cancel'],
      cancelButtonIndex: 1,
      title: this.props.title
    }, buttonIndex => console.log('Button selected', buttonIndex));
  }

  render() {
    const {
      style,
      imageUrl,
      title,
      author,
      date,
      location,
      description,
      onPress
    } = this.props;
    const accentColor = globalStyles.ACCENT_COLORS[
      this.props.index % globalStyles.ACCENT_COLORS.length
    ];
    return (
      <TouchableOpacity
        style={style}
        onLongPress={this.onLongPress}
        onPress={onPress}
      >
        <View>
          <Thumbnail
            url={imageUrl}
            titleText={title}
            accentColor={accentColor}
            style={styles.thumbnail}
          />
          <View style={styles.content}>
            <Byline
              author={author}
              date={date}
              location={location}
            />
            <AppText>
              {description}
            </AppText>
          </View>
        </View>
      </TouchableOpacity>
    );
  }
}

NewsItem.propTypes = {
  imageUrl: PropTypes.string,
  title: PropTypes.string.isRequired,
  description: PropTypes.string,
  date: PropTypes.instanceOf(Date).isRequired,
  author: PropTypes.string.isRequired,
  location: PropTypes.string,
  index: PropTypes.number.isRequired,
  onPress: PropTypes.func.isRequired,
  style: View.propTypes.style
};

const styles = StyleSheet.create({
  thumbnail: {
    marginBottom: 5
  },
  content: {
    paddingHorizontal: 5
  }
});<|endoftext|>


<commit_before>import React from 'react'
import { debounce, includes, isEmpty } from 'lodash'
import { uniqBy } from 'lodash/fp'
import { KeyControlledItemList } from './KeyControlledList'
import { getKeyCode, keyMap } from '../util/textInput'
import { NonLinkAvatar } from './Avatar'
import cx from 'classnames'
const { array, bool, string, func } = React.PropTypes

// keys that can be pressed to create a new tag
const creationKeyCodes = [keyMap.ENTER, keyMap.SPACE, keyMap.COMMA]

export default class TagInput extends React.Component {
  static propTypes = {
    tags: array,
    type: string,
    choices: array,
    handleInput: func.isRequired,
    onSelect: func,
    onRemove: func,
    allowNewTags: bool,
    placeholder: string,
    filter: func,
    className: string
  }

  resetInput () {
    this.refs.input.value = ''
    this.props.handleInput('')
  }

  handleKeys = event => {
    let { allowNewTags, onSelect, handleInput, filter } = this.props
    const keyCode = getKeyCode(event)
    const keyWasHandled = this.refs.list && this.refs.list.handleKeys(event)

    if (!keyWasHandled && allowNewTags) {
      // if the current input has matching search results, you can press Escape
      // to clear the results.
      if (keyCode === keyMap.ESC) {
        handleInput('')
        return
      }

      // if there are no matches, or there are matches but none has been
      // selected yet, you can also press any key listed in creationKeyCodes to
      // create a tag based on what you've typed so far.
      if (includes(creationKeyCodes, keyCode)) {
        let { value } = event.target
        onSelect({id: value, name: value})
        this.resetInput()
        event.preventDefault()
        return
      }
    }

    if (filter) filter(event)
  }

  select = choice => {
    this.props.onSelect(choice)
    this.resetInput()
  }

  remove = tag => event => {
    this.props.onRemove(tag)
    event.preventDefault()
  }

  focus = () => {
    this.refs.input.focus()
  }

  handleChange = debounce(value => {
    this.props.handleInput(value)
  }, 200)

  render () {
    let { choices, tags, placeholder, className } = this.props
    if (!tags) tags = []
    if (!placeholder) placeholder = 'Type...'

    return

        {uniqBy('id', tags).map(t =>

          {t.avatar_url && <NonLinkAvatar person={t} />}
          {t.label || t.name}
          ×

)}

      <input ref='input' type='text' placeholder={placeholder} spellCheck={false}
        onChange={event => this.handleChange(event.target.value)}
        onKeyDown={this.handleKeys} />

      {!isEmpty(choices) &&

        <KeyControlledItemList className='dropdown-menu' ref='list'
          items={choices} onChange={this.select} />

}

  }
}
<commit_msg>don't allow submitting a blank tag<commit_after>import React from 'react'
import { debounce, includes, isEmpty } from 'lodash'
import { uniqBy } from 'lodash/fp'
import { KeyControlledItemList } from './KeyControlledList'
import { getKeyCode, keyMap } from '../util/textInput'
import { NonLinkAvatar } from './Avatar'
import cx from 'classnames'
const { array, bool, string, func } = React.PropTypes

// keys that can be pressed to create a new tag
const creationKeyCodes = [keyMap.ENTER, keyMap.SPACE, keyMap.COMMA]

export default class TagInput extends React.Component {
  static propTypes = {
    tags: array,
    type: string,
    choices: array,
    handleInput: func.isRequired,
    onSelect: func,
    onRemove: func,
    allowNewTags: bool,
    placeholder: string,
    filter: func,
    className: string
  }

  resetInput () {
    this.refs.input.value = ''
    this.props.handleInput('')
  }

  handleKeys = event => {
    let { allowNewTags, onSelect, handleInput, filter } = this.props
    const keyCode = getKeyCode(event)
    const keyWasHandled = this.refs.list && this.refs.list.handleKeys(event)

    if (!keyWasHandled && allowNewTags) {
      // if the current input has matching search results, you can press Escape
      // to clear the results.
      if (keyCode === keyMap.ESC) {
        handleInput('')
        return
      }

      // if there are no matches, or there are matches but none has been
      // selected yet, you can also press any key listed in creationKeyCodes to
      // create a tag based on what you've typed so far.
      if (includes(creationKeyCodes, keyCode)) {
        let { value } = event.target
        if (!value) return
        onSelect({id: value, name: value})
        this.resetInput()
        event.preventDefault()
        return
      }
    }

    if (filter) filter(event)
  }

  select = choice => {
    this.props.onSelect(choice)
    this.resetInput()
  }

  remove = tag => event => {
    this.props.onRemove(tag)
    event.preventDefault()
  }

  focus = () => {
    this.refs.input.focus()
  }

  handleChange = debounce(value => {
    this.props.handleInput(value)
  }, 200)

  render () {
    let { choices, tags, placeholder, className } = this.props
    if (!tags) tags = []
    if (!placeholder) placeholder = 'Type...'

    return

        {uniqBy('id', tags).map(t =>

          {t.avatar_url && <NonLinkAvatar person={t} />}
          {t.label || t.name}
          ×

)}

      <input ref='input' type='text' placeholder={placeholder} spellCheck={false}
        onChange={event => this.handleChange(event.target.value)}
        onKeyDown={this.handleKeys} />

      {!isEmpty(choices) &&

        <KeyControlledItemList className='dropdown-menu' ref='list'
          items={choices} onChange={this.select} />

}

  }
}
<|endoftext|>


<commit_before>(function($) {
  "use strict";

  function notificationBar() {
    var completeMessage = $(".notification-bar").remove();
    $("#content-inner").before(completeMessage);
  }

  function closeNotification(){
    var notification = $(this).parent();
    var id = notification.attr("data-notification");

    $.ajax({
      url: noosfero_root()+"/admin/plugin/environment_notification/close_notification",
      type: "POST",
      data: {notification_id: id},
      success: function(response) {
        notification.fadeOut();
      }
    });
  }

  function hideNotification(){
    var notification = $(this).parent();
    var id = notification.attr("data-notification");

    $.ajax({
      url: noosfero_root()+"/admin/plugin/environment_notification/hide_notification",
      type: "POST",
      data: {notification_id: id},
      success: function(response) {
        notification.fadeOut();
      }
    });
  }

  function hideUserNotification(){
    var ids = $.cookie('hide_notifications');
    if(ids === null) {
      return null;
    }

    if(ids.startsWith('[') && ids.endsWith(']')){
      ids = ids.substring(1, ids.length - 1);
      ids = ids.split(",");

      for(var i = 0; i < ids.length; i++) {
        $('[data-notification="' + ids[i] + '"]').fadeOut();
      }
    }
  }

  function mceRestrict() {
    tinyMCE.init({
      menubar : false,
      selector: "textarea",
      plugins: [
          "autolink link"
      ],
      toolbar: "bold italic underline | link"
    });
  }

  function showPopup() {
    if($('.action-home-index').length > 0) {
      jQuery(function($){
        $.colorbox({href: noosfero_root()+'/plugin/environment_notification/public/notifications_with_popup?previous_path=home'});
      });
    }
    else {
      jQuery(function($){
        $.colorbox({href: noosfero_root()+'/plugin/environment_notification/public/notifications_with_popup'});
      });
    }
  }

  $(document).ready(function(){
    notificationBar();
    $(".notification-close").on("click", closeNotification);
    $(".notification-hide").on("click", hideNotification);

    if($('.environment-notification-plugin-message').length > 0){
      mceRestrict();
    }

    if($('.notification-bar').length > 0){
      hideUserNotification();
    }

    if($('[notification-display-popup="true"]').length > 0){
      showPopup();
    }
  });

})($);<commit_msg>Scoping environment_notification plugin's javascript functions<commit_after>(function($) {
  "use strict";

  var environment_notification_plugin = {

    notificationBar: function() {
      var completeMessage = $(".notification-bar").remove();
      $("#content-inner").before(completeMessage);
    },

    closeNotification: function(){
      var notification = $(this).parent();
      var id = notification.attr("data-notification");

      $.ajax({
        url: noosfero_root()+"/admin/plugin/environment_notification/close_notification",
        type: "POST",
        data: {notification_id: id},
        success: function(response) {
          notification.fadeOut();
        }
      });
    },

    hideNotification: function(){
      var notification = $(this).parent();
      var id = notification.attr("data-notification");

      $.ajax({
        url: noosfero_root()+"/admin/plugin/environment_notification/hide_notification",
        type: "POST",
        data: {notification_id: id},
        success: function(response) {
          notification.fadeOut();
        }
      });
    },

    hideUserNotification: function(){
      var ids = $.cookie('hide_notifications');
      if(ids === null) {
        return null;
      }

      if(ids.startsWith('[') && ids.endsWith(']')){
        ids = ids.substring(1, ids.length - 1);
        ids = ids.split(",");

        for(var i = 0; i < ids.length; i++) {
          $('[data-notification="' + ids[i] + '"]').fadeOut();
        }
      }
    },

    mceRestrict: function() {
      tinyMCE.init({
        menubar : false,
        selector: "textarea",
        plugins: [
            "autolink link"
        ],
        toolbar: "bold italic underline | link"
      });
    },

    showPopup: function() {
      if($('.action-home-index').length > 0) {
        jQuery(function($){
          $.colorbox({href: noosfero_root()+'/plugin/environment_notification/public/notifications_with_popup?previous_path=home'});
        });
      }
      else {
        jQuery(function($){
          $.colorbox({href: noosfero_root()+'/plugin/environment_notification/public/notifications_with_popup'});
        });
      }
    },
  };

  $(document).ready(function(){
    environment_notification_plugin.notificationBar();
    $(".notification-close").on("click", environment_notification_plugin.closeNotification);
    $(".notification-hide").on("click", environment_notification_plugin.hideNotification);

    if($('.environment-notification-plugin-message').length > 0){
      environment_notification_plugin.mceRestrict();
    }

    if($('.notification-bar').length > 0){
      environment_notification_plugin.hideUserNotification();
    }

    if($('[notification-display-popup="true"]').length > 0){
      environment_notification_plugin.showPopup();
    }
  });

})($);<|endoftext|>


<commit_before>import View from 'core/view/view';
import Log from 'core/infrastructure/log';
import Command from 'core/infrastructure/command';
import * as columnService from 'core/column/column.service';
import PipeUnit from 'core/pipe/units/pipe.unit';

export default class HeadView extends View {
	constructor(model, service, tagName) {
		super(model);

		this.tagName = tagName;
		this.rows = [];

		this.drop = new Command({
			canExecute: e => {
				if (e.source && e.source.key === tagName) {
					const map = columnService.map(model.data().columns);
					return map.hasOwnProperty(e.target.value);
				}

				return false;
			},
			execute: e => {
				const view = model.view;
				const columnRows = view().columns;
				for (let columns of columnRows) {
					const targetIndex = columns.findIndex(c => c.model.key === e.target.value);
					const sourceIndex = columns.findIndex(c => c.model.key === e.source.value);
					if (targetIndex >= 0 && sourceIndex >= 0) {
						const sourceColumn = columns[sourceIndex].model;
						const targetColumn = columns[targetIndex].model;
						const indexMap = Array.from(model.columnList().index);
						indexMap.splice(sourceColumn.index, 1);
						indexMap.splice(targetColumn.index, 0, sourceColumn.key);
						model.columnList({index: indexMap});

						service.invalidate(
							'reorder', {
								target: targetIndex,
								source: sourceIndex
							},
							PipeUnit.column
						);
					}
				}
			}
		});

		this.drag = new Command({
			canExecute: e => {
				if (e.source.key === tagName) {
					const map = columnService.map(model.data().columns);
					return map.hasOwnProperty(e.source.value) && map[e.source.value].canMove !== false;
				}

				return false;
			}
		});

		this.resize = new Command({
			canExecute: e => {
				if (e.source.key === tagName) {
					const columns = columnService.lineView(model.view().columns).map(v => v.model);
					const map = columnService.map(columns);
					return map.hasOwnProperty(e.source.value) && map[e.source.value].canResize !== false;
				}

				return false;
			}
		});

		model.viewChanged.watch(() => this.invalidate(model));
	}

	transfer(cell) {
		return {
			key: this.tagName,
			value: cell.column.key
		};
	}

	invalidate(model) {
		Log.info('view.head', 'invalidate');

		const columns = model.view().columns;
		this.rows = columns;
	}
}<commit_msg>If canMove = false header is not droppable<commit_after>import View from 'core/view/view';
import Log from 'core/infrastructure/log';
import Command from 'core/infrastructure/command';
import * as columnService from 'core/column/column.service';
import PipeUnit from 'core/pipe/units/pipe.unit';

export default class HeadView extends View {
	constructor(model, service, tagName) {
		super(model);

		this.tagName = tagName;
		this.rows = [];

		this.drop = new Command({
			canExecute: e => {
				if (e.source && e.source.key === tagName) {
					const key = e.target.value;
					const map = columnService.map(model.data().columns);
					return map.hasOwnProperty(key) && map[key].canMove;
				}

				return false;
			},
			execute: e => {
				const view = model.view;
				const columnRows = view().columns;
				for (let columns of columnRows) {
					const targetIndex = columns.findIndex(c => c.model.key === e.target.value);
					const sourceIndex = columns.findIndex(c => c.model.key === e.source.value);
					if (targetIndex >= 0 && sourceIndex >= 0) {
						const sourceColumn = columns[sourceIndex].model;
						const targetColumn = columns[targetIndex].model;
						const indexMap = Array.from(model.columnList().index);
						indexMap.splice(sourceColumn.index, 1);
						indexMap.splice(targetColumn.index, 0, sourceColumn.key);
						model.columnList({index: indexMap});

						service.invalidate(
							'reorder', {
								target: targetIndex,
								source: sourceIndex
							},
							PipeUnit.column
						);
					}
				}
			}
		});

		this.drag = new Command({
			canExecute: e => {
				if (e.source.key === tagName) {
					const map = columnService.map(model.data().columns);
					return map.hasOwnProperty(e.source.value) && map[e.source.value].canMove !== false;
				}

				return false;
			}
		});

		this.resize = new Command({
			canExecute: e => {
				if (e.source.key === tagName) {
					const columns = columnService.lineView(model.view().columns).map(v => v.model);
					const map = columnService.map(columns);
					return map.hasOwnProperty(e.source.value) && map[e.source.value].canResize !== false;
				}

				return false;
			}
		});

		model.viewChanged.watch(() => this.invalidate(model));
	}

	transfer(cell) {
		return {
			key: this.tagName,
			value: cell.column.key
		};
	}

	invalidate(model) {
		Log.info('view.head', 'invalidate');

		const columns = model.view().columns;
		this.rows = columns;
	}
}<|endoftext|>