<commit_before>(function (env) {
    "use strict";

    var formatNxt = function(amount) {
        return (amount / 100000000)+" NXT"
    };

    env.ddg_spice_nxt_account = function(api_result) {

        if (!api_result || api_result.status == 'error') {
            return Spice.failed('nxt_account');
        }

        Spice.add({
            id: "nxt_account",
            name: "Nxt Blockchain",
            data: {
                record_data: {
                    "Current Balance": formatNxt(api_result.balanceNQT),
                    "Forged Balance": formatNxt(api_result.forgedBalanceNQT),
                    "Assets Owned": api_result.assetBalances ? api_result.assetBalances.length : "0"
                }
            },
            meta: {
                sourceName: "myNXT.info",
                sourceUrl: "http://www.mynxt.info/blockexplorer/details.php?action=ac&ac="+api_result.accountRS
            },
            normalize: function(item) {
                return {
                    image: 'https://api.qrserver.com/v1/create-qr-code/?size=110x110&data='+api_result.accountRS,
                    img_m: 'https://api.qrserver.com/v1/create-qr-code/?size=110x110&data='+api_result.accountRS
                };
            },
            templates: {
                group: 'info',
                options:{
                    moreAt: true,
                    content: 'record',
                    item: 'basic_image_item',
                    rowHighlight: true
                }
            }
        });
    };
}(this));
<commit_msg>fix spice being displayed for invalid accs<commit_after>(function (env) {
    "use strict";

    var formatNxt = function(amount) {
        return (amount / 100000000)+" NXT"
    };

    env.ddg_spice_nxt_account = function(api_result) {

        if (!api_result || api_result.status == 'error' || !api_result.accountRS) {
            return Spice.failed('nxt_account');
        }

        Spice.add({
            id: "nxt_account",
            name: "Nxt Blockchain",
            data: {
                record_data: {
                    "Current Balance": formatNxt(api_result.balanceNQT),
                    "Forged Balance": formatNxt(api_result.forgedBalanceNQT),
                    "Assets Owned": api_result.assetBalances ? api_result.assetBalances.length : "0"
                }
            },
            meta: {
                sourceName: "myNXT.info",
                sourceUrl: "http://www.mynxt.info/blockexplorer/details.php?action=ac&ac="+api_result.accountRS
            },
            normalize: function(item) {
                return {
                    image: 'https://api.qrserver.com/v1/create-qr-code/?size=110x110&data='+api_result.accountRS,
                    img_m: 'https://api.qrserver.com/v1/create-qr-code/?size=110x110&data='+api_result.accountRS
                };
            },
            templates: {
                group: 'info',
                options:{
                    moreAt: true,
                    content: 'record',
                    item: 'basic_image_item',
                    rowHighlight: true
                }
            }
        });
    };
}(this));
<|endoftext|>


<commit_before>function dismiss_notification(notification_id) {
  $.get("/notifications/dismiss/" + notification_id + "/", {},
    function(data, textStatus, xhr) {
      $("#notification-" + notification_id).slideUp(function(){$(this).remove()});
  });
}

jQuery(function($){
  function slugify(string) {
    return string.replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase();
  }

  function ajaxHandler(data) {
    if (data.update) {
      $.each(data.update,function(k,v){
        $(k).html(v);
      });
    }
  }

  function load_recipe_template(project_id) {
    return (function(node) {
      if ($('#available_recipes').val() != "") {
        $("#recipe_template_container").load("/recipes/" + project_id +
          "/recipe_template/" +
          $('#available_recipes').val() + '/',function(){
            $("#id_eggs, #id_extra_paths").lineeditor();
          }
        );
      }
    })
  }

  function queue_button(node_or_function_string,selector) {
    return (function(ev) {
      if ( typeof node_or_function_string == 'string' ) {
        node = $(this)[node_or_function_string](selector);
      } else {
        node = node_or_function_string;
      }
      ev.preventDefault(); ev.stopPropagation();
      $.ajax({
        url: $(this).attr('href'),
        success: show_queuing_response(node),
        error: show_queuing_response(node)
      });
    });
  }

  function show_queuing_response(node) {
    return (function(data_or_xhr, textStatus) {
      var to_append = '';
      switch (textStatus) {
        case null:
        case 'timeout':
        case 'error':
        case 'notmodified':
        case 'parsererror':
          to_append = '' + data_or_xhr.responseText + '';
          break;
        default:
          to_append = '' + data_or_xhr + '';
          break;
      }
      to_append = $(to_append).css('display','none');
      $(to_append).appendTo(node).slideDown().delay(2000).slideUp(function(){$(this).remove()});
    });
  }

  function ajax_update(params) {
    if ( !params ) {
      params = [];
      if ( $('div.project').size() ) {
        params.push( '"#project-list":"projects"' )
      } else {
        params.push( '"#project-list":"home-projects"' )
      }
      params.push( '"#favourite-project-list":"favourite-projects"' );
      params = '{' + params.join(',') + '}'
    }
    $.post('/projects/ajax', {
      update: params
    }, ajaxHandler);
  }

  function update_notifications(data) {
    var $el = $(this);
    var number_to_remove = $el.find('li').size()-10;
    $(data).each(function(_,n){
      if ( n.id && $("#"+n.id).size() == 0 ) {
        var id = parseInt(n.id.replace(/\D*/,''));
        var node_after = added = null;
        $('.tests li').each(function(){
          if ( added ) { return false; }
          if ( parseInt(this.id.replace(/\D*/,'')) > id ) {
            node_after = this;
          } else {
            $(n).css('display','none').insertBefore($(this)).slideDown();
            number_to_remove++;
            added = true;
          }
        })
        if ( node_after && !added ) {
          $(n).css('display','none').insertAfter($(node_after)).slideDown();
          number_to_remove++;
          added = true;
        } else if ( !node_after && !added ) {
          $(n).css('display','none').appendTo($el).slideDown();
          number_to_remove++;
          added = true;
        }
        if ( added ) {
          notification_handler($(n));
        }
      }
    });
    while ( number_to_remove-- > 0 ) {
      $el.find('li:last').remove();
    }
    // Update the testing button on the project detail page
    if ( $('#sidebar .project').size() ) {
      if ( $el.find('li[rel*=TEST]:first').hasClass('success') ) {
        $('#sidebar .project .actions .tests').addClass('success')
      } else {
        $('#sidebar .project .actions .tests').removeClass('success').addClass('error');
      }
    }
    ajax_update();
  }

  function notification_handler(node) {
    if ( node.attr('rel') == 'GITCLONE' && node.hasClass('success') ) {
      confirm("The git clone has completed.  Would you like to refresh the page?") && window.location.reload();
    }
  }

  $('.autosubmit').change(function(){
    $(this).parents('form').first().submit();
  });

  $('.projects li').live('click', function(e){
    if ( e.isPropagationStopped() ) { return; }
    e.preventDefault();
    e.stopPropagation();
    var id = $(this).attr('id');
    id = id.match(/project-(\d+)/)[1];
    var href = "/projects/" + id + "/view/";
    window.location = href;
  });

  $('ul.projects .edit').live('click', function(e){
    e.stopPropagation();
  });

  $('div.projects .favourite').live('click', function(e){
    e.preventDefault();
    e.stopPropagation();
    var href = $(this).attr('href') + '?' + $(this).parents('form').serialize();
    $.post(href, {update: '{"#project-list":"projects"}'}, ajaxHandler);
  });

  $('div.dashboard .projects .favourite').live('click', function(e){
    e.preventDefault();
    e.stopPropagation();
    $.post($(this).attr('href'), {
      update: '{"#project-list":"home-projects","#favourite-project-list":"favourite-projects"}'
    }, ajaxHandler);
  });

  $('.projects .buildout, .projects .tests').live('click',queue_button('closest', 'li'));
  $('.actions .ajax').live('click',queue_button('closest', 'div.project > section'));
  $('.confirm').live('click',function(e){
    e.preventDefault();
    if ( confirm("Are you sure you want to do this?") ) {
      $('<form action="' + $(this).attr('href') + '" method="post"></form>').submit();
    } else {
      e.preventDefault();
    }
  });

  $('div.dashboard ul.tests:first').ekko({url: '/notifications/ajax/'},update_notifications);

  if ( $('#content .project:first').size() ) {
    $('div.project .tests.live:first').ekko({url: '/projects/' + $('#content .project:first').attr('id').replace(/\D*/,'') + '/notifications/'},update_notifications);
  }

  $("#recipe_form").submit(function() {
    if ($("#available_recipes").val() == "") {
      alert("Must select a recipe");
      return false;
    }
    return true;
  });
});

<commit_msg>Updating polling interval to be just a wee bit faster.<commit_after>function dismiss_notification(notification_id) {
  $.get("/notifications/dismiss/" + notification_id + "/", {},
    function(data, textStatus, xhr) {
      $("#notification-" + notification_id).slideUp(function(){$(this).remove()});
  });
}

jQuery(function($){
  function slugify(string) {
    return string.replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase();
  }

  function ajaxHandler(data) {
    if (data.update) {
      $.each(data.update,function(k,v){
        $(k).html(v);
      });
    }
  }

  function load_recipe_template(project_id) {
    return (function(node) {
      if ($('#available_recipes').val() != "") {
        $("#recipe_template_container").load("/recipes/" + project_id +
          "/recipe_template/" +
          $('#available_recipes').val() + '/',function(){
            $("#id_eggs, #id_extra_paths").lineeditor();
          }
        );
      }
    })
  }

  function queue_button(node_or_function_string,selector) {
    return (function(ev) {
      if ( typeof node_or_function_string == 'string' ) {
        node = $(this)[node_or_function_string](selector);
      } else {
        node = node_or_function_string;
      }
      ev.preventDefault(); ev.stopPropagation();
      $.ajax({
        url: $(this).attr('href'),
        success: show_queuing_response(node),
        error: show_queuing_response(node)
      });
    });
  }

  function show_queuing_response(node) {
    return (function(data_or_xhr, textStatus) {
      var to_append = '';
      switch (textStatus) {
        case null:
        case 'timeout':
        case 'error':
        case 'notmodified':
        case 'parsererror':
          to_append = '' + data_or_xhr.responseText + '';
          break;
        default:
          to_append = '' + data_or_xhr + '';
          break;
      }
      to_append = $(to_append).css('display','none');
      $(to_append).appendTo(node).slideDown().delay(2000).slideUp(function(){$(this).remove()});
    });
  }

  function ajax_update(params) {
    if ( !params ) {
      params = [];
      if ( $('div.project').size() ) {
        params.push( '"#project-list":"projects"' )
      } else {
        params.push( '"#project-list":"home-projects"' )
      }
      params.push( '"#favourite-project-list":"favourite-projects"' );
      params = '{' + params.join(',') + '}'
    }
    $.post('/projects/ajax', {
      update: params
    }, ajaxHandler);
  }

  function update_notifications(data) {
    var $el = $(this);
    var number_to_remove = $el.find('li').size()-10;
    $(data).each(function(_,n){
      if ( n.id && $("#"+n.id).size() == 0 ) {
        var id = parseInt(n.id.replace(/\D*/,''));
        var node_after = added = null;
        $('.tests li').each(function(){
          if ( added ) { return false; }
          if ( parseInt(this.id.replace(/\D*/,'')) > id ) {
            node_after = this;
          } else {
            $(n).css('display','none').insertBefore($(this)).slideDown();
            number_to_remove++;
            added = true;
          }
        })
        if ( node_after && !added ) {
          $(n).css('display','none').insertAfter($(node_after)).slideDown();
          number_to_remove++;
          added = true;
        } else if ( !node_after && !added ) {
          $(n).css('display','none').appendTo($el).slideDown();
          number_to_remove++;
          added = true;
        }
        if ( added ) {
          notification_handler($(n));
        }
      }
    });
    while ( number_to_remove-- > 0 ) {
      $el.find('li:last').remove();
    }
    // Update the testing button on the project detail page
    if ( $('#sidebar .project').size() ) {
      if ( $el.find('li[rel*=TEST]:first').hasClass('success') ) {
        $('#sidebar .project .actions .tests').addClass('success')
      } else {
        $('#sidebar .project .actions .tests').removeClass('success').addClass('error');
      }
    }
    ajax_update();
  }

  function notification_handler(node) {
    if ( node.attr('rel') == 'GITCLONE' && node.hasClass('success') ) {
      confirm("The git clone has completed.  Would you like to refresh the page?") && window.location.reload();
    }
  }

  $('.autosubmit').change(function(){
    $(this).parents('form').first().submit();
  });

  $('.projects li').live('click', function(e){
    if ( e.isPropagationStopped() ) { return; }
    e.preventDefault();
    e.stopPropagation();
    var id = $(this).attr('id');
    id = id.match(/project-(\d+)/)[1];
    var href = "/projects/" + id + "/view/";
    window.location = href;
  });

  $('ul.projects .edit').live('click', function(e){
    e.stopPropagation();
  });

  $('div.projects .favourite').live('click', function(e){
    e.preventDefault();
    e.stopPropagation();
    var href = $(this).attr('href') + '?' + $(this).parents('form').serialize();
    $.post(href, {update: '{"#project-list":"projects"}'}, ajaxHandler);
  });

  $('div.dashboard .projects .favourite').live('click', function(e){
    e.preventDefault();
    e.stopPropagation();
    $.post($(this).attr('href'), {
      update: '{"#project-list":"home-projects","#favourite-project-list":"favourite-projects"}'
    }, ajaxHandler);
  });

  $('.projects .buildout, .projects .tests').live('click',queue_button('closest', 'li'));
  $('.actions .ajax').live('click',queue_button('closest', 'div.project > section'));
  $('.confirm').live('click',function(e){
    e.preventDefault();
    if ( confirm("Are you sure you want to do this?") ) {
      $('<form action="' + $(this).attr('href') + '" method="post"></form>').submit();
    } else {
      e.preventDefault();
    }
  });

  $('div.dashboard ul.tests:first').ekko(
    {
      url: '/notifications/ajax/',
      minTimeout: 500,
      maxTimeout: 5000
    },
  update_notifications);

  if ( $('#content .project:first').size() ) {
    $('div.project .tests.live:first').ekko(
      {
        url: '/projects/' + $('#content .project:first').attr('id').replace(/\D*/,'') + '/notifications/',
        minTimeout: 500,
        maxTimeout: 5000
      },update_notifications);
  }

  $("#recipe_form").submit(function() {
    if ($("#available_recipes").val() == "") {
      alert("Must select a recipe");
      return false;
    }
    return true;
  });
});

<|endoftext|>


<commit_before>/**
 * Command Bar Plugin
 */

(function ($) {
  $.fn.CommandBar = function () {

  	var createMenuItem = function(text, icon, link) {
  		var item = '
';
  			item += text;
  			item += '
';

  		return item;
  	}

  	var saveCommands = function($commands, $commandWidth, $commandarea) {

  		var commands = [];
  		$commands.each(function(index) {

	  		var $Item = $(this);
	  		var $rightOffset = ($Item.offset().left + $Item.outerWidth() + $commandWidth + 10) - $commandarea.offset().left; // Added padding of 10

		  	commands.push({ jquery: $Item, rightOffset: $rightOffset});

	  	});

	  	return commands;
  	}

  	var processCommands = function(commands, width) {

  		var overFlowCommands = [];

  		for(var i=0; i < commands.length; i++) {

  			var $Item = commands[i].jquery;
	  		var rightOffset = commands[i].rightOffset;

  			// If the command is outside the right boundaries add to overflow items
	  		if(!$Item.hasClass('ms-CommandBarItem-overflow')) {

		  		if(rightOffset > width) {
		  			overFlowCommands.push($Item);
		  		} else {
		  			// Make sure item is displayed
		  			$Item.removeClass('hideCommand');
		  		}

		  	}

  		}

	  	return overFlowCommands;
  	}

  	var processOverflow = function(overFlowCommands, $oCommand, $menu) {

  		var overflowStrings = '';

  		if(overFlowCommands.length > 0) {

  			$oCommand.addClass("showOverflow");

  			// Empty menu
  			$menu.html('');

  			// Add overflowed commands to ContextualMenu
  			for(i=0; i < overFlowCommands.length; i++) {

  				var $Item = $(overFlowCommands[i]);

  				// Hide Element in CommandBar
  				$Item.addClass('hideCommand');

  				var commandBarItemText = $Item.find('.ms-CommandBarItem-commandText').text();
  				overflowStrings += createMenuItem(commandBarItemText);

  			}

  			$menu.html(overflowStrings);

  		} else {
  			$oCommand.removeClass("showOverflow");
  			console.log("getting removed");
  		}
  	}

    /** Go through each CommandBar we've been given. */
    return this.each(function () {

	    var $CommandBar = $(this);
	    var $CommandMainArea = $CommandBar.find('.ms-CommandBar-mainArea');
	    var $CommandBarItems = $CommandMainArea.find('.ms-CommandBarItem');
	    var $OverflowCommand = $CommandBar.find('.ms-CommandBarItem-overflow');
	    var $OverflowCommandWidth = $CommandBar.find('.ms-CommandBarItem-overflow').outerWidth();
	    var $OverflowMenu = $CommandBar.find('.ms-CommandBar-overflowMenu');
	    var mobileSwitch = false;

	    var overFlowCommands;
	    var allCommands;

	    // Go through process and save commands
	    allCommands = saveCommands($CommandBarItems, $OverflowCommandWidth, $CommandMainArea);

	    // Initiate process commands and add commands to overflow on load
	    overFlowCommands = processCommands(allCommands, $CommandMainArea.innerWidth());
	    processOverflow(overFlowCommands, $OverflowCommand, $OverflowMenu);

	    // Add resize event handler on commandBar
	    $(window).resize(function() {

	    	var overFlowCommands;
	    	overFlowCommands = processCommands(allCommands, $CommandMainArea.innerWidth());
	    	processOverflow(overFlowCommands, $OverflowCommand, $OverflowMenu);

	    	if($(window).width() < 640 && mobileSwitch == false) {

	    		allCommands = saveCommands($CommandBarItems, $OverflowCommandWidth);
	    		mobileSwitch = true;

	    		console.log("Mobile switch");

	    	} else if($(window).width() > 639 && mobileSwitch == true) {

	    		allCommands = saveCommands($CommandBarItems, $OverflowCommandWidth);
	    		mobileSwitch = false;

	    		console.log("Mobile Off");

	    	}

	    });

	    // Hook up contextual menu
	    $OverflowCommand.click(function() {
	    	$OverflowMenu.toggleClass('is-open');
	    })

    });
  };
})(jQuery);
<commit_msg>- Removing white space.<commit_after>/**
 * Command Bar Plugin
 */

(function ($) {
  $.fn.CommandBar = function () {

  	var createMenuItem = function(text, icon, link) {
  		var item = '
';
  			item += text;
  			item += '
';

  		return item;
  	}

  	var saveCommands = function($commands, $commandWidth, $commandarea) {
  		var commands = [];
  		$commands.each(function(index) {
	  		var $Item = $(this);
	  		var $rightOffset = ($Item.offset().left + $Item.outerWidth() + $commandWidth + 10) - $commandarea.offset().left; // Added padding of 10
		  	commands.push({ jquery: $Item, rightOffset: $rightOffset});
	  	});
	  	return commands;
  	}

  	var processCommands = function(commands, width) {
  		var overFlowCommands = [];
  		for(var i=0; i < commands.length; i++) {
  			var $Item = commands[i].jquery;
	  		var rightOffset = commands[i].rightOffset;
  			// If the command is outside the right boundaries add to overflow items
	  		if(!$Item.hasClass('ms-CommandBarItem-overflow')) {
		  		if(rightOffset > width) {
		  			overFlowCommands.push($Item);
		  		} else {
		  			// Make sure item is displayed
		  			$Item.removeClass('hideCommand');
		  		}
		  	}
  		}
	  	return overFlowCommands;
  	}

  	var processOverflow = function(overFlowCommands, $oCommand, $menu) {
  		var overflowStrings = '';
  		if(overFlowCommands.length > 0) {
  			$oCommand.addClass("showOverflow");
  			// Empty menu
  			$menu.html('');
  			// Add overflowed commands to ContextualMenu
  			for(i=0; i < overFlowCommands.length; i++) {
  				var $Item = $(overFlowCommands[i]);
  				// Hide Element in CommandBar
  				$Item.addClass('hideCommand');
  				var commandBarItemText = $Item.find('.ms-CommandBarItem-commandText').text();
  				overflowStrings += createMenuItem(commandBarItemText);
  			}
  			$menu.html(overflowStrings);
  		} else {
  			$oCommand.removeClass("showOverflow");
  			console.log("getting removed");
  		}
  	}

    /** Go through each CommandBar we've been given. */
    return this.each(function () {
	    var $CommandBar = $(this);
	    var $CommandMainArea = $CommandBar.find('.ms-CommandBar-mainArea');
	    var $CommandBarItems = $CommandMainArea.find('.ms-CommandBarItem');
	    var $OverflowCommand = $CommandBar.find('.ms-CommandBarItem-overflow');
	    var $OverflowCommandWidth = $CommandBar.find('.ms-CommandBarItem-overflow').outerWidth();
	    var $OverflowMenu = $CommandBar.find('.ms-CommandBar-overflowMenu');
	    var mobileSwitch = false;
	    var overFlowCommands;
	    var allCommands;

	    // Go through process and save commands
	    allCommands = saveCommands($CommandBarItems, $OverflowCommandWidth, $CommandMainArea);

	    // Initiate process commands and add commands to overflow on load
	    overFlowCommands = processCommands(allCommands, $CommandMainArea.innerWidth());
	    processOverflow(overFlowCommands, $OverflowCommand, $OverflowMenu);

	    // Add resize event handler on commandBar
	    $(window).resize(function() {
	    	var overFlowCommands;
	    	overFlowCommands = processCommands(allCommands, $CommandMainArea.innerWidth());
	    	processOverflow(overFlowCommands, $OverflowCommand, $OverflowMenu);
	    	if($(window).width() < 640 && mobileSwitch == false) {
	    		allCommands = saveCommands($CommandBarItems, $OverflowCommandWidth, $CommandMainArea);
	    		mobileSwitch = true;
	    	} else if($(window).width() > 639 && mobileSwitch == true) {
	    		allCommands = saveCommands($CommandBarItems, $OverflowCommandWidth, $CommandMainArea);
	    		mobileSwitch = false;
	    	}
	    });
	    // Hook up contextual menu
	    $OverflowCommand.click(function() {
	    	$OverflowMenu.toggleClass('is-open');
	    })

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


<commit_before>//  - Login Page
//        |
//        v  login
//  - Dashboard View
//        |
//        v  select Process Defintion
//  - Process Defintion View
//    - Called Process Definitions tab
//        |
//        v  open Called Process
//    - Called Process Definitions tab
//        |
//        v  switch tab
//    - Job Definitions tabs
//        |
//        v  switch tab
//    - Process Instances tabs
//        |
//        v  select instance
//  - Process Instance View

'use strict';

var dashboardPage = require('../pages/dashboard');
var processDefinitionPage = require('../pages/process-definition');
var processInstancePage = require('../pages/process-instance');

describe('cockpit - ', function() {

  describe('start test', function () {

    it('should login', function () {

      // when
      dashboardPage.navigateToWebapp('Cockpit');
      dashboardPage.authentication.userLogin('jonny1', 'jonny1');

      // then
      dashboardPage.isActive();
      expect(dashboardPage.navBarHeaderName()).toBe('camunda Cockpit');
    });

  });

  describe('dashboard', function () {

    it('should select process', function() {

      // when
      dashboardPage.deployedProcessesList.selectProcess(3);

      // then
      expect(processDefinitionPage.fullPageHeaderProcessDefinitionName()).toEqual('PROCESS DEFINITION\n' + 'CallingCallActivity');
    });

  });

  describe('process definition view', function() {

    it('should check action bar', function () {

      // then
      expect(processDefinitionPage.actionBar.suspendButton().isEnabled()).toBe(true);
    });

    it('should check Called Process Definitions tab', function() {

      // when
      processDefinitionPage.table.calledProcessDefinitionsTab.selectTab();

      // then
      processDefinitionPage.table.calledProcessDefinitionsTab.checkTabName();
      processDefinitionPage.table.calledProcessDefinitionsTab.isTabSelected();
    });

    function clickFirstCalledProceesDefintion() {
      return processDefinitionPage.table.calledProcessDefinitionsTab.calledProcessDefintionName(0).then(function(title) {
        processDefinitionPage.table.calledProcessDefinitionsTab.selectCalledProcessDefinitions(0);
        return title;
      });
    }

    it('should open called process defintion', function () {

      var processName;

      // when
      clickFirstCalledProceesDefintion().then(function(name) {
        processName = name;
      })
      .then(processDefinitionPage.pageHeaderProcessDefinitionName)
      .then(function(headerName) {

        // then
        expect(processName).toBe(headerName);
      });
      // check URL
    });

    it('should select calling activity', function () {

      // when
      processDefinitionPage.table.calledProcessDefinitionsTab.selectTab();
      processDefinitionPage.table.calledProcessDefinitionsTab.selectCalledFromActivity(0);

      // then
      processInstancePage.diagram.isActivitySelected('CallActivity_1');
    });

    it('should go deeper', function () {

      // when
      processDefinitionPage.table.calledProcessDefinitionsTab.selectCalledProcessDefinitions(0);

      // then
      expect(processDefinitionPage.pageHeaderProcessDefinitionName()).toBe('FailingProcess');
    });

    it('should check Job Definitions tab', function() {

      // when
      processDefinitionPage.table.jobDefinitionsTab.selectTab();

      // then
      processDefinitionPage.table.jobDefinitionsTab.checkTabName();
      processDefinitionPage.table.jobDefinitionsTab.isTabSelected();
      processDefinitionPage.table.calledProcessDefinitionsTab.isTabNotSelected();
    });

    it('should select job activity', function () {

      // when
      processDefinitionPage.table.jobDefinitionsTab.selectJobDefinition(0);

      // then
      processInstancePage.diagram.isActivitySelected('ServiceTask_1');
      expect(processDefinitionPage.table.jobDefinitionsTab.jobDefinitionName(0)).toBe('Service Task');
      expect(processDefinitionPage.table.jobDefinitionsTab.suspendJobButton(0).isEnabled()).toBe(true);
    });

    it('should check Process Instances tab', function() {

      // when
      processDefinitionPage.table.processInstancesTab.selectTab();

      // then
      processDefinitionPage.table.processInstancesTab.checkTabName();
      processDefinitionPage.table.processInstancesTab.isTabSelected();
    });

    function clickFirstProcessInstance() {
      return processDefinitionPage.table.processInstancesTab.processInstanceName(0).then(function(title) {
        processDefinitionPage.table.processInstancesTab.selectProcessInstance(0);
        return title;
      });
    }

    it('should select process instance and check instance view page', function() {

      // when
      var instanceId;

      clickFirstProcessInstance()
        .then(function(id) {
          instanceId = id;
        })
        .then(processInstancePage.pageHeaderProcessInstanceName)
        .then(function(headerId) {
          expect(instanceId).toBe(headerId);
        })
        .then(function() {
          processInstancePage.isActive({ instance: instanceId });
        });

    });

  });

  describe('cockpit navigation', function () {

    it('should call dashboard by bread crumb', function () {

      processInstancePage.pageHeaderProcessInstanceName()
          .then(function(instanceId) {

            // when
            processInstancePage.selectBreadCrumb(0);

            // then
            expect(dashboardPage.isActive());

            // when
            browser.navigate().back();

            // then
            processInstancePage.isActive({ instance: instanceId });
          })
    });

    it('should call defintions page by bread crumb', function () {

      // when
      processInstancePage.selectBreadCrumb(2);

      // then
      processDefinitionPage.table.processInstancesTab.selectProcessInstance(5);
    });

    it('should call dashboard by header menu', function () {
      var url;

      browser.getCurrentUrl()
        .then(function(urlString) {
          url = urlString;
        })
        .then(processInstancePage.pageHeaderProcessInstanceName)
        .then(function(instanceId) {

          // when
          processInstancePage.clickNavBarHeader();

          // then
          dashboardPage.isActive();

          // when
          browser.get(url);

          // then
          processInstancePage.isActive({ instance: instanceId });
        });

    });

  });

  describe('process instance view', function () {

    it('should select process and goto instance view', function () {

      // given
      dashboardPage.clickNavBarHeader();

      // when
      dashboardPage.deployedProcessesList.selectProcess(4);  // change variable process

      // then
      processDefinitionPage.table.processInstancesTab.selectProcessInstance(0);
    });

    it('should select Incident tab', function () {

      // when
      processInstancePage.table.incidentTab.selectTab();

      // then
      processInstancePage.table.incidentTab.checkTabName();
    });

    it('should open Called Process Instances tab', function () {

      // when
      processInstancePage.table.calledProcessInstancesTab.selectTab();

      // then
      processInstancePage.table.calledProcessInstancesTab.checkTabName();
    });

    it('should open Variables tab', function () {

      // when
      processInstancePage.table.variablesTab.selectTab();

      // then
      processInstancePage.table.variablesTab.checkTabName();
    });

    it('should open User Task tab', function () {

      // when
      processInstancePage.table.userTaskTab.selectTab();

      // then
      processInstancePage.table.userTaskTab.checkTabName();
    });

    it('should select user task in table', function () {

      // when
      processInstancePage.table.userTaskTab.selectUserTask(0);

      // then
      processInstancePage.diagram.isActivitySelected('userTask');

      processInstancePage.diagram.deselectActivity('userTask');
    });

    it('should check action bar', function () {

      // then
      expect(processInstancePage.actionBar.cancelButton().isEnabled()).toBe(true);
      expect(processInstancePage.actionBar.retryButton().isEnabled()).toBe(true);
      expect(processInstancePage.actionBar.addVariableButton().isEnabled()).toBe(true);
      expect(processInstancePage.actionBar.suspendButton().isEnabled()).toBe(true);
    });

    it('should select diagram element', function() {

      // when
      processInstancePage.diagram.selectActivity('userTask');

      // then
      processInstancePage.diagram.isActivitySelected('userTask');
    });

    it('should deselect diagram element', function() {

      // when
      processInstancePage.diagram.deselectActivity('userTask');

      // then
      processInstancePage.diagram.isActivityNotSelected('userTask');

    });

  });

  describe('end test', function() {

    it('should log out', function () {

      dashboardPage.logout();
    });

  });

});<commit_msg>chore(cockpit/navigation): rearrange test sequence<commit_after>//  - Login Page
//        |
//        v  login
//  - Dashboard View
//        |
//        v  select Process Defintion (CallingCallActivity)
//  - Process Defintion View
//    - Called Process Definitions tab
//        |
//        v  open Called Process (CallActivity)
//    - Called Process Definitions tab
//        |
//        v  switch tab
//    - Job Definitions tabs
//        |
//        v  switch tab
//    - Process Instances tabs
//        |
//        v  select instance
//  - Process Instance View

'use strict';

var dashboardPage = require('../pages/dashboard');
var processDefinitionPage = require('../pages/process-definition');
var processInstancePage = require('../pages/process-instance');

describe('cockpit - ', function() {

  describe('start test', function () {

    it('should login', function () {

      // when
      dashboardPage.navigateToWebapp('Cockpit');
      dashboardPage.authentication.userLogin('jonny1', 'jonny1');

      // then
      dashboardPage.isActive();
      expect(dashboardPage.navBarHeaderName()).toBe('camunda Cockpit');
    });

  });

  describe('dashboard', function () {

    it('should select process', function() {

      // when
      dashboardPage.deployedProcessesList.selectProcess(3);

      // then
      expect(processDefinitionPage.fullPageHeaderProcessDefinitionName()).toEqual('PROCESS DEFINITION\n' + 'CallingCallActivity');
    });

  });

  describe('process definition view', function() {

    it('should check action bar', function () {

      // then
      expect(processDefinitionPage.actionBar.suspendButton().isEnabled()).toBe(true);
    });

    it('should check Called Process Definitions tab', function() {

      // when
      processDefinitionPage.table.calledProcessDefinitionsTab.selectTab();

      // then
      processDefinitionPage.table.calledProcessDefinitionsTab.checkTabName();
      processDefinitionPage.table.calledProcessDefinitionsTab.isTabSelected();
    });

    function clickFirstCalledProcessDefintion() {
      return processDefinitionPage.table.calledProcessDefinitionsTab.calledProcessDefintionName(0).then(function(title) {
        processDefinitionPage.table.calledProcessDefinitionsTab.selectCalledProcessDefinitions(0);
        return title;
      });
    }

    it('should open called process defintion', function () {

      var processName;

      // when
      clickFirstCalledProcessDefintion().then(function(name) {
        processName = name;
      })
      .then(processDefinitionPage.pageHeaderProcessDefinitionName)
      .then(function(headerName) {

        // then
        expect(processName).toBe(headerName);
      });
      // TODO check URL
    });

    it('should select calling activity', function () {

      // when
      processDefinitionPage.table.calledProcessDefinitionsTab.selectTab();
      processDefinitionPage.table.calledProcessDefinitionsTab.selectCalledFromActivity(0);

      // then
      processInstancePage.diagram.isActivitySelected('CallActivity_1');
    });

    it('should go deeper', function () {

      var processName;

      // when
      clickFirstCalledProcessDefintion().then(function(name) {
        processName = name;
      })
          .then(processDefinitionPage.pageHeaderProcessDefinitionName)
          .then(function(headerName) {

            // then
            expect(processName).toBe(headerName);
          });
      // TODO check URL
    });

    it('should check Job Definitions tab', function() {

      // when
      processDefinitionPage.table.jobDefinitionsTab.selectTab();

      // then
      processDefinitionPage.table.jobDefinitionsTab.checkTabName();
      processDefinitionPage.table.jobDefinitionsTab.isTabSelected();
      processDefinitionPage.table.calledProcessDefinitionsTab.isTabNotSelected();
    });

    it('should select job activity', function () {

      // when
      processDefinitionPage.table.jobDefinitionsTab.selectJobDefinition(0);

      // then
      processInstancePage.diagram.isActivitySelected('ServiceTask_1');
      expect(processDefinitionPage.table.jobDefinitionsTab.jobDefinitionName(0)).toBe('Service Task');
      expect(processDefinitionPage.table.jobDefinitionsTab.suspendJobButton(0).isEnabled()).toBe(true);
    });

    it('should check Process Instances tab', function() {

      // when
      processDefinitionPage.table.processInstancesTab.selectTab();

      // then
      processDefinitionPage.table.processInstancesTab.checkTabName();
      processDefinitionPage.table.processInstancesTab.isTabSelected();
    });

    function clickFirstProcessInstance() {
      return processDefinitionPage.table.processInstancesTab.processInstanceId(0).then(function(title) {
        processDefinitionPage.table.processInstancesTab.selectProcessInstance(0);
        return title;
      });
    }

    it('should select process instance and check instance view page', function() {

      // when
      var instanceId;

      clickFirstProcessInstance()
        .then(function(id) {
          instanceId = id;
        })
        .then(processInstancePage.pageHeaderProcessInstanceName)
        .then(function(headerId) {
          expect(instanceId).toBe(headerId);
        })
        .then(function() {
          processInstancePage.isActive({ instance: instanceId });
        });

    });

  });

  // disabled by CAM-3171
  xdescribe('cockpit navigation', function () {

    it('should call dashboard by bread crumb', function () {

      processInstancePage.pageHeaderProcessInstanceName()
          .then(function(instanceId) {

            // when
            processInstancePage.selectBreadCrumb(0);

            // then
            expect(dashboardPage.isActive());

            // when
            browser.navigate().back();

            // then
            processInstancePage.isActive({ instance: instanceId });
          })
    });

    it('should call defintions page by bread crumb', function () {

      // when
      processInstancePage.selectBreadCrumb(2);

      // then
      processDefinitionPage.table.processInstancesTab.selectProcessInstance(5);
    });

    it('should call dashboard by header menu', function () {
      var url;

      browser.getCurrentUrl()
        .then(function(urlString) {
          url = urlString;
        })
        .then(processInstancePage.pageHeaderProcessInstanceName)
        .then(function(instanceId) {

          // when
          processInstancePage.clickNavBarHeader();

          // then
          dashboardPage.isActive();

          // when
          browser.get(url);

          // then
          processInstancePage.isActive({ instance: instanceId });
        });

    });

  });

  describe('process instance view', function () {

    describe('variables tab -', function () {

      it('should select change variable process and open instance view', function () {

        // given
        dashboardPage.clickNavBarHeader();

        // when
        dashboardPage.deployedProcessesList.selectProcess(4);  // change variable process

        // then
        processDefinitionPage.table.processInstancesTab.selectProcessInstance(0);
      });

      it('should open Variables tab', function () {

        // when
        processInstancePage.table.variablesTab.selectTab();

        // then
        processInstancePage.table.variablesTab.checkTabName();
      });

    });

    describe('user task tab -', function () {

      it('should open User Task tab', function () {

        // when
        processInstancePage.table.userTaskTab.selectTab();

        // then
        processInstancePage.table.userTaskTab.checkTabName();
      });

      it('should select user task in table', function () {

        // when
        processInstancePage.table.userTaskTab.selectUserTask(0);

        // then
        processInstancePage.diagram.isActivitySelected('userTask');

        processInstancePage.diagram.deselectActivity('userTask');
      });

    });

    describe('incidents tab -', function () {

      it('should select Another Failing Process and open instance view', function () {

        // given
        dashboardPage.clickNavBarHeader();

        // when
        dashboardPage.deployedProcessesList.selectProcess(0);  // Another Failing Process

        // then
        processDefinitionPage.table.processInstancesTab.selectProcessInstance(0);
      });

      it('should select Incident tab', function () {

        // when
        processInstancePage.table.incidentTab.selectTab();

        // then
        processInstancePage.table.incidentTab.checkTabName();
      });

    });

    describe('called process instances tab -', function () {

      it('should select CallActivity Process and open instance view', function () {

        // given
        dashboardPage.clickNavBarHeader();

        // when
        dashboardPage.deployedProcessesList.selectProcess(2);  // CallActivity Process

        // then
        processDefinitionPage.table.processInstancesTab.selectProcessInstance(0);
      });

      it('should open Called Process Instances tab', function () {

        // when
        processInstancePage.table.calledProcessInstancesTab.selectTab();

        // then
        processInstancePage.table.calledProcessInstancesTab.checkTabName();
      });

    });

    it('should check action bar', function () {

      // then
      expect(processInstancePage.actionBar.cancelButton().isEnabled()).toBe(true);
      expect(processInstancePage.actionBar.retryButton().isEnabled()).toBe(true);
      expect(processInstancePage.actionBar.addVariableButton().isEnabled()).toBe(true);
      expect(processInstancePage.actionBar.suspendButton().isEnabled()).toBe(true);
    });

    it('should select diagram element', function() {
      // used process: CallActivity

      // when
      processInstancePage.diagram.selectActivity('CallActivity_1');

      // then
      processInstancePage.diagram.isActivitySelected('CallActivity_1');
    });

    it('should deselect diagram element', function() {
      // used process: CallActivity

      // when
      processInstancePage.diagram.deselectActivity('CallActivity_1');

      // then
      processInstancePage.diagram.isActivityNotSelected('CallActivity_1');

    });

  });

  describe('end test', function() {

    it('should log out', function () {

      dashboardPage.logout();
    });

  });

});<|endoftext|>


<commit_before>var CHEMICAL_ELEMENTS = {
  0: {'background-color': '#F1EEFA',
      'border-color': '#AAA',
      'color': '#F1EEFA',
      'name': 'n/a',
      'symbol': ''},

  1: {'background-color': '#dde',
      'border-color': '#888',
      'color': 'black',
      'name': 'hydrogen',
      'symbol': 'H'},

  2: {'background-color': '#edd',
      'border-color': '#888',
      'color': 'black',
      'name': 'helium',
      'symbol': 'He'},
};

var BLOCK_FONT = "12px Verdana";
var DROP_DELAY = 300;
var INPUT_DELAY = 200;

var GRID_HEIGHT = 20;
var GRID_WIDTH = 10;

var BLOCK_WIDTH, BLOCK_HEIGHT;
var BLOCK_SPACING_WIDTH, BLOCK_SPACING_HEIGHT;

var TETRINIMO_TEMPLATES = {
  jBlock: ['xx',
           'x ',
           'x '],
  lBlock: ['xx',
           ' x',
           ' x'],
  square: ['xx',
           'xx'],
  sBlock: ['x ',
           'xx',
           ' x'],
  zBlock: [' x',
           'xx',
           'x '],
  line:   ['x',
           'x',
           'x',
           'x'],
  tBlock: ['xxx',
           ' x ']
};
var processTetrinimos = function() {
  var tetraShape = new Object;
  for(var shape in TETRINIMO_TEMPLATES) {
    if( TETRINIMO_TEMPLATES.hasOwnProperty(shape)) {
      tetraShape[shape] = new Array;
      var currentShape = TETRINIMO_TEMPLATES[shape];
      for(var row in currentShape) {
        for(var col in currentShape[row]) {
          if(currentShape[row][col] == 'x') {
            tetraShape[shape].push({x: parseInt(col, 10),
                                    y: parseInt(row, 10)});
          }
        }
      }
    }
  }
  return tetraShape
}
var TETRINIMO_SHAPES = processTetrinimos();

var TetrisBoard = function(args) {
  this.board = new Array;
  this.tetrinimo = args.tetrinimo;

  for(var row = 0; row < 20; row++) {
    this.board[row] = new Array;
    for(var col = 0; col < 10; col++) {
      this.board[row][col] = 0;
    }
  };
}
TetrisBoard.prototype.blit = function(clear) {
  var element = this.tetrinimo.element;

  if(clear) {
    element = 0;
  }

  for(var block in this.tetrinimo.blocks) {
    var currentBlock = this.tetrinimo.blocks[block];
    this.board[currentBlock.y][currentBlock.x] = element;
  }
};
TetrisBoard.prototype.detectCollision = function() {
  for(var block in this.tetrinimo.blocks) {
    currentBlock = this.tetrinimo.blocks[block];
    if(currentBlock.y >= GRID_HEIGHT) {
      return 'floor';
    }
    else if(currentBlock.x < 0 || currentBlock.x >= GRID_WIDTH) {
      return 'wall';
    }
    else if(this.board[currentBlock.y][currentBlock.x] !== 0) {
      return 'block';
    }
  }
  return 'clear';
};
TetrisBoard.prototype.dropBlock = function() {
  this.blit(true);
  this.tetrinimo.drop();
  var collision = this.detectCollision();
  if(collision == 'floor' || collision == 'block') {
    this.tetrinimo.raise();
    this.blit();
    this.tetrinimo = null;
    clearInterval(this.intervalID);
    return;
  }
  this.blit();
};
TetrisBoard.prototype.slideBlock = function(direction) {
  this.blit(true);
  this.tetrinimo.slide(direction);
  var collision = this.detectCollision();
  if(collision == 'wall' || collision == 'block') {
    var reverseDirection = direction == 'left' ? 'right' : 'left';
    this.tetrinimo.slide(reverseDirection);
  }
  this.blit();
};

var Tetrinimo = function(args) {
  this.element = args.element;
  var shape = args.shape;

  this.blocks = shape.map(function(block) {
    return {x: new Number(block.x), y: new Number(block.y)};
  });

  this.row = 0;
  this.col = 5;

  for(var block in this.blocks) {
    this.blocks[block].y += this.row;
    this.blocks[block].x += this.col;
  }
}
Tetrinimo.prototype.raise = function() {
  this.row--;
  for(var block in this.blocks) {
    this.blocks[block].y--;
  }
};
Tetrinimo.prototype.drop = function() {
  this.row++;
  for(var block in this.blocks) {
    this.blocks[block].y++;
  }
};
var directToInt = {
  'left': -1,
  'right': 1
};
Tetrinimo.prototype.slide = function(direction) {
  this.blocks.forEach(function(block) {
    block.x += directToInt[direction];
  });
};

var keyCodes = {
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  8: 'backspace'
}

var View = function(args) {
  this.context = document.querySelector('canvas').getContext('2d');
  this.gameBoard = args.gameBoard;
  this.pressed = false;

  addEventListener('keydown', this.keyDown.bind(this));
  addEventListener('keyup', this.keyUp.bind(this));
}
View.prototype.keyDown = function(event) {
  var pressedKey = keyCodes[event.keyCode];
  if(pressedKey == 'left' || pressedKey == 'right') {
    event.preventDefault();
    if(this.pressed == false) {
      this.pressed = pressedKey;
      this.handleInput.bind(this).call();
    }
  }
};
View.prototype.keyUp = function(event){
  var releasedKey = keyCodes[event.keyCode];
  if(releasedKey == 'left' || releasedKey == 'right') {
    event.preventDefault();
    this.pressed = false;
  }
};
View.prototype.handleInput = function() {
  console.log('pressed in handleInput', this.pressed);
  if(this.pressed) {
    this.gameBoard.slideBlock(this.pressed);
    setTimeout(this.handleInput.bind(this), INPUT_DELAY);
  }
};
View.prototype.drawBoard = function(board) {
  var context = this.context
  context.lineWidth = 4;
  context.font = BLOCK_FONT;

  board.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      context.fillStyle = CHEMICAL_ELEMENTS[col]['background-color'];
      context.strokeStyle = CHEMICAL_ELEMENTS[col]['border-color'];

      context.fillRect((cIndex * BLOCK_SPACING_WIDTH) + 5, (rIndex * BLOCK_SPACING_HEIGHT) + 5, BLOCK_WIDTH, BLOCK_HEIGHT);
      context.strokeRect((cIndex * BLOCK_SPACING_WIDTH) + 5, (rIndex * BLOCK_SPACING_HEIGHT) + 5, BLOCK_WIDTH, BLOCK_HEIGHT);
      context.fillStyle = CHEMICAL_ELEMENTS[col]['color'];
      context.fillText(CHEMICAL_ELEMENTS[col].symbol, (cIndex * BLOCK_SPACING_WIDTH) + (BLOCK_SPACING_WIDTH / 2) - 4, (rIndex * BLOCK_SPACING_HEIGHT) + (BLOCK_SPACING_HEIGHT / 2) + 4);
    });
  });
};
View.prototype.animate = function(board) {
  var lastTime = null;
  var progress = true;
  var self = this;

  var animate = function(time) {
    if(lastTime) {
      var timeStep = Math.min(time - lastTime, 100) / 1000;
      progress = timeStep < 2000;
    }
    lastTime = time;
    self.drawBoard(board);
    if(progress) {
      requestAnimationFrame(animate);
    }
  }
  requestAnimationFrame(animate);
};

var ready = function(fn) {
  if(document.readyState != 'loading') {
    fn();
  }
  else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}
ready(function() {
  var canvas = document.querySelector('canvas');
  BLOCK_SPACING_HEIGHT = canvas.getAttribute('height') / 20;
  BLOCK_SPACING_WIDTH = canvas.getAttribute('width') / 10;
  BLOCK_HEIGHT = BLOCK_SPACING_HEIGHT - 10;
  BLOCK_WIDTH = BLOCK_SPACING_WIDTH - 10;

  window.lineBlock = new Tetrinimo({element: 1, shape: TETRINIMO_SHAPES.line});
  window.gameBoard = new TetrisBoard({tetrinimo: lineBlock});
  window.gameView = new View({gameBoard: gameBoard});

  gameBoard.blit({tetrinimo: lineBlock});
  gameView.animate(gameBoard.board);

  gameBoard.intervalID = setInterval(function() {
    gameBoard.dropBlock(lineBlock);
  }, DROP_DELAY);
});
<commit_msg>Refactor dropBlock interval as part of dropBlock function<commit_after>var CHEMICAL_ELEMENTS = {
  0: {'background-color': '#F1EEFA',
      'border-color': '#AAA',
      'color': '#F1EEFA',
      'name': 'n/a',
      'symbol': ''},

  1: {'background-color': '#dde',
      'border-color': '#888',
      'color': 'black',
      'name': 'hydrogen',
      'symbol': 'H'},

  2: {'background-color': '#edd',
      'border-color': '#888',
      'color': 'black',
      'name': 'helium',
      'symbol': 'He'},
};

var BLOCK_FONT = "12px Verdana";
var DROP_DELAY = 300;
var INPUT_DELAY = 200;

var GRID_HEIGHT = 20;
var GRID_WIDTH = 10;

var BLOCK_WIDTH, BLOCK_HEIGHT;
var BLOCK_SPACING_WIDTH, BLOCK_SPACING_HEIGHT;

var TETRINIMO_TEMPLATES = {
  jBlock: ['xx',
           'x ',
           'x '],
  lBlock: ['xx',
           ' x',
           ' x'],
  square: ['xx',
           'xx'],
  sBlock: ['x ',
           'xx',
           ' x'],
  zBlock: [' x',
           'xx',
           'x '],
  line:   ['x',
           'x',
           'x',
           'x'],
  tBlock: ['xxx',
           ' x ']
};
var processTetrinimos = function() {
  var tetraShape = new Object;
  for(var shape in TETRINIMO_TEMPLATES) {
    if( TETRINIMO_TEMPLATES.hasOwnProperty(shape)) {
      tetraShape[shape] = new Array;
      var currentShape = TETRINIMO_TEMPLATES[shape];
      for(var row in currentShape) {
        for(var col in currentShape[row]) {
          if(currentShape[row][col] == 'x') {
            tetraShape[shape].push({x: parseInt(col, 10),
                                    y: parseInt(row, 10)});
          }
        }
      }
    }
  }
  return tetraShape
}
var TETRINIMO_SHAPES = processTetrinimos();

var TetrisBoard = function(args) {
  this.board = new Array;
  this.tetrinimo = args.tetrinimo;
  this.dropDelay = DROP_DELAY;

  for(var row = 0; row < 20; row++) {
    this.board[row] = new Array;
    for(var col = 0; col < 10; col++) {
      this.board[row][col] = 0;
    }
  };
}
TetrisBoard.prototype.blit = function(clear) {
  var element = this.tetrinimo.element;

  if(clear) {
    element = 0;
  }

  for(var block in this.tetrinimo.blocks) {
    var currentBlock = this.tetrinimo.blocks[block];
    this.board[currentBlock.y][currentBlock.x] = element;
  }
};
TetrisBoard.prototype.detectCollision = function() {
  for(var block in this.tetrinimo.blocks) {
    currentBlock = this.tetrinimo.blocks[block];
    if(currentBlock.y >= GRID_HEIGHT) {
      return 'floor';
    }
    else if(currentBlock.x < 0 || currentBlock.x >= GRID_WIDTH) {
      return 'wall';
    }
    else if(this.board[currentBlock.y][currentBlock.x] !== 0) {
      return 'block';
    }
  }
  return 'clear';
};
TetrisBoard.prototype.dropBlock = function() {
  this.blit(true);
  this.tetrinimo.drop();
  var collision = this.detectCollision();
  if(collision == 'floor' || collision == 'block') {
    this.tetrinimo.raise();
    this.blit();
    this.tetrinimo = null;
    clearInterval(this.intervalID);
    return;
  }
  this.blit();
  setInterval(function() {this.dropBlock}, this.dropDelay);
};
TetrisBoard.prototype.slideBlock = function(direction) {
  this.blit(true);
  this.tetrinimo.slide(direction);
  var collision = this.detectCollision();
  if(collision == 'wall' || collision == 'block') {
    var reverseDirection = direction == 'left' ? 'right' : 'left';
    this.tetrinimo.slide(reverseDirection);
  }
  this.blit();
};

var Tetrinimo = function(args) {
  this.element = args.element;
  var shape = args.shape;

  this.blocks = shape.map(function(block) {
    return {x: new Number(block.x), y: new Number(block.y)};
  });

  this.row = 0;
  this.col = 5;

  for(var block in this.blocks) {
    this.blocks[block].y += this.row;
    this.blocks[block].x += this.col;
  }
}
Tetrinimo.prototype.raise = function() {
  this.row--;
  for(var block in this.blocks) {
    this.blocks[block].y--;
  }
};
Tetrinimo.prototype.drop = function() {
  this.row++;
  for(var block in this.blocks) {
    this.blocks[block].y++;
  }
};
var directToInt = {
  'left': -1,
  'right': 1
};
Tetrinimo.prototype.slide = function(direction) {
  this.blocks.forEach(function(block) {
    block.x += directToInt[direction];
  });
};

var keyCodes = {
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  8: 'backspace'
}

var View = function(args) {
  this.context = document.querySelector('canvas').getContext('2d');
  this.gameBoard = args.gameBoard;
  this.pressed = false;

  addEventListener('keydown', this.keyDown.bind(this));
  addEventListener('keyup', this.keyUp.bind(this));
}
View.prototype.keyDown = function(event) {
  var pressedKey = keyCodes[event.keyCode];
  if(pressedKey == 'left' || pressedKey == 'right') {
    event.preventDefault();
    if(this.pressed == false) {
      this.pressed = pressedKey;
      this.handleInput.bind(this).call();
    }
  }
};
View.prototype.keyUp = function(event){
  var releasedKey = keyCodes[event.keyCode];
  if(releasedKey == 'left' || releasedKey == 'right') {
    event.preventDefault();
    this.pressed = false;
  }
};
View.prototype.handleInput = function() {
  console.log('pressed in handleInput', this.pressed);
  if(this.pressed) {
    this.gameBoard.slideBlock(this.pressed);
    setTimeout(this.handleInput.bind(this), INPUT_DELAY);
  }
};
View.prototype.drawBoard = function(board) {
  var context = this.context
  context.lineWidth = 4;
  context.font = BLOCK_FONT;

  board.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      context.fillStyle = CHEMICAL_ELEMENTS[col]['background-color'];
      context.strokeStyle = CHEMICAL_ELEMENTS[col]['border-color'];

      context.fillRect((cIndex * BLOCK_SPACING_WIDTH) + 5, (rIndex * BLOCK_SPACING_HEIGHT) + 5, BLOCK_WIDTH, BLOCK_HEIGHT);
      context.strokeRect((cIndex * BLOCK_SPACING_WIDTH) + 5, (rIndex * BLOCK_SPACING_HEIGHT) + 5, BLOCK_WIDTH, BLOCK_HEIGHT);
      context.fillStyle = CHEMICAL_ELEMENTS[col]['color'];
      context.fillText(CHEMICAL_ELEMENTS[col].symbol, (cIndex * BLOCK_SPACING_WIDTH) + (BLOCK_SPACING_WIDTH / 2) - 4, (rIndex * BLOCK_SPACING_HEIGHT) + (BLOCK_SPACING_HEIGHT / 2) + 4);
    });
  });
};
View.prototype.animate = function(board) {
  var lastTime = null;
  var progress = true;
  var self = this;

  var animate = function(time) {
    if(lastTime) {
      var timeStep = Math.min(time - lastTime, 100) / 1000;
      progress = timeStep < 2000;
    }
    lastTime = time;
    self.drawBoard(board);
    if(progress) {
      requestAnimationFrame(animate);
    }
  }
  requestAnimationFrame(animate);
};

var ready = function(fn) {
  if(document.readyState != 'loading') {
    fn();
  }
  else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}
ready(function() {
  var canvas = document.querySelector('canvas');
  BLOCK_SPACING_HEIGHT = canvas.getAttribute('height') / 20;
  BLOCK_SPACING_WIDTH = canvas.getAttribute('width') / 10;
  BLOCK_HEIGHT = BLOCK_SPACING_HEIGHT - 10;
  BLOCK_WIDTH = BLOCK_SPACING_WIDTH - 10;

  window.lineBlock = new Tetrinimo({element: 1, shape: TETRINIMO_SHAPES.line});
  window.gameBoard = new TetrisBoard({tetrinimo: lineBlock});
  window.gameView = new View({gameBoard: gameBoard});

  gameBoard.blit({tetrinimo: lineBlock});
  gameView.animate(gameBoard.board);
  gameBoard.dropBlock();
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Slice arguments into an array
process.ARI = {};
var args = process.argv.slice(2);

// If there are no arguments run help
if (!args.length){
    require('../cmd/help')();
    return;
}

var fs = require('fs');
var Err = require('../lib/logger').Err;
var configPath = process.cwd() + '/.ari-config.json';

// Checks for configuration file
if (!fs.existsSync(configPath)){
    Err('Config not found');
    Err('Please run ari init');
    return;
}

var config = fs.readFileSync(configPath);

// Checks if config is empty for some reason?
if (!config.length){
    Err('Config file is empty');
    Err('Please run ari init');
    return;
}

// Parses config for use
config = JSON.parse(config);
var commands = {
    init: true,
    help: true,
    add: true,
    del: true,
    delete: true,
    project: true,
}

// If first argument is the name of a project in the config, add 'project' to the front of the args array
if (config.projects[args[0]]) args.unshift('project');

process.ARI.args = args;
process.ARI.config = config;
process.ARI.configPath = configPath;

// If the command exists require that file and run it
if (commands[args[0]]) require('../cmd/' + args[0])();
// Else run help
else {
    require('../cmd/help')();
    Err('Command not found');
    return;
}
<commit_msg>Fixed Issue(error on empty projects section)<commit_after>#!/usr/bin/env node

/* Main 'ari' routing command */

var args = process.argv.slice(2);

if (!args.length){
    require('../cmd/help')();
    return;
}

var fs = require('fs');
var Err = require('../lib/logger').Err;
var configPath = process.cwd() + '/.ari-config.json';

if (!fs.existsSync(configPath)){
    Err('Config not found');
    Err('Please run ari init');
    return;
}

var config = fs.readFileSync(configPath);

if (!config.length){
    Err('Config file is empty');
    Err('Please run ari init');
    return;
}

config = JSON.parse(config);
var commands = {
    init: true,
    help: true,
    add: true,
    del: true,
    delete: true,
    project: true,
}

config.projects = config.projects || {};
if (config.projects[args[0]]) args.unshift('project');

process.ARI = {};
process.ARI.args = args;
process.ARI.config = config;
process.ARI.configPath = configPath;

if (commands[args[0]]) require('../cmd/' + args[0])();
else {
    require('../cmd/help')();
    Err('Command not found');
    return;
}
<|endoftext|>


<commit_before>angular
  .module('app')
  .controller('featureEditController', [
    '$scope',
    '$location',
    '$routeParams',
    'userService',
    'featureService',
    'actionKitService',
    '$rootScope',
    function($scope, $location, $routeParams, userAPI, Feature, actionKitService, $rootScope) {
        $scope.feature = Feature.get({id: $routeParams.id}, function(feature) {
            return feature;
        });

        $scope.update = function() {
            $scope.feature.$update(function(response) {
                alert("Feature updated successfully");
                $location.path('/admin/features');
            });
        };
    }]);
<commit_msg>Update Edit Feature Form to use FormHelper service. Add validations and alerts.<commit_after>angular
  .module('app')
  .controller('featureEditController', [
    '$scope',
    '$location',
    '$routeParams',
    'userService',
    'featureService',
    'actionKitService',
    'FormHelper',
    '$rootScope',
    function($scope, $location, $routeParams, userAPI, Feature, actionKitService, FormHelper, $rootScope) {
        $scope.feature = Feature.get({id: $routeParams.id}, function(feature) {
            return feature;
        });

        $scope.showError = FormHelper.showError;
        $scope.showSuccess = FormHelper.showSuccess;

        $scope.update = function() {
            // FormHelper.update(form, model, callback)
            FormHelper.update($scope.EditFeatureForm, $scope.feature, function() {
                alert("Feature updated successfully");
                $location.path('/admin/features');
            });
        };
    }]);
<|endoftext|>


<commit_before>window.onload = function() {
    // the items in this array are the whitelisted 'QR codes'
    var validationArr = [ "appidaapi","appidaapi2"];
    var imageHolder;

    var width         = 320;    // We will scale the photo width to this
    var height        = 0;     // This will be computed based on the input stream
    var streaming     = false;
    var scanning      = false;
    var playing       = false;
    var video         = document.getElementById('video');
    var canvas        = document.getElementById('canvas');
    var photo         = document.getElementById('photo');
    var upload        = document.getElementById('upload');
    var preview       = document.getElementById('preview');
    var qr            = new QrCode();
    const constraints = {advanced: [{facingMode: "environment"}]}
    // this function takes a key and checks if it is whitelisted
    function validationKey(key){
        var validation = false;
        for(var i = 0; i < validationArr.length;i++){
            if(validationArr[i] == key){
                validation = true;
            }
        }
        return validation
    }

    // set a key in storage as owned
    function setStorageItem(key){
        if (typeof(Storage) !== "undefined") {
            if(validationKey(key)){
                // good to go
                localStorage.setItem(key,1)    // define 1 as 'true' / 'present'
                if('vibrate' in navigator){
                    navigator.vibrate([200,100,50])
                }else{
                    console.log("Should be vibrating.. but your device sucks")
                }
            }else{
                console.log("this item does not pass validation")
            }
        } else {
            alert("Browser does not support storage! git gud browser plz")
        }

    }
    // setStorageItem("appidaapi4")

    navigator.mediaDevices.getUserMedia({ video: constraints, audio: false }).then(function(stream) {
        video.srcObject = stream;
        video.play();
    }).catch(function(err) {
        console.log("An error occured initialising video element! \n error code: " + err);
    });

    qr.callback = function(err, result) {
      var span = document.querySelector('span') || document.createElement('span');
      if(result){
        var result = result.result;
        setStorageItem(result);
        console.error("Found QR: " +result.result);
      }
      else{
        span.textContent = 'Error! See error message in console!';
        console.error(err);
      }
      preview.appendChild(span);
    }
    /*

    */
    video.addEventListener('canplay', function(ev){
        if (!streaming) {
          height = video.videoHeight / (video.videoWidth/width);
          video.setAttribute('width', width);
          video.setAttribute('height', height);
          canvas.setAttribute('width', width);
          canvas.setAttribute('height', height);
          streaming = true;
        }
      }, false);

    upload.addEventListener('change', function() {
        for (var i = 0; i < this.files.length; i++) {
          var file = this.files[i];
          var imageType = /^image\//;
          if (!imageType.test(file.type)) {
            throw new Error('File type not valid');
          }
          // Read file
          var reader = new FileReader();
          reader.addEventListener('load', function() {
            // Show as preview image
            var img = document.querySelector('img') || document.createElement('img');
            img.src = this.result;
            preview.appendChild(img);
            // Analyse code
            qr.decode(this.result);
          }.bind(reader), false);
          reader.readAsDataURL(file);
        }
      }, false);

    /////////////////
    ////QR /////////////

    function handleFiles(f){
        var o=[];
        for(var i =0;i<f.length;i++){
          var reader = new FileReader();
          reader.onload = (function(theFile) {
            return function(e) {
              qrcode.decode(e.target.result);
            };
          })(f[i]);
          // Read in the image file as a data URL.
          reader.readAsDataURL(f[i]);
        }
    }

    function startscan(){
        scanning = true;
        video.play();
        if(!playing){
            var takeScreenCap = function(){
                if(scanning){
                    var context = canvas.getContext('2d');
                    if (width != undefined && height != undefined) {
                      canvas.width = width;
                      canvas.height = height;
                      context.drawImage(video, 0, 0, width, height);
                      var data = canvas.toDataURL('image/png');
                      qr.decode(data);
                    }
                }
            }
            setInterval(takeScreenCap , 1000)
        }
    }

    /*
        Modal controls
    */
    // Get the modal
    var modal = document.getElementById('myModal');

    // Get the button that opens the modal
    var btn = document.getElementById("myBtn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal
    btn.onclick = function() {
        startscan();
        playing = true;
        modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        scanning = false;
        video.pause();
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            scanning = false;
            video.pause();
            modal.style.display = "none";
        }
    }

};

<commit_msg>qr<commit_after>window.onload = function() {
    // the items in this array are the whitelisted 'QR codes'
    var validationArr = [ "appidaapi","appidaapi2"];
    var imageHolder;

    var width         = 320;    // We will scale the photo width to this
    var height        = 0;     // This will be computed based on the input stream
    var streaming     = false;
    var scanning      = false;
    var playing       = false;
    var video         = document.getElementById('video');
    var canvas        = document.getElementById('canvas');
    var photo         = document.getElementById('photo');
    var upload        = document.getElementById('upload');
    var preview       = document.getElementById('preview');
    var qr            = new QrCode();
    const constraints = {advanced: [{facingMode: "environment"}]}
    // this function takes a key and checks if it is whitelisted
    function validationKey(key){
        var validation = false;
        for(var i = 0; i < validationArr.length;i++){
            if(validationArr[i] == key){
                validation = true;
            }
        }
        return validation
    }

    // set a key in storage as owned
    function setStorageItem(key){
        if (typeof(Storage) !== "undefined") {
            if(validationKey(key)){
                // good to go
                localStorage.setItem(key,1)    // define 1 as 'true' / 'present'
                if('vibrate' in navigator){
                    navigator.vibrate([200,100,50])
                }else{
                    console.log("Should be vibrating.. but your device sucks")
                }
            }else{
                console.log("this item does not pass validation")
            }
        } else {
            alert("Browser does not support storage! git gud browser plz")
        }

    }
    // setStorageItem("appidaapi4")

    navigator.mediaDevices.getUserMedia({ video: constraints, audio: false }).then(function(stream) {
        video.srcObject = stream;
        video.play();
    }).catch(function(err) {
        console.log("An error occured initialising video element! \n error code: " + err);
    });

    qr.callback = function(err, result) {
      var span = document.querySelector('span') || document.createElement('span');
      if(result){
        var resultZ = result.result;
        setStorageItem(resultZ);
        console.error("Found QR: " +result.result);
      }
      else{
        span.textContent = 'Error! See error message in console!';
        console.error(err);
      }
      preview.appendChild(span);
    }
    /*

    */
    video.addEventListener('canplay', function(ev){
        if (!streaming) {
          height = video.videoHeight / (video.videoWidth/width);
          video.setAttribute('width', width);
          video.setAttribute('height', height);
          canvas.setAttribute('width', width);
          canvas.setAttribute('height', height);
          streaming = true;
        }
      }, false);

    upload.addEventListener('change', function() {
        for (var i = 0; i < this.files.length; i++) {
          var file = this.files[i];
          var imageType = /^image\//;
          if (!imageType.test(file.type)) {
            throw new Error('File type not valid');
          }
          // Read file
          var reader = new FileReader();
          reader.addEventListener('load', function() {
            // Show as preview image
            var img = document.querySelector('img') || document.createElement('img');
            img.src = this.result;
            preview.appendChild(img);
            // Analyse code
            qr.decode(this.result);
          }.bind(reader), false);
          reader.readAsDataURL(file);
        }
      }, false);

    /////////////////
    ////QR /////////////

    function handleFiles(f){
        var o=[];
        for(var i =0;i<f.length;i++){
          var reader = new FileReader();
          reader.onload = (function(theFile) {
            return function(e) {
              qrcode.decode(e.target.result);
            };
          })(f[i]);
          // Read in the image file as a data URL.
          reader.readAsDataURL(f[i]);
        }
    }

    function startscan(){
        scanning = true;
        video.play();
        if(!playing){
            var takeScreenCap = function(){
                if(scanning){
                    var context = canvas.getContext('2d');
                    if (width != undefined && height != undefined) {
                      canvas.width = width;
                      canvas.height = height;
                      context.drawImage(video, 0, 0, width, height);
                      var data = canvas.toDataURL('image/png');
                      qr.decode(data);
                    }
                }
            }
            setInterval(takeScreenCap , 1000)
        }
    }

    /*
        Modal controls
    */
    // Get the modal
    var modal = document.getElementById('myModal');

    // Get the button that opens the modal
    var btn = document.getElementById("myBtn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal
    btn.onclick = function() {
        startscan();
        playing = true;
        modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        scanning = false;
        video.pause();
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            scanning = false;
            video.pause();
            modal.style.display = "none";
        }
    }

};

<|endoftext|>


<commit_before>import m from 'mithril';

const view = () =>
{m.trust('  ')}
;

export default {
  view,
};
<commit_msg>:p trey<commit_after>import { trust } from 'mithril';

const view = () =>
{trust('  ')}
;

export default {
  view,
};
<|endoftext|>


<commit_before>module.exports = function(config){
    config.set({
    basePath : '../',

    files : [
      'app/lib/angular/angular.js',
      'app/lib/angular/angular-*.js',
      'test/lib/angular/angular-mocks.js',
      'app/js/**/*.js',
      'test/unit/**/*.js'
    ],

    exclude : [
      'app/lib/angular/angular-loader.js',
      'app/lib/angular/*.min.js'
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    browsers : ['Chrome'],

    plugins : [
            'karma-junit-reporter',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

})}
<commit_msg>fix(karma): excluded angular-scenario<commit_after>module.exports = function(config){
    config.set({
    basePath : '../',

    files : [
      'app/lib/angular/angular.js',
      'app/lib/angular/angular-*.js',
      'test/lib/angular/angular-mocks.js',
      'app/js/**/*.js',
      'test/unit/**/*.js'
    ],

    exclude : [
      'app/lib/angular/angular-loader.js',
      'app/lib/angular/*.min.js',
      'app/lib/angular/angular-scenario.js'
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    browsers : ['Chrome'],

    plugins : [
            'karma-junit-reporter',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

})}
<|endoftext|>


<commit_before>{
  "id":16,
  "name":"Enhanced payments data",
  "description": "Discovery is looking to identify DWP’s user needs for a long-term industry-wide plan to include payment data with payments automatically.",
  "theme": "Platforms",
  "location": "Stockport",
  "facing":"internal",
  "phase":"discovery",
  "sro":"John Fundry",
  "service_man":"Martin Little",
  "phase-history":{
    "discovery": [
      {"label":"Started", "date": "November 2015"}
    ],
    "alpha": [
      {"label":"Predicted", "date": "March 2016"}
    ],
    "beta": [
      {"label":"Predicted Start Date", "date": "TBC"}
    ]
  },
  "priority":"Low"
}
<commit_msg>Update enhanced-data.js<commit_after>{
  "id":16,
  "name":"Enhanced payments data",
  "description": "Discovery is looking to identify DWP’s user needs for a long-term industry-wide plan to include payment data with payments automatically.",
  "theme": "Platforms",
  "location": "Stockport",
  "facing":"internal",
  "phase":"discovery",
  "sro":"John Fundry",
  "service_man":"Martin Little",
  "phase-history":{
    "discovery": [
      {"label":"Started", "date": "November 2015"}
    ],
    "alpha": [
      {"label":"Predicted", "date": "March 2016"}
    ],
    "beta": [
      {"label":"Predicted start date", "date": "TBC"}
    ]
  },
  "priority":"Low"
}
<|endoftext|>


<commit_before>import debug from 'debug'
import cookies from 'cookies-js'
import invariant from 'invariant'
import defaults from 'lodash/object/defaults'

const log = debug('bshed:client:request')

/**
 * RequestPlugin
 * Adds executeRequest(fn, params) to action context
 */
export default function RequestPlugin () {
  return {
    name: 'RequestPlugin',
    plugContext
  }

  function plugContext (contextOptions={}) {
    const request = defaults(contextOptions, {
      fetch: global.fetch,
      rootUrl: '',
      cookie: ''
    })

    return {
      plugActionContext
    }

    function plugActionContext (actionContext) {
      actionContext.request = request
      actionContext.executeRequest = executeRequestFactory(request)
    }
  }
}

/**
 * Factory for creating executeRequest
 * @param {Object} config
 * @param {Fetch} config.fetch Fetch
 * @return {Function} executeRequest Request creator
 */
function executeRequestFactory ({fetch, rootUrl, cookie}) {
  // node-fetch exposes Headers on the fetch object
  // whatwg-fetch polyfills Headers on the window
  const Headers = fetch.Headers || global.Headers

  /**
   * Execute a request with payload
   * @param {Function} request Request to execute
   * @param {Object} payload Request payload
   * @returns {Promise}
   */
  return function executeRequest (fn, payload={}) {
    invariant(typeof fn === 'function', 'executeRequest requires a function')
    log(`Executing request ${fn.displayName || fn.name} with payload`, payload)

    return new Promise((resolve, reject) => {
      fn(requestCreator, payload).then(resolve, reject)
    })
  }

  function requestCreator (url='', options={}) {
    if (url.charAt(0) === '/') {
      url = `${rootUrl}${url}`
    }

    defaults(options, { credentials: 'include' })

    options.headers = new Headers(options.headers || {})
    if (!options.headers.has('cookie') && cookie) {
      options.headers.set('cookie', cookie)
    }
    if (!options.headers.has('x-xsrf-token') && shouldSetXsrfToken(options.method)) {
      options.headers.set('x-xsrf-token', cookies.get('XSRF-TOKEN'))
    }

    return fetch(url, options)
      // .then(status)
      // .then(parseJsonBody)
  }
}

/**
 * Check if X-XSRF-TOKEN header should be set
 * @param {Object} options Request creator options
 * @returns {boolean} if it should be set
 */
function shouldSetXsrfToken (method='GET') {
  return ['GET', 'HEAD', 'OPTIONS'].indexOf(method.toUpperCase()) === -1
}

/**
 * Call response.json and add parsedBody
 * @param {Response} response Fetch response
 * @return {Promise}
 */
// function parseJsonBody (res) {
//   return res.json().then(parsedBody => {
//     res.parsedBody = parsedBody
//     return res
//   })
// }

/**
 * Resolve when status code is 2XX, otherwise reject
 * @param {Response} response Fetch response
 * @return {Promise}
 */
// function status (res) {
//   return res.status >= 200 && res.status < 300
//     ? Promise.resolve(res)
//     : Promise.reject(res)
// }
<commit_msg>Readability<commit_after>import debug from 'debug'
import cookies from 'cookies-js'
import invariant from 'invariant'
import defaults from 'lodash/object/defaults'

const log = debug('bshed:client:request')

/**
 * RequestPlugin
 * Adds executeRequest(fn, params) to action context
 */
export default function RequestPlugin () {
  return {
    name: 'RequestPlugin',
    plugContext
  }

  function plugContext (contextOptions={}) {
    const request = defaults(contextOptions, {
      fetch: global.fetch,
      rootUrl: '',
      cookie: ''
    })

    return {
      plugActionContext
    }

    function plugActionContext (actionContext) {
      actionContext.request = request
      actionContext.executeRequest = executeRequestFactory(request)
    }
  }
}

/**
 * Factory for creating executeRequest
 * @param {Object} config
 * @param {Fetch} config.fetch Fetch
 * @return {Function} executeRequest Request creator
 */
function executeRequestFactory ({fetch, rootUrl, cookie}) {
  // node-fetch exposes Headers on the fetch object
  // whatwg-fetch polyfills Headers on the window
  const Headers = fetch.Headers || global.Headers

  /**
   * Execute a request with payload
   * @param {Function} request Request to execute
   * @param {Object} payload Request payload
   * @returns {Promise}
   */
  return function executeRequest (fn, payload={}) {
    invariant(typeof fn === 'function', 'executeRequest requires a function')
    log(`Executing request ${fn.displayName || fn.name} with payload`, payload)

    return new Promise((resolve, reject) => {
      fn(requestCreator, payload).then(resolve, reject)
    })
  }

  function requestCreator (url='', options={}) {
    if (url[0] === '/') {
      url = `${rootUrl}${url}`
    }

    defaults(options, { credentials: 'include' })

    options.headers = new Headers(options.headers || {})
    if (!options.headers.has('cookie') && cookie) {
      options.headers.set('cookie', cookie)
    }
    if (!options.headers.has('x-xsrf-token') && shouldSetXsrfToken(options.method)) {
      options.headers.set('x-xsrf-token', cookies.get('XSRF-TOKEN'))
    }

    return fetch(url, options)
      // .then(status)
      // .then(parseJsonBody)
  }
}

/**
 * Check if X-XSRF-TOKEN header should be set
 * @param {Object} options Request creator options
 * @returns {boolean} if it should be set
 */
function shouldSetXsrfToken (method='GET') {
  return ['GET', 'HEAD', 'OPTIONS'].indexOf(method.toUpperCase()) === -1
}

/**
 * Call response.json and add parsedBody
 * @param {Response} response Fetch response
 * @return {Promise}
 */
// function parseJsonBody (res) {
//   return res.json().then(parsedBody => {
//     res.parsedBody = parsedBody
//     return res
//   })
// }

/**
 * Resolve when status code is 2XX, otherwise reject
 * @param {Response} response Fetch response
 * @return {Promise}
 */
// function status (res) {
//   return res.status >= 200 && res.status < 300
//     ? Promise.resolve(res)
//     : Promise.reject(res)
// }
<|endoftext|>