<commit_before>import Ember from 'ember';
var Utils = require('asNEAT/utils')['default'];

export default Ember.Component.extend({
  tagName: 'span',

  // parameters
  note: "a4",
  hotkey: "q",
  colemakHotkey: "q",
  instrumentNetwork: null,
  hotkeyLayout: "colemakHotkey",
  sustaining: false,

  releaseHandler: null,
  keyIsDown: false,

  activeHotkey: function() {
    var hotkeyAccesor = this.get('hotkeyLayout');
    return this.get(hotkeyAccesor);
  }.property('hotkeyLayout'),

  activeHotkeyKeyCode: function() {
    var hotkey = this.get('activeHotkey');

    // special character cases
    if (hotkey === ";")
      hotkey = 186;
    else if (hotkey === "'")
      hotkey = 222;
    else if (hotkey === "]")
      hotkey = 221;
    else
      hotkey = hotkey.toUpperCase().charCodeAt();

    return hotkey;
  }.property('activeHotkey'),

  isPlaying: function() {
    return typeof this.get('releaseHandler') === 'function';
  }.property('releaseHandler'),

  sustainingChange: function() {
    var sustaining = this.get('sustaining'),
        keyIsDown = this.get('keyIsDown');
    if (!sustaining && !keyIsDown)
      this.turnOffInstrument();
  }.observes('sustaining'),

  onkeyDownHandler: null,
  onkeyUpHandler: null,
  setupKeyEvents: function() {
    var self = this;
    var onkeyDownHandler = function(e) {
      var hotkey = self.get('activeHotkeyKeyCode');
      if(e.keyCode === hotkey) {
        self.set('keyIsDown', true);
        if (!self.get('isPlaying'))
          self.playNote();
      }
    };
    var onkeyUpHandler = function(e) {
      var hotkey = self.get('activeHotkeyKeyCode');
      if(e.keyCode === hotkey) {
        self.set('keyIsDown', false);
        self.tryReleaseNote();
      }
    };
    this.set('onkeyDownHandler', onkeyDownHandler);
    this.set('onkeyUpHandler', onkeyUpHandler);
    // setting up events from document because we can't
    // get focus on multiple piano-keys at once for key events
    // to fire correctly
    $(document).keydown(onkeyDownHandler);
    $(document).keyup(onkeyUpHandler);

  }.on('init'),

  playNote: function() {
    var instrumentNetwork = this.get('instrumentNetwork'),
        note = this.get('note'),
        releaseHandler = this.get('releaseHandler');

    // make sure to release any previous notes playing
    if (typeof releaseHandler === "function")
      releaseHandler();

    if (!instrumentNetwork)
      return;

    var steps = Utils.stepsFromRootNote(note);
    Utils.log('Playing note: '+note+' ('+steps+')');

    var noteOscillators = instrumentNetwork.getNoteOscillatorNodes();
    _.forEach(noteOscillators, function(node) {
      node.stepFromRootNote = steps;
    });

    releaseHandler = instrumentNetwork.playHold();
    this.set('releaseHandler', releaseHandler);
  },

  tryReleaseNote: function() {
    if (!this.get('sustaining'))
      this.turnOffInstrument();
  },

  turnOffInstrument: function() {
    var releaseHandler = this.get('releaseHandler');
    if (typeof releaseHandler === "function") {
      releaseHandler();
      this.set('releaseHandler', null);
    }
  },

  mouseDown: function() {
    this.set('keyIsDown', true);
    this.playNote();
  },

  mouseUp: function() {
    this.set('keyIsDown', false);
    this.tryReleaseNote();
  },

  willDestroy: function() {
    this._super();
    $(document).off('keydown', this.get('onkeyDownHandler'));
    $(document).off('keyup', this.get('onkeyUpHandler'));
  }
});
<commit_msg>don't play virtual keyboard with hotkeys when an input field has focus<commit_after>import Ember from 'ember';
var Utils = require('asNEAT/utils')['default'];

export default Ember.Component.extend({
  tagName: 'span',

  // parameters
  note: "a4",
  hotkey: "q",
  colemakHotkey: "q",
  instrumentNetwork: null,
  hotkeyLayout: "colemakHotkey",
  sustaining: false,

  releaseHandler: null,
  keyIsDown: false,

  activeHotkey: function() {
    var hotkeyAccesor = this.get('hotkeyLayout');
    return this.get(hotkeyAccesor);
  }.property('hotkeyLayout'),

  activeHotkeyKeyCode: function() {
    var hotkey = this.get('activeHotkey');

    // special character cases
    if (hotkey === ";")
      hotkey = 186;
    else if (hotkey === "'")
      hotkey = 222;
    else if (hotkey === "]")
      hotkey = 221;
    else
      hotkey = hotkey.toUpperCase().charCodeAt();

    return hotkey;
  }.property('activeHotkey'),

  isPlaying: function() {
    return typeof this.get('releaseHandler') === 'function';
  }.property('releaseHandler'),

  sustainingChange: function() {
    var sustaining = this.get('sustaining'),
        keyIsDown = this.get('keyIsDown');
    if (!sustaining && !keyIsDown)
      this.turnOffInstrument();
  }.observes('sustaining'),

  onkeyDownHandler: null,
  onkeyUpHandler: null,
  setupKeyEvents: function() {
    var self = this;
    var onkeyDownHandler = function(e) {
      var hotkey = self.get('activeHotkeyKeyCode');
      if(e.keyCode === hotkey && e.target.tagName !== 'INPUT') {
        self.set('keyIsDown', true);
        if (!self.get('isPlaying'))
          self.playNote();
      }
    };
    var onkeyUpHandler = function(e) {
      var hotkey = self.get('activeHotkeyKeyCode');
      if(e.keyCode === hotkey) {
        self.set('keyIsDown', false);
        self.tryReleaseNote();
      }
    };
    this.set('onkeyDownHandler', onkeyDownHandler);
    this.set('onkeyUpHandler', onkeyUpHandler);
    // setting up events from document because we can't
    // get focus on multiple piano-keys at once for key events
    // to fire correctly
    $(document).keydown(onkeyDownHandler);
    $(document).keyup(onkeyUpHandler);

  }.on('init'),

  playNote: function() {
    var instrumentNetwork = this.get('instrumentNetwork'),
        note = this.get('note'),
        releaseHandler = this.get('releaseHandler');

    // make sure to release any previous notes playing
    if (typeof releaseHandler === "function")
      releaseHandler();

    if (!instrumentNetwork)
      return;

    var steps = Utils.stepsFromRootNote(note);
    Utils.log('Playing note: '+note+' ('+steps+')');

    var noteOscillators = instrumentNetwork.getNoteOscillatorNodes();
    _.forEach(noteOscillators, function(node) {
      node.stepFromRootNote = steps;
    });

    releaseHandler = instrumentNetwork.playHold();
    this.set('releaseHandler', releaseHandler);
  },

  tryReleaseNote: function() {
    if (!this.get('sustaining'))
      this.turnOffInstrument();
  },

  turnOffInstrument: function() {
    var releaseHandler = this.get('releaseHandler');
    if (typeof releaseHandler === "function") {
      releaseHandler();
      this.set('releaseHandler', null);
    }
  },

  mouseDown: function() {
    this.set('keyIsDown', true);
    this.playNote();
  },

  mouseUp: function() {
    this.set('keyIsDown', false);
    this.tryReleaseNote();
  },

  willDestroy: function() {
    this._super();
    $(document).off('keydown', this.get('onkeyDownHandler'));
    $(document).off('keyup', this.get('onkeyUpHandler'));
  }
});
<|endoftext|>


<commit_before>// Unobtrusive example - http://wowkhmer.com/2011/09/19/unobtrusive-ajax-with-rails-31/
//
// TODO:
//
// 1. Закрывать форму комментирования, если открыта новая.

$(function() {
    $('form.alice-new_form')
      .live('ajax:success', function(evt, data, status, xhr){
              t = $(this);
              commentable = t.data('commentable');
              b = t.find('button'); // input[type=submit]
              remove_disabled(t);

              var tp = t.parent();
              if (tp.hasClass('alice-reply_form-container')) {
                tp.hide('fast');
                a = $("#alice-comment-reply_link-"+commentable);
                a.text(a.data('hidden-text') || 'комментировать');
              }

              b = $("#alice-replies_of-"+commentable);

              if (t.data('new-reply-placement')=='prepend') {
                b.prepend(JSON.parse(data)['html']);
              } else {
                b.append(JSON.parse(data)['html']);
              }

              counter = $('#alice-comments-counter');
              counter.html((parseInt(counter.text())+1).toString());
            })
      .live('ajax:error', function(data, xhr, status){
             if (xhr.responseText!=''){
               alert(xhr.responseText);
             }else{
               alert("Что-то пошло не так");
             }
             if(xhr.status==406){
                remove_disabled($(this));
              }
            })
      .live('ajax:beforeSend', function(evt, data, status, xhr){
              t = $(this);
              t.find('textarea').attr('disabled','disabled');
              b = t.find('button'); // input[type=submit]
              b.attr('disabled', 'disabled');
              b.data('hidden-text', b.text());
              // b = t.find('button.alice-send-button');
              b.text('Отправляю..');
            });
    $('.alice-comment-reply_link').live('click', function(event){
              t = $(this);
              commentable = t.data('commentable');
              form = $("#alice-form-container-" + commentable)
              form.toggle();
              if (form.is(':visible')) {
                t.text(t.data('visible-text') || 'скрыть');
              } else {
                t.text(t.data('hidden-text') || 'комментировать');
              }
              return false;
        });

      function remove_disabled(form){
        form[0].reset();
        form.find('textarea').removeAttr('disabled');
        form.find('button').removeAttr('disabled');
        form.find('button').text(b.data('hidden-text') || 'комментировать');
        if (form.find('button').text() == 'Отправляем...') {
          form.find('button').text('Отправить');
        }
      }

    $('li.alice-comment a.comment-edit-link').live('click', function(event){
      var commentContainer = $(this).parent().parent().parent().parent();

      $(commentContainer.find("div.alice-comment-content")[0]).hide();
      $(commentContainer.find("div.alice-comment-edit")[0]).show();
      $(commentContainer.find("form.commentor-edit-form")[0]).focus();

      return false;
    });

    $('li.alice-comment form.alice-edit-form button.alice-cancel-button').live('click', function(event){
      var $this = $(this);

      var commentContainer = $($this.parents("li.alice-comment")[0]);

      commentContainer.find("div.alice-comment-content").show();
      commentContainer.find("div.alice-comment-edit").hide();

      return false;
    });

    $('form.alice-edit-form').live('ajax:success', function(evt, data, status, xhr){
      $this = $(this);
      //С bootstrap2 вроде не надо
      //$this.twipsy('hide'); // TODO Проверять на наличие twipsy

      var commentContainer = $($this.parents(".alice-comment-div")[0]);
      commentContainer.html(JSON.parse(data)['html']);
    });

    $('a.comment-remove-link').live('ajax:success', function(evt, data, status, xhr){
      $this = $(this);
      //С bootstrap2 вроде не надо
      // $this.twipsy('hide'); // TODO Проверять на наличие twipsy

      var commentContainer = $($this.parents(".alice-comment-div")[0]);
      commentContainer.html(JSON.parse(data['html']));

      return false;
    });

});
<commit_msg>Фикс айаксовых комментариев<commit_after>// Unobtrusive example - http://wowkhmer.com/2011/09/19/unobtrusive-ajax-with-rails-31/
//
// TODO:
//
// 1. Закрывать форму комментирования, если открыта новая.

$(function() {
    $('form.alice-new_form')
      .live('ajax:success', function(evt, data, status, xhr){
              t = $(this);
              commentable = t.data('commentable');
              b = t.find('button'); // input[type=submit]
              remove_disabled(t);

              var tp = t.parent();
              if (tp.hasClass('alice-reply_form-container')) {
                tp.hide('fast');
                a = $("#alice-comment-reply_link-"+commentable);
                a.text(a.data('hidden-text') || 'комментировать');
              }

              b = $("#alice-replies_of-"+commentable);

              if (t.data('new-reply-placement')=='prepend') {
                b.prepend(JSON.parse(data)['html']);
              } else {
                b.append(JSON.parse(data)['html']);
              }

              counter = $('#alice-comments-counter');
              counter.html((parseInt(counter.text())+1).toString());
            })
      .live('ajax:error', function(data, xhr, status){
             if (xhr.responseText!=''){
               alert(xhr.responseText);
             }else{
               alert("Что-то пошло не так");
             }
             if(xhr.status==406){
                remove_disabled($(this));
              }
            })
      .live('ajax:beforeSend', function(evt, data, status, xhr){
              t = $(this);
              t.find('textarea').attr('disabled','disabled');
              b = t.find('button'); // input[type=submit]
              b.attr('disabled', 'disabled');
              b.data('hidden-text', b.text());
            });
    $('.alice-comment-reply_link').live('click', function(event){
              t = $(this);
              commentable = t.data('commentable');
              form = $("#alice-form-container-" + commentable)
              form.toggle();
              if (form.is(':visible')) {
                t.text(t.data('visible-text') || 'скрыть');
              } else {
                t.text(t.data('hidden-text') || 'комментировать');
              }
              return false;
        });

      function remove_disabled(form){
        form[0].reset();
        form.find('textarea').removeAttr('disabled');
        form.find('button').removeAttr('disabled');
        form.find('button').text(b.data('hidden-text') || 'комментировать');
        if (form.find('button').text() == 'Отправляем...') {
          form.find('button').text('Отправить');
        }
      }

    $('li.alice-comment a.comment-edit-link').live('click', function(event){
      var commentContainer = $(this).parent().parent().parent().parent();

      $(commentContainer.find("div.alice-comment-content")[0]).hide();
      $(commentContainer.find("div.alice-comment-edit")[0]).show();
      $(commentContainer.find("form.commentor-edit-form")[0]).focus();

      return false;
    });

    $('li.alice-comment form.alice-edit-form button.alice-cancel-button').live('click', function(event){
      var $this = $(this);

      var commentContainer = $($this.parents("li.alice-comment")[0]);

      commentContainer.find("div.alice-comment-content").show();
      commentContainer.find("div.alice-comment-edit").hide();

      return false;
    });

    $('form.alice-edit-form').live('ajax:success', function(evt, data, status, xhr){
      $this = $(this);
      //С bootstrap2 вроде не надо
      //$this.twipsy('hide'); // TODO Проверять на наличие twipsy

      var commentContainer = $($this.parents(".alice-comment-div")[0]);
      commentContainer.html(JSON.parse(data)['html']);
    });

    $('a.comment-remove-link').live('ajax:success', function(evt, data, status, xhr){
      $this = $(this);
      //С bootstrap2 вроде не надо
      // $this.twipsy('hide'); // TODO Проверять на наличие twipsy

      var commentContainer = $($this.parents(".alice-comment-div")[0]);
      commentContainer.html(JSON.parse(data['html']));

      return false;
    });

});
<|endoftext|>


<commit_before>// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
//


<commit_before>var INTERVAL = 60000; // runs every minute
from_dropdown = null;

// TODO what should it do?
// * it should update the "inline timer" regularly
// * in some conditions:
// * only if the task has been created already
// *
var $minutes,
    $hours;

// it should pause the timer and then hide itself to show the play button
var update_displayed_time = function() {
    var current_minutes = parseInt($minutes.text(), 10),
        current_hours   = parseInt($hours.text(), 10);

    current_minutes++;

    if (current_minutes > 59) {
        current_minutes = 0;
        current_hours++;
    }

    $minutes.text(current_minutes);
    $hours.text(current_hours);
};

jQuery(document).ready(function($) {
    // timers
    var inline = $('#timer-bar-elapsed'),
        $timer;

    // timer spans
    $minutes = $('#minutes > .timer-val');
    $hours   = $('#hours > .timer-val');

    // buttons
    var $pause_button = $('#pause-btn'),
        $play_button  = $('#play-btn'),
        $pin_button   = $('#pin-btn');

    var $save_button  = $('#save-btn'),
        $dropdown = $('#save-dropdown'),
        $li_elapsed = $('#worklog-elapsed'),
        $li_custom = $('#worklog-custom'),
        $li_none = $('#worklog-none'),
        $dialog = $('#worktime_container'),
        $form = $('#taskform');

    // init timer
    $timer = $.timer(function() {
      update_displayed_time();
    });

    // bindings
    $pause_button.bind('click', function() {
        $timer.pause();
        $(this).hide();
        $play_button.show();
    });

    // it should restart the timer and then hide itself to show the pause button
    $play_button.bind('click', function() {
        $timer.play();
        $(this).hide();
        $pause_button.show();
    });

    // initial timer values
    $minutes.text('00');
    $hours.text('00');

    // make it look like a submit button
    $save_button.addClass("ui-button ui-widget ui-state-default ui-corner-all");

    $form.submit(function(event) {
        var elapsed = $('#timer-bar-elapsed').text();
        $('#worklog-elapsed > a').text(elapsed);
        $dropdown.toggle('blind');

        // prevent submit
        if (!from_dropdown) {
            event.preventDefault();
            event.stopPropagation();
        }
        from_dropdown = false;
    });

    // set up elements

    var buttons = [
        {
            text: 'Save',
            click: function() {
                $('input', $(this)).clone().appendTo($form);
                from_dropdown = true;
                $form.submit();
                $dropdown.toggle('blind');
                $(this).dialog('close');
            }
        },
        {
            text: 'Cancel',
            click: function() { $(this).dialog('close'); }
        }
    ];

    //set up dialog
    $dialog.dialog({
        autoOpen: false,
        buttons: buttons,
        draggable: false,
        title: 'Crete work log'
    });

    $li_elapsed.click(function() {
        var elapsed = $('#timer-bar-elapsed').text(),
            $input = $('div[role=dialog] input#work_log_duration'),
            $clone = $input.clone();

        remove_residue();
        $clone.val($.trim(elapsed));
        $clone.appendTo($form);

        from_dropdown = true;
        $form.submit();
        $dropdown.toggle('blind');
    });
    $li_custom.click(function() {
        remove_residue();
        $dialog.dialog('open');
    });
    $li_none.click(function() {
        remove_residue();
        from_dropdown = true;
        $form.submit();
        $dropdown.toggle('blind');
    });

    var remove_residue = function() {
        var $residue = $('#taskform input[name^=work_log]');
        $residue.remove();
    }

    // TODO when should it start?
    $timer.set({ time: INTERVAL, autostart: true });
});
<commit_msg>don't toggle dropdown twice<commit_after>var INTERVAL = 60000; // runs every minute
from_dropdown = null;

// TODO what should it do?
// * it should update the "inline timer" regularly
// * in some conditions:
// * only if the task has been created already
// *
var $minutes,
    $hours;

// it should pause the timer and then hide itself to show the play button
var update_displayed_time = function() {
    var current_minutes = parseInt($minutes.text(), 10),
        current_hours   = parseInt($hours.text(), 10);

    current_minutes++;

    if (current_minutes > 59) {
        current_minutes = 0;
        current_hours++;
    }

    $minutes.text(current_minutes);
    $hours.text(current_hours);
};

jQuery(document).ready(function($) {
    // timers
    var inline = $('#timer-bar-elapsed'),
        $timer;

    // timer spans
    $minutes = $('#minutes > .timer-val');
    $hours   = $('#hours > .timer-val');

    // buttons
    var $pause_button = $('#pause-btn'),
        $play_button  = $('#play-btn'),
        $pin_button   = $('#pin-btn');

    var $save_button  = $('#save-btn'),
        $dropdown = $('#save-dropdown'),
        $li_elapsed = $('#worklog-elapsed'),
        $li_custom = $('#worklog-custom'),
        $li_none = $('#worklog-none'),
        $dialog = $('#worktime_container'),
        $form = $('#taskform');

    // init timer
    $timer = $.timer(function() {
      update_displayed_time();
    });

    // bindings
    $pause_button.bind('click', function() {
        $timer.pause();
        $(this).hide();
        $play_button.show();
    });

    // it should restart the timer and then hide itself to show the pause button
    $play_button.bind('click', function() {
        $timer.play();
        $(this).hide();
        $pause_button.show();
    });

    // initial timer values
    $minutes.text('00');
    $hours.text('00');

    // make it look like a submit button
    $save_button.addClass("ui-button ui-widget ui-state-default ui-corner-all");

    $form.submit(function(event) {
        var elapsed = $('#timer-bar-elapsed').text();
        $('#worklog-elapsed > a').text(elapsed);
        $dropdown.toggle('blind');

        // prevent submit
        if (!from_dropdown) {
            event.preventDefault();
            event.stopPropagation();
        }
        from_dropdown = false;
    });

    // set up elements

    var buttons = [
        {
            text: 'Save',
            click: function() {
                $('input', $(this)).clone().appendTo($form);
                from_dropdown = true;
                $form.submit();
                $(this).dialog('close');
            }
        },
        {
            text: 'Cancel',
            click: function() { $(this).dialog('close'); }
        }
    ];

    //set up dialog
    $dialog.dialog({
        autoOpen: false,
        buttons: buttons,
        draggable: false,
        title: 'Crete work log'
    });

    $li_elapsed.click(function() {
        var elapsed = $('#timer-bar-elapsed').text(),
            $input = $('div[role=dialog] input#work_log_duration'),
            $clone = $input.clone();

        remove_residue();
        $clone.val($.trim(elapsed));
        $clone.appendTo($form);

        from_dropdown = true;
        $form.submit();
        $dropdown.toggle('blind');
    });
    $li_custom.click(function() {
        remove_residue();
        $dialog.dialog('open');
    });
    $li_none.click(function() {
        remove_residue();
        from_dropdown = true;
        $form.submit();
        $dropdown.toggle('blind');
    });

    var remove_residue = function() {
        var $residue = $('#taskform input[name^=work_log]');
        $residue.remove();
    }

    // TODO when should it start?
    $timer.set({ time: INTERVAL, autostart: true });
});
<|endoftext|>


<commit_before>define([
  'extensions/views/view',
  'd3loader!',
  './xaxis',
  './yaxis',
  './yaxisRight',
  './line',
  './stack',
  './hover',
  './tooltip',
  './missing-data'
],
function (View, d3, XAxis, YAxis, YAxisRight, Line, Stack, Hover, Tooltip, MissingData) {

  var Graph = View.extend({

    d3: d3,

    valueAttr: '_count',

    minYDomainExtent: 6,
    numYTicks: 7,
    innerElBorderOffset: 2,

    sharedComponents: {
      xaxis: XAxis,
      yaxis: YAxis,
      yaxisRight: YAxisRight,
      line: Line,
      stack: Stack,
      callout: Tooltip,
      hover: Hover,
      tooltip: Tooltip
    },

    initialize: function (options) {
      View.prototype.initialize.apply(this, arguments);

      var collection = this.collection = options.collection;
      this.listenTo(collection, 'reset add remove sync', function () {
        this.getAxisPeriod();
        this.render();
      });

      this.prepareGraphArea();

      this.scales = {};
      this.margin = {};

      // initialize graph components
      this.componentInstances = [];
      var defaultComponentOptions = this.getDefaultComponentOptions();
      _.each(this.prop('components'), function (definition) {
        var options = _.extend({}, defaultComponentOptions, definition.options);
        this.componentInstances.push(new definition.view(options));
      }, this);

      if (isClient) {
        $(window).on('resize.' + this.cid, _.bind(this.render, this));
      }
    },

    /**
     * Defines default options that get passed to all graph components.
     * This object will be extended with component-specific options.
     * @returns {Object} Default options that get passed to components
     */
    getDefaultComponentOptions: function () {
      return {
        graph: this,
        collection: this.collection,
        model: this.model,
        el: this.figure,
        svg: this.svg,
        wrapper: this.wrapper,
        margin: this.margin,
        scales: this.scales
      };
    },

    showLineLabels: function () {
      return this.model && this.model.get('show-line-labels');
    },

    prepareGraphArea: function () {
      var figure = this.figure = $('
').addClass('graph');
      if (this.showLineLabels()) {
        figure.addClass('graph-with-labels');
      }
      figure.appendTo(this.$el);

      var graphWrapper = this.graphWrapper = $('

');
      graphWrapper.appendTo(figure);

      this.innerEl = $('

');
      this.innerEl.appendTo(graphWrapper);

      var svg = this.svg = this.d3.select(graphWrapper[0]).append('svg');

      // Apply attributes to SVGs so that they're ignored by screenreaders.
      // The WAI-ARIA 1.0 spec says that authors MAY use aria-hidden only
      // if they're hiding content to improve the experience for users
      // of assistive technologies.
      svg.attr('role', 'presentation');
      svg.attr('aria-hidden', 'true');

      this.wrapper = svg.append('g')
        .classed('wrapper', true);
    },

    /**
     * Calculates current factor between size in displayed pixels and logical
     * size.
     */
    scaleFactor: function () {
      return $(this.svg.node()).width() / this.width;
    },

    modelToDate: function (model) {
      var prop = '_start_at';
      var period = this.axisperiod || this.getAxisPeriod();
      if (period === 'hour') {
        prop = '_timestamp';
      } else if (period === 'week' || period === 'quarter') {
        prop = '_end_at';
      }
      return model.get(prop);
    },

    getXPos: function (modelIndex) {
      var model = this.collection.at(modelIndex);
      return model ? this.modelToDate(model) : null;
    },

    getYPos: function (modelIndex, valueAttr) {
      valueAttr = valueAttr || this.valueAttr;
      var model = this.collection.at(modelIndex);
      if (model) {
        return model.get(valueAttr);
      }
      return null;
    },

    getY0Pos: function () {
      return 0;
    },

    calcXScale: function () {
      var start = this.modelToDate(this.collection.first()).toDate(),
          end = this.modelToDate(this.collection.last()).toDate();

      return this.d3.time.scale()
              .domain([start, end])
              .range([0, this.innerWidth]);
    },

    calcYScale: function () {
      var max = this.maxValue();
      var yScale;
      if (this.formatOptions && this.formatOptions.type === 'duration') {
        yScale = d3.time.scale();
        if (max) {
          yScale.domain([0, Math.max(max, this.minYDomainExtent)]);
          var niceScale = d3.time.second;
          if (max > 120000) {
            niceScale = d3.time.min;
          }
          yScale.nice(niceScale);
        }
      } else {
        yScale = this.d3.scale.linear();
        if (max) {
          var tickValues = this.calculateLinearTicks([this.minValue(), Math.max(max, this.minYDomainExtent)], this.numYTicks);
          yScale.domain(tickValues.extent);
          yScale.tickValueList = tickValues.values;
        }
      }
      yScale.rangeRound([this.innerHeight, 0]);
      return yScale;
    },

    maxValue: function () {
      return this.collection.max(this.valueAttr);
    },

    minValue: function () {
      return 0;
    },

    hasData: function () {
      return this.collection.defined(this.valueAttr).length > 0;
    },

    getPeriod: function () {
      return this.collection.getPeriod() || 'week';
    },

    getAxisPeriod: function () {
      var period = (this.model && this.model.get('axis-period')) || this.getPeriod();
      var periods = ['hour', 'day', 'week', 'month', 'quarter'];
      if (this.scales.x) {
        var domain = this.scales.x.domain();
        var start = this.getMoment(domain[0]);
        var end = this.getMoment(domain[1]);
        var index = periods.indexOf(period);
        while (index > 0 && Math.abs(start.diff(end, period)) > 15 && index < periods.length) {
          period = periods[index];
          index++;
        }
      }
      this.axisperiod = period;
      return period;
    },

    /**
     * Returns an object describing evenly spaced, nice tick values given an extent and a minimum tick count.
     * The returned object will include the values, extent and step of the ticks.
     * The extent may be extended to include the next nice tick value.
     *
     * @param extent
     * @param minimumTickCount
     * @return {Object}
     */
    calculateLinearTicks: function (extent, minimumTickCount) {

      if (extent[0] >= extent[1]) {
        throw new Error('Upper bound must be larger than lower.');
      }
      var targetTickCount = (minimumTickCount === 1) ? minimumTickCount : minimumTickCount - 1,
          span = extent[1] - extent[0],
          step = Math.pow(10, Math.floor(Math.log(span / targetTickCount) / Math.LN10)),
          err = targetTickCount / span * step;

      // Filter ticks to get closer to the desired count.
      if (err <= 0.15) {
        step *= 10;
      } else if (err <= 0.35) {
        step *= 5;
      } else if (err <= 0.75) {
        step *= 2;
      }

      // Round start and stop values to step interval.
      var first = Math.floor(extent[0] / step) * step,
          last = Math.ceil(extent[1] / step) * step,
          lastInclusive = last + step / 2;

      return {
        values: _.range(first, lastInclusive, step),
        extent: [first, last],
        step: step
      };
    },

    pxToValue: function (cssVal) {
      if (!_.isString(cssVal)) {
        return null;
      }
      var matches = cssVal.match(/([0-9\.]+)px/);
      return matches ? parseFloat(matches[1]) : null;
    },

    resize: function () {
      var $svg = $(this.svg.node());
      $svg.attr('style', '');
      var width = this.width = $svg.parent().width(),
          height;

      // when both max-width and max-height are defined, scale graph according
      // to this aspect ratio
      var maxWidth = this.pxToValue($svg.css('max-width'));
      var maxHeight = this.pxToValue($svg.css('max-height'));
      var minHeight = this.pxToValue($svg.css('min-height'));

      if (_.isNumber(maxWidth) && _.isNumber(maxHeight)) {
        var aspectRatio = maxWidth / maxHeight;
        height = width / aspectRatio;
        if (_.isNumber(minHeight)) {
          height = Math.max(height, minHeight);
        }
      } else {
        height = $svg.height();
      }
      this.height = height;

      // configure SVG for automatic resize
      this.svg.attr({
        width: '100%',
        height: '100%',
        viewBox: '0 0 ' + width + ' ' + height,
        style: 'max-width:' + width + 'px; max-height:' + height + 'px; display:block;'
      });
      $svg.height(height);

      var innerEl = this.innerEl;
      this.margin.top = innerEl.position().top - this.innerElBorderOffset;
      this.margin.left = innerEl.position().left;

      this.innerWidth = innerEl.outerWidth();
      this.innerHeight = innerEl.outerHeight();

      this.wrapper.attr('transform', 'translate(' + this.margin.left + ', ' +  this.margin.top + ')');
    },

    /**
     * The linelabel figcaption is positioned on top of the graph
     * at small screen sizes using position static.
     */
    lineLabelOnTop: function () {
      return this.$el.find('figcaption').css('position') === 'static';
    },

    /**
     * Hide callout during resize if present. Works around bug in iOS Webkit
     * that incorrectly calculates height of inner element.
     */
    resizeWithCalloutHidden: function () {
      var callout = this.$el.find('.callout');
      var calloutHidden = callout.hasClass('performance-hidden');
      callout.addClass('performance-hidden');

      this.resize();

      if (!calloutHidden) {
        callout.removeClass('performance-hidden');
      }
    },

    /**
     * Applies current configuration, then renders components in defined order
     */
    render: function () {
      if (this.missingData) {
        this.figure.children().show();
        this.missingData.remove();
        delete this.missingData;
      }
      if (this.collection.isEmpty()) {
        this.figure.children().hide();
        var $container = $('
').appendTo(this.figure);
        this.missingData = new MissingData({
          el: $container
        });
        this.missingData.render();
        return;
      }

      View.prototype.render.apply(this, arguments);

      if (this.collection.options) {
        this.currency = this.collection.options.currency;
      }

      this.resizeWithCalloutHidden();

      this.scales.x = this.calcXScale();
      this.scales.y = this.calcYScale();

      _.each(this.componentInstances, function (component) {
        component.render();
      }, this);
    },

    remove: function () {
      if (this.table) {
        this.table.remove();
      }
      _.invoke(this.componentInstances, 'remove');
      this.componentInstances = [];
      if (isClient) {
        $(window).off('resize.' + this.cid);
      }
      return View.prototype.remove.apply(this, arguments);
    },

    isOneHundredPercent: function () {
      return false;
    }

  });

  return Graph;
});
<commit_msg>Remove `isClient` checks from client-only code<commit_after>define([
  'extensions/views/view',
  'd3loader!',
  './xaxis',
  './yaxis',
  './yaxisRight',
  './line',
  './stack',
  './hover',
  './tooltip',
  './missing-data'
],
function (View, d3, XAxis, YAxis, YAxisRight, Line, Stack, Hover, Tooltip, MissingData) {

  var Graph = View.extend({

    d3: d3,

    valueAttr: '_count',

    minYDomainExtent: 6,
    numYTicks: 7,
    innerElBorderOffset: 2,

    sharedComponents: {
      xaxis: XAxis,
      yaxis: YAxis,
      yaxisRight: YAxisRight,
      line: Line,
      stack: Stack,
      callout: Tooltip,
      hover: Hover,
      tooltip: Tooltip
    },

    initialize: function (options) {
      View.prototype.initialize.apply(this, arguments);

      var collection = this.collection = options.collection;
      this.listenTo(collection, 'reset add remove sync', function () {
        this.getAxisPeriod();
        this.render();
      });

      this.prepareGraphArea();

      this.scales = {};
      this.margin = {};

      // initialize graph components
      this.componentInstances = [];
      var defaultComponentOptions = this.getDefaultComponentOptions();
      _.each(this.prop('components'), function (definition) {
        var options = _.extend({}, defaultComponentOptions, definition.options);
        this.componentInstances.push(new definition.view(options));
      }, this);

      $(window).on('resize.' + this.cid, _.bind(this.render, this));
    },

    /**
     * Defines default options that get passed to all graph components.
     * This object will be extended with component-specific options.
     * @returns {Object} Default options that get passed to components
     */
    getDefaultComponentOptions: function () {
      return {
        graph: this,
        collection: this.collection,
        model: this.model,
        el: this.figure,
        svg: this.svg,
        wrapper: this.wrapper,
        margin: this.margin,
        scales: this.scales
      };
    },

    showLineLabels: function () {
      return this.model && this.model.get('show-line-labels');
    },

    prepareGraphArea: function () {
      var figure = this.figure = $('
').addClass('graph');
      if (this.showLineLabels()) {
        figure.addClass('graph-with-labels');
      }
      figure.appendTo(this.$el);

      var graphWrapper = this.graphWrapper = $('

');
      graphWrapper.appendTo(figure);

      this.innerEl = $('

');
      this.innerEl.appendTo(graphWrapper);

      var svg = this.svg = this.d3.select(graphWrapper[0]).append('svg');

      // Apply attributes to SVGs so that they're ignored by screenreaders.
      // The WAI-ARIA 1.0 spec says that authors MAY use aria-hidden only
      // if they're hiding content to improve the experience for users
      // of assistive technologies.
      svg.attr('role', 'presentation');
      svg.attr('aria-hidden', 'true');

      this.wrapper = svg.append('g')
        .classed('wrapper', true);
    },

    /**
     * Calculates current factor between size in displayed pixels and logical
     * size.
     */
    scaleFactor: function () {
      return $(this.svg.node()).width() / this.width;
    },

    modelToDate: function (model) {
      var prop = '_start_at';
      var period = this.axisperiod || this.getAxisPeriod();
      if (period === 'hour') {
        prop = '_timestamp';
      } else if (period === 'week' || period === 'quarter') {
        prop = '_end_at';
      }
      return model.get(prop);
    },

    getXPos: function (modelIndex) {
      var model = this.collection.at(modelIndex);
      return model ? this.modelToDate(model) : null;
    },

    getYPos: function (modelIndex, valueAttr) {
      valueAttr = valueAttr || this.valueAttr;
      var model = this.collection.at(modelIndex);
      if (model) {
        return model.get(valueAttr);
      }
      return null;
    },

    getY0Pos: function () {
      return 0;
    },

    calcXScale: function () {
      var start = this.modelToDate(this.collection.first()).toDate(),
          end = this.modelToDate(this.collection.last()).toDate();

      return this.d3.time.scale()
              .domain([start, end])
              .range([0, this.innerWidth]);
    },

    calcYScale: function () {
      var max = this.maxValue();
      var yScale;
      if (this.formatOptions && this.formatOptions.type === 'duration') {
        yScale = d3.time.scale();
        if (max) {
          yScale.domain([0, Math.max(max, this.minYDomainExtent)]);
          var niceScale = d3.time.second;
          if (max > 120000) {
            niceScale = d3.time.min;
          }
          yScale.nice(niceScale);
        }
      } else {
        yScale = this.d3.scale.linear();
        if (max) {
          var tickValues = this.calculateLinearTicks([this.minValue(), Math.max(max, this.minYDomainExtent)], this.numYTicks);
          yScale.domain(tickValues.extent);
          yScale.tickValueList = tickValues.values;
        }
      }
      yScale.rangeRound([this.innerHeight, 0]);
      return yScale;
    },

    maxValue: function () {
      return this.collection.max(this.valueAttr);
    },

    minValue: function () {
      return 0;
    },

    hasData: function () {
      return this.collection.defined(this.valueAttr).length > 0;
    },

    getPeriod: function () {
      return this.collection.getPeriod() || 'week';
    },

    getAxisPeriod: function () {
      var period = (this.model && this.model.get('axis-period')) || this.getPeriod();
      var periods = ['hour', 'day', 'week', 'month', 'quarter'];
      if (this.scales.x) {
        var domain = this.scales.x.domain();
        var start = this.getMoment(domain[0]);
        var end = this.getMoment(domain[1]);
        var index = periods.indexOf(period);
        while (index > 0 && Math.abs(start.diff(end, period)) > 15 && index < periods.length) {
          period = periods[index];
          index++;
        }
      }
      this.axisperiod = period;
      return period;
    },

    /**
     * Returns an object describing evenly spaced, nice tick values given an extent and a minimum tick count.
     * The returned object will include the values, extent and step of the ticks.
     * The extent may be extended to include the next nice tick value.
     *
     * @param extent
     * @param minimumTickCount
     * @return {Object}
     */
    calculateLinearTicks: function (extent, minimumTickCount) {

      if (extent[0] >= extent[1]) {
        throw new Error('Upper bound must be larger than lower.');
      }
      var targetTickCount = (minimumTickCount === 1) ? minimumTickCount : minimumTickCount - 1,
          span = extent[1] - extent[0],
          step = Math.pow(10, Math.floor(Math.log(span / targetTickCount) / Math.LN10)),
          err = targetTickCount / span * step;

      // Filter ticks to get closer to the desired count.
      if (err <= 0.15) {
        step *= 10;
      } else if (err <= 0.35) {
        step *= 5;
      } else if (err <= 0.75) {
        step *= 2;
      }

      // Round start and stop values to step interval.
      var first = Math.floor(extent[0] / step) * step,
          last = Math.ceil(extent[1] / step) * step,
          lastInclusive = last + step / 2;

      return {
        values: _.range(first, lastInclusive, step),
        extent: [first, last],
        step: step
      };
    },

    pxToValue: function (cssVal) {
      if (!_.isString(cssVal)) {
        return null;
      }
      var matches = cssVal.match(/([0-9\.]+)px/);
      return matches ? parseFloat(matches[1]) : null;
    },

    resize: function () {
      var $svg = $(this.svg.node());
      $svg.attr('style', '');
      var width = this.width = $svg.parent().width(),
          height;

      // when both max-width and max-height are defined, scale graph according
      // to this aspect ratio
      var maxWidth = this.pxToValue($svg.css('max-width'));
      var maxHeight = this.pxToValue($svg.css('max-height'));
      var minHeight = this.pxToValue($svg.css('min-height'));

      if (_.isNumber(maxWidth) && _.isNumber(maxHeight)) {
        var aspectRatio = maxWidth / maxHeight;
        height = width / aspectRatio;
        if (_.isNumber(minHeight)) {
          height = Math.max(height, minHeight);
        }
      } else {
        height = $svg.height();
      }
      this.height = height;

      // configure SVG for automatic resize
      this.svg.attr({
        width: '100%',
        height: '100%',
        viewBox: '0 0 ' + width + ' ' + height,
        style: 'max-width:' + width + 'px; max-height:' + height + 'px; display:block;'
      });
      $svg.height(height);

      var innerEl = this.innerEl;
      this.margin.top = innerEl.position().top - this.innerElBorderOffset;
      this.margin.left = innerEl.position().left;

      this.innerWidth = innerEl.outerWidth();
      this.innerHeight = innerEl.outerHeight();

      this.wrapper.attr('transform', 'translate(' + this.margin.left + ', ' +  this.margin.top + ')');
    },

    /**
     * The linelabel figcaption is positioned on top of the graph
     * at small screen sizes using position static.
     */
    lineLabelOnTop: function () {
      return this.$el.find('figcaption').css('position') === 'static';
    },

    /**
     * Hide callout during resize if present. Works around bug in iOS Webkit
     * that incorrectly calculates height of inner element.
     */
    resizeWithCalloutHidden: function () {
      var callout = this.$el.find('.callout');
      var calloutHidden = callout.hasClass('performance-hidden');
      callout.addClass('performance-hidden');

      this.resize();

      if (!calloutHidden) {
        callout.removeClass('performance-hidden');
      }
    },

    /**
     * Applies current configuration, then renders components in defined order
     */
    render: function () {
      if (this.missingData) {
        this.figure.children().show();
        this.missingData.remove();
        delete this.missingData;
      }
      if (this.collection.isEmpty()) {
        this.figure.children().hide();
        var $container = $('
').appendTo(this.figure);
        this.missingData = new MissingData({
          el: $container
        });
        this.missingData.render();
        return;
      }

      View.prototype.render.apply(this, arguments);

      if (this.collection.options) {
        this.currency = this.collection.options.currency;
      }

      this.resizeWithCalloutHidden();

      this.scales.x = this.calcXScale();
      this.scales.y = this.calcYScale();

      _.each(this.componentInstances, function (component) {
        component.render();
      }, this);
    },

    remove: function () {
      if (this.table) {
        this.table.remove();
      }
      _.invoke(this.componentInstances, 'remove');
      this.componentInstances = [];
      $(window).off('resize.' + this.cid);
      return View.prototype.remove.apply(this, arguments);
    },

    isOneHundredPercent: function () {
      return false;
    }

  });

  return Graph;
});
<|endoftext|>


<commit_before>let app       = require('../../../index.js');
let discord   = require('discord.js-commando');
let logger    = app.logger;
let client    = app.client;
let twitter   = app.services.twitter;

module.exports = class TweetCommand extends discord.Command {
	constructor(client) {
		super(client, {
			name: 'tweet',
			group: 'moderation',
			memberName: 'tweet',
			description: 'Sendet einen Tweet auf Twitter',
			throttling: {
				usages: 3,
				duration: 60
			},
			args: [
				{
					key: 'tweet',
					label: 'Tweet',
					prompt: 'Was möchtest du Tweeten? (Max. 140 Zeichen)\n',
					type: 'string'
				}
			]
		});
	}

	hasPermission(msg) {
		var response = false;

		let commandGroupRoles = app.config.discord.commandGroupRoles.find((role) => {
			return role.group === this.groupID;
		});

		commandGroupRoles.roles.forEach((role) => {
			if (msg.member._roles.includes(role)) {
				response = true;
			}
		});

		return response;
	}

	async run(msg, args) {
		let message          = args.tweet;
		let tweetLengthCount = message.length;

		if (tweetLengthCount > 140) {
			return msg.reply('Dein Tweet ist um ' + (tweetLengthCount - 140) + ' Zeichen zu lang.');
		}

		twitter.post('statuses/update', {status: message}, (error, tweet, response) => {
			if (error) {
				logger.error(error);
				return msg.reply('Beim senden deines Tweets ist ein Fehler aufgetreten');
			}

			return msg.reply('Dein Tweet wurde gesendet');
		});
	}
};
<commit_msg>Increased throttling duration for tweet command<commit_after>let app       = require('../../../index.js');
let discord   = require('discord.js-commando');
let logger    = app.logger;
let client    = app.client;
let twitter   = app.services.twitter;

module.exports = class TweetCommand extends discord.Command {
	constructor(client) {
		super(client, {
			name: 'tweet',
			group: 'moderation',
			memberName: 'tweet',
			description: 'Sendet einen Tweet auf Twitter',
			throttling: {
				usages: 3,
				duration: 900
			},
			args: [
				{
					key: 'tweet',
					label: 'Tweet',
					prompt: 'Was möchtest du Tweeten? (Max. 140 Zeichen)\n',
					type: 'string'
				}
			]
		});
	}

	hasPermission(msg) {
		var response = false;

		let commandGroupRoles = app.config.discord.commandGroupRoles.find((role) => {
			return role.group === this.groupID;
		});

		commandGroupRoles.roles.forEach((role) => {
			if (msg.member._roles.includes(role)) {
				response = true;
			}
		});

		return response;
	}

	async run(msg, args) {
		let message          = args.tweet;
		let tweetLengthCount = message.length;

		if (tweetLengthCount > 140) {
			return msg.reply('Dein Tweet ist um ' + (tweetLengthCount - 140) + ' Zeichen zu lang.');
		}

		twitter.post('statuses/update', {status: message}, (error, tweet, response) => {
			if (error) {
				logger.error(error);
				return msg.reply('Beim senden deines Tweets ist ein Fehler aufgetreten');
			}

			return msg.reply('Dein Tweet wurde gesendet');
		});
	}
};
<|endoftext|>


<commit_before>import h from 'react-hyperscript'
import {Link} from 'react-router-dom'
import styled from 'styled-components'
import NotificationBar from './NotificationBar.js'

import fathomLogo from '../../assets/fathom_monkey_beret_color_cropped.svg'

import {networkName} from '../../constants.js'

const Logo = styled('img').attrs({className: 'flex w2 mh2 self-center'})`
`

//  h(LinkUnstyled, {to: '/concepts'}, h(conceptButton, 'Concepts')),
// TODO add link to concepts

export const Header = (props) => {
  let address = props.userAddress.substring(0, 8) + '...' + props.userAddress.substring(35, 42)
  let balance = (props.AhaBalance / 1e9).toString().substring(0, 6) + ' AHA'
  let network = networkName(props.networkID)

  return (
    h(headerContainer,
      [
        h(headerRowLeft, [
          h(Link, {to: '/'}, h(Logo, {alt: 'logo', src: fathomLogo})),
          h(headerItem, {name: 'Address', value: address}),
          h(headerItem, {name: 'Network', value: network})
        ]),
        h(headerRowRight, [
          h(headerItem, {name: 'Balance', value: balance})
        ]),
        props.notificationBar.display
          ? h(NotificationBar, {status: props.notificationBar, setNotificationBar: props.setNotificationBar})
          : null
      ])
  )
}

const headerContainer = styled('ul').attrs({
  className: 'list flex w-100 flex-row flex-wrap pl0 pv2 ma0 items-start justify-between bg-dark-blue'})`
  `

const headerRowLeft = styled('ul').attrs({
  className: 'list pl0 flex w-auto flex-row ma0 items-center justify-start'})`
    `

const headerRowRight = styled('ul').attrs({
  className: 'list pl0 flex w-auto flex-row ma0 items-center justify-end'})`
      `

const headerItemContainer = styled('li').attrs({className: 'flex ba br1 b--dark-purple lightest-blue mh2'})`
`
const headerItemLabel = styled('div').attrs({className: 'ph3 pv2'})`
`
const headerItemValue = styled('div').attrs({className: 'bg-lightest-blue dark-blue ph3 pv2'})`
`

const headerItem = (props) => {
  return (
    h(headerItemContainer,
      [
        h(headerItemLabel, props.name),
        h(headerItemValue, props.value)
      ])
  )
}

export default Header
<commit_msg>deleted comment aout concept button<commit_after>import h from 'react-hyperscript'
import {Link} from 'react-router-dom'
import styled from 'styled-components'
import NotificationBar from './NotificationBar.js'

import fathomLogo from '../../assets/fathom_monkey_beret_color_cropped.svg'

import {networkName} from '../../constants.js'

const Logo = styled('img').attrs({className: 'flex w2 mh2 self-center'})`
`

export const Header = (props) => {
  let address = props.userAddress.substring(0, 8) + '...' + props.userAddress.substring(35, 42)
  let balance = (props.AhaBalance / 1e9).toString().substring(0, 6) + ' AHA'
  let network = networkName(props.networkID)

  return (
    h(headerContainer,
      [
        h(headerRowLeft, [
          h(Link, {to: '/'}, h(Logo, {alt: 'logo', src: fathomLogo})),
          h(headerItem, {name: 'Address', value: address}),
          h(headerItem, {name: 'Network', value: network})
        ]),
        h(headerRowRight, [
          h(headerItem, {name: 'Balance', value: balance})
        ]),
        props.notificationBar.display
          ? h(NotificationBar, {status: props.notificationBar, setNotificationBar: props.setNotificationBar})
          : null
      ])
  )
}

const headerContainer = styled('ul').attrs({
  className: 'list flex w-100 flex-row flex-wrap pl0 pv2 ma0 items-start justify-between bg-dark-blue'})`
  `

const headerRowLeft = styled('ul').attrs({
  className: 'list pl0 flex w-auto flex-row ma0 items-center justify-start'})`
    `

const headerRowRight = styled('ul').attrs({
  className: 'list pl0 flex w-auto flex-row ma0 items-center justify-end'})`
      `

const headerItemContainer = styled('li').attrs({className: 'flex ba br1 b--dark-purple lightest-blue mh2'})`
`
const headerItemLabel = styled('div').attrs({className: 'ph3 pv2'})`
`
const headerItemValue = styled('div').attrs({className: 'bg-lightest-blue dark-blue ph3 pv2'})`
`

const headerItem = (props) => {
  return (
    h(headerItemContainer,
      [
        h(headerItemLabel, props.name),
        h(headerItemValue, props.value)
      ])
  )
}

export default Header
<|endoftext|>


<commit_before>'use strict';

import _ from 'underscore';
import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import { Button } from 'react-bootstrap';

import { acComponents, colors, dimensions } from 'app/constants';
import TripIdeaDragPreview from './TripIdeaDragPreview';
import TextInput from './TextInput';
import TripIdea from 'app/containers/TripIdea';
import PlaceAutocomplete from 'app/containers/PlaceAutocomplete';

class TripIdeasList extends Component {
  render() {
    const {
      ideas,
      isViewOnly,
      newIdea,
      onAddIdeaPress,
      onEnterIdeaComment,
      onShowAllIdeas
    } = this.props;

    const tripIdeas = ideas.map((idea, index) => {
      return (
        <TripIdea
          idea={idea}
          index={index}
          isViewOnly={isViewOnly}
          key={idea._id}
        />
      );
    });

    const commentBox = (
      <TextInput
        onChange={onEnterIdeaComment}
        placeholder="Add a comment"
        style={styles.commentBox}
        tabIndex={2}
        type="text"
      />
    );

    const dragPreview = (
      <TripIdeaDragPreview ideas={ideas} key="__preview" />
    );

    const addIdeaSection = (

          <PlaceAutocomplete
            id={acComponents.tripIdeaAC}
            placeholder="Enter a place or destination"
            style={styles.searchBox}
            tabIndex={1}
          />
          <Button
            disabled={!newIdea}
            onClick={onAddIdeaPress}
            style={this.loadAddIdeaButtonStyle()}
            tabIndex={3}
          >
            Add
          </Button>

        {newIdea && commentBox}

    );

    return (

Ideas

            {ideas.length > 0 && (

                Show all

            )}

          {!isViewOnly && addIdeaSection}

          {tripIdeas}
          {!isViewOnly && dragPreview}

    );
  }

  loadAddIdeaButtonStyle() {
    let style = styles.searchBoxButton;
    const disabledStyle = styles.searchBoxButtonDisabled;
    const { newIdea } = this.props;

    return newIdea ? style : { ...style, ...disabledStyle };
  }
}

TripIdeasList.propTypes = {
  ideas: PropTypes.array,
  isViewOnly: PropTypes.bool.isRequired,
  newIdea: PropTypes.object,
  onAddIdeaPress: PropTypes.func.isRequired,
  onClearTripIdea: PropTypes.func.isRequired,
  onEnterIdea: PropTypes.func.isRequired,
  onEnterIdeaComment: PropTypes.func.isRequired,
  onShowAllIdeas: PropTypes.func.isRequired
};

const styles = {
  commentBox: {
    display: "inline",
    margin: "0px 0px 10px 0px",
    width: "100%"
  },
  h3: {
    fontFamily: "'Raleway', sans-serif",
    fontWeight: 400
  },
  ideasSection: {
    padding: "0 " + dimensions.sidePadding + " 0"
  },
  inputSection: {
    marginBottom: 10
  },
  searchBox: {
    fontSize: 14,
    width: 280
  },
  searchBoxButton: {
    backgroundColor: colors.primary,
    border: "none",
    color: "white",
    float: "right"
  },
  searchBoxButtonDisabled: {
    backgroundColor: "#f3f3f3",
    border: "1px solid #e1e1e1",
    color: "#cccccc",
    cursor: "default"
  },
  searchSection: {
    alignItems: "baseline",
    display: "flex",
    justifyContent: "space-between",
    margin: "0px 0px 10px 0px"
  },
  showAllLink: {
    cursor: "pointer",
    textDecoration: "underline"
  },
  titleSection: {
    display: "flex",
    alignItems: "baseline",
    justifyContent: "space-between"
  }
};

export default TripIdeasList;
<commit_msg>Move "Show All ideas" link to bottom of trip page<commit_after>'use strict';

import _ from 'underscore';
import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import { Button } from 'react-bootstrap';

import { acComponents, colors, dimensions } from 'app/constants';
import TripIdeaDragPreview from './TripIdeaDragPreview';
import TextInput from './TextInput';
import TripIdea from 'app/containers/TripIdea';
import PlaceAutocomplete from 'app/containers/PlaceAutocomplete';

class TripIdeasList extends Component {
  render() {
    const {
      ideas,
      isViewOnly,
      newIdea,
      onAddIdeaPress,
      onEnterIdeaComment,
      onShowAllIdeas
    } = this.props;

    const tripIdeas = ideas.map((idea, index) => {
      return (
        <TripIdea
          idea={idea}
          index={index}
          isViewOnly={isViewOnly}
          key={idea._id}
        />
      );
    });

    const commentBox = (
      <TextInput
        onChange={onEnterIdeaComment}
        placeholder="Add a comment"
        style={styles.commentBox}
        tabIndex={2}
        type="text"
      />
    );

    const showAllIdeasLink = (

        Show all ideas on map

    );

    const dragPreview = (
      <TripIdeaDragPreview ideas={ideas} key="__preview" />
    );

    const addIdeaSection = (

          <PlaceAutocomplete
            id={acComponents.tripIdeaAC}
            placeholder="Enter a place or destination"
            style={styles.searchBox}
            tabIndex={1}
          />
          <Button
            disabled={!newIdea}
            onClick={onAddIdeaPress}
            style={this.loadAddIdeaButtonStyle()}
            tabIndex={3}
          >
            Add
          </Button>

        {newIdea && commentBox}

    );

    return (

Ideas

          {!isViewOnly && addIdeaSection}

          {tripIdeas}
          {ideas.length > 0 && showAllIdeasLink}
          {!isViewOnly && dragPreview}

    );
  }

  loadAddIdeaButtonStyle() {
    let style = styles.searchBoxButton;
    const disabledStyle = styles.searchBoxButtonDisabled;
    const { newIdea } = this.props;

    return newIdea ? style : { ...style, ...disabledStyle };
  }
}

TripIdeasList.propTypes = {
  ideas: PropTypes.array,
  isViewOnly: PropTypes.bool.isRequired,
  newIdea: PropTypes.object,
  onAddIdeaPress: PropTypes.func.isRequired,
  onClearTripIdea: PropTypes.func.isRequired,
  onEnterIdea: PropTypes.func.isRequired,
  onEnterIdeaComment: PropTypes.func.isRequired,
  onShowAllIdeas: PropTypes.func.isRequired
};

const styles = {
  commentBox: {
    display: "inline",
    margin: "0px 0px 10px 0px",
    width: "100%"
  },
  h3: {
    fontFamily: "'Raleway', sans-serif",
    fontWeight: 400
  },
  ideasSection: {
    padding: "0 " + dimensions.sidePadding + " 0"
  },
  inputSection: {
    marginBottom: 10
  },
  searchBox: {
    fontSize: 14,
    width: 280
  },
  searchBoxButton: {
    backgroundColor: colors.primary,
    border: "none",
    color: "white",
    float: "right"
  },
  searchBoxButtonDisabled: {
    backgroundColor: "#f3f3f3",
    border: "1px solid #e1e1e1",
    color: "#cccccc",
    cursor: "default"
  },
  searchSection: {
    alignItems: "baseline",
    display: "flex",
    justifyContent: "space-between",
    margin: "0px 0px 10px 0px"
  },
  showAllLink: {
    cursor: "pointer",
    backgroundColor: "#f4f4f4",
    border: "1px solid #dddddd",
    borderRadius: 3,
    margin: "10px auto 20px",
    textAlign: "center",
    padding: 10
  },
  titleSection: {
    display: "flex",
    alignItems: "baseline",
    justifyContent: "space-between"
  }
};

export default TripIdeasList;
<|endoftext|>


<commit_before>"use strict";

var React = require('react');

var Button = require('react-bootstrap').Button;
var Input = require('react-bootstrap').Input;
var Modal = require('react-bootstrap').Modal;

var LinkedStateMixin = require('react-addons-linked-state-mixin');

var remote = require('electron').remote;
var Menu = remote.Menu;
var MenuItem = remote.MenuItem;

var tinycolor = require('tinycolor2');

var log = require('../../logger');

var currentWindow = remote.getCurrentWindow();

var BigButton = React.createClass({
	mixins: [LinkedStateMixin],

	propTypes: {
        idx: React.PropTypes.number,
		name: React.PropTypes.string.isRequired,
		type: React.PropTypes.string.isRequired,
        iconClass: React.PropTypes.string,
		color: React.PropTypes.string,
		onClick: React.PropTypes.func,
		onEdit: React.PropTypes.func,
		patterns: React.PropTypes.array,
		serials: React.PropTypes.array,
        serial: React.PropTypes.string
	},
	getInitialState: function() {
		return {
			name: this.props.name
		};
		// return {name: this.props.name, editName:false};
	},
	componentDidMount: function() {
		// log.msg("BigButton.componentDidMount type:",this.props.type);
		// if( this.props.type !== 'sys' ) { this.menu = this.makeMenu(); }
	},
	makeMenu: function() {
		// log.msg("BigButton.makeMenu: props:",this.props);
		var self = this;
		var idx = self.props.idx;
		var menu = new Menu();

		// Make pattern menu
		var pattmenu = new Menu();
		this.props.patterns.map( function(p) {
			pattmenu.append( new MenuItem({label:p.name, click: self.doContextMenu.bind(null,null, 'setpattern', p.id)}) );
		});
		// Make serials menu
		var serialsmenu = null;
		if( this.props.serials && this.props.serials.length > 0 ) {
			serialsmenu = new Menu();
			serialsmenu.append( new MenuItem({label:'-use-default-',
										click: self.doContextMenu.bind(null,null, 'setserial', 'default')}) );
			this.props.serials.map( function(s) {
				serialsmenu.append( new MenuItem({label:s, type: 'radio',
										click: self.doContextMenu.bind(null,null, 'setserial', s),
                                        checked: (self.props.serial === s) }) );
			});
		}
		menu.append(new MenuItem({ label:'Set to current color',
				click: self.doContextMenu.bind(null,null, 'setcolor', idx)})); // fixme
		menu.append(new MenuItem({ label:'Set to pattern',
				submenu: pattmenu} ));
				// click: self.doContextMenu.bind(null,null, 'setpattern', idx)})); // fixme
		if( serialsmenu ) {
			menu.append(new MenuItem({ label:'Assign to device',
				submenu: serialsmenu} ));
		}
		menu.append(new MenuItem({ label:'Move button left',
				click: self.doContextMenu.bind(null,null, 'moveleft', idx)})); // fixme
		menu.append(new MenuItem({ label:'Delete button',
				click: self.doContextMenu.bind(null,null, 'delete', idx)})); // fixme
		menu.append(new MenuItem({ label:'Rename Button',
				click: self.showEditMenu }));
		return menu;
	},
	showEditMenu: function() {
		this.setState({showEditMenu:true});
	},
	hideEditMenu: function() {
		this.setState({showEditMenu:false});
	},
	handleEditClose: function(e) {
		e.preventDefault();
		log.msg("BigButton.handleEditClose");
		this.props.onEdit('rename', this.props.idx, this.state.name); // FIXME: seems really hacky
		this.hideEditMenu();
	},
	showContextMenu: function(evt) {
		// log.msg("BigButton:showContextMenu2: menu:",a,"b:",b,"c:",c);
        evt.preventDefault();
		if( this.props.type === 'sys' ) { return; } // no context for sys buttons
		var menu = this.makeMenu();
		menu.popup(currentWindow);
	},
	doContextMenu: function(event, eventKey, arg) {
    	log.msg("BigButton.doContextMenu: eventKey:",eventKey, "arg:",arg, "idx:",this.props.idx);
		this.props.onEdit(eventKey, this.props.idx, arg);
	},
    handleMouseDown: function(evt) {
        // log.msg("BigButton.handleMouseDown:", evt, "buttons:",evt.buttons, evt.button, 'ctrl:',evt.ctrlKey );
        if( evt.button === 2 || evt.ctrlKey) {
            // log.msg("CONTEXT MENU!");
        }
    },
	render: function() {
		var buttonStyle = { width: 72, height: 72, padding: 3, margin: 5, textShadow:'none'  };
		// var tstyle = { height: 28, border:'1px solid red', color: 'grey', fontSize: "0.8em", wordWrap:'break-word', whiteSpace:'normal'  };
		// var tstyle = { height: 24, display:'flex',justifyContent:'center',alignItems:'center',border:'1px solid red', color: 'grey', fontSize: "0.8em", wordWrap:'break-word', whiteSpace:'normal', verticalAlign:'middle' };
		var namestyle = { height: 24, display:'flex',justifyContent:'center', alignItems:'flex-end',
			fontWeight: 400, fontSize: "0.9em",
			wordWrap:'break-word', whiteSpace:'normal', lineHeight:'90%' };

		var iconContent;
		if( this.props.type === "color" ) {
			buttonStyle.background = this.props.color;
			if( tinycolor(buttonStyle.background).isDark() ) {
				buttonStyle.color = '#eee';
			}
			iconContent = ;
		}
		else if( this.props.type === 'pattern' ) {
			buttonStyle.background = this.props.color; // FIXME: pattern color summary, see below
			buttonStyle.color = '#000';
            iconContent = ;

            // FIXME: idea for doing pattern color summary
            // var patternColors =  ['#ff00ff', '#000000', '#0ff000'];
        	// iconContent =
            //      {patternColors.map(function(c,idx) {
            //         return ;
            //     })} ;
		}
		else if( this.props.type === "sys") {  // FIXME: seems hacky, must be better way surely
            iconContent = ;
		}
		else if( this.props.type === "add" ) {
			iconContent = ;
		}
        var titlestr = (this.props.type !== 'sys') ? "right-click to edit button":"";

		return (

				<Button style={buttonStyle} title={titlestr}
					onContextMenu={this.showContextMenu}
                    onClick={this.props.onClick}>
					{iconContent}

{this.props.name}

				</Button>

				<Modal show={this.state.showEditMenu} onHide={this.hideEditMenu} bsSize="small" >
				  <Modal.Header>
					<Modal.Title>Edit Button Name</Modal.Title>
				  </Modal.Header>
				  <Modal.Body>
					  <form className="form-horizontal" onSubmit={this.handleEditClose} >
						  <Input labelClassName="col-xs-5" wrapperClassName="col-xs-7" bsSize="small"
							  type="text" label="Button Name" valueLink={this.linkState('name')} />
					  </form>
				  </Modal.Body>
				  <Modal.Footer>
					  <Button onClick={this.hideEditMenu}>Cancel</Button>
					  <Button type="submit" onClick={this.handleEditClose}>OK</Button>
				 </Modal.Footer>
			  </Modal>

		);
	}
});

module.exports = BigButton;

// var cmstyle = {
// 	position: 'absolute',
// 	backgroundColor: '#EEE',
// 	boxShadow: '0 5px 10px rgba(0, 0, 0, 0.2)',
// 	border: '1px solid #CCC',
// 	borderRadius: 3,
// 	marginLeft: -5,
// 	marginTop: 5,
// 	padding: 10
// };

			// <Overlay
			// 	show={this.state.showContextMenu}
			// 	onHide={this.hideContextMenu}
			// 	rootClose={true}
			// 	container={this}
			// 	target={this.refs.btbar}
			// 	>
			// 	<Popover title="Edit Button" id="editbutton">
			// 		<MenuItem eventKey="setcolor" onSelect={this.doContextMenu}>Set to current color</MenuItem>
			// 		<MenuItem eventKey="setpattern" onSelect={this.doContextMenu}>Set to last pattern</MenuItem>
			// 		<MenuItem eventKey="moveleft" onSelect={this.doContextMenu}>Move button left</MenuItem>
			// 		<MenuItem eventKey="delete" onSelect={this.doContextMenu}>Delete button</MenuItem>
			// 	</Popover>
			// </Overlay>
			//

// var modalish= (
//
// 		<Button style={buttonStyle} ref={function(ref) { console.log("WHAT, ref=",ref); return self.mybuttonRef = ref; }}
// 			onClick={this.props.onClick} onContextMenu={this.showContextMenu}>
// 			{iconContent}
{this.props.name}

// 		</Button>
// 		<Modal show={this.state.showContextMenu} onHide={this.hideContextMenu} bsSize="small" >
// 		  <Modal.Header>
// 			<Modal.Title>Edit Button</Modal.Title>
// 		  </Modal.Header>
// 		  <Modal.Body>
// 			  FUCKKKK.
// 			  <MenuItem eventKey="setcolor" onSelect={this.doContextMenu}>Set to current color</MenuItem>
// 			  <MenuItem eventKey="setpattern" onSelect={this.doContextMenu}>Set to last pattern</MenuItem>
// 			  <MenuItem eventKey="moveleft" onSelect={this.doContextMenu}>Move button left</MenuItem>
// 			  <MenuItem eventKey="delete" onSelect={this.doContextMenu}>Delete button</MenuItem>
// 		  </Modal.Body>
// 	  </Modal>
//
// );
<commit_msg>fix bigbutton rename issue<commit_after>"use strict";

var React = require('react');

var Button = require('react-bootstrap').Button;
var Input = require('react-bootstrap').Input;
var Modal = require('react-bootstrap').Modal;

var LinkedStateMixin = require('react-addons-linked-state-mixin');

var remote = require('electron').remote;
var Menu = remote.Menu;
var MenuItem = remote.MenuItem;

var tinycolor = require('tinycolor2');

var log = require('../../logger');

var currentWindow = remote.getCurrentWindow();

var BigButton = React.createClass({
	mixins: [LinkedStateMixin],

	propTypes: {
        idx: React.PropTypes.number,
		name: React.PropTypes.string.isRequired,
		type: React.PropTypes.string.isRequired,
        iconClass: React.PropTypes.string,
		color: React.PropTypes.string,
		onClick: React.PropTypes.func,
		onEdit: React.PropTypes.func,
		patterns: React.PropTypes.array,
		serials: React.PropTypes.array,
        serial: React.PropTypes.string
	},
	getInitialState: function() {
		return {
			// tempname: this.props.name // just for
		};
		// return {name: this.props.name, editName:false};
	},
	componentDidMount: function() {
		// log.msg("BigButton.componentDidMount type:",this.props.type);
		// if( this.props.type !== 'sys' ) { this.menu = this.makeMenu(); }
	},
	makeMenu: function() {
		// log.msg("BigButton.makeMenu: props:",this.props);
		var self = this;
		var idx = self.props.idx;
		var menu = new Menu();

		// Make pattern menu
		var pattmenu = new Menu();
		this.props.patterns.map( function(p) {
			pattmenu.append( new MenuItem({label:p.name, click: self.doContextMenu.bind(null,null, 'setpattern', p.id)}) );
		});
		// Make serials menu
		var serialsmenu = null;
		if( this.props.serials && this.props.serials.length > 0 ) {
			serialsmenu = new Menu();
			serialsmenu.append( new MenuItem({label:'-use-default-',
										click: self.doContextMenu.bind(null,null, 'setserial', 'default')}) );
			this.props.serials.map( function(s) {
				serialsmenu.append( new MenuItem({label:s, type: 'radio',
										click: self.doContextMenu.bind(null,null, 'setserial', s),
                                        checked: (self.props.serial === s) }) );
			});
		}
		menu.append(new MenuItem({ label:'Set to current color',
				click: self.doContextMenu.bind(null,null, 'setcolor', idx)})); // fixme
		menu.append(new MenuItem({ label:'Set to pattern',
				submenu: pattmenu} ));
				// click: self.doContextMenu.bind(null,null, 'setpattern', idx)})); // fixme
		if( serialsmenu ) {
			menu.append(new MenuItem({ label:'Assign to device',
				submenu: serialsmenu} ));
		}
		menu.append(new MenuItem({ label:'Move button left',
				click: self.doContextMenu.bind(null,null, 'moveleft', idx)})); // fixme
		menu.append(new MenuItem({ label:'Delete button',
				click: self.doContextMenu.bind(null,null, 'delete', idx)})); // fixme
		menu.append(new MenuItem({ label:'Rename Button',
				click: self.showEditMenu }));
		return menu;
	},
	showEditMenu: function() {
        this.setState({tempname: this.props.name});
		this.setState({showEditMenu:true});
	},
	hideEditMenu: function() {
		this.setState({showEditMenu:false});
	},
	handleEditClose: function(e) {
		e.preventDefault();
		log.msg("BigButton.handleEditClose");
		this.props.onEdit('rename', this.props.idx, this.state.tempname); // FIXME: seems really hacky
		this.hideEditMenu();
	},
	showContextMenu: function(evt) {
		// log.msg("BigButton:showContextMenu2: menu:",a,"b:",b,"c:",c);
        evt.preventDefault();
		if( this.props.type === 'sys' ) { return; } // no context for sys buttons
		var menu = this.makeMenu();
		menu.popup(currentWindow);
	},
	doContextMenu: function(event, eventKey, arg) {
    	log.msg("BigButton.doContextMenu: eventKey:",eventKey, "arg:",arg, "idx:",this.props.idx);
		this.props.onEdit(eventKey, this.props.idx, arg);
	},
    // handleMouseDown: function(evt) {
    //     // log.msg("BigButton.handleMouseDown:", evt, "buttons:",evt.buttons, evt.button, 'ctrl:',evt.ctrlKey );
    //     if( evt.button === 2 || evt.ctrlKey) {
    //         // log.msg("CONTEXT MENU!");
    //     }
    // },
	render: function() {
		var buttonStyle = { width: 72, height: 72, padding: 3, margin: 5, textShadow:'none'  };
		// var tstyle = { height: 28, border:'1px solid red', color: 'grey', fontSize: "0.8em", wordWrap:'break-word', whiteSpace:'normal'  };
		// var tstyle = { height: 24, display:'flex',justifyContent:'center',alignItems:'center',border:'1px solid red', color: 'grey', fontSize: "0.8em", wordWrap:'break-word', whiteSpace:'normal', verticalAlign:'middle' };
		var namestyle = { height: 24, display:'flex',justifyContent:'center', alignItems:'flex-end',
			fontWeight: 400, fontSize: "0.9em",
			wordWrap:'break-word', whiteSpace:'normal', lineHeight:'90%' };

		var iconContent;
		if( this.props.type === "color" ) {
			buttonStyle.background = this.props.color;
			if( tinycolor(buttonStyle.background).isDark() ) {
				buttonStyle.color = '#eee';
			}
			iconContent = ;
		}
		else if( this.props.type === 'pattern' ) {
			buttonStyle.background = this.props.color; // FIXME: pattern color summary, see below
			buttonStyle.color = '#000';
            iconContent = ;

            // FIXME: idea for doing pattern color summary
            // var patternColors =  ['#ff00ff', '#000000', '#0ff000'];
        	// iconContent =
            //      {patternColors.map(function(c,idx) {
            //         return ;
            //     })} ;
		}
		else if( this.props.type === "sys") {  // FIXME: seems hacky, must be better way surely
            iconContent = ;
		}
		else if( this.props.type === "add" ) {
			iconContent = ;
		}
        var titlestr = (this.props.type !== 'sys') ? "right-click to edit button":"";

		return (

				<Button style={buttonStyle} title={titlestr}
					onContextMenu={this.showContextMenu}
                    onClick={this.props.onClick}>
					{iconContent}

{this.props.name}

				</Button>

				<Modal show={this.state.showEditMenu} onHide={this.hideEditMenu} bsSize="small" >
				  <Modal.Header>
					<Modal.Title>Edit Button Name</Modal.Title>
				  </Modal.Header>
				  <Modal.Body>
					  <form className="form-horizontal" onSubmit={this.handleEditClose} >
						  <Input labelClassName="col-xs-5" wrapperClassName="col-xs-7" bsSize="small"
							  type="text" label="Button Name" valueLink={this.linkState('tempname')} />
					  </form>
				  </Modal.Body>
				  <Modal.Footer>
					  <Button onClick={this.hideEditMenu}>Cancel</Button>
					  <Button type="submit" onClick={this.handleEditClose}>OK</Button>
				 </Modal.Footer>
			  </Modal>

		);
	}
});

module.exports = BigButton;

// var cmstyle = {
// 	position: 'absolute',
// 	backgroundColor: '#EEE',
// 	boxShadow: '0 5px 10px rgba(0, 0, 0, 0.2)',
// 	border: '1px solid #CCC',
// 	borderRadius: 3,
// 	marginLeft: -5,
// 	marginTop: 5,
// 	padding: 10
// };

			// <Overlay
			// 	show={this.state.showContextMenu}
			// 	onHide={this.hideContextMenu}
			// 	rootClose={true}
			// 	container={this}
			// 	target={this.refs.btbar}
			// 	>
			// 	<Popover title="Edit Button" id="editbutton">
			// 		<MenuItem eventKey="setcolor" onSelect={this.doContextMenu}>Set to current color</MenuItem>
			// 		<MenuItem eventKey="setpattern" onSelect={this.doContextMenu}>Set to last pattern</MenuItem>
			// 		<MenuItem eventKey="moveleft" onSelect={this.doContextMenu}>Move button left</MenuItem>
			// 		<MenuItem eventKey="delete" onSelect={this.doContextMenu}>Delete button</MenuItem>
			// 	</Popover>
			// </Overlay>
			//

// var modalish= (
//
// 		<Button style={buttonStyle} ref={function(ref) { console.log("WHAT, ref=",ref); return self.mybuttonRef = ref; }}
// 			onClick={this.props.onClick} onContextMenu={this.showContextMenu}>
// 			{iconContent}
{this.props.name}

// 		</Button>
// 		<Modal show={this.state.showContextMenu} onHide={this.hideContextMenu} bsSize="small" >
// 		  <Modal.Header>
// 			<Modal.Title>Edit Button</Modal.Title>
// 		  </Modal.Header>
// 		  <Modal.Body>
// 			  FUCKKKK.
// 			  <MenuItem eventKey="setcolor" onSelect={this.doContextMenu}>Set to current color</MenuItem>
// 			  <MenuItem eventKey="setpattern" onSelect={this.doContextMenu}>Set to last pattern</MenuItem>
// 			  <MenuItem eventKey="moveleft" onSelect={this.doContextMenu}>Move button left</MenuItem>
// 			  <MenuItem eventKey="delete" onSelect={this.doContextMenu}>Delete button</MenuItem>
// 		  </Modal.Body>
// 	  </Modal>
//
// );
<|endoftext|>


<commit_before>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import countryList from 'iso-3166-country-list';

const organizationTypeList = [
  'researchInstitution',
  'academicInstitution',
  'governmentAgency',
  'nationalInstitution',
  'professionalSociety',
  'publisher',
  'serviceProvider',
  'other'
]
const memberTypeList = [
  'provider',
  'consortium',
  'consortium_organization',
  'contractual_provider',
  'for_profit_provider',
  'member_only',
  'registration_agency'
]
const focusAreaList = [
  'naturalSciences',
  'engineeringAndTechnology',
  'medicalAndHealthSciences',
  'agriculturalSciences',
  'socialSciences',
  'humanities',
  'general'
]

export default Component.extend({
  store: service(),

  tagName: 'div',
  classNames: ['row'],
  provider: null,
  new: false,
  countryList,
  countries: null,
  organizationTypeList,
  organizationTypes: organizationTypeList,
  memberTypeList,
  memberTypes: memberTypeList,
  focusAreaList,
  focusAreas: focusAreaList,

  organizations: [],
  organizationsNames: [],

  reset() {
    this.set('provider', null);
    this.set('new', false);
  },
  searchCountry(query) {
    var countries = countryList.filter(function(country) {
      return country.name.toLowerCase().startsWith(query.toLowerCase());
    })
    this.set('countries', countries);
  },
  selectCountry(country) {
    this.provider.set('country', country);
    this.set('countries', countryList);
  },
  searchOrganizationType(query) {
    var organizationTypes = organizationTypeList.filter(function(organizationType) {
      return organizationType.startsWith(query.toLowerCase());
    })
    this.set('organizationTypes', organizationTypes);
  },
  selectOrganizationType(organizationType) {
    this.provider.set('organizationType', organizationType);
    this.set('organizationTypes', organizationTypeList);
  },
  searchMemberType(query) {
    var memberTypes = memberTypeList.filter(function(memberType) {
      return memberType.startsWith(query.toLowerCase());
    })
    this.set('memberTypes', memberTypes);
  },
  selectMemberType(memberType) {
    this.provider.set('memberType', memberType);
    this.set('memberTypes', memberTypeList);
  },
  searchConsortium(query) {
    this.set('consortia', this.store.query('provider', { 'query': query, 'member-type': 'consortium', sort: 'name', 'page[size]': 100 }));
  },
  selectConsortium(consortium) {
    this.provider.set('consortium', consortium)
  },
  searchFocusArea(query) {
    var focusAreas = focusAreaList.filter(function(focusArea) {
      return focusArea.startsWith(query.toLowerCase());
    })
    this.set('focusAreas', focusAreas);
  },
  selectFocusArea(focusArea) {
    this.provider.set('focusArea', focusArea);
    this.set('focusAreas', focusAreaList);
  },
  searchNonProfitStatus(query) {
    var nonProfitStatuses = nonProfitStatusList.filter(function(nonProfitStatus) {
      return nonProfitStatus.startsWith(query.toLowerCase());
    })
    this.set('nonProfitStatuses', nonProfitStatuses);
  },
  selectNonProfitStatus(nonProfitStatus) {
    this.provider.set('nonProfitStatus', nonProfitStatus);
    this.set('nonProfitStatuses', nonProfitStatusList);
  },
  selectBillingCountry(billingCountry) {
    this.provider.set('billingInformationCountry', billingCountry);
    this.provider.set('billingInformation.country', billingCountry);
    this.set('countries', countryList);
  },

  actions: {
    new() {
      this.set('provider', this.store.createRecord('provider', { billingInformation: {}, technicalContact: {}, isActive: true }));
      this.set('countries', countryList);
      this.set('new', true);
    },
    submit(provider) {
      let self = this;

      // this.provider.set('billingInformation', {
      //   address: this.provider.get('billingInformationAddress'),
      //   organization: this.provider.get('billingInformationOrganization'),
      //   department: this.provider.get('billingInformationDepartment'),
      //   city: this.provider.get('billingInformationCity'),
      //   state: this.provider.get('billingInformationState'),
      //   postCode: this.provider.get('billingInformationPostCode'),
      //   country: this.provider.get('billingInformationCountry')
      // });

      provider.save().then(function(provider) {
        self.router.transitionTo('providers.show.settings', provider.id);
        self.set('new', false);
      }).catch(function(reason){
        if (console.debug) {
          console.debug(reason);
        } else {
          console.log(reason);
        }
      });
    },
    cancel() {
      this.provider.rollbackAttributes();
      this.reset();
    },
    searchCountry(query) {
      this.searchCountry(query);
    },
    selectCountry(country) {
      this.selectCountry(country);
    },
    searchOrganizationType(query) {
      this.searchOrganizationType(query);
    },
    selectOrganizationType(organizationType) {
      this.selectOrganizationType(organizationType);
    },
    searchMemberType(query) {
      this.searchMemberType(query);
    },
    selectMemberType(memberType) {
      this.selectMemberType(memberType);
    },
    searchConsortium(query) {
      this.searchConsortium(query);
    },
    selectConsortium(provider) {
      this.selectConsortium(provider);
    },
    searchFocusArea(query) {
      this.searchFocusArea(query);
    },
    selectFocusArea(focusArea) {
      this.selectFocusArea(focusArea);
    },
    searchNonProfitStatus(query) {
      this.searchNonProfitStatus(query);
    },
    selectNonProfitStatus(nonProfitStatus) {
      this.selectNonProfitStatus(nonProfitStatus);
    },
    selectBillingCountry(billingCountry) {
      this.selectBillingCountry(billingCountry);
    },
    searchOrganization(query) {
      let self = this;
      this.store.query('organization', { 'query': query }).then(function (orgs) {
        let organizations = orgs.toArray();
        let organizationsNames = orgs.mapBy('name');
        self.set('organizations', organizations);
        self.set('organizationsNames', organizationsNames);
        return organizationsNames;
      });
    },
    selectOrganization(organization) {
      let organizationRecord = this.get('organizations').findBy('name', organization);

      this.set('organization', organization);
      this.provider.set('rorId', organizationRecord.id);
    }
  }
});
<commit_msg>added missing constant<commit_after>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import countryList from 'iso-3166-country-list';

const organizationTypeList = [
  'researchInstitution',
  'academicInstitution',
  'governmentAgency',
  'nationalInstitution',
  'professionalSociety',
  'publisher',
  'serviceProvider',
  'other'
]
const memberTypeList = [
  'provider',
  'consortium',
  'consortium_organization',
  'contractual_provider',
  'for_profit_provider',
  'member_only',
  'registration_agency'
]
const focusAreaList = [
  'naturalSciences',
  'engineeringAndTechnology',
  'medicalAndHealthSciences',
  'agriculturalSciences',
  'socialSciences',
  'humanities',
  'general'
]

const nonProfitStatusList = [
  'non-profit',
  'for-profit'
]

export default Component.extend({
  store: service(),

  tagName: 'div',
  classNames: ['row'],
  provider: null,
  new: false,
  countryList,
  countries: null,
  organizationTypeList,
  organizationTypes: organizationTypeList,
  memberTypeList,
  memberTypes: memberTypeList,
  focusAreaList,
  focusAreas: focusAreaList,

  organizations: [],
  organizationsNames: [],

  reset() {
    this.set('provider', null);
    this.set('new', false);
  },
  searchCountry(query) {
    var countries = countryList.filter(function(country) {
      return country.name.toLowerCase().startsWith(query.toLowerCase());
    })
    this.set('countries', countries);
  },
  selectCountry(country) {
    this.provider.set('country', country);
    this.set('countries', countryList);
  },
  searchOrganizationType(query) {
    var organizationTypes = organizationTypeList.filter(function(organizationType) {
      return organizationType.startsWith(query.toLowerCase());
    })
    this.set('organizationTypes', organizationTypes);
  },
  selectOrganizationType(organizationType) {
    this.provider.set('organizationType', organizationType);
    this.set('organizationTypes', organizationTypeList);
  },
  searchMemberType(query) {
    var memberTypes = memberTypeList.filter(function(memberType) {
      return memberType.startsWith(query.toLowerCase());
    })
    this.set('memberTypes', memberTypes);
  },
  selectMemberType(memberType) {
    this.provider.set('memberType', memberType);
    this.set('memberTypes', memberTypeList);
  },
  searchConsortium(query) {
    this.set('consortia', this.store.query('provider', { 'query': query, 'member-type': 'consortium', sort: 'name', 'page[size]': 100 }));
  },
  selectConsortium(consortium) {
    this.provider.set('consortium', consortium)
  },
  searchFocusArea(query) {
    var focusAreas = focusAreaList.filter(function(focusArea) {
      return focusArea.startsWith(query.toLowerCase());
    })
    this.set('focusAreas', focusAreas);
  },
  selectFocusArea(focusArea) {
    this.provider.set('focusArea', focusArea);
    this.set('focusAreas', focusAreaList);
  },
  searchNonProfitStatus(query) {
    var nonProfitStatuses = nonProfitStatusList.filter(function(nonProfitStatus) {
      return nonProfitStatus.startsWith(query.toLowerCase());
    })
    this.set('nonProfitStatuses', nonProfitStatuses);
  },
  selectNonProfitStatus(nonProfitStatus) {
    this.provider.set('nonProfitStatus', nonProfitStatus);
    this.set('nonProfitStatuses', nonProfitStatusList);
  },
  selectBillingCountry(billingCountry) {
    this.provider.set('billingInformationCountry', billingCountry);
    this.provider.set('billingInformation.country', billingCountry);
    this.set('countries', countryList);
  },

  actions: {
    new() {
      this.set('provider', this.store.createRecord('provider', { billingInformation: {}, technicalContact: {}, isActive: true }));
      this.set('countries', countryList);
      this.set('new', true);
    },
    submit(provider) {
      let self = this;

      // this.provider.set('billingInformation', {
      //   address: this.provider.get('billingInformationAddress'),
      //   organization: this.provider.get('billingInformationOrganization'),
      //   department: this.provider.get('billingInformationDepartment'),
      //   city: this.provider.get('billingInformationCity'),
      //   state: this.provider.get('billingInformationState'),
      //   postCode: this.provider.get('billingInformationPostCode'),
      //   country: this.provider.get('billingInformationCountry')
      // });

      provider.save().then(function(provider) {
        self.router.transitionTo('providers.show.settings', provider.id);
        self.set('new', false);
      }).catch(function(reason){
        if (console.debug) {
          console.debug(reason);
        } else {
          console.log(reason);
        }
      });
    },
    cancel() {
      this.provider.rollbackAttributes();
      this.reset();
    },
    searchCountry(query) {
      this.searchCountry(query);
    },
    selectCountry(country) {
      this.selectCountry(country);
    },
    searchOrganizationType(query) {
      this.searchOrganizationType(query);
    },
    selectOrganizationType(organizationType) {
      this.selectOrganizationType(organizationType);
    },
    searchMemberType(query) {
      this.searchMemberType(query);
    },
    selectMemberType(memberType) {
      this.selectMemberType(memberType);
    },
    searchConsortium(query) {
      this.searchConsortium(query);
    },
    selectConsortium(provider) {
      this.selectConsortium(provider);
    },
    searchFocusArea(query) {
      this.searchFocusArea(query);
    },
    selectFocusArea(focusArea) {
      this.selectFocusArea(focusArea);
    },
    searchNonProfitStatus(query) {
      this.searchNonProfitStatus(query);
    },
    selectNonProfitStatus(nonProfitStatus) {
      this.selectNonProfitStatus(nonProfitStatus);
    },
    selectBillingCountry(billingCountry) {
      this.selectBillingCountry(billingCountry);
    },
    searchOrganization(query) {
      let self = this;
      this.store.query('organization', { 'query': query }).then(function (orgs) {
        let organizations = orgs.toArray();
        let organizationsNames = orgs.mapBy('name');
        self.set('organizations', organizations);
        self.set('organizationsNames', organizationsNames);
        return organizationsNames;
      });
    },
    selectOrganization(organization) {
      let organizationRecord = this.get('organizations').findBy('name', organization);

      this.set('organization', organization);
      this.provider.set('rorId', organizationRecord.id);
    }
  }
});
<|endoftext|>


<commit_before>module.exports = function (clients) {

    'use strict';

    /**
     *
     *      CONFIG should return e.g
     *
     *      module.exports.TWITTER = {
     *          key: 'keystring',
     *          secret: 'secretstring',
     *          accessToken: 'accesstokenstring',
     *          tokenSecret: 'tokensecretstring'
     *      }
     *
     *      Config is not in source control for security.
     *
     */

    if (process.env.TWITTER_KEY) {

        var CONFIG = {};

        CONFIG.TWITTER = {
            key: process.env.TWITTER_KEY,
            secret: process.env.TWITTER_SECRET,
            accessToken: process.env.ACCESS_TOKEN,
            tokenSecret: process.env.TOKEN_SECRET
        }

    } else {
        var CONFIG = require('../../config');

    }

    var twitter = require('twit'),
        Tweet = require('./model.js'),
        stream;

    var twit = new twitter({
        consumer_key: CONFIG.TWITTER.key,
        consumer_secret: CONFIG.TWITTER.secret,
        access_token: CONFIG.TWITTER.accessToken,
        access_token_secret: CONFIG.TWITTER.tokenSecret
    });

    var searchTweets = function (nickname, socket) {

        console.log('searching tweets with filter',nickname)

        stream = twit.stream('statuses/filter', { track: nickname });
        stream.on('tweet', function (data) {
            console.log(data.text)
            var tweet = new Tweet(data);
            socket.emit('tweets', tweet);
        });

    };

    return {
        stream: searchTweets,
        searchTweets: function(user, socket) {
            stream.stop();
            searchTweets(user, socket)
        }
    };

};
<commit_msg>woops<commit_after>module.exports = function (clients) {

    'use strict';

    /**
     *
     *      CONFIG should return e.g
     *
     *      module.exports.TWITTER = {
     *          key: 'keystring',
     *          secret: 'secretstring',
     *          accessToken: 'accesstokenstring',
     *          tokenSecret: 'tokensecretstring'
     *      }
     *
     *      Config is not in source control for security.
     *
     */

    if (process.env.TWITTER_KEY) {

        var CONFIG = {};

        CONFIG.TWITTER = {
            key: process.env.TWITTER_KEY,
            secret: process.env.TWITTER_SECRET,
            accessToken: process.env.ACCESS_TOKEN,
            tokenSecret: process.env.TOKEN_SECRET
        }

    } else {
        var CONFIG = require('../../config');

    }

    var twitter = require('twit'),
        Tweet = require('./model.js'),
        stream;

    var twit = new twitter({
        consumer_key: CONFIG.TWITTER.key,
        consumer_secret: CONFIG.TWITTER.secret,
        access_token: CONFIG.TWITTER.accessToken,
        access_token_secret: CONFIG.TWITTER.tokenSecret
    });

    var searchTweets = function (nickname, socket) {

        console.log('searching tweets with filter',nickname)

        stream = twit.stream('statuses/filter', { track: nickname });
        stream.on('tweet', function (data) {
            console.log(data.text)
            var tweet = new Tweet(data);
            socket.emit('tweets', tweet);
        });

    };

    return {
        stream: searchTweets,
        searchTweets: function(user, socket) {
            if(stream) {
                stream.stop();
            }
            searchTweets(user, socket)
        }
    };

};
<|endoftext|>


<commit_before>import Ember from "ember";
import AjaxPromise from "../utils/ajax-promise";
import config from "../config/environment";
const { getOwner } = Ember;

export default Ember.Controller.extend({
  messageBox: Ember.inject.service(),
  attemptedTransition: null,
  pin: "",
  backLinkPath: "login",

  mobile: Ember.computed("mobilePhone", function() {
    return config.APP.HK_COUNTRY_CODE + this.get("mobilePhone");
  }),

  actions: {
    authenticateUser() {
      Ember.$(".auth_error").hide();
      var pin = this.get("pin");
      var otp_auth_key = this.get("session.otpAuthKey");
      var _this = this;

      var loadingView = getOwner(this)
        .lookup("component:loading")
        .append();
      new AjaxPromise("/auth/verify", "POST", null, {
        pin: pin,
        otp_auth_key: otp_auth_key
      })
        .then(function(data) {
          _this.setProperties({ pin: null });
          _this.set("session.authToken", data.jwt_token);
          _this.set("session.otpAuthKey", null);
          _this.store.pushPayload(data.user);
          _this.setProperties({ pin: null });
          _this.transitionToRoute("post_login");
        })
        .catch(function(jqXHR) {
          Ember.$("#pin")
            .closest("div")
            .addClass("error");
          _this.setProperties({ pin: null });
          if (
            jqXHR.status === 422 &&
            jqXHR.responseJSON.errors &&
            jqXHR.responseJSON.errors.pin
          ) {
            _this.get("messageBox").alert(jqXHR.responseJSON.errors.pin);
          }
          console.log("Unable to authenticate");
        })
        .finally(() => loadingView.destroy());
    },

    resendPin() {
      var mobile = this.get("mobile");
      var loadingView = getOwner(this)
        .lookup("component:loading")
        .append();
      var _this = this;

      new AjaxPromise("/auth/send_pin", "POST", null, { mobile: mobile })
        .then(data => {
          this.set("session.otpAuthKey", data.otp_auth_key);
          this.setProperties({ pin: null });
          this.transitionToRoute("/authenticate");
        })
        .catch(error => {
          if ([401].includes(error.status)) {
            _this.get("messageBox").alert("You are not authorized.", () => {
              _this.transitionToRoute("/");
            });
          } else if ([422, 403].includes(error.status)) {
            Ember.$("#mobile")
              .closest(".mobile")
              .addClass("error");
            return;
          }
          throw error;
        })
        .finally(() => loadingView.destroy());
    },

    transitionTo(path) {
      this.transitionToRoute(path);
    }
  }
});
<commit_msg>GCW-3587 - Set value of backLinkPath after login action triggered<commit_after>import Ember from "ember";
import AjaxPromise from "../utils/ajax-promise";
import config from "../config/environment";
const { getOwner } = Ember;

export default Ember.Controller.extend({
  messageBox: Ember.inject.service(),
  attemptedTransition: null,
  pin: "",

  mobile: Ember.computed("mobilePhone", function() {
    return config.APP.HK_COUNTRY_CODE + this.get("mobilePhone");
  }),

  backLinkPath: Ember.computed("session.backLinkPath", function() {
    return this.session.get("backLinkPath") || "login";
  }),

  actions: {
    authenticateUser() {
      Ember.$(".auth_error").hide();
      var pin = this.get("pin");
      var otp_auth_key = this.get("session.otpAuthKey");
      var _this = this;

      var loadingView = getOwner(this)
        .lookup("component:loading")
        .append();
      new AjaxPromise("/auth/verify", "POST", null, {
        pin: pin,
        otp_auth_key: otp_auth_key
      })
        .then(function(data) {
          _this.setProperties({ pin: null });
          _this.set("session.authToken", data.jwt_token);
          _this.set("session.otpAuthKey", null);
          _this.store.pushPayload(data.user);
          _this.setProperties({ pin: null });
          _this.transitionToRoute("post_login");
        })
        .catch(function(jqXHR) {
          Ember.$("#pin")
            .closest("div")
            .addClass("error");
          _this.setProperties({ pin: null });
          if (
            jqXHR.status === 422 &&
            jqXHR.responseJSON.errors &&
            jqXHR.responseJSON.errors.pin
          ) {
            _this.get("messageBox").alert(jqXHR.responseJSON.errors.pin);
          }
          console.log("Unable to authenticate");
        })
        .finally(() => loadingView.destroy());
    },

    resendPin() {
      var mobile = this.get("mobile");
      var loadingView = getOwner(this)
        .lookup("component:loading")
        .append();
      var _this = this;

      new AjaxPromise("/auth/send_pin", "POST", null, { mobile: mobile })
        .then(data => {
          this.set("session.otpAuthKey", data.otp_auth_key);
          this.set("session.backLinkPath", "login");
          this.setProperties({ pin: null });
          this.transitionToRoute("/authenticate");
        })
        .catch(error => {
          if ([401].includes(error.status)) {
            _this.get("messageBox").alert("You are not authorized.", () => {
              _this.transitionToRoute("/");
            });
          } else if ([422, 403].includes(error.status)) {
            Ember.$("#mobile")
              .closest(".mobile")
              .addClass("error");
            return;
          }
          throw error;
        })
        .finally(() => loadingView.destroy());
    },

    transitionTo(path) {
      this.transitionToRoute(path);
    }
  }
});
<|endoftext|>


<commit_before>var args = arguments[0] || {};

$.IDLabel.text = args.get('id') || 'Default ID';
$.companynameLabel.text = args.get('companyName') || 'Default Company Name';
$.firstnameLabel.text = args.get('firstName') || 'Default First Name';
$.lastnameLabel.text = args.get('lastName') || 'Default Last Name';
$.positionLabel.text = args.get('position') || 'Default Position';
$.phoneLabel.text = args.get('phone') || 'Default Phone';
$.emailLabel.text = args.get('email') || 'Default Email';
<commit_msg>add comment and remove last name label<commit_after>var args = arguments[0] || {};

$.IDLabel.text = args.get('id') || 'Default ID';
$.companynameLabel.text = args.get('companyName') || 'Default Company Name';
$.firstnameLabel.text = args.get('firstName') || 'Default First Name';
$.positionLabel.text = args.get('position') || 'Default Position';
$.phoneLabel.text = args.get('phone') || 'Default Phone';
$.emailLabel.text = args.get('email') || 'Default Email';

//TESTTTT DARI REYNALD<|endoftext|>