<commit_before>// map controller
// public/map.js

findMate.controller('singleMeetingController', ['$scope', '$http', '$routeParams', '$location', '$mdSidenav', '$mdDialog', 'editService',
                    function($scope,
                             $http,
                             $routeParams,
                             $location,
                             $mdSidenav,
                             $mdDialog,
                             editService) {
    //init logged in user
    $scope.$watch('logged_in_user', function () {
        $scope.loadFriends();
    });

    $scope.$watch('currentMeeting', function () {
        $scope.currentMeetingId = $scope.currentMeeting._id;
        console.log($scope.meetingId);
    });

    // join meeting

    $scope.joinMeeting = function(id){

        $http.put('/join/meetings/' + id)
            .success(function (data) {
                $scope.meetings = data;
                var meetings = $scope.meetings;
                console.log(data);
                var meetingsLength = meetings.length;
                 for(var i = 0; i < meetingsLength; i++) {
                     var meeting = meetings[i];
                     if (meeting._id === id){
                        meeting.joined = true;
                        console.log(meeting);
                     }

                 }

            })
            .error(function (data) {
                console.log('Error: ' + data);
            })
    };

    $scope.unjoinMeeting = function(id){

        $http.put('/unjoin/meetings/' + id)
            .success(function (data) {
                $scope.meetings = data;
                var meetings = $scope.meetings;
                console.log(data);
                var meetingsLength = meetings.length;
                 for(var i = 0; i < meetingsLength; i++) {
                     var meeting = meetings[i];
                     if (meeting._id === id){
                        meeting.joined = false;
                        console.log(meeting);
                     }
                 }
            })
            .error(function (data) {
                console.log('Error: ' + data);
            })
    };

         $scope.loadFriends = function(){
             var friendsRequest = 'https://graph.facebook.com/' + $scope.logged_in_user.facebook.id + '/friends' + '?access_token=' + $scope.logged_in_user.facebook.token;
             $http.get(friendsRequest)
                 .success(function(data) {
                     $scope.friends = data.data;
                 })
                 .error(function (data) {
                     console.log('Error: ' + data);
                 });
         };

    // delete a todo after checking it
    $scope.deleteMeeting = function(id) {
        $http.delete('../api/meeting/' + id)
            .success(function (data) {
                $scope.meetings = data;
                console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

    $scope.declineInvitation = function(id){

        $http.put('/decline/meetings/' + id)
            .success(function (data) {
                $scope.meetings = data;
                var meetings = $scope.meetings;
                console.log(data);
                var meetingsLength = meetings.length;
                 for(var i = 0; i < meetingsLength; i++) {
                     var meeting = meetings[i];
                     if (meeting._id === id){
                        meeting.invited = false;
                        console.log(meeting);
                     }
                 }
            })
            .error(function (data) {
                console.log('Error: ' + data);
            })
    };

    // side nav
    $scope.toggleNav = function() {
       $mdSidenav('nav').toggle();
    };

    //edit service update

    $scope.$watch('meetingId', function() {
        editService.getId($scope.meetingId, $scope.logged_in_user);
    });

    $scope.$on('valuesUpdated', function() {
        $scope.meetingId = editService.meetingId;
        $scope.logged_in_user = editService.user;
    });

    // edit meeting dialog
    $scope.editMeeting = function(id){
        $scope.meetingId = id;
        console.log($scope.meetingId);
        $scope.showDialog();
    };

    $scope.showDialog = function(ev){
        $mdDialog.show({
          controller: 'EditMeetingController',
          templateUrl: '../public/partials/editMeeting.tmpl.ejs',
          targetEvent: ev
             }).then(function(data) {
                  $scope.refresh();
                  console.log('refreshed')
             }, function() {
                  $scope.refresh();
             })
    };

    $scope.refresh = function(){
        $http.get('../api/meetings/' + currentMeetingId)
        .success(function(data) {
            $scope.meeting = data;
            var meeting = $scope.meeting;
            console.log(data);
            var dateNow = new Date().toJSON();

                 //remove duplicates, delete this part later
                 meeting.invitedUsers = _.uniq(meeting.invitedUsers,
                    function(item, key, a){
                        return item.a;
                    });

                 meeting.participants = _.uniq(meeting.participants,
                    function(item, key, a){
                        return item.a;
                    });

                 // date filter
                 var meetingDate = meeting.startDate;
                 if (meetingDate > dateNow){
                     meeting.active = true;
                 } else {
                    meeting.active = false;
                 };// end date filter

                 //invited filter
                 var invitedArray = meeting.invitedUsers;
                 var invitedArrayLength = invitedArray.length;
                 for (var u = 0; u< invitedArrayLength; u++){
                    var invitedUser = invitedArray[u];
                    if(invitedUser._id === $scope.logged_in_user._id){
                        meeting.invited = true;
                    } else {
                        meeting.invited = false;
                    }
                    console.log(meeting.invited);
                 }// end invited filter

                 // participants filter
                 var participantsArray = meeting.participants;
                 var participantsArrayLength = participantsArray.length;
                 for (var j = 0; j < participantsArrayLength; j++){
                    var joinedUser = participantsArray[j];
                    if(joinedUser._id === $scope.logged_in_user._id){
                        meeting.joined = true;
                    } else {
                        meeting.joined = false;
                    }
                    console.log(meeting.joined);
                 }// end participants filter

        })
        .error(function (data) {
            console.log('Error: ' + data);
        });
    }

    /*$scope.refresh = function(){
        $http.get('../api/meetings')
        .success(function(data) {
            $scope.meetings = data;
            var meetings = $scope.meetings;
            console.log(data);
            var dateNow = new Date().toJSON();

            // loop through data
            var meetingsLength = meetings.length;
             for(var i = 0; i < meetingsLength; i++) {
                 var meeting = meetings[i];

                 //remove duplicates, delete this part later
                 meeting.invitedUsers = _.uniq(meeting.invitedUsers,
                    function(item, key, a){
                        return item.a;
                    });

                 meeting.participants = _.uniq(meeting.participants,
                    function(item, key, a){
                        return item.a;
                    });

                 // date filter
                 var meetingDate = meeting.startDate;
                 if (meetingDate > dateNow){
                     meeting.active = true;
                 } else {
                    meeting.active = false;
                 };// end date filter

                 //invited filter
                 var invitedArray = meeting.invitedUsers;
                 var invitedArrayLength = invitedArray.length;
                 for (var u = 0; u< invitedArrayLength; u++){
                    var invitedUser = invitedArray[u];
                    if(invitedUser._id === $scope.logged_in_user._id){
                        meeting.invited = true;
                    } else {
                        meeting.invited = false;
                    }
                    console.log(meeting.invited);
                 }// end invited filter

                 // participants filter
                 var participantsArray = meeting.participants;
                 var participantsArrayLength = participantsArray.length;
                 for (var j = 0; j < participantsArrayLength; j++){
                    var joinedUser = participantsArray[j];
                    if(joinedUser._id === $scope.logged_in_user._id){
                        meeting.joined = true;
                    } else {
                        meeting.joined = false;
                    }
                    console.log(meeting.joined);
                 }// end participants filter

             }; // end for loop
        })
        .error(function (data) {
            console.log('Error: ' + data);
        });
    }*/
}]);<commit_msg>change refresh to get single<commit_after>// map controller
// public/map.js

findMate.controller('singleMeetingController', ['$scope', '$http', '$routeParams', '$location', '$mdSidenav', '$mdDialog', 'editService',
                    function($scope,
                             $http,
                             $routeParams,
                             $location,
                             $mdSidenav,
                             $mdDialog,
                             editService) {
    //init logged in user
    $scope.$watch('logged_in_user', function () {
        $scope.loadFriends();
    });

    $scope.$watch('currentMeeting', function () {
        console.log($scope.currentMeeting);
        $scope.currentMeetingId = $scope.currentMeeting._id;
        console.log($scope.meetingId);
    });

    // join meeting

    $scope.joinMeeting = function(id){

        $http.put('/join/meetings/' + id)
            .success(function (data) {
                $scope.meetings = data;
                var meetings = $scope.meetings;
                console.log(data);
                var meetingsLength = meetings.length;
                 for(var i = 0; i < meetingsLength; i++) {
                     var meeting = meetings[i];
                     if (meeting._id === id){
                        meeting.joined = true;
                        console.log(meeting);
                     }

                 }

            })
            .error(function (data) {
                console.log('Error: ' + data);
            })
    };

    $scope.unjoinMeeting = function(id){

        $http.put('/unjoin/meetings/' + id)
            .success(function (data) {
                $scope.meetings = data;
                var meetings = $scope.meetings;
                console.log(data);
                var meetingsLength = meetings.length;
                 for(var i = 0; i < meetingsLength; i++) {
                     var meeting = meetings[i];
                     if (meeting._id === id){
                        meeting.joined = false;
                        console.log(meeting);
                     }
                 }
            })
            .error(function (data) {
                console.log('Error: ' + data);
            })
    };

         $scope.loadFriends = function(){
             var friendsRequest = 'https://graph.facebook.com/' + $scope.logged_in_user.facebook.id + '/friends' + '?access_token=' + $scope.logged_in_user.facebook.token;
             $http.get(friendsRequest)
                 .success(function(data) {
                     $scope.friends = data.data;
                 })
                 .error(function (data) {
                     console.log('Error: ' + data);
                 });
         };

    // delete a todo after checking it
    $scope.deleteMeeting = function(id) {
        $http.delete('../api/meeting/' + id)
            .success(function (data) {
                $scope.meetings = data;
                console.log(data);
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

    $scope.declineInvitation = function(id){

        $http.put('/decline/meetings/' + id)
            .success(function (data) {
                $scope.meetings = data;
                var meetings = $scope.meetings;
                console.log(data);
                var meetingsLength = meetings.length;
                 for(var i = 0; i < meetingsLength; i++) {
                     var meeting = meetings[i];
                     if (meeting._id === id){
                        meeting.invited = false;
                        console.log(meeting);
                     }
                 }
            })
            .error(function (data) {
                console.log('Error: ' + data);
            })
    };

    // side nav
    $scope.toggleNav = function() {
       $mdSidenav('nav').toggle();
    };

    //edit service update

    $scope.$watch('meetingId', function() {
        editService.getId($scope.meetingId, $scope.logged_in_user);
    });

    $scope.$on('valuesUpdated', function() {
        $scope.meetingId = editService.meetingId;
        $scope.logged_in_user = editService.user;
    });

    // edit meeting dialog
    $scope.editMeeting = function(id){
        $scope.meetingId = id;
        console.log($scope.meetingId);
        $scope.showDialog();
    };

    $scope.showDialog = function(ev){
        $mdDialog.show({
          controller: 'EditMeetingController',
          templateUrl: '../public/partials/editMeeting.tmpl.ejs',
          targetEvent: ev
             }).then(function(data) {
                  $scope.refresh();
                  console.log('refreshed')
             }, function() {
                  $scope.refresh();
             })
    };

    $scope.refresh = function(){
        $http.get('../api/meetings/' + currentMeetingId)
        .success(function(data) {
            $scope.meeting = data;
            var meeting = $scope.meeting;
            console.log(data);
            var dateNow = new Date().toJSON();

                 //remove duplicates, delete this part later
                 meeting.invitedUsers = _.uniq(meeting.invitedUsers,
                    function(item, key, a){
                        return item.a;
                    });

                 meeting.participants = _.uniq(meeting.participants,
                    function(item, key, a){
                        return item.a;
                    });

                 // date filter
                 var meetingDate = meeting.startDate;
                 if (meetingDate > dateNow){
                     meeting.active = true;
                 } else {
                    meeting.active = false;
                 };// end date filter

                 //invited filter
                 var invitedArray = meeting.invitedUsers;
                 var invitedArrayLength = invitedArray.length;
                 for (var u = 0; u< invitedArrayLength; u++){
                    var invitedUser = invitedArray[u];
                    if(invitedUser._id === $scope.logged_in_user._id){
                        meeting.invited = true;
                    } else {
                        meeting.invited = false;
                    }
                    console.log(meeting.invited);
                 }// end invited filter

                 // participants filter
                 var participantsArray = meeting.participants;
                 var participantsArrayLength = participantsArray.length;
                 for (var j = 0; j < participantsArrayLength; j++){
                    var joinedUser = participantsArray[j];
                    if(joinedUser._id === $scope.logged_in_user._id){
                        meeting.joined = true;
                    } else {
                        meeting.joined = false;
                    }
                    console.log(meeting.joined);
                 }// end participants filter

        })
        .error(function (data) {
            console.log('Error: ' + data);
        });
    }

    /*$scope.refresh = function(){
        $http.get('../api/meetings')
        .success(function(data) {
            $scope.meetings = data;
            var meetings = $scope.meetings;
            console.log(data);
            var dateNow = new Date().toJSON();

            // loop through data
            var meetingsLength = meetings.length;
             for(var i = 0; i < meetingsLength; i++) {
                 var meeting = meetings[i];

                 //remove duplicates, delete this part later
                 meeting.invitedUsers = _.uniq(meeting.invitedUsers,
                    function(item, key, a){
                        return item.a;
                    });

                 meeting.participants = _.uniq(meeting.participants,
                    function(item, key, a){
                        return item.a;
                    });

                 // date filter
                 var meetingDate = meeting.startDate;
                 if (meetingDate > dateNow){
                     meeting.active = true;
                 } else {
                    meeting.active = false;
                 };// end date filter

                 //invited filter
                 var invitedArray = meeting.invitedUsers;
                 var invitedArrayLength = invitedArray.length;
                 for (var u = 0; u< invitedArrayLength; u++){
                    var invitedUser = invitedArray[u];
                    if(invitedUser._id === $scope.logged_in_user._id){
                        meeting.invited = true;
                    } else {
                        meeting.invited = false;
                    }
                    console.log(meeting.invited);
                 }// end invited filter

                 // participants filter
                 var participantsArray = meeting.participants;
                 var participantsArrayLength = participantsArray.length;
                 for (var j = 0; j < participantsArrayLength; j++){
                    var joinedUser = participantsArray[j];
                    if(joinedUser._id === $scope.logged_in_user._id){
                        meeting.joined = true;
                    } else {
                        meeting.joined = false;
                    }
                    console.log(meeting.joined);
                 }// end participants filter

             }; // end for loop
        })
        .error(function (data) {
            console.log('Error: ' + data);
        });
    }*/
}]);<|endoftext|>


<commit_before><commit_msg>Initial Commit<commit_after><|endoftext|>


<commit_before>/**
 * This Source Code is licensed under the MIT license. If a copy of the
 * MIT-license was not distributed with this file, You can obtain one at:
 * http://opensource.org/licenses/mit-license.html.
 *
 * @author: Hein Rutjes (IjzerenHein)
 * @license MIT
 * @copyright Gloey Apps, 2015
 */

/*global console*/
/*eslint no-console: 0*/

/**
 * Lays out renderables based on Apple's Visual Format Language.
 *
 * @module
 */
define(function(require, exports, module) {

	// import dependencies
	var AutoLayout = require('autolayout');

    function _setSpacing(view, spacing) {
        view.setSpacing(spacing);
    }

    function _setIntrinsicWidths(context, view, widths) {
        for (var key in widths) {
            var subView = view.subViews[key];
            if (subView) {
                subView.intrinsicWidth = (widths[key] === true) ? context.resolveSize(key, context.size)[0] : widths[key];
            }
        }
    }

    function _setIntrinsicHeights(context, view, heights) {
        for (var key in heights) {
            var subView = view.subViews[key];
            if (subView) {
                subView.intrinsicHeight = (heights[key] === true) ? context.resolveSize(key, context.size)[1] : heights[key];
            }
        }
    }

    function _setViewPortSize(context, view, vp) {
        var size = [
            ((vp.width !== undefined) && (vp.width !== true)) ? vp.width : Math.max(Math.min(context.size[0], vp['max-width'] || context.size[0]), vp['min-width'] || 0),
            ((vp.height !== undefined) && (vp.height !== true)) ? vp.height : Math.max(Math.min(context.size[1], vp['max-height'] || context.size[1]), vp['min-height'] || 0)
        ];
        if ((vp.width === true) && (vp.height === true)) {
            size[0] = view.fittingWidth;
            size[1] = view.fittingHeight;
        }
        else if (vp.width === true) {
            view.setSize(undefined, size[1]);
            size[0] = view.fittingWidth;
            // TODO ASPECT RATIO?
        }
        else if (vp.height === true) {
            view.setSize(size[0], undefined);
            size[1] = view.fittingHeight;
            // TODO ASPECT RATIO?
        }
        else {
            size = vp['aspect-ratio'] ? [
                Math.min(size[0], size[1] * vp['aspect-ratio']),
                Math.min(size[1], size[0] / vp['aspect-ratio'])
            ] : size;
            view.setSize(size[0], size[1]);
        }
        return size;
    }

	function vflToLayout(visualFormat, viewOptions) {
		var view = new AutoLayout.View(viewOptions);
		try {
			var constraints = AutoLayout.VisualFormat.parse(visualFormat, {extended: true, strict: false});
			var metaInfo = AutoLayout.VisualFormat.parseMetaInfo ? AutoLayout.VisualFormat.parseMetaInfo(visualFormat) : {};
			view.addConstraints(constraints);
			return function(context, options) {
				var key;
				var subView;
                var x;
                var y;
                if (options.spacing || metaInfo.spacing) {
                    _setSpacing(view, options.spacing || metaInfo.spacing);
                }
                if (options.widths || metaInfo.widths) {
                    _setIntrinsicWidths(context, view, options.widths || metaInfo.widths);
                }
                if (options.heights || metaInfo.heights) {
                    _setIntrinsicHeights(context, view, options.heights || metaInfo.heights);
                }
				if (options.viewport || metaInfo.viewport) {
                    var size = _setViewPortSize(context, view, options.viewport || metaInfo.viewport);
                    x = (context.size[0] - size[0]) / 2;
                    y = (context.size[1] - size[1]) / 2;
                }
                else {
                    view.setSize(context.size[0], context.size[1]);
                    x = 0;
                    y = 0;
                }
				for (key in view.subViews) {
					subView = view.subViews[key];
					if ((key.indexOf('_') !== 0) && (subView.type !== 'stack')) {
						context.set(subView.name, {
							size: [subView.width, subView.height],
							translate: [x + subView.left, y + subView.top, subView.zIndex * 5]
						});
					}
				}
			};
		}
		catch (err) {
			console.log(err); //eslint-disable-line no-console
		}
	}

    module.exports = vflToLayout;
});
<commit_msg>Fixed exception when LayoutController specified no options<commit_after>/**
 * This Source Code is licensed under the MIT license. If a copy of the
 * MIT-license was not distributed with this file, You can obtain one at:
 * http://opensource.org/licenses/mit-license.html.
 *
 * @author: Hein Rutjes (IjzerenHein)
 * @license MIT
 * @copyright Gloey Apps, 2015
 */

/*global console*/
/*eslint no-console: 0*/

/**
 * Lays out renderables based on Apple's Visual Format Language.
 *
 * @module
 */
define(function(require, exports, module) {

    // import dependencies
    var AutoLayout = require('autolayout');

    function _setSpacing(view, spacing) {
        view.setSpacing(spacing);
    }

    function _setIntrinsicWidths(context, view, widths) {
        for (var key in widths) {
            var subView = view.subViews[key];
            if (subView) {
                subView.intrinsicWidth = (widths[key] === true) ? context.resolveSize(key, context.size)[0] : widths[key];
            }
        }
    }

    function _setIntrinsicHeights(context, view, heights) {
        for (var key in heights) {
            var subView = view.subViews[key];
            if (subView) {
                subView.intrinsicHeight = (heights[key] === true) ? context.resolveSize(key, context.size)[1] : heights[key];
            }
        }
    }

    function _setViewPortSize(context, view, vp) {
        var size = [
            ((vp.width !== undefined) && (vp.width !== true)) ? vp.width : Math.max(Math.min(context.size[0], vp['max-width'] || context.size[0]), vp['min-width'] || 0),
            ((vp.height !== undefined) && (vp.height !== true)) ? vp.height : Math.max(Math.min(context.size[1], vp['max-height'] || context.size[1]), vp['min-height'] || 0)
        ];
        if ((vp.width === true) && (vp.height === true)) {
            size[0] = view.fittingWidth;
            size[1] = view.fittingHeight;
        }
        else if (vp.width === true) {
            view.setSize(undefined, size[1]);
            size[0] = view.fittingWidth;
            // TODO ASPECT RATIO?
        }
        else if (vp.height === true) {
            view.setSize(size[0], undefined);
            size[1] = view.fittingHeight;
            // TODO ASPECT RATIO?
        }
        else {
            size = vp['aspect-ratio'] ? [
                Math.min(size[0], size[1] * vp['aspect-ratio']),
                Math.min(size[1], size[0] / vp['aspect-ratio'])
            ] : size;
            view.setSize(size[0], size[1]);
        }
        return size;
    }

    function vflToLayout(visualFormat, viewOptions) {
        var view = new AutoLayout.View(viewOptions);
        try {
            var constraints = AutoLayout.VisualFormat.parse(visualFormat, {extended: true, strict: false});
            var metaInfo = AutoLayout.VisualFormat.parseMetaInfo ? AutoLayout.VisualFormat.parseMetaInfo(visualFormat) : {};
            view.addConstraints(constraints);
            var dummyOptions = {};
            return function(context, options) {
                options = options || dummyOptions;
                var key;
                var subView;
                var x;
                var y;
                if (options.spacing || metaInfo.spacing) {
                    _setSpacing(view, options.spacing || metaInfo.spacing);
                }
                if (options.widths || metaInfo.widths) {
                    _setIntrinsicWidths(context, view, options.widths || metaInfo.widths);
                }
                if (options.heights || metaInfo.heights) {
                    _setIntrinsicHeights(context, view, options.heights || metaInfo.heights);
                }
                        if (options.viewport || metaInfo.viewport) {
                  var size = _setViewPortSize(context, view, options.viewport || metaInfo.viewport);
                  x = (context.size[0] - size[0]) / 2;
                  y = (context.size[1] - size[1]) / 2;
                }
                else {
                  view.setSize(context.size[0], context.size[1]);
                  x = 0;
                  y = 0;
                }
                for (key in view.subViews) {
                    subView = view.subViews[key];
                    if ((key.indexOf('_') !== 0) && (subView.type !== 'stack')) {
                        context.set(subView.name, {
                            size: [subView.width, subView.height],
                            translate: [x + subView.left, y + subView.top, subView.zIndex * 5]
                        });
                    }
                }
            };
        }
        catch (err) {
            console.log(err); //eslint-disable-line no-console
        }
    }

    module.exports = vflToLayout;
});
<|endoftext|>


<commit_before>module.exports = {
  pageTitle: 'Submitting your MSP premium assistance application',
  transmissionSuccess: 'You MSP premium assistance application has been successfully submitted!',
  transmissionInProgressMessage: 'Please do not close this browser tab or window, it can take 1-2 minutes to complete the submission.',
  transmissionErrorTitle: 'System error',
  instructionForUserOnError: '
Sorry, it looks like something happened while your application was being submitted.

You can try submitting again - the data you’ve entered is saved on your device until you close the web browser.

If that doesn’t work, apply using a paper form:

MSP Application form (PDF)

'
}
<commit_msg>add placeholder "try submitting again" link<commit_after>module.exports = {
  pageTitle: 'Submitting your MSP premium assistance application',
  transmissionSuccess: 'You MSP premium assistance application has been successfully submitted!',
  transmissionInProgressMessage: 'Please do not close this browser tab or window, it can take 1-2 minutes to complete the submission.',
  transmissionErrorTitle: 'System error',
  instructionForUserOnError: '
Sorry, it looks like something happened while your application was being submitted.

You can try submitting again - the data you’ve entered is saved on your device until you close the web browser.

Try to submit your application again

If that doesn’t work, apply using a paper form:

MSP Application form (PDF)

'
}
<|endoftext|>


<commit_before>
"use strict;";

var express = require('express'),
router      = express.Router(),
_           = require('underscore'),
moment      = require('moment'),
Promise     = require('bluebird'),
ical        = require('ical-generator'),
TeamView    = require('../model/team_view');

router.get('/:token/ical.ics', function(req, res){

  var cal = ical({
      domain : 'timeoff.management',
    }),
    token = req.param('token'),
    model = req.app.get('db_model'),
    user;

  Promise.resolve()
    .then(function(){
      return model.UserFeed.find({
        where : {feed_token : token},
        include : [
          {model : model.User, as : 'user'}
        ]
      });
    })
    .then(function(feed){

      if ( ! feed ) {
        throw new Error("Unknown token provided");
      }

      user = feed.user;

      if (feed.is_calendar()){
        return user.promise_calendar({
          year           : moment(),
          show_full_year : true,
        })
          .then(function(calendar){

            cal.name(user.full_name() + ' calendar');

            var days = _.flatten(
              _.map(calendar, function(cal){ return cal.as_for_team_view(); })
            );

            days.forEach(function(day){ day.user = user; });

            return Promise.resolve(days);
          });
      } else {

        cal.name(user.full_name() + ' team');

        var team_view = new TeamView({
          user : user,
        });

        return team_view.promise_team_view_details()
          .then(function(details){
            var days = [];

            details.users_and_leaves.forEach(function(rec){
              var user = rec.user;
              rec.days.forEach(function(day){
                day.user = user;
              });
              days = days.concat( rec.days );
            });

            return Promise.resolve(days);
          });
      }
    })

    .then(function(days){

      days.forEach(function(day){

        // We care only about days when employee is on leave
        if (!(day.is_leave_morning || day.is_leave_afternoon)) {
          return;
        }

        var start = moment(day.moment),
            end = moment(day.moment);

        if (day.is_leave_morning && day.is_leave_afternoon) {
          start.hour(9).minute(0);
          end.hour(17).minute(0);
        } else if (!day.is_leave_morning && day.is_leave_afternoon) {
          start.hour(13).minute(0);
          end.hour(17).minute(0);
        } else if (day.is_leave_morning && !day.is_leave_afternoon) {
          start.hour(9).minute(0);
          end.hour(13).minute(0);
        }

        cal.createEvent({
          start       : start.toDate(),
          end         : end.toDate(),
          summary     : day.user.full_name() + ' is out of office',
//          description : 'It works ;)',
        });
      });

      res.send( cal.toString() );
    })
    .catch(function(){
      // TODO VPP set 404 status
      res.send('N/A');
    });

});

module.exports = router;
<commit_msg>Fix issue with ICal feed for team view.<commit_after>
"use strict;";

var express = require('express'),
router      = express.Router(),
_           = require('underscore'),
moment      = require('moment'),
Promise     = require('bluebird'),
ical        = require('ical-generator'),
TeamView    = require('../model/team_view');

router.get('/:token/ical.ics', function(req, res){

  var cal = ical({
      domain : 'timeoff.management',
    }),
    token = req.param('token'),
    model = req.app.get('db_model'),
    user;

  Promise.resolve()
    .then(function(){
      return model.UserFeed.find({
        where : {feed_token : token},
        include : [
          {
            model : model.User,
            as : 'user',
            include : [{
              model : model.Company,
              as : 'company',
            }]
          }
        ]
      });
    })
    .then(function(feed){

      if ( ! feed ) {
        throw new Error("Unknown token provided");
      }

      user = feed.user;

      if (feed.is_calendar()){
        return user.promise_calendar({
          year           : moment(),
          show_full_year : true,
        })
          .then(function(calendar){

            cal.name(user.full_name() + ' calendar');

            var days = _.flatten(
              _.map(calendar, function(cal){ return cal.as_for_team_view(); })
            );

            days.forEach(function(day){ day.user = user; });

            return Promise.resolve(days);
          });
      } else {

        cal.name(user.full_name() + ' team');

        var team_view = new TeamView({
          user : user,
        });

        return team_view.promise_team_view_details()
          .then(function(details){
            var days = [];

            details.users_and_leaves.forEach(function(rec){
              var user = rec.user;
              rec.days.forEach(function(day){
                day.user = user;
              });
              days = days.concat( rec.days );
            });

            return Promise.resolve(days);
          });
      }
    })

    .then(function(days){

      days.forEach(function(day){

        // We care only about days when employee is on leave
        if (!(day.is_leave_morning || day.is_leave_afternoon)) {
          return;
        }

        var start = moment(day.moment),
            end = moment(day.moment);

        if (day.is_leave_morning && day.is_leave_afternoon) {
          start.hour(9).minute(0);
          end.hour(17).minute(0);
        } else if (!day.is_leave_morning && day.is_leave_afternoon) {
          start.hour(13).minute(0);
          end.hour(17).minute(0);
        } else if (day.is_leave_morning && !day.is_leave_afternoon) {
          start.hour(9).minute(0);
          end.hour(13).minute(0);
        }

        cal.createEvent({
          start       : start.toDate(),
          end         : end.toDate(),
          summary     : day.user.full_name() + ' is out of office',
//          description : 'It works ;)',
        });
      });

      res.send( cal.toString() );
    })
    .catch(function(){
      // TODO VPP set 404 status
      res.send('N/A');
    });

});

module.exports = router;
<|endoftext|>


<commit_before>var L = require('leaflet'),
    config = require('./config');

module.exports = {
    'Karta': L.tileLayer('https://a.tiles.mapbox.com/v4/mapbox.outdoors/{z}/{x}/{y}' + (L.Browser.retina ? '@2x' : '') +'.png?access_token=' + config.mapboxToken, {
        attribution: '© Mapbox © OpenStreetMap'
    }),
    'Flygfoto': L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        attribution: 'Kartdata © Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
        maxZoom: 18
    })
};
<commit_msg>Update baselayers.js<commit_after>var L = require('leaflet'),
    config = require('./config');

module.exports = {
    'Karta': L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/outdoors-v11/tiles/{z}/{x}/{y}' + (L.Browser.retina ? '@2x' : '') +'?access_token=' + config.mapboxToken, {
        attribution: '© Mapbox © OpenStreetMap'
    }),
    'Flygfoto': L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        attribution: 'Kartdata © Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
        maxZoom: 18
    })
};
<|endoftext|>


<commit_before>var date = require("./dateformat"),
    log_uids = {},
    log_format = "%date | %uid: [%type] %text",
    colorlog_format = {
	      info: "\033[1;34m%date | %uid: %text\033[0m",
	     debug: "\033[1;32m%date | %uid: %text\033[0m",
	      warn: "\033[1;33m%date | %uid: %text\033[0m",
	     error: "\033[1;31m%date | %uid: %text\033[0m"
	},
    date_format = "HH:MM:ss",
    use_colors = true,
    transports = [];

function Houston(uid) {
	this.uid = uid || "default";
	this.silent = false;
	this.silent_types = [];
}
Houston.prototype.silence = function () {
	var silent = true, type = false;

	for (var i = 0; i < arguments.length; i++) {
		switch (typeof arguments[i]) {
			case "boolean":
				silent = arguments[i];
				break;
			case "string":
				type = arguments[i];
		}
	}

	if (type === false) {
		this.silent = !(silent === false);
		return this;
	}

	if (typeof this[type] == "function") {
		if (silent === true) {
			if (this.silent_types.indexOf(type) == -1) {
				this.silent_types.push(type);
			}
		} else {
			if (this.silent_types.indexOf(type) != -1) {
				this.silent_types.splice(this.silent_types.indexOf(type), 1);
			}
		}
	}
	return this;
}
Houston.prototype.info = saveLogEntry("info");
Houston.prototype.debug = saveLogEntry("debug");
Houston.prototype.warn = saveLogEntry("warn");
Houston.prototype.error = saveLogEntry("error", true);

module.exports = function (uid) {
	if (!log_uids.hasOwnProperty(uid)) {
		log_uids[uid] = new Houston(uid);
	}
	return log_uids[uid];
};
module.exports.silence = function (silence) {
	for (uid in log_uids) {
		log_uids[uid].silence(silence);
	}
	return this;
};
module.exports.useColors = function (use) {
	use_colors = (use === true || typeof use == "undefined");
	return this;
};
module.exports.setDateFormat = function (fmt) {
	date_format = fmt;
	return this;
};
module.exports.setLogFormat = function (fmt) {
	log_format = fmt;
	return this;
};
module.exports.setColorLogFormat = function (fmt, type) {
	if (type) {
		colorlog_format[type] = fmt;
	} else {
		for (k in colorlog_format) {
			colorlog_format[k] = fmt;
		}
	}
	return this;
};
module.exports.addTransport = function (transport) {
	transports.push(transport);
	return this;
};
module.exports.clearTransports = function () {
	transports.length = 0;
	return this;
};

initTransports();

function initTransports() {
	var fs = require("fs"),
        path = require("path"),
        items = [], name = "";

	try {
		items = fs.readdirSync(__dirname + "/transports/");

		for (var i = 0; i < items.length; i++) {
			name = items[i].substr(0, items[i].length - path.extname(items[i]).length);

			module.exports[name] = require("./transports/" + name);
		}
	} catch (e) {}

	if (typeof module.exports.std == "function") {
		module.exports.addTransport(new module.exports.std());
	}
}

function saveLogEntry(type, error) {
	return function () {
		if (this.silent) return this;
		if (this.silent_types.indexOf(type) != -1) return this;

		var args = Array.prototype.slice.call(arguments),
		    i = 0, l = args.length,
		    output = false, coloroutput = false,
		    text = "", obj = false, cb;

		for (; i < l; i++) {
			switch (typeof args[i]) {
				case "string":
					text = args[i];
					break;
				case "object":
					obj = args[i];
					break;
			}
		}

		for (i = 0, l = transports.length; i < l; i++) {
			if (transports[i].original === true) {
				transports[i][error ? "err" : "out"]({
					type: type,
					 uid: this.uid,
					text: text,
					 obj: obj
				});
				continue;
			}

			if (use_colors && typeof transports[i].colors == "function" && transports[i].colors(error)) {
				if (coloroutput === false) {
					coloroutput = colorlog_format[type].replace("%date", date.format(date_format))
					                                   .replace("%uid", this.uid)
					                                   .replace("%text", text);
				}

				transports[i][error ? "err" : "out"](coloroutput, obj);
				continue;
			}

			if (output === false) {
				output = log_format.replace("%date", date.format(date_format))
				                   .replace("%type", type)
				                   .replace("%uid", this.uid)
				                   .replace("%text", text);
			}

			transports[i][error ? "err" : "out"](output, obj);
		}

		return this;
	};
}<commit_msg>Add try/catch to avoid breaking because of bad transports.<commit_after>var date = require("./dateformat"),
    log_uids = {},
    log_format = "%date | %uid: [%type] %text",
    colorlog_format = {
	      info: "\033[1;34m%date | %uid: %text\033[0m",
	     debug: "\033[1;32m%date | %uid: %text\033[0m",
	      warn: "\033[1;33m%date | %uid: %text\033[0m",
	     error: "\033[1;31m%date | %uid: %text\033[0m"
	},
    date_format = "HH:MM:ss",
    use_colors = true,
    transports = [];

function Houston(uid) {
	this.uid = uid || "default";
	this.silent = false;
	this.silent_types = [];
}
Houston.prototype.silence = function () {
	var silent = true, type = false;

	for (var i = 0; i < arguments.length; i++) {
		switch (typeof arguments[i]) {
			case "boolean":
				silent = arguments[i];
				break;
			case "string":
				type = arguments[i];
		}
	}

	if (type === false) {
		this.silent = !(silent === false);
		return this;
	}

	if (typeof this[type] == "function") {
		if (silent === true) {
			if (this.silent_types.indexOf(type) == -1) {
				this.silent_types.push(type);
			}
		} else {
			if (this.silent_types.indexOf(type) != -1) {
				this.silent_types.splice(this.silent_types.indexOf(type), 1);
			}
		}
	}
	return this;
}
Houston.prototype.info = saveLogEntry("info");
Houston.prototype.debug = saveLogEntry("debug");
Houston.prototype.warn = saveLogEntry("warn");
Houston.prototype.error = saveLogEntry("error", true);

module.exports = function (uid) {
	if (!log_uids.hasOwnProperty(uid)) {
		log_uids[uid] = new Houston(uid);
	}
	return log_uids[uid];
};
module.exports.silence = function (silence) {
	for (uid in log_uids) {
		log_uids[uid].silence(silence);
	}
	return this;
};
module.exports.useColors = function (use) {
	use_colors = (use === true || typeof use == "undefined");
	return this;
};
module.exports.setDateFormat = function (fmt) {
	date_format = fmt;
	return this;
};
module.exports.setLogFormat = function (fmt) {
	log_format = fmt;
	return this;
};
module.exports.setColorLogFormat = function (fmt, type) {
	if (type) {
		colorlog_format[type] = fmt;
	} else {
		for (k in colorlog_format) {
			colorlog_format[k] = fmt;
		}
	}
	return this;
};
module.exports.addTransport = function (transport) {
	transports.push(transport);
	return this;
};
module.exports.clearTransports = function () {
	transports.length = 0;
	return this;
};

initTransports();

function initTransports() {
	var fs = require("fs"),
        path = require("path"),
        items = [], name = "";

	try {
		items = fs.readdirSync(__dirname + "/transports/");

		for (var i = 0; i < items.length; i++) {
			name = items[i].substr(0, items[i].length - path.extname(items[i]).length);

			try {
				module.exports[name] = require("./transports/" + name);
			} catch (e) {}
		}
	} catch (e) {}

	if (typeof module.exports.std == "function") {
		module.exports.addTransport(new module.exports.std());
	}
}

function saveLogEntry(type, error) {
	return function () {
		if (this.silent) return this;
		if (this.silent_types.indexOf(type) != -1) return this;

		var args = Array.prototype.slice.call(arguments),
		    i = 0, l = args.length,
		    output = false, coloroutput = false,
		    text = "", obj = false, cb;

		for (; i < l; i++) {
			switch (typeof args[i]) {
				case "string":
					text = args[i];
					break;
				case "object":
					obj = args[i];
					break;
			}
		}

		for (i = 0, l = transports.length; i < l; i++) {
			try {
				if (transports[i].original === true) {
					transports[i][error ? "err" : "out"]({
						type: type,
						 uid: this.uid,
						text: text,
						 obj: obj
					});
					continue;
				}

				if (use_colors && typeof transports[i].colors == "function" && transports[i].colors(error)) {
					if (coloroutput === false) {
						coloroutput = colorlog_format[type].replace("%date", date.format(date_format))
						                                   .replace("%uid", this.uid)
						                                   .replace("%text", text);
					}

					transports[i][error ? "err" : "out"](coloroutput, obj);
					continue;
				}

				if (output === false) {
					output = log_format.replace("%date", date.format(date_format))
					                   .replace("%type", type)
					                   .replace("%uid", this.uid)
					                   .replace("%text", text);
				}

				transports[i][error ? "err" : "out"](output, obj);
			} catch (e) {}
		}

		return this;
	};
}<|endoftext|>


<commit_before>import $screen from 'wee-screen';
import { _html, _win } from 'core/variables';

let state = {
	one: false,
	two: false,
	three: false,
};

function resetState() {
	state = {
		one: false,
		two: false,
		three: false,
	}
}

function setScreenSize(size) {
	_html.style.fontFamily = '"' + size + '"';
	triggerEvent(_win, 'resize');
}

// TODO: Once merged, extract this helper and use in both
// TODO: events and screen
function triggerEvent(el, type) {
	let e = document.createEvent('HTMLEvents');
	e.initEvent(type, false, true);
	el.dispatchEvent(e);
}

describe('Screen', () => {
	afterEach(() => {
		resetState();
		$screen.reset();
	});

	describe('map', () => {
		it('should add a mapping to the registry', () => {
			$screen.map({
				size: 3,
				callback() {
					state.one = true;
				}
			});

			setScreenSize(3);
			expect(state.one).to.equal(true);
			expect($screen.bound().length).to.equal(1);
		});

		it('should add multiple mappings to the registry', () => {
			$screen.map([
				{
					size: 3,
					callback() {
						state.one = true;
					}
				},
				{
					size: 2,
					callback() {
						state.two = true;
					}
				}
			]);

			setScreenSize(2);
			expect(state.one).to.equal(true);
			setScreenSize(3);
			expect(state.two).to.equal(true);
		});

		it('should not execute callback outside of specified size', () => {
			$screen.map({
				size: 3,
				callback() {
					state.one = true;
				}
			});

			setScreenSize(3);
			expect(state.one).to.equal(true);
			resetState();
			setScreenSize(4);
			expect(state.one).to.equal(false);
		});

		it('should execute callback when max size is reached', () => {
			$screen.map([
				{
					max: 3,
					callback() {
						state.one = true;
					}
				}
			]);

			setScreenSize(3);
			expect(state.one).to.equal(true);
		});

		it('should inject data object as first parameter to callback', () => {
			$screen.map({
				size: 3,
				callback(data) {
					expect(data).to.be.an('object');
					expect(data).to.have.keys(['dir', 'init', 'prev', 'size']);
					expect(data.size).to.equal(3);
				}
			});

			setScreenSize(3);
		});

		it('should execute callback when min size is reached', () => {
			$screen.map([
				{
					min: 3,
					callback() {
						state.one = true;
					}
				}
			]);

			setScreenSize(3);
			expect(state.one).to.equal(true);
		});

		it('should execute callback when min and max size is reached', () => {
			$screen.map([
				{
					min: 1,
					max: 3,
					callback() {
						state.one = true;
					}
				}
			]);

			setScreenSize(1);
			expect(state.one).to.equal(true);
			resetState();
			setScreenSize(4);
			setScreenSize(3);
			expect(state.one).to.equal(true);
		});

		it('can use function as callback', () => {
			function callback() {
				state.one = true;
			}

			$screen.map({
				size: 3,
				callback
			});

			setScreenSize(3);
			expect(state.one).to.equal(true);
		});

		it('should execute multiple callbacks', () => {
			function callbackOne() {
				state.one = true;
			}

			function callbackTwo() {
				state.two = true;
			}

			$screen.map({
				size: 3,
				callback: [
					callbackOne,
					callbackTwo
				]
			});

			setScreenSize(3);
			expect(state.one).to.equal(true);
			expect(state.two).to.equal(true);
		});

		describe('each', () => {
			it('should execute callback on each size until max', () => {
				$screen.map({
					max: 3,
					each: true,
					callback() {
						state.one = true;
					}
				});

				setScreenSize(1);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(2);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(3);
				expect(state.one).to.equal(true);
			});

			it('should execute callback within bounds of min and max size', () => {
				$screen.map({
					min: 1,
					max: 3,
					each: true,
					callback() {
						state.one = true;
					}
				});

				setScreenSize(1);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(2);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(3);
				expect(state.one).to.equal(true);
			});
		});

		describe('namespace', () => {
			it('should attach namespace to map object', () => {
				$screen.map({
					size: 3,
					namespace: 'namespace',
					callback() {
						state.one = true;
					}
				});

				setScreenSize(3);
				expect(state.one).to.equal(true);
				resetState();

				$screen.reset('namespace');

				setScreenSize(3);
				expect(state.one).to.equal(false);
			});
		});

		describe('once', () => {
			it('should only execute callback once', () => {
				$screen.map({
					size: 3,
					once: true,
					callback() {
						state.one = true;
					}
				});

				setScreenSize(3);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(3);
				expect(state.one).to.equal(false);
			})
		});

		describe('args', () => {
			it('should add to the arguments array', () => {
				$screen.map({
					size: 3,
					args: ['one', 'two'],
					callback(arg, one, two) {
						expect(one).to.equal('one');
						expect(two).to.equal('two');
					}
				});

				setScreenSize(3);
			})
		});

		describe('scope', () => {
			it('should change the scope of the callback', () => {
				let obj = {
					one: 'one'
				};

				$screen.map({
					size: 3,
					scope: obj,
					callback() {
						expect(this.one).to.equal('one');
					}
				});

				setScreenSize(3);
			});
		});

		describe('watch', () => {
			it('should determine evaluation on screen resize', () => {
				$screen.map({
					size: 3,
					watch: false,
					callback() {
						state.one = true;
					}
				});

				setScreenSize(3);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(3);
				expect(state.one).to.equal(false);
			});
		});
	});

	describe('run', () => {
		it('should run all mappings', () => {
			$screen.map([
				{
					callback() {
						state.one = true;
					}
				},
				{
					callback() {
						state.two = true;
					}
				},
				{
					callback() {
						state.three = true;
					}
				}
			]);

			$screen.run();
			expect(state.one).to.equal(true);
			expect(state.two).to.equal(true);
			expect(state.three).to.equal(true);
		});

		it('should run all namespaced mappings', () => {
			setScreenSize(3);
			$screen.map([
				{
					size: 3,
					namespace: 'namespace',
					callback() {
						state.one = true;
					}
				},
				{
					size: 3,
					namespace: 'namespace',
					callback() {
						state.two = true;
					}
				},
				{
					size: 3,
					callback() {
						state.three = true;
					}
				}
			]);

			resetState();

			$screen.run('namespace');
			expect(state.one).to.equal(true);
			expect(state.two).to.equal(true);
			expect(state.three).to.equal(false);
		});
	});

	describe('size', () => {
		it('should return the current screen size', () => {
			setScreenSize(2);
			expect($screen.size()).to.equal(2);
		});
	});

	describe('bound', () => {
		it('should return the currently bound mappings', () => {
			expect($screen.bound()).to.be.an('array');
			expect($screen.bound().length).to.equal(0);

			$screen.map({
				size: 3,
				callback() {
					return 'three';
				}
			});

			expect($screen.bound().length).to.equal(1);
			expect($screen.bound()[0].callback()).to.equal('three');
		});

		it('should return the currently bound mappings by namespace', () => {
			$screen.map([
				{
					size: 3,
					namespace: 'namespace',
					callback() {
						return 'three';
					}
				},
				{
					size: 2,
					callback() {
						return 'two';
					}
				}
			]);

			expect($screen.bound().length).to.equal(2);
			expect($screen.bound('namespace').length).to.equal(1);
		});
	});
});<commit_msg>Add semi-colons and additional assertions<commit_after>import $screen from 'wee-screen';
import { _html, _win } from 'core/variables';

let state = {
	one: false,
	two: false,
	three: false,
};

function resetState() {
	state = {
		one: false,
		two: false,
		three: false,
	}
}

function setScreenSize(size) {
	_html.style.fontFamily = '"' + size + '"';
	triggerEvent(_win, 'resize');
}

// TODO: Once merged, extract this helper and use in both
// TODO: events and screen
function triggerEvent(el, type) {
	let e = document.createEvent('HTMLEvents');
	e.initEvent(type, false, true);
	el.dispatchEvent(e);
}

describe('Screen', () => {
	afterEach(() => {
		resetState();
		$screen.reset();
	});

	describe('map', () => {
		it('should add a mapping to the registry', () => {
			$screen.map({
				size: 3,
				callback() {
					state.one = true;
				}
			});

			setScreenSize(3);
			expect(state.one).to.equal(true);
			expect($screen.bound().length).to.equal(1);
		});

		it('should add multiple mappings to the registry', () => {
			$screen.map([
				{
					size: 3,
					callback() {
						state.one = true;
					}
				},
				{
					size: 2,
					callback() {
						state.two = true;
					}
				}
			]);

			setScreenSize(2);
			expect(state.one).to.equal(true);
			setScreenSize(3);
			expect(state.two).to.equal(true);
		});

		it('should not execute callback outside of specified size', () => {
			$screen.map({
				size: 3,
				callback() {
					state.one = true;
				}
			});

			setScreenSize(3);
			expect(state.one).to.equal(true);
			resetState();
			setScreenSize(4);
			expect(state.one).to.equal(false);
		});

		it('should execute callback when max size is reached', () => {
			$screen.map([
				{
					max: 3,
					callback() {
						state.one = true;
					}
				}
			]);

			setScreenSize(3);
			expect(state.one).to.equal(true);
		});

		it('should inject data object as first parameter to callback', () => {
			$screen.map({
				size: 3,
				callback(data) {
					expect(data).to.be.an('object');
					expect(data).to.have.keys(['dir', 'init', 'prev', 'size']);
					expect(data.size).to.equal(3);
				}
			});

			setScreenSize(3);
		});

		it('should execute callback when min size is reached', () => {
			$screen.map([
				{
					min: 3,
					callback() {
						state.one = true;
					}
				}
			]);

			setScreenSize(3);
			expect(state.one).to.equal(true);
		});

		it('should execute callback when min and max size is reached', () => {
			$screen.map([
				{
					min: 1,
					max: 3,
					callback() {
						state.one = true;
					}
				}
			]);

			setScreenSize(1);
			expect(state.one).to.equal(true);
			resetState();
			setScreenSize(4);
			setScreenSize(3);
			expect(state.one).to.equal(true);
		});

		it('can use function as callback', () => {
			function callback() {
				state.one = true;
			}

			$screen.map({
				size: 3,
				callback
			});

			setScreenSize(3);
			expect(state.one).to.equal(true);
		});

		it('should execute multiple callbacks', () => {
			function callbackOne() {
				state.one = true;
			}

			function callbackTwo() {
				state.two = true;
			}

			$screen.map({
				size: 3,
				callback: [
					callbackOne,
					callbackTwo
				]
			});

			setScreenSize(3);
			expect(state.one).to.equal(true);
			expect(state.two).to.equal(true);
		});

		describe('each', () => {
			it('should execute callback on each size until max', () => {
				$screen.map({
					max: 3,
					each: true,
					callback() {
						state.one = true;
					}
				});

				setScreenSize(1);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(2);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(3);
				expect(state.one).to.equal(true);
			});

			it('should execute callback within bounds of min and max size', () => {
				$screen.map({
					min: 1,
					max: 3,
					each: true,
					callback() {
						state.one = true;
					}
				});

				setScreenSize(1);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(2);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(3);
				expect(state.one).to.equal(true);
			});
		});

		describe('namespace', () => {
			it('should attach namespace to map object', () => {
				$screen.map({
					size: 3,
					namespace: 'namespace',
					callback() {
						state.one = true;
					}
				});

				setScreenSize(3);
				expect(state.one).to.equal(true);
				resetState();

				$screen.reset('namespace');

				setScreenSize(3);
				expect(state.one).to.equal(false);
			});
		});

		describe('once', () => {
			it('should only execute callback once', () => {
				$screen.map({
					size: 3,
					once: true,
					callback() {
						state.one = true;
					}
				});

				setScreenSize(3);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(3);
				expect(state.one).to.equal(false);
			});
		});

		describe('args', () => {
			it('should add to the arguments array', () => {
				$screen.map({
					size: 3,
					args: ['one', 'two'],
					callback(arg, one, two) {
						expect(one).to.equal('one');
						expect(two).to.equal('two');

						state.one = true;
					}
				});

				setScreenSize(3);

				expect(state.one).to.be.true;
			});
		});

		describe('scope', () => {
			it('should change the scope of the callback', () => {
				let obj = {
					one: 'one'
				};

				$screen.map({
					size: 3,
					scope: obj,
					callback() {
						expect(this.one).to.equal('one');

						state.one = true;
					}
				});

				setScreenSize(3);

				expect(state.one).to.be.true;
			});
		});

		describe('watch', () => {
			it('should determine evaluation on screen resize', () => {
				$screen.map({
					size: 3,
					watch: false,
					callback() {
						state.one = true;
					}
				});

				setScreenSize(3);
				expect(state.one).to.equal(true);
				resetState();
				setScreenSize(3);
				expect(state.one).to.equal(false);
			});
		});
	});

	describe('run', () => {
		it('should run all mappings', () => {
			$screen.map([
				{
					callback() {
						state.one = true;
					}
				},
				{
					callback() {
						state.two = true;
					}
				},
				{
					callback() {
						state.three = true;
					}
				}
			]);

			$screen.run();
			expect(state.one).to.equal(true);
			expect(state.two).to.equal(true);
			expect(state.three).to.equal(true);
		});

		it('should run all namespaced mappings', () => {
			setScreenSize(3);
			$screen.map([
				{
					size: 3,
					namespace: 'namespace',
					callback() {
						state.one = true;
					}
				},
				{
					size: 3,
					namespace: 'namespace',
					callback() {
						state.two = true;
					}
				},
				{
					size: 3,
					callback() {
						state.three = true;
					}
				}
			]);

			resetState();

			$screen.run('namespace');
			expect(state.one).to.equal(true);
			expect(state.two).to.equal(true);
			expect(state.three).to.equal(false);
		});
	});

	describe('size', () => {
		it('should return the current screen size', () => {
			setScreenSize(2);
			expect($screen.size()).to.equal(2);

			setScreenSize(3);
			expect($screen.size()).to.equal(3);
		});
	});

	describe('bound', () => {
		it('should return the currently bound mappings', () => {
			expect($screen.bound()).to.be.an('array');
			expect($screen.bound().length).to.equal(0);

			$screen.map({
				size: 3,
				callback() {
					return 'three';
				}
			});

			expect($screen.bound().length).to.equal(1);
			expect($screen.bound()[0].callback()).to.equal('three');
		});

		it('should return the currently bound mappings by namespace', () => {
			$screen.map([
				{
					size: 3,
					namespace: 'namespace',
					callback() {
						return 'three';
					}
				},
				{
					size: 2,
					callback() {
						return 'two';
					}
				}
			]);

			expect($screen.bound().length).to.equal(2);
			expect($screen.bound('namespace').length).to.equal(1);
		});
	});
});<|endoftext|>


<commit_before>/* @flow */

import { isDef, isUndef, extend, toNumber } from 'shared/util'

function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {
  if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
    return
  }
  let key, cur
  const elm: any = vnode.elm
  const oldProps = oldVnode.data.domProps || {}
  let props = vnode.data.domProps || {}
  // clone observed objects, as the user probably wants to mutate it
  if (isDef(props.__ob__)) {
    props = vnode.data.domProps = extend({}, props)
  }

  for (key in oldProps) {
    if (isUndef(props[key])) {
      elm[key] = ''
    }
  }
  for (key in props) {
    cur = props[key]
    // ignore children if the node has textContent or innerHTML,
    // as these will throw away existing DOM nodes and cause removal errors
    // on subsequent patches (#3360)
    if (key === 'textContent' || key === 'innerHTML') {
      if (vnode.children) vnode.children.length = 0
      if (cur === oldProps[key]) continue
    }

    if (key === 'value') {
      // store value as _value as well since
      // non-string values will be stringified
      elm._value = cur
      // avoid resetting cursor position when value is the same
      const strCur = isUndef(cur) ? '' : String(cur)
      if (shouldUpdateValue(elm, vnode, strCur)) {
        elm.value = strCur
      }
    } else {
      elm[key] = cur
    }
  }
}

// check platforms/web/util/attrs.js acceptValue
type acceptValueElm = HTMLInputElement | HTMLSelectElement | HTMLOptionElement;

function shouldUpdateValue (
  elm: acceptValueElm,
  vnode: VNodeWithData,
  checkVal: string
): boolean {
  return (!elm.composing && (
    vnode.tag === 'option' ||
    isDirty(elm, checkVal) ||
    isInputChanged(elm, checkVal)
  ))
}

function isDirty (elm: acceptValueElm, checkVal: string): boolean {
  // return true when textbox (.number and .trim) loses focus and its value is
  // not equal to the updated value
  let notInFocus = true
  // #6157
  // work around IE bug when accessing document.activeElement in an iframe
  try { notInFocus = document.activeElement !== elm } catch (e) {}
  return notInFocus && elm.value !== checkVal
}

function isInputChanged (elm: any, newVal: string): boolean {
  const value = elm.value
  const modifiers = elm._vModifiers // injected by v-model runtime
  if (isDef(modifiers) && modifiers.number) {
    return toNumber(value) !== toNumber(newVal)
  }
  if (isDef(modifiers) && modifiers.trim) {
    return value.trim() !== newVal.trim()
  }
  return value !== newVal
}

export default {
  create: updateDOMProps,
  update: updateDOMProps
}
<commit_msg>fix: work around old Chrome bug<commit_after>/* @flow */

import { isDef, isUndef, extend, toNumber } from 'shared/util'

function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {
  if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
    return
  }
  let key, cur
  const elm: any = vnode.elm
  const oldProps = oldVnode.data.domProps || {}
  let props = vnode.data.domProps || {}
  // clone observed objects, as the user probably wants to mutate it
  if (isDef(props.__ob__)) {
    props = vnode.data.domProps = extend({}, props)
  }

  for (key in oldProps) {
    if (isUndef(props[key])) {
      elm[key] = ''
    }
  }
  for (key in props) {
    cur = props[key]
    // ignore children if the node has textContent or innerHTML,
    // as these will throw away existing DOM nodes and cause removal errors
    // on subsequent patches (#3360)
    if (key === 'textContent' || key === 'innerHTML') {
      if (vnode.children) vnode.children.length = 0
      if (cur === oldProps[key]) continue
      // #6601 work around Chrome version <= 55 bug where single textNode
      // replaced by innerHTML/textContent retains its parentNode property
      if (elm.childNodes.length === 1) {
        elm.removeChild(elm.childNodes[0])
      }
    }

    if (key === 'value') {
      // store value as _value as well since
      // non-string values will be stringified
      elm._value = cur
      // avoid resetting cursor position when value is the same
      const strCur = isUndef(cur) ? '' : String(cur)
      if (shouldUpdateValue(elm, vnode, strCur)) {
        elm.value = strCur
      }
    } else {
      elm[key] = cur
    }
  }
}

// check platforms/web/util/attrs.js acceptValue
type acceptValueElm = HTMLInputElement | HTMLSelectElement | HTMLOptionElement;

function shouldUpdateValue (
  elm: acceptValueElm,
  vnode: VNodeWithData,
  checkVal: string
): boolean {
  return (!elm.composing && (
    vnode.tag === 'option' ||
    isDirty(elm, checkVal) ||
    isInputChanged(elm, checkVal)
  ))
}

function isDirty (elm: acceptValueElm, checkVal: string): boolean {
  // return true when textbox (.number and .trim) loses focus and its value is
  // not equal to the updated value
  let notInFocus = true
  // #6157
  // work around IE bug when accessing document.activeElement in an iframe
  try { notInFocus = document.activeElement !== elm } catch (e) {}
  return notInFocus && elm.value !== checkVal
}

function isInputChanged (elm: any, newVal: string): boolean {
  const value = elm.value
  const modifiers = elm._vModifiers // injected by v-model runtime
  if (isDef(modifiers) && modifiers.number) {
    return toNumber(value) !== toNumber(newVal)
  }
  if (isDef(modifiers) && modifiers.trim) {
    return value.trim() !== newVal.trim()
  }
  return value !== newVal
}

export default {
  create: updateDOMProps,
  update: updateDOMProps
}
<|endoftext|>


<commit_before>import {ArrayRepeatStrategy} from 'aurelia-templating-resources/array-repeat-strategy';
import {createFullOverrideContext, updateOverrideContext, refreshBinding} from 'aurelia-templating-resources/repeat-utilities';
import {updateOverrideContexts, rebindAndMoveView} from './utilities';

/**
* A strategy for repeating a template over an array.
*/
export class ArrayVirtualRepeatStrategy extends ArrayRepeatStrategy {
  // create first item to calculate the heights
  createFirstItem(repeat) {
    var overrideContext = createFullOverrideContext(repeat, repeat.items[0], 0, 1);
    var view = repeat.viewFactory.create();
    view.bind(overrideContext.bindingContext, overrideContext);
    repeat.viewSlot.add(view);
  }
  /**
  * Handle the repeat's collection instance changing.
  * @param repeat The repeater instance.
  * @param items The new array instance.
  */
  instanceChanged(repeat, items) {
    this._inPlaceProcessItems(repeat, items);
  }

  _standardProcessInstanceChanged(repeat, items) {
    for(var i = 1, ii = repeat._viewsLength; i < ii; ++i){
      let overrideContext = createFullOverrideContext(repeat, items[i], i, ii);
      let view = repeat.viewFactory.create();
      view.bind(overrideContext.bindingContext, overrideContext);
      repeat.viewSlot.add(view);
    }
  }

  _inPlaceProcessItems(repeat, items) {
    let itemsLength = items.length;
    let viewsLength = repeat.viewSlot.children.length;
    let first = repeat._getIndexOfFirstView();
    // remove unneeded views.
    while (viewsLength > repeat._viewsLength) {
      viewsLength--;
      repeat.viewSlot.removeAt(viewsLength, true);
    }
    // avoid repeated evaluating the property-getter for the "local" property.
    let local = repeat.local;
    // re-evaluate bindings on existing views.
    for (let i = 0; i < viewsLength; i++) {
      let view = repeat.viewSlot.children[i];
      let last = i === itemsLength - 1;
      let middle = i !== 0 && !last;
      // any changes to the binding context?
      if (view.bindingContext[local] === items[i + first] && view.overrideContext.$middle === middle && view.overrideContext.$last === last) {
        // no changes. continue...
        continue;
      }
      // update the binding context and refresh the bindings.
      view.bindingContext[local] = items[i + first];
      view.overrideContext.$middle = middle;
      view.overrideContext.$last = last;
      let j = view.bindings.length;
      while (j--) {
        refreshBinding(view.bindings[j]);
      }
      j = view.controllers.length;
      while (j--) {
        let k = view.controllers[j].boundProperties.length;
        while (k--) {
          let binding = view.controllers[j].boundProperties[k].binding;
          refreshBinding(binding);
        }
      }
    }
    // add new views
    for (let i = viewsLength; i < repeat._viewsLength; i++) {
      let overrideContext = createFullOverrideContext(repeat, items[i], i, itemsLength);
      let view = repeat.viewFactory.create();
      view.bind(overrideContext.bindingContext, overrideContext);
      repeat.viewSlot.add(view);
    }
  }

  /**
  * Handle the repeat's collection instance mutating.
  * @param repeat The repeat instance.
  * @param array The modified array.
  * @param splices Records of array changes.
  */
  instanceMutated(repeat, array, splices) {
    this._standardProcessInstanceMutated(repeat, array, splices);
  }

  _standardProcessInstanceMutated(repeat, array, splices) {
    let removeDelta = 0;
    let viewSlot = repeat.viewSlot;
    let rmPromises = [];

    for (let i = 0, ii = splices.length; i < ii; ++i) {
      let splice = splices[i];
      let removed = splice.removed;
      for (let j = 0, jj = removed.length; j < jj; ++j) {
        let viewOrPromise = this._removeViewAt(repeat, splice.index + removeDelta + rmPromises.length, true);
        if (viewOrPromise instanceof Promise) {
          rmPromises.push(viewOrPromise);
        }
      }
      removeDelta -= splice.addedCount;
    }

    if (rmPromises.length > 0) {
      Promise.all(rmPromises).then(() => {
        this._handleAddedSplices(repeat, array, splices);
        updateOverrideContexts(repeat, 0);
      });
    } else {
      this._handleAddedSplices(repeat, array, splices);
      updateOverrideContexts(repeat, 0);
    }
  }

  _removeViewAt(repeat, collectionIndex, returnToCache){
    let viewOrPromise;
    let view;
    let viewSlot = repeat.viewSlot;
    let viewIndex = this._getViewIndex(repeat, viewSlot, collectionIndex);

    if(viewIndex >= 0 && viewIndex <= viewSlot.children.length -1){
      viewOrPromise = viewSlot.removeAt(viewIndex, returnToCache);
      if(repeat.items >= viewSlot.children && repeat._bottomBufferHeight > repeat.itemHeight) {
        // TODO: do not trigger view lifecycle here
        let index = repeat._getIndexOfLastView() + 1;
        let overrideContext = createFullOverrideContext(repeat, repeat.items[index], index, repeat.items.length);
        view = repeat.viewFactory.create();
        view.bind(overrideContext.bindingContext, overrideContext);
        repeat._bottomBufferHeight = repeat._bottomBufferHeight - (repeat.itemHeight);
      } else {
        return viewOrPromise;
      }
    } else if (viewIndex < 0) {
      // this is to correctly update override context
      if(repeat._bottomBufferHeight > 0) {
        repeat._bottomBufferHeight = repeat._bottomBufferHeight - (repeat.itemHeight);
        rebindAndMoveView(repeat, viewSlot.children[0], viewSlot.children[0].overrideContext.$index, true);
      } else {
        repeat._topBufferHeight = repeat._topBufferHeight - (repeat.itemHeight);
      }
    }

    if (viewOrPromise instanceof Promise) {
      viewOrPromise.then(() => {
        repeat.viewSlot.add(view);
        this._adjustBufferHeight(repeat);
      });
      return;
    } else if(view) {
      repeat.viewSlot.add(view);
    }

    this._adjustBufferHeight(repeat);
  }

  _adjustBufferHeight(repeat) {
    /*if(repeat._bottomBufferHeight > 0) {
      repeat._bottomBufferHeight = repeat._bottomBufferHeight - repeat.itemHeight;
    } else {
      repeat._topBufferHeight = repeat._topBufferHeight - repeat.itemHeight;
    }  */

    repeat._adjustBufferHeights();
  }

  _getViewIndex(repeat, viewSlot, index) {
    if(viewSlot.children.length === 0) {
      return -1;
    }
    let indexLow = viewSlot.children[0].overrideContext.$index;
    let viewIndex = index - indexLow;
    if(viewIndex > repeat._viewsLength - 1 || viewIndex < 0) {
      viewIndex = -1;
    }
    return viewIndex;
  }

  _isIndexInDom(viewSlot, index) {
    if(viewSlot.children.length === 0) {
      return false;
    }
    let indexLow = viewSlot.children[0].overrideContext.$index;
    let indexHi = viewSlot.children[viewSlot.children.length - 1].overrideContext.$index;
    return index >= indexLow && index <= indexHi;
  }

  _handleAddedSplices(repeat, array, splices) {
    let arrayLength = array.length;
    for (let i = 0, ii = splices.length; i < ii; ++i) {
      let splice = splices[i];
      let addIndex = splice.index;
      let end = splice.index + splice.addedCount;

      for (; addIndex < end; ++addIndex) {
        let overrideContext = createFullOverrideContext(repeat, array[addIndex], addIndex, arrayLength);
        let view = repeat.viewFactory.create();
        view.bind(overrideContext.bindingContext, overrideContext);
        repeat.viewSlot.insert(addIndex, view);
      }
    }
  }
}
<commit_msg>fix(array-virtual-repeat-strategy): handle remove from bottom and top<commit_after>import {ArrayRepeatStrategy} from 'aurelia-templating-resources/array-repeat-strategy';
import {createFullOverrideContext, updateOverrideContext, refreshBinding} from 'aurelia-templating-resources/repeat-utilities';
import {updateOverrideContexts, rebindAndMoveView} from './utilities';

/**
* A strategy for repeating a template over an array.
*/
export class ArrayVirtualRepeatStrategy extends ArrayRepeatStrategy {
  // create first item to calculate the heights
  createFirstItem(repeat) {
    var overrideContext = createFullOverrideContext(repeat, repeat.items[0], 0, 1);
    var view = repeat.viewFactory.create();
    view.bind(overrideContext.bindingContext, overrideContext);
    repeat.viewSlot.add(view);
  }
  /**
  * Handle the repeat's collection instance changing.
  * @param repeat The repeater instance.
  * @param items The new array instance.
  */
  instanceChanged(repeat, items) {
    this._inPlaceProcessItems(repeat, items);
  }

  _standardProcessInstanceChanged(repeat, items) {
    for(var i = 1, ii = repeat._viewsLength; i < ii; ++i){
      let overrideContext = createFullOverrideContext(repeat, items[i], i, ii);
      let view = repeat.viewFactory.create();
      view.bind(overrideContext.bindingContext, overrideContext);
      repeat.viewSlot.add(view);
    }
  }

  _inPlaceProcessItems(repeat, items) {
    let itemsLength = items.length;
    let viewsLength = repeat.viewSlot.children.length;
    let first = repeat._getIndexOfFirstView();
    // remove unneeded views.
    while (viewsLength > repeat._viewsLength) {
      viewsLength--;
      repeat.viewSlot.removeAt(viewsLength, true);
    }
    // avoid repeated evaluating the property-getter for the "local" property.
    let local = repeat.local;
    // re-evaluate bindings on existing views.
    for (let i = 0; i < viewsLength; i++) {
      let view = repeat.viewSlot.children[i];
      let last = i === itemsLength - 1;
      let middle = i !== 0 && !last;
      // any changes to the binding context?
      if (view.bindingContext[local] === items[i + first] && view.overrideContext.$middle === middle && view.overrideContext.$last === last) {
        // no changes. continue...
        continue;
      }
      // update the binding context and refresh the bindings.
      view.bindingContext[local] = items[i + first];
      view.overrideContext.$middle = middle;
      view.overrideContext.$last = last;
      let j = view.bindings.length;
      while (j--) {
        refreshBinding(view.bindings[j]);
      }
      j = view.controllers.length;
      while (j--) {
        let k = view.controllers[j].boundProperties.length;
        while (k--) {
          let binding = view.controllers[j].boundProperties[k].binding;
          refreshBinding(binding);
        }
      }
    }
    // add new views
    for (let i = viewsLength; i < repeat._viewsLength; i++) {
      let overrideContext = createFullOverrideContext(repeat, items[i], i, itemsLength);
      let view = repeat.viewFactory.create();
      view.bind(overrideContext.bindingContext, overrideContext);
      repeat.viewSlot.add(view);
    }
  }

  /**
  * Handle the repeat's collection instance mutating.
  * @param repeat The repeat instance.
  * @param array The modified array.
  * @param splices Records of array changes.
  */
  instanceMutated(repeat, array, splices) {
    this._standardProcessInstanceMutated(repeat, array, splices);
  }

  _standardProcessInstanceMutated(repeat, array, splices) {
    let removeDelta = 0;
    let viewSlot = repeat.viewSlot;
    let rmPromises = [];

    for (let i = 0, ii = splices.length; i < ii; ++i) {
      let splice = splices[i];
      let removed = splice.removed;
      for (let j = 0, jj = removed.length; j < jj; ++j) {
        let viewOrPromise = this._removeViewAt(repeat, splice.index + removeDelta + rmPromises.length, true);
        if (viewOrPromise instanceof Promise) {
          rmPromises.push(viewOrPromise);
        }
      }
      removeDelta -= splice.addedCount;
    }

    if (rmPromises.length > 0) {
      Promise.all(rmPromises).then(() => {
        this._handleAddedSplices(repeat, array, splices);
        updateOverrideContexts(repeat, 0);
      });
    } else {
      this._handleAddedSplices(repeat, array, splices);
      updateOverrideContexts(repeat, 0);
    }
  }

  _removeViewAt(repeat, collectionIndex, returnToCache){
    let viewOrPromise;
    let view;
    let viewSlot = repeat.viewSlot;
    let viewAddIndex;

    // index in view slot?
    if(!this._isIndexBeforeViewSlot(repeat, viewSlot, collectionIndex) && !this._isIndexAfterViewSlot(repeat, viewSlot, collectionIndex)){
      let viewIndex = this._getViewIndex(repeat, viewSlot, collectionIndex);
      viewOrPromise = viewSlot.removeAt(viewIndex, returnToCache);
      if(repeat.items.length > viewSlot.children.length) {
        // TODO: do not trigger view lifecycle here
        let collectionAddIndex;
        if(repeat._bottomBufferHeight > repeat.itemHeight) {
          viewAddIndex = viewSlot.children.length;
          collectionAddIndex = repeat._getIndexOfLastView() + 1;
          repeat._bottomBufferHeight = repeat._bottomBufferHeight - (repeat.itemHeight);
        } else if(repeat._topBufferHeight > 0) {
          viewAddIndex = 0;
          collectionAddIndex = repeat._getIndexOfFirstView() - 1;
          repeat._topBufferHeight = repeat._topBufferHeight - (repeat.itemHeight);
        }
        let data = repeat.items[collectionAddIndex];
        if(data) {
          let overrideContext = createFullOverrideContext(repeat, repeat.items[collectionAddIndex], collectionAddIndex, repeat.items.length);
        view = repeat.viewFactory.create();
        view.bind(overrideContext.bindingContext, overrideContext);
        }
      } else {
        return viewOrPromise;
      }
    } else if (this._isIndexBeforeViewSlot(repeat, viewSlot, collectionIndex)) {
      if(repeat._bottomBufferHeight > 0) {
        repeat._bottomBufferHeight = repeat._bottomBufferHeight - (repeat.itemHeight);
        rebindAndMoveView(repeat, viewSlot.children[0], viewSlot.children[0].overrideContext.$index, true);
      } else {
        repeat._topBufferHeight = repeat._topBufferHeight - (repeat.itemHeight);
      }
    } else if(this._isIndexAfterViewSlot(repeat, viewSlot, collectionIndex)){
      repeat._bottomBufferHeight = repeat._bottomBufferHeight - (repeat.itemHeight);
    }

    if (viewOrPromise instanceof Promise) {
      viewOrPromise.then(() => {
        repeat.viewSlot.insert(viewAddIndex, view);
        repeat._adjustBufferHeights();
      });
      return;
    } else if(view) {
      repeat.viewSlot.insert(viewAddIndex, view);
    }

    repeat._adjustBufferHeights();
  }

  _isIndexBeforeViewSlot(repeat: VirtualRepeat, viewSlot: ViewSlot, index: number): number {
    let viewIndex = this._getViewIndex(repeat, viewSlot, index);
    return viewIndex < 0;
  }

  _isIndexAfterViewSlot(repeat: VirtualRepeat, viewSlot: ViewSlot, index: number): number {
    let viewIndex = this._getViewIndex(repeat, viewSlot, index);
    return viewIndex > repeat._viewsLength - 1;
  }

  _getViewIndex(repeat: VirtualRepeat, viewSlot: ViewSlot, index: number): number {
    if(viewSlot.children.length === 0) {
      return -1;
    }

    let topBufferItems = repeat._topBufferHeight / repeat.itemHeight;
    return index - topBufferItems;
  }

  _handleAddedSplices(repeat, array, splices) {
    let arrayLength = array.length;
    for (let i = 0, ii = splices.length; i < ii; ++i) {
      let splice = splices[i];
      let addIndex = splice.index;
      let end = splice.index + splice.addedCount;

      for (; addIndex < end; ++addIndex) {
        let overrideContext = createFullOverrideContext(repeat, array[addIndex], addIndex, arrayLength);
        let view = repeat.viewFactory.create();
        view.bind(overrideContext.bindingContext, overrideContext);
        repeat.viewSlot.insert(addIndex, view);
      }
    }
  }
}
<|endoftext|>


<commit_before>// script.js

// create the module and name it scotchApp
// Also include ngRoute for all our routing needs
var scotchApp = angular.module('scotchApp', ['ngRoute']);

// configure our routes
scotchApp.config(function($routeProvider) {
	$routeProvider

	// route for the home page
		.when('/', {
			templateUrl: 'public_html/onePageApp-take1/pages/home.html',
			controller : 'mainController'
		})

		// route for the about page
		.when('/about', {
			templateUrl : 'public_html/onePageApp-take1/pages/about.html',
			controller  : 'aboutController'
		})

		// route for the contact page
		.when('/contact', {
			templateUrl : 'pages/contract.html',
			controller  : 'contactController'
		});
});

// crate the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {

	// create a message to display in our view
	$scope.message = 'Everyone come and see how good I look!';
});

scotchApp.controller('aboutController', function($scope) {
	$scope.message = 'Look! I am an about page.';
});

scotchApp.controller('contactController', function($scope) {
	$scope.message = 'Contact us!  JK.  This is just a demo.';
});<commit_msg>Refactored Page folder to page folder and added comment to script.js<commit_after>// script.js

// create the module and name it scotchApp
// Also include ngRoute for all our routing needs
var scotchApp = angular.module('scotchApp', ['ngRoute']);

// configure our routes
scotchApp.config(function($routeProvider) {
	$routeProvider

	// route for the home page
		.when('/', {
			templateUrl: 'public_html/onePageApp-take1/pages/home.html',
			controller : 'mainController'
		})

		// route for the about page
		.when('/about', {
			templateUrl : 'public_html/onePageApp-take1/pages/about.html',
			controller  : 'aboutController'
		})

		// route for the contact page
		.when('/contact', {
			templateUrl : 'pages/contract.html',
			controller  : 'contactController'
		});
});

// crate the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {

	// create a message to display in our view
	$scope.message = 'Everyone come and see how good I look!';
});

scotchApp.controller('aboutController', function($scope) {
	$scope.message = 'Look! I am an about page.';
});

scotchApp.controller('contactController', function($scope) {
	$scope.message = 'Contact us!  JK.  This is just a demo.';
});

// End of module<|endoftext|>