<commit_before>var keys = require('./keys');

var Input = function(game, container) {
  this._container = container;
  this._keys = {};

  this.canControlKeys = true;

  this.mouse = {
    isDown: false,
    isLeftDown: false,
    isMiddleDown: false,
    isRightDown: false,
    x: null,
    y: null
  };

  this._addEvents(game);
};

Input.prototype.resetKeys = function() {
  this._keys = {};
};

Input.prototype.isKeyDown = function(key) {
  if (key == null) { return false; }

  if (this.canControlKeys) {
    var code = typeof key === 'number' ? key : keys[key.toUpperCase()];
    return this._keys[code];
  }
};

Input.prototype._addEvents = function(game) {
  var self = this;

  self._container.addEventListener('mousemove', function(e) {
    var x = e.offsetX === undefined ? e.layerX - self._container.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - self._container.offsetTop : e.offsetY;

    self.mouse.x = x;
    self.mouse.y = y;

    game.states.mousemove(x, y, e);
  });

  self._container.addEventListener('mouseup', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - self._container.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - self._container.offsetTop : e.offsetY;

    self.mouse.isDown = false;

    switch (e.button) {
      case 0:
        self.mouse.isLeftDown = false;
      break;
      case 1:
        self.mouse.isMiddleDown = false;
        break;
      case 2:
        self.mouse.isRightDown = false;
        break;
    }

    game.states.mouseup(x, y, e.button);
  }, false);

  self._container.addEventListener('mousedown', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - self._container.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - self._container.offsetTop : e.offsetY;

    self.mouse.x = x;
    self.mouse.y = y;
    self.mouse.isDown = true;

    switch (e.button) {
      case 0:
        self.mouse.isLeftDown = true;
      break;
      case 1:
        self.mouse.isMiddleDown = true;
        break;
      case 2:
        self.mouse.isRightDown = true;
        break;
    }

    game.states.mousedown(x, y, e.button);
  }, false);

  self._container.addEventListener('touchstart', function(e) {
    e.preventDefault();

    for (var i=0; i<e.touches.length; i++) {
      var touch = e.touches[i];

      var x = touch.pageX - self._container.offsetLeft;
      var y = touch.pageY - self._container.offsetTop;

      self.mouse.x = x;
      self.mouse.y = y;
      self.mouse.isDown = true;
      self.mouse.isLeftDown = true;

      game.states.mousedown(x, y, 1);
    }
  });

  self._container.addEventListener('touchmove', function(e) {
    e.preventDefault();

    for (var i=0; i<e.touches.length; i++) {
      var touch = e.touches[i];

      var x = touch.pageX - self._container.offsetLeft;
      var y = touch.pageY - self._container.offsetTop;

      self.mouse.x = x;
      self.mouse.y = y;
      self.mouse.isDown = true;
      self.mouse.isLeftDown = true;

      game.states.mousemove(x, y);
    }
  });

  self._container.addEventListener('touchend', function(e) {
    e.preventDefault();

    var touch = e.changedTouches[0];

    var x = touch.pageX - self._container.offsetLeft;
    var y = touch.pageY - self._container.offsetTop;

    self.mouse.x = x;
    self.mouse.y = y;
    self.mouse.isDown = false;
    self.mouse.isLeftDown = false;

    game.states.mouseup(x, y, 1);
  });

  self._container.addEventListener('contextmenu', function(e) {
    e.preventDefault();
  });

  document.addEventListener('keydown', function(e) {
    self._keys[e.keyCode] = true;
    game.states.keydown(e.which, e);
  });

  document.addEventListener('keyup', function(e) {
    self._keys[e.keyCode] = false;
    game.states.keyup(e.which, e);
  });
};

module.exports = Input;
<commit_msg>call events with one object, not with multiple arg<commit_after>var keys = require('./keys');

var Input = function(game, container) {
  this._container = container;
  this._keys = {};

  this.canControlKeys = true;

  this.mouse = {
    isDown: false,
    isLeftDown: false,
    isMiddleDown: false,
    isRightDown: false,
    x: null,
    y: null
  };

  this._addEvents(game);
};

Input.prototype.resetKeys = function() {
  this._keys = {};
};

Input.prototype.isKeyDown = function(key) {
  if (key == null) { return false; }

  if (this.canControlKeys) {
    var code = typeof key === 'number' ? key : keys[key.toUpperCase()];
    return this._keys[code];
  }
};

Input.prototype._addEvents = function(game) {
  var self = this;

  var mouseEvent = {
    x: null,
    y: null,
    button: null,
    event: null
  };

  var keyboardEvent = {
    key: null,
    name: null,
    event: null
  };

  self._container.addEventListener('mousemove', function(e) {
    var x = e.offsetX === undefined ? e.layerX - self._container.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - self._container.offsetTop : e.offsetY;

    self.mouse.x = x;
    self.mouse.y = y;

    mouseEvent.x = x;
    mouseEvent.y = y;
    mouseEvent.button = null;
    mouseEvent.event = e;

    game.states.mousemove(mouseEvent);
  });

  self._container.addEventListener('mouseup', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - self._container.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - self._container.offsetTop : e.offsetY;

    self.mouse.isDown = false;

    switch (e.button) {
      case 0:
        self.mouse.isLeftDown = false;
      break;
      case 1:
        self.mouse.isMiddleDown = false;
        break;
      case 2:
        self.mouse.isRightDown = false;
        break;
    }

    mouseEvent.x = x;
    mouseEvent.y = y;
    mouseEvent.button = e.button;
    mouseEvent.event = e;

    game.states.mouseup(mouseEvent);
  }, false);

  self._container.addEventListener('mousedown', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - self._container.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - self._container.offsetTop : e.offsetY;

    self.mouse.x = x;
    self.mouse.y = y;
    self.mouse.isDown = true;

    switch (e.button) {
      case 0:
        self.mouse.isLeftDown = true;
      break;
      case 1:
        self.mouse.isMiddleDown = true;
        break;
      case 2:
        self.mouse.isRightDown = true;
        break;
    }

    mouseEvent.x = x;
    mouseEvent.y = y;
    mouseEvent.button = e.button;
    mouseEvent.event = e;

    game.states.mousedown(mouseEvent);
  }, false);

  self._container.addEventListener('touchstart', function(e) {
    e.preventDefault();

    for (var i=0; i<e.touches.length; i++) {
      var touch = e.touches[i];

      var x = touch.pageX - self._container.offsetLeft;
      var y = touch.pageY - self._container.offsetTop;

      self.mouse.x = x;
      self.mouse.y = y;
      self.mouse.isDown = true;
      self.mouse.isLeftDown = true;

      mouseEvent.x = x;
      mouseEvent.y = y;
      mouseEvent.button = 1;
      mouseEvent.event = e;

      game.states.mousedown(e);
    }
  });

  self._container.addEventListener('touchmove', function(e) {
    e.preventDefault();

    for (var i=0; i<e.touches.length; i++) {
      var touch = e.touches[i];

      var x = touch.pageX - self._container.offsetLeft;
      var y = touch.pageY - self._container.offsetTop;

      self.mouse.x = x;
      self.mouse.y = y;
      self.mouse.isDown = true;
      self.mouse.isLeftDown = true;

      mouseEvent.x = x;
      mouseEvent.y = y;
      mouseEvent.event = e;

      game.states.mousemove(e);
    }
  });

  self._container.addEventListener('touchend', function(e) {
    e.preventDefault();

    var touch = e.changedTouches[0];

    var x = touch.pageX - self._container.offsetLeft;
    var y = touch.pageY - self._container.offsetTop;

    self.mouse.x = x;
    self.mouse.y = y;
    self.mouse.isDown = false;
    self.mouse.isLeftDown = false;

    mouseEvent.x = x;
    mouseEvent.y = y;
    mouseEvent.event = e;

    game.states.mouseup(e);
  });

  self._container.addEventListener('contextmenu', function(e) {
    e.preventDefault();
  });

  document.addEventListener('keydown', function(e) {
    self._keys[e.keyCode] = true;

    keyboardEvent.key = e.which;
    keyboardEvent.event = e;

    game.states.keydown(keyboardEvent);
  });

  document.addEventListener('keyup', function(e) {
    self._keys[e.keyCode] = false;

    keyboardEvent.key = e.which;
    keyboardEvent.event = e;

    game.states.keyup(keyboardEvent);
  });
};

module.exports = Input;
<|endoftext|>


<commit_before>"use strict";
angular.module('jtt_aping')

    .config(['$provide', function ($provide) {
        $provide.value("apingDefaultSettings", {
            apingApiKeys: {}
        });
    }])
    .value("apingResults", {})
    .directive('aping', ['apingResults', 'apingDefaultSettings', 'apingUtilityHelper', '$templateRequest', '$compile', function (apingResults, apingDefaultSettings, apingUtilityHelper, $templateRequest, $compile) {
        return {
            restrict: 'E',
            transclude: true,
            template: '<ng-transclude></ng-transclude>',
            scope: {
                model: '@',
                getNativeData: '@',
                items: '@',
                maxItems: '@',
                orderBy: '@',
                orderReverse: '@',
                templateUrl: '@',
                payloadJson: '@',
                removeDoubles: '@',
                mergeDoubles: '@',
                idBy: '@',
                resultProperty: '@',
                valueName: '@'
            },
            link: function (scope, element, attrs, controller, transcludeFn) {

                var templatePath = scope.templateUrl;

                scope.$watch('templateUrl', function () {
                    renderTemplate(scope.templateUrl);
                });

                if (angular.isUndefined(templatePath)) {
                    if (angular.isDefined(apingDefaultSettings.templateUrl)) {
                        templatePath = apingDefaultSettings.templateUrl;
                        renderTemplate(templatePath);
                    }
                }

                function renderTemplate(_templatePath) {
                    if (angular.isDefined(_templatePath) && _templatePath !== "$NONE") {
                        $templateRequest(_templatePath).then(function (html) {
                            var template = angular.element(html);
                            element.empty().append(template);
                            $compile(template)(scope);
                        });
                    } else {
                        transcludeFn(scope, function (clone, innerScope) {
                            element.html("");
                            element.append(clone);
                            $compile(clone)(innerScope);
                        });
                    }
                    scope.$broadcast('apiNG.templateRendered');
                }
            },
            controller: ['$scope', function ($scope) {

                if (angular.isUndefined($scope.resultProperty)) {
                    $scope.resultProperty = "results";
                }

                $scope[$scope.resultProperty] = [];
                $scope.payload = $scope.payloadJson ? apingUtilityHelper.replaceSingleQuotesAndParseJson($scope.payloadJson) : {};

                /**
                 * return current appSettings by merging 'apingDefaultSettings' and '$scope params'
                 * @returns {Object}
                 */
                this.getAppSettings = function () {

                    var items;
                    var maxItems;
                    var getNativeData;
                    var orderReverse;
                    var orderBy;
                    var removeDoubles;
                    var mergeDoubles;
                    var valueName;
                    var idBy;

                    if (angular.isDefined($scope.valueName)) {
                        valueName = $scope.valueName;
                    } else {
                        valueName = undefined;
                    }

                    if (angular.isDefined($scope.items)) {
                        items = $scope.items;
                    } else if (angular.isDefined(apingDefaultSettings.items)) {
                        items = apingDefaultSettings.items;
                    } else {
                        items = undefined;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.getNativeData)) {
                        getNativeData = $scope.getNativeData;
                    } else if (angular.isDefined(apingDefaultSettings.getNativeData)) {
                        getNativeData = apingDefaultSettings.getNativeData;
                    } else {
                        getNativeData = false;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.orderBy)) {
                        orderBy = $scope.orderBy;
                    } else if (angular.isDefined(apingDefaultSettings.orderBy)) {
                        orderBy = apingDefaultSettings.orderBy;
                    } else {
                        orderBy = undefined;
                    }

                    if (angular.isDefined($scope.orderReverse)) {
                        orderReverse = $scope.orderReverse;
                    } else if (angular.isDefined(apingDefaultSettings.orderReverse)) {
                        orderReverse = apingDefaultSettings.orderReverse;
                    } else {
                        orderReverse = false;
                    }

                    if (angular.isDefined($scope.removeDoubles)) {
                        removeDoubles = $scope.removeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.removeDoubles)) {
                        removeDoubles = apingDefaultSettings.removeDoubles;
                    } else {
                        removeDoubles = false;
                    }

                    if (angular.isDefined($scope.mergeDoubles)) {
                        mergeDoubles = $scope.mergeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.mergeDoubles)) {
                        mergeDoubles = apingDefaultSettings.mergeDoubles;
                    } else {
                        mergeDoubles = false;
                    }

                    if (angular.isDefined($scope.idBy)) {
                        idBy = $scope.idBy;
                    } else if (angular.isDefined(apingDefaultSettings.idBy)) {
                        idBy = apingDefaultSettings.idBy;
                    } else {
                        idBy = undefined;
                    }

                    return {
                        model: $scope.model || apingDefaultSettings.model || "native",
                        getNativeData: getNativeData,
                        items: items,
                        maxItems: maxItems,
                        orderBy: orderBy,
                        orderReverse: orderReverse,
                        removeDoubles: removeDoubles,
                        mergeDoubles: mergeDoubles,
                        idBy: idBy,
                        valueName: valueName
                    };
                };

                /**
                 * merge current '$scope.results' with '_array' and sorts, limits and filters the data
                 *
                 * @param _array
                 */
                this.concatToResults = function (_array) {
                    if (angular.isUndefined($scope.resultProperty)) {
                        $scope.resultProperty = "results";
                    }

                    var tempArray = $scope[$scope.resultProperty].concat(_array);

                    var appSettings = this.getAppSettings();

                    if (angular.isDefined(appSettings.idBy)) {
                        tempArray = apingUtilityHelper.createIdByPropertiesForArray(tempArray, appSettings.idBy);
                        if (appSettings.mergeDoubles === true || appSettings.mergeDoubles === "true") {
                            tempArray = apingUtilityHelper.mergeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE")
                            );
                        }
                    }

                    //remove doubles
                    if (appSettings.removeDoubles === true || appSettings.removeDoubles === "true") {
                        if (appSettings.mergeDoubles !== true && appSettings.mergeDoubles !== "true") {
                            tempArray = apingUtilityHelper.removeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE"),
                                angular.isDefined(appSettings.idBy)
                            );
                        }
                    }

                    //order array
                    if (angular.isDefined(appSettings.orderBy) && appSettings.orderBy !== false && appSettings.orderBy !== "false" && appSettings.orderBy !== "$NONE") {
                        //order random
                        if (appSettings.orderBy === "$RANDOM") {
                            tempArray = apingUtilityHelper.shuffleArray(tempArray);
                        }
                        //order by attribute
                        else {
                            tempArray.sort(apingUtilityHelper.sortArrayByProperty(appSettings.orderBy));
                        }
                    }

                    //order reverse
                    if ((appSettings.orderReverse === true || appSettings.orderReverse === "true") && appSettings.orderBy !== "$RANDOM") {
                        tempArray.reverse();
                    }

                    //crop spare
                    if (appSettings.maxItems > -1 && tempArray.length > appSettings.maxItems) {
                        tempArray = tempArray.splice(0, appSettings.maxItems);
                    }

                    if (angular.isDefined(appSettings.valueName)) {
                        apingResults[appSettings.valueName] = tempArray;
                    }

                    $scope[$scope.resultProperty] = tempArray;

                    $scope.$broadcast('apiNG.resultMerged', {'resultProperty': $scope.resultProperty});
                };
                this.apply = function () {
                    $scope.$apply();
                };
            }]
        };
    }]);<commit_msg>added "resultName" instead of "resultProperty"<commit_after>"use strict";
angular.module('jtt_aping')
    .config(['$provide', function ($provide) {
        $provide.value("apingDefaultSettings", {
            apingApiKeys: {}
        });
    }])
    .value("apingResults", {})
    .directive('aping', ['apingResults', 'apingDefaultSettings', 'apingUtilityHelper', '$templateRequest', '$compile', function (apingResults, apingDefaultSettings, apingUtilityHelper, $templateRequest, $compile) {
        return {
            restrict: 'E',
            transclude: true,
            template: '<ng-transclude></ng-transclude>',
            scope: {
                model: '@',
                getNativeData: '@',
                items: '@',
                maxItems: '@',
                orderBy: '@',
                orderReverse: '@',
                templateUrl: '@',
                payloadJson: '@',
                removeDoubles: '@',
                mergeDoubles: '@',
                idBy: '@',
                resultProperty: '@', // legacy
                resultName: '@',
                valueName: '@'
            },
            link: function (scope, element, attrs, controller, transcludeFn) {

                var templatePath = scope.templateUrl;

                scope.$watch('templateUrl', function () {
                    renderTemplate(scope.templateUrl);
                });

                if (angular.isUndefined(templatePath)) {
                    if (angular.isDefined(apingDefaultSettings.templateUrl)) {
                        templatePath = apingDefaultSettings.templateUrl;
                        renderTemplate(templatePath);
                    }
                }

                function renderTemplate(_templatePath) {
                    if (angular.isDefined(_templatePath) && _templatePath !== "$NONE") {
                        $templateRequest(_templatePath).then(function (html) {
                            var template = angular.element(html);
                            element.empty().append(template);
                            $compile(template)(scope);
                        });
                    } else {
                        transcludeFn(scope, function (clone, innerScope) {
                            element.html("");
                            element.append(clone);
                            $compile(clone)(innerScope);
                        });
                    }
                    scope.$broadcast('apiNG.templateRendered');
                }
            },
            controller: ['$scope', function ($scope) {

                if(angular.isUndefined($scope.resultName)) {
                    if (angular.isUndefined($scope.resultProperty)) {
                        $scope.resultName = "results";
                    } else {
                        $scope.resultName = $scope.resultProperty;
                    }
                }

                $scope[$scope.resultName] = [];
                $scope.payload = $scope.payloadJson ? apingUtilityHelper.replaceSingleQuotesAndParseJson($scope.payloadJson) : {};

                /**
                 * return current appSettings by merging 'apingDefaultSettings' and '$scope params'
                 * @returns {Object}
                 */
                this.getAppSettings = function () {

                    var items;
                    var maxItems;
                    var getNativeData;
                    var orderReverse;
                    var orderBy;
                    var removeDoubles;
                    var mergeDoubles;
                    var valueName;
                    var idBy;

                    if (angular.isDefined($scope.valueName)) {
                        valueName = $scope.valueName;
                    } else {
                        valueName = undefined;
                    }

                    if (angular.isDefined($scope.items)) {
                        items = $scope.items;
                    } else if (angular.isDefined(apingDefaultSettings.items)) {
                        items = apingDefaultSettings.items;
                    } else {
                        items = undefined;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.getNativeData)) {
                        getNativeData = $scope.getNativeData;
                    } else if (angular.isDefined(apingDefaultSettings.getNativeData)) {
                        getNativeData = apingDefaultSettings.getNativeData;
                    } else {
                        getNativeData = false;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.orderBy)) {
                        orderBy = $scope.orderBy;
                    } else if (angular.isDefined(apingDefaultSettings.orderBy)) {
                        orderBy = apingDefaultSettings.orderBy;
                    } else {
                        orderBy = undefined;
                    }

                    if (angular.isDefined($scope.orderReverse)) {
                        orderReverse = $scope.orderReverse;
                    } else if (angular.isDefined(apingDefaultSettings.orderReverse)) {
                        orderReverse = apingDefaultSettings.orderReverse;
                    } else {
                        orderReverse = false;
                    }

                    if (angular.isDefined($scope.removeDoubles)) {
                        removeDoubles = $scope.removeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.removeDoubles)) {
                        removeDoubles = apingDefaultSettings.removeDoubles;
                    } else {
                        removeDoubles = false;
                    }

                    if (angular.isDefined($scope.mergeDoubles)) {
                        mergeDoubles = $scope.mergeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.mergeDoubles)) {
                        mergeDoubles = apingDefaultSettings.mergeDoubles;
                    } else {
                        mergeDoubles = false;
                    }

                    if (angular.isDefined($scope.idBy)) {
                        idBy = $scope.idBy;
                    } else if (angular.isDefined(apingDefaultSettings.idBy)) {
                        idBy = apingDefaultSettings.idBy;
                    } else {
                        idBy = undefined;
                    }

                    return {
                        model: $scope.model || apingDefaultSettings.model || "native",
                        getNativeData: getNativeData,
                        items: items,
                        maxItems: maxItems,
                        orderBy: orderBy,
                        orderReverse: orderReverse,
                        removeDoubles: removeDoubles,
                        mergeDoubles: mergeDoubles,
                        idBy: idBy,
                        valueName: valueName
                    };
                };

                /**
                 * merge current '$scope.results' with '_array' and sorts, limits and filters the data
                 *
                 * @param _array
                 */
                this.concatToResults = function (_array) {
                    if(angular.isUndefined($scope.resultName)) {
                        if (angular.isUndefined($scope.resultProperty)) {
                            $scope.resultName = "results";
                        } else {
                            $scope.resultName = $scope.resultProperty;
                        }
                    }

                    var tempArray = $scope[$scope.resultName].concat(_array);

                    var appSettings = this.getAppSettings();

                    if (angular.isDefined(appSettings.idBy)) {
                        tempArray = apingUtilityHelper.createIdByPropertiesForArray(tempArray, appSettings.idBy);
                        if (appSettings.mergeDoubles === true || appSettings.mergeDoubles === "true") {
                            tempArray = apingUtilityHelper.mergeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE")
                            );
                        }
                    }

                    //remove doubles
                    if (appSettings.removeDoubles === true || appSettings.removeDoubles === "true") {
                        if (appSettings.mergeDoubles !== true && appSettings.mergeDoubles !== "true") {
                            tempArray = apingUtilityHelper.removeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE"),
                                angular.isDefined(appSettings.idBy)
                            );
                        }
                    }

                    //order array
                    if (angular.isDefined(appSettings.orderBy) && appSettings.orderBy !== false && appSettings.orderBy !== "false" && appSettings.orderBy !== "$NONE") {
                        //order random
                        if (appSettings.orderBy === "$RANDOM") {
                            tempArray = apingUtilityHelper.shuffleArray(tempArray);
                        }
                        //order by attribute
                        else {
                            tempArray.sort(apingUtilityHelper.sortArrayByProperty(appSettings.orderBy));
                        }
                    }

                    //order reverse
                    if ((appSettings.orderReverse === true || appSettings.orderReverse === "true") && appSettings.orderBy !== "$RANDOM") {
                        tempArray.reverse();
                    }

                    //crop spare
                    if (appSettings.maxItems > -1 && tempArray.length > appSettings.maxItems) {
                        tempArray = tempArray.splice(0, appSettings.maxItems);
                    }

                    if (angular.isDefined(appSettings.valueName)) {
                        apingResults[appSettings.valueName] = tempArray;
                    }

                    $scope[$scope.resultName] = tempArray;

                    $scope.$broadcast('apiNG.resultMerged', {'resultName': $scope.resultName});
                };
                this.apply = function () {
                    $scope.$apply();
                };
            }]
        };
    }]);<|endoftext|>


<commit_before>Kalendae.Input = function (targetElement, options) {
	if (typeof document.addEventListener !== 'function'  && !util.isIE8()) return;

	var $input = this.input = util.$(targetElement),
		overwriteInput,
		$closeButton,
		changing = false;

	if (!$input || $input.tagName !== 'INPUT') throw "First argument for Kalendae.Input must be an <input> element or a valid element id.";

	var self = this,
		classes = self.classes,
		opts = self.settings = util.merge(self.defaults, options);

	this._events = {};

	//force attachment to the body
	opts.attachTo = window.document.body;

	//if no override provided, use the input's contents
	if (!opts.selected) opts.selected = $input.value;
	else overwriteInput = true;

	//call our parent constructor
	Kalendae.call(self, opts);

	//create the close button
	if (opts.closeButton) {
		$closeButton = util.make('a', {'class':classes.closeButton}, self.container);
		util.addEvent($closeButton, 'click', function () {
			$input.blur();
		});
	}

	if (overwriteInput) $input.value = self.getSelected();

	var $container = self.container,
		noclose = false;

	$container.style.display = 'none';
	util.addClassName($container, classes.positioned);

	this._events.containerMouseDown = util.addEvent($container, 'mousedown', function (event, target) {
		noclose = true; //IE8 doesn't obey event blocking when it comes to focusing, so we have to do this shit.
	});

	this._events.documentMousedown = util.addEvent(window.document, 'mousedown', function (event, target) {
		noclose = false;
	});

	this._events.inputFocus = util.addEvent($input, 'focus', function () {
		changing = true; // prevent setSelected from altering the input contents.
		self.setSelected(this.value);
		changing = false;
		self.show();
	});

	this._events.inputBlur = util.addEvent($input, 'blur', function () {
		if (noclose && util.isIE8()) {
			noclose = false;
			$input.focus();
		}
		else self.hide();
	});

	this._events.inputKeyup = util.addEvent($input, 'keyup', function (event) {
		changing = true; // prevent setSelected from altering the input contents.
		self.setSelected(this.value);
		changing = false;
	});

	var $scrollContainer = util.scrollContainer($input);

	if( $scrollContainer ) {

		// Hide calendar when $scrollContainer is scrolled
		util.addEvent($scrollContainer, 'scroll', function (event) {
			$input.blur();
		});
	}

	self.subscribe('change', function () {
		if (changing) {
			// the change event came from an internal modification, don't update the field contents
			return;
		}
		$input.value = self.getSelected();
	});

};

Kalendae.Input.prototype = util.merge(Kalendae.prototype, {
	defaults : util.merge(Kalendae.prototype.defaults, {
		format: 'MM/DD/YYYY',
		side: 'bottom',
		closeButton: true,
		offsetLeft: 0,
		offsetTop: 0
	}),
	classes : util.merge(Kalendae.prototype.classes, {
		positioned : 'k-floating',
		closeButton: 'k-btn-close'
	}),

	show : function () {
		var $container = this.container,
			style = $container.style,
			$input = this.input,
			pos = util.getPosition($input),
			$scrollContainer = util.scrollContainer($input),
			scrollTop = $scrollContainer ? $scrollContainer.scrollTop : 0,
			opts = this.settings;

		style.display = '';
		switch (opts.side) {
			case 'left':
				style.left = (pos.left - util.getWidth($container) + opts.offsetLeft) + 'px';
				style.top  = (pos.top + opts.offsetTop - scrollTop) + 'px';
				break;
			case 'right':
				style.left = (pos.left + util.getWidth($input)) + 'px';
				style.top  = (pos.top + opts.offsetTop - scrollTop) + 'px';
				break;
			case 'top':
				style.left = (pos.left + opts.offsetLeft) + 'px';
				style.top  = (pos.top - util.getHeight($container) + opts.offsetTop - scrollTop) + 'px';
				break;
			case 'bottom':
				/* falls through */
			default:
				style.left = (pos.left + opts.offsetLeft) + 'px';
				style.top  = (pos.top + util.getHeight($input) + opts.offsetTop - scrollTop) + 'px';
				break;
		}

		style.position = util.isFixed($input) ? 'fixed' : 'absolute';

		this.publish('show', this);
	},

	hide : function () {
		this.container.style.display = 'none';
		this.publish('hide', this);
	},

	destroy : function() {
		var $container = this.container;
		var $input = this.input;

		util.removeEvent($container, 'mousedown', this._events.containerMousedown);

		util.removeEvent(window.document, 'mousedown', this._events.documentMousedown);

		util.removeEvent($input, 'focus', this._events.inputFocus);

		util.removeEvent($input, 'blur', this._events.inputBlur);

		util.removeEvent($input, 'keyup', this._events.inputKeyup);

		$container.remove();
	}
});

<commit_msg>Kalendae.Input: Fire DOM change when choosing date<commit_after>Kalendae.Input = function (targetElement, options) {
	if (typeof document.addEventListener !== 'function'  && !util.isIE8()) return;

	var $input = this.input = util.$(targetElement),
		overwriteInput,
		$closeButton,
		changing = false;

	if (!$input || $input.tagName !== 'INPUT') throw "First argument for Kalendae.Input must be an <input> element or a valid element id.";

	var self = this,
		classes = self.classes,
		opts = self.settings = util.merge(self.defaults, options);

	this._events = {};

	//force attachment to the body
	opts.attachTo = window.document.body;

	//if no override provided, use the input's contents
	if (!opts.selected) opts.selected = $input.value;
	else overwriteInput = true;

	//call our parent constructor
	Kalendae.call(self, opts);

	//create the close button
	if (opts.closeButton) {
		$closeButton = util.make('a', {'class':classes.closeButton}, self.container);
		util.addEvent($closeButton, 'click', function () {
			$input.blur();
		});
	}

	if (overwriteInput) $input.value = self.getSelected();

	var $container = self.container,
		noclose = false;

	$container.style.display = 'none';
	util.addClassName($container, classes.positioned);

	this._events.containerMouseDown = util.addEvent($container, 'mousedown', function (event, target) {
		noclose = true; //IE8 doesn't obey event blocking when it comes to focusing, so we have to do this shit.
	});

	this._events.documentMousedown = util.addEvent(window.document, 'mousedown', function (event, target) {
		noclose = false;
	});

	this._events.inputFocus = util.addEvent($input, 'focus', function () {
		changing = true; // prevent setSelected from altering the input contents.
		self.setSelected(this.value);
		changing = false;
		self.show();
	});

	this._events.inputBlur = util.addEvent($input, 'blur', function () {
		if (noclose && util.isIE8()) {
			noclose = false;
			$input.focus();
		}
		else self.hide();
	});

	this._events.inputKeyup = util.addEvent($input, 'keyup', function (event) {
		changing = true; // prevent setSelected from altering the input contents.
		self.setSelected(this.value);
		changing = false;
	});

	var $scrollContainer = util.scrollContainer($input);

	if( $scrollContainer ) {

		// Hide calendar when $scrollContainer is scrolled
		util.addEvent($scrollContainer, 'scroll', function (event) {
			$input.blur();
		});
	}

	function fireChange(elem){
		if (document.createEvent) {
			var evt = document.createEvent('HTMLEvents');
			evt.initEvent('change', false, true);
			elem.dispatchEvent(evt);
		} else if (document.createEventObject) {
			elem.fireEvent('onchange') ;
		} else if (typeof elem.onchange == 'function' ) {
			elem.onchange();
		}
	}

	self.subscribe('change', function () {
		if (changing) {
			// the change event came from an internal modification, don't update the field contents
			return;
		}
		$input.value = self.getSelected();
		fireChange($input);
	});

};

Kalendae.Input.prototype = util.merge(Kalendae.prototype, {
	defaults : util.merge(Kalendae.prototype.defaults, {
		format: 'MM/DD/YYYY',
		side: 'bottom',
		closeButton: true,
		offsetLeft: 0,
		offsetTop: 0
	}),
	classes : util.merge(Kalendae.prototype.classes, {
		positioned : 'k-floating',
		closeButton: 'k-btn-close'
	}),

	show : function () {
		var $container = this.container,
			style = $container.style,
			$input = this.input,
			pos = util.getPosition($input),
			$scrollContainer = util.scrollContainer($input),
			scrollTop = $scrollContainer ? $scrollContainer.scrollTop : 0,
			opts = this.settings;

		style.display = '';
		switch (opts.side) {
			case 'left':
				style.left = (pos.left - util.getWidth($container) + opts.offsetLeft) + 'px';
				style.top  = (pos.top + opts.offsetTop - scrollTop) + 'px';
				break;
			case 'right':
				style.left = (pos.left + util.getWidth($input)) + 'px';
				style.top  = (pos.top + opts.offsetTop - scrollTop) + 'px';
				break;
			case 'top':
				style.left = (pos.left + opts.offsetLeft) + 'px';
				style.top  = (pos.top - util.getHeight($container) + opts.offsetTop - scrollTop) + 'px';
				break;
			case 'bottom':
				/* falls through */
			default:
				style.left = (pos.left + opts.offsetLeft) + 'px';
				style.top  = (pos.top + util.getHeight($input) + opts.offsetTop - scrollTop) + 'px';
				break;
		}

		style.position = util.isFixed($input) ? 'fixed' : 'absolute';

		this.publish('show', this);
	},

	hide : function () {
		this.container.style.display = 'none';
		this.publish('hide', this);
	},

	destroy : function() {
		var $container = this.container;
		var $input = this.input;

		util.removeEvent($container, 'mousedown', this._events.containerMousedown);

		util.removeEvent(window.document, 'mousedown', this._events.documentMousedown);

		util.removeEvent($input, 'focus', this._events.inputFocus);

		util.removeEvent($input, 'blur', this._events.inputBlur);

		util.removeEvent($input, 'keyup', this._events.inputKeyup);

		$container.remove();
	}
});

<|endoftext|>


<commit_before>import mapValues from 'lodash/mapValues';

export const FilterState = {
  DO_NOT_FILTER: 'DO_NOT_FILTER',
  BLACKLIST_SPECIFIC: 'BLACKLIST_SPECIFIC',
  WHITELIST_SPECIFIC: 'WHITELIST_SPECIFIC'
};

export function getLocalFilter(config) {
  if (config.actionsBlacklist || config.actionsWhitelist) {
    return {
      whitelist: config.actionsWhitelist && config.actionsWhitelist.join('|'),
      blacklist: config.actionsBlacklist && config.actionsBlacklist.join('|')
    };
  }
  return undefined;
}

export function isFiltered(action, localFilter) {
  if (!localFilter && window.devToolsOptions.filter === FilterState.DO_NOT_FILTER) return false;

  const { whitelist, blacklist } = localFilter || window.devToolsOptions;
  return (
    whitelist && !action.type.match(whitelist) ||
    blacklist && action.type.match(blacklist)
  );
}

function filterActions(actionsById, actionSanitizer) {
  if (!actionSanitizer) return actionsById;
  return mapValues(actionsById, (action, id) => (
    { ...action, action: actionSanitizer(action.action, id) }
  ));
}

function filterStates(computedStates, stateSanitizer) {
  if (!stateSanitizer) return computedStates;
  return computedStates.map((state, idx) => (
    { ...state, state: stateSanitizer(state.state, idx) }
  ));
}

export function filterState(state, type, localFilter, stateSanitizer, actionSanitizer, nextActionId, predicate) {
  if (type === 'ACTION') return !stateSanitizer ? state : stateSanitizer(state, nextActionId - 1);
  else if (type !== 'STATE') return state;

  if (predicate || localFilter || window.devToolsOptions.filter !== FilterState.DO_NOT_FILTER) {
    const filteredStagedActionIds = [];
    const filteredComputedStates = [];
    const filteredActionsById = actionSanitizer && {};
    const { actionsById } = state;
    const { computedStates } = state;

    state.stagedActionIds.forEach((id, idx) => {
      const liftedAction = actionsById[id];
      const currAction = liftedAction.action;
      const liftedState = computedStates[idx];
      const currState = liftedState.state;
      if (idx) {
        if (predicate && !predicate(currState, currAction)) return;
        if (isFiltered(currAction, localFilter)) return;
      }

      filteredStagedActionIds.push(id);
      filteredComputedStates.push(
        stateSanitizer ? { ...liftedState, state: stateSanitizer(currState, idx) } : liftedState
      );
      if (actionSanitizer) {
        filteredActionsById[id] = {
          ...liftedAction, action: actionSanitizer(currAction, id)
        };
      }
    });

    return {
      ...state,
      actionsById: filteredActionsById || actionsById,
      stagedActionIds: filteredStagedActionIds,
      computedStates: filteredComputedStates
    };
  }

  if (!stateSanitizer && !actionSanitizer) return state;
  return {
    ...state,
    actionsById: filterActions(state.actionsById, actionSanitizer),
    computedStates: filterStates(state.computedStates, stateSanitizer)
  };
}
<commit_msg>chore: Rename filteredActionsById to sanitizedActionsById<commit_after>import mapValues from 'lodash/mapValues';

export const FilterState = {
  DO_NOT_FILTER: 'DO_NOT_FILTER',
  BLACKLIST_SPECIFIC: 'BLACKLIST_SPECIFIC',
  WHITELIST_SPECIFIC: 'WHITELIST_SPECIFIC'
};

export function getLocalFilter(config) {
  if (config.actionsBlacklist || config.actionsWhitelist) {
    return {
      whitelist: config.actionsWhitelist && config.actionsWhitelist.join('|'),
      blacklist: config.actionsBlacklist && config.actionsBlacklist.join('|')
    };
  }
  return undefined;
}

export function isFiltered(action, localFilter) {
  if (!localFilter && window.devToolsOptions.filter === FilterState.DO_NOT_FILTER) return false;

  const { whitelist, blacklist } = localFilter || window.devToolsOptions;
  return (
    whitelist && !action.type.match(whitelist) ||
    blacklist && action.type.match(blacklist)
  );
}

function filterActions(actionsById, actionSanitizer) {
  if (!actionSanitizer) return actionsById;
  return mapValues(actionsById, (action, id) => (
    { ...action, action: actionSanitizer(action.action, id) }
  ));
}

function filterStates(computedStates, stateSanitizer) {
  if (!stateSanitizer) return computedStates;
  return computedStates.map((state, idx) => (
    { ...state, state: stateSanitizer(state.state, idx) }
  ));
}

export function filterState(state, type, localFilter, stateSanitizer, actionSanitizer, nextActionId, predicate) {
  if (type === 'ACTION') return !stateSanitizer ? state : stateSanitizer(state, nextActionId - 1);
  else if (type !== 'STATE') return state;

  if (predicate || localFilter || window.devToolsOptions.filter !== FilterState.DO_NOT_FILTER) {
    const filteredStagedActionIds = [];
    const filteredComputedStates = [];
    const sanitizedActionsById = actionSanitizer && {};
    const { actionsById } = state;
    const { computedStates } = state;

    state.stagedActionIds.forEach((id, idx) => {
      const liftedAction = actionsById[id];
      const currAction = liftedAction.action;
      const liftedState = computedStates[idx];
      const currState = liftedState.state;
      if (idx) {
        if (predicate && !predicate(currState, currAction)) return;
        if (isFiltered(currAction, localFilter)) return;
      }

      filteredStagedActionIds.push(id);
      filteredComputedStates.push(
        stateSanitizer ? { ...liftedState, state: stateSanitizer(currState, idx) } : liftedState
      );
      if (actionSanitizer) {
        sanitizedActionsById[id] = {
          ...liftedAction, action: actionSanitizer(currAction, id)
        };
      }
    });

    return {
      ...state,
      actionsById: sanitizedActionsById || actionsById,
      stagedActionIds: filteredStagedActionIds,
      computedStates: filteredComputedStates
    };
  }

  if (!stateSanitizer && !actionSanitizer) return state;
  return {
    ...state,
    actionsById: filterActions(state.actionsById, actionSanitizer),
    computedStates: filterStates(state.computedStates, stateSanitizer)
  };
}
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/* eslint-disable no-invalid-this */

'use strict';

// MODULES //

var fs = require( 'fs' );
var path = require( 'path' );
var render = require( 'react-dom/server' ).renderToString;
var ServerStyleSheets = require( '@mui/styles' ).ServerStyleSheets;
var readFile = require( '@stdlib/fs/read-file' );
var pkg2title = require( 'pkg2title' );
var packageData = require( 'package-data' );
var parallel = require( 'parallel' );
var onError = require( './error.js');
var app = require( './app.jsx' );

// VARIABLES //

var RE_BUNDLE = /\/(test|benchmark)[^\/]*\.js$/; // eslint-disable-line no-useless-escape
var RE_ASSET = /^(.+)\/(tests|benchmarks)$/;
var FOPTS = {
	'encoding': 'utf8'
};

// FUNCTIONS //

/**
* Returns a function which invokes a provided callback with a specified constant value.
*
* @private
* @param {*} value - constant value
* @returns {Function} function
*/
function constantFunction( value ) {
	return fcn;

	/**
	* Invokes a provided callback with a specified constant value.
	*
	* @private
	* @param {Function} clbk - callback function
	*/
	function fcn( clbk ) {
		clbk( null, value );
	}
}

// MAIN //

/**
* Callback invoked upon receiving an HTTP request.
*
* @private
* @param {Object} request - request object
* @param {Object} reply - reply object
* @returns {void}
*/
function handler( request, reply ) {
	var match;
	var fcns;
	var self;
	var pkg;
	var p;
	var f;
	var v;

	self = this;

	v = request.params.version;
	request.log.info( 'Version: %s', v );
	if ( v === 'latest' ) {
		v = this.latestVersion;
		request.log.info( 'Resolved version: %s', v );
	}
	p = request.params[ '*' ];

	// Check whether we need to serve a package's benchmark or test bundles...
	match = p.match( RE_BUNDLE );
	if ( match ) {
		// Resolve the bundle path:
		p = '@stdlib/' + p;
		request.log.info( 'Path: %s', p );

		p = path.resolve( this.rootDir, v, p );
		request.log.info( 'Resolved path: %s', p );

		// Ensure we have not received a request for an asset above the root directory:
		if ( p.substring( 0, this.rootDir.length ) !== this.rootDir ) {
			reply.callNotFound();
			return;
		}
		request.log.info( 'Requested a %s package asset.', match[ 1 ] );
		reply.type( 'text/javascript' );
		return reply.send( fs.createReadStream( p, FOPTS ) );
	}
	// Determine whether we need to serve a package's benchmark or test page...
	match = p.match( RE_ASSET );
	if ( match ) {
		pkg = match[ 1 ];
		f = match[ 2 ];

		// At this point, the request is for either a `benchmark.html`, `test.html`, or `index.html` file...
	} else {
		// If unable to match an asset, assume the request is for a directory (i.e., `index.html` file)...
		request.log.info( 'Failed to match file path. Serving `index.html`...' );
		if ( p[ p.length-1 ] === '/' ) {
			pkg = p.substring( 0, p.length-1 );
		} else {
			pkg = p;
			p += '/';
		}
		p += 'index.html';
		f = 'index';
	}
	p = '@stdlib/' + p;
	request.log.info( 'Path: %s', p );

	p = path.resolve( this.rootDir, v, p );
	request.log.info( 'Resolved path: %s', p );

	// Ensure we have not received a request for an asset above the root directory:
	if ( p.substring( 0, this.rootDir.length ) !== this.rootDir ) {
		reply.callNotFound();
		return;
	}
	// At this point, we should only be serving HTML files...
	reply.type( 'text/html' );

	// Check whether we should serve a package's README as a fragment or as part of a rendered application...
	if ( f === 'index' && request.query.fragment ) {
		request.log.info( 'Requested a fragment.' );
		return reply.send( fs.createReadStream( p, FOPTS ) );
	}
	// We need to serve a rendered application...
	request.log.info( 'Requested an application.' );

	// If the request is for a benchmark or test asset, we need to return an application shell; otherwise, we need to return the application with a rendered README...
	fcns = [];
	if ( f === 'index' ) {
		request.log.info( 'Returning an application with a rendered README.' );
		fcns.push( [ readFile, p, FOPTS ] );
	} else {
		request.log.info( 'Returning an application shell.' );
		fcns.push( [ constantFunction( '' ) ] );
	}
	fcns.push( [ packageData, this.rootDir, v ] );

	// Resolve application data:
	parallel( fcns, onResults );

	/**
	* Callback invoked upon resolving application data.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {Array} results - application data
	* @param {string} results.0 - file contents
	* @param {Object} results.1 - package data
	* @returns {void}
	*/
	function onResults( error, results ) {
		var sheets;
		var html;
		var desc;
		var data;
		var file;
		var url;
		var css;
		var idx;

		if ( error ) {
			request.log.error( error );
			if ( error.code !== 'ENOENT' ) {
				return onError( error, request, reply );
			}
			file = '';
			data = {};
		} else {
			file = results[ 0 ];
			data = results[ 1 ];
		}
		// Resolve a normalized URL:
		url = request.url;
		if ( url[ url.length-1 ] === '/' ) {
			url = url.substring( 0, url.length-1 );
		}
		// Initialize a means for generating Material-UI CSS:
		sheets = new ServerStyleSheets();

		// Render the application component as parameterized by request data:
		html = render( sheets.collect( app( self.App, url, v, file, data, request.locals, {} ) ) );  // eslint-disable-line max-len

		// Generate Material-UI CSS:
		css = sheets.toString();

		// Resolve a page description...
		if ( data.order ) {
			idx = data.order[ pkg ];
			if ( typeof idx === 'number' ) {
				desc = data.descriptions[ idx ];
			}
		}
		if ( desc === void 0 ) {
			request.log.info( 'Unable to resolve document description.' );

			// Fallback to default description:
			desc = self.appinfo.description;
		}
		// Insert the rendered application into the application template:
		html = self.template
			.theme( request.locals.theme )
			.title( pkg2title( pkg ) )
			.description( desc )
			.url( url )
			.css( css )
			.content( html )
			.toString();

		// Send the response data:
		reply.send( html );
	}
}

// EXPORTS //

module.exports = handler;
<commit_msg>Add comment<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/* eslint-disable no-invalid-this */

'use strict';

// MODULES //

var fs = require( 'fs' );
var path = require( 'path' );
var render = require( 'react-dom/server' ).renderToString;
var ServerStyleSheets = require( '@mui/styles' ).ServerStyleSheets;
var readFile = require( '@stdlib/fs/read-file' );
var pkg2title = require( 'pkg2title' );
var packageData = require( 'package-data' );
var parallel = require( 'parallel' );
var onError = require( './error.js');
var app = require( './app.jsx' );

// VARIABLES //

var RE_BUNDLE = /\/(test|benchmark)[^\/]*\.js$/; // eslint-disable-line no-useless-escape
var RE_ASSET = /^(.+)\/(tests|benchmarks)$/;
var FOPTS = {
	'encoding': 'utf8'
};

// FUNCTIONS //

/**
* Returns a function which invokes a provided callback with a specified constant value.
*
* @private
* @param {*} value - constant value
* @returns {Function} function
*/
function constantFunction( value ) {
	return fcn;

	/**
	* Invokes a provided callback with a specified constant value.
	*
	* @private
	* @param {Function} clbk - callback function
	*/
	function fcn( clbk ) {
		clbk( null, value );
	}
}

// MAIN //

/**
* Callback invoked upon receiving an HTTP request.
*
* @private
* @param {Object} request - request object
* @param {Object} reply - reply object
* @returns {void}
*/
function handler( request, reply ) {
	var match;
	var fcns;
	var self;
	var pkg;
	var p;
	var f;
	var v;

	self = this;

	v = request.params.version;
	request.log.info( 'Version: %s', v );
	if ( v === 'latest' ) {
		v = this.latestVersion;
		request.log.info( 'Resolved version: %s', v );
	}
	p = request.params[ '*' ];

	// Check whether we need to serve a package's benchmark or test bundles...
	match = p.match( RE_BUNDLE );
	if ( match ) {
		// Resolve the bundle path:
		p = '@stdlib/' + p;
		request.log.info( 'Path: %s', p );

		p = path.resolve( this.rootDir, v, p );
		request.log.info( 'Resolved path: %s', p );

		// Ensure we have not received a request for an asset above the root directory:
		if ( p.substring( 0, this.rootDir.length ) !== this.rootDir ) {
			reply.callNotFound();
			return;
		}
		request.log.info( 'Requested a %s package asset.', match[ 1 ] );
		reply.type( 'text/javascript' );
		return reply.send( fs.createReadStream( p, FOPTS ) );
	}
	// Determine whether we need to serve a package's benchmark or test page...
	match = p.match( RE_ASSET );
	if ( match ) {
		pkg = match[ 1 ];
		f = match[ 2 ];

		// At this point, the request is for either a `benchmark.html`, `test.html`, or `index.html` file...
	} else {
		// If unable to match an asset, assume the request is for a directory (i.e., `index.html` file)...
		request.log.info( 'Failed to match file path. Serving `index.html`...' );
		if ( p[ p.length-1 ] === '/' ) {
			pkg = p.substring( 0, p.length-1 );
		} else {
			pkg = p;
			p += '/';
		}
		p += 'index.html';
		f = 'index';
	}
	p = '@stdlib/' + p;
	request.log.info( 'Path: %s', p );

	p = path.resolve( this.rootDir, v, p );
	request.log.info( 'Resolved path: %s', p );

	// Ensure we have not received a request for an asset above the root directory:
	if ( p.substring( 0, this.rootDir.length ) !== this.rootDir ) {
		reply.callNotFound();
		return;
	}
	// At this point, we should only be serving HTML files...
	reply.type( 'text/html' );

	// Check whether we should serve a package's README as a fragment or as part of a rendered application...
	if ( f === 'index' && request.query.fragment ) {
		request.log.info( 'Requested a fragment.' );
		return reply.send( fs.createReadStream( p, FOPTS ) );
	}
	// We need to serve a rendered application...
	request.log.info( 'Requested an application.' );

	// If the request is for a benchmark or test asset, we need to return an application shell; otherwise, we need to return the application with a rendered README...
	fcns = [];
	if ( f === 'index' ) {
		request.log.info( 'Returning an application with a rendered README.' );
		fcns.push( [ readFile, p, FOPTS ] );
	} else {
		request.log.info( 'Returning an application shell.' );
		fcns.push( [ constantFunction( '' ) ] );
	}
	fcns.push( [ packageData, this.rootDir, v ] );

	// Resolve application data:
	parallel( fcns, onResults );

	/**
	* Callback invoked upon resolving application data.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {Array} results - application data
	* @param {string} results.0 - file contents
	* @param {Object} results.1 - package data
	* @returns {void}
	*/
	function onResults( error, results ) {
		var sheets;
		var html;
		var desc;
		var data;
		var file;
		var url;
		var css;
		var idx;

		if ( error ) {
			request.log.error( error );
			if ( error.code !== 'ENOENT' ) {
				return onError( error, request, reply );
			}
			// We assume that the `ENOENT` (i.e., no "entry" (file or directory) error) indicates a missing package README; in which case, we want the application to "404", rather than return a JSON error, so we simply SSR an empty application shell and allow client side rendering to generate the 404 page...
			file = '';
			data = {};
		} else {
			file = results[ 0 ];
			data = results[ 1 ];
		}
		// Resolve a normalized URL:
		url = request.url;
		if ( url[ url.length-1 ] === '/' ) {
			url = url.substring( 0, url.length-1 );
		}
		// Initialize a means for generating Material-UI CSS:
		sheets = new ServerStyleSheets();

		// Render the application component as parameterized by request data:
		html = render( sheets.collect( app( self.App, url, v, file, data, request.locals, {} ) ) );  // eslint-disable-line max-len

		// Generate Material-UI CSS:
		css = sheets.toString();

		// Resolve a page description...
		if ( data.order ) {
			idx = data.order[ pkg ];
			if ( typeof idx === 'number' ) {
				desc = data.descriptions[ idx ];
			}
		}
		if ( desc === void 0 ) {
			request.log.info( 'Unable to resolve document description.' );

			// Fallback to default description:
			desc = self.appinfo.description;
		}
		// Insert the rendered application into the application template:
		html = self.template
			.theme( request.locals.theme )
			.title( pkg2title( pkg ) )
			.description( desc )
			.url( url )
			.css( css )
			.content( html )
			.toString();

		// Send the response data:
		reply.send( html );
	}
}

// EXPORTS //

module.exports = handler;
<|endoftext|>


<commit_before>var assert = require('assert');

var sinon = require('sinon')

var Cli = require('../src/cli.js').Diff2HtmlInterface;
var Utils = require('../src/utils.js').Utils;

describe('Cli', function() {
  describe('getInput', function() {
    it('should readFile when inputType is `file`', function() {
      let spy = sinon.stub(Utils, 'readFile');
      Cli.getInput('file', ['lol', 'foo'], 'callback');
      assert(spy.calledOnce);
      assert(spy.calledWith('lol', 'callback'));
      spy.restore()
    });

    it('should readStdin when inputType is `stdin`', function() {
      let spy = sinon.stub(Utils, 'readStdin');
      Cli.getInput('stdin', ['lol'], 'callback');
      assert(spy.calledOnce);
      assert(spy.calledWith('callback'));
    });

    it('should _runGitDiff by default', function() {
      let spy = sinon.stub(Cli, '_runGitDiff');
      Cli.getInput('abc', ['lol'], 'callback');
      assert(spy.calledOnce);
      assert(spy.calledWith(['lol'], 'callback'));
    });
  });
});
<commit_msg>simple unit test for preview and postToDiffy<commit_after>var assert = require('assert');

var sinon = require('sinon')

var Cli = require('../src/cli.js').Diff2HtmlInterface;
var http = require('../src/http-utils.js').HttpUtils;
var Utils = require('../src/utils.js').Utils;

describe('Cli', function() {
  describe('getInput', function() {
    it('should readFile when inputType is `file`', function() {
      let spy = sinon.stub(Utils, 'readFile');
      Cli.getInput('file', ['lol', 'foo'], 'callback');
      assert(spy.calledOnce);
      assert(spy.calledWith('lol', 'callback'));
      spy.restore()
    });

    it('should readStdin when inputType is `stdin`', function() {
      let spy = sinon.stub(Utils, 'readStdin');
      Cli.getInput('stdin', ['lol'], 'callback');
      assert(spy.calledOnce);
      assert(spy.calledWith('callback'));
    });

    it('should _runGitDiff by default', function() {
      let spy = sinon.stub(Cli, '_runGitDiff');
      Cli.getInput('abc', ['lol', 'foo'], 'callback');
      assert(spy.calledOnce);
      assert(spy.calledWith(['lol', 'foo'], 'callback'));
    });
  });

  describe('preview', function() {
    it('should call `utils.writeFile`', function() {
      let spy = sinon.stub(Utils, 'writeFile');
      Cli.preview('a', 'b');
      assert(spy.calledOnce);
    });
  });

  describe('postToDiffy', function() {
    it('should call `http.post`', function() {
      let spy = sinon.stub(http, 'post');
      Cli.postToDiffy('a', 'b', 'callback');
      assert(spy.calledOnce);
      assert(spy.calledWith('http://diffy.org/api/new', { udiff: 'a' }));
    });
  });
});
<|endoftext|>


<commit_before>//
//  PushNotification.js
//
// Based on the Push Notifications Cordova Plugin by Olivier Louvignes on 06/05/12.
// Modified by Max Konev on 18/05/12.
//
// Pushwoosh Push Notifications Plugin for Cordova iOS
// www.pushwoosh.com
//
// MIT Licensed

(function(cordova) {

	function PushNotification() {}

	// Call this to register for push notifications and retreive a deviceToken
	PushNotification.prototype.registerDevice = function(config, success, fail) {
		cordova.exec(success, fail, "PushNotification", "registerDevice", config ? [config] : []);
	};

	// Call this to set tags for the device
	PushNotification.prototype.setTags = function(config, success, fail) {
		cordova.exec(success, fail, "PushNotification", "setTags", config ? [config] : []);
	};

	//Android Only----
	PushNotification.prototype.unregisterDevice = function(success, fail) {
		cordova.exec(success, fail, "PushNotification", "unregisterDevice", []);
	};

	PushNotification.prototype.sendLocation = function(success, fail) {
		cordova.exec(success, fail, "PushNotification", "startGeoPushes", []);
	};

	PushNotification.prototype.sendLocation = function(success, fail) {
		cordova.exec(success, fail, "PushNotification", "stopGeoPushes", []);
	};

	//Android End----

	//iOS only----
	// Call this to send geo location for the device
	PushNotification.prototype.sendLocation = function(config, success, fail) {
		cordova.exec(success, fail, "PushNotification", "sendLocation", config ? [config] : []);
	};

	PushNotification.prototype.onDeviceReady = function() {
		cordova.exec(null, null, "PushNotification", "onDeviceReady", []);
	};

	// Call this to get a detailed status of remoteNotifications
	PushNotification.prototype.getRemoteNotificationStatus = function(callback) {
		cordova.exec(callback, callback, "PushNotification", "getRemoteNotificationStatus", []);
	};

	// Call this to set the application icon badge
	PushNotification.prototype.setApplicationIconBadgeNumber = function(badge, callback) {
		cordova.exec(callback, callback, "PushNotification", "setApplicationIconBadgeNumber", [{badge: badge}]);
	};

	// Call this to clear all notifications from the notification center
	PushNotification.prototype.cancelAllLocalNotifications = function(callback) {
		cordova.exec(callback, callback, "PushNotification", "cancelAllLocalNotifications", []);
	};
	//iOS End----

	// Event spawned when a notification is received while the application is active
	PushNotification.prototype.notificationCallback = function(notification) {
		var ev = document.createEvent('HTMLEvents');
		ev.notification = notification;
		ev.initEvent('push-notification', true, true, arguments);
		document.dispatchEvent(ev);
	};

	cordova.addConstructor(function() {
		if(!window.plugins) window.plugins = {};
		window.plugins.pushNotification = new PushNotification();
	});

})(window.cordova || window.Cordova || window.PhoneGap);
<commit_msg>typo fix in Android Phonegap interface<commit_after>//
//  PushNotification.js
//
// Based on the Push Notifications Cordova Plugin by Olivier Louvignes on 06/05/12.
// Modified by Max Konev on 18/05/12.
//
// Pushwoosh Push Notifications Plugin for Cordova iOS
// www.pushwoosh.com
//
// MIT Licensed

(function(cordova) {

	function PushNotification() {}

	// Call this to register for push notifications and retreive a deviceToken
	PushNotification.prototype.registerDevice = function(config, success, fail) {
		cordova.exec(success, fail, "PushNotification", "registerDevice", config ? [config] : []);
	};

	// Call this to set tags for the device
	PushNotification.prototype.setTags = function(config, success, fail) {
		cordova.exec(success, fail, "PushNotification", "setTags", config ? [config] : []);
	};

	//Android Only----
	PushNotification.prototype.unregisterDevice = function(success, fail) {
		cordova.exec(success, fail, "PushNotification", "unregisterDevice", []);
	};

	PushNotification.prototype.startGeoPushes = function(success, fail) {
		cordova.exec(success, fail, "PushNotification", "startGeoPushes", []);
	};

	PushNotification.prototype.stopGeoPushes = function(success, fail) {
		cordova.exec(success, fail, "PushNotification", "stopGeoPushes", []);
	};

	//Android End----

	//iOS only----
	// Call this to send geo location for the device
	PushNotification.prototype.sendLocation = function(config, success, fail) {
		cordova.exec(success, fail, "PushNotification", "sendLocation", config ? [config] : []);
	};

	PushNotification.prototype.onDeviceReady = function() {
		cordova.exec(null, null, "PushNotification", "onDeviceReady", []);
	};

	// Call this to get a detailed status of remoteNotifications
	PushNotification.prototype.getRemoteNotificationStatus = function(callback) {
		cordova.exec(callback, callback, "PushNotification", "getRemoteNotificationStatus", []);
	};

	// Call this to set the application icon badge
	PushNotification.prototype.setApplicationIconBadgeNumber = function(badge, callback) {
		cordova.exec(callback, callback, "PushNotification", "setApplicationIconBadgeNumber", [{badge: badge}]);
	};

	// Call this to clear all notifications from the notification center
	PushNotification.prototype.cancelAllLocalNotifications = function(callback) {
		cordova.exec(callback, callback, "PushNotification", "cancelAllLocalNotifications", []);
	};
	//iOS End----

	// Event spawned when a notification is received while the application is active
	PushNotification.prototype.notificationCallback = function(notification) {
		var ev = document.createEvent('HTMLEvents');
		ev.notification = notification;
		ev.initEvent('push-notification', true, true, arguments);
		document.dispatchEvent(ev);
	};

	cordova.addConstructor(function() {
		if(!window.plugins) window.plugins = {};
		window.plugins.pushNotification = new PushNotification();
	});

})(window.cordova || window.Cordova || window.PhoneGap);
<|endoftext|>


<commit_before>$(function() {
    var expect = chai.expect;
    var should = chai.should();
    var chart = null;

    beforeEach(function() {
      if (chart !== null){
        chart.destroy();
      }
    });

    describe("Core", function() {
      describe("Constructor", function() {
        it("Simple construction", function() {
          chart = $.jqplot('chart', [[4, 3, 5, 6, 8, 12, 1, 5]], {});
          should.exist(chart);
          console.log(chart);
        });
      });

      describe("Constructor using title", function() {
        it("Construction with title", function() {
          chart = $.jqplot('chart', [[4, 3, 5, 6, 8, 12, 1, 5]], {
            title: 'Chart title'
          });
          should.exist(chart);
        });
      });

      describe("Destructor", function() {
        it("Destruction from DOM", function() {
          chart = $.jqplot('chart', [[4, 3, 5, 6, 8, 12, 1, 5]], {
            title: 'Chart title'
          });
          should.exist(chart);
          chart.destroy();
          expect($('#chart')).to.have.property('length').equals(1);
          expect($('#chart').children()).to.have.property('length').equals(0);
        });
      });

      describe("Destructor", function() {
        it("Destruction from DOM", function() {
          chart = $.jqplot('chart', [[4, 3, 5, 6, 8, 12, 1, 5]], {
            title: 'Chart title'
          });
          should.exist(chart);
          chart.destroy();
          expect($('#chart')).to.have.property('length').equals(1);
          expect($('#chart').children()).to.have.property('length').equals(0);
        });
      });

    describe("No data indicator", function() {
        it("Checking no data indicator display", function() {
          chart = $.jqplot('chart', [[]], {
            title: 'Chart title',
            noDataIndicator: {
                show: true
            }
          });
          should.exist(chart);
          expect($('#chart .jqplot-noData-contents')).to.have.property('length').equals(1);
        });
      });
    });
});<commit_msg>Added more tests<commit_after>/*jslint browser: true, plusplus: true, nomen: true, white: false */
/*global $, console, chai, describe, it, beforeEach */

$(function () {

    "use strict";

    var expect = chai.expect,
        should = chai.should(),
        chart = null,
        timer;

    beforeEach(function () {
        if (chart !== null) {
            chart.destroy();
        }
    });

    describe("Core", function () {

        describe("Constructor", function () {

            beforeEach(function () {
                chart = $.jqplot('chart', [[4, 3, 5, 6, 8, 12, 1, 5]]);
            });

            it("Simple construction", function () {
                should.exist(chart);
                console.log(chart);
            });

            it("Checking chart.plotData", function () {
                should.exist(chart);
                expect(chart._plotData).to.be.an('array');
                expect(chart._plotData[0][0][0] >= 0).to.be.true;
                console.log(chart._plotData[0][0][0]);

            });

        });

        describe("Redraw", function () {

            beforeEach(function () {
                chart = $.jqplot('chart', [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]]);
            });

             it("Should redraw", function () {
                chart.redraw();
                should.exist(chart);
            });

        });

        describe("Replot", function () {

            beforeEach(function () {
                chart = $.jqplot('chart', [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]]);
            });

             it("Should replot", function () {
                chart.replot();
                should.exist(chart);
            });

        });

        describe("Constructor using title", function () {
            it("Construction with title", function () {
                chart = $.jqplot('chart', [[4, 3, 5, 6, 8, 12, 1, 5]], {
                    title: 'Chart title'
                });
                should.exist(chart);
            });
        });

        describe("Destructor", function () {
            it("Destruction from DOM", function () {
                chart = $.jqplot('chart', [[4, 3, 5, 6, 8, 12, 1, 5]], {
                    title: 'Chart title'
                });
                should.exist(chart);
                chart.destroy();
                expect($('#chart')).to.have.property('length').equals(1);
                expect($('#chart').children()).to.have.property('length').equals(0);
            });
        });

        describe("Destructor", function () {
            it("Destruction from DOM", function () {
                chart = $.jqplot('chart', [[4, 3, 5, 6, 8, 12, 1, 5]], {
                    title: 'Chart title'
                });
                should.exist(chart);
                chart.destroy();
                expect($('#chart')).to.have.property('length').equals(1);
                expect($('#chart').children()).to.have.property('length').equals(0);
            });
        });

        describe("No data indicator", function () {
            it("Checking no data indicator display", function () {
                chart = $.jqplot('chart', [[]], {
                    title: 'Chart title',
                    noDataIndicator: {
                        show: true
                    }
                });
                should.exist(chart);
                expect($('#chart .jqplot-noData-contents')).to.have.property('length').equals(1);
            });
        });

    });
});<|endoftext|>


<commit_before>/*jshint node:true */

'use strict';

var React = require('react');
var Formsy = require('formsy-react');
var FRCMixin = require('./mixin');
var Row = require('./row');
var Icon = require('./icon.js');

var Input = React.createClass({

    mixins: [Formsy.Mixin, FRCMixin],

    propTypes: {
        type: React.PropTypes.oneOf(['text', 'date', 'email', 'password', 'hidden'])
    },

    changeValue: function(event) {
        this.setValue(event.currentTarget.value);
    },

    getDefaultProps: function() {
        return {
            type: 'text'
        };
    },

    render: function() {

        var warningIcon = '';

        if (this.showErrors()) {
            warningIcon = (
                <Icon symbol="remove" className="form-control-feedback" />
            );
        }

        if (this.props.layout === 'elementOnly' || this.props.type === 'hidden') {
            return this.renderElement();
        }

        return (
            <Row
                label={this.props.label}
                required={this.isRequired()}
                hasErrors={this.showErrors()}
                layout={this.props.layout}
            >
                {this.renderElement()}
                {warningIcon}
                {this.renderHelp()}
                {this.renderErrorMessage()}
            </Row>
        );
    },

    renderElement: function() {
        return (
            <input
                className="form-control"
                {...this.props}
                label={null}
                value={this.getValue()}
                onChange={this.changeValue}
                disabled={this.isFormDisabled() || this.props.disabled}
            />
        );
    }

});

module.exports = Input;
<commit_msg>Added more possible types https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input<commit_after>/*jshint node:true */

'use strict';

var React = require('react');
var Formsy = require('formsy-react');
var FRCMixin = require('./mixin');
var Row = require('./row');
var Icon = require('./icon.js');

var Input = React.createClass({

    mixins: [Formsy.Mixin, FRCMixin],

    propTypes: {
        type: React.PropTypes.oneOf(['color', 'date', 'datetime', 'datetime-local', 'email', 'file', 'hidden', 'month', 'number', 'password', 'range', 'tel', 'text', 'time', 'url', 'week'])
    },

    changeValue: function(event) {
        this.setValue(event.currentTarget.value);
    },

    getDefaultProps: function() {
        return {
            type: 'text'
        };
    },

    render: function() {

        var warningIcon = '';

        if (this.showErrors()) {
            warningIcon = (
                <Icon symbol="remove" className="form-control-feedback" />
            );
        }

        if (this.props.layout === 'elementOnly' || this.props.type === 'hidden') {
            return this.renderElement();
        }

        return (
            <Row
                label={this.props.label}
                required={this.isRequired()}
                hasErrors={this.showErrors()}
                layout={this.props.layout}
            >
                {this.renderElement()}
                {warningIcon}
                {this.renderHelp()}
                {this.renderErrorMessage()}
            </Row>
        );
    },

    renderElement: function() {
        return (
            <input
                className="form-control"
                {...this.props}
                label={null}
                value={this.getValue()}
                onChange={this.changeValue}
                disabled={this.isFormDisabled() || this.props.disabled}
            />
        );
    }

});

module.exports = Input;
<|endoftext|>


<commit_before>  $(document).ready( function () {
      // I only have one form on the page but you can be more specific if need be.
      var $form = $('form.js');

      if ( $form.length > 0 ) {
          $form.bind('submit', function ( event ) {
              if ( event ) event.preventDefault();
              // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
              register($form);
          });
      }
  });

  function register($form) {
      $.ajax({
          type: $form.attr('method'),
          url: $form.attr('action'),
          data: $form.serialize(),
          cache       : false,
          dataType    : 'json',
          contentType: "application/json; charset=utf-8",
          error       : function(err) { $('.mce-success-response').hide(); $('.mce-error-response').show();  },
          success     : function(data) {
              $('.mce-error-response').hide(); $('.mce-success-response').show();
          }
      });
  }
<commit_msg>serializeArray<commit_after>  $(document).ready( function () {
      // I only have one form on the page but you can be more specific if need be.
      var $form = $('form.js');

      if ( $form.length > 0 ) {
          $form.bind('submit', function ( event ) {
              if ( event ) event.preventDefault();
              // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
              register($form);
          });
      }
  });

  function register($form) {
      $.ajax({
          type: $form.attr('method'),
          url: $form.attr('action'),
          //data: $form.serialize(),
          data: $form.serializeArray().reduce(function(a, x) { a[x.name] = x.value; return a; }, {});
          cache       : false,
          dataType    : 'json',
          //processData: false,
          contentType: "application/json; charset=utf-8",
          error       : function(err) { $('.mce-success-response').hide(); $('.mce-error-response').show();  },
          success     : function(data) {
              $('.mce-error-response').hide(); $('.mce-success-response').show();
          }
      });
  }
<|endoftext|>


<commit_before>window.onload = function() {
  var loginbt = document.querySelector('.login-bt');
  var un = document.querySelector("input[name='uname']");
  var ps = document.querySelector("input[name='upsd']");
  un.value = localStorage.un;
  ps.value = localStorage.ps;
  loginbt.onclick = function(e){
    e.preventDefault();
    localStorage.un = un.value;
    localStorage.ps = ps.value;
    document.querySelector("form").submit();
  };
}<commit_msg>修复login<commit_after>window.onload = function() {
  var loginbt = document.querySelector('.login-bt');
  var un = document.querySelector("input[name='uname']");
  var ps = document.querySelector("input[name='upsd']");
  if(localStorage.un) un.value = localStorage.un;
  if(localStorage.ps)ps.value = localStorage.ps;
  loginbt.onclick = function(e){
    e.preventDefault();
    localStorage.un = un.value;
    localStorage.ps = ps.value;
    document.querySelector("form").submit();
  };
}<|endoftext|>


<commit_before>window.$ = window.jQuery = require("jquery");
require("jquery-ui");

require("./ui.js")();
require("./client.js")();
<commit_msg>only runs socketio on app connections<commit_after>window.$ = window.jQuery = require("jquery");
require("jquery-ui");

require("./ui.js")();

if(location.pathname === "/app") {
    require("./client.js")();
}
<|endoftext|>


<commit_before>var Spaz; if (!Spaz) Spaz = {};

/***********
Spaz.UI
***********/
if (!Spaz.Keyboard) Spaz.Keyboard = {};

Spaz.Keyboard.setShortcuts = function() {
	Spaz.dump("Setting Shortcuts=================================================")
    Spaz.dump("os: " + air.Capabilities['os']);

	var Modkey = 'Meta';

	if (air.Capabilities['os'].search(/Windows/i) != -1) {
		Spaz.dump('THIS IS WINDOWS');
		Modkey = 'Ctrl';
	} else if (air.Capabilities['os'].search(/Linux/i) != -1) { // thx agolna
		Spaz.dump('THIS IS LINUX');
		Modkey = 'Ctrl';
	} else if (air.Capabilities['os'].search(/Mac/i) != -1) {
		Spaz.dump('THIS IS MACOS');
		Modkey = 'Meta';
	}

	Spaz.dump('Modkey is '+Modkey);

	shortcut.add(Modkey+'+T', function() {
		$('#entrybox').focus();
	})

	shortcut.add('F5', function() {
		Spaz.UI.reloadCurrentTab(true);
		Spaz.restartReloadTimer();
	})

	shortcut.add('Shift+F5', function() {
		Spaz.UI.clearCurrentTimeline();
		Spaz.UI.reloadCurrentTab(true);
		Spaz.restartReloadTimer();
	})

	shortcut.add(Modkey+'+Shift+A', function() {
		Spaz.UI.showShortLink();
	});

	shortcut.add(Modkey+'+Shift+M', function() {
		Spaz.UI.markCurrentTimelineAsRead();
	});

	shortcut.add('F1', function() {
		Spaz.UI.showHelp();
	});

	/*
		Added so we can open the preferences folder if the UI is hosed by bad CSS
	*/
	shortcut.add(Modkey+'+Shift+,', function() {
		Spaz.Sys.openAppStorageFolder();
	});

	shortcut.add(Modkey+'+Shift+@', function() {
			Spaz.dump('getting screenname from current selection');
			var screenname = $('div.ui-selected .user-screen-name').text();

			if (screenname) {
				Spaz.dump('username for reply is:'+screenname);
				// var username = '';
				Spaz.UI.prepReply(screenname);
			}
		}, {
			'disable_in_input':false
	});

	// ****************************************
	// tabs shortcuts
	// ****************************************
	shortcut.add(Modkey+'+1', function() {
		Spaz.UI.showTab(0);
	})
	shortcut.add(Modkey+'+2', function() {
		Spaz.UI.showTab(1);
	})
	shortcut.add(Modkey+'+3', function() {
		Spaz.UI.showTab(2);
	})
	shortcut.add(Modkey+'+4', function() {
		Spaz.UI.showTab(3);
	})
	shortcut.add(Modkey+'+5', function() {
		Spaz.UI.showTab(4);
	})
	shortcut.add(Modkey+'+6', function() {
		Spaz.UI.showTab(5);
	})
	shortcut.add(Modkey+'+7', function() {
		Spaz.UI.showTab(6);
	})
	shortcut.add(Modkey+'+,', function() {
		Spaz.UI.showPrefs()
	})

	// ****************************************
	// Keys to navigate timeline
	// ****************************************
	shortcut.add(Modkey+'+down', function() {
		Spaz.Keyboard.move('down', '.reply');
	});
	shortcut.add(Modkey+'+up', function() {
		Spaz.Keyboard.move('up', '.reply');
	});
	shortcut.add(Modkey+'+Shift+down', function() {
		Spaz.Keyboard.move('down', '.dm');
	});
	shortcut.add(Modkey+'+Shift+up', function() {
		Spaz.Keyboard.move('up', '.dm');
	});
	shortcut.add(Modkey+'+End', function() {
		Spaz.Keyboard.move('down', ':last');
	});
	shortcut.add(Modkey+'+Home', function() {
		Spaz.Keyboard.move('up', ':first');
	});
	shortcut.add('Down', function() {
			Spaz.Keyboard.move('down');
		}, {
			'disable_in_input':true
	});
	shortcut.add('Up', function() {
			Spaz.Keyboard.move('up');
		}, {
			'disable_in_input':true
	});
	shortcut.add(Modkey+'+J', function() {
		Spaz.Keyboard.move('down');
	});
	shortcut.add(Modkey+'+K', function() {
		Spaz.Keyboard.move('up');
	});
	shortcut.add('J', function() {
			Spaz.Keyboard.move('down');
		}, {
			'disable_in_input':true
	});
	shortcut.add('K', function() {
			Spaz.Keyboard.move('up');
		}, {
			'disable_in_input':true
	});

	shortcut.add(Modkey+'+F', function() {
			Spaz.UI.toggleTimelineFilter();
			return false;
		}, {
			type:'keypress',
			propagate:false
	});

	// ****************************************
	// editor shortcuts
	// ****************************************
	shortcut.add(Modkey+'+B', function() {
			Spaz.Editor.bold();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
	shortcut.add(Modkey+'+I', function() {
			Spaz.Editor.italics();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
	shortcut.add(Modkey+'+R', function() {
			Spaz.Editor.code();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
	shortcut.add(Modkey+'+U', function() {
			Spaz.Editor.link();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
	shortcut.add('Enter', function() {
			Spaz.UI.sendUpdate();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
}

Spaz.Keyboard.move = function(dir, selector) {

	if (!selector) {
		selector = '';
	}

	Spaz.dump("selector is '" + selector+"'")

	var timelineid = 'timeline-friends';

	if (!dir) { dir = 'down' }

	if (dir == 'down') {
		var movefunc = 'nextAll';
		var wrapselc = 'first';
	} else if (dir == 'up') {
		dir = 'up'
		var movefunc = 'prevAll';
		var wrapselc = 'last';
	} else {
		return false;
	}

	// get current selected
	var jqsel = $('#'+timelineid+' div.ui-selected');
	// alert('selected:'+selected.length);
	//alert('moving:'+movefunc+'/'+wrapselc+"\n"+'selected:'+selected.length + "\n"+'current:'+selected.html());

	// if none selected, or there is no 'next', select first
	if (selector == ":first" || selector == ":last") {
		Spaz.dump('first in timeline')
		Spaz.Keyboard.moveSelect($('#'+timelineid+' div.timeline-entry'+selector), timelineid)
	} else if (jqsel.length == 0 ) {
		Spaz.dump('nothing is selected')
		Spaz.Keyboard.moveSelect($('#'+timelineid+' div.timeline-entry'+selector+':'+wrapselc), timelineid)
		jqsel = $('#'+timelineid+' div.timeline-entry.ui-selected'+selector);
	} else if (jqsel[movefunc]('div.timeline-entry'+selector).eq(0).length == 0) {
		Spaz.dump('we are at the beginning or end')
		Spaz.Keyboard.moveSelect($('#'+timelineid+' div.timeline-entry'+selector+':'+wrapselc), timelineid)
		jqsel = $('#'+timelineid+' div.timeline-entry.ui-selected'+selector);
	} else {
		Spaz.dump('something is now selected');
		Spaz.Keyboard.moveSelect(jqsel[movefunc]('div.timeline-entry'+selector).eq(0), timelineid);
	}
	// if selected is at bottom, go to top
}

Spaz.Keyboard.moveSelect = function(jqelement, timelineid) {

	Spaz.dump('Moving to new selected item');

	Spaz.dump('jqelement.length:'+jqelement.length);

	// unselect everything
	$('#'+timelineid+' div.timeline-entry.ui-selected').removeClass('ui-selected').addClass('read');

	if ( entryId = Spaz.UI.getStatusIdFromElement(jqelement[0]) ) {
		Spaz.DB.markEntryAsRead(entryId);
	}

	// select passed
	if (jqelement.length > 0) {
		jqelement.toggleClass('ui-selected');
		$('#'+timelineid+'').scrollTo(jqelement, {
								offset:-25,
								speed:90,
								easing:'swing'
								}
		);
	} else {
		Spaz.dump("Problem - jqelement passed length = 0 - can't scroll to anything");
	}
}

/******************************
 * Keyboard
 ******************************/
Spaz.Keyboard.keyboardHandler = function(event) {
	e = event || window.event;
	el = e.srcElement || e.target;

	if (el.name) {
		return true;
	}

	if (e.which == 13 && e.srcElement.id == 'entrybox') {
		Spaz.UI.sendUpdate();
		return false;
	}

	// debugging
	if (e.srcElement.id == 'home') {
		Spaz.dump('keyboard Event =================');
		Spaz.dump("keyIdentifier:"+ e.keyIdentifier);
		Spaz.dump("KeyCode:" + e.keyCode);
		Spaz.dump("which:"+ e.which);
		Spaz.dump("type:"+ e.type);
		Spaz.dump("shift:"+ e.shiftKey);
		Spaz.dump("ctrl:"+ e.ctrlKey);
		Spaz.dump("alt:"+ e.altKey);
		Spaz.dump("meta:"+ e.metaKey);
		Spaz.dump("src:"+ e.srcElement.id);
	}

	return true;
}<commit_msg>- Enter in #search-for now starts search<commit_after>var Spaz; if (!Spaz) Spaz = {};

/***********
Spaz.UI
***********/
if (!Spaz.Keyboard) Spaz.Keyboard = {};

Spaz.Keyboard.setShortcuts = function() {
	Spaz.dump("Setting Shortcuts=================================================")
    Spaz.dump("os: " + air.Capabilities['os']);

	var Modkey = 'Meta';

	if (air.Capabilities['os'].search(/Windows/i) != -1) {
		Spaz.dump('THIS IS WINDOWS');
		Modkey = 'Ctrl';
	} else if (air.Capabilities['os'].search(/Linux/i) != -1) { // thx agolna
		Spaz.dump('THIS IS LINUX');
		Modkey = 'Ctrl';
	} else if (air.Capabilities['os'].search(/Mac/i) != -1) {
		Spaz.dump('THIS IS MACOS');
		Modkey = 'Meta';
	}

	Spaz.dump('Modkey is '+Modkey);

	shortcut.add(Modkey+'+T', function() {
		$('#entrybox').focus();
	})

	shortcut.add('F5', function() {
		Spaz.UI.reloadCurrentTab(true);
		Spaz.restartReloadTimer();
	})

	shortcut.add('Shift+F5', function() {
		Spaz.UI.clearCurrentTimeline();
		Spaz.UI.reloadCurrentTab(true);
		Spaz.restartReloadTimer();
	})

	shortcut.add(Modkey+'+Shift+A', function() {
		Spaz.UI.showShortLink();
	});

	shortcut.add(Modkey+'+Shift+M', function() {
		Spaz.UI.markCurrentTimelineAsRead();
	});

	shortcut.add('F1', function() {
		Spaz.UI.showHelp();
	});

	/*
		Added so we can open the preferences folder if the UI is hosed by bad CSS
	*/
	shortcut.add(Modkey+'+Shift+,', function() {
		Spaz.Sys.openAppStorageFolder();
	});

	shortcut.add(Modkey+'+Shift+@', function() {
			Spaz.dump('getting screenname from current selection');
			var screenname = $('div.ui-selected .user-screen-name').text();

			if (screenname) {
				Spaz.dump('username for reply is:'+screenname);
				// var username = '';
				Spaz.UI.prepReply(screenname);
			}
		}, {
			'disable_in_input':false
	});

	// ****************************************
	// tabs shortcuts
	// ****************************************
	shortcut.add(Modkey+'+1', function() {
		Spaz.UI.showTab(0);
	})
	shortcut.add(Modkey+'+2', function() {
		Spaz.UI.showTab(1);
	})
	shortcut.add(Modkey+'+3', function() {
		Spaz.UI.showTab(2);
	})
	shortcut.add(Modkey+'+4', function() {
		Spaz.UI.showTab(3);
	})
	shortcut.add(Modkey+'+5', function() {
		Spaz.UI.showTab(4);
	})
	shortcut.add(Modkey+'+6', function() {
		Spaz.UI.showTab(5);
	})
	shortcut.add(Modkey+'+7', function() {
		Spaz.UI.showTab(6);
	})
	shortcut.add(Modkey+'+,', function() {
		Spaz.UI.showPrefs()
	})

	// ****************************************
	// Keys to navigate timeline
	// ****************************************
	shortcut.add(Modkey+'+down', function() {
		Spaz.Keyboard.move('down', '.reply');
	});
	shortcut.add(Modkey+'+up', function() {
		Spaz.Keyboard.move('up', '.reply');
	});
	shortcut.add(Modkey+'+Shift+down', function() {
		Spaz.Keyboard.move('down', '.dm');
	});
	shortcut.add(Modkey+'+Shift+up', function() {
		Spaz.Keyboard.move('up', '.dm');
	});
	shortcut.add(Modkey+'+End', function() {
		Spaz.Keyboard.move('down', ':last');
	});
	shortcut.add(Modkey+'+Home', function() {
		Spaz.Keyboard.move('up', ':first');
	});
	shortcut.add('Down', function() {
			Spaz.Keyboard.move('down');
		}, {
			'disable_in_input':true
	});
	shortcut.add('Up', function() {
			Spaz.Keyboard.move('up');
		}, {
			'disable_in_input':true
	});
	shortcut.add(Modkey+'+J', function() {
		Spaz.Keyboard.move('down');
	});
	shortcut.add(Modkey+'+K', function() {
		Spaz.Keyboard.move('up');
	});
	shortcut.add('J', function() {
			Spaz.Keyboard.move('down');
		}, {
			'disable_in_input':true
	});
	shortcut.add('K', function() {
			Spaz.Keyboard.move('up');
		}, {
			'disable_in_input':true
	});

	shortcut.add(Modkey+'+F', function() {
			Spaz.UI.toggleTimelineFilter();
			return false;
		}, {
			type:'keypress',
			propagate:false
	});

	/*
		Search box submit on Enter
	*/
	shortcut.add('Enter', function() {
			Spaz.Section.search.build();
		}, {
			target:$('search-for')[0],
			type:'keypress',
			propagate:false
	});

	// ****************************************
	// editor shortcuts
	// ****************************************
	shortcut.add(Modkey+'+B', function() {
			Spaz.Editor.bold();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
	shortcut.add(Modkey+'+I', function() {
			Spaz.Editor.italics();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
	shortcut.add(Modkey+'+R', function() {
			Spaz.Editor.code();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
	shortcut.add(Modkey+'+U', function() {
			Spaz.Editor.link();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
	shortcut.add('Enter', function() {
			Spaz.UI.sendUpdate();
		}, {
			target:$('entrybox')[0],
			type:'keypress',
			propagate:false
	});
}

Spaz.Keyboard.move = function(dir, selector) {

	if (!selector) {
		selector = '';
	}

	Spaz.dump("selector is '" + selector+"'")

	var timelineid = 'timeline-friends';

	if (!dir) { dir = 'down' }

	if (dir == 'down') {
		var movefunc = 'nextAll';
		var wrapselc = 'first';
	} else if (dir == 'up') {
		dir = 'up'
		var movefunc = 'prevAll';
		var wrapselc = 'last';
	} else {
		return false;
	}

	// get current selected
	var jqsel = $('#'+timelineid+' div.ui-selected');
	// alert('selected:'+selected.length);
	//alert('moving:'+movefunc+'/'+wrapselc+"\n"+'selected:'+selected.length + "\n"+'current:'+selected.html());

	// if none selected, or there is no 'next', select first
	if (selector == ":first" || selector == ":last") {
		Spaz.dump('first in timeline')
		Spaz.Keyboard.moveSelect($('#'+timelineid+' div.timeline-entry'+selector), timelineid)
	} else if (jqsel.length == 0 ) {
		Spaz.dump('nothing is selected')
		Spaz.Keyboard.moveSelect($('#'+timelineid+' div.timeline-entry'+selector+':'+wrapselc), timelineid)
		jqsel = $('#'+timelineid+' div.timeline-entry.ui-selected'+selector);
	} else if (jqsel[movefunc]('div.timeline-entry'+selector).eq(0).length == 0) {
		Spaz.dump('we are at the beginning or end')
		Spaz.Keyboard.moveSelect($('#'+timelineid+' div.timeline-entry'+selector+':'+wrapselc), timelineid)
		jqsel = $('#'+timelineid+' div.timeline-entry.ui-selected'+selector);
	} else {
		Spaz.dump('something is now selected');
		Spaz.Keyboard.moveSelect(jqsel[movefunc]('div.timeline-entry'+selector).eq(0), timelineid);
	}
	// if selected is at bottom, go to top
}

Spaz.Keyboard.moveSelect = function(jqelement, timelineid) {

	Spaz.dump('Moving to new selected item');

	Spaz.dump('jqelement.length:'+jqelement.length);

	// unselect everything
	$('#'+timelineid+' div.timeline-entry.ui-selected').removeClass('ui-selected').addClass('read');

	if ( entryId = Spaz.UI.getStatusIdFromElement(jqelement[0]) ) {
		Spaz.DB.markEntryAsRead(entryId);
	}

	// select passed
	if (jqelement.length > 0) {
		jqelement.toggleClass('ui-selected');
		$('#'+timelineid+'').scrollTo(jqelement, {
								offset:-25,
								speed:90,
								easing:'swing'
								}
		);
	} else {
		Spaz.dump("Problem - jqelement passed length = 0 - can't scroll to anything");
	}
}

/******************************
 * Keyboard
 ******************************/
Spaz.Keyboard.keyboardHandler = function(event) {
	e = event || window.event;
	el = e.srcElement || e.target;

	if (el.name) {
		return true;
	}

	if (e.which == 13 && e.srcElement.id == 'entrybox') {
		Spaz.UI.sendUpdate();
		return false;
	}

	// debugging
	if (e.srcElement.id == 'home') {
		Spaz.dump('keyboard Event =================');
		Spaz.dump("keyIdentifier:"+ e.keyIdentifier);
		Spaz.dump("KeyCode:" + e.keyCode);
		Spaz.dump("which:"+ e.which);
		Spaz.dump("type:"+ e.type);
		Spaz.dump("shift:"+ e.shiftKey);
		Spaz.dump("ctrl:"+ e.ctrlKey);
		Spaz.dump("alt:"+ e.altKey);
		Spaz.dump("meta:"+ e.metaKey);
		Spaz.dump("src:"+ e.srcElement.id);
	}

	return true;
}<|endoftext|>