<commit_before>/**
 * Created by mcgourtyalex on 4/29/15.
 */

var PupHashTags = {

    hashtags: [
        "#EasyToObedienceTrain",
        "#HardToObedienceTrain",
        "#EasyToHouseTrain",
        "#HardToHouseTrain",
        '##ReallySmartDog',
        "#CalmPersonality",
        "#BarksALot",
        "#VeryQuiet",
        "#OnePersonDog",
        "#FriendlyTowardEveryone",
        "#UnpredictableWithStrangers",
        "#UnpredictableWithChildren",
        "#Independent",
        "#ConstantCompanionAroundHome",
        "#GreatWithCats&OtherSmallAnimals",
        "#UnpredictableWithCats&OtherSmallAnimals",
        "#LovesToPlayBall&Fetch",
        "#WellMannered&CanGoAnywhereWithMe",
        "#ShedsALot",
        "#CoatNeedsFrequentGrooming",
        "#EatsPoopOrOtherDisgustingThings"
    ]

    ,num: 0

    ,setup: function() {
        for (hashtag in PupHashTags.hashtags) {
            $('' + PupHashTags.hashtags[hashtag] + ' ').appendTo('#hashtags').click( function() {

                if ($(this).attr('class').indexOf("hashtag_selected") > -1) {
                    $(this).removeClass('hashtag_selected');
                    PupHashTags.num--;
                    this_id = parseInt($(this).attr('number'));

                    if ($('#invisible_hashtag_1').val() == PupHashTags.hashtags[this_id]) {
                        $('#invisible_hashtag_1').val("")
                    } else if ($('#invisible_hashtag_2').val() == PupHashTags.hashtags[this_id]) {
                        $('#invisible_hashtag_2').val("")
                    } else {
                        $('#invisible_hashtag_3').val("")
                    }
                } else {
                    if (PupHashTags.num < 3) {
                        this_id = parseInt($(this).attr('number'))
                        if ($('#invisible_hashtag_1').val() == "") {
                            $('#invisible_hashtag_1').val(PupHashTags.hashtags[this_id])
                        } else if ($('#invisible_hashtag_2').val() == "") {
                            $('#invisible_hashtag_2').val(PupHashTags.hashtags[this_id])
                        } else {
                            $('#invisible_hashtag_3').val(PupHashTags.hashtags[this_id])
                        }

                        $(this).addClass('hashtag_selected');
                        PupHashTags.num++;
                    }
                }
            });
        }
    }

    ,preTag: function () {
        let pathArray = window.location.pathname.substring(1).split('/');
        console.log(pathArray)
        if (pathArray.length == 3 && pathArray[2] === 'edit') {
            let pupId = parseInt(pathArray[1]);
            console.log(pupId);

            $.ajax({
                type: 'GET',
                url: '/pups/hashtags',
                data: {
                    "pup_id": pupId
                },
                contentType: 'application/json',
                dataType: 'json',
                timeout: 5000,
                // callback designated by selection of find or form
                success: function(data) {
                    console.log(data);
                },
                error: function() {
                    console.log("fail to get hashtag");
                }
            })

            // $.ajax({
            //     type: 'GET',
            //     url: '/pup/hashtags',
            //     data: {
            //         'pup_id': pupId
            //     },
            //     contentType: 'application/json',
            //     dataType: 'json',
            //     timeout: 50000,
            //     success: function(data) {
            //         console.log("asd");
            //         console.log(data);
            //     },
            //     error: function() {
            //         console.log("fail");
            //     }
            // });
        }
    }
};

$(document).ready(function () {
    $(PupHashTags.setup);
    PupHashTags.preTag();
});
<commit_msg>feat:  finish pre-click hashtag<commit_after>/**
 * Created by mcgourtyalex on 4/29/15.
 */

var PupHashTags = {

    hashtags: [
        "#EasyToObedienceTrain",
        "#HardToObedienceTrain",
        "#EasyToHouseTrain",
        "#HardToHouseTrain",
        '##ReallySmartDog',
        "#CalmPersonality",
        "#BarksALot",
        "#VeryQuiet",
        "#OnePersonDog",
        "#FriendlyTowardEveryone",
        "#UnpredictableWithStrangers",
        "#UnpredictableWithChildren",
        "#Independent",
        "#ConstantCompanionAroundHome",
        "#GreatWithCats&OtherSmallAnimals",
        "#UnpredictableWithCats&OtherSmallAnimals",
        "#LovesToPlayBall&Fetch",
        "#WellMannered&CanGoAnywhereWithMe",
        "#ShedsALot",
        "#CoatNeedsFrequentGrooming",
        "#EatsPoopOrOtherDisgustingThings"
    ]

    ,num: 0

    ,setup: function() {
        for (hashtag in PupHashTags.hashtags) {
            $('' + PupHashTags.hashtags[hashtag] + ' ').appendTo('#hashtags').click( function() {

                if ($(this).attr('class').indexOf("hashtag_selected") > -1) {
                    $(this).removeClass('hashtag_selected');
                    PupHashTags.num--;
                    this_id = parseInt($(this).attr('number'));

                    if ($('#invisible_hashtag_1').val() == PupHashTags.hashtags[this_id]) {
                        $('#invisible_hashtag_1').val("")
                    } else if ($('#invisible_hashtag_2').val() == PupHashTags.hashtags[this_id]) {
                        $('#invisible_hashtag_2').val("")
                    } else {
                        $('#invisible_hashtag_3').val("")
                    }
                } else {
                    if (PupHashTags.num < 3) {
                        this_id = parseInt($(this).attr('number'))
                        if ($('#invisible_hashtag_1').val() == "") {
                            $('#invisible_hashtag_1').val(PupHashTags.hashtags[this_id])
                        } else if ($('#invisible_hashtag_2').val() == "") {
                            $('#invisible_hashtag_2').val(PupHashTags.hashtags[this_id])
                        } else {
                            $('#invisible_hashtag_3').val(PupHashTags.hashtags[this_id])
                        }

                        $(this).addClass('hashtag_selected');
                        PupHashTags.num++;
                    }
                }
            });
        }
    }

    ,preTag: function () {
        let pathArray = window.location.pathname.substring(1).split('/');
        console.log(pathArray)
        if (pathArray.length == 3 && pathArray[2] === 'edit') {
            let pupId = parseInt(pathArray[1]);
            console.log(pupId);

            $.ajax({
                type: 'GET',
                url: '/pups/hashtags',
                data: {
                    "pup_id": pupId
                },
                contentType: 'application/json',
                dataType: 'json',
                timeout: 5000,
                // callback designated by selection of find or form
                success: function(data) {
                    console.log(data);
                    for (let i = 0; i < data.length; i += 1) {
                        console.log(data[i])
                        if (data[i]) {
                            let index = PupHashTags.hashtags.indexOf(data[i]);
                            console.log(".hashtag[number=" + index + "]")
                            console.log($(".hashtag[number=" + index + "]"))
                            $(".hashtag[number=" + index + "]").click()
                        }
                    }
                },
                error: function() {
                    console.log("fail to get hashtag");
                }
            })
        }
    }
};

$(document).ready(function () {
    $(PupHashTags.setup);
    PupHashTags.preTag();
});
<|endoftext|>


<commit_before>jQuery(function ($) {
  const WRITE_COMMENT_BTN = '#write_comment_repository_btn';
  const $body = $('body');

  // Shows and hides the comment form
  $body.off('click', WRITE_COMMENT_BTN);
  $body.on('click', WRITE_COMMENT_BTN, (_e) => {
    $('#write_comment_form').toggle(400, 'swing', function () {
      if ($('#write_comment_form').is(':visible')) {
        $('#comment_body').focus();
        layout_resizer();
      }
    });
  });
});
<commit_msg>js: removed old repositories.js file<commit_after><|endoftext|>


<commit_before>this.SS_Popup = (function () {
  function SS_Popup(el, options) {
    this.el = el;
    this.options = options || {};
    this.render();
  }

  SS_Popup.initialized = false;

  SS_Popup.initializeOnce = function () {
    if (SS_Popup.initialized) {
      return;
    }

    SS_Popup.initialized = true;

    // tippy default settings
    tippy.setDefaultProps({
      theme: 'light-border ss-popup',
      trigger: 'click'
    });
  };

  SS_Popup.render = function (selector, options) {
    SS_Popup.initializeOnce();

    if (! selector) {
      selector = ".ss-popup";
    }

    $(document).on("click", selector, function (ev) {
      new SS_Popup(ev.target, options);
      return false;
    });
  };

  SS_Popup.prototype.render = function() {
    if (this.el._ss && this.el._ss.popup) {
      return;
    }
    if (this.el._tippy) {
      this.el._ss = this.el._ss || {};
      this.el._ss.popup = this;
      return;
    }

    var inline = ("ssPopupInline" in this.el.dataset) || this.options["ss-popup-inline"];
    var result;
    if (inline) {
      result = this.renderInlinePopup();
    } else {
      result = this.renderAjaxPopup();
    }
    if (! result) {
      return;
    }

    this.el._ss = this.el._ss || {};
    this.el._ss.popup = this;
  };

  SS_Popup.prototype.renderInlinePopup = function() {
    var self = this;
    var createAndShow = function(content, overflow) {
      var tippyOptions = { content: content };
      if (self.options["tippy-theme"]) {
        tippyOptions["theme"] = self.options["tippy-theme"]
      }
      if (overflow) {
        tippyOptions["popperOptions"] = { modifiers: { preventOverflow: { escapeWithReference: true } } };
      }
      var instance = tippy(self.el, tippyOptions);
      instance.show();
    };

    var overflow = this.el.dataset["ssPopupOverflow"] || this.options["ss-popup-overflow"];
    var content = this.el.dataset["ssPopupHtml"] || this.options["ss-popup-html"];
    if (content) {
      createAndShow(content, overflow);
      return true;
    }

    var href = this.el.dataset["ssPopupHref"] || this.options["ss-popup-href"];
    if (href) {
      content = this.el.querySelector(href) || document.querySelector(href);
      if (content) {
        createAndShow(content, overflow);
        return true;
      }
    }

    return false;
  };

  SS_Popup.prototype.renderAjaxPopup = function() {
    var href = this.el.dataset["ssPopupHref"] || this.options["ss-popup-href"];
    if (! href) {
      return false;
    }

    var tippyOptions = { content: SS.loading, trigger: 'click', theme: 'light-border ss-popup' };

    if (this.options["tippy-theme"]) {
      tippyOptions["theme"] = this.options["tippy-theme"]
    }

    var overflow = this.el.dataset["ssPopupOverflow"] || this.options["ss-popup-overflow"];
    if (overflow) {
      tippyOptions["popperOptions"] = { modifiers: { preventOverflow: { escapeWithReference: true } } };
    }

    var instance = tippy(this.el, tippyOptions);
    instance.show();

    var self = this;
    $.ajax({
      url: href,
      cache: false,
      success: function(html) {
        self.el._tippy.setContent(html);
      },
      error: function(xhr, status, error) {
        self.showError(xhr, status, error);
      }
    });
  };

  SS_Popup.prototype.showError = function(xhr, status, error) {
    this.el._tippy.setContent("[==Error==]");
  };

  return SS_Popup;
})();
<commit_msg>[fix] too many popup instances created (#3575)<commit_after>this.SS_Popup = (function () {
  function SS_Popup(el, options) {
    this.el = el;
    this.options = options || {};
    this.render();
  }

  SS_Popup.initialized = false;

  SS_Popup.initializeOnce = function () {
    if (SS_Popup.initialized) {
      return;
    }

    SS_Popup.initialized = true;

    // tippy default settings
    tippy.setDefaultProps({
      theme: 'light-border ss-popup',
      trigger: 'click'
    });
  };

  SS_Popup.render = function (selector, options) {
    SS_Popup.initializeOnce();

    if (! selector) {
      selector = ".ss-popup";
    }

    $(document).on("click", selector, function (ev) {
      if (ev.target._ss && ev.target._ss.popup) {
        return;
      }

      var popup = new SS_Popup(ev.target, options);
      popup.show();
      return false;
    });
  };

  SS_Popup.prototype.render = function() {
    if (this.el._ss && this.el._ss.popup) {
      return;
    }
    if (this.el._tippy) {
      this.el._ss = this.el._ss || {};
      this.el._ss.popup = this;
      return;
    }

    var inline = ("ssPopupInline" in this.el.dataset) || this.options["ss-popup-inline"];
    var result;
    if (inline) {
      result = this.renderInlinePopup();
    } else {
      result = this.renderAjaxPopup();
    }
    if (! result) {
      return;
    }

    this.el._ss = this.el._ss || {};
    this.el._ss.popup = this;
  };

  SS_Popup.prototype.renderInlinePopup = function() {
    var self = this;
    var createAndShow = function(content, overflow) {
      var tippyOptions = { content: content };
      if (self.options["tippy-theme"]) {
        tippyOptions["theme"] = self.options["tippy-theme"]
      }
      if (overflow) {
        tippyOptions["popperOptions"] = { modifiers: { preventOverflow: { escapeWithReference: true } } };
      }
      tippy(self.el, tippyOptions);
    };

    var overflow = this.el.dataset["ssPopupOverflow"] || this.options["ss-popup-overflow"];
    var content = this.el.dataset["ssPopupHtml"] || this.options["ss-popup-html"];
    if (content) {
      createAndShow(content, overflow);
      return true;
    }

    var href = this.el.dataset["ssPopupHref"] || this.options["ss-popup-href"];
    if (href) {
      content = this.el.querySelector(href) || document.querySelector(href);
      if (content) {
        createAndShow(content, overflow);
        return true;
      }
    }

    return false;
  };

  SS_Popup.prototype.renderAjaxPopup = function() {
    var href = this.el.dataset["ssPopupHref"] || this.options["ss-popup-href"];
    if (! href) {
      return false;
    }

    var tippyOptions = { content: SS.loading, trigger: 'click', theme: 'light-border ss-popup' };

    if (this.options["tippy-theme"]) {
      tippyOptions["theme"] = this.options["tippy-theme"]
    }

    var overflow = this.el.dataset["ssPopupOverflow"] || this.options["ss-popup-overflow"];
    if (overflow) {
      tippyOptions["popperOptions"] = { modifiers: { preventOverflow: { escapeWithReference: true } } };
    }

    tippy(this.el, tippyOptions);

    var self = this;
    $.ajax({
      url: href,
      cache: false,
      success: function(html) {
        self.el._tippy.setContent(html);
      },
      error: function(xhr, status, error) {
        self.showError(xhr, status, error);
      }
    });
  };

  SS_Popup.prototype.showError = function(xhr, status, error) {
    this.el._tippy.setContent("[==Error==]");
  };

  SS_Popup.prototype.show = function() {
    if (!this.el._tippy) {
      return;
    }

    this.el._tippy.show();
  }

  return SS_Popup;
})();
<|endoftext|>


<commit_before>$(function() {
    $(document).on('change', '.meter-filter', function() {
        chart_id = this.form.id.replace("-filter", "");
        chart = Chartkick.charts[chart_id];
        current_source = chart.getDataSource();
        new_source = current_source.split("?")[0] + "?" + $(this.form).serialize();
        chart.updateData(new_source);
    });
});
<commit_msg>Display loading indicator<commit_after>$(function() {
    $(document).on('change', '.meter-filter', function() {
        chart_id = this.form.id.replace("-filter", "");
        chart = Chartkick.charts[chart_id];
        current_source = chart.getDataSource();
        new_source = current_source.split("?")[0] + "?" + $(this.form).serialize();
        chart.updateData(new_source);
        chart.getChartObject().showLoading();
    });
});
<|endoftext|>


<commit_before>// example-scene.js
// just and example of how to use cosmonaut

var harness = require('cosmonaut-harness');

var scene = new harness.scene();
scene.attachToDom($('#context'));

var sphere = new harness.primitive.sphere({
  radius: 50
});

var light = new harness.light();

var lambert = new harness.material();

sphere.set('material', lambert);

scene.addObject(sphere);
scene.addLight(light);

var time = 0;

scene.on('prerender', function() {
  time++;
  sphere.scale(Math.cos(time/100), Math.sin(time/100), Math.cos(time/100) * Math.sin(time/100));
});

scene.startRenderLoop();
<commit_msg>updating example for camera stuff<commit_after>// example-scene.js
// just and example of how to use cosmonaut

var harness = require('cosmonaut-harness');

var scene = new harness.scene();
scene.attachToDom($('#context'));

var sphere = new harness.primitive.sphere({
  radius: 50
});

var light = new harness.light();

var lambert = new harness.material();

sphere.set('material', lambert);

scene.addObject(sphere);
scene.addLight(light);

var time = 0;

scene.on('prerender', function() {
  time++;
  sphere.scale(Math.cos(time/100), Math.sin(time/100), Math.cos(time/100) * Math.sin(time/100));
  scene.camera.move(Math.cos(time/50), Math.sin(time/50), Math.cos(time/50) * Math.sin(time/50));
});

scene.camera.set('lookAtObject', sphere);

scene.startRenderLoop();
<|endoftext|>


<commit_before>/**
 * dat-gui JavaScript Controller Library
 * http://code.google.com/p/dat-gui
 *
 * Copyright 2011 Data Arts Team, Google Creative Lab
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 */

define([
  'dat/controllers/OptionController',
  'dat/controllers/NumberControllerBox',
  'dat/controllers/NumberControllerSlider',
  'dat/controllers/StringController',
  'dat/controllers/FunctionController',
  'dat/controllers/BooleanController',
  'dat/utils/common'
],
    function(OptionController, NumberControllerBox, NumberControllerSlider, StringController, FunctionController, BooleanController, common) {

      return function(object, property) {

        var initialValue = object[property];

        // Providing options?
        if (common.isArray(arguments[2]) || common.isObject(arguments[2])) {
          return new OptionController(object, property, arguments[2]);
        }

        // Providing a map?

        if (common.isNumber(initialValue)) {

          if (common.isNumber(arguments[2]) && common.isNumber(arguments[3])) {

            // Has min and max.
            return new NumberControllerSlider(object, property, arguments[2], arguments[3]);

          } else {

            return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] });

          }

        }

        if (common.isString(initialValue)) {
          return new StringController(object, property);
        }

        if (common.isFunction(initialValue)) {
          return new FunctionController(object, property, '');
        }

        if (common.isBoolean(initialValue)) {
          return new BooleanController(object, property);
        }

      }

    });<commit_msg>fixes missing step argument<commit_after>/**
 * dat-gui JavaScript Controller Library
 * http://code.google.com/p/dat-gui
 *
 * Copyright 2011 Data Arts Team, Google Creative Lab
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 */

define([
  'dat/controllers/OptionController',
  'dat/controllers/NumberControllerBox',
  'dat/controllers/NumberControllerSlider',
  'dat/controllers/StringController',
  'dat/controllers/FunctionController',
  'dat/controllers/BooleanController',
  'dat/utils/common'
],
    function(OptionController, NumberControllerBox, NumberControllerSlider, StringController, FunctionController, BooleanController, common) {

      return function(object, property) {

        var initialValue = object[property];

        // Providing options?
        if (common.isArray(arguments[2]) || common.isObject(arguments[2])) {
          return new OptionController(object, property, arguments[2]);
        }

        // Providing a map?

        if (common.isNumber(initialValue)) {

          if (common.isNumber(arguments[2]) && common.isNumber(arguments[3])) {

        	// Has min and max.
            if (common.isNumber(arguments[4])) // has step
              return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
            else
              return new NumberControllerSlider(object, property, arguments[2], arguments[3]);

          } else {

        	if (common.isNumber(arguments[4]))
              return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3], step: arguments[4] });
          	else
              return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] });

          }

        }

        if (common.isString(initialValue)) {
          return new StringController(object, property);
        }

        if (common.isFunction(initialValue)) {
          return new FunctionController(object, property, '');
        }

        if (common.isBoolean(initialValue)) {
          return new BooleanController(object, property);
        }

      }

    });<|endoftext|>


<commit_before>import { format as d3Format } from "d3";

Template.visBigNumber.helpers({
  value: function() {
    var settings = this.settings;
    settings.valueFormat = settings.valueFormat || ",";

    if (settings.valueField && settings.valueAggregation) {
      var aggregationFunction = AGGREGATIONS[settings.valueAggregation].fn;
      var values = _.pluck(this.data, settings.valueField);
      var result = aggregationFunction(values);

      var parsedResult = parseFloat(result);
      if (!isNaN(parsedResult) && result.match(/^[\d\.]+$/)) {
        result = parsedResult;
      }

      return _.isNumber(result)
        ? d3Format(settings.valueFormat)(result)
        : result;
    } else return "-";
  }
});

Template.visBigNumberForm.helpers({
  aggregationMethods: _.keys(AGGREGATIONS)
});
<commit_msg>small fix<commit_after>import { format as d3Format } from "d3";

Template.visBigNumber.helpers({
  value: function() {
    var settings = this.settings;
    settings.valueFormat = settings.valueFormat || ",";

    if (settings.valueField && settings.valueAggregation) {
      var aggregationFunction = AGGREGATIONS[settings.valueAggregation].fn;
      var values = _.pluck(this.data, settings.valueField);
      var result = aggregationFunction(values);

      var parsedResult = parseFloat(result);
      if (!isNaN(parsedResult) && String(result).match(/^[\d\.]+$/)) {
        result = parsedResult;
      }

      return _.isNumber(result)
        ? d3Format(settings.valueFormat)(result)
        : result;
    } else return "-";
  }
});

Template.visBigNumberForm.helpers({
  aggregationMethods: _.keys(AGGREGATIONS)
});
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _MDDropDownMenu = require('./MDDropDownMenu.css');

var _MDDropDownMenu2 = _interopRequireDefault(_MDDropDownMenu);

var _jquery = require('jquery');

var _jquery2 = _interopRequireDefault(_jquery);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MDDropDownMenu = function (_Component) {
  _inherits(MDDropDownMenu, _Component);

  function MDDropDownMenu(props) {
    _classCallCheck(this, MDDropDownMenu);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(MDDropDownMenu).call(this, props));

    _this.state = {
      defaultOption: _this.props.defaultOption
    };
    return _this;
  }

  _createClass(MDDropDownMenu, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var localDropdown = _MDDropDownMenu2.default.dropdown;
      var localSelected = _MDDropDownMenu2.default.selected;
      var localOptions = _MDDropDownMenu2.default.options;
      var mdDropDownMenu = this;

      var dropdown = (0, _jquery2.default)('.' + localDropdown);
      dropdown.find('.' + localSelected).click(function () {
        dropdown.find('.' + localOptions + ' ul').toggle();
      });

      dropdown.find('li').click(function () {
        var selectedOption = (0, _jquery2.default)(this).html();
        mdDropDownMenu.setState({ defaultOption: selectedOption });
        dropdown.find('.' + localOptions + ' ul').hide();
      });

      (0, _jquery2.default)(document).bind('click', function (e) {
        if (!(0, _jquery2.default)(e.target).parents().hasClass(localDropdown)) {
          (0, _jquery2.default)('.' + localDropdown + ' ul').hide();
        }
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props;
      var options = _props.options;
      var width = _props.width;
      var height = _props.height;
      var defaultOption = this.state.defaultOption;

      var widthStyle = { width: width };
      var heightStyle = { height: height, lineHeight: height + 'px' };
      var optionsWithoutDefault = options.filter(function (option) {
        return option !== defaultOption;
      });
      return _react2.default.createElement(
        'div',
        { className: _MDDropDownMenu2.default.dropdown, style: widthStyle },
        _react2.default.createElement(
          'div',
          { className: _MDDropDownMenu2.default.selected, style: heightStyle },
          _react2.default.createElement(
            'div',
            null,
            defaultOption
          ),
          _react2.default.createElement(
            'span',
            null,
            _react2.default.createElement('i', { className: 'fa fa-chevron-down' })
          )
        ),
        _react2.default.createElement(
          'div',
          { className: _MDDropDownMenu2.default.options },
          _react2.default.createElement(
            'ul',
            { style: widthStyle },
            optionsWithoutDefault.map(function (option, i) {
              return _react2.default.createElement(
                'li',
                { key: i, style: heightStyle },
                option
              );
            })
          )
        )
      );
    }
  }]);

  return MDDropDownMenu;
}(_react.Component);

MDDropDownMenu.propTypes = {
  options: _react.PropTypes.arrayOf(_react.PropTypes.string),
  defaultOption: _react.PropTypes.string,
  onSelect: _react.PropTypes.func,
  width: _react.PropTypes.number,
  height: _react.PropTypes.number
};

MDDropDownMenu.defaultProps = {
  width: 300,
  height: 40
};

exports.default = MDDropDownMenu;<commit_msg>add test<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _MDDropDownMenu = require('./MDDropDownMenu.css');

var _MDDropDownMenu2 = _interopRequireDefault(_MDDropDownMenu);

var _jquery = require('jquery');

var _jquery2 = _interopRequireDefault(_jquery);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MDDropDownMenu = function (_Component) {
  _inherits(MDDropDownMenu, _Component);

  function MDDropDownMenu(props) {
    _classCallCheck(this, MDDropDownMenu);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(MDDropDownMenu).call(this, props));

    _this.state = {
      defaultOption: _this.props.defaultOption
    };
    return _this;
  }

  _createClass(MDDropDownMenu, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var localDropdown = _MDDropDownMenu2.default.dropdown;
      var localSelected = _MDDropDownMenu2.default.selected;
      var localOptions = _MDDropDownMenu2.default.options;
      var mdDropDownMenu = this;

      var dropdown = (0, _jquery2.default)('.' + localDropdown);
      dropdown.find('.' + localSelected).click(function () {
        dropdown.find('.' + localOptions + ' ul').toggle();
      });

      dropdown.find('li').click(function () {
        var selectedOption = (0, _jquery2.default)(this).html();
        mdDropDownMenu.setState({ defaultOption: selectedOption });
        dropdown.find('.' + localOptions + ' ul').hide();
      });

      (0, _jquery2.default)(document).bind('click', function (e) {
        if (!(0, _jquery2.default)(e.target).parents().hasClass(localDropdown)) {
          (0, _jquery2.default)('.' + localDropdown + ' ul').hide();
        }
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props;
      var options = _props.options;
      var width = _props.width;
      var height = _props.height;
      var defaultOption = this.state.defaultOption;

      var widthStyle = { width: width };
      var heightStyle = { height: height, lineHeight: height + 'px' };
      var optionsWithoutDefault = options.filter(function (option) {
        return option !== defaultOption;
      });
      return _react2.default.createElement(
        'div',
        { className: _MDDropDownMenu2.default.dropdown, style: widthStyle },
        _react2.default.createElement(
          'div',
          { className: _MDDropDownMenu2.default.selected, style: heightStyle },
          _react2.default.createElement(
            'div',
            null,
            defaultOption
          ),
          _react2.default.createElement(
            'span',
            null,
            _react2.default.createElement('i', { className: 'fa fa-chevron-down' })
          )
        ),
        _react2.default.createElement(
          'div',
          { className: _MDDropDownMenu2.default.options },
          _react2.default.createElement(
            'ul',
            { style: widthStyle },
            optionsWithoutDefault.map(function (option, i) {
              return _react2.default.createElement(
                'li',
                { key: i, style: heightStyle },
                option
              );
            })
          )
        )
      );
    }
  }]);

  return MDDropDownMenu;
}(_react.Component);

MDDropDownMenu.propTypes = {
  options: _react.PropTypes.arrayOf(_react.PropTypes.string).isRequired,
  defaultOption: _react.PropTypes.string.isRequired,
  onSelect: _react.PropTypes.func,
  width: _react.PropTypes.number,
  height: _react.PropTypes.number
};

MDDropDownMenu.defaultProps = {
  width: 300,
  height: 40
};

exports.default = MDDropDownMenu;<|endoftext|>


<commit_before>/**
*
* GettingStarted
*
*/

import React from 'react';

import styles from './styles.css';

function GettingStarted() {
  return (

Getting Started

Clone the boilerplate if you haven't downloaded it

						git clone https://github.com/mxstbr/react-boilerplate.git

Run the setup to get everything up and running

						npm run setup

And start the development server

						npm run start

Now you can go to localhost:3000 and see your app!

  );
}

export default GettingStarted;
<commit_msg>fix git url in GettingStarted component<commit_after>/**
*
* GettingStarted
*
*/

import React from 'react';

import styles from './styles.css';

function GettingStarted() {
  return (

Getting Started

Clone the boilerplate if you haven't downloaded it

						git clone https://github.com/react-boilerplate/react-boilerplate.git

Run the setup to get everything up and running

						npm run setup

And start the development server

						npm run start

Now you can go to localhost:3000 and see your app!

  );
}

export default GettingStarted;
<|endoftext|>


<commit_before>/**
* @class
*
*
*/

OpenLayers.Map = Class.create();
OpenLayers.Map.prototype = {
    // Hash: base z-indexes for different classes of thing
    Z_INDEX_BASE: { Layer: 100, Popup: 200, Control: 250 },

    // Array: supported application event types
    EVENT_TYPES: [
        "addlayer", "removelayer", "movestart", "move", "moveend",
        "zoomend", "layerchanged", "popupopen", "popupclose",
        "addmarker", "removemarker", "clearmarkers", "mouseover",
        "mouseout", "mousemove", "dragstart", "drag", "dragend" ],

    // int: zoom levels, used to draw zoom dragging control and limit zooming
    maxZoomLevel: 16,

    // OpenLayers.Bounds
    maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90),

    /* maxScale was determined empirically by finding the resolution
       of GMaps in degrees per pixel at zoom level 0. */
    // float
    maxResolution: .3515625, // degrees per pixel

    // DOMElement: the div that our map lives in
    div: null,

    // HTMLDivElement: the map's control layer
    controlDiv: null,

    // HTMLDivElement: the map's view port
    viewPortDiv: null,

    // HTMLDivElement: the map's layer container
    layerContainerDiv: null,

    // Array(OpenLayers.Layer): ordered list of layers in the map
    layers: null,

    // Array(OpenLayers.Control)
    controls: null,

    // OpenLayers.LonLat
    center: null,

    // int
    zoom: null,

    // OpenLayers.Events
    events: null,

    // OpenLayers.Pixel
    mouseDragStart: null,

    /**
    * @param {DOMElement} div
    */
    initialize: function (div, options) {
        Object.extend(this, options);

        this.div = div = $(div);

        // the viewPortDiv is the outermost div we modify
        this.viewPortDiv = OpenLayers.Util.createDiv(
                                div.id + "_OpenLayers_ViewPort" );
        this.viewPortDiv.style.width = "100%";
        this.viewPortDiv.style.height = "100%";
        this.viewPortDiv.style.overflow = "hidden";
        this.viewPortDiv.style.position = "relative";
        this.div.appendChild(this.viewPortDiv);

        // the controlDiv is the div that all the controls sit on
        this.controlDiv = OpenLayers.Util.createDiv(
                                div.id + "_OpenLayers_Control" );
        this.controlDiv.style.width="100%";
        this.controlDiv.style.height="100%";
        this.controlDiv.style.zIndex = this.Z_INDEX_BASE["Control"];
        this.viewPortDiv.appendChild(this.controlDiv);

        // the layerContainerDiv is the one that holds all the layers
        this.layerContainerDiv = OpenLayers.Util.createDiv(
                                div.id + "_OpenLayers_Container" );
        this.viewPortDiv.appendChild(this.layerContainerDiv);

        this.events = new OpenLayers.Events(this, div, this.EVENT_TYPES);

        this.layers = [];

        this.controls = [];
        this.addControl( new OpenLayers.Control.PanZoom() );

        this.events.register( "dblclick", this, this.defaultDblClick );
        this.events.register( "mousedown", this, this.defaultMouseDown );
        this.events.register( "mouseup", this, this.defaultMouseUp );
        this.events.register( "mousemove", this, this.defaultMouseMove );

        // always call map.destroy()
        Event.observe(window, 'unload',
            this.destroy.bindAsEventListener(this));
    },

    /**
    */
    destroy:function() {
        for(var i=0; i< this.layers.length; i++) {
            this.layers[i].destroy();
        }
        this.layers = null;
        for(var i=0; i< this.controls.length; i++) {
            this.controls[i].destroy();
        }
        this.controls = null;
    },

    /**
    * @param {OpenLayers.Layer} layer
    */
    addLayer: function (layer) {
        layer.map = this;
        layer.div.style.overflow = "";
        layer.div.style.zIndex = this.Z_INDEX_BASE['Layer'] + this.layers.length;
        this.layerContainerDiv.appendChild(layer.div);
        this.layers.push(layer);
        this.events.triggerEvent("addlayer");
    },

    /**
    * @param {Array(OpenLayers.Layer)} layers
    */
    addLayers: function (layers) {
        for (var i = 0; i <  layers.length; i++) {
            this.addLayer(layers[i]);
        }
    },

    /**
    * @param {OpenLayers.Control} control
    */
    addControl: function (control) {
        control.map = this;
        this.controls.push(control);
        this.controlDiv.appendChild( control.draw() );
    },

    /**
    * @return {float}
    */
    getResolution: function () {
        // return degrees per pixel
        return this.maxResolution / Math.pow(2, this.zoom);
    },

    /**
    * @return {int}
    */
    getZoom: function () {
        return this.zoom;
    },

    /**
    * @returns {OpenLayers.Size}
    */
    getSize: function () {
        // should this be cached?
        return new OpenLayers.Size(
                    this.div.clientWidth, this.div.clientHeight);
    },

    /**
    * @return {OpenLayers.LonLat}
    */
    getCenter: function () {
        return this.center;
    },

    /**
    * @return {OpenLayers.Bounds}
    */
    getExtent: function () {
        if (this.center) {
            var res = this.getResolution();
            var size = this.getSize();
            var w_deg = size.w * res;
            var h_deg = size.h * res;
            return new OpenLayers.Bounds(
                this.center.lon - w_deg / 2,
                this.center.lat - h_deg / 2,
                this.center.lon + w_deg / 2,
                this.center.lat + h_deg / 2);
        } else {
            return null;
        }
    },

    /**
    * @return {OpenLayers.Bounds}
    */
    getFullExtent: function () {
        return this.maxExtent;
    },

    getZoomLevels: function() {
        return this.maxZoomLevel;
    },

    /**
    * @param {OpenLayers.Bounds} bounds
    *
    * @return {int}
    */
    getZoomForExtent: function (bounds) {
        var size = this.getSize();
        var deg_per_pixel = bounds.width / size.w;
        var zoom = Math.log(deg_per_pixel / this.maxResolution) / Math.log(2);
        return Math.floor(Math.max(zoom, 0));
    },

    /**
    * @param {OpenLayers.Pixel} point
    *
    * @return {OpenLayers.LonLat}
    */
    getLonLatFromPixel: function (point) {
        var center = this.getCenter();        //map center lon/lat
        var res  = this.getResolution();
        var size = this.getSize();

        var delta_x = point.x - (size.w / 2);
        var delta_y = point.y - (size.h / 2);

        return new OpenLayers.LonLat(center.lon + delta_x * res ,
                                     center.lat - delta_y * res);
    },

    /**
    * @param {OpenLayers.LonLat} lonlat
    * @param {int} zoom
    */
    setCenter: function (lonlat, zoom) {
        if (this.center) { // otherwise there's nothing to move yet
            this.moveLayerContainer(lonlat);
        }
        this.center = lonlat.copyOf();
        var zoomChanged = null;
        if (zoom != null && zoom != this.zoom
            && zoom >= 0 && zoom <= this.getZoomLevels()) {
            zoomChanged = (this.zoom == null ? 0 : this.zoom);
            this.zoom = zoom;
        }

        this.events.triggerEvent("movestart");
        this.moveToNewExtent(zoomChanged);
        this.events.triggerEvent("moveend");
    },

    moveToNewExtent: function (zoomChanged) {
        if (zoomChanged != null) { // reset the layerContainerDiv's location
            this.layerContainerDiv.style.left = "0px";
            this.layerContainerDiv.style.top  = "0px";
        }
        var bounds = this.getExtent();
        for (var i = 0; i < this.layers.length; i++) {
            this.layers[i].moveTo(bounds, (zoomChanged != null));
        }
        this.events.triggerEvent("move");
        if (zoomChanged != null)
            this.events.triggerEvent("zoomend",
                {oldZoom: zoomChanged, newZoom: this.zoom});
    },

    /**
     * zoomIn
     * Increase zoom level by one.
     */
    zoomIn: function() {
        if (this.zoom != null && this.zoom <= this.getZoomLevels()) {
            this.zoomTo( this.zoom += 1 );
        }

    },

    /**
     * zoomTo
     * Set Zoom To int
     */
    zoomTo: function(zoom) {
       if (zoom >= 0 && zoom <= this.getZoomLevels()) {
            var oldZoom = this.zoom;
            this.zoom = zoom;
            this.moveToNewExtent(oldZoom);
       }
    },

    /**
     * zoomOut
     * Decrease zoom level by one.
     */
    zoomOut: function() {
        if (this.zoom != null && this.zoom > 0) {
            this.zoomTo( this.zoom - 1 );
        }
    },

    zoomExtent: function() {
        var fullExtent = this.getFullExtent();
        var oldZoom = this.zoom;
        this.zoom = this.getZoomForExtent( fullExtent );
        this.setCenter(
          new OpenLayers.LonLat((fullExtent.minlon+fullExtent.maxlon)/2,
                                (fullExtent.minlat+fullExtent.maxlat)/2)
                               );
    },

    /**
    * @param {OpenLayers.LonLat} lonlat
    */
    moveLayerContainer: function (lonlat) {
        var container = this.layerContainerDiv;
        var resolution = this.getResolution();

        var deltaX = Math.round((this.center.lon - lonlat.lon) / resolution);
        var deltaY = Math.round((this.center.lat - lonlat.lat) / resolution);

        var offsetLeft = parseInt(container.style.left);
        var offsetTop  = parseInt(container.style.top);

        container.style.left = (offsetLeft + deltaX) + "px";
        container.style.top  = (offsetTop  - deltaY) + "px";
    },

    /**
    * @param {Event} evt
    */
    defaultDblClick: function (evt) {
        var newCenter = this.getLonLatFromPixel( evt.xy );
        this.setCenter(newCenter, this.zoom + 1);
    },

    /**
    * @param {Event} evt
    */
    defaultMouseDown: function (evt) {
        this.mouseDragStart = evt.xy.copyOf();
        this.div.style.cursor = "move";
        Event.stop(evt);
    },

    /**
    * @param {Event} evt
    */
    defaultMouseMove: function (evt) {
        if (this.mouseDragStart != null) {
            var deltaX = this.mouseDragStart.x - evt.xy.x;
            var deltaY = this.mouseDragStart.y - evt.xy.y
            var size = this.getSize();
            var newXY = new OpenLayers.Pixel(size.w / 2 + deltaX,
                                             size.h / 2 + deltaY);
            var newCenter = this.getLonLatFromPixel( newXY );
            this.setCenter(newCenter);
            this.mouseDragStart = evt.xy.copyOf();
        }
    },

    /**
    * @param {Event} evt
    */
    defaultMouseUp: function (evt) {
        this.mouseDragStart = null;
        this.div.style.cursor = "default";
    }
};
<commit_msg>fall back to Element.getDimensions when the element has no size (such as when it's hidden).<commit_after>/**
* @class
*
*
*/

OpenLayers.Map = Class.create();
OpenLayers.Map.prototype = {
    // Hash: base z-indexes for different classes of thing
    Z_INDEX_BASE: { Layer: 100, Popup: 200, Control: 250 },

    // Array: supported application event types
    EVENT_TYPES: [
        "addlayer", "removelayer", "movestart", "move", "moveend",
        "zoomend", "layerchanged", "popupopen", "popupclose",
        "addmarker", "removemarker", "clearmarkers", "mouseover",
        "mouseout", "mousemove", "dragstart", "drag", "dragend" ],

    // int: zoom levels, used to draw zoom dragging control and limit zooming
    maxZoomLevel: 16,

    // OpenLayers.Bounds
    maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90),

    /* maxScale was determined empirically by finding the resolution
       of GMaps in degrees per pixel at zoom level 0. */
    // float
    maxResolution: .3515625, // degrees per pixel

    // DOMElement: the div that our map lives in
    div: null,

    // HTMLDivElement: the map's control layer
    controlDiv: null,

    // HTMLDivElement: the map's view port
    viewPortDiv: null,

    // HTMLDivElement: the map's layer container
    layerContainerDiv: null,

    // Array(OpenLayers.Layer): ordered list of layers in the map
    layers: null,

    // Array(OpenLayers.Control)
    controls: null,

    // OpenLayers.LonLat
    center: null,

    // int
    zoom: null,

    // OpenLayers.Events
    events: null,

    // OpenLayers.Pixel
    mouseDragStart: null,

    /**
    * @param {DOMElement} div
    */
    initialize: function (div, options) {
        Object.extend(this, options);

        this.div = div = $(div);

        // the viewPortDiv is the outermost div we modify
        this.viewPortDiv = OpenLayers.Util.createDiv(
                                div.id + "_OpenLayers_ViewPort" );
        this.viewPortDiv.style.width = "100%";
        this.viewPortDiv.style.height = "100%";
        this.viewPortDiv.style.overflow = "hidden";
        this.viewPortDiv.style.position = "relative";
        this.div.appendChild(this.viewPortDiv);

        // the controlDiv is the div that all the controls sit on
        this.controlDiv = OpenLayers.Util.createDiv(
                                div.id + "_OpenLayers_Control" );
        this.controlDiv.style.width="100%";
        this.controlDiv.style.height="100%";
        this.controlDiv.style.zIndex = this.Z_INDEX_BASE["Control"];
        this.viewPortDiv.appendChild(this.controlDiv);

        // the layerContainerDiv is the one that holds all the layers
        this.layerContainerDiv = OpenLayers.Util.createDiv(
                                div.id + "_OpenLayers_Container" );
        this.viewPortDiv.appendChild(this.layerContainerDiv);

        this.events = new OpenLayers.Events(this, div, this.EVENT_TYPES);

        this.layers = [];

        this.controls = [];
        this.addControl( new OpenLayers.Control.PanZoom() );

        this.events.register( "dblclick", this, this.defaultDblClick );
        this.events.register( "mousedown", this, this.defaultMouseDown );
        this.events.register( "mouseup", this, this.defaultMouseUp );
        this.events.register( "mousemove", this, this.defaultMouseMove );

        // always call map.destroy()
        Event.observe(window, 'unload',
            this.destroy.bindAsEventListener(this));
    },

    /**
    */
    destroy:function() {
        for(var i=0; i< this.layers.length; i++) {
            this.layers[i].destroy();
        }
        this.layers = null;
        for(var i=0; i< this.controls.length; i++) {
            this.controls[i].destroy();
        }
        this.controls = null;
    },

    /**
    * @param {OpenLayers.Layer} layer
    */
    addLayer: function (layer) {
        layer.map = this;
        layer.div.style.overflow = "";
        layer.div.style.zIndex = this.Z_INDEX_BASE['Layer'] + this.layers.length;
        this.layerContainerDiv.appendChild(layer.div);
        this.layers.push(layer);
        this.events.triggerEvent("addlayer");
    },

    /**
    * @param {Array(OpenLayers.Layer)} layers
    */
    addLayers: function (layers) {
        for (var i = 0; i <  layers.length; i++) {
            this.addLayer(layers[i]);
        }
    },

    /**
    * @param {OpenLayers.Control} control
    */
    addControl: function (control) {
        control.map = this;
        this.controls.push(control);
        this.controlDiv.appendChild( control.draw() );
    },

    /**
    * @return {float}
    */
    getResolution: function () {
        // return degrees per pixel
        return this.maxResolution / Math.pow(2, this.zoom);
    },

    /**
    * @return {int}
    */
    getZoom: function () {
        return this.zoom;
    },

    /**
    * @returns {OpenLayers.Size}
    */
    getSize: function () {
        // should this be cached?
        var size = new OpenLayers.Size(
                    this.div.clientWidth, this.div.clientHeight);

        // Workaround for the fact that hidden elements return 0 for size.
        if (size.w == 0 && size.h == 0) {
           var elementSize = Element.getDimensions(this.div);
           size.w = elementSize.width;
           size.h = elementSize.height;
        }
        return size;
    },

    /**
    * @return {OpenLayers.LonLat}
    */
    getCenter: function () {
        return this.center;
    },

    /**
    * @return {OpenLayers.Bounds}
    */
    getExtent: function () {
        if (this.center) {
            var res = this.getResolution();
            var size = this.getSize();
            var w_deg = size.w * res;
            var h_deg = size.h * res;
            return new OpenLayers.Bounds(
                this.center.lon - w_deg / 2,
                this.center.lat - h_deg / 2,
                this.center.lon + w_deg / 2,
                this.center.lat + h_deg / 2);
        } else {
            return null;
        }
    },

    /**
    * @return {OpenLayers.Bounds}
    */
    getFullExtent: function () {
        return this.maxExtent;
    },

    getZoomLevels: function() {
        return this.maxZoomLevel;
    },

    /**
    * @param {OpenLayers.Bounds} bounds
    *
    * @return {int}
    */
    getZoomForExtent: function (bounds) {
        var size = this.getSize();
        var deg_per_pixel = bounds.width / size.w;
        var zoom = Math.log(deg_per_pixel / this.maxResolution) / Math.log(2);
        return Math.floor(Math.max(zoom, 0));
    },

    /**
    * @param {OpenLayers.Pixel} point
    *
    * @return {OpenLayers.LonLat}
    */
    getLonLatFromPixel: function (point) {
        var center = this.getCenter();        //map center lon/lat
        var res  = this.getResolution();
        var size = this.getSize();

        var delta_x = point.x - (size.w / 2);
        var delta_y = point.y - (size.h / 2);

        return new OpenLayers.LonLat(center.lon + delta_x * res ,
                                     center.lat - delta_y * res);
    },

    /**
    * @param {OpenLayers.LonLat} lonlat
    * @param {int} zoom
    */
    setCenter: function (lonlat, zoom) {
        if (this.center) { // otherwise there's nothing to move yet
            this.moveLayerContainer(lonlat);
        }
        this.center = lonlat.copyOf();
        var zoomChanged = null;
        if (zoom != null && zoom != this.zoom
            && zoom >= 0 && zoom <= this.getZoomLevels()) {
            zoomChanged = (this.zoom == null ? 0 : this.zoom);
            this.zoom = zoom;
        }

        this.events.triggerEvent("movestart");
        this.moveToNewExtent(zoomChanged);
        this.events.triggerEvent("moveend");
    },

    moveToNewExtent: function (zoomChanged) {
        if (zoomChanged != null) { // reset the layerContainerDiv's location
            this.layerContainerDiv.style.left = "0px";
            this.layerContainerDiv.style.top  = "0px";
        }
        var bounds = this.getExtent();
        for (var i = 0; i < this.layers.length; i++) {
            this.layers[i].moveTo(bounds, (zoomChanged != null));
        }
        this.events.triggerEvent("move");
        if (zoomChanged != null)
            this.events.triggerEvent("zoomend",
                {oldZoom: zoomChanged, newZoom: this.zoom});
    },

    /**
     * zoomIn
     * Increase zoom level by one.
     */
    zoomIn: function() {
        if (this.zoom != null && this.zoom <= this.getZoomLevels()) {
            this.zoomTo( this.zoom += 1 );
        }

    },

    /**
     * zoomTo
     * Set Zoom To int
     */
    zoomTo: function(zoom) {
       if (zoom >= 0 && zoom <= this.getZoomLevels()) {
            var oldZoom = this.zoom;
            this.zoom = zoom;
            this.moveToNewExtent(oldZoom);
       }
    },

    /**
     * zoomOut
     * Decrease zoom level by one.
     */
    zoomOut: function() {
        if (this.zoom != null && this.zoom > 0) {
            this.zoomTo( this.zoom - 1 );
        }
    },

    zoomExtent: function() {
        var fullExtent = this.getFullExtent();
        var oldZoom = this.zoom;
        this.zoom = this.getZoomForExtent( fullExtent );
        this.setCenter(
          new OpenLayers.LonLat((fullExtent.minlon+fullExtent.maxlon)/2,
                                (fullExtent.minlat+fullExtent.maxlat)/2)
                               );
    },

    /**
    * @param {OpenLayers.LonLat} lonlat
    */
    moveLayerContainer: function (lonlat) {
        var container = this.layerContainerDiv;
        var resolution = this.getResolution();

        var deltaX = Math.round((this.center.lon - lonlat.lon) / resolution);
        var deltaY = Math.round((this.center.lat - lonlat.lat) / resolution);

        var offsetLeft = parseInt(container.style.left);
        var offsetTop  = parseInt(container.style.top);

        container.style.left = (offsetLeft + deltaX) + "px";
        container.style.top  = (offsetTop  - deltaY) + "px";
    },

    /**
    * @param {Event} evt
    */
    defaultDblClick: function (evt) {
        var newCenter = this.getLonLatFromPixel( evt.xy );
        this.setCenter(newCenter, this.zoom + 1);
    },

    /**
    * @param {Event} evt
    */
    defaultMouseDown: function (evt) {
        this.mouseDragStart = evt.xy.copyOf();
        this.div.style.cursor = "move";
        Event.stop(evt);
    },

    /**
    * @param {Event} evt
    */
    defaultMouseMove: function (evt) {
        if (this.mouseDragStart != null) {
            var deltaX = this.mouseDragStart.x - evt.xy.x;
            var deltaY = this.mouseDragStart.y - evt.xy.y
            var size = this.getSize();
            var newXY = new OpenLayers.Pixel(size.w / 2 + deltaX,
                                             size.h / 2 + deltaY);
            var newCenter = this.getLonLatFromPixel( newXY );
            this.setCenter(newCenter);
            this.mouseDragStart = evt.xy.copyOf();
        }
    },

    /**
    * @param {Event} evt
    */
    defaultMouseUp: function (evt) {
        this.mouseDragStart = null;
        this.div.style.cursor = "default";
    }
};
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
    actions: {
        scrollToLayer(index){
            debugger;
            let el = $('#layer'+index);
            let offset = el.offset();
            $('body').animate({scrollTop:offset.top}, '500');
        }
    }
});
<commit_msg>Remove debugger;<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
    actions: {
        scrollToLayer(index){
            let el = $('#layer'+index);
            let offset = el.offset();
            $('body').animate({scrollTop:offset.top}, '500');
        }
    }
});
<|endoftext|>


<commit_before>import React from 'react';
import { Route, Switch, Link, withRouter } from 'react-router-dom';
import { RouteTransition } from 'react-router-transition';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as Actions from '../../actions';
import * as PlayerActions from '../../actions/player';
import * as QueueActions from '../../actions/queue';
import * as ScrobblingActions from '../../actions/scrobbling';
import Sound from 'react-sound';

class SoundContainer extends React.Component {
  handlePlaying(update) {
    let seek = update.position;
    let progress = (update.position/update.duration) * 100;
    this.props.actions.updatePlaybackProgress(progress, seek);
    this.props.actions.updateStreamLoading(false);
  }

  handleLoading() {
    this.props.actions.updateStreamLoading(true);
  }

  handleLoaded() {
    this.props.actions.updateStreamLoading(false);
  }

  handleFinishedPlaying() {
    if(this.props.scrobbling.lastFmScrobblingEnabled && this.props.scrobbling.lastFmSessionKey) {
      let currentSong = this.props.queue.queueItems[this.props.queue.currentSong];
      this.props.actions.scrobbleAction(currentSong.artist, currentSong.name, this.props.scrobbling.lastFmSessionKey);
    }
    if (this.props.queue.currentSong < this.props.queue.queueItems.length -1 || this.props.settings.loopAfterQueueEnd) {
      this.props.actions.nextSong();
    } else {
      this.props.actions.pausePlayback();
    }
  }

  shouldComponentUpdate(nextProps) {
    return (
      this.props.queue.currentSong !== nextProps.queue.currentSong ||
      this.props.player.playbackStatus !== nextProps.player.playbackStatus ||
      this.props.player.seek !== nextProps.player.seek
    );
  }

  render() {
    let {
      player,
      queue
    } = this.props;
    let streamUrl = '';
    if (queue.queueItems.length > 0) {
      let currentSong = queue.queueItems[queue.currentSong];
      if (currentSong.streams && currentSong.streams.length > 0) {
        streamUrl = currentSong.streams[0].stream;
      }
    }

    return (
      <Sound
        url={streamUrl}
        playStatus={player.playbackStatus}
        onPlaying={this.handlePlaying.bind(this)}
        onFinishedPlaying={this.handleFinishedPlaying.bind(this)}
        onLoading={this.handleLoading.bind(this)}
        onLoad={this.handleLoaded.bind(this)}
        position={player.seek}
        volume={player.volume}
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    queue: state.queue,
    player: state.player,
    scrobbling: state.scrobbling,
    settings: state.settings
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Object.assign({}, Actions, PlayerActions, QueueActions, ScrobblingActions), dispatch)
  };
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(SoundContainer));
<commit_msg>Play stream from selected plugin<commit_after>import React from 'react';
import { Route, Switch, Link, withRouter } from 'react-router-dom';
import { RouteTransition } from 'react-router-transition';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as Actions from '../../actions';
import * as PlayerActions from '../../actions/player';
import * as QueueActions from '../../actions/queue';
import * as ScrobblingActions from '../../actions/scrobbling';
import Sound from 'react-sound';
import { getSelectedStream } from '../../utils';

class SoundContainer extends React.Component {
  handlePlaying(update) {
    let seek = update.position;
    let progress = (update.position/update.duration) * 100;
    this.props.actions.updatePlaybackProgress(progress, seek);
    this.props.actions.updateStreamLoading(false);
  }

  handleLoading() {
    this.props.actions.updateStreamLoading(true);
  }

  handleLoaded() {
    this.props.actions.updateStreamLoading(false);
  }

  handleFinishedPlaying() {
    if(this.props.scrobbling.lastFmScrobblingEnabled && this.props.scrobbling.lastFmSessionKey) {
      let currentSong = this.props.queue.queueItems[this.props.queue.currentSong];
      this.props.actions.scrobbleAction(currentSong.artist, currentSong.name, this.props.scrobbling.lastFmSessionKey);
    }
    if (this.props.queue.currentSong < this.props.queue.queueItems.length -1 || this.props.settings.loopAfterQueueEnd) {
      this.props.actions.nextSong();
    } else {
      this.props.actions.pausePlayback();
    }
  }

  shouldComponentUpdate(nextProps) {
    return (
      this.props.queue.currentSong !== nextProps.queue.currentSong ||
      this.props.player.playbackStatus !== nextProps.player.playbackStatus ||
      this.props.player.seek !== nextProps.player.seek
    );
  }

  render() {
    let {
      player,
      queue,
      plugins
    } = this.props;

    let streamUrl = '';

    if (queue.queueItems.length > 0) {
      let currentSong = queue.queueItems[queue.currentSong];
      streamUrl = getSelectedStream(currentSong.streams, plugins.musicSourceOrder).stream;
    }

    return (
      <Sound
        url={streamUrl}
        playStatus={player.playbackStatus}
        onPlaying={this.handlePlaying.bind(this)}
        onFinishedPlaying={this.handleFinishedPlaying.bind(this)}
        onLoading={this.handleLoading.bind(this)}
        onLoad={this.handleLoaded.bind(this)}
        position={player.seek}
        volume={player.volume}
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    queue: state.queue,
    plugins: state.plugin,
    player: state.player,
    scrobbling: state.scrobbling,
    settings: state.settings
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Object.assign({}, Actions, PlayerActions, QueueActions, ScrobblingActions), dispatch)
  };
}

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


<commit_before>/**
 * @file Class definition
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GpfClassDefMember*/ // GPF class member definition
/*global _gpfAssert*/ // Assertion method
/*global _gpfAsserts*/ // Multiple assertion method
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*exported _GpfClassDefinition*/ // GPF class definition
/*#endif*/

_gpfErrorDeclare("define/definition/class", {
    "classMemberAlreadyExist":
        "You can't add a member twice"
});

/**
 * Link the class definition to the super one
 *
 * @param {_GpfClassDefinition} classDef Class definition receiving the link
 * @param {_GpfClassDefinition} [superClassDef=undefined] Class definition to link to
 * @return {Object} Superclass member dictionary if provided or an empty object
 */
function _gpfLinkToSuperClassDef (classDef, superClassDef) {
    if (superClassDef) {
        classDef._super = superClassDef;
        return superClassDef._members;
    }
    return {};
}

/**
 * Class definition
 * - Maintain a flat dictionary of members (using prototype inheritance)
 *
 * @param {String} qName Fully qualified class name (namespace.name)
 * @param {_GpfClassDefinition} [superClassDef=undefined] Super class definition
 * @constructor
 */
function _GpfClassDefinition (qName, superClassDef) {
    _gpfAssert(!superClassDef || superClassDef instanceof _GpfClassDefinition, "Expected a _GpfClassDefinition");
    /*jshint validthis:true*/ // constructor
    /*eslint-disable no-invalid-this*/
    this._qName = qName;
    this._members = Object.create(_gpfLinkToSuperClassDef(this, superClassDef));
    /*eslint-enable no-invalid-this*/
}

_GpfClassDefinition.prototype = {

    /** Fully qualified class name */
    _qName: "",

    /** @return {String} Class name */
    getName: function () {
        if (-1 !== this._qName.indexOf(".")) {
            return this._qName.split(".").pop();
        }
        return this._qName;
    },

    /** @return {String} Class namespace */
    getNamespace: function () {
        if (-1 !== this._qName.indexOf(".")) {
            var nameArray = this._qName.split(".");
            nameArray.pop();
            return nameArray.join(".");
        }
        return "";
    },

    /** @return {String} Class qualified name (namespace.name) */
    getQualifiedName: function () {
        return this._qName;
    },

    /**
     * Super class definition
     *
     * @type {_GpfClassDefinition}
     */
    _super: null,

    /** Dictionary of members */
    _members: {},

    /**
     * Get a member by its name
     *
     * @param {String} name Member name
     * @return {_GpfClassDefMember|undefined} Member or undefined if not found
     */
    getMember: function (name) {
        return this._members[name];
    },

    /**
     * Get a member by its name only if it is defined for this class definition
     *
     * @param {String} name Member name
     * @return {_GpfClassDefMember|undefined} Member or undefined if not found
     */
    getOwnMember: function (name) {
        if (this._members.hasOwnProperty(name)) {
            return this._members[name];
        }
    },

    _checkOwnMemberDoesntExist: function (name) {
        if (this._members.hasOwnProperty(name)) {
            throw gpf.Error.classMemberAlreadyExist();
        }
    },

    /**
     * Get the list of member names that were defined / overridden for this class
     *
     * @return {_GpfClassDefMember[]} List of member names
     */
    getOwnMembers: function () {
        var members = this._members;
        return Object.keys(members).map(function (memberName) {
            return members[memberName];
        }, this);
    },

    /**
     * Before adding a member:
     * - Check that it does not already exist for this class definition
     * - If overloading an inherited member, check that it is compatible
     *
     * @param {_GpfClassDefMember} member Member to check
     * @throws {gpf.Error.classMemberAlreadyExist}
     */
    _checkMemberBeforeAdd: function (member) {
        var name = member.getName(),
            existing;
        this._checkOwnMemberDoesntExist(name);
        existing = this._members[name];
        if (existing) {
            existing.checkOverloadedWith(member);
        }
    },

    /**
     * Add a member
     *
     * @param {_GpfClassDefMember} member Member to add
     * @gpf:chainable
     */
    addMember: function (member) {
        _gpfAsserts({
            "Expected a _GpfClassDefMember": member instanceof _GpfClassDefMember,
            "Member is already assigned to a class": null === member._classDef
        });
        this._checkMemberBeforeAdd(member);
        this._members[member.getName()] = member;
        member._classDef = this;
        return this;
    },

    /**
     * Class constructor method
     *
     * @type {Function}
     */
    _constructorMethod: null,

    /**
     * Set the class constructor
     *
     * @param {Function} constructor Constructor function
     */
    setConstructor: function (constructor) {
        _gpfAssert(typeof constructor === "function", "Function expected");
        this._constructorMethod = constructor;
    },

    /**
     * Get the class constructor
     *
     * @return {Function|null} Class constructor if existing
     */
    getConstructor: function () {
        return this._constructorMethod;
    }

};

/*#ifndef(UMD)*/

gpf.internals._GpfClassDefinition = _GpfClassDefinition;

/*#endif*/
<commit_msg>Removes throw<commit_after>/**
 * @file Class definition
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GpfClassDefMember*/ // GPF class member definition
/*global _gpfAssert*/ // Assertion method
/*global _gpfAsserts*/ // Multiple assertion method
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*exported _GpfClassDefinition*/ // GPF class definition
/*#endif*/

_gpfErrorDeclare("define/definition/class", {
    "classMemberAlreadyExist":
        "You can't add a member twice"
});

/**
 * Link the class definition to the super one
 *
 * @param {_GpfClassDefinition} classDef Class definition receiving the link
 * @param {_GpfClassDefinition} [superClassDef=undefined] Class definition to link to
 * @return {Object} Superclass member dictionary if provided or an empty object
 */
function _gpfLinkToSuperClassDef (classDef, superClassDef) {
    if (superClassDef) {
        classDef._super = superClassDef;
        return superClassDef._members;
    }
    return {};
}

/**
 * Class definition
 * - Maintain a flat dictionary of members (using prototype inheritance)
 *
 * @param {String} qName Fully qualified class name (namespace.name)
 * @param {_GpfClassDefinition} [superClassDef=undefined] Super class definition
 * @constructor
 */
function _GpfClassDefinition (qName, superClassDef) {
    _gpfAssert(!superClassDef || superClassDef instanceof _GpfClassDefinition, "Expected a _GpfClassDefinition");
    /*jshint validthis:true*/ // constructor
    /*eslint-disable no-invalid-this*/
    this._qName = qName;
    this._members = Object.create(_gpfLinkToSuperClassDef(this, superClassDef));
    /*eslint-enable no-invalid-this*/
}

_GpfClassDefinition.prototype = {

    /** Fully qualified class name */
    _qName: "",

    /** @return {String} Class name */
    getName: function () {
        if (-1 !== this._qName.indexOf(".")) {
            return this._qName.split(".").pop();
        }
        return this._qName;
    },

    /** @return {String} Class namespace */
    getNamespace: function () {
        if (-1 !== this._qName.indexOf(".")) {
            var nameArray = this._qName.split(".");
            nameArray.pop();
            return nameArray.join(".");
        }
        return "";
    },

    /** @return {String} Class qualified name (namespace.name) */
    getQualifiedName: function () {
        return this._qName;
    },

    /**
     * Super class definition
     *
     * @type {_GpfClassDefinition}
     */
    _super: null,

    /** Dictionary of members */
    _members: {},

    /**
     * Get a member by its name
     *
     * @param {String} name Member name
     * @return {_GpfClassDefMember|undefined} Member or undefined if not found
     */
    getMember: function (name) {
        return this._members[name];
    },

    /**
     * Get a member by its name only if it is defined for this class definition
     *
     * @param {String} name Member name
     * @return {_GpfClassDefMember|undefined} Member or undefined if not found
     */
    getOwnMember: function (name) {
        if (this._members.hasOwnProperty(name)) {
            return this._members[name];
        }
    },

    _checkOwnMemberDoesntExist: function (name) {
        if (this._members.hasOwnProperty(name)) {
            gpf.Error.classMemberAlreadyExist();
        }
    },

    /**
     * Get the list of member names that were defined / overridden for this class
     *
     * @return {_GpfClassDefMember[]} List of member names
     */
    getOwnMembers: function () {
        var members = this._members;
        return Object.keys(members).map(function (memberName) {
            return members[memberName];
        }, this);
    },

    /**
     * Before adding a member:
     * - Check that it does not already exist for this class definition
     * - If overloading an inherited member, check that it is compatible
     *
     * @param {_GpfClassDefMember} member Member to check
     * @throws {gpf.Error.classMemberAlreadyExist}
     */
    _checkMemberBeforeAdd: function (member) {
        var name = member.getName(),
            existing;
        this._checkOwnMemberDoesntExist(name);
        existing = this._members[name];
        if (existing) {
            existing.checkOverloadedWith(member);
        }
    },

    /**
     * Add a member
     *
     * @param {_GpfClassDefMember} member Member to add
     * @gpf:chainable
     */
    addMember: function (member) {
        _gpfAsserts({
            "Expected a _GpfClassDefMember": member instanceof _GpfClassDefMember,
            "Member is already assigned to a class": null === member._classDef
        });
        this._checkMemberBeforeAdd(member);
        this._members[member.getName()] = member;
        member._classDef = this;
        return this;
    },

    /**
     * Class constructor method
     *
     * @type {Function}
     */
    _constructorMethod: null,

    /**
     * Set the class constructor
     *
     * @param {Function} constructor Constructor function
     */
    setConstructor: function (constructor) {
        _gpfAssert(typeof constructor === "function", "Function expected");
        this._constructorMethod = constructor;
    },

    /**
     * Get the class constructor
     *
     * @return {Function|null} Class constructor if existing
     */
    getConstructor: function () {
        return this._constructorMethod;
    }

};

/*#ifndef(UMD)*/

gpf.internals._GpfClassDefinition = _GpfClassDefinition;

/*#endif*/
<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */
"use strict";

/**
 * Register named factories
 * register<<Name>>(Factory)
 * create<<Name>>Instance(name,arg)
 * <<Name>> // lookup
 */
exports.defineRegistrarProperties = function (object, name) {
	const properties = {};

	const ucFirstName = name.charAt(0).toUpperCase() + name.slice(1);
	const pluralLowercaseName = name + "s";
	const eventNameRegistered = pluralLowercaseName + 'Registered';

	const registry = {};

	properties[pluralLowercaseName] = {
		get: function () {
			return registry;
		}
	};

	properties['create' + ucFirstName + 'Instance'] = {
		// TODO use ... if node supports it
		value: function (name, arg1, arg2, arg3) {
			const clazz = registry[name];
			return new clazz(arg1, arg2, arg3);
		}
	};

	properties['register' + ucFirstName] = {
		value: function (toBeRegistered) {
			const name = toBeRegistered.name || toBeRegistered.type;

			if (registry[name]) {
				if (registry[name] === toBeRegistered) {
					return;
				}
			}

			registry[name] = toBeRegistered;
			this.emit(eventNameRegistered, toBeRegistered);
		}
	};

	Object.defineProperties(object, properties);
};

/*
manager.emit('serviceDeleted', serviceName);
*/
<commit_msg>fix: evnet name singular entity<commit_after>/* jslint node: true, esnext: true */
"use strict";

/**
 * Register named factories
 * register<<Name>>(Factory)
 * create<<Name>>Instance(name,arg)
 * <<Name>> // lookup
 */
exports.defineRegistrarProperties = function (object, name) {
	const properties = {};

	const ucFirstName = name.charAt(0).toUpperCase() + name.slice(1);
	const pluralLowercaseName = name + "s";
	const eventNameRegistered = name + 'Registered';

	const registry = {};

	properties[pluralLowercaseName] = {
		get: function () {
			return registry;
		}
	};

	properties['create' + ucFirstName + 'Instance'] = {
		// TODO use ... if node supports it
		value: function (name, arg1, arg2, arg3) {
			const clazz = registry[name];
			return new clazz(arg1, arg2, arg3);
		}
	};

	properties['register' + ucFirstName] = {
		value: function (toBeRegistered) {
			const name = toBeRegistered.name || toBeRegistered.type;

			if (registry[name]) {
				if (registry[name] === toBeRegistered) {
					return;
				}
			}

			registry[name] = toBeRegistered;

			this.emit(eventNameRegistered, toBeRegistered);
		}
	};

	Object.defineProperties(object, properties);
};

/*
manager.emit('serviceDeleted', serviceName);
*/
<|endoftext|>


<commit_before>'use strict';

/*
	Tempmon
*/
function Tempmon( canvas, deviceID, initialDate )
{
	if ( !initialDate )
		initialDate = new Date();

	var initialWidth = 100 * GraphDataFetcher._messageIntervalMs;
	var initialX = initialDate.getTime() - (initialWidth/2);

	// The object that knows how to get data from SigFox backend
	this._graphDataFetcher = new GraphDataFetcher(deviceID, 100, initialX+initialWidth/2);

	// The type of graph data currently being displayed
	this._graphDataType = 'temperature';

	// The graph data window used to render the graph
	this._graphDataWindow = {
		x: initialX,
		y: -5,
		width: initialWidth,
		height: 40
	};

	// The backed-up graph data windows for each type of data
	this._graphDataWindows = {
		'temperature' : {
			x: initialX,
			y: -5,
			width: initialWidth,
			height: 40
		},
		'humidity' : {
			x: initialX,
			y: -10,
			width: initialWidth,
			height: 120
		},
		'pressure' : {
			x: initialX,
			y: 950,
			width: initialWidth,
			height: 150							// When height is perfectly 100, I've got flickering on the Y lines
		}
	};

	// The graph option used for rendering
	this._graphOptions = {
		yPropertyName: this._graphDataType,
		clearCanvas: true,
		drawOriginAxes: true,
		drawDataRange: true,
		drawDataGaps: true,
		contiguityThreshold: GraphDataFetcher._messageIntervalMs*1.02,
		textSize: 12,
		numMaxLinesX: 5,
		numMaxLinesY: 5,
		getPrimaryLinesTextX: GraphDataPresenter.getLinesTextForTime,
		getPrimaryLinesSpacingX: GraphDataPresenter.getPrimaryLinesSpacingForTime,
		getSecondaryLinesSpacingX: GraphDataPresenter.getSecondaryLinesSpacingForTime,
		getPrimaryLinesTextY: GraphDataPresenter.getLinesText,
		getPrimaryLinesSpacingY: GraphDataPresenter.getLinesSpacing,
		getSecondaryLinesSpacingY: GraphDataPresenter.getSecondaryLinesSpacing,
		points: {
			//typicalDataPointXSpacing: 10*60*1000,		// No need if we provide a contiguityThreshold
			maxPointSize: 5,
			maxNumPoints: 500,
		}
		/*colors: {
			clear:'#FFFFFF',
			dataRange: "#EEEEEE",
			dataGaps: "#EEEEEE",
			axesLines: "#AA6666",
			primaryLinesText: '#AA6666',
			primaryLines: '#FFAAAA',
			secondaryLines: '#FFDDDD',
			dataLine: "#884444",
			dataPoint: "#884444",
		},*/
	};

	// The graph controller is responsible for rendering the graph and handling input events to navigate in it
	this._graphController = new GraphController( canvas, this._graphDataFetcher._graphData, this._graphDataWindow, this._graphOptions );

	// When the user navigates in the graph (i.e. changes the graph data window), we need to check whether more data needs to be fetched
	this._graphController._onGraphDataWindowChange = this._onGraphDataWindowChange.bind(this);

	// Whenever the window resizes, we need to recalculate a few graph options to adjust to the new size
	window.addEventListener( "resize", this._onResize.bind(this) );

	this._onGraphDataTypeChanged = null;
	this._onAutoscrollChanged = null;

	this._forwardFetchTimeout = null;

	// Initialize for current size
	this._onResize();

	// Start fetching some data
	this._onGraphDataWindowChange();

	this._forwardFetchInterval = setInterval(
		function()
		{
			if ( !this._graphDataFetcher.isFetching() )
			{
				this._fetchDataIfNeeded()
			};
		}.bind(this),
		10 * 1000 );
}

Tempmon.prototype.setGraphDataType = function( graphDataType )
{
	if ( graphDataType===this._graphDataType )
		return;

	this._graphDataWindows[this._graphDataType].y = this._graphDataWindow.y;
	this._graphDataWindows[this._graphDataType].height = this._graphDataWindow.height;

	var prevGraphDataType = this._graphDataType;
	this._graphDataType = graphDataType;

	this._graphDataWindow.y = this._graphDataWindows[this._graphDataType].y;
	this._graphDataWindow.height = this._graphDataWindows[this._graphDataType].height;

	this._graphOptions.yPropertyName = this._graphDataType;
	this._graphController.render();

	if ( this._onGraphDataTypeChanged )
		this._onGraphDataTypeChanged( prevGraphDataType, this._graphDataType );
};

Tempmon.prototype.setAutoscroll = function( autoscroll )
{
	if ( this._autoscroll===autoscroll )
		return;

	this._autoscroll = autoscroll;

	if ( this._autoscroll )
	{
		var graphData = this._graphDataFetcher._graphData;
		if ( graphData.length>0 )
		{
			var lastDataPoint = graphData[0];
			this._graphDataWindow.x = lastDataPoint.x - this._graphDataWindow.width;
			this._graphController.render();
		}
	}

	if ( this._onAutoscrollChanged )
		this._onAutoscrollChanged();
};

Tempmon.prototype.getAutoscroll = function()
{
	return this._autoscroll;
};

Tempmon.prototype._fetchDataIfNeeded = function()
{
	//console.log("_fetchDataIfNeeded");
	var graphDataFetcher = this._graphDataFetcher;

	if ( graphDataFetcher.isFetching() )
		return Promise.reject();

	var promise = null;

	// Is it the first fetch ever?
	if ( graphDataFetcher._xmin===null || graphDataFetcher._xmax===null )
	{
		// This is the first data fetch, use forward fetch
		promise = graphDataFetcher.fetchDataForward();
	}

	// Do we need to fetch data forward based on current graph data window?
	if ( !promise && this._graphDataWindow.x+this._graphDataWindow.width>graphDataFetcher._xmax )
	{
		var now = new Date().getTime();
		var expectedNumberOfMessagesReadyForFetch = Math.floor( (now - graphDataFetcher._xmax) / (GraphDataFetcher._messageIntervalMs*1.02) );
		if ( expectedNumberOfMessagesReadyForFetch>0 )
		{
			promise = graphDataFetcher.fetchDataForward();
		}
		else
		{
			// There's most probably no new message to fetch yet
		}
	}

	// Do we need to fetch data backward based on current graph data window?
	if ( !promise && this._graphDataWindow.x<graphDataFetcher._xmin && !graphDataFetcher.xminFinalReached() )
	{
		promise = graphDataFetcher.fetchDataBackward();
	}

	if ( promise )
	{
		promise = promise
			.then(
				function()
				{
					this._graphController.render();
					return this._fetchDataIfNeeded();
				}.bind(this))
			.catch(
				function( error )
				{
					alert( error.toString() );
				}.bind(this));
	}
	else
	{
		promise = Promise.resolve();
	}

	return promise;
};

Tempmon.prototype._onGraphDataWindowChange = function()
{
	if ( !this._graphDataFetcher.isFetching() )
	{
		this._fetchDataIfNeeded();
	};

	this.setAutoscroll( false );
};

Tempmon.prototype._onRendered = function()
{
};

Tempmon.prototype._onResize = function( event )
{
	this._updateLinesOptions();
	this._updatePointsOptions();
	this._graphController.render();
};

Tempmon.prototype._updateLinesOptions = function()
{
	var canvas = this._graphController._canvas;
	var width = canvas.clientWidth;
	var height = canvas.clientHeight;

	var textSize = this._graphOptions.textSize;

	// Calculate a decent max number of grid lines along the x axis based
	// on an average text/label width in pixels (itself calculated from font size)
	var averageCharWidth = textSize * 0.5;
	var maxTextWidth = averageCharWidth * 22 + 4;		// Include a few more pixels as a margin
	var numMaxLinesX = Math.floor( width / maxTextWidth );
	if ( numMaxLinesX<1 )
		numMaxLinesX = 1;

	// Based on the aspect ratio of the canvas and max number of lines on X,
	// we calculate a max number of linex on the Y axis so it looks balanced
	var numMaxLinesY = Math.floor( height / (maxTextWidth*0.7) );		// We can fit more y-lines than x-lines hence the 0.7 factor

	this._graphOptions.numMaxLinesX = numMaxLinesX;
	this._graphOptions.numMaxLinesY = numMaxLinesY;
};

Tempmon.prototype._updatePointsOptions = function()
{
	var canvas = this._graphController._canvas;
	var width = canvas.clientWidth;
	this._graphOptions.points.maxNumPoints = Math.trunc( width * 0.3 );
};
<commit_msg>Made autoscroll happens when new data arrives<commit_after>'use strict';

/*
	Tempmon
*/
function Tempmon( canvas, deviceID, initialDate )
{
	if ( !initialDate )
		initialDate = new Date();

	var initialWidth = 100 * GraphDataFetcher._messageIntervalMs;
	var initialX = initialDate.getTime() - (initialWidth/2);

	// The object that knows how to get data from SigFox backend
	this._graphDataFetcher = new GraphDataFetcher(deviceID, 100, initialX+initialWidth/2);

	// The type of graph data currently being displayed
	this._graphDataType = 'temperature';

	// The graph data window used to render the graph
	this._graphDataWindow = {
		x: initialX,
		y: -5,
		width: initialWidth,
		height: 40
	};

	// The backed-up graph data windows for each type of data
	this._graphDataWindows = {
		'temperature' : {
			x: initialX,
			y: -5,
			width: initialWidth,
			height: 40
		},
		'humidity' : {
			x: initialX,
			y: -10,
			width: initialWidth,
			height: 120
		},
		'pressure' : {
			x: initialX,
			y: 950,
			width: initialWidth,
			height: 150							// When height is perfectly 100, I've got flickering on the Y lines
		}
	};

	// The graph option used for rendering
	this._graphOptions = {
		yPropertyName: this._graphDataType,
		clearCanvas: true,
		drawOriginAxes: true,
		drawDataRange: true,
		drawDataGaps: true,
		contiguityThreshold: GraphDataFetcher._messageIntervalMs*1.02,
		textSize: 12,
		numMaxLinesX: 5,
		numMaxLinesY: 5,
		getPrimaryLinesTextX: GraphDataPresenter.getLinesTextForTime,
		getPrimaryLinesSpacingX: GraphDataPresenter.getPrimaryLinesSpacingForTime,
		getSecondaryLinesSpacingX: GraphDataPresenter.getSecondaryLinesSpacingForTime,
		getPrimaryLinesTextY: GraphDataPresenter.getLinesText,
		getPrimaryLinesSpacingY: GraphDataPresenter.getLinesSpacing,
		getSecondaryLinesSpacingY: GraphDataPresenter.getSecondaryLinesSpacing,
		points: {
			//typicalDataPointXSpacing: 10*60*1000,		// No need if we provide a contiguityThreshold
			maxPointSize: 5,
			maxNumPoints: 500,
		}
		/*colors: {
			clear:'#FFFFFF',
			dataRange: "#EEEEEE",
			dataGaps: "#EEEEEE",
			axesLines: "#AA6666",
			primaryLinesText: '#AA6666',
			primaryLines: '#FFAAAA',
			secondaryLines: '#FFDDDD',
			dataLine: "#884444",
			dataPoint: "#884444",
		},*/
	};

	// The graph controller is responsible for rendering the graph and handling input events to navigate in it
	this._graphController = new GraphController( canvas, this._graphDataFetcher._graphData, this._graphDataWindow, this._graphOptions );

	// When the user navigates in the graph (i.e. changes the graph data window), we need to check whether more data needs to be fetched
	this._graphController._onGraphDataWindowChange = this._onGraphDataWindowChange.bind(this);

	// Whenever the window resizes, we need to recalculate a few graph options to adjust to the new size
	window.addEventListener( "resize", this._onResize.bind(this) );

	this._onGraphDataTypeChanged = null;
	this._onAutoscrollChanged = null;

	this._forwardFetchTimeout = null;

	// Initialize for current size
	this._onResize();

	// Start fetching some data
	this._onGraphDataWindowChange();

	this._forwardFetchInterval = setInterval(
		function()
		{
			if ( !this._graphDataFetcher.isFetching() )
			{
				this._fetchDataIfNeeded()
			};
		}.bind(this),
		10 * 1000 );
}

Tempmon.prototype.setGraphDataType = function( graphDataType )
{
	if ( graphDataType===this._graphDataType )
		return;

	this._graphDataWindows[this._graphDataType].y = this._graphDataWindow.y;
	this._graphDataWindows[this._graphDataType].height = this._graphDataWindow.height;

	var prevGraphDataType = this._graphDataType;
	this._graphDataType = graphDataType;

	this._graphDataWindow.y = this._graphDataWindows[this._graphDataType].y;
	this._graphDataWindow.height = this._graphDataWindows[this._graphDataType].height;

	this._graphOptions.yPropertyName = this._graphDataType;
	this._graphController.render();

	if ( this._onGraphDataTypeChanged )
		this._onGraphDataTypeChanged( prevGraphDataType, this._graphDataType );
};

Tempmon.prototype.setAutoscroll = function( autoscroll )
{
	if ( this._autoscroll===autoscroll )
		return;

	this._autoscroll = autoscroll;

	if ( this._autoscroll )
	{
		this._scrollToLatestData();
		this._graphController.render();
	}

	if ( this._onAutoscrollChanged )
		this._onAutoscrollChanged();
};

Tempmon.prototype.getAutoscroll = function()
{
	return this._autoscroll;
};

// Change the x position of the graph data window to show the latest data points.
// This method doesn't affect the other graph data window properties.
Tempmon.prototype._scrollToLatestData = function()
{
	var graphData = this._graphDataFetcher._graphData;
	if ( graphData.length===0 )
		return;

	var latestDataPoint = graphData[0];
	this._graphDataWindow.x = latestDataPoint.x - this._graphDataWindow.width;
};

Tempmon.prototype._fetchDataIfNeeded = function()
{
	//console.log("_fetchDataIfNeeded");
	var graphDataFetcher = this._graphDataFetcher;

	if ( graphDataFetcher.isFetching() )
		return Promise.reject();

	var promise = null;

	// Is it the first fetch ever?
	if ( graphDataFetcher._xmin===null || graphDataFetcher._xmax===null )
	{
		// This is the first data fetch, use forward fetch
		promise = graphDataFetcher.fetchDataForward();
	}

	// Do we need to fetch data forward based on current graph data window?
	if ( !promise && this._graphDataWindow.x+this._graphDataWindow.width>graphDataFetcher._xmax )
	{
		var now = new Date().getTime();
		var expectedNumberOfMessagesReadyForFetch = Math.floor( (now - graphDataFetcher._xmax) / (GraphDataFetcher._messageIntervalMs*1.02) );
		if ( expectedNumberOfMessagesReadyForFetch>0 )
		{
			promise = graphDataFetcher.fetchDataForward();
		}
		else
		{
			// There's most probably no new message to fetch yet
		}
	}

	// Do we need to fetch data backward based on current graph data window?
	if ( !promise && this._graphDataWindow.x<graphDataFetcher._xmin && !graphDataFetcher.xminFinalReached() )
	{
		promise = graphDataFetcher.fetchDataBackward();
	}

	if ( promise )
	{
		promise = promise
			.then(
				function()
				{
					if ( this._autoscroll )
						this._scrollToLatestData();
					this._graphController.render();
					return this._fetchDataIfNeeded();
				}.bind(this))
			.catch(
				function( error )
				{
					alert( error.toString() );
				}.bind(this));
	}
	else
	{
		promise = Promise.resolve();
	}

	return promise;
};

Tempmon.prototype._onGraphDataWindowChange = function()
{
	if ( !this._graphDataFetcher.isFetching() )
	{
		this._fetchDataIfNeeded();
	};

	this.setAutoscroll( false );
};

Tempmon.prototype._onRendered = function()
{
};

Tempmon.prototype._onResize = function( event )
{
	this._updateLinesOptions();
	this._updatePointsOptions();
	this._graphController.render();
};

Tempmon.prototype._updateLinesOptions = function()
{
	var canvas = this._graphController._canvas;
	var width = canvas.clientWidth;
	var height = canvas.clientHeight;

	var textSize = this._graphOptions.textSize;

	// Calculate a decent max number of grid lines along the x axis based
	// on an average text/label width in pixels (itself calculated from font size)
	var averageCharWidth = textSize * 0.5;
	var maxTextWidth = averageCharWidth * 22 + 4;		// Include a few more pixels as a margin
	var numMaxLinesX = Math.floor( width / maxTextWidth );
	if ( numMaxLinesX<1 )
		numMaxLinesX = 1;

	// Based on the aspect ratio of the canvas and max number of lines on X,
	// we calculate a max number of linex on the Y axis so it looks balanced
	var numMaxLinesY = Math.floor( height / (maxTextWidth*0.7) );		// We can fit more y-lines than x-lines hence the 0.7 factor

	this._graphOptions.numMaxLinesX = numMaxLinesX;
	this._graphOptions.numMaxLinesY = numMaxLinesY;
};

Tempmon.prototype._updatePointsOptions = function()
{
	var canvas = this._graphController._canvas;
	var width = canvas.clientWidth;
	this._graphOptions.points.maxNumPoints = Math.trunc( width * 0.3 );
};
<|endoftext|>


<commit_before>export default {
  bind(_el, _, { context: $vue }) {
    const el = _el;

    el.addEventListener('keydown', (e) => {
      const { key } = e;

      if (typeof key === 'undefined') return;

      if (key === '#') {
        const { value: content, selectionStart: caret } = el;

        if (content.substring(caret - 1, caret) !== '\\') {
          e.preventDefault();
          $vue.$_eventBus.$emit('addTag');
        }
      }
    });

    el.addEventListener('keyup', ({ key }) => {
      if (typeof key === 'undefined') return;

      el.value = el.value
        .replace(/\\\\#/, '\\#') // \<ZERO WIDTH SPACE\u200b>#
        .replace(/\\#/, '#');

      el.dispatchEvent(new Event('input')); // Force Vuex update
    });
  },
};
<commit_msg>Disable `add tag` shortcut on mobile<commit_after>import detectIt from 'detect-it';

const { deviceType } = detectIt;

export default {
  bind(_el, _, { context: $vue }) {
    const el = _el;

    el.addEventListener('keydown', (e) => {
      const { key } = e;

      if (deviceType === 'touchOnly') return;

      if (key === '#') {
        const { value: content, selectionStart: caret } = el;

        if (content.substring(caret - 1, caret) !== '\\') {
          e.preventDefault();
          $vue.$_eventBus.$emit('addTag');
        }
      }
    });

    el.addEventListener('keyup', () => {
      if (deviceType === 'touchOnly') return;

      el.value = el.value
        .replace(/\\\\#/, '\\#') // \<ZERO WIDTH SPACE\u200b>#
        .replace(/\\#/, '#');

      el.dispatchEvent(new Event('input')); // Force Vuex update
    });
  },
};
<|endoftext|>