<commit_before>app.controller('MealCtrl', function ($scope, $rootScope, $ionicModal, $ionicLoading, $ionicPopup, Meals, $filter) {

  // Load or initialize projects
  $scope.meals = Meals.all();
  $scope.loggedInUser = angular.fromJson(window.localStorage['loggedInUser']);

  //
  $scope.breakfastList = [];
  $scope.lunchList = [];
  $scope.dinnerList = [];
  $scope.snackList = [];
  $scope.drinkList = [];

  $scope.meals.forEach(function(meal) {
    if(meal.cat == "breakfast"){
      $scope.breakfastList.push(meal);
    }
    if(meal.cat == "lunch"){
      $scope.lunchList.push(meal);
    }
    if(meal.cat == "dinner"){
      $scope.dinnerList.push(meal);
    }
    if(meal.cat == "snack"){
      $scope.snackList.push(meal);
    }
    if(meal.cat == "drink"){
      $scope.drinkList.push(meal);
    }

  });

  var getMeal = function(ID) {
      return $filter('filter')($scope.meals, {id: ID})[0];
  };

  $scope.getMealByID = function(ID) {
    return getMeal(ID);
  };

});

app.controller('RegistrationCtrl', function ($scope, $rootScope, $ionicModal, $ionicLoading, $ionicPopup, Meals, Registrations, $filter, $location, $state) {

  $scope.meals = Meals.all();
  $scope.registrations = Registrations.all();
  $scope.loggedInUser = angular.fromJson(window.localStorage['loggedInUser']);

  var getMeal = function(ID) {
      return $filter('filter')($scope.meals, {id: ID})[0];
  };

  var getRegistration = function(ID) {
      return $filter('filter')($scope.registrations, {rID: ID})[0];
  };

  $scope.getRegistrationUser = function(SSN) {
      return $filter('filter')($scope.registrations, {userSSN: parseInt(SSN)});
  };

  $scope.loggedInUserRegistrations = $scope.getRegistrationUser($scope.loggedInUser.SSN);

  $scope.getRegistrationByID = function(ID) {
    return getRegistration(ID);
  };

  $scope.registration = $scope.getRegistrationByID(window.localStorage['chosenRegID']);

  $scope.addMealToRegistration = function(regID, mealID) {

    var registration = getRegistration(regID);
    var meal = getMeal(mealID);
    meal.amount = 0;
    meal.mID = registration.meals.length+1;
    registration.meals.push(angular.copy(meal));
    Registrations.save($scope.registrations);
    $ionicLoading.show({ template: 'Tilføjet', noBackdrop: true, duration: 400 });
  };

  $scope.removeMealFromRegistration = function(id) {
    for(var i = $scope.registration.meals.length - 1; i >= 0; i--) {
      if($scope.registration.meals[i].mID == id) {
         $scope.registration.meals.splice(i, 1);
      }
    }
  };

  $scope.saveRegistration = function(regID) {
    var registration = getRegistration(regID);
    Registrations.save($scope.registrations);
    $scope.modal.hide();
  };

  $scope.openRegs = function(){
    $ionicModal.fromTemplateUrl('views/meal/kostregistrering.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
      $scope.modal.show();
    });
  };

  $scope.cancelReg = function () {
    $scope.modal.hide();
  };

  $scope.checkToCreateReg = function () {
    var today = new Date();
    var weekday=new Array("Søndag","Mandag","Tirsdag","Onsdag","Torsdag","Fredag","Lørdag");
    var monthname=new Array("Januar","Februar","Marts","April","Maj","Juni","Juli","August","September","October","November","December");
    var userSSN = $scope.loggedInUser.SSN;
    var title = weekday[today.getDay()] + " d. " + today.getDate() + ". " + monthname[today.getMonth()] + " " + today.getFullYear();

    var usersRegistrations = $scope.getRegistrationUser(userSSN);

    var isThereOneForToday = false;
    if(usersRegistrations.length > 0) {
        for(var i = usersRegistrations.length - 1; i >= 0; i--) {
          if(usersRegistrations[i].title == title) {
            //Der er oprettet, send videre
            isThereOneForToday = true;

            window.localStorage['chosenRegID'] = angular.toJson(usersRegistrations[i].rID);
            $location.path("/meal/breakfast");

            break;
          }
        } //endfor

    }

    if(!isThereOneForToday) {
      //opret så send
      var newRegistration =
        {
          "rID": $scope.registrations.length+1,
          "userSSN": parseInt(userSSN),
          "title": weekday[today.getDay()] + " d. " + today.getDate() + ". " + monthname[today.getMonth()] + " " + today.getFullYear(),
          "date": today,
          "meals": []
        };

      $scope.registrations.push(angular.copy(newRegistration));
      Registrations.save($scope.registrations);
      window.localStorage['chosenRegID'] = angular.toJson(newRegistration.rID);
      $location.path("/meal/breakfast");
    }

  };

  $scope.goToReg = function(rID) {
    window.localStorage['chosenRegID'] = angular.toJson(rID);
      $location.path("/meal/breakfast");
  };

});

app.controller('MealRecommendationCtrl', function($scope, Meals, $window, $ionicSideMenuDelegate){
	$scope.userWeight = 100;
	$scope.proteinToday = 75;
	$scope.energyToday = 6000;
	$scope.mealRecommendations = [];

	var date = new Date();
	var currentHour = date.getHours();
	console.log(currentHour);

	var breakfastRecommendations = angular.fromJson(window.localStorage['breakfastRecommendations']);
	var lunchRecommendations = angular.fromJson(window.localStorage['lunchRecommendations']);
	var dinnerRecommendations = angular.fromJson(window.localStorage['dinnerRecommendations']);
	var snackRecommendations = angular.fromJson(window.localStorage['snackRecommendations']);
	console.log(breakfastRecommendations);
	console.log(lunchRecommendations);
	console.log(dinnerRecommendations);
	console.log(snackRecommendations);

	if(currentHour > 6 && currentHour < 12)
	{
		breakfastRecommendations.forEach(function(meal){
			$scope.mealRecommendations.push(meal);
		});
	}
	else if(currentHour < 16)
	{
		lunchRecommendations.forEach(function(meal){
			$scope.mealRecommendations.push(meal);
		});
	}
	else if(currentHour < 22)
	{
		dinnerRecommendations.forEach(function(meal){
			$scope.mealRecommendations.push(meal);
		});
	}
	else
	{
		snackRecommendations.forEach(function(meal){
			$scope.mealRecommendations.push(meal);
		});
	}

	$scope.energyNeeded = function(energyPerKilo){
		return userWeight * energyPerKil - energyToday;
	}

	$scope.proteinNeeded = function(proteinPerKilo){
		return userWeight * proteinPerKilo - proteinToday;
	}

	$scope.recommendedBreakfast = function(proteinPerKilo){
		var breakfastProtein = proteinNeeded(proteinPerKilo) / 3;
		$scope.breakfastList.forEach(function(meal){
//			if(meal.protein)
		});
	}
})
<commit_msg>Close modal<commit_after>app.controller('MealCtrl', function ($scope, $rootScope, $ionicModal, $ionicLoading, $ionicPopup, Meals, $filter) {

  // Load or initialize projects
  $scope.meals = Meals.all();
  $scope.loggedInUser = angular.fromJson(window.localStorage['loggedInUser']);

  //
  $scope.breakfastList = [];
  $scope.lunchList = [];
  $scope.dinnerList = [];
  $scope.snackList = [];
  $scope.drinkList = [];

  $scope.meals.forEach(function(meal) {
    if(meal.cat == "breakfast"){
      $scope.breakfastList.push(meal);
    }
    if(meal.cat == "lunch"){
      $scope.lunchList.push(meal);
    }
    if(meal.cat == "dinner"){
      $scope.dinnerList.push(meal);
    }
    if(meal.cat == "snack"){
      $scope.snackList.push(meal);
    }
    if(meal.cat == "drink"){
      $scope.drinkList.push(meal);
    }

  });

  var getMeal = function(ID) {
      return $filter('filter')($scope.meals, {id: ID})[0];
  };

  $scope.getMealByID = function(ID) {
    return getMeal(ID);
  };

});

app.controller('RegistrationCtrl', function ($scope, $rootScope, $ionicModal, $ionicLoading, $ionicPopup, Meals, Registrations, $filter, $location, $state) {

  $scope.meals = Meals.all();
  $scope.registrations = Registrations.all();
  $scope.loggedInUser = angular.fromJson(window.localStorage['loggedInUser']);

  var getMeal = function(ID) {
      return $filter('filter')($scope.meals, {id: ID})[0];
  };

  var getRegistration = function(ID) {
      return $filter('filter')($scope.registrations, {rID: ID})[0];
  };

  $scope.getRegistrationUser = function(SSN) {
      return $filter('filter')($scope.registrations, {userSSN: parseInt(SSN)});
  };

  $scope.loggedInUserRegistrations = $scope.getRegistrationUser($scope.loggedInUser.SSN);

  $scope.getRegistrationByID = function(ID) {
    return getRegistration(ID);
  };

  $scope.registration = $scope.getRegistrationByID(window.localStorage['chosenRegID']);

  $scope.addMealToRegistration = function(regID, mealID) {

    var registration = getRegistration(regID);
    var meal = getMeal(mealID);
    meal.amount = 0;
    meal.mID = registration.meals.length+1;
    registration.meals.push(angular.copy(meal));
    Registrations.save($scope.registrations);
    $ionicLoading.show({ template: 'Tilføjet', noBackdrop: true, duration: 400 });
  };

  $scope.removeMealFromRegistration = function(id) {
    for(var i = $scope.registration.meals.length - 1; i >= 0; i--) {
      if($scope.registration.meals[i].mID == id) {
         $scope.registration.meals.splice(i, 1);
      }
    }
  };

  $scope.saveRegistration = function(regID) {
    var registration = getRegistration(regID);
    Registrations.save($scope.registrations);

    $scope.modal.hide();
  };

  $scope.openRegs = function(){
    $ionicModal.fromTemplateUrl('views/meal/kostregistrering.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
      $scope.modal.show();
    });
  };

  $scope.cancelReg = function () {
    $scope.modal.hide();
  };

  $scope.checkToCreateReg = function () {
    var today = new Date();
    var weekday=new Array("Søndag","Mandag","Tirsdag","Onsdag","Torsdag","Fredag","Lørdag");
    var monthname=new Array("Januar","Februar","Marts","April","Maj","Juni","Juli","August","September","October","November","December");
    var userSSN = $scope.loggedInUser.SSN;
    var title = weekday[today.getDay()] + " d. " + today.getDate() + ". " + monthname[today.getMonth()] + " " + today.getFullYear();

    var usersRegistrations = $scope.getRegistrationUser(userSSN);

    var isThereOneForToday = false;
    if(usersRegistrations.length > 0) {
        for(var i = usersRegistrations.length - 1; i >= 0; i--) {
          if(usersRegistrations[i].title == title) {
            //Der er oprettet, send videre
            isThereOneForToday = true;

            window.localStorage['chosenRegID'] = angular.toJson(usersRegistrations[i].rID);
            $location.path("/meal/breakfast");

            break;
          }
        } //endfor

    }

    if(!isThereOneForToday) {
      //opret så send
      var newRegistration =
        {
          "rID": $scope.registrations.length+1,
          "userSSN": parseInt(userSSN),
          "title": weekday[today.getDay()] + " d. " + today.getDate() + ". " + monthname[today.getMonth()] + " " + today.getFullYear(),
          "date": today,
          "meals": []
        };

      $scope.registrations.push(angular.copy(newRegistration));
      Registrations.save($scope.registrations);
      window.localStorage['chosenRegID'] = angular.toJson(newRegistration.rID);
      $location.path("/meal/breakfast");
    }

  };

  $scope.goToReg = function(rID) {
    window.localStorage['chosenRegID'] = angular.toJson(rID);
      $location.path("/meal/breakfast");
  };

});

app.controller('MealRecommendationCtrl', function($scope, Meals, $window, $ionicSideMenuDelegate){
	$scope.userWeight = 100;
	$scope.proteinToday = 75;
	$scope.energyToday = 6000;
	$scope.mealRecommendations = [];

	var date = new Date();
	var currentHour = date.getHours();
	console.log(currentHour);

	var breakfastRecommendations = angular.fromJson(window.localStorage['breakfastRecommendations']);
	var lunchRecommendations = angular.fromJson(window.localStorage['lunchRecommendations']);
	var dinnerRecommendations = angular.fromJson(window.localStorage['dinnerRecommendations']);
	var snackRecommendations = angular.fromJson(window.localStorage['snackRecommendations']);
	console.log(breakfastRecommendations);
	console.log(lunchRecommendations);
	console.log(dinnerRecommendations);
	console.log(snackRecommendations);

	if(currentHour > 6 && currentHour < 12)
	{
		breakfastRecommendations.forEach(function(meal){
			$scope.mealRecommendations.push(meal);
		});
	}
	else if(currentHour < 16)
	{
		lunchRecommendations.forEach(function(meal){
			$scope.mealRecommendations.push(meal);
		});
	}
	else if(currentHour < 22)
	{
		dinnerRecommendations.forEach(function(meal){
			$scope.mealRecommendations.push(meal);
		});
	}
	else
	{
		snackRecommendations.forEach(function(meal){
			$scope.mealRecommendations.push(meal);
		});
	}

	$scope.energyNeeded = function(energyPerKilo){
		return userWeight * energyPerKil - energyToday;
	}

	$scope.proteinNeeded = function(proteinPerKilo){
		return userWeight * proteinPerKilo - proteinToday;
	}

	$scope.recommendedBreakfast = function(proteinPerKilo){
		var breakfastProtein = proteinNeeded(proteinPerKilo) / 3;
		$scope.breakfastList.forEach(function(meal){
//			if(meal.protein)
		});
	}
})
<|endoftext|>


<commit_before>"use strict";

var Dragons = Dragons || {
    Class: GT.Class
};

(function(exports) {

    var Class = exports.Class;
    var Utils = exports.Utils;
    var Composite = exports.Composite;

    var BaseElement = GT.Class.create({
        rawData: null,
        userData: null,

        setRawData: function(rawData) {
            this.rawData = JSON.parse(JSON.stringify(rawData));
        },
        initAttributes: function(options) {
            var Me = this;
            options.forEach(function(op) {
                if (typeof op == "string") {
                    Me.initAttribute(op)
                } else {
                    Me.initAttribute(op[0], op[1], op[2]);
                }
            });
        },

        initAttribute: function(name, defaultValue, newName) {
            newName = newName || name;
            if (arguments.length == 1) {
                defaultValue = this[name];
            }
            var rawData = this.rawData;
            if (name in rawData) {
                this[newName] = rawData[name]
            } else {
                this[newName] = defaultValue;
            }
            return this[newName];
        },
        getDefaultTransform: function() {
            return {
                x: 0,
                y: 0,
                scX: 1,
                scY: 1,
                skX: 0,
                skY: 0,

                scaleX: 1,
                scaleY: 1,
                angle: 0,
                rotation: 0
            };
        },
        setTransform: function(transform) {
            var defaultValue = this.getDefaultTransform();

            this.transform = transform || {};
            for (var p in defaultValue) {
                if (!(p in this.transform)) {
                    this.transform[p] = defaultValue[p];
                }
            }
            this.transform.angle = this.transform.skX;
            this.transform.rotation = this.transform.skX * Math.PI / 180;
            this.transform.scaleX = this.transform.scX;
            this.transform.scaleY = this.transform.scY;
            var matrix = new Matrix(1, 0, 0, 1, 0, 0);
            matrix.rotate(this.transform.rotation);
            matrix.scale(this.transform.scaleX, this.transform.scaleY);
            matrix.translate(this.transform.x, this.transform.y);
            this.matrix = matrix;
        },

        getDefaultColor: function(color) {
            return {
                rO: 0,
                gO: 0,
                bO: 0,
                aO: 0,
                rM: 100,
                gM: 100,
                bM: 100,
                aM: 100
            };
        },

        setColorOffset: function(color) {
            // aM, rM, gM, bM, aO, rO, gO, bO
            var defaultValue = this.getDefaultColor();
            this.color = color || {};
            for (var p in defaultValue) {
                if (!(p in this.color)) {
                    this.color[p] = defaultValue[p];
                }
            }
        },

        setTweenEasing: function(tweenEasing) {
            if (tweenEasing === 0) {
                this.easingFunction = this.tweenLinear;
            } else if (!tweenEasing) {
                this.easingFunction = this.tweenNone;
            }
        },
        setTweenCurve: function(curve) {
            // var defaultValue = [
            //     0, 0,
            //     1, 1
            // ];
            this.curve = curve; // || defaultValue;
            if (curve) {
                this.easingFunction = this.createTweenBezier(curve);
            }
        },

        createTweenBezier: function(points) {
            var bezier = new BezierEasing(points);
            return function(t) {
                return bezier.get(t);
            };
        },

        tweenNone: function(t) {
            return t >= 1 ? 1 : 0;
        },
        tweenLinear: function(t) {
            return t;
        },

        easingFunction: function(t) {
            return t;
        },

        getTweenValue: function(a, b, passedPercent) {
            return a + (b - a) * this.easingFunction(passedPercent);
        },
        getTweenAngle: function(a, b, passedPercent, tweenRotate) {
            tweenRotate = tweenRotate || 0;

            var d = b - a;
            d = d % 360;

            if (d > 180) {
                d = 360 - d;
            } else if (d < -180) {
                d = 360 + d;
            }

            d += 360 * tweenRotate;

            if (d == 0) {
                return a;
            }

            // d = d % 360;
            // d += (d < 0 ? -1 : 1) * (360 * tweenRotate);

            // if (d == 0) {
            //     return a;
            // }
            // if (spin < 0) {
            //     d = d - 360;
            // } else {
            //     d = d + 360;
            // }
            // d = d % 360;
            // console.log(a, b, d, "--", spin,b-a)
            var ta = (a + d * this.easingFunction(passedPercent));
            // console.log(a, b, passedPercent, ta)
            return ta;
        },

        getTweenTransform: function(prevFrame, nextFrame, passedPercent) {
            var pT = prevFrame.transform;
            if (!nextFrame) {
                return {
                    x: pT.x,
                    y: pT.y,
                    scX: pT.scX,
                    scY: pT.scY,
                    skX: pT.skX,
                    skY: pT.skY,
                    scaleX: pT.scaleX,
                    scaleY: pT.scaleY,
                    angle: pT.angle,
                    rotation: pT.rotation,
                }
            }
            var nT = nextFrame.transform;
            var x = prevFrame.getTweenValue(pT.x, nT.x, passedPercent);
            var y = prevFrame.getTweenValue(pT.y, nT.y, passedPercent);
            var scaleX = prevFrame.getTweenValue(pT.scaleX, nT.scaleX, passedPercent);
            var scaleY = prevFrame.getTweenValue(pT.scaleY, nT.scaleY, passedPercent);
            var angle = prevFrame.getTweenAngle(pT.angle, nT.angle, passedPercent, prevFrame.tweenRotate);
            var transform = {
                x: x,
                y: y,
                scX: scaleX,
                scY: scaleY,
                skX: angle,
                skY: angle,
                scaleX: scaleX,
                scaleY: scaleY,
                angle: angle,
                rotation: angle * Math.PI / 180,
            };
            // console.log(transform)
            return transform;
        },

        getTweenColor: function(prevFrame, nextFrame, passedPercent) {
            var pC = prevFrame.color || this.getDefaultColor();
            if (!nextFrame) {
                return {
                    rO: pC.rO,
                    gO: pC.gO,
                    bO: pC.bO,
                    aO: pC.aO,
                    rM: pC.rM,
                    gM: pC.gM,
                    bM: pC.bM,
                    aM: pC.aM,
                }
            }
            var nC = nextFrame.color || this.getDefaultColor();
            var keys = [
                "rO", "gO", "bO", "aO",
                "rM", "gM", "bM", "aM",
            ];
            var color = {};
            var Me = this;
            keys.forEach(function(k) {
                color[k] = prevFrame.getTweenValue(pC[k], nC[k], passedPercent);
            });
            return color;
        },

        getFrameTweenInfo: function(index) {
            var prevFrame, nextFrame;
            var passed = 0;
            for (var i = 0, len = this.frames.length; i < len; i++) {
                var keyFrame = this.frames[i];
                // console.log(i, '-', keyFrame.startIndex, index, keyFrame.endIndex)
                if (keyFrame.startIndex <= index && index < keyFrame.endIndex) {
                    prevFrame = keyFrame;
                    passed = index - keyFrame.startIndex;
                    if (passed > 0) {
                        nextFrame = this.frames[i + 1] || null;
                    }
                    // console.log(passed)
                    break;
                }
            }
            // console.log(index, prevFrame);
            if (!prevFrame) {
                return null;
            }
            return {
                passed: passed,
                passedPercent: passed / prevFrame.duration,
                duration: prevFrame.duration,
                prevFrame: prevFrame,
                nextFrame: nextFrame
            };
        },

        strokeAABB: function(context, aabb) {
            context.beginPath();
            context.moveTo(aabb[0], aabb[1]);
            context.lineTo(aabb[2], aabb[1]);
            context.lineTo(aabb[2], aabb[3]);
            context.lineTo(aabb[0], aabb[3]);
            context.closePath();
            context.stroke();
        },

        strokePoly: function(context, vertices, color, tx, ty) {
            tx = tx || 0;
            ty = ty || 0;
            if (color) {
                context.strokeStyle = color;
            }
            var vertexCount = vertices.length;
            var a = vertices[0];
            var first = a;
            context.beginPath();
            context.moveTo(a[0] + tx, a[1] + ty);
            for (var j = 1; j < vertexCount; j++) {
                var a = vertices[j];
                context.lineTo(a[0] + tx, a[1] + ty);
            }
            context.closePath();
            context.stroke();
        }
    });

    exports.BaseElement = BaseElement;

}(Dragons));
<commit_msg>update<commit_after>"use strict";

var Dragons = Dragons || {
    Class: GT.Class
};

(function(exports) {

    var Class = exports.Class;
    var Utils = exports.Utils;
    var Composite = exports.Composite;

    var BaseElement = GT.Class.create({
        rawData: null,
        userData: null,

        setRawData: function(rawData) {
            this.rawData = JSON.parse(JSON.stringify(rawData));
        },
        initAttributes: function(options) {
            var Me = this;
            options.forEach(function(op) {
                if (typeof op == "string") {
                    Me.initAttribute(op)
                } else {
                    Me.initAttribute(op[0], op[1], op[2]);
                }
            });
        },

        initAttribute: function(name, defaultValue, newName) {
            newName = newName || name;
            if (arguments.length == 1) {
                defaultValue = this[name];
            }
            var rawData = this.rawData;
            if (name in rawData) {
                this[newName] = rawData[name]
            } else {
                this[newName] = defaultValue;
            }
            return this[newName];
        },
        getDefaultTransform: function() {
            return {
                x: 0,
                y: 0,
                scX: 1,
                scY: 1,
                skX: 0,
                skY: 0,

                scaleX: 1,
                scaleY: 1,
                angle: 0,
                rotation: 0
            };
        },
        setTransform: function(transform) {
            var defaultValue = this.getDefaultTransform();

            this.transform = transform || {};
            for (var p in defaultValue) {
                if (!(p in this.transform)) {
                    this.transform[p] = defaultValue[p];
                }
            }
            this.transform.angle = this.transform.skX;
            this.transform.rotation = this.transform.skX * Math.PI / 180;
            this.transform.scaleX = this.transform.scX;
            this.transform.scaleY = this.transform.scY;
            var matrix = new Matrix(1, 0, 0, 1, 0, 0);
            matrix.rotate(this.transform.rotation);
            matrix.scale(this.transform.scaleX, this.transform.scaleY);
            matrix.translate(this.transform.x, this.transform.y);
            this.matrix = matrix;
        },

        getDefaultColor: function(color) {
            return {
                rO: 0,
                gO: 0,
                bO: 0,
                aO: 0,
                rM: 100,
                gM: 100,
                bM: 100,
                aM: 100
            };
        },

        setColorOffset: function(color) {
            // aM, rM, gM, bM, aO, rO, gO, bO
            var defaultValue = this.getDefaultColor();
            this.color = color || {};
            for (var p in defaultValue) {
                if (!(p in this.color)) {
                    this.color[p] = defaultValue[p];
                }
            }
        },

        setTweenEasing: function(tweenEasing) {
            if (tweenEasing === 0) {
                this.easingFunction = this.tweenLinear;
            } else if (!tweenEasing) {
                this.easingFunction = this.tweenNone;
            }
        },
        setTweenCurve: function(curve) {
            // var defaultValue = [
            //     0, 0,
            //     1, 1
            // ];
            this.curve = curve; // || defaultValue;
            if (curve) {
                this.easingFunction = this.createTweenBezier(curve);
            }
        },

        createTweenBezier: function(points) {
            var bezier = new BezierEasing(points);
            return function(t) {
                return bezier.get(t);
            };
        },

        tweenNone: function(t) {
            return t >= 1 ? 1 : 0;
        },
        tweenLinear: function(t) {
            return t;
        },

        easingFunction: function(t) {
            return t;
        },

        clampAngle: function(angle) {
            angle = angle % 360;
            if (angle > 180) {
                angle = 360 - angle;
            } else if (angle < -180) {
                angle = 360 + angle;
            }
            return angle;
        },
        getTweenValue: function(a, b, passedPercent) {
            return a + (b - a) * this.easingFunction(passedPercent);
        },
        getTweenAngle: function(a, b, passedPercent, tweenRotate) {
            tweenRotate = tweenRotate || 0;

            var d = this.clampAngle(b - a);

            d += 360 * tweenRotate;

            if (d == 0) {
                return a;
            }

            // d = d % 360;
            // d += (d < 0 ? -1 : 1) * (360 * tweenRotate);

            // if (d == 0) {
            //     return a;
            // }
            // if (spin < 0) {
            //     d = d - 360;
            // } else {
            //     d = d + 360;
            // }
            // d = d % 360;
            // console.log(a, b, d, "--", spin,b-a)
            var ta = (a + d * this.easingFunction(passedPercent));
            // console.log(a, b, passedPercent, ta)
            return ta;
        },

        getTweenTransform: function(prevFrame, nextFrame, passedPercent) {
            var pT = prevFrame.transform;
            if (!nextFrame) {
                return {
                    x: pT.x,
                    y: pT.y,
                    scX: pT.scX,
                    scY: pT.scY,
                    skX: pT.skX,
                    skY: pT.skY,
                    scaleX: pT.scaleX,
                    scaleY: pT.scaleY,
                    angle: pT.angle,
                    rotation: pT.rotation,
                }
            }
            var nT = nextFrame.transform;
            var x = prevFrame.getTweenValue(pT.x, nT.x, passedPercent);
            var y = prevFrame.getTweenValue(pT.y, nT.y, passedPercent);
            var scaleX = prevFrame.getTweenValue(pT.scaleX, nT.scaleX, passedPercent);
            var scaleY = prevFrame.getTweenValue(pT.scaleY, nT.scaleY, passedPercent);

            var angle;

            var pA = pT.angle,
                nA = nT.angle;
            if (this.baseBone) {
                var baseAngle = this.baseBone.transform.angle;
                pA = this.clampAngle(pA + baseAngle);
                nA = this.clampAngle(nA + baseAngle);
                angle = prevFrame.getTweenAngle(pA, nA, passedPercent, prevFrame.tweenRotate);
                angle -= baseAngle;
            } else {
                angle = prevFrame.getTweenAngle(pA, nA, passedPercent, prevFrame.tweenRotate);
            }
            var transform = {
                x: x,
                y: y,
                scX: scaleX,
                scY: scaleY,
                skX: angle,
                skY: angle,
                scaleX: scaleX,
                scaleY: scaleY,
                angle: angle,
                rotation: angle * Math.PI / 180,
            };
            // console.log(transform)
            return transform;
        },

        getTweenColor: function(prevFrame, nextFrame, passedPercent) {
            var pC = prevFrame.color || this.getDefaultColor();
            if (!nextFrame) {
                return {
                    rO: pC.rO,
                    gO: pC.gO,
                    bO: pC.bO,
                    aO: pC.aO,
                    rM: pC.rM,
                    gM: pC.gM,
                    bM: pC.bM,
                    aM: pC.aM,
                }
            }
            var nC = nextFrame.color || this.getDefaultColor();
            var keys = [
                "rO", "gO", "bO", "aO",
                "rM", "gM", "bM", "aM",
            ];
            var color = {};
            var Me = this;
            keys.forEach(function(k) {
                color[k] = prevFrame.getTweenValue(pC[k], nC[k], passedPercent);
            });
            return color;
        },

        getFrameTweenInfo: function(index) {
            var prevFrame, nextFrame;
            var passed = 0;
            for (var i = 0, len = this.frames.length; i < len; i++) {
                var keyFrame = this.frames[i];
                // console.log(i, '-', keyFrame.startIndex, index, keyFrame.endIndex)
                if (keyFrame.startIndex <= index && index < keyFrame.endIndex) {
                    prevFrame = keyFrame;
                    passed = index - keyFrame.startIndex;
                    if (passed > 0) {
                        nextFrame = this.frames[i + 1] || null;
                    }
                    // console.log(passed)
                    break;
                }
            }
            // console.log(index, prevFrame);
            if (!prevFrame) {
                return null;
            }
            return {
                passed: passed,
                passedPercent: passed / prevFrame.duration,
                duration: prevFrame.duration,
                prevFrame: prevFrame,
                nextFrame: nextFrame
            };
        },

        strokeAABB: function(context, aabb) {
            context.beginPath();
            context.moveTo(aabb[0], aabb[1]);
            context.lineTo(aabb[2], aabb[1]);
            context.lineTo(aabb[2], aabb[3]);
            context.lineTo(aabb[0], aabb[3]);
            context.closePath();
            context.stroke();
        },

        strokePoly: function(context, vertices, color, tx, ty) {
            tx = tx || 0;
            ty = ty || 0;
            if (color) {
                context.strokeStyle = color;
            }
            var vertexCount = vertices.length;
            var a = vertices[0];
            var first = a;
            context.beginPath();
            context.moveTo(a[0] + tx, a[1] + ty);
            for (var j = 1; j < vertexCount; j++) {
                var a = vertices[j];
                context.lineTo(a[0] + tx, a[1] + ty);
            }
            context.closePath();
            context.stroke();
        }
    });

    exports.BaseElement = BaseElement;

}(Dragons));
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.fs.fileDropZone',
  name: 'FileDropZone',
  extends: 'foam.u2.Controller',

  documentation: 'A default zone to drag & drop files',

  requires: [
    'foam.log.LogLevel',
    'foam.blob.BlobBlob',
    'foam.nanos.fs.File',
    'foam.nanos.fs.FileArray'
  ],

  imports: [
    'ctrl',
    'user',
    'fileTypeDAO'
  ],

  exports: [
    'allowRemoval',
    'removeFile',
    'highlight'
  ],

  css: `
    ^ {
      box-sizing: border-box;
      max-width: 365px;
      padding: 16px;
      border: 2px dashed #8e9090;
      border-radius: 3px;
      box-shadow: inset 0 1px 2px 0 rgba(116, 122, 130, 0.21);
    }
    ^instruction-container {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      height: 228px;
    }
    ^instruction-container.selection {
      height: 172px;
      margin-bottom: 16px;
    }
    ^input {
      display: none;
    }
    ^title {
      font-size: 16px;
      font-weight: 900;
      margin: 0;
    }
    ^or {
      display: inline-block;
      vertical-align: bottom;
      margin: 0;
      margin-top: 8px;
    }
    ^link {
      display: inline-block;
      cursor: pointer;
      color: /*%PRIMARY3%*/ #406dea;
      margin: 0;
      margin-left: 5px;
    }
    ^caption-container {
      margin-top: 24px;
      position: relative;
      top: 60px;
    }
    ^caption {
      display: inline-block;
      font-size: 10px;
      color: #525455;
      margin: 0;
      margin-top: 4px;
    }
  `,

  messages: [
    { name: 'LABEL_DEFAULT_TITLE', message: 'Drag your file here' },
    { name: 'LABEL_OR',            message: 'or' },
    { name: 'LABEL_BROWSE',        message: 'select from your device' },
    { name: 'LABEL_SUPPORTED',     message: 'Supported file types:' },
    { name: 'LABEL_MAX_SIZE',      message: 'Max size:' },
    { name: 'ERROR_FILE_TYPE',     message: 'Invalid file type' },
    { name: 'ERROR_FILE_SIZE',     message: 'File size exceeds 15MB' }
  ],

  properties: [
    {
      class: 'String',
      name: 'title'
    },
    {
      name: 'supportedFormats',
      documentation: `Please use the following format: { 'image/jpg' : 'JPG' }`,
      value: {}
    },
    {
      class: 'Boolean',
      name: 'isMultipleFiles',
      value: true
    },
    {
      class: 'Boolean',
      name: 'allowRemoval',
      value: true
    },
    {
      class: 'foam.nanos.fs.FileArray',
      name: 'files',
      factory: function() {
        return [];
      }
    },
    {
      class: 'Long',
      name: 'maxSize',
      value: 15,
      documentation: 'Dictates maximum file size in MB (Megabyte).'
    },
    {
      name: 'onFilesChanged',
      documentation: 'When a file has been selected/changed/removed, this function will be called. (OPTIONAL)'
    },
    {
      name: 'selected'
    }
  ],

  methods: [
    async function initE() {
      this.SUPER();
      var self = this;

      if ( Object.keys(this.supportedFormats).length == 0 ) {
        let s = await this.fileTypeDAO.select()
        s.array.forEach(type => {
          this.supportedFormats[type.toSummary()] = type.abbreviation
        })
      }

      this
        .addClass(this.myClass())
        .start().addClass(this.myClass('instruction-container')).enableClass('selection', this.files$.map((v) => { return v.length > 0; }))
          .start('p').addClass(this.myClass('title')).add(this.title || this.LABEL_DEFAULT_TITLE).end()
          .start().addClass(this.myClass('browse-container'))
            .start('p').addClass(this.myClass('or')).add(this.LABEL_OR).end()
            .start('p').addClass(this.myClass('link'))
              .add(this.LABEL_BROWSE)
              .on('click', this.onAddAttachmentClicked)
            .end()
          .end()
          .start().addClass(this.myClass('caption-container')).hide(this.files$.map((v) => { return v.length > 0; }))
            .start()
              .start('p').addClass(this.myClass('caption')).add(this.LABEL_SUPPORTED).end()
              .start('p').addClass(self.myClass('caption')).add(this.getSupportedTypes(true)).end()
            .end()
            .start()
              .start('p').addClass(this.myClass('caption')).add(this.LABEL_MAX_SIZE + ' ' + this.maxSize + 'MB').end()
            .end()
          .end()
        .end()
        .add(this.slot(function(files) {
          var e = this.E();
          for ( var i = 0; i < files.length; i++ ) {
            e.tag({
              class: 'foam.nanos.fs.fileDropZone.FileCard',
              data: files[i],
              selected: this.selected,
              index: i
            });
          }
          return e;
        }, this.files$))
        .on('drop', this.onDrop)
        .on('dragover', (e) => { e.preventDefault() })
        .on('dragenter', (e) => { e.preventDefault() })
        .callIf(this.isMultipleFiles, function() {
          this.start('input')
            .addClass(this.myClass('input'))
            .addClass(this.instanceClass(`input`))
            .attrs({
              type: 'file',
              accept: this.getSupportedTypes(),
              multiple: 'multiple'
            })
            .on('change', this.onChange)
          .end();
        })
        .callIf(! this.isMultipleFiles, function() {
          this.start('input')
            .addClass(this.myClass('input'))
            .addClass(this.instanceClass(`input`))
            .attrs({
              type: 'file',
              accept: this.getSupportedTypes()
            })
            .on('change', this.onChange)
          .end();
        });
    },

    function getSupportedTypes(readable) {
      var supportedTypes = Object.keys(this.supportedFormats);
      var constructedString = '';

      if ( readable ) {
        supportedTypes.forEach((type, index) => {
          constructedString += this.supportedFormats[type];
          if ( index < supportedTypes.length - 1 ) {
            constructedString += ', ';
          }
        });
      } else {
        supportedTypes.forEach((type, index) => {
          constructedString += type;
          if ( index < supportedTypes.length - 1 ) {
            constructedString += ', ';
          }
        });
      }
      return constructedString;
    },

    function addFiles(files) {
      var errors = false;
      for ( var i = 0 ; i < files.length ; i++ ) {
        // skip files that exceed limit
        if ( files[i].size > ( this.maxSize * 1024 * 1024 ) ) {
          if ( ! errors ) errors = true;
          ctrl.notify(this.ERROR_FILE_SIZE, '', this.LogLevel.ERROR, true);
          continue;
        }
        var isIncluded = false;
        for ( var j = 0; j < this.files.length; j++ ) {
          if ( this.files[j].filename.localeCompare(files[i].name) === 0 ) {
            isIncluded = true;
            break;
          }
        }
        if ( isIncluded ) continue;
        if ( this.isMultipleFiles ) {
          var f = this.File.create({
            owner:    this.user.id,
            filename: files[i].name,
            filesize: files[i].size,
            mimeType: files[i].type,
            data:     this.BlobBlob.create({
              blob: files[i]
            })
          });
          this.files.push(f);
        } else {
          this.files[0] = this.File.create({
            owner:    this.user.id,
            filename: files[i].name,
            filesize: files[i].size,
            mimeType: files[i].type,
            data:     this.BlobBlob.create({
              blob: files[i]
            })
          });
        }
      }
      this.selected = this.files.length - 1;
      this.files = Array.from(this.files);
    },

    function isFileType(file) {
      return ( file.type in this.supportedFormats );
    },

    function removeFile(atIndex) {
      var files = Array.from(this.files);
      files.splice(atIndex, 1);
      debugger;
      if ( this.selected === files.length )
              this.selected = files.length - 1;
      this.files = files;
      this.document.querySelector('.' + this.instanceClass(`input`)).value = null;

    },

    function highlight(atIndex) {
      this.selected = atIndex;
      this.files = this.files;
    }
  ],

  listeners: [
    function onAddAttachmentClicked(e) {
      if ( typeof e.target != 'undefined' ) {
        if ( e.target.tagName == 'P' && e.target.tagName != 'A' ) {
          this.document.querySelector('.' + this.instanceClass(`input`)).click();
        }
      } else {
        // For IE browser
        if ( e.srcElement.tagName == 'P' && e.srcElement.tagName != 'A' ) {
          this.document.querySelector('.' + this.instanceClass(`input`)).click();
        }
      }
    },

    function onDrop(e) {
      e.preventDefault();
      var files = [];
      var inputFile;
      if ( e.dataTransfer.items ) {
        inputFile = e.dataTransfer.items;
        if ( inputFile ) {
          for ( var i = 0 ; i < inputFile.length ; i++ ) {
            // If dropped items aren't files, reject them
            if ( inputFile[i].kind === 'file' ) {
              var file = inputFile[i].getAsFile();
              if ( this.isFileType(file) ) {
                files.push(file);
              } else {
                ctrl.notify(this.ERROR_FILE_TYPE, '', this.LogLevel.ERROR, true);
              }
            }
          }
        }
      } else if ( e.dataTransfer.files ) {
        inputFile = e.dataTransfer.files;
        for ( var i = 0 ; i < inputFile.length ; i++ ) {
          var file = inputFile[i];
          if ( this.isFileType(file) ) {
            files.push(file);
          } else {
            ctrl.notify(this.ERROR_FILE_TYPE, '', this.LogLevel.ERROR, true);
          }
        }
      }
      this.addFiles(files);
    },

    function onChange(e) {
      var files = e.target.files;
      this.addFiles(files);
      // Remove all temporary files in the element.target.files
      this.document.querySelector('.' + this.instanceClass(`input`)).value = null;
    }
  ]
});
<commit_msg>remove debugger<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.fs.fileDropZone',
  name: 'FileDropZone',
  extends: 'foam.u2.Controller',

  documentation: 'A default zone to drag & drop files',

  requires: [
    'foam.log.LogLevel',
    'foam.blob.BlobBlob',
    'foam.nanos.fs.File',
    'foam.nanos.fs.FileArray'
  ],

  imports: [
    'ctrl',
    'user',
    'fileTypeDAO'
  ],

  exports: [
    'allowRemoval',
    'removeFile',
    'highlight'
  ],

  css: `
    ^ {
      box-sizing: border-box;
      max-width: 365px;
      padding: 16px;
      border: 2px dashed #8e9090;
      border-radius: 3px;
      box-shadow: inset 0 1px 2px 0 rgba(116, 122, 130, 0.21);
    }
    ^instruction-container {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      height: 228px;
    }
    ^instruction-container.selection {
      height: 172px;
      margin-bottom: 16px;
    }
    ^input {
      display: none;
    }
    ^title {
      font-size: 16px;
      font-weight: 900;
      margin: 0;
    }
    ^or {
      display: inline-block;
      vertical-align: bottom;
      margin: 0;
      margin-top: 8px;
    }
    ^link {
      display: inline-block;
      cursor: pointer;
      color: /*%PRIMARY3%*/ #406dea;
      margin: 0;
      margin-left: 5px;
    }
    ^caption-container {
      margin-top: 24px;
      position: relative;
      top: 60px;
    }
    ^caption {
      display: inline-block;
      font-size: 10px;
      color: #525455;
      margin: 0;
      margin-top: 4px;
    }
  `,

  messages: [
    { name: 'LABEL_DEFAULT_TITLE', message: 'Drag your file here' },
    { name: 'LABEL_OR',            message: 'or' },
    { name: 'LABEL_BROWSE',        message: 'select from your device' },
    { name: 'LABEL_SUPPORTED',     message: 'Supported file types:' },
    { name: 'LABEL_MAX_SIZE',      message: 'Max size:' },
    { name: 'ERROR_FILE_TYPE',     message: 'Invalid file type' },
    { name: 'ERROR_FILE_SIZE',     message: 'File size exceeds 15MB' }
  ],

  properties: [
    {
      class: 'String',
      name: 'title'
    },
    {
      name: 'supportedFormats',
      documentation: `Please use the following format: { 'image/jpg' : 'JPG' }`,
      value: {}
    },
    {
      class: 'Boolean',
      name: 'isMultipleFiles',
      value: true
    },
    {
      class: 'Boolean',
      name: 'allowRemoval',
      value: true
    },
    {
      class: 'foam.nanos.fs.FileArray',
      name: 'files',
      factory: function() {
        return [];
      }
    },
    {
      class: 'Long',
      name: 'maxSize',
      value: 15,
      documentation: 'Dictates maximum file size in MB (Megabyte).'
    },
    {
      name: 'onFilesChanged',
      documentation: 'When a file has been selected/changed/removed, this function will be called. (OPTIONAL)'
    },
    {
      name: 'selected'
    }
  ],

  methods: [
    async function initE() {
      this.SUPER();
      var self = this;

      if ( Object.keys(this.supportedFormats).length == 0 ) {
        let s = await this.fileTypeDAO.select()
        s.array.forEach(type => {
          this.supportedFormats[type.toSummary()] = type.abbreviation
        })
      }

      this
        .addClass(this.myClass())
        .start().addClass(this.myClass('instruction-container')).enableClass('selection', this.files$.map((v) => { return v.length > 0; }))
          .start('p').addClass(this.myClass('title')).add(this.title || this.LABEL_DEFAULT_TITLE).end()
          .start().addClass(this.myClass('browse-container'))
            .start('p').addClass(this.myClass('or')).add(this.LABEL_OR).end()
            .start('p').addClass(this.myClass('link'))
              .add(this.LABEL_BROWSE)
              .on('click', this.onAddAttachmentClicked)
            .end()
          .end()
          .start().addClass(this.myClass('caption-container')).hide(this.files$.map((v) => { return v.length > 0; }))
            .start()
              .start('p').addClass(this.myClass('caption')).add(this.LABEL_SUPPORTED).end()
              .start('p').addClass(self.myClass('caption')).add(this.getSupportedTypes(true)).end()
            .end()
            .start()
              .start('p').addClass(this.myClass('caption')).add(this.LABEL_MAX_SIZE + ' ' + this.maxSize + 'MB').end()
            .end()
          .end()
        .end()
        .add(this.slot(function(files) {
          var e = this.E();
          for ( var i = 0; i < files.length; i++ ) {
            e.tag({
              class: 'foam.nanos.fs.fileDropZone.FileCard',
              data: files[i],
              selected: this.selected,
              index: i
            });
          }
          return e;
        }, this.files$))
        .on('drop', this.onDrop)
        .on('dragover', (e) => { e.preventDefault() })
        .on('dragenter', (e) => { e.preventDefault() })
        .callIf(this.isMultipleFiles, function() {
          this.start('input')
            .addClass(this.myClass('input'))
            .addClass(this.instanceClass(`input`))
            .attrs({
              type: 'file',
              accept: this.getSupportedTypes(),
              multiple: 'multiple'
            })
            .on('change', this.onChange)
          .end();
        })
        .callIf(! this.isMultipleFiles, function() {
          this.start('input')
            .addClass(this.myClass('input'))
            .addClass(this.instanceClass(`input`))
            .attrs({
              type: 'file',
              accept: this.getSupportedTypes()
            })
            .on('change', this.onChange)
          .end();
        });
    },

    function getSupportedTypes(readable) {
      var supportedTypes = Object.keys(this.supportedFormats);
      var constructedString = '';

      if ( readable ) {
        supportedTypes.forEach((type, index) => {
          constructedString += this.supportedFormats[type];
          if ( index < supportedTypes.length - 1 ) {
            constructedString += ', ';
          }
        });
      } else {
        supportedTypes.forEach((type, index) => {
          constructedString += type;
          if ( index < supportedTypes.length - 1 ) {
            constructedString += ', ';
          }
        });
      }
      return constructedString;
    },

    function addFiles(files) {
      var errors = false;
      for ( var i = 0 ; i < files.length ; i++ ) {
        // skip files that exceed limit
        if ( files[i].size > ( this.maxSize * 1024 * 1024 ) ) {
          if ( ! errors ) errors = true;
          ctrl.notify(this.ERROR_FILE_SIZE, '', this.LogLevel.ERROR, true);
          continue;
        }
        var isIncluded = false;
        for ( var j = 0; j < this.files.length; j++ ) {
          if ( this.files[j].filename.localeCompare(files[i].name) === 0 ) {
            isIncluded = true;
            break;
          }
        }
        if ( isIncluded ) continue;
        if ( this.isMultipleFiles ) {
          var f = this.File.create({
            owner:    this.user.id,
            filename: files[i].name,
            filesize: files[i].size,
            mimeType: files[i].type,
            data:     this.BlobBlob.create({
              blob: files[i]
            })
          });
          this.files.push(f);
        } else {
          this.files[0] = this.File.create({
            owner:    this.user.id,
            filename: files[i].name,
            filesize: files[i].size,
            mimeType: files[i].type,
            data:     this.BlobBlob.create({
              blob: files[i]
            })
          });
        }
      }
      this.selected = this.files.length - 1;
      this.files = Array.from(this.files);
    },

    function isFileType(file) {
      return ( file.type in this.supportedFormats );
    },

    function removeFile(atIndex) {
      var files = Array.from(this.files);
      files.splice(atIndex, 1);
      if ( this.selected === files.length )
              this.selected = files.length - 1;
      this.files = files;
      this.document.querySelector('.' + this.instanceClass(`input`)).value = null;

    },

    function highlight(atIndex) {
      this.selected = atIndex;
      this.files = this.files;
    }
  ],

  listeners: [
    function onAddAttachmentClicked(e) {
      if ( typeof e.target != 'undefined' ) {
        if ( e.target.tagName == 'P' && e.target.tagName != 'A' ) {
          this.document.querySelector('.' + this.instanceClass(`input`)).click();
        }
      } else {
        // For IE browser
        if ( e.srcElement.tagName == 'P' && e.srcElement.tagName != 'A' ) {
          this.document.querySelector('.' + this.instanceClass(`input`)).click();
        }
      }
    },

    function onDrop(e) {
      e.preventDefault();
      var files = [];
      var inputFile;
      if ( e.dataTransfer.items ) {
        inputFile = e.dataTransfer.items;
        if ( inputFile ) {
          for ( var i = 0 ; i < inputFile.length ; i++ ) {
            // If dropped items aren't files, reject them
            if ( inputFile[i].kind === 'file' ) {
              var file = inputFile[i].getAsFile();
              if ( this.isFileType(file) ) {
                files.push(file);
              } else {
                ctrl.notify(this.ERROR_FILE_TYPE, '', this.LogLevel.ERROR, true);
              }
            }
          }
        }
      } else if ( e.dataTransfer.files ) {
        inputFile = e.dataTransfer.files;
        for ( var i = 0 ; i < inputFile.length ; i++ ) {
          var file = inputFile[i];
          if ( this.isFileType(file) ) {
            files.push(file);
          } else {
            ctrl.notify(this.ERROR_FILE_TYPE, '', this.LogLevel.ERROR, true);
          }
        }
      }
      this.addFiles(files);
    },

    function onChange(e) {
      var files = e.target.files;
      this.addFiles(files);
      // Remove all temporary files in the element.target.files
      this.document.querySelector('.' + this.instanceClass(`input`)).value = null;
    }
  ]
});
<|endoftext|>


<commit_before>/**
 * @ngdoc directive
 * @name defaultOption
 *
 * @description
 * Directive allowing to place a default option on select elements.
 **/
(function () {
  'use strict';

  angular.module('aa.formExtensions')
    //generate a label for an input generating an ID for it if it doesn't already exist
    .directive('defaultOption', ['aaFormExtensions', 'aaUtils', '$compile', '$injector', function (aaFormExtensions, aaUtils, $compile, $injector) {
      return {
          priority: -1000,
        link: function (scope, element, attrs) {
          //add default option if specified
          //if this is a select with a default-option attribute add a default option (per ng spec)
          if (element.prop('tagName').toUpperCase() === 'SELECT' && attrs.defaultOption !== undefined) {

            var msg = attrs.defaultOption;

            if (msg === null || msg === "") {

              //gen one
              msg = 'Select';

              if (attrs.aaLabel) {
                msg += ' a ' + attrs.aaLabel;
              }

              msg += '...';
            }

              var options = element.children('option[value=""]');

              if(!options.length) {
                element.append(angular.element('<option value=""></option>').html(msg));

              element.removeAttr('default-option');
              }
          }
        }
      };
    }]);
})();<commit_msg>Fixing defaultOption directive for ngOptions<commit_after>/**
 * @ngdoc directive
 * @name defaultOption
 *
 * @description
 * Directive allowing to place a default option on select elements.
 **/
(function () {
  'use strict';

  angular.module('aa.formExtensions')
    //generate a label for an input generating an ID for it if it doesn't already exist
    .directive('defaultOption', ['aaFormExtensions', 'aaUtils', '$compile', '$injector', function (aaFormExtensions, aaUtils, $compile, $injector) {
      return {
          priority: 1,
          compile: function (element, attrs) {
            return {
                pre: function (scope, element, attrs) {
                    //add default option if specified
                  //if this is a select with a default-option attribute add a default option (per ng spec)
                  if (element.prop('tagName').toUpperCase() === 'SELECT' && attrs.defaultOption !== undefined) {

                    var msg = attrs.defaultOption;

                    if (msg === null || msg === "") {

                      //gen one
                      msg = 'Select';

                      if (attrs.aaLabel) {
                        msg += ' a ' + attrs.aaLabel;
                      }

                      msg += '...';
                    }

                      var options = element.children('option[value=""]');

                      if(!options.length) {
                        element.append(angular.element('<option value=""></option>').html(msg));

                      element.removeAttr('default-option');
                      }
                  }
                }
            };
          }

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


<commit_before>import { Component } from 'react'
import styled from 'styled-components'
import TxList from '../../TxList.js'
import { statusMessage } from '../../../utils.js'
import ButtonPrimary from '../../Global/Buttons.ts'
var h = require('react-hyperscript')

class FailedBar extends Component {
  refund () {
    this.props.refund(this.props.assessment.address, this.props.assessment.stage)
  }

  showWhy () {
    console.log('TODO: explain why????')
  }

  render () {
    let assessment = this.props.assessment
    let userFault = assessment.userStage === assessment.stage
    let StageDescriptor = statusMessage(this.props.userAddress === assessment.assessee, assessment)
    return (
      h(containerProgressBar, [
        h(rowObjectText, StageDescriptor),
        (h(WhyButton, {onClick: this.showWhy.bind(this)}, 'Why?'),
        // has the user been at fault?
          !userFault
          // if not, has he been refunded yet?
            ? !assessment.refunded
            // user has not been refunded yet -> show button
              ? h(buttonProgressActive, {onClick: this.refund.bind(this)}, 'Refund')
              : h(buttonProgressActive, 'Refunded')
            : undefined),
        this.props.transactions
          ? h(TxList, {transactions: this.props.transactions})
          : null
      ])
    )
  }
}

// TODO add txList

export default FailedBar

export const FailedStatusText = styled('div')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

export const WhyButton = styled('button')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

export const RefundButton = styled('button')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

export const RefundedButton = styled('div')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

//

export const containerProgressBar = styled('div').attrs({className: 'flex flex-row w-100 pa3 items-center shadow-3'})`
margin-top: 1px;
min-height: 64px;
`

export const ProgressButton = styled('button')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

export const containerProgressButton = styled('div').attrs({className: 'flex w-auto items-center justify-center'})`
`

export const buttonProgressActive = styled('button').attrs({className: 'flex pv2 ph4 items-center justify-center br-pill bn ttu uppercase pointer shadow-1'})`
color: ${props => props.theme.tertiary};
background-color: ${props => props.theme.primary};
`

export const stageTexts = styled('h5').attrs({className: 'f5 fw4 mv0'})`
color: ${props => props.theme.primary};
`

// TODO need to rename to progressBarTextDescription
export const StageDescriptor = styled('div').attrs({className: 'flex w-auto items-center justify-center f5 gray debug'})`
color: ${props => props.theme.primary};
`

export const rowObjectButton = styled('div').attrs({className: 'flex w-auto items-center justify-center'})`
`

export const rowObjectText = styled('div').attrs({className: 'flex w-100 items-center justify-between br b--light-gray f5 gray'})`;
`
<commit_msg>updated box-shadow to match figma<commit_after>import { Component } from 'react'
import styled from 'styled-components'
import TxList from '../../TxList.js'
import { statusMessage } from '../../../utils.js'
import ButtonPrimary from '../../Global/Buttons.ts'
var h = require('react-hyperscript')

class FailedBar extends Component {
  refund () {
    this.props.refund(this.props.assessment.address, this.props.assessment.stage)
  }

  showWhy () {
    console.log('TODO: explain why????')
  }

  render () {
    let assessment = this.props.assessment
    let userFault = assessment.userStage === assessment.stage
    let StageDescriptor = statusMessage(this.props.userAddress === assessment.assessee, assessment)
    return (
      h(containerProgressBar, [
        h(rowObjectText, StageDescriptor),
        (h(WhyButton, {onClick: this.showWhy.bind(this)}, 'Why?'),
        // has the user been at fault?
          !userFault
          // if not, has he been refunded yet?
            ? !assessment.refunded
            // user has not been refunded yet -> show button
              ? h(buttonProgressActive, {onClick: this.refund.bind(this)}, 'Refund')
              : h(buttonProgressActive, 'Refunded')
            : undefined),
        this.props.transactions
          ? h(TxList, {transactions: this.props.transactions})
          : null
      ])
    )
  }
}

// TODO add txList

export default FailedBar

export const FailedStatusText = styled('div')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

export const WhyButton = styled('button')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

export const RefundButton = styled('button')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

export const RefundedButton = styled('div')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

//

export const containerProgressBar = styled('div').attrs({className: 'flex flex-row w-100 pa3 items-center shadow-4'})`
margin-top: 1px;
min-height: 64px;
background-color: ${props => props.theme.bgSecondary};
`

export const ProgressButton = styled('button')`
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
`

export const containerProgressButton = styled('div').attrs({className: 'flex w-auto items-center justify-center'})`
`

export const buttonProgressActive = styled('button').attrs({className: 'flex pv2 ph4 items-center justify-center br-pill bn ttu uppercase pointer shadow-1'})`
color: ${props => props.theme.tertiary};
background-color: ${props => props.theme.primary};
`

export const stageTexts = styled('h5').attrs({className: 'f5 fw4 mv0'})`
color: ${props => props.theme.primary};
`

// TODO need to rename to progressBarTextDescription
export const StageDescriptor = styled('div').attrs({className: 'flex w-auto items-center justify-center f5 gray debug'})`
color: ${props => props.theme.primary};
`

export const rowObjectButton = styled('div').attrs({className: 'flex w-auto items-center justify-center'})`
`

export const rowObjectText = styled('div').attrs({className: 'flex w-100 items-center justify-between br b--light-gray f5 gray'})`;
`
<|endoftext|>