<commit_before>'use strict';

/* App Module */

var services = ['ui','formsAngular.form','ui.bootstrap.tabs'];

var myApp = angular.module('myApp', services).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/index', {templateUrl: 'partials/howto.html'} ).
            when('/404', {templateUrl: 'partials/404.html'} ).
            when('/z_custom_form/new', {templateUrl: 'partials/custom-new.html', controller: BaseCtrl}).   // example view override
            when('/z_custom_form/:id/edit', {templateUrl: 'partials/custom-edit.html', controller: BaseCtrl}).   // example view override
            when('/z_custom_form/:form/new', {templateUrl: 'partials/custom-new.html', controller: BaseCtrl}).   // example view override
            when('/z_custom_form/:form/:id/edit', {templateUrl: 'partials/custom-edit.html', controller: BaseCtrl}).   // example view override
            when('/:model/:id/edit', {templateUrl: 'partials/base-edit.html', controller: BaseCtrl}).
            when('/:model/new', {templateUrl: 'partials/base-edit.html', controller: BaseCtrl}).
            when('/:model', {templateUrl: 'partials/base-list.html', controller: BaseCtrl}).
            when('/:model/:form/:id/edit', {templateUrl: 'partials/base-edit.html', controller: BaseCtrl}).
            when('/:model/:form/new', {templateUrl: 'partials/base-edit.html', controller: BaseCtrl}).
            when('/:model/:form', {templateUrl: 'partials/base-list.html', controller: BaseCtrl}).
            otherwise({redirectTo: '/index'});
    }]);

angular.module('myModule', ['ui']);

myApp.value('ui.config', {
    date: {
        dateFormat: 'dd/mm/yy'
    }
});
<commit_msg>Add some explanation<commit_after>'use strict';

/* App Module */

var services = ['ui','formsAngular.form','ui.bootstrap.tabs'];

var myApp = angular.module('myApp', services).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/index', {templateUrl: 'partials/howto.html'} ).
            when('/404', {templateUrl: 'partials/404.html'} ).
            when('/z_custom_form/new', {templateUrl: 'partials/custom-new.html', controller: BaseCtrl}).            // example view override
            when('/z_custom_form/:id/edit', {templateUrl: 'partials/custom-edit.html', controller: BaseCtrl}).      // example view override
            when('/z_custom_form/:form/new', {templateUrl: 'partials/custom-new.html', controller: BaseCtrl}).      // example view override with specified form content
            when('/z_custom_form/:form/:id/edit', {templateUrl: 'partials/custom-edit.html', controller: BaseCtrl}).// example view override with specified form content
            when('/:model/:id/edit', {templateUrl: 'partials/base-edit.html', controller: BaseCtrl}).
            when('/:model/new', {templateUrl: 'partials/base-edit.html', controller: BaseCtrl}).
            when('/:model', {templateUrl: 'partials/base-list.html', controller: BaseCtrl}).
            when('/:model/:form/:id/edit', {templateUrl: 'partials/base-edit.html', controller: BaseCtrl}).  // non default form (different fields etc)
            when('/:model/:form/new', {templateUrl: 'partials/base-edit.html', controller: BaseCtrl}).       // non default form (different fields etc)
            when('/:model/:form', {templateUrl: 'partials/base-list.html', controller: BaseCtrl}).           // list page with links to non default form
            otherwise({redirectTo: '/index'});
    }]);

angular.module('myModule', ['ui']);

myApp.value('ui.config', {
    date: {
        dateFormat: 'dd/mm/yy'
    }
});
<|endoftext|>


<commit_before>var app = angular.module('materialscommons',
    ['ui', 'Filter', 'materialsCommonsServices', 'materialsdirective', 'jqyoui', 'AngularStomp',
        'ui.bootstrap', 'NgTree', 'ngCookies', '$strap.directives']);

app.config(['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider) {
    Stomp.WebSocketClass = SockJS;
    mcglobals = {};
    doConfig();

    /*
     ** CORS support
     */
    //$httpProvider.defaults.useXDomain = true;
    //delete $httpProvider.defaults.headers.common['X-Requested-With'];

    $routeProvider.
        when('/home', {templateUrl: 'partials/home.html', controller: HomeController}).
        when('/searchindex/:subpage/:name',
        {templateUrl: 'partials/search.html', controller: SearchIndexController}).

        /*
         ** Account controllers
         */
        when('/account/login', {templateUrl: 'partials/account/login.html', controller: LoginController}).
        when('/account/logout', {templateUrl: 'partials/about.html', controller: LogOutController}).
        when('/account/create-account', {templateUrl: 'partials/account/create-account.html', controller: CreateAccountController}).
        when('/account/details', {templateUrl: 'partials/account/account-details.html', controller: AccountDetailsController}).
        when('/account/details/apikey/view', {templateUrl: 'partials/account/details/apikeyview.html', controller: ApiKeyController}).
        when('/account/details/apikey/reset', {templateUrl: 'partials/account/details/apikeyreset.html', controller: ApiKeyResetController}).
        when('/account/details/usergroups/my_list', {templateUrl: 'partials/account/details/usergroups.html', controller: UserGroupController}).
        when('/account/details/usergroups/create', {templateUrl: 'partials/account/details/usergroup-create.html', controller: UserGroupController}).
        when('/account/details/usergroups/list_all', {templateUrl: 'partials/account/details/usergroups_list_all.html', controller: ListUserGroupController}).
        when('/account/details/usergroup/list_users/:usergroup_name', {templateUrl: 'partials/account/details/usergroup_list_users.html', controller: ListUserController}).

        /*
         ** Top level controllers
         */
        when('/about', {templateUrl: 'partials/about.html', controller: AboutController}).
        when('/contact', {templateUrl: 'partials/contact.html', controller: ContactController}).
        when('/help', {templateUrl: 'partials/help.html', controller: HelpController}).
        when('/search', {templateUrl: 'partials/search.html', controller: SearchIndexController}).
        when('/my-tools', {templateUrl: 'partials/my-tools.html', controller: FrontPageController}).

        /*
         ** Controllers with in the My Tools subpages
         */

        /*
         ** Data Groups
         */
        when('/datagroups/tree', {templateUrl: 'partials/datagroups/tree.html', controller: MyDataGroupsTreeController}).
        when('/datagroups/tree/group', {templateUrl: 'partials/datagroups/tree.html', controller: MyGroupsDataGroupsTreeController}).
        when('/datagroups/data/:id', {templateUrl: 'partials/datagroups/datareport.html', controller: DataDirReportController}).

        /*
         ** Other
         */
        when('/datagroups',
        {templateUrl: 'partials/datagroups/my_data_groups.html', controller: MyDataGroupsController}).
        when('/my_lab', {templateUrl: 'partials/datagroups/my_lab.html', controller: LabController}).
        when('/results_by_date',
        {templateUrl: 'partials/datagroups/results_by_date.html', controller: SearchByDateController}).

        /*
         ** Data
         */
        when('/data/edit/:id', {templateUrl: 'partials/data/data-edit.html', controller: DataEditController}).
        when('/data/mydata', {templateUrl: 'partials/data/my-data.html', controller: MyDataController}).

        /*
         ** Tags
         */
        when('/tags/list/:listtype', {templateUrl: 'partials/tags/tags-list.html', controller: TagListController}).
        when('/tags/data/bytag/:tag/:user',
        {templateUrl: 'partials/tags/data-for-tag.html', controller: TagDataController}).
        when('/tags/tag_info/:tag_name', {templateUrl: 'partials/tags/tag_info.html', controller: TagListController}).
        when('/tags/cloud/global', {templateUrl: 'partials/tags/tagcloud.html', controller: GlobalTagCloudController}).

        /*
         ** Upload/Download
         */
        when('/upload/file', {templateUrl: 'partials/updownload/upload-file.html', controller: UploadFileController}).
        when('/upload/directory', {templateUrl: 'partials/updownload/upload-directory.html', controller: UploadDirectoryController}).
        when('/updownload/queue', {templateUrl: 'partials/updownload/udqueue.html', controller: UpDownLoadQueueController}).

        otherwise({redirectTo: '/home'});
}]);

app.run(function ($rootScope, $location, $cookieStore, User, ngstomp) {
    $rootScope.$on('$routeChangeStart', function (event, next, current) {
        if (matchesPartial(next, "partials/front-page", "HomeController")) {
            setActiveMainNav("#home-nav");
        }
        else if (matchesPartial(next, "partials/my-tools", "FrontPageController")) {
            setActiveMainNav("#user-nav");
        }
        else if (matchesPartial(next, "partials/explore", "ExploreController")) {
            setActiveMainNav("#explore-nav");
        }
        else if (matchesPartial(next, "partials/about", "AboutController")) {
            setActiveMainNav('#about-nav');
        }
        else if (matchesPartial(next, "partials/contact", "ContactController")) {
            setActiveMainNav('#contact-nav');
        }
        else if (matchesPartial(next, "partials/help", "HelpController")) {
            setActiveMainNav("#help-nav");
        }

        if (!$rootScope.stompClient) {
            var chatConnection = "http://" + document.location.name + ":15674/stomp";
            if (document.location.hostname == "materialscommons.org") {
                chatConnection = "https://materialscommons.org:55674/stomp";
            }

            $rootScope.stompClient = ngstomp(chatConnection);
        }

        if (mcglobals.bypasslogin) {
            if (mcglobals.username) {
                User.setAuthenticated(true, mcglobals.apikey, mcglobals.username);
                $rootScope.email_address = mcglobals.username;
            }
            return;
        }

        if (!User.isAuthenticated()) {
            if (next.templateUrl && next.templateUrl.indexOf("partials/my-tools") != -1) {
                $location.path("/account/login");
            }
        }
        else {
            $rootScope.email_address = User.u();
        }
    });

});

function matchesPartial(next, what, controller) {
    if (!next.templateUrl) {
        return false;
    }
    else {
        var value = next.templateUrl.indexOf(what) != -1;
        /*
         Hack to look at controller name to figure out tab. We do this so that partials can be
         shared by controllers, but we need to show which tab is active. So, we look at the
         name of the controller (only if controller != 'ignore').
         */
        if (controller == "ignore") {
            return value;
        }
        else if (value) {
            return true;
        }
        else {
            return next.controller.toString().indexOf(controller) != -1;
        }
    }
}
<commit_msg>ISSUE#5 Moved a datagroups call up into the datagroups section from the other section.<commit_after>var app = angular.module('materialscommons',
    ['ui', 'Filter', 'materialsCommonsServices', 'materialsdirective', 'jqyoui', 'AngularStomp',
        'ui.bootstrap', 'NgTree', 'ngCookies', '$strap.directives']);

app.config(['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider) {
    Stomp.WebSocketClass = SockJS;
    mcglobals = {};
    doConfig();

    /*
     ** CORS support
     */
    //$httpProvider.defaults.useXDomain = true;
    //delete $httpProvider.defaults.headers.common['X-Requested-With'];

    $routeProvider.
        when('/home', {templateUrl: 'partials/home.html', controller: HomeController}).
        when('/searchindex/:subpage/:name',
        {templateUrl: 'partials/search.html', controller: SearchIndexController}).

        /*
         ** Account controllers
         */
        when('/account/login', {templateUrl: 'partials/account/login.html', controller: LoginController}).
        when('/account/logout', {templateUrl: 'partials/about.html', controller: LogOutController}).
        when('/account/create-account', {templateUrl: 'partials/account/create-account.html', controller: CreateAccountController}).
        when('/account/details', {templateUrl: 'partials/account/account-details.html', controller: AccountDetailsController}).
        when('/account/details/apikey/view', {templateUrl: 'partials/account/details/apikeyview.html', controller: ApiKeyController}).
        when('/account/details/apikey/reset', {templateUrl: 'partials/account/details/apikeyreset.html', controller: ApiKeyResetController}).
        when('/account/details/usergroups/my_list', {templateUrl: 'partials/account/details/usergroups.html', controller: UserGroupController}).
        when('/account/details/usergroups/create', {templateUrl: 'partials/account/details/usergroup-create.html', controller: UserGroupController}).
        when('/account/details/usergroups/list_all', {templateUrl: 'partials/account/details/usergroups_list_all.html', controller: ListUserGroupController}).
        when('/account/details/usergroup/list_users/:usergroup_name', {templateUrl: 'partials/account/details/usergroup_list_users.html', controller: ListUserController}).

        /*
         ** Top level controllers
         */
        when('/about', {templateUrl: 'partials/about.html', controller: AboutController}).
        when('/contact', {templateUrl: 'partials/contact.html', controller: ContactController}).
        when('/help', {templateUrl: 'partials/help.html', controller: HelpController}).
        when('/search', {templateUrl: 'partials/search.html', controller: SearchIndexController}).
        when('/my-tools', {templateUrl: 'partials/my-tools.html', controller: FrontPageController}).

        /*
         ** Controllers with in the My Tools subpages
         */

        /*
         ** Data Groups
         */
        when('/datagroups/tree', {templateUrl: 'partials/datagroups/tree.html', controller: MyDataGroupsTreeController}).
        when('/datagroups/tree/group', {templateUrl: 'partials/datagroups/tree.html', controller: MyGroupsDataGroupsTreeController}).
        when('/datagroups/data/:id', {templateUrl: 'partials/datagroups/datareport.html', controller: DataDirReportController}).
        when('/datagroups',
        {templateUrl: 'partials/datagroups/my_data_groups.html', controller: MyDataGroupsController}).

        /*
         ** Other
         */
        when('/my_lab', {templateUrl: 'partials/datagroups/my_lab.html', controller: LabController}).
        when('/results_by_date',
        {templateUrl: 'partials/datagroups/results_by_date.html', controller: SearchByDateController}).

        /*
         ** Data
         */
        when('/data/edit/:id', {templateUrl: 'partials/data/data-edit.html', controller: DataEditController}).
        when('/data/mydata', {templateUrl: 'partials/data/my-data.html', controller: MyDataController}).

        /*
         ** Tags
         */
        when('/tags/list/:listtype', {templateUrl: 'partials/tags/tags-list.html', controller: TagListController}).
        when('/tags/data/bytag/:tag/:user',
        {templateUrl: 'partials/tags/data-for-tag.html', controller: TagDataController}).
        when('/tags/tag_info/:tag_name', {templateUrl: 'partials/tags/tag_info.html', controller: TagListController}).
        when('/tags/cloud/global', {templateUrl: 'partials/tags/tagcloud.html', controller: GlobalTagCloudController}).

        /*
         ** Upload/Download
         */
        when('/upload/file', {templateUrl: 'partials/updownload/upload-file.html', controller: UploadFileController}).
        when('/upload/directory', {templateUrl: 'partials/updownload/upload-directory.html', controller: UploadDirectoryController}).
        when('/updownload/queue', {templateUrl: 'partials/updownload/udqueue.html', controller: UpDownLoadQueueController}).

        otherwise({redirectTo: '/home'});
}]);

app.run(function ($rootScope, $location, $cookieStore, User, ngstomp) {
    $rootScope.$on('$routeChangeStart', function (event, next, current) {
        if (matchesPartial(next, "partials/front-page", "HomeController")) {
            setActiveMainNav("#home-nav");
        }
        else if (matchesPartial(next, "partials/my-tools", "FrontPageController")) {
            setActiveMainNav("#user-nav");
        }
        else if (matchesPartial(next, "partials/explore", "ExploreController")) {
            setActiveMainNav("#explore-nav");
        }
        else if (matchesPartial(next, "partials/about", "AboutController")) {
            setActiveMainNav('#about-nav');
        }
        else if (matchesPartial(next, "partials/contact", "ContactController")) {
            setActiveMainNav('#contact-nav');
        }
        else if (matchesPartial(next, "partials/help", "HelpController")) {
            setActiveMainNav("#help-nav");
        }

        if (!$rootScope.stompClient) {
            var chatConnection = "http://" + document.location.name + ":15674/stomp";
            if (document.location.hostname == "materialscommons.org") {
                chatConnection = "https://materialscommons.org:55674/stomp";
            }

            $rootScope.stompClient = ngstomp(chatConnection);
        }

        if (mcglobals.bypasslogin) {
            if (mcglobals.username) {
                User.setAuthenticated(true, mcglobals.apikey, mcglobals.username);
                $rootScope.email_address = mcglobals.username;
            }
            return;
        }

        if (!User.isAuthenticated()) {
            if (next.templateUrl && next.templateUrl.indexOf("partials/my-tools") != -1) {
                $location.path("/account/login");
            }
        }
        else {
            $rootScope.email_address = User.u();
        }
    });

});

function matchesPartial(next, what, controller) {
    if (!next.templateUrl) {
        return false;
    }
    else {
        var value = next.templateUrl.indexOf(what) != -1;
        /*
         Hack to look at controller name to figure out tab. We do this so that partials can be
         shared by controllers, but we need to show which tab is active. So, we look at the
         name of the controller (only if controller != 'ignore').
         */
        if (controller == "ignore") {
            return value;
        }
        else if (value) {
            return true;
        }
        else {
            return next.controller.toString().indexOf(controller) != -1;
        }
    }
}
<|endoftext|>


<commit_before>define(['angular',"route",
	'js/directive/directive',
	'js/home/controller','js/home/directive',
	'js/article/controller',
	'js/timeline/controller',
	'js/show/controller','js/show/directive',
	'js/service/service',
	],function(){

	'use strict';

	// define app module
	var appModule = angular.module('App', ['ngRoute',
		'Timeline','Show','homeDirectiveModule','ShowDirectiveModule',
		'ArticleCtrl','httpService',
		]);

	// app module config
	appModule.config(['$routeProvider','$locationProvider',
		function($routeProvider,$locationProvider) {

			$locationProvider.html5Mode(false).hashPrefix('~');

			$routeProvider
				.when("/home",{
									templateUrl : "./js/home/home.html",
									//controller : 'ChartCtrl',
									reloadOnSearch : false
							  }
				)
				.when("/timeline",{
									templateUrl : "./js/timeline/timeline.html",
									controller : 'timelineCtrl',
									reloadOnSearch : false
								  }
				)
				.when("/article",{
									templateUrl : "./js/article/article.html",
									controller : 'articleCtrl',
									reloadOnSearch : false
								 }
				).when("/articleDetail/:id",{
									templateUrl : "./js/article/articleDetail.html",
									controller : 'articleDetailCtrl',
									reloadOnSearch : false
								 }
				)
				.when("/show",{
									templateUrl : "./js/show/show.html",
									controller : 'showCtrl',
									reloadOnSearch : false
							  }
				)
				.when("/about",{
									templateUrl : "./js/about/about.html",
									//controller : 'HelloCtrl',
									reloadOnSearch : false
								}
				)
				.otherwise({
						redirectTo : "/home"
				});
			}]);

});<commit_msg>change<commit_after>define(['angular',"route",
	'js/directive/directive',
	'js/home/controller','js/home/directive',
	'js/article/controller',
	'js/timeline/controller',
	'js/show/controller','js/show/directive',
	'js/service/service',
	],function(){

	'use strict';

	// define app module
	var appModule = angular.module('App', ['ngRoute',
		'Timeline','Show','homeDirectiveModule','ShowDirectiveModule',
		'ArticleCtrl','httpService',
		]);

	// app module config
	appModule.config(['$routeProvider','$locationProvider',
		function($routeProvider,$locationProvider) {

			$locationProvider.html5Mode(false).hashPrefix('~');

			$routeProvider
				.when("/home",{
									templateUrl : "./js/home/home.html",
									//controller : 'ChartCtrl',
									reloadOnSearch : false
							  }
				)
				.when("/timeline",{
									templateUrl : "./js/timeline/timeline.html",
									controller : 'timelineCtrl',
									reloadOnSearch : false
								  }
				)
				.when("/article",{
									templateUrl : "./js/article/article.html",
									controller : 'articleCtrl',
									reloadOnSearch : false
								 }
				).when("/articleDetail/:id",{
									templateUrl : "./js/article/articleDetail.html",
									controller : 'articleDetailCtrl',
									reloadOnSearch : false
								 }
				)
				.when("/show",{
									templateUrl : "./js/show/show.html",
									controller : 'showCtrl',
									reloadOnSearch : false
							  }
				)
				.when("/about",{
									templateUrl : "./js/about/about.html",
									//controller : 'HelloCtrl',
									reloadOnSearch : false
								}
				)
				.otherwise({
						redirectTo : "/home"
				});
			}]).run([ "$rootScope", "$window", function($rootScope, $window) {

						$rootScope.$on('$locationChangeSuccess', function(){

							if(arguments[1].indexOf('plan') !== -1){
								scroll(0,450);
					        }else{
					        	scroll(0,0);
					        }

						});
					} ]);

});<|endoftext|>


<commit_before>/**
 * Tests over http_on_pipe.js
 */

var assert = require("assert"),
    Q = require("q"),
    Readable = require('stream').Readable,
    Writable = require('stream').Writable,
    debug = require("debug")("tests/http_on_pipe"),
    http_on_pipe = require("../../http_on_pipe"),
    HTTPParser = http_on_pipe.HTTPParser;

require("../thenMochaDone");

function writeStringToParser(parser, str) {
    return parser.write(new Buffer(str));
}

describe("HTTPParser", function () {
    it("parses a GET", function (done) {
        var parser = new HTTPParser();
        var timely = false;
        parser.on('request', function (req) {
            if (timely) {
                try {
                    assert.equal(req.url, "/zoinx");
                    assert.equal(req.headers.host, "zoinx.org");
                    done();
                } catch (e) {
                    done(e);
                }
            } else {
                done(new Error("not timely"));
            }
        });
        writeStringToParser(parser, "GET /zoinx HTTP/1.1\r\n");
        writeStringToParser(parser, "Host: zoinx.org\r\n");
        timely = true;
        writeStringToParser(parser, "\r\n");
    });
    it("parses two GETs back to back", function (done) {
        function writeOneRequest(parser) {
            writeStringToParser(parser, "GET /zoinx HTTP/1.1\r\n" +
                "Host: zoinx.org\r\n\r\n");
        }
        var parser = new HTTPParser();
        var count = 0;
        parser.on('request', function () {
            count += 1;
            if (count == 2) {
                done();  // Ah, ah, ah !!!
            }
        });
        writeOneRequest(parser);
        writeOneRequest(parser);
    });
    it("parses a POST with a body, and resumes parsing GETs", function (done) {
        var foundPOST = Q.defer(), foundGET = Q.defer();
        Q.all([foundPOST.promise, foundGET.promise]).thenMochaDone(done);

        var parser = new HTTPParser();
        parser.on('request', function (req) {
            if (req.method === "POST") {
                try {
                    assert.equal(req.url, "/zoinx");
                    assert.equal(req.headers.host, "zoinx.org");
                    var buf = "";
                    req.on("data", function (txt) {
                        buf += txt;
                    });
                    req.on("end", function () {
                        try {
                            assert.equal(buf, "ZOINX");
                        } catch (e) {
                            foundPOST.reject(e);
                        }
                        foundPOST.resolve();
                    });
                } catch (e) {
                    foundPOST.reject(e);
                }
            } else {
                try {
                    assert.equal(req.url, "/zoinx");
                    assert.equal(req.headers.host, "zoinx.org");
                    foundGET.resolve();
                } catch (e) {
                    foundGET.reject(e);
                }
            }
        });
        writeStringToParser(parser,
            "POST /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n" +
            "Content-Length: 5\r\n" +
            "\r\n" +
            "ZOINX" +  // Note conspicuous lack of \r\n
            "GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
    });
    it("closes cleanly", function (done) {
        var parser = new HTTPParser();
        parser.on("request", function() {done()});
        writeStringToParser(parser, "GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
        parser.end();
    });
    it("deals with parse errors", function (done) {
        var parser = new HTTPParser();
        parser.on("request", function () {
            done(new Error("This sure shouldn't parse"));
        });
        parser.on("error", function () {
            done();
        });
        writeStringToParser(parser, "GET\r\n" +
            "Host: zoinx.org\r\n\r\n");
        parser.end();
    });
});

function checkThenDone(checks, done) {
    return function() {
        try {
            checks.apply(this, Array.prototype.slice.apply(arguments));
            done();
        } catch (e) {
            done(e);
        }
    };
}

describe("http_on_pipe", function () {
    function makeStringSource(readBuf) {
        var source = new Readable();
        source._read = function () {
            source.push(readBuf);
            readBuf = null;
        };
        return source;
    }

    function makeStringSink() {
        var sink = new Writable();
        sink.buf = "";
        sink._write = function (data, encoding, cb) {
            sink.buf += data;
            debug("sink.buf is now " + sink.buf.length + " bytes long");
            cb();
        };
        return sink;
    }

    function bogoServe(req, res) {
        debug("bogoServing");
        res.setHeader("Content-Type", "text/plain");
        res.write("This is a " + req.method + " on " + req.url + "\n");
        res.end();
    }

    it("serves", function (done) {
        var src = makeStringSource("GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
        var sink = makeStringSink();
        http_on_pipe(src, sink, bogoServe,
            checkThenDone(function (err) {
                assert.equal(err, undefined);
                assert(sink.buf.toString().match("This is a GET on /zoinx"));
            }, done));
    });
    it("deals with parse errors");
    it("deals with EPIPE", function (done) {
        var src = makeStringSource("GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
        var brokenSink = new Writable();
        brokenSink._write = function (chunk, encoding, callback) {
            debug("Ehh, no piping");
            callback(new Error("EPIPE"));
        };
        http_on_pipe(src, brokenSink, bogoServe,
            checkThenDone(function (err) {
                assert.equal(err.message, "EPIPE");
            }, done));
    });
    it("deals with errors thrown in the handler");
});
<commit_msg>it("serves POSTs (and then GETs)")<commit_after>/**
 * Tests over http_on_pipe.js
 */

var assert = require("assert"),
    Q = require("q"),
    Readable = require('stream').Readable,
    Writable = require('stream').Writable,
    debug = require("debug")("tests/http_on_pipe"),
    http_on_pipe = require("../../http_on_pipe"),
    HTTPParser = http_on_pipe.HTTPParser;

require("../thenMochaDone");

function writeStringToParser(parser, str) {
    return parser.write(new Buffer(str));
}

describe("HTTPParser", function () {
    it("parses a GET", function (done) {
        var parser = new HTTPParser();
        var timely = false;
        parser.on('request', function (req) {
            if (timely) {
                try {
                    assert.equal(req.url, "/zoinx");
                    assert.equal(req.headers.host, "zoinx.org");
                    done();
                } catch (e) {
                    done(e);
                }
            } else {
                done(new Error("not timely"));
            }
        });
        writeStringToParser(parser, "GET /zoinx HTTP/1.1\r\n");
        writeStringToParser(parser, "Host: zoinx.org\r\n");
        timely = true;
        writeStringToParser(parser, "\r\n");
    });
    it("parses two GETs back to back", function (done) {
        function writeOneRequest(parser) {
            writeStringToParser(parser, "GET /zoinx HTTP/1.1\r\n" +
                "Host: zoinx.org\r\n\r\n");
        }
        var parser = new HTTPParser();
        var count = 0;
        parser.on('request', function () {
            count += 1;
            if (count == 2) {
                done();  // Ah, ah, ah !!!
            }
        });
        writeOneRequest(parser);
        writeOneRequest(parser);
    });
    it("parses a POST with a body, and resumes parsing GETs", function (done) {
        var foundPOST = Q.defer(), foundGET = Q.defer();
        Q.all([foundPOST.promise, foundGET.promise]).thenMochaDone(done);

        var parser = new HTTPParser();
        parser.on('request', function (req) {
            if (req.method === "POST") {
                try {
                    assert.equal(req.url, "/zoinx");
                    assert.equal(req.headers.host, "zoinx.org");
                    var buf = "";
                    req.on("data", function (txt) {
                        buf += txt;
                    });
                    req.on("end", function () {
                        try {
                            assert.equal(buf, "ZOINX");
                        } catch (e) {
                            foundPOST.reject(e);
                        }
                        foundPOST.resolve();
                    });
                } catch (e) {
                    foundPOST.reject(e);
                }
            } else {
                try {
                    assert.equal(req.url, "/zoinx");
                    assert.equal(req.headers.host, "zoinx.org");
                    foundGET.resolve();
                } catch (e) {
                    foundGET.reject(e);
                }
            }
        });
        writeStringToParser(parser,
            "POST /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n" +
            "Content-Length: 5\r\n" +
            "\r\n" +
            "ZOINX" +  // Note conspicuous lack of \r\n
            "GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
    });
    it("closes cleanly", function (done) {
        var parser = new HTTPParser();
        parser.on("request", function() {done()});
        writeStringToParser(parser, "GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
        parser.end();
    });
    it("deals with parse errors", function (done) {
        var parser = new HTTPParser();
        parser.on("request", function () {
            done(new Error("This sure shouldn't parse"));
        });
        parser.on("error", function () {
            done();
        });
        writeStringToParser(parser, "GET\r\n" +
            "Host: zoinx.org\r\n\r\n");
        parser.end();
    });
});

function checkThenDone(checks, done) {
    return function() {
        try {
            checks.apply(this, Array.prototype.slice.apply(arguments));
            done();
        } catch (e) {
            done(e);
        }
    };
}

describe("http_on_pipe", function () {
    function makeStringSource(readBuf) {
        var source = new Readable();
        source._read = function () {
            source.push(readBuf);
            readBuf = null;
        };
        return source;
    }

    function makeStringSink() {
        var sink = new Writable();
        sink.buf = "";
        sink._write = function (data, encoding, cb) {
            sink.buf += data;
            debug("sink.buf is now " + sink.buf.length + " bytes long");
            cb();
        };
        return sink;
    }

    function bogoServe(req, res) {
        debug("bogoServing");
        res.setHeader("Content-Type", "text/plain");
        res.write("This is a " + req.method + " on " + req.url + "\n");
        res.end();
    }

    it("serves", function (done) {
        var src = makeStringSource("GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
        var sink = makeStringSink();
        http_on_pipe(src, sink, bogoServe,
            checkThenDone(function (err) {
                assert.equal(err, undefined);
                assert(sink.buf.toString().match("This is a GET on /zoinx"));
            }, done));
    });
    it("serves POSTs (and then GETs)", function (done) {
        var src = makeStringSource(
            "POST /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n" +
            "Content-Length: 5\r\n" +
            "\r\n" +
            "ZOINX" +  // Note conspicuous lack of \r\n
            "GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
        var sink = makeStringSink();
        http_on_pipe(src, sink, bogoServe,
            checkThenDone(function (err) {
                assert.equal(err, undefined);
                assert(sink.buf.toString().match(
                    /This is a POST on \/zoinx[\s\S]*This is a GET on \/zoinx/));
            }, done));
    });
    it("deals with parse errors");
    it("deals with EPIPE", function (done) {
        var src = makeStringSource("GET /zoinx HTTP/1.1\r\n" +
            "Host: zoinx.org\r\n\r\n");
        var brokenSink = new Writable();
        brokenSink._write = function (chunk, encoding, callback) {
            debug("Ehh, no piping");
            callback(new Error("EPIPE"));
        };
        http_on_pipe(src, brokenSink, bogoServe,
            checkThenDone(function (err) {
                assert.equal(err.message, "EPIPE");
            }, done));
    });
    it("deals with errors thrown in the handler");
});
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

// This file creates a set of helper functions that will be loaded for all html
// templates. These functions should be self contained and not rely on any
// external dependencies as they are loaded prior to the application. We may
// want to change this later, but for now this should be thought of as a
// "purely functional" helper system.

define([
  "jquery",
  "lodash"
],

function($, _ ) {

  var mixins = {};

  var onWindowResize = {};

  mixins.addWindowResize = function(fun, key){
    onWindowResize[key]=fun;
    // You shouldn't need to call it here. Just define it at startup and each time it will loop
    // through all the functions in the hash.
    //app.initWindowResize();
  };

  mixins.removeWindowResize = function(key){
    delete onWindowResize[key];
    mixins.initWindowResize();
  };

  mixins.initWindowResize = function(){
  //when calling this it should be overriding what was called previously
    window.onresize = function(e) {
       // could do this instead of the above for loop
      _.each(onWindowResize, function (fn) {
        fn();
      });
    };
  };

  mixins.removeSpecialCharacters = function(name){
    return name.replace(/[^\w\s]/gi,"");
  };

  mixins.safeURLName = function(name){
    var checkforBad = name.match(/[\$\-/_,+-]/g);
    return (checkforBad !== null)?encodeURIComponent(name):name;
  };

  return mixins;
});

<commit_msg>null pattern check on safeURLname<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

// This file creates a set of helper functions that will be loaded for all html
// templates. These functions should be self contained and not rely on any
// external dependencies as they are loaded prior to the application. We may
// want to change this later, but for now this should be thought of as a
// "purely functional" helper system.

define([
  "jquery",
  "lodash"
],

function($, _ ) {

  var mixins = {};

  var onWindowResize = {};

  mixins.addWindowResize = function(fun, key){
    onWindowResize[key]=fun;
    // You shouldn't need to call it here. Just define it at startup and each time it will loop
    // through all the functions in the hash.
    //app.initWindowResize();
  };

  mixins.removeWindowResize = function(key){
    delete onWindowResize[key];
    mixins.initWindowResize();
  };

  mixins.initWindowResize = function(){
  //when calling this it should be overriding what was called previously
    window.onresize = function(e) {
       // could do this instead of the above for loop
      _.each(onWindowResize, function (fn) {
        fn();
      });
    };
  };

  mixins.removeSpecialCharacters = function(name){
    return name.replace(/[^\w\s]/gi,"");
  };

  mixins.safeURLName = function(name){
    var testName = name || "";
    var checkforBad = testName.match(/[\$\-/_,+-]/g);
    return (checkforBad !== null)?encodeURIComponent(name):name;
  };

  return mixins;
});

<|endoftext|>


<commit_before>( function() {
	'use strict';

	describe( 'vui', function() {

		var node, heading;

		beforeEach( function () {
			jasmine.addMatchers( d2l.jasmine.matchers );
			node = document.body.appendChild( document.createElement( 'div' ) );
			node.className = 'vui-accordion';
		} );

		afterEach( function() {
			document.body.removeChild( node );
		} );

		describe( 'accordion', function() {

			it( 'defines a "vui-accordion" selector', function() {
				expect( true ).toBeTruthy();
			} );

		} );

	} );

} )();<commit_msg>Adding a couple of real tests for accordion widget.<commit_after>( function() {
	'use strict';

	describe( 'vui', function() {

		var node, heading;

		beforeEach( function () {
			jasmine.addMatchers( d2l.jasmine.matchers );
			node = document.body.appendChild( document.createElement( 'div' ) );
			node.className = 'vui-accordion';
		} );

		afterEach( function() {
			document.body.removeChild( node );
		} );

		describe( 'accordion', function() {

			var accordion, header1, heading1, content1;

			beforeEach( function () {

				accordion = node.appendChild( document.createElement( 'div' ) );
				accordion.className = 'vui-accordion';
				accordion.setAttribute( 'data-display-mode', 'accordion' );

				header1 = accordion.appendChild( document.createElement( 'div' ) );
				header1.className = 'vui-accordion-header';
				header1.setAttribute( 'data-content-labelledby', 'heading1' );

				heading1 = header1.appendChild( document.createElement( 'h2' ) );
				heading1.id = 'heading1';
				heading1.innerHTML = 'This is heading 1.';

				content1 = accordion.appendChild( document.createElement( 'div' ) );
				content1.className = 'vui-accordion-content';

				content1.appendChild( document.createElement( 'p' ) ).innerHTML = 'This is content 1.';

			} );

			it( 'defines a "vui-accordion" selector', function() {
				expect( document ).toHaveCssSelector( '.vui-accordion' );
			} );

			it( 'initializes accordion using widget method', function() {

				$( accordion ).vui_accordion();

				expect( accordion.getAttribute( 'role' ) ).toBe( 'tablist' );

			} );

		} );

	} );

} )();<|endoftext|>


<commit_before>import React, { Component } from 'react';
import AllActivitiesBox from '../components/AllActivitiesBox';
import {getUpcomingActivities} from '../APIFunctions';

import ActivityPageContainer from '../components/ActivityPageComponent';
import { connect } from "react-redux";

class AllActivitiesContainer extends Component {

    constructor(props) {
        super(props);
        console.log("AllActivitiesContainer is here");
        this.state = {

            ids: []
        }
    }

    createActivityPageComponent() {
        console.log(this.props.activities);
        console.log('^from All activities Container');
        return this.props.activities.activities.map((activity) => {
            return (
                <ActivityPageContainer key={activity.id} activity={activity}/>
            )
        });
    }

    render() {

        const styles = {
            activitiesContainerStyle: {
                margin: "0px 10px 0px 10px"
            },
            activitiesStyle: {
                display: "flex",
                flexWrap: "wrap",
                flexDirection: "row",
                justifyContent: "center"
            }
        };

        console.log('render');
        return (

Aktiviteter

                  {this.createActivityPageComponent()}

        );
    }

    componentDidMount() {
        getUpcomingActivities(function(idArray) {
            this.setState({ids: idArray});
        }.bind(this));
    }
}

function mapStateToProps(state) {
    //console.log(state.activity);
    //console.log("^ is from mapStateToProps in APC");
    return {
        activities: state.activity
    };
}

export default connect(mapStateToProps)(AllActivitiesContainer);
<commit_msg>Removed debug statements<commit_after>import React, { Component } from 'react';
import AllActivitiesBox from '../components/AllActivitiesBox';
import {getUpcomingActivities} from '../APIFunctions';

import ActivityPageContainer from '../components/ActivityPageComponent';
import { connect } from "react-redux";

class AllActivitiesContainer extends Component {

    constructor(props) {
        super(props);
        this.state = {

            ids: []
        }
    }

    createActivityPageComponent() {
        return this.props.activities.map((activity) => {
            return (
                <ActivityPageContainer key={activity.id} activity={activity}/>
            )
        });
    }

    render() {

        const styles = {
            activitiesContainerStyle: {
                margin: "0px 10px 0px 10px"
            },
            activitiesStyle: {
                display: "flex",
                flexWrap: "wrap",
                flexDirection: "row",
                justifyContent: "center"
            }
        };

        return (

Aktiviteter

                  {this.createActivityPageComponent()}

        );
    }

    componentDidMount() {
        getUpcomingActivities(function(idArray) {
            this.setState({ids: idArray});
        }.bind(this));
    }
}

function mapStateToProps(state) {
    return {
        activities: state.activity
    };
}

export default connect(mapStateToProps)(AllActivitiesContainer);
<|endoftext|>


<commit_before>/* eslint-env jasmine, mocha */

describe('dom: outerHTML', () => {
  function compare(src, dst) {
    expect(src.outerHTML).to.equal(dst);
  }

  function runTests (type) {
    describe(`${type}: `, () => {
      let host;
      let root;
      let slot;
      let div;
      let elem;

      beforeEach(() => {
        host = document.createElement('div');
        root = host.attachShadow({ mode: 'open' });
        slot = document.createElement('slot');

        root.appendChild(slot);

        div = document.createElement('div');

        switch (type) {
          case 'div':
            elem = div;
            break;
          case 'slot':
            elem = slot;
            break;
          default:
            elem = host;
        }
      });

      it('should get a proper value from a node with one element child', () => {
        elem.innerHTML = '<test></test>';
        if (type === 'host' || type === 'div') {
          compare(elem, '
<test></test>
');
        } else if (type === 'slot') {
          compare(elem, '<slot><test></test></slot>');
        }
      });

      it('should get a proper value from a node with one text child', () => {
        elem.innerHTML = 'text';
        if (type === 'host' || type === 'div') {
          compare(elem, '
text
');
        } else if (type === 'slot') {
          compare(elem, '<slot>text</slot>');
        }
      });

      it('should get a proper value from a node with one comment child', () => {
        elem.innerHTML = '';
        if (type === 'host' || type === 'div') {
          compare(elem, '

');
        } else if (type === 'slot') {
          compare(elem, '<slot></slot>');
        }
      });

      it('should get a proper value from a node with two or more children', () => {
        elem.innerHTML = '<test></test><test2>text</test2>';
        if (type === 'host' || type === 'div') {
          compare(elem, '
<test></test><test2>text</test2>
');
        } else if (type === 'slot') {
          compare(elem, '<slot><test></test><test2>text</test2></slot>');
        }
      });

      it('should set a proper value', () => {
        elem.innerHTML = '<div1><div2></div2><div3></div3></div1>';
        elem.childNodes[0].childNodes[0].outerHTML = '<div4></div4>';
        expect(elem.innerHTML).to.equal('<div1><div4></div4><div3></div3></div1>');

        elem.innerHTML = '<div1><div2></div2><div3></div3></div1>';
        elem.childNodes[0].outerHTML = '<div4></div4>';
        expect(elem.innerHTML).to.equal('<div4></div4>');
      });
    });
  }

  runTests('div');
  runTests('slot');
  runTests('host');
});
<commit_msg>chore: Fix linting errors.<commit_after>/* eslint-env jasmine, mocha */

describe('dom: outerHTML', () => {
  function compare (src, dst) {
    expect(src.outerHTML).to.equal(dst);
  }

  function runTests (type) {
    describe(`${type}: `, () => {
      let host;
      let root;
      let slot;
      let div;
      let elem;

      beforeEach(() => {
        host = document.createElement('div');
        root = host.attachShadow({ mode: 'open' });
        slot = document.createElement('slot');

        root.appendChild(slot);

        div = document.createElement('div');

        switch (type) {
          case 'div':
            elem = div;
            break;
          case 'slot':
            elem = slot;
            break;
          default:
            elem = host;
        }
      });

      it('should get a proper value from a node with one element child', () => {
        elem.innerHTML = '<test></test>';
        if (type === 'host' || type === 'div') {
          compare(elem, '
<test></test>
');
        } else if (type === 'slot') {
          compare(elem, '<slot><test></test></slot>');
        }
      });

      it('should get a proper value from a node with one text child', () => {
        elem.innerHTML = 'text';
        if (type === 'host' || type === 'div') {
          compare(elem, '
text
');
        } else if (type === 'slot') {
          compare(elem, '<slot>text</slot>');
        }
      });

      it('should get a proper value from a node with one comment child', () => {
        elem.innerHTML = '';
        if (type === 'host' || type === 'div') {
          compare(elem, '

');
        } else if (type === 'slot') {
          compare(elem, '<slot></slot>');
        }
      });

      it('should get a proper value from a node with two or more children', () => {
        elem.innerHTML = '<test></test><test2>text</test2>';
        if (type === 'host' || type === 'div') {
          compare(elem, '
<test></test><test2>text</test2>
');
        } else if (type === 'slot') {
          compare(elem, '<slot><test></test><test2>text</test2></slot>');
        }
      });

      it('should set a proper value', () => {
        elem.innerHTML = '<div1><div2></div2><div3></div3></div1>';
        elem.childNodes[0].childNodes[0].outerHTML = '<div4></div4>';
        expect(elem.innerHTML).to.equal('<div1><div4></div4><div3></div3></div1>');

        elem.innerHTML = '<div1><div2></div2><div3></div3></div1>';
        elem.childNodes[0].outerHTML = '<div4></div4>';
        expect(elem.innerHTML).to.equal('<div4></div4>');
      });
    });
  }

  runTests('div');
  runTests('slot');
  runTests('host');
});
<|endoftext|>


<commit_before>const ol = require('openlayers');
const ContextMenu = require('../../dist/ol-contextmenu');
const { DEFAULT_OPTIONS, DEFAULT_ITEMS } = require('../../konstants');
const { toJSON, countItems } = require('./helpers/functions');
const {
  options,
  items,
  items2,
  dataMarker,
  dataCenter
} = require('./helpers/data');

describe('Instance of', () => {
  const menu = new ContextMenu();

  test('is a constructor', () => {
    expect(menu instanceof ContextMenu).toBeTruthy();
  });

  test('is ol.control.Control', () => {
    expect(menu instanceof ol.control.Control).toBeTruthy();
  });
});

describe('Instance options', () => {
  const menu = new ContextMenu();
  const menuWithOptions = new ContextMenu(options);

  test('default options', () => {
    expect(menu.options).toEqual(DEFAULT_OPTIONS);
  });

  test('merge options', () => {
    expect(menuWithOptions.options).toMatchObject(options);
  });
});

describe('Instance methods', () => {
  const menu = new ContextMenu();

  test('getDefaultItems()', () => {
    expect(toJSON(menu.getDefaultItems())).toEqual(toJSON(DEFAULT_ITEMS));
  });

  test('push()', () => {
    menu.clear();
    menu.push(items2[0]);
    expect(countItems(menu.Internal.items)).toBe(1);
  });

  test('pop()', () => {
    menu.clear();
    menu.extend(items);
    menu.pop();
    expect(countItems(menu.Internal.items)).toBe(items.length - 1);

    const keys = Object.keys(menu.Internal.items);
    const last = menu.Internal.items[keys[keys.length - 1]];
    expect(last.data).toBe(dataCenter);
  });

  test('shift()', () => {
    menu.clear();
    menu.extend(items);
    menu.shift();
    expect(countItems(menu.Internal.items)).toBe(items.length - 1);

    const keys = Object.keys(menu.Internal.items);
    const first = menu.Internal.items[keys[0]];
    expect(first.data).toBe(dataCenter);
  });

  test('extend()', () => {
    menu.clear();
    menu.extend(items);
    expect(countItems(menu.Internal.items)).toBe(items.length);

    menu.extend(items2);
    expect(countItems(menu.Internal.items)).toBe(items.length + items2.length);
  });

  test('clear()', () => {
    menu.extend(items);
    menu.clear();
    expect(countItems(menu.Internal.items)).toBe(0);
  });

});

describe('Throw errors', () => {
  test('wrong options type', () => {
    expect(() => { new ContextMenu('foo') }).toThrowError();
  });
});
<commit_msg>Make Travis happy<commit_after>const ol = require('openlayers');
const ContextMenu = require('../../dist/ol-contextmenu');
const { DEFAULT_OPTIONS, DEFAULT_ITEMS } = require('../../konstants');
const { toJSON, countItems } = require('./helpers/functions');
const {
  options,
  items,
  items2,
  dataCenter
} = require('./helpers/data');

describe('Instance of', () => {
  const menu = new ContextMenu();

  test('is a constructor', () => {
    expect(menu instanceof ContextMenu).toBeTruthy();
  });

  test('is ol.control.Control', () => {
    expect(menu instanceof ol.control.Control).toBeTruthy();
  });
});

describe('Instance options', () => {
  const menu = new ContextMenu();
  const menuWithOptions = new ContextMenu(options);

  test('default options', () => {
    expect(menu.options).toEqual(DEFAULT_OPTIONS);
  });

  test('merge options', () => {
    expect(menuWithOptions.options).toMatchObject(options);
  });
});

describe('Instance methods', () => {
  const menu = new ContextMenu();

  test('getDefaultItems()', () => {
    expect(toJSON(menu.getDefaultItems())).toEqual(toJSON(DEFAULT_ITEMS));
  });

  test('push()', () => {
    menu.clear();
    menu.push(items2[0]);
    expect(countItems(menu.Internal.items)).toBe(1);
  });

  test('pop()', () => {
    menu.clear();
    menu.extend(items);
    menu.pop();
    expect(countItems(menu.Internal.items)).toBe(items.length - 1);

    const keys = Object.keys(menu.Internal.items);
    const last = menu.Internal.items[keys[keys.length - 1]];
    expect(last.data).toBe(dataCenter);
  });

  test('shift()', () => {
    menu.clear();
    menu.extend(items);
    menu.shift();
    expect(countItems(menu.Internal.items)).toBe(items.length - 1);

    const keys = Object.keys(menu.Internal.items);
    const first = menu.Internal.items[keys[0]];
    expect(first.data).toBe(dataCenter);
  });

  test('extend()', () => {
    menu.clear();
    menu.extend(items);
    expect(countItems(menu.Internal.items)).toBe(items.length);

    menu.extend(items2);
    expect(countItems(menu.Internal.items)).toBe(items.length + items2.length);
  });

  test('clear()', () => {
    menu.extend(items);
    menu.clear();
    expect(countItems(menu.Internal.items)).toBe(0);
  });

});

describe('Throw errors', () => {
  test('wrong options type', () => {
    expect(() => { new ContextMenu('foo') }).toThrowError();
  });
});
<|endoftext|>


<commit_before>describe('svgStar', function () {
  var $compile,
      $rootScope;

  beforeEach(module('astrifex.svg-star'));

  beforeEach(inject(function (_$compile_, _$rootScope_) {
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  it('should work as an element', function () {
    var elt = angular.element('<svg-star></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-10 -10 20 20');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(11);
  });

  it('should do something random with randomness set', function () {
    var elt = angular.element('<svg-star randomness="0.5"></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-10 -10 20 20');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(11);
  });
});
<commit_msg>Add more thorough tests<commit_after>describe('svgStar', function () {
  var $compile,
      $rootScope;

  beforeEach(module('astrifex.svg-star'));

  beforeEach(inject(function (_$compile_, _$rootScope_) {
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  it('should work as an element', function () {
    var elt = angular.element('<svg-star></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-10 -10 20 20');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(11);
  });

  it('should have the right number of segments for its corners', function () {
    var elt = angular.element('<svg-star corners="10"></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-10 -10 20 20');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(21);
  });

  it('should change the size when size is given', function () {
    var elt = angular.element('<svg-star size="100"></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-50 -50 100 100');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(11);
  });

  // TODO: This should actually test that something random is happening;
  // perhaps we need to mock out seedrandom or something
  it('should do something random with randomness set', function () {
    var elt = angular.element('<svg-star randomness="0.5"></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-10 -10 20 20');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(11);
  });

  // TODO: This should actually test that the large positive spoke ratio has
  // the desired effect
  it('should work with a large positive spoke-ratio', function () {
    var elt = angular.element('<svg-star spoke-ratio="10"></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-10 -10 20 20');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(11);
  });

  // TODO: This should actually test that the large negative spoke ratio has
  // the desired effect
  it('should work with a large negative spoke-ratio', function () {
    var elt = angular.element('<svg-star spoke-ratio="-10"></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-10 -10 20 20');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(11);
  });

  // TODO: This should actually test that skew the desired effect
  it('should work with a skew', function () {
    var elt = angular.element('<svg-star skew="0.5"></svg-star>');
    $compile(elt)($rootScope);
    $rootScope.$digest();

    var svg = elt.find('svg');
    expect(svg.length).toBe(1);
    expect(svg.eq(0).attr('viewBox')).toBe('-10 -10 20 20');

    var star = svg.find('path');
    expect(star.length).toBe(1);

    var path = star.eq(0).prop('pathSegList');
    expect(path).not.toBeNull();
    expect(path.numberOfItems).toBe(11);
  });
});
<|endoftext|>


<commit_before>import $path from 'path'

export class Router {
	_scopedAction = null
	_scopedPrefix = ''

	app = null
	bindings = { }
	patterns = { }

	constructor(app) {
		this.app = app
	}

	group(action, callback) {
		this._scopedAction = Object.assign({ }, action)

		if(this._scopedAction.prefix) {
			this._scopedPrefix = this._normalizePathComponent(this._scopedAction.prefix)
			delete this._scopedAction.prefix
		} else {
			this._scopedPrefix = ''
		}

		callback(this, action.controller)

		this._scopedAction = null
		this._scopedPrefix = ''
	}

	all(path, action) {
		console.log('Don’t use `all` routes. Offender: %s', path)
		return this.app.all(this._scopedPrefix + path, this._makeAction(action))
	}

	get(path, action, context) {
		return this._add('get', path, action, context)
	}

	post(path, action, context) {
		return this._add('post', path, action, context)
	}

	put(path, action, context) {
		return this._add('put', path, action, context)
	}

	patch(path, action, context) {
		return this._add('patch', path, action, context)
	}

	delete(path, action, context) {
		return this._add('delete', path, action, context)
	}

	_add(method, path, action, context) {
		const handler = this._makeAction(action)

		// WARNING: Prone to failure if ExpressJS changes this logic
		this.app.lazyrouter()

		const handlers = [ handler ]

		if(typeof action.use !== 'undefined') {
			if(Array.isArray(action.use)) {
				action.use = {
					before: action.use
				}
			}

			if(typeof action.use === 'object') {
				if(Array.isArray(action.use.before)) {
					handlers.unshift(...action.use.before)
				} else if(Array.isArray(action.use.before)) {
					handlers.push(...action.use.after)
				}
			}
		}

		path = this._normalizePathComponent(path)
		const compiledPath = $path.join('/', this._scopedPrefix, path).replace(/:([a-z0-0_\-\.]+)/g, (param, name) => {
			const pattern = this.patterns[name]

			if(pattern.isNil) {
				return param
			} else {
				return param + '(' + pattern + ')'
			}
		})

		let route = this.app._router.route(compiledPath)
		route = route[method](...handlers)
		route.context = context || {}

		return route
	}

	_makeAction(action) {
		if(typeof action === 'function') {
			return action
		}

		if(typeof action === 'string') {
			action = { method: action }
		}

		action = Object.assign({ }, this._scopedAction, action)
		const method = action.controller[action.method]
		const controller = action.controller

		return (...args) => {
			const result = method.apply(controller, args)

			if(typeof result === 'object' && typeof result.catch === 'function') {
				return result.catch(args[2])
			} else {
				return result
			}
		}
	}

	_normalizePathComponent(component) {
		return $path.normalize(component.trim()).replace(/^\//, '')
	}

	bind(name, resolver, context) {
		this.bindings[name] = { resolver }

		if(!context.isNil) {
			this.bindings[name].context = context
		}

		this.app.param(name, (req, res, next, value) => {
			resolver(value, newValue => {
				req.params[name] = newValue
				next()
			}, err => {
				next(err)
			}, req, res)
		})
	}

	pattern(name, pattern) {
		this.patterns[name] = pattern
	}

}
<commit_msg>Route groups are now nestable<commit_after>import $path from 'path'

export class Router {
	app = null
	bindings = { }
	patterns = { }

	_scopedActionStack = [ { } ]
	_scopedPrefixStack = [ '/' ]

	get _scopedAction() {
		return this._scopedActionStack[this._scopedActionStack.length - 1]
	}

	get _scopedPrefix() {
		return this._scopedPrefixStack[this._scopedPrefixStack.length - 1]
	}

	constructor(app) {
		this.app = app
	}

	group(action, callback) {
		const parentAction = this._scopedAction
		const parentPrefix = this._scopedPrefix

		const scopedAction = Object.assign({ }, parentAction, action)
		let scopedPrefix = scopedAction.prefix
		delete scopedAction.prefix
		this._scopedActionStack.push(scopedAction)

		if(!scopedPrefix.isNil && scopedPrefix.length > 0) {
			if(!parentPrefix.isNil && parentPrefix.length > 0) {
				scopedPrefix = $path.join(parentPrefix, scopedPrefix)
			}

			this._scopedPrefixStack.push(this._normalizePathComponent(scopedPrefix))
		} else {
			this._scopedPrefixStack.push(parentPrefix)
		}

		callback(this, action.controller)

		this._scopedActionStack.pop()
		this._scopedPrefixStack.pop()
	}

	all(path, action) {
		console.log('Don’t use `all` routes. Offender: %s', path)
		return this.app.all(this._scopedPrefix + path, this._makeAction(action))
	}

	get(path, action, context) {
		return this._add('get', path, action, context)
	}

	post(path, action, context) {
		return this._add('post', path, action, context)
	}

	put(path, action, context) {
		return this._add('put', path, action, context)
	}

	patch(path, action, context) {
		return this._add('patch', path, action, context)
	}

	delete(path, action, context) {
		return this._add('delete', path, action, context)
	}

	_add(method, path, action, context) {
		const handler = this._makeAction(action)

		// WARNING: Prone to failure if ExpressJS changes this logic
		this.app.lazyrouter()

		const handlers = [ handler ]

		if(typeof action.use !== 'undefined') {
			if(Array.isArray(action.use)) {
				action.use = {
					before: action.use
				}
			}

			if(typeof action.use === 'object') {
				if(Array.isArray(action.use.before)) {
					handlers.unshift(...action.use.before)
				} else if(Array.isArray(action.use.before)) {
					handlers.push(...action.use.after)
				}
			}
		}

		path = this._normalizePathComponent(path)
		const compiledPath = $path.join('/', this._scopedPrefix, path).replace(/:([a-z0-0_\-\.]+)/g, (param, name) => {
			const pattern = this.patterns[name]

			if(pattern.isNil) {
				return param
			} else {
				return param + '(' + pattern + ')'
			}
		})

		let route = this.app._router.route(compiledPath)
		route = route[method](...handlers)
		route.context = context || {}

		return route
	}

	_makeAction(action) {
		if(typeof action === 'function') {
			return action
		}

		if(typeof action === 'string') {
			action = { method: action }
		}

		action = Object.assign({ }, this._scopedAction, action)
		const method = action.controller[action.method]
		const controller = action.controller

		return (...args) => {
			const result = method.apply(controller, args)

			if(typeof result === 'object' && typeof result.catch === 'function') {
				return result.catch(args[2])
			} else {
				return result
			}
		}
	}

	_normalizePathComponent(component) {
		return $path.normalize(component.trim()).replace(/^\//, '')
	}

	bind(name, resolver, context) {
		this.bindings[name] = { resolver }

		if(!context.isNil) {
			this.bindings[name].context = context
		}

		this.app.param(name, (req, res, next, value) => {
			resolver(value, newValue => {
				req.params[name] = newValue
				next()
			}, err => {
				next(err)
			}, req, res)
		})
	}

	pattern(name, pattern) {
		this.patterns[name] = pattern
	}

}
<|endoftext|>


<commit_before>angular.module("myApp.invitations", ['ngRoute'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/invites', {
            templateUrl: 'Webpages/invitations/invitations.html',
            controller: 'invitationsController'
        }).when('/create_invite', {
            templateUrl: 'Webpages/invitations/send_invitation.html',
            controller: 'sendInvitationsController'
        })
    }])
    .controller("invitationsController", function($scope, $http) {
        $http.get('http://localhost:5000/invites').then(function(response) {
            if(response.data.response === "error"){
                console.log(response);
            } else {
                $scope.invites = response.data;
            }
        });

        $scope.accept_invite = function(invite_id, group_id, user_id) {
            data = {
                'invite_id': invite_id,
                'group_id': group_id,
                'user_id': user_id
            };
            $http.post('http://localhost:5000/accept_invite', data).then(function(response) {
                if(response.data.response !== "success"){
                    console.log(response.data.response);
                }
            })
        }
    })
    .controller("sendInvitationsController", function($scope, $http) {
        $scope.send_invite = function(invitation) {
            data = {
                'group_name': invitation.group_name,
                'user_name': invitation.user_name
            };
            $http.post('http://localhost:5000/invites', data).then(function(response) {
                if(response.data.response !== "success"){
                    console.log(response.data.response);
                }
            });
        }
    });<commit_msg>invites fixed<commit_after>angular.module("myApp.invitations", ['ngRoute'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/invites', {
            templateUrl: 'Webpages/invitations/invitations.html',
            controller: 'invitationsController'
        }).when('/create_invite', {
            templateUrl: 'Webpages/invitations/send_invitation.html',
            controller: 'sendInvitationsController'
        })
    }])
    .controller("invitationsController", function($scope, $http) {
        $http.get('http://localhost:5000/invites').then(function(response) {
            if(response.data.response === "error"){
                console.log(response);
            } else {
                $scope.invites = response.data;
            }
        });

        $scope.accept_invite = function(invite_id, group_id, user_id) {
            data = {
                'invite_id': invite_id,
                'group_id': group_id,
                'user_id': user_id
            };
            $http.post('http://localhost:5000/accept_invite', data).then(function(response) {
                if(response.data.response === "error"){
                    console.log(response.data.response);
                }
            })
        }
    })
    .controller("sendInvitationsController", function($scope, $http) {
        $scope.send_invite = function(invitation) {
            data = {
                'group_name': invitation.group_name,
                'user_name': invitation.user_name
            };
            $http.post('http://localhost:5000/invites', data).then(function(response) {
                if(response.data.response === "error"){
                    console.log(response.data.response);
                }
            });
        }
    });<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

define([
  'app',
  'api',
  'addons/documents/changes/actiontypes',
  'addons/documents/changes/stores',
  'addons/documents/helpers'
],
function (app, FauxtonAPI, ActionTypes, Stores, Helpers) {

  var changesStore = Stores.changesStore;
  var pollingTimeout = 60000;
  var currentRequest;

  return {
    toggleTabVisibility: function () {
      FauxtonAPI.dispatch({
        type: ActionTypes.TOGGLE_CHANGES_TAB_VISIBILITY
      });
    },

    addFilter: function (filter) {
      FauxtonAPI.dispatch({
        type: ActionTypes.ADD_CHANGES_FILTER_ITEM,
        filter: filter
      });
    },

    removeFilter: function (filter) {
      FauxtonAPI.dispatch({
        type: ActionTypes.REMOVE_CHANGES_FILTER_ITEM,
        filter: filter
      });
    },

    initChanges: function (options) {
      FauxtonAPI.dispatch({
        type: ActionTypes.INIT_CHANGES,
        options: options
      });
      currentRequest = null;
      this.getLatestChanges();
    },

    getLatestChanges: function () {
      var params = {
        limit: 100
      };

      // after the first request for the changes list has been made, switch to longpoll
      if (currentRequest) {
        params.since = changesStore.getLastSeqNum();
        params.timeout = pollingTimeout;
        params.feed = 'longpoll';
      }

      var query = $.param(params);
      var db = app.utils.safeURLName(changesStore.getDatabaseName());

      var endpoint = FauxtonAPI.urls('changes', 'apiurl', db, '');
      currentRequest = $.get(endpoint);
      currentRequest.then(_.bind(this.updateChanges, this));
    },

    updateChanges: function (resp) {
      var json = JSON.parse(resp);

      // only bother updating the list of changes if the seq num has changed
      var latestSeqNum = Helpers.getSeqNum(json.last_seq);
      if (latestSeqNum !== changesStore.getLastSeqNum()) {
        FauxtonAPI.dispatch({
          type: ActionTypes.UPDATE_CHANGES,
          changes: json.results,
          seqNum: latestSeqNum
        });
      }

      if (changesStore.pollingEnabled()) {
        this.getLatestChanges();
      }
    },

    togglePolling: function () {
      FauxtonAPI.dispatch({ type: ActionTypes.TOGGLE_CHANGES_POLLING });

      // the user just enabled polling. Start 'er up
      if (changesStore.pollingEnabled()) {
        this.getLatestChanges();
      } else {
        currentRequest.abort();
      }
    }
  };

});
<commit_msg>fix changes url<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

define([
  'app',
  'api',
  'addons/documents/changes/actiontypes',
  'addons/documents/changes/stores',
  'addons/documents/helpers'
],
function (app, FauxtonAPI, ActionTypes, Stores, Helpers) {

  var changesStore = Stores.changesStore;
  var pollingTimeout = 60000;
  var currentRequest;

  return {
    toggleTabVisibility: function () {
      FauxtonAPI.dispatch({
        type: ActionTypes.TOGGLE_CHANGES_TAB_VISIBILITY
      });
    },

    addFilter: function (filter) {
      FauxtonAPI.dispatch({
        type: ActionTypes.ADD_CHANGES_FILTER_ITEM,
        filter: filter
      });
    },

    removeFilter: function (filter) {
      FauxtonAPI.dispatch({
        type: ActionTypes.REMOVE_CHANGES_FILTER_ITEM,
        filter: filter
      });
    },

    initChanges: function (options) {
      FauxtonAPI.dispatch({
        type: ActionTypes.INIT_CHANGES,
        options: options
      });
      currentRequest = null;
      this.getLatestChanges();
    },

    getLatestChanges: function () {
      var params = {
        limit: 100
      };

      // after the first request for the changes list has been made, switch to longpoll
      if (currentRequest) {
        params.since = changesStore.getLastSeqNum();
        params.timeout = pollingTimeout;
        params.feed = 'longpoll';
      }

      var query = $.param(params);
      var db = app.utils.safeURLName(changesStore.getDatabaseName());

      var endpoint = FauxtonAPI.urls('changes', 'server', db, '');
      currentRequest = $.get(endpoint);
      currentRequest.then(_.bind(this.updateChanges, this));
    },

    updateChanges: function (resp) {
      var json = JSON.parse(resp);

      // only bother updating the list of changes if the seq num has changed
      var latestSeqNum = Helpers.getSeqNum(json.last_seq);
      if (latestSeqNum !== changesStore.getLastSeqNum()) {
        FauxtonAPI.dispatch({
          type: ActionTypes.UPDATE_CHANGES,
          changes: json.results,
          seqNum: latestSeqNum
        });
      }

      if (changesStore.pollingEnabled()) {
        this.getLatestChanges();
      }
    },

    togglePolling: function () {
      FauxtonAPI.dispatch({ type: ActionTypes.TOGGLE_CHANGES_POLLING });

      // the user just enabled polling. Start 'er up
      if (changesStore.pollingEnabled()) {
        this.getLatestChanges();
      } else {
        currentRequest.abort();
      }
    }
  };

});
<|endoftext|>


<commit_before>GlobalMultiSelect = {};

GlobalMultiSelect.fetch = function(){
  var query = $('form').serialize();
  window.location=location.pathname+'?'+query;
};

GlobalMultiSelect.search = function(event){
  event.stopPropagation()
  if(GlobalMultiSelect.validate_search()){
    GlobalMultiSelect.fetch()
  }else{
    GlobalMultiSelect.show_search_attribute_missing_error()
    return false
  }
};

GlobalMultiSelect.search_reset = function(event){
  event.stopPropagation();
  $('#search_field_index input#search').val('')
  $('#search_field_index input:radio').prop('checked',false)
  GlobalMultiSelect.manage_search_button_visibility();
  return false;
};

GlobalMultiSelect.search_revert_to_current = function(){
  var index = filter_params.search_field_index
  $("#search_field_index input:radio").prop('checked',false)
  $("#search_field_index ._"+index+" input:radio").prop('checked',true)
  var search = filter_params.search
  $('#search_field_index input#search').val(search)
};

GlobalMultiSelect.validate_search = function(){
  return ($("#search_field_index input:radio:checked").length == 1)
};

GlobalMultiSelect.show_search_attribute_missing_error = function(){
  $('#search-dropdown-heading').replaceWith("
Please select a field to search in.
")
};

GlobalMultiSelect.remove_error = function(){
  $('#search-error-message').remove();
};

GlobalMultiSelect.fetch_all = function(){
  window.location=location.pathname;
};

GlobalMultiSelect.filter_select = function(event){
  //$('.text-input-error').remove()
  var $target = $(event.target);
  var $li = $target.closest('li');
  var close_on_select = $li.parent().data('close-on-select');
  var fetch_immediate = close_on_select;
  if(!close_on_select){event.stopPropagation();};

  if(fetch_immediate){
    GlobalMultiSelect.fetch(); // trigger ajax request on any change
  }else{
    GlobalMultiSelect.selection_callback($li);
  }
};

GlobalMultiSelect.selection_callback = function ($li) {
  var $text_input = $li.closest('ul.dropdown-menu').find('.input-group input.form-control');
  var text = $li.text().trim();
  $text_input.attr('placeholder', text + ' (all/part)');
  $text_input.focus();
};

GlobalMultiSelect.manage_search_button_visibility = function(){
  var $input = $('#search_field_index input#search');
  var $search_button = $input.closest('.input-group').find('.input-group-append')
  if($input.val().length == 0)
    { $search_button.hide()}else{ $search_button.show()};
};

GlobalMultiSelect.add_error = function ($field, text) {
  $field.after("
" + text + "
");
};

$(function(){
  $(document).on('click', '#reset_message', GlobalMultiSelect.fetch_all );
  $(document).on('click', '.globalselect-container>ul>li>label', GlobalMultiSelect.filter_select );
  $(document).on('keyup', '#filter_controls input#search', GlobalMultiSelect.manage_search_button_visibility );
  $(document).on('click', '#filter_controls .dropdown-menu .input-group#search #search_button', GlobalMultiSelect.search );
  $(document).on('click', '#filter_controls .dropdown-menu .input-group#search #search_reset_button', GlobalMultiSelect.search_reset );
  $(document).on('change', '#filter_controls .dropdown-menu input:radio', GlobalMultiSelect.remove_error );
  $('#search_field_index').on('show.bs.dropdown',GlobalMultiSelect.manage_search_button_visibility);
  $('#search_field_index').on('hide.bs.dropdown',GlobalMultiSelect.search_revert_to_current);
});
<commit_msg>adds another selector to on click handler for dog search button<commit_after>GlobalMultiSelect = {};

GlobalMultiSelect.fetch = function(){
  var query = $('form').serialize();
  window.location=location.pathname+'?'+query;
};

GlobalMultiSelect.search = function(event){
  event.stopPropagation()
  if(GlobalMultiSelect.validate_search()){
    GlobalMultiSelect.fetch()
  }else{
    GlobalMultiSelect.show_search_attribute_missing_error()
    return false
  }
};

GlobalMultiSelect.search_reset = function(event){
  event.stopPropagation();
  $('#search_field_index input#search').val('')
  $('#search_field_index input:radio').prop('checked',false)
  GlobalMultiSelect.manage_search_button_visibility();
  return false;
};

GlobalMultiSelect.search_revert_to_current = function(){
  var index = filter_params.search_field_index
  $("#search_field_index input:radio").prop('checked',false)
  $("#search_field_index ._"+index+" input:radio").prop('checked',true)
  var search = filter_params.search
  $('#search_field_index input#search').val(search)
};

GlobalMultiSelect.validate_search = function(){
  return ($("#search_field_index input:radio:checked").length == 1)
};

GlobalMultiSelect.show_search_attribute_missing_error = function(){
  $('#search-dropdown-heading').replaceWith("
Please select a field to search in.
")
};

GlobalMultiSelect.remove_error = function(){
  $('#search-error-message').remove();
};

GlobalMultiSelect.fetch_all = function(){
  window.location=location.pathname;
};

GlobalMultiSelect.filter_select = function(event){
  //$('.text-input-error').remove()
  var $target = $(event.target);
  var $li = $target.closest('li');
  var close_on_select = $li.parent().data('close-on-select');
  var fetch_immediate = close_on_select;
  if(!close_on_select){event.stopPropagation();};

  if(fetch_immediate){
    GlobalMultiSelect.fetch(); // trigger ajax request on any change
  }else{
    GlobalMultiSelect.selection_callback($li);
  }
};

GlobalMultiSelect.selection_callback = function ($li) {
  var $text_input = $li.closest('ul.dropdown-menu').find('.input-group input.form-control');
  var text = $li.text().trim();
  $text_input.attr('placeholder', text + ' (all/part)');
  $text_input.focus();
};

GlobalMultiSelect.manage_search_button_visibility = function(){
  var $input = $('#search_field_index input#search');
  var $search_button = $input.closest('.input-group').find('.input-group-append')
  if($input.val().length == 0)
    { $search_button.hide()}else{ $search_button.show()};
};

GlobalMultiSelect.add_error = function ($field, text) {
  $field.after("
" + text + "
");
};

$(function(){
  $(document).on('click', '#reset_message', GlobalMultiSelect.fetch_all );
  $(document).on('click', '.globalselect-container>ul>li>label', GlobalMultiSelect.filter_select );
  $(document).on('keyup', '#filter_controls input#search', GlobalMultiSelect.manage_search_button_visibility );
  $(document).on('click', '#filter_controls .dropdown-menu .input-group#search #search_button', '#dog-search input#search_button', GlobalMultiSelect.search );
  $(document).on('click', '#filter_controls .dropdown-menu .input-group#search #search_reset_button', GlobalMultiSelect.search_reset );
  $(document).on('change', '#filter_controls .dropdown-menu input:radio', GlobalMultiSelect.remove_error );
  $('#search_field_index').on('show.bs.dropdown',GlobalMultiSelect.manage_search_button_visibility);
  $('#search_field_index').on('hide.bs.dropdown',GlobalMultiSelect.search_revert_to_current);
});
<|endoftext|>


<commit_before>$(document).on('turbolinks:load', function() {
  addEventListeners();
});

function addEventListeners(){
  createActionListener();
  gameActionListener();
  addSubscriptionListener();
}

function addSubscriptionListener() {
  $('main').on('submit', '.subscription-form', function(event) {
    event.preventDefault();
    var name = $(event.target).find('input[type=text]').val()
    App['game_' + name] = App.cable.subscriptions.create({channel: 'GamesChannel', name: name}, {
      connected: function() {
        console.log('Player connected')
      },

      disconnected: function() {
        console.log('Player disconnected')
      },

      received: function(data) {
        switch(data['action']) {
          case 'updateGame':
            renderGamePage(data.gameState);
            break;
          case 'setTimer':
            createTimer(data.gameName);
            break;
        }
      },

      setGameName: function(gameName) {
        this.gameName = gameName
      }
    })
    App['game_' + name].setGameName(name)
  })
}

function createActionListener(){
  $('main').on('submit', '.action-form', function(event) {
    event.preventDefault();
    var $form = $(this);
    $.ajax( {
      url : $form.attr('action'),
      method : "POST",
      data : $form.serialize()
    });
  })
}

function gameActionListener(){
  $('main').on('submit', '.game-form', function(event) {
    event.preventDefault();
    var timeLeft = $('#timer')[0].innerText
    var $form = $(this);
    $.ajax( {
      url : $form.attr('action'),
      method : "POST",
      data : {timeLeft: timeLeft}
    });
  })
}

function setTimer(gameName){
  $('#timer p').text(60);
  jsTimer(gameName);
}
<commit_msg>remove old JS timer code<commit_after>$(document).on('turbolinks:load', function() {
  addEventListeners();
});

function addEventListeners(){
  createActionListener();
  gameActionListener();
  addSubscriptionListener();
}

function addSubscriptionListener() {
  $('main').on('submit', '.subscription-form', function(event) {
    event.preventDefault();
    var name = $(event.target).find('input[type=text]').val()
    App['game_' + name] = App.cable.subscriptions.create({channel: 'GamesChannel', name: name}, {
      connected: function() {
        console.log('Player connected')
      },

      disconnected: function() {
        console.log('Player disconnected')
      },

      received: function(data) {
        switch(data['action']) {
          case 'updateGame':
            renderGamePage(data.gameState);
            break;
          case 'setTimer':
            createTimer(data.gameName);
            break;
        }
      },

      setGameName: function(gameName) {
        this.gameName = gameName
      }
    })
    App['game_' + name].setGameName(name)
  })
}

function createActionListener(){
  $('main').on('submit', '.action-form', function(event) {
    event.preventDefault();
    var $form = $(this);
    $.ajax( {
      url : $form.attr('action'),
      method : "POST",
      data : $form.serialize()
    });
  })
}

function gameActionListener(){
  $('main').on('submit', '.game-form', function(event) {
    event.preventDefault();
    var timeLeft = $('#timer')[0].innerText
    var $form = $(this);
    $.ajax( {
      url : $form.attr('action'),
      method : "POST",
      data : {timeLeft: timeLeft}
    });
  })
}
<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require foundation/foundation
//= require foundation
//= require jquery.loadingdotdotdot
//= require_tree .<commit_msg>Revert "Revert "[#96970256] Take out old references to foundation""<commit_after>//= require jquery
//= require jquery_ujs
//= require jquery.loadingdotdotdot
//= require_tree .<|endoftext|>