<commit_before>// immediate function
document.UI = (function () {

	// module object; add all methods and properties that should be visible globally
    var module = {};
	module.theSounds = [];

	var updateSoundList = function () {

		$('ul#sound-list').empty();
		var groupName = $('select#banch-select').find(':selected').attr('value');
		$(document.Sound.sounds[groupName]).each(function (sampleCounter, sample) {
			$('ul#sound-list').append('
' + sample["name"] + '
');
		});
		$('.sound-item').click(soundClickHandler);
		document.Sound.currentSelection["groupName"] = groupName;
	};

	var soundClickHandler = function () {
		var currentGroupName = document.Sound.currentSelection["groupName"];
		document.Sound.currentSelection["sampleName"] = document.Sound.sounds[currentGroupName][$(this).attr('value')]["name"];
		document.Sound.sounds[currentGroupName][$(this).attr('value')]["buzzObject"].play();
		var s = document.Sound.sounds[currentGroupName][$(this).attr('value')]["buzzObject"]
		//save last played(on klick) sound in array
		module.theSounds.push(s);
	};

	var init = function () {

		// init interface for sound selection
		var selected = " selected";
		$.each(document.Sound.sounds, function (groupName, samples) {
			$('select#banch-select').append('<option value="' + groupName + '"' + selected + '>' + groupName + '</option>');
			selected = ""; // only add selected attribute to first option
		});

		updateSoundList();

		// assign event handlers
		$('select#banch-select').change(updateSoundList);

		/*
		 *menu click events
		 */

		$('#loopToggle').click(function (e) {
			document.graph.setLoopFlag();
			$('#loopOn, #loopOff').toggle();
		});

		$('#soundToggle').click(function (e) {
			$('#soundOn, #soundOff').toggle();
			document.Sound.toggleSound();
		});

		$('#clear').click(function (e) {
			console.log("clear");
			document.graph.clear();
		});

		// show short instructions on mouse move
		var instrFlag = false;
		$("body").hover(function() {
			if(instrFlag == false) {
				$("#instructionText").fadeIn("normal");
		           instrFlag = true;
		        }
		    });
		$("rect").mousedown(function() {
		        if(instrFlag == true) {
					$("#instructionText").fadeOut("normal");
		            //instrFlag = false;
		        }
		    });
		/*
		 * popup for info
		 */
		var popupFlag = false;
			$("#info").click(function() {
		        if(popupFlag == false) {
		            $("#popup").fadeIn("normal");
		            popupFlag = true;
		        }
				return false;
		    });
		 	//close popup, set msg object to the left side
		    $(".schliessen").click(function() {
		        if(popupFlag == true) {
					$("#popup").fadeOut("normal");
		            $("#popupHintergrund").fadeOut("normal");
		            popupFlag = false;
		            $("#msg").makeAbsolute(true, 10, 90);
		        }
		    });

	};

    module.init = init;
    return module;
})();<commit_msg>upon reload or batch select, first sound is selected automatically; red hightlighting for sounds now permanent<commit_after>// immediate function
document.UI = (function () {

	// module object; add all methods and properties that should be visible globally
    var module = {};

	var updateSoundList = function () {

		$('ul#sound-list').empty();
		var groupName = $('select#banch-select').find(':selected').attr('value');
		$(document.Sound.sounds[groupName]).each(function (sampleCounter, sample) {
			$('ul#sound-list').append('
' + sample["name"] + '
');
		});
		$('.sound-item').click(soundClickHandler);
		document.Sound.currentSelection["groupName"] = groupName;

		// select and highlight first sound
		soundClickHandler.call($('.sound-item[value=0]'));
	};

	var highlightSelection = function (elementToHighlight) {
		$('#sound-list').children().each(function (counter, element) {
			$(element).css("color", "white");
		});
		$(elementToHighlight).css("color", "red");
	};

	var soundClickHandler = function () {
		var currentGroupName = document.Sound.currentSelection["groupName"];
		document.Sound.currentSelection["sampleName"] = document.Sound.sounds[currentGroupName][$(this).attr('value')]["name"];
		document.Sound.sounds[currentGroupName][$(this).attr('value')]["buzzObject"].play();
		var s = document.Sound.sounds[currentGroupName][$(this).attr('value')]["buzzObject"];

		highlightSelection(this);
	};

	var init = function () {

		// init interface for sound selection
		var selected = " selected";
		$.each(document.Sound.sounds, function (groupName, samples) {
			$('select#banch-select').append('<option value="' + groupName + '"' + selected + '>' + groupName + '</option>');
			selected = ""; // only add selected attribute to first option
		});

		updateSoundList();

		// assign event handlers
		$('select#banch-select').change(updateSoundList);

		/*
		 *menu click events
		 */

		$('#loopToggle').click(function (e) {
			document.graph.setLoopFlag();
			$('#loopOn, #loopOff').toggle();
		});

		$('#soundToggle').click(function (e) {
			$('#soundOn, #soundOff').toggle();
			document.Sound.toggleSound();
		});

		$('#clear').click(function (e) {
			console.log("clear");
			document.graph.clear();
		});

		// show short instructions on mouse move
		var instrFlag = false;
		$("body").hover(function() {
			if(instrFlag == false) {
				$("#instructionText").fadeIn("normal");
		           instrFlag = true;
		        }
		    });
		$("rect").mousedown(function() {
		        if(instrFlag == true) {
					$("#instructionText").fadeOut("normal");
		            //instrFlag = false;
		        }
		    });
		/*
		 * popup for info
		 */
		var popupFlag = false;
			$("#info").click(function() {
		        if(popupFlag == false) {
		            $("#popup").fadeIn("normal");
		            popupFlag = true;
		        }
				return false;
		    });
		 	//close popup, set msg object to the left side
		    $(".schliessen").click(function() {
		        if(popupFlag == true) {
					$("#popup").fadeOut("normal");
		            $("#popupHintergrund").fadeOut("normal");
		            popupFlag = false;
		            $("#msg").makeAbsolute(true, 10, 90);
		        }
		    });

	};

    module.init = init;
    return module;
})();<|endoftext|>


<commit_before>var Jabaku = (function(module) {
	'use strict';

	function Entity(entitySystem, debugName) {
		this._debugName = debugName;
		this._entitySystem = entitySystem;
		this._components = {};
	}
	Entity.extends(Object, {
		get debugName() {
			return this._debugName;
		},
		get: function(componentConstructor) {
			return this._components[componentConstructor.type];
		},
		add: function(component) {
			this._components[component.type] = component;
			this._entitySystem.onComponentAdded(this, component);
		},
		remove: function(componentConstructor) {
			if (componentConstructor.type in this._components) {
				var component = this._components[componentConstructor.type];
				delete this._components[componentConstructor.type];
				this._entitySystem.onComponentRemoved(this, component);
			}
		},
		contains: function(componentConstructor) {
			return (componentConstructor.type in this._components);
		}
	});

	function EntitySystem() {
		this._systems = [];
	}
	EntitySystem.extends(Object, {
		newEntity: function(debugName) {
			return new Entity(this, debugName);
		},
		registerSystem: function(system) {
			this._systems.push(system);
		},
		onComponentAdded: function(entity) {
			for (var i = 0; i < this._systems.length; ++i) {
				this._systems[i].onComponentAdded(entity);
			}
		},
		onComponentRemoved: function(entity) {
			for (var i = 0; i < this._systems.length; ++i) {
				this._systems[i].onComponentRemoved(entity);
			}
		}
	});

	module.EntitySystem = EntitySystem;
	return module;
})(Jabaku || {});
<commit_msg>Added safety checks in the entity object<commit_after>var Jabaku = (function(module) {
	'use strict';

	function Entity(entitySystem, debugName) {
		this._debugName = debugName;
		this._entitySystem = entitySystem;
		this._components = {};
	}
	Entity.extends(Object, {
		get debugName() {
			return this._debugName;
		},
		get: function(componentConstructor) {
			if (componentConstructor.type === undefined) {
				throw new Error(componentConstructor.name + ' is not a component!');
			}

			return this._components[componentConstructor.type];
		},
		add: function(component) {
			if (component.type === undefined) {
				throw new Error(component.constructor.name + ' is not a component!');
			}

			this._components[component.type] = component;
			this._entitySystem.onComponentAdded(this, component);
		},
		remove: function(componentConstructor) {
			if (componentConstructor.type === undefined) {
				throw new Error(componentConstructor.name + ' is not a component!');
			}

			if (componentConstructor.type in this._components) {
				var component = this._components[componentConstructor.type];
				delete this._components[componentConstructor.type];
				this._entitySystem.onComponentRemoved(this, component);
			}
		},
		contains: function(componentConstructor) {
			if (componentConstructor.type === undefined) {
				throw new Error(componentConstructor.name + ' is not a component!');
			}

			return (componentConstructor.type in this._components);
		}
	});

	function EntitySystem() {
		this._systems = [];
	}
	EntitySystem.extends(Object, {
		newEntity: function(debugName) {
			return new Entity(this, debugName);
		},
		registerSystem: function(system) {
			this._systems.push(system);
		},
		onComponentAdded: function(entity) {
			for (var i = 0; i < this._systems.length; ++i) {
				this._systems[i].onComponentAdded(entity);
			}
		},
		onComponentRemoved: function(entity) {
			for (var i = 0; i < this._systems.length; ++i) {
				this._systems[i].onComponentRemoved(entity);
			}
		}
	});

	module.EntitySystem = EntitySystem;
	return module;
})(Jabaku || {});
<|endoftext|>


<commit_before>function main() {

    var SLACK_URL = 'https://hooks.slack.com/services/xxxxxxxx/zzzzzzzz/yyyyyyyy';
    var SCRIPT_LABEL = 'Budget_Control';

    // ===================================================================

    ensureAccountLabels(); // Проверяем и создаем ярлык

    var campaignSelector = AdWordsApp.campaigns()
        .withCondition('LabelNames CONTAINS_ANY ["' + SCRIPT_LABEL + '"]');
    var campaignIterator = campaignSelector.get();
    while (campaignIterator.hasNext()) {
        var campaign = campaignIterator.next();
        var budget = campaign.getBudget();
        var stats = campaign.getStatsFor('TODAY');
        var cost = parseFloat(stats.getCost()).toFixed(2);
        if (budget.isExplicitlyShared() == true) {
            var budgetCampaignIterator = budget.campaigns().get();
            var allAssociatedCost = +0;
            while (budgetCampaignIterator.hasNext()) {
                var associatedCampaign = budgetCampaignIterator.next();
                // Logger.log(associatedCampaign.getName());
                var associatedCampaignStats = associatedCampaign.getStatsFor('TODAY');
                var associatedCost = associatedCampaignStats.getCost();
                // Logger.log('Budget spend: ' + associatedCost);
                allAssociatedCost = allAssociatedCost + +associatedCost;
            }
            allAssociatedCost = parseFloat(allAssociatedCost).toFixed(2)
            if (allAssociatedCost > budget.getAmount()) {
                if (campaign.isEnabled() == true) {
                    campaign.pause();
                    Logger.log('Campaign ' + campaign.getName() + ' paused');
                    Logger.log('Budget amount: ' + budget.getAmount());
                    Logger.log('Budget spend: ' + allAssociatedCost);
                    Logger.log('-------------------------------------------------');
                    var message = ':double_vertical_bar: В кампании ' + campaign.getName() + ', сегодня расход ' + allAssociatedCost + ' при бюджете ' + budget.getAmount() + '. Кампания остановлена. \n\n';
                    sendSlackMessage(message);
                }
            } else {
                if (campaign.isPaused() == true) {
                    campaign.enable();
                    Logger.log('Campaign ' + campaign.getName() + ' enabled');
                    Logger.log('Budget amount: ' + budget.getAmount());
                    Logger.log('Budget spend: ' + allAssociatedCost);
                    Logger.log('-------------------------------------------------');
                }
            }
        } else {
            if (cost > budget.getAmount()) {
                if (campaign.isEnabled() == true) {
                    campaign.pause();
                    Logger.log('Campaign ' + campaign.getName() + ' paused');
                    Logger.log('Budget amount: ' + budget.getAmount());
                    Logger.log('Budget spend: ' + cost);
                    Logger.log('-------------------------------------------------');
                    var message = ':double_vertical_bar: В кампании ' + campaign.getName() + ', сегодня расход ' + cost + ' при бюджете ' + budget.getAmount() + '. Кампания остановлена. \n\n';
                    sendSlackMessage(message);
                }
            } else {
                if (campaign.isPaused() == true) {
                    campaign.enable();
                    Logger.log('Campaign ' + campaign.getName() + ' enabled');
                    Logger.log('Budget amount: ' + budget.getAmount());
                    Logger.log('Budget spend: ' + cost);
                    Logger.log('-------------------------------------------------');
                }
            }
        }
    }

    function ensureAccountLabels() {
        function getAccountLabelNames() {
            var labelNames = [];
            var iterator = AdWordsApp.labels().get();
            while (iterator.hasNext()) {
                labelNames.push(iterator.next().getName());
            }
            return labelNames;
        }
        var labelNames = getAccountLabelNames();
        if (labelNames.indexOf(SCRIPT_LABEL) == -1) {
            AdWordsApp.createLabel(SCRIPT_LABEL);
        }
    }

    function sendSlackMessage(text, opt_channel) {
        var slackMessage = {
            text: text,
            icon_url: 'https://www.gstatic.com/images/icons/material/product/1x/adwords_64dp.png',
            username: 'AdWords Scripts',
            channel: opt_channel || '#adwords'
        };

        var options = {
            method: 'POST',
            contentType: 'application/json',
            payload: JSON.stringify(slackMessage)
        };
        UrlFetchApp.fetch(SLACK_URL, options);
    }
}
<commit_msg>Update Budget_Control.js<commit_after>function main() {

    var CONFIG = {
        SLACK_URL: 'https://hooks.slack.com/services/xxxxxxxx/zzzzzzzz/yyyyyyyy',
        // Вебхук для Слака

        SCRIPT_LABEL: 'Budget_Control'
        // Следим за кампаниями помеченными этим ярлыком
    };

    // ===================================================================

    ensureAccountLabels(); // Проверяем и создаем ярлык

    var campaignSelector = AdWordsApp.campaigns()
        .withCondition('LabelNames CONTAINS_ANY ["' + CONFIG.SCRIPT_LABEL + '"]');
    var campaignIterator = campaignSelector.get();
    while (campaignIterator.hasNext()) {
        var campaign = campaignIterator.next();
        var budget = campaign.getBudget();
        var stats = campaign.getStatsFor('TODAY');
        var cost = parseFloat(stats.getCost()).toFixed(2);
        if (budget.isExplicitlyShared() == true) {
            var budgetCampaignIterator = budget.campaigns().get();
            var allAssociatedCost = +0;
            while (budgetCampaignIterator.hasNext()) {
                var associatedCampaign = budgetCampaignIterator.next();
                var associatedCampaignStats = associatedCampaign.getStatsFor('TODAY');
                var associatedCost = associatedCampaignStats.getCost();
                allAssociatedCost = allAssociatedCost + +associatedCost;
            }
            allAssociatedCost = parseFloat(allAssociatedCost).toFixed(2)
            if (allAssociatedCost > budget.getAmount()) {
                if (campaign.isEnabled() == true) {
                    campaign.pause();
                    Logger.log('Campaign ' + campaign.getName() + ' paused');
                    Logger.log('Budget amount: ' + budget.getAmount());
                    Logger.log('Budget spend: ' + allAssociatedCost);
                    Logger.log('-------------------------------------------------');
                    var message = ':double_vertical_bar: В кампании ' + campaign.getName() + ', сегодня расход ' + allAssociatedCost + ' при бюджете ' + budget.getAmount() + '. Кампания остановлена. \n\n';
                    sendSlackMessage(message);
                }
            } else {
                if (campaign.isPaused() == true) {
                    campaign.enable();
                    Logger.log('Campaign ' + campaign.getName() + ' enabled');
                    Logger.log('Budget amount: ' + budget.getAmount());
                    Logger.log('Budget spend: ' + allAssociatedCost);
                    Logger.log('-------------------------------------------------');
                }
            }
        } else {
            if (cost > budget.getAmount()) {
                if (campaign.isEnabled() == true) {
                    campaign.pause();
                    Logger.log('Campaign ' + campaign.getName() + ' paused');
                    Logger.log('Budget amount: ' + budget.getAmount());
                    Logger.log('Budget spend: ' + cost);
                    Logger.log('-------------------------------------------------');
                    var message = ':double_vertical_bar: В кампании ' + campaign.getName() + ', сегодня расход ' + cost + ' при бюджете ' + budget.getAmount() + '. Кампания остановлена. \n\n';
                    sendSlackMessage(message);
                }
            } else {
                if (campaign.isPaused() == true) {
                    campaign.enable();
                    Logger.log('Campaign ' + campaign.getName() + ' enabled');
                    Logger.log('Budget amount: ' + budget.getAmount());
                    Logger.log('Budget spend: ' + cost);
                    Logger.log('-------------------------------------------------');
                }
            }
        }
    }

    function ensureAccountLabels() {
        function getAccountLabelNames() {
            var labelNames = [];
            var iterator = AdWordsApp.labels().get();
            while (iterator.hasNext()) {
                labelNames.push(iterator.next().getName());
            }
            return labelNames;
        }
        var labelNames = getAccountLabelNames();
        if (labelNames.indexOf(CONFIG.SCRIPT_LABEL) == -1) {
            AdWordsApp.createLabel(CONFIG.SCRIPT_LABEL);
        }
    }

    function sendSlackMessage(text, opt_channel) {
        var slackMessage = {
            text: text,
            icon_url: 'https://www.gstatic.com/images/icons/material/product/1x/adwords_64dp.png',
            username: 'AdWords Scripts',
            channel: opt_channel || '#adwords'
        };

        var options = {
            method: 'POST',
            contentType: 'application/json',
            payload: JSON.stringify(slackMessage)
        };
        UrlFetchApp.fetch(CONFIG.SLACK_URL, options);
    }
}
<|endoftext|>


<commit_before>/* Example definition of a simple mode that understands a subset of
 * JavaScript:
 */
var CodeMirror = require('./codemirror.js');

CodeMirror.defineSimpleMode("gcode", {
  // The start state contains the rules that are intially used
  start: [
    {regex: /\([^\)]*\)/i, token: "comment"},
    {regex: /[GM]\d+/i, token: "keyword"},
    // You can match multiple tokens at once. Note that the captured
    // groups must span the whole string in this case
    {regex: /([A-FH-LN-Z])([+\-]?[0-9]+(?:\.[0-9]+)?)/i,
     token: ["variable", "number"]},
    {regex: /\?.*/, token: "comment"},
    {regex: /[^\w\s]/, token: "error"}
  ],
  // The meta property contains global information about the mode. It
  // can contain properties like lineComment, which are supported by
  // all modes, and also directives like dontIndentStates, which are
  // specific to simple modes.
  meta: {
    dontIndentStates: ["comment"],
    lineComment: "?"
  }
});

var CMD_REGEX = /^[A-Z](?:[A-Z]|[0-9]+|C\#)\b/i
var LINENO_REGEX = /^N[0-9]+\b/i
var LABEL_REGEX = /^[A-Z_][A-Z0-9_]*\:/i
var WORD_REGEX = /^[A-Z_][A-Z0-9_]*/i
var STRING_REGEX = /^"(?:[^\\]|\\.)*?"/
var NUMBER_REGEX = /^0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/i
var SYS_VAR_REGEX = /^\%\([ \t]*[0-9]+[ \t]*\)/i
var USR_VAR_REGEX = /^\&[A-Z_][A-Z0-9_]*/i
var PERSIST_VAR_REGEX = /^\$[A-Z_][A-Z0-9_]*/i

var BARE_REGEX = /^[IOT]/i
var COMMENT_REGEX = /^'.*/i
var OPERATOR_REGEX = /^[\+\-\*\/\^\!\(\)\=\>\<|\=\:]/i

function matchExpression(stream) {
  if(stream.match(SYS_VAR_REGEX)) {
    return "variable";
  }
  if(stream.match(USR_VAR_REGEX)) {
    return "variable-2";
  }
  if(stream.match(PERSIST_VAR_REGEX)) {
    return "variable-3";
  }
  if(stream.match(NUMBER_REGEX)) {
    return "number";
  }
  if(stream.match(STRING_REGEX)) {
    return "string";
  }
  if(stream.match(OPERATOR_REGEX)) {
    return "operator";
  }
  return null;
}

function matchArgument(stream) {
  var match = matchExpression(stream);
  if(match) { return match; }
  if(stream.match(BARE_REGEX)) { return "atom"; }
  return null;
}

CodeMirror.defineMode("opensbp", function() {
  return {
    startState: function() {
      return {
        name : "sol",
      }
    },

    token: function(stream, state) {
      if(stream.sol()) {
        state.name = "sol";
      }

      if(stream.eatSpace()) {
        return null;
      }
      if(stream.eat("'")) {
        stream.skipToEnd();
        return 'comment';
      }
      switch(state.name) {
        case "sol":
          if(stream.eatSpace()) {
            return null;
          }

          // Line Comment
          if(stream.match(COMMENT_REGEX)) {
            return "comment";
          }

          // ON INPUT statement
          if(stream.match("ON")) {
            state.name = "on";
            return "keyword";
          }

          // LHS of an assignment
          if(stream.match(SYS_VAR_REGEX)) {
            state.name = "assign";
            return "variable";
          }

          if(stream.match(USR_VAR_REGEX)) {
            state.name = "assign";
            return "variable-2";
          }

          if(stream.match(PERSIST_VAR_REGEX)) {
            state.name = "assign";
            return "variable-3";
          }

          // Label (for GOTOs)
          if(stream.match(LABEL_REGEX)) {
            return "property";
          }

          if(stream.match(/^IF/i)) {
            state.name = "test";
            return "keyword"
          }

          if(stream.match(LINENO_REGEX)) {
          	state.name = "gcode";
          	return "property";
          }
          // Command mnemonic
          if(stream.match(CMD_REGEX)) {
            state.name = "args";
            return "keyword";
          }

          // Pause command
          if(stream.match(/^PAUSE\s*,?\s*/i)) {
            state.name = "pause";
            return "keyword"
          }

          // Pause command
          if(stream.match(/^FAIL/i)) {
            state.name = "fail";
            return "keyword"
          }

          // Goto commands
          if(stream.match(/^GOTO|GOSUB/i)) {
            state.name = "goto";
            return "keyword"
          }

          // Singles
          if(stream.match(/^RETURN|END/i)) {
            state.name = "single";
            return "keyword";
          }
          //
          stream.skipToEnd();
        break;

        case "single":

        break;

        case "args":
          if(stream.eat(',')) {
            return null
          }
          var match = matchArgument(stream);
          if(match) { return match; }

        break;

        case "assign":
          var match = matchExpression(stream);
          if(match) { return match;}
          stream.skipToEnd();
          return 'string';

        break;

        case "test":
          var match = matchExpression(stream);
          if(match) { return match;}
          if(stream.match(/^THEN/i)) {
            return "keyword";
          }
          if(stream.match(/^GOTO|GOSUB/i)) {
            state.name = "goto"
            return "keyword";
          }
          if(stream.match(LABEL_REGEX)) {
            return "property";
          }
        break;

        case "goto":
          if(stream.match(WORD_REGEX)) {
            state.name = "sol"
            return "property"
          }
        break;

        case "on":
          if(stream.eat(',')) {
            return null;
          }
          if(stream.match(/INP(?:UT)?/i)) {
            return "keyword";
          }
          if(stream.match(/(?:GOTO)|(?:GOSUB)/i)) {
            state.name = "goto"
            return "keyword";
          }
          if(stream.match(/\(|\)/)) {
            return "operator";
          }
          if(stream.match(/\d+/)) {
            return "number";
          }
          break;

        case "pause":
          if(stream.eatSpace()) {
            return null;
          }

          var match = matchExpression(stream);
          if(match) { return match; }

          break;

        case "fail":
          if(stream.eatSpace()) {
            return null;
          }

          var match = matchExpression(stream);
          if(match) { return match; }

          break;

        default:
          console.error("Unknown state: ", state)
        break;

        case "gcode":
        	stream.skipToEnd();
        	return null;
        break;
      }

      stream.next();
      return "error";

    }
  }
});
CodeMirror.defineMIME("text/x-opensbp","opensbp")

/*

CodeMirror.defineSimpleMode("opensbp", {
  // The start state contains the rules that are intially used
  start: [
    {regex: /\s*[A-Z](?:[A-Z]|[0-9]+|\#)\b/i, token: "keyword", next:"args", sol: true},
    {regex: /PAUSE/i, token: "keyword", next:"args"},

    // You can match multiple tokens at once. Note that the captured
    // groups must span the whole string in this case
    //{regex: /([A-FH-LN-Z])([+\-]?[0-9]+(?:\.[0-9]+)?)/i,
    // token: ["variable", "number"]},
    {regex: /\'., token: "comment"},
  ],

  args: [
    {regex: /,/i, token: "operator"},
    {regex: /"(?:[^\\]|\\.)*?"/, token: "string"},
    {regex: /[+\-]?[0-9]+(?:\.[0-9]+)?/i, token: "number"},
    {regex: /[^\t ,]/, next: "start"}
  ],
  // The meta property contains global information about the mode. It
  // can contain properties like lineComment, which are supported by
  // all modes, and also directives like dontIndentStates, which are
  // specific to simple modes.
  meta: {
    dontIndentStates: ["comment"],
    lineComment: "'"
  }
});*/
<commit_msg>refs #48672 fix code error highlight for pause.<commit_after>/* Example definition of a simple mode that understands a subset of
 * JavaScript:
 */
var CodeMirror = require('./codemirror.js');

CodeMirror.defineSimpleMode("gcode", {
  // The start state contains the rules that are intially used
  start: [
    {regex: /\([^\)]*\)/i, token: "comment"},
    {regex: /[GM]\d+/i, token: "keyword"},
    // You can match multiple tokens at once. Note that the captured
    // groups must span the whole string in this case
    {regex: /([A-FH-LN-Z])([+\-]?[0-9]+(?:\.[0-9]+)?)/i,
     token: ["variable", "number"]},
    {regex: /\?.*/, token: "comment"},
    {regex: /[^\w\s]/, token: "error"}
  ],
  // The meta property contains global information about the mode. It
  // can contain properties like lineComment, which are supported by
  // all modes, and also directives like dontIndentStates, which are
  // specific to simple modes.
  meta: {
    dontIndentStates: ["comment"],
    lineComment: "?"
  }
});

var CMD_REGEX = /^[A-Z](?:[A-Z]|[0-9]+|C\#)\b/i
var LINENO_REGEX = /^N[0-9]+\b/i
var LABEL_REGEX = /^[A-Z_][A-Z0-9_]*\:/i
var WORD_REGEX = /^[A-Z_][A-Z0-9_]*/i
var STRING_REGEX = /^"(?:[^\\]|\\.)*?"/
var NUMBER_REGEX = /^0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/i
var SYS_VAR_REGEX = /^\%\([ \t]*[0-9]+[ \t]*\)/i
var USR_VAR_REGEX = /^\&[A-Z_][A-Z0-9_]*/i
var PERSIST_VAR_REGEX = /^\$[A-Z_][A-Z0-9_]*/i

var BARE_REGEX = /^[IOT]/i
var COMMENT_REGEX = /^'.*/i
var OPERATOR_REGEX = /^[\+\-\*\/\^\!\(\)\=\>\<|\=\:]/i

function matchExpression(stream) {
  if(stream.match(SYS_VAR_REGEX)) {
    return "variable";
  }
  if(stream.match(USR_VAR_REGEX)) {
    return "variable-2";
  }
  if(stream.match(PERSIST_VAR_REGEX)) {
    return "variable-3";
  }
  if(stream.match(NUMBER_REGEX)) {
    return "number";
  }
  if(stream.match(STRING_REGEX)) {
    return "string";
  }
  if(stream.match(OPERATOR_REGEX)) {
    return "operator";
  }
  return null;
}

function matchArgument(stream) {
  var match = matchExpression(stream);
  if(match) { return match; }
  if(stream.match(BARE_REGEX)) { return "atom"; }
  return null;
}

CodeMirror.defineMode("opensbp", function() {
  return {
    startState: function() {
      return {
        name : "sol",
      }
    },

    token: function(stream, state) {
      if(stream.sol()) {
        state.name = "sol";
      }

      if(stream.eatSpace()) {
        return null;
      }
      if(stream.eat("'")) {
        stream.skipToEnd();
        return 'comment';
      }
      switch(state.name) {
        case "sol":
          if(stream.eatSpace()) {
            return null;
          }

          // Line Comment
          if(stream.match(COMMENT_REGEX)) {
            return "comment";
          }

          // ON INPUT statement
          if(stream.match("ON")) {
            state.name = "on";
            return "keyword";
          }

          // LHS of an assignment
          if(stream.match(SYS_VAR_REGEX)) {
            state.name = "assign";
            return "variable";
          }

          if(stream.match(USR_VAR_REGEX)) {
            state.name = "assign";
            return "variable-2";
          }

          if(stream.match(PERSIST_VAR_REGEX)) {
            state.name = "assign";
            return "variable-3";
          }

          // Label (for GOTOs)
          if(stream.match(LABEL_REGEX)) {
            return "property";
          }

          if(stream.match(/^IF/i)) {
            state.name = "test";
            return "keyword"
          }

          if(stream.match(LINENO_REGEX)) {
          	state.name = "gcode";
          	return "property";
          }
          // Command mnemonic
          if(stream.match(CMD_REGEX)) {
            state.name = "args";
            return "keyword";
          }

          // Pause command
          if(stream.match(/^PAUSE\s*/i)) {
            state.name = "args";
            return "keyword"
          }

          // Pause command
          if(stream.match(/^FAIL/i)) {
            state.name = "fail";
            return "keyword"
          }

          // Goto commands
          if(stream.match(/^GOTO|GOSUB/i)) {
            state.name = "goto";
            return "keyword"
          }

          // Singles
          if(stream.match(/^RETURN|END/i)) {
            state.name = "single";
            return "keyword";
          }
          //
          stream.skipToEnd();
        break;

        case "single":

        break;

        case "args":
          if(stream.eat(',')) {
            return null
          }
          var match = matchArgument(stream);
          if(match) { return match; }

        break;

        case "assign":
          var match = matchExpression(stream);
          if(match) { return match;}
          stream.skipToEnd();
          return 'string';

        break;

        case "test":
          var match = matchExpression(stream);
          if(match) { return match;}
          if(stream.match(/^THEN/i)) {
            return "keyword";
          }
          if(stream.match(/^GOTO|GOSUB/i)) {
            state.name = "goto"
            return "keyword";
          }
          if(stream.match(LABEL_REGEX)) {
            return "property";
          }
        break;

        case "goto":
          if(stream.match(WORD_REGEX)) {
            state.name = "sol"
            return "property"
          }
        break;

        case "on":
          if(stream.eat(',')) {
            return null;
          }
          if(stream.match(/INP(?:UT)?/i)) {
            return "keyword";
          }
          if(stream.match(/(?:GOTO)|(?:GOSUB)/i)) {
            state.name = "goto"
            return "keyword";
          }
          if(stream.match(/\(|\)/)) {
            return "operator";
          }
          if(stream.match(/\d+/)) {
            return "number";
          }
          break;

        case "pause":
          if(stream.eatSpace()) {
            return null;
          }

          var match = matchExpression(stream);
          if(match) { return match; }

          break;

        case "fail":
          if(stream.eatSpace()) {
            return null;
          }

          var match = matchExpression(stream);
          if(match) { return match; }

          break;

        default:
          console.error("Unknown state: ", state)
        break;

        case "gcode":
        	stream.skipToEnd();
        	return null;
        break;
      }

      stream.next();
      return "error";

    }
  }
});
CodeMirror.defineMIME("text/x-opensbp","opensbp")

/*

CodeMirror.defineSimpleMode("opensbp", {
  // The start state contains the rules that are intially used
  start: [
    {regex: /\s*[A-Z](?:[A-Z]|[0-9]+|\#)\b/i, token: "keyword", next:"args", sol: true},
    {regex: /PAUSE/i, token: "keyword", next:"args"},

    // You can match multiple tokens at once. Note that the captured
    // groups must span the whole string in this case
    //{regex: /([A-FH-LN-Z])([+\-]?[0-9]+(?:\.[0-9]+)?)/i,
    // token: ["variable", "number"]},
    {regex: /\'., token: "comment"},
  ],

  args: [
    {regex: /,/i, token: "operator"},
    {regex: /"(?:[^\\]|\\.)*?"/, token: "string"},
    {regex: /[+\-]?[0-9]+(?:\.[0-9]+)?/i, token: "number"},
    {regex: /[^\t ,]/, next: "start"}
  ],
  // The meta property contains global information about the mode. It
  // can contain properties like lineComment, which are supported by
  // all modes, and also directives like dontIndentStates, which are
  // specific to simple modes.
  meta: {
    dontIndentStates: ["comment"],
    lineComment: "'"
  }
});*/
<|endoftext|>


<commit_before>/* global _ */
'use strict';

angular.module('metadatamanagementApp').controller('ProjectCockpitController',
  function($q, $scope, $state, $location, $transitions, UserResource, Principal,
           PageTitleService, LanguageService, ToolbarHeaderService,
           DataAcquisitionProjectResource, SimpleMessageToastService,
           CurrentProjectService, projectDeferred, CommonDialogsService,
           SearchDao, $translate, $mdDialog) {

    PageTitleService.setPageTitle(
      'data-acquisition-project-management.project-cockpit.title');
    ToolbarHeaderService.updateToolbarHeader({
      stateName: $state.current.name
    });

    var registerConfirmOnDirtyHook = function() {
      var unregisterTransitionHook = $transitions.onBefore({}, function() {
        if ($scope.changed) {
          return CommonDialogsService.showConfirmOnDirtyDialog();
        }
      });

      $scope.$on('$destroy', unregisterTransitionHook);
    };

    var setProjectRequirementsDisabled = function(project) {
      var loginName = Principal.loginName();
      var publishers = _.get(project, 'configuration.publishers');
      var result;
      if (_.isArray(publishers)) {
        result = publishers.indexOf(loginName) === -1;
      } else {
        result = false;
      }
      $scope.isProjectRequirementsDisabled = result;
      return result;
    };

    var setAssignedToProject = function() {
      var name = Principal.loginName();
      $scope.isAssignedToProject =
        !!_.find($scope.activeUsers.publishers, function(o) {
          return o.login === name;
        }) || !!_.find($scope.activeUsers.dataProviders, function(o) {
          return o.login === name;
        });
    };

    var requiredTypesWatch;

    $state.loadStarted = true;

    $scope.$on('current-project-changed',
      function(event, changedProject) { // jshint ignore:line
        if (changedProject) {
          $location.url('/' + LanguageService.getCurrentInstantly() +
            '/projects/' + changedProject.id);
        }
      });

    var saveProject = function(project) {
      return DataAcquisitionProjectResource.save(
        project,
        //Success
        function() {
          $scope.changed = false;
          $scope.project = project;
          setAssignedToProject();
          CurrentProjectService.setCurrentProject($scope.project);
          SimpleMessageToastService
            .openSimpleMessageToast(
              'data-acquisition-project-management.log-messages.' +
              'data-acquisition-project.saved', {
                id: $scope.project.id
              });
        },
        //Server Error
        function(response) {
          var errors = _.get(response, 'data.errors');

          if (errors) {
            errors.forEach(function(error) {
              SimpleMessageToastService.openAlertMessageToast(error.message);
            });
          }
        }
      );
    };

    var showAssigneeGroupMessageDialog = function() {
      var currentProject = CurrentProjectService.getCurrentProject();
      var assigneeGroup = _.get(currentProject, 'assigneeGroup');
      var recipient;

      switch (assigneeGroup) {
        case 'PUBLISHER':
          recipient = $translate.instant('data-acquisition' +
            '-project-management.project-cockpit.label.ROLE_PUBLISHER');
          break;
        case 'DATA_PROVIDER':
          recipient = $translate.instant('data-acquisition' +
            '-project-management.project-cockpit.label.ROLE_DATA_PROVIDER');
          break;
        default:
          recipient = '';
      }

      return $mdDialog.show({
        controller: 'AssigneeMessageDialogController',
        templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
          'assignee-message-dialog.html.tmpl',
        locals: {
          recipient: recipient
        }
      });
    };

    var prepareProjectForSave = function(assigneeGroupMessage,
                                         newAssigneeGroup) {

      var project = _.assignIn({}, $scope.project);

      if (!project.configuration) {
        $scope.project.configuration = {};
      }

      var configuredPublishers = $scope.activeUsers.publishers
        .map(function(identity) {
          return identity.login;
        });

      var configuredDataProviders = $scope.activeUsers.dataProviders
        .map(function(identity) {
          return identity.login;
        });

      if (project.configuration.publishers) {
        project.configuration.publishers =
          _.union(project.configuration.publishers, configuredPublishers);
      } else {
        project.configuration.publishers = configuredPublishers;
      }

      if (project.configuration.dataProviders) {
        project.configuration.dataProviders =
          _.union(project.configuration.dataProviders,
            configuredDataProviders);
      } else {
        project.configuration.dataProviders = configuredDataProviders;
      }

      if (assigneeGroupMessage) {
        project.lastAssigneeGroupMessage = assigneeGroupMessage;
      }

      if (newAssigneeGroup) {
        project.assigneeGroup = newAssigneeGroup;
      }

      return project;
    };

    $scope.onSaveChangesAndAssign = function() {
      showAssigneeGroupMessageDialog().then(function(message) {
        var newAssigneeGroup;

        switch ($scope.project.assigneeGroup) {
          case 'DATA_PROVIDER':
            newAssigneeGroup = 'PUBLISHER';
            break;
          case 'PUBLISHER':
            newAssigneeGroup = 'DATA_PROVIDER';
            break;
          default:
            newAssigneeGroup = $scope.project.assigneeGroup;
        }

        var project = prepareProjectForSave(message, newAssigneeGroup);
        saveProject(project);
      });
    };

    $scope.onSaveChanges = function(origin) {
      var project = prepareProjectForSave();
      saveProject(project).$promise.then(function() {
        if (origin !== 'requirements') {
          $state.reload();
        }
      });
    };

    $scope.changed = false;

    $scope.searchText = {
      publishers: '',
      dataProviders: ''
    };

    $scope.selectedUser = {
      publishers: null,
      dataProviders: null
    };

    $scope.selectedUserChanged = function(user, role) {
      if (user) {
        $scope.activeUsers[role].push(user);
        $scope.changed = true;
        $scope.searchText[role] = '';
        $scope.selectedUser[role] = null;
        $state.searchCache[role] = {};
      }
    };

    $scope.activeUsers = {
      publishers: [],
      dataProviders: []
    };

    $scope.fetching = false;

    $scope.advancedPrivileges = Principal.hasAnyAuthority(['ROLE_PUBLISHER',
      'ROLE_ADMIN']);
    $scope.isPublisher = Principal.hasAnyAuthority(['ROLE_PUBLISHER']);
    $scope.isDataProvider = Principal.hasAnyAuthority(['ROLE_DATA_PROVIDER']);
    $scope.isAssignedToProject = false;

    // load all users assigned to the currrent project
    projectDeferred.promise.then(
      function(project) {
        $scope.project = project;
        $scope.fetching = true;

        var isProjectRequirementsDisabled =
          setProjectRequirementsDisabled(project);
        CurrentProjectService.setCurrentProject(project);

        if (requiredTypesWatch) {
          requiredTypesWatch();
        }

        if (!isProjectRequirementsDisabled &&
          project.configuration.requirements) {
          $scope.$watch(function() {
            return $scope.project.configuration.requirements;
          }, function(newVal, oldVal) {
            if (newVal !== oldVal && !$scope.changed) {
              $scope.changed = true;
            }
          }, true);
        }

        function getAndAddUsers(key) {
          // get users of type {key} asynchronously
          // and return promise resolving when all are fetched
          if (project.configuration[key]) {
            return $q.all(
              project.configuration[key].map(function(userLogin) {
                return (
                  UserResource.getPublic({
                    login: userLogin
                  }).$promise.then(function(userResult) {
                    if (!_.includes($scope.activeUsers[key].map(function(u) {
                      return u.login;
                    }), userResult.login)) {
                      $scope.activeUsers[key].push(userResult);
                    }
                  })
                );
              })
            );
          } else {
            return $q.resolve([]);
          }
        }

        $q.resolve($q.all([
          getAndAddUsers('publishers'),
          getAndAddUsers('dataProviders')
        ])).then(function() {
          $scope.fetching = false;
          setAssignedToProject();
        }).catch(function(error) {
          SimpleMessageToastService
            .openAlertMessageToast(
              'global.error.server-error.internal-server-error', {
                status: error.data.error_description
              });
        });
        registerConfirmOnDirtyHook();
      }).finally(function() {
      $scope.loadStarted = false;
    });

    $scope.canDeleteUser = function(user, role) {
      if (user.restricted) {
        // cannot modify user whose details we can't read
        return false;
      }
      if (!$scope.advancedPrivileges && role === 'publishers') {
        // cannot remove publishers without advanced privilege
        return false;
      }
      if ($scope.activeUsers[role].length <= 1) {
        // cannot remove the last user in this list
        return false;
      }
      return true;
    };

    $state.currentPromise = null;
    $state.searchCache = {
      publishers: {},
      dataProviders: {}
    };
    var internalRoles = {
      'publishers': 'ROLE_PUBLISHER',
      'dataProviders': 'ROLE_DATA_PROVIDER'
    };
    $scope.searchUsers = function(search, role) {
      var roleInternal = internalRoles[role];
      if (!$state.loadComplete) {
        return [];
      }
      if ($state.searchCache[role][search]) {
        return $state.searchCache[role][search];
      }
      if (!$state.currentPromise) {
        $state.currentPromise = UserResource.search({
          login: search,
          role: roleInternal
        }).$promise.then(function(result) {
          $state.currentPromise = null;
          var results = result.filter(function(x) {
            // filter out already added users
            return $scope.activeUsers[role].map(function(u) {
              return u.login;
            }).indexOf(x.login) < 0 && _.includes(x.authorities, roleInternal);
          });
          $state.searchCache[role][search] = results;
          return results;
        });
      }
      return $state.currentPromise;
    };
    $scope.searchProjectData = function(group) {
      return SearchDao.search('', 0, $scope.project.id, '', group, 1, '');
    };

    $scope.removeUser = function(user, role) {
      $scope.changed = true;
      $scope.activeUsers[role] = $scope.activeUsers[role]
        .filter(function(item) {
          return item.login !== user.login;
        });
      $state.searchCache[role] = {};
    };

    $scope.shareButtonShown = false;
    $scope.onTabSelect = function(tab) {
      if (tab === 'config') {
        $scope.shareButtonShown = false;
      } else if (tab === 'status') {
        $scope.shareButtonShown = true;
      }
    };

    $scope.setChanged = function(changed) {
      if (changed === undefined) {
        changed = true;
      }
      $scope.changed = changed;
    };

    $state.loadComplete = true;
  }).directive('projectCockpitConfig', function() {
  return {
    restrict: 'E',
    templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
      'project-cockpit-config.html.tmpl'
  };
}).directive('projectCockpitStatus', function() {
  return {
    restrict: 'E',
    templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
      'project-cockpit-status.html.tmpl'
  };
}).directive('projectCockpitUserlist', function() {
  return {
    restrict: 'E',
    templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
      'project-cockpit-userlist.html.tmpl',
    scope: true,
    link: function(scope, elem, attrs) { // jshint ignore:line
      scope.group = attrs.group;
    }
  };
}).directive('projectCockpitAssignment', function($state) {
  return {
    restrict: 'E',
    templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
      'project-cockpit-assignment.html.tmpl',
    scope: true,
    replace: true,
    link: function(scope, elem, attrs) { // jshint ignore:line
      var elasticSearchType = {
        studies: 'studies',
        surveys: 'surveys',
        instruments: 'instruments',
        questions: 'questions',
        dataSets: 'data_sets',
        variables: 'variables'
      };
      scope.group = attrs.group;
      scope.create = function() {
        $state.go(attrs.createstate, {});
      };
      scope.count = null;
      scope.$watch(function() {
        return scope.project &&
        scope.project.configuration[attrs.group + 'State'] ?
          scope.project.configuration[attrs.group + 'State']
            .dataProviderReady : null;
      }, function(newVal, oldVal) {
        if (newVal !== oldVal) {
          scope.setChanged(true);
        }
      });
      scope.$watch(function() {
        return scope.project &&
        scope.project.configuration[attrs.group + 'State'] ?
          scope.project.configuration[attrs.group + 'State']
            .publisherReady : null;
      }, function(newVal, oldVal) {
        if (newVal !== oldVal) {
          scope.setChanged(true);
        }
      });

      scope.searchProjectData(
        elasticSearchType[attrs.group]
      ).then(function(data) {
        scope.count = data.hits.total;
      }).catch(function() {
        scope.count = 0;
      });

    }
  };
});
<commit_msg>#1844 Fix wrong recipient assignment;set fullscreen flag to true for assignee group message dialog<commit_after>/* global _ */
'use strict';

angular.module('metadatamanagementApp').controller('ProjectCockpitController',
  function($q, $scope, $state, $location, $transitions, UserResource, Principal,
           PageTitleService, LanguageService, ToolbarHeaderService,
           DataAcquisitionProjectResource, SimpleMessageToastService,
           CurrentProjectService, projectDeferred, CommonDialogsService,
           SearchDao, $translate, $mdDialog) {

    PageTitleService.setPageTitle(
      'data-acquisition-project-management.project-cockpit.title');
    ToolbarHeaderService.updateToolbarHeader({
      stateName: $state.current.name
    });

    var registerConfirmOnDirtyHook = function() {
      var unregisterTransitionHook = $transitions.onBefore({}, function() {
        if ($scope.changed) {
          return CommonDialogsService.showConfirmOnDirtyDialog();
        }
      });

      $scope.$on('$destroy', unregisterTransitionHook);
    };

    var setProjectRequirementsDisabled = function(project) {
      var loginName = Principal.loginName();
      var publishers = _.get(project, 'configuration.publishers');
      var result;
      if (_.isArray(publishers)) {
        result = publishers.indexOf(loginName) === -1;
      } else {
        result = false;
      }
      $scope.isProjectRequirementsDisabled = result;
      return result;
    };

    var setAssignedToProject = function() {
      var name = Principal.loginName();
      $scope.isAssignedToProject =
        !!_.find($scope.activeUsers.publishers, function(o) {
          return o.login === name;
        }) || !!_.find($scope.activeUsers.dataProviders, function(o) {
          return o.login === name;
        });
    };

    var requiredTypesWatch;

    $state.loadStarted = true;

    $scope.$on('current-project-changed',
      function(event, changedProject) { // jshint ignore:line
        if (changedProject) {
          $location.url('/' + LanguageService.getCurrentInstantly() +
            '/projects/' + changedProject.id);
        }
      });

    var saveProject = function(project) {
      return DataAcquisitionProjectResource.save(
        project,
        //Success
        function() {
          $scope.changed = false;
          $scope.project = project;
          setAssignedToProject();
          CurrentProjectService.setCurrentProject($scope.project);
          SimpleMessageToastService
            .openSimpleMessageToast(
              'data-acquisition-project-management.log-messages.' +
              'data-acquisition-project.saved', {
                id: $scope.project.id
              });
        },
        //Server Error
        function(response) {
          var errors = _.get(response, 'data.errors');

          if (errors) {
            errors.forEach(function(error) {
              SimpleMessageToastService.openAlertMessageToast(error.message);
            });
          }
        }
      );
    };

    var showAssigneeGroupMessageDialog = function() {
      var currentProject = CurrentProjectService.getCurrentProject();
      var assigneeGroup = _.get(currentProject, 'assigneeGroup');
      var recipient;

      switch (assigneeGroup) {
        case 'PUBLISHER':
          recipient = $translate.instant('data-acquisition' +
            '-project-management.project-cockpit.label.ROLE_DATA_PROVIDER');
          break;
        case 'DATA_PROVIDER':
          recipient = $translate.instant('data-acquisition' +
            '-project-management.project-cockpit.label.ROLE_PUBLISHER');
          break;
        default:
          recipient = '';
      }

      return $mdDialog.show({
        controller: 'AssigneeMessageDialogController',
        templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
          'assignee-message-dialog.html.tmpl',
        fullscreen: true,
        locals: {
          recipient: recipient
        }
      });
    };

    var prepareProjectForSave = function(assigneeGroupMessage,
                                         newAssigneeGroup) {

      var project = _.assignIn({}, $scope.project);

      if (!project.configuration) {
        $scope.project.configuration = {};
      }

      var configuredPublishers = $scope.activeUsers.publishers
        .map(function(identity) {
          return identity.login;
        });

      var configuredDataProviders = $scope.activeUsers.dataProviders
        .map(function(identity) {
          return identity.login;
        });

      if (project.configuration.publishers) {
        project.configuration.publishers =
          _.union(project.configuration.publishers, configuredPublishers);
      } else {
        project.configuration.publishers = configuredPublishers;
      }

      if (project.configuration.dataProviders) {
        project.configuration.dataProviders =
          _.union(project.configuration.dataProviders,
            configuredDataProviders);
      } else {
        project.configuration.dataProviders = configuredDataProviders;
      }

      if (assigneeGroupMessage) {
        project.lastAssigneeGroupMessage = assigneeGroupMessage;
      }

      if (newAssigneeGroup) {
        project.assigneeGroup = newAssigneeGroup;
      }

      return project;
    };

    $scope.onSaveChangesAndAssign = function() {
      showAssigneeGroupMessageDialog().then(function(message) {
        var newAssigneeGroup;

        switch ($scope.project.assigneeGroup) {
          case 'DATA_PROVIDER':
            newAssigneeGroup = 'PUBLISHER';
            break;
          case 'PUBLISHER':
            newAssigneeGroup = 'DATA_PROVIDER';
            break;
          default:
            newAssigneeGroup = $scope.project.assigneeGroup;
        }

        var project = prepareProjectForSave(message, newAssigneeGroup);
        saveProject(project);
      });
    };

    $scope.onSaveChanges = function(origin) {
      var project = prepareProjectForSave();
      saveProject(project).$promise.then(function() {
        if (origin !== 'requirements') {
          $state.reload();
        }
      });
    };

    $scope.changed = false;

    $scope.searchText = {
      publishers: '',
      dataProviders: ''
    };

    $scope.selectedUser = {
      publishers: null,
      dataProviders: null
    };

    $scope.selectedUserChanged = function(user, role) {
      if (user) {
        $scope.activeUsers[role].push(user);
        $scope.changed = true;
        $scope.searchText[role] = '';
        $scope.selectedUser[role] = null;
        $state.searchCache[role] = {};
      }
    };

    $scope.activeUsers = {
      publishers: [],
      dataProviders: []
    };

    $scope.fetching = false;

    $scope.advancedPrivileges = Principal.hasAnyAuthority(['ROLE_PUBLISHER',
      'ROLE_ADMIN']);
    $scope.isPublisher = Principal.hasAnyAuthority(['ROLE_PUBLISHER']);
    $scope.isDataProvider = Principal.hasAnyAuthority(['ROLE_DATA_PROVIDER']);
    $scope.isAssignedToProject = false;

    // load all users assigned to the currrent project
    projectDeferred.promise.then(
      function(project) {
        $scope.project = project;
        $scope.fetching = true;

        var isProjectRequirementsDisabled =
          setProjectRequirementsDisabled(project);
        CurrentProjectService.setCurrentProject(project);

        if (requiredTypesWatch) {
          requiredTypesWatch();
        }

        if (!isProjectRequirementsDisabled &&
          project.configuration.requirements) {
          $scope.$watch(function() {
            return $scope.project.configuration.requirements;
          }, function(newVal, oldVal) {
            if (newVal !== oldVal && !$scope.changed) {
              $scope.changed = true;
            }
          }, true);
        }

        function getAndAddUsers(key) {
          // get users of type {key} asynchronously
          // and return promise resolving when all are fetched
          if (project.configuration[key]) {
            return $q.all(
              project.configuration[key].map(function(userLogin) {
                return (
                  UserResource.getPublic({
                    login: userLogin
                  }).$promise.then(function(userResult) {
                    if (!_.includes($scope.activeUsers[key].map(function(u) {
                      return u.login;
                    }), userResult.login)) {
                      $scope.activeUsers[key].push(userResult);
                    }
                  })
                );
              })
            );
          } else {
            return $q.resolve([]);
          }
        }

        $q.resolve($q.all([
          getAndAddUsers('publishers'),
          getAndAddUsers('dataProviders')
        ])).then(function() {
          $scope.fetching = false;
          setAssignedToProject();
        }).catch(function(error) {
          SimpleMessageToastService
            .openAlertMessageToast(
              'global.error.server-error.internal-server-error', {
                status: error.data.error_description
              });
        });
        registerConfirmOnDirtyHook();
      }).finally(function() {
      $scope.loadStarted = false;
    });

    $scope.canDeleteUser = function(user, role) {
      if (user.restricted) {
        // cannot modify user whose details we can't read
        return false;
      }
      if (!$scope.advancedPrivileges && role === 'publishers') {
        // cannot remove publishers without advanced privilege
        return false;
      }
      if ($scope.activeUsers[role].length <= 1) {
        // cannot remove the last user in this list
        return false;
      }
      return true;
    };

    $state.currentPromise = null;
    $state.searchCache = {
      publishers: {},
      dataProviders: {}
    };
    var internalRoles = {
      'publishers': 'ROLE_PUBLISHER',
      'dataProviders': 'ROLE_DATA_PROVIDER'
    };
    $scope.searchUsers = function(search, role) {
      var roleInternal = internalRoles[role];
      if (!$state.loadComplete) {
        return [];
      }
      if ($state.searchCache[role][search]) {
        return $state.searchCache[role][search];
      }
      if (!$state.currentPromise) {
        $state.currentPromise = UserResource.search({
          login: search,
          role: roleInternal
        }).$promise.then(function(result) {
          $state.currentPromise = null;
          var results = result.filter(function(x) {
            // filter out already added users
            return $scope.activeUsers[role].map(function(u) {
              return u.login;
            }).indexOf(x.login) < 0 && _.includes(x.authorities, roleInternal);
          });
          $state.searchCache[role][search] = results;
          return results;
        });
      }
      return $state.currentPromise;
    };
    $scope.searchProjectData = function(group) {
      return SearchDao.search('', 0, $scope.project.id, '', group, 1, '');
    };

    $scope.removeUser = function(user, role) {
      $scope.changed = true;
      $scope.activeUsers[role] = $scope.activeUsers[role]
        .filter(function(item) {
          return item.login !== user.login;
        });
      $state.searchCache[role] = {};
    };

    $scope.shareButtonShown = false;
    $scope.onTabSelect = function(tab) {
      if (tab === 'config') {
        $scope.shareButtonShown = false;
      } else if (tab === 'status') {
        $scope.shareButtonShown = true;
      }
    };

    $scope.setChanged = function(changed) {
      if (changed === undefined) {
        changed = true;
      }
      $scope.changed = changed;
    };

    $state.loadComplete = true;
  }).directive('projectCockpitConfig', function() {
  return {
    restrict: 'E',
    templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
      'project-cockpit-config.html.tmpl'
  };
}).directive('projectCockpitStatus', function() {
  return {
    restrict: 'E',
    templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
      'project-cockpit-status.html.tmpl'
  };
}).directive('projectCockpitUserlist', function() {
  return {
    restrict: 'E',
    templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
      'project-cockpit-userlist.html.tmpl',
    scope: true,
    link: function(scope, elem, attrs) { // jshint ignore:line
      scope.group = attrs.group;
    }
  };
}).directive('projectCockpitAssignment', function($state) {
  return {
    restrict: 'E',
    templateUrl: 'scripts/dataacquisitionprojectmanagement/views/' +
      'project-cockpit-assignment.html.tmpl',
    scope: true,
    replace: true,
    link: function(scope, elem, attrs) { // jshint ignore:line
      var elasticSearchType = {
        studies: 'studies',
        surveys: 'surveys',
        instruments: 'instruments',
        questions: 'questions',
        dataSets: 'data_sets',
        variables: 'variables'
      };
      scope.group = attrs.group;
      scope.create = function() {
        $state.go(attrs.createstate, {});
      };
      scope.count = null;
      scope.$watch(function() {
        return scope.project &&
        scope.project.configuration[attrs.group + 'State'] ?
          scope.project.configuration[attrs.group + 'State']
            .dataProviderReady : null;
      }, function(newVal, oldVal) {
        if (newVal !== oldVal) {
          scope.setChanged(true);
        }
      });
      scope.$watch(function() {
        return scope.project &&
        scope.project.configuration[attrs.group + 'State'] ?
          scope.project.configuration[attrs.group + 'State']
            .publisherReady : null;
      }, function(newVal, oldVal) {
        if (newVal !== oldVal) {
          scope.setChanged(true);
        }
      });

      scope.searchProjectData(
        elasticSearchType[attrs.group]
      ).then(function(data) {
        scope.count = data.hits.total;
      }).catch(function() {
        scope.count = 0;
      });

    }
  };
});
<|endoftext|>


<commit_before>/* Example definition of a simple mode that understands a subset of
 * JavaScript:
 */
var CodeMirror = require('./codemirror.js');

CodeMirror.defineSimpleMode("gcode", {
  // The start state contains the rules that are intially used
  start: [
    {regex: /\([^\)]*\)/i, token: "comment"},
    {regex: /[GM]\d+/i, token: "keyword"},
    // You can match multiple tokens at once. Note that the captured
    // groups must span the whole string in this case
    {regex: /([A-FH-LN-Z])([+\-]?[0-9]+(?:\.[0-9]+)?)/i,
     token: ["variable", "number"]},
    {regex: /\?.*/, token: "comment"},
    {regex: /[^\w\s]/, token: "error"}
  ],
  // The meta property contains global information about the mode. It
  // can contain properties like lineComment, which are supported by
  // all modes, and also directives like dontIndentStates, which are
  // specific to simple modes.
  meta: {
    dontIndentStates: ["comment"],
    lineComment: "?"
  }
});

var CMD_REGEX = /^[A-Z](?:[A-Z]|[0-9]+|C\#)\b/i
var LABEL_REGEX = /^[A-Z_][A-Z0-9_]*\:/i
var WORD_REGEX = /^[A-Z_][A-Z0-9_]*/i
var STRING_REGEX = /^"(?:[^\\]|\\.)*?"/
var NUMBER_REGEX = /^0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/i
var SYS_VAR_REGEX = /^\%\([ \t]*[0-9]+[ \t]*\)/i
var USR_VAR_REGEX = /^\&[A-Z_][A-Z0-9_]*/i
var PERSIST_VAR_REGEX = /^\$[A-Z_][A-Z0-9_]*/i

var BARE_REGEX = /^[IOT]/i
var COMMENT_REGEX = /^'.*/i
var OPERATOR_REGEX = /^[\+\-\*\/\^\!\(\)\=\>\<|\=\:]/i

function matchExpression(stream) {
  if(stream.match(SYS_VAR_REGEX)) {
    return "variable";
  }
  if(stream.match(USR_VAR_REGEX)) {
    return "variable-2";
  }
  if(stream.match(PERSIST_VAR_REGEX)) {
    return "variable-3";
  }
  if(stream.match(NUMBER_REGEX)) {
    return "number";
  }
  if(stream.match(STRING_REGEX)) {
    return "string";
  }
  if(stream.match(OPERATOR_REGEX)) {
    return "operator";
  }
  return null;
}

function matchArgument(stream) {
  var match = matchExpression(stream);
  if(match) { return match; }
  if(stream.match(BARE_REGEX)) { return "atom"; }
  return null;
}

CodeMirror.defineMode("opensbp", function() {
  return {
    startState: function() {
      return {
        name : "sol",
      }
    },

    token: function(stream, state) {
      if(stream.sol()) {
        state.name = "sol";
      }

      if(stream.eatSpace()) {
        return null;
      }
      if(stream.eat("'")) {
        stream.skipToEnd();
        return 'comment';
      }
      switch(state.name) {
        case "sol":
          if(stream.eatSpace()) {
            return null;
          }

          // Line Comment
          if(stream.match(COMMENT_REGEX)) {
            return "comment";
          }

          // ON INPUT statement
          if(stream.match("ON")) {
            state.name = "on";
            return "keyword";
          }

          // LHS of an assignment
          if(stream.match(SYS_VAR_REGEX)) {
            state.name = "assign";
            return "variable";
          }

          if(stream.match(USR_VAR_REGEX)) {
            state.name = "assign";
            return "variable-2";
          }

          if(stream.match(PERSIST_VAR_REGEX)) {
            state.name = "assign";
            return "variable-3";
          }

          // Label (for GOTOs)
          if(stream.match(LABEL_REGEX)) {
            return "property";
          }

          if(stream.match(/^IF/i)) {
            state.name = "test";
            return "keyword"
          }

          // Command mnemonic
          if(stream.match(CMD_REGEX)) {
            state.name = "args";
            return "keyword";
          }

          // Pause command
          if(stream.match(/^PAUSE\s*,?\s*/i)) {
            state.name = "pause";
            return "keyword"
          }

          // Pause command
          if(stream.match(/^FAIL/i)) {
            state.name = "fail";
            return "keyword"
          }

          // Goto commands
          if(stream.match(/^GOTO|GOSUB/i)) {
            state.name = "goto";
            return "keyword"
          }

          // Singles
          if(stream.match(/^RETURN|END/i)) {
            state.name = "single";
            return "keyword";
          }
          //
          stream.skipToEnd();
        break;

        case "single":

        break;

        case "args":
          if(stream.eat(',')) {
            return null
          }
          var match = matchArgument(stream);
          if(match) { return match; }

        break;

        case "assign":
          var match = matchExpression(stream);
          if(match) { return match;}
          stream.skipToEnd();
          return 'string';

        break;

        case "test":
          var match = matchExpression(stream);
          if(match) { return match;}
          if(stream.match(/^THEN/i)) {
            return "keyword";
          }
          if(stream.match(/^GOTO|GOSUB/i)) {
            state.name = "goto"
            return "keyword";
          }
          if(stream.match(LABEL_REGEX)) {
            return "property";
          }
        break;

        case "goto":
          if(stream.match(WORD_REGEX)) {
            state.name = "sol"
            return "property"
          }
        break;

        case "on":
          if(stream.eat(',')) {
            return null;
          }
          if(stream.match(/INP(?:UT)?/i)) {
            return "keyword";
          }
          if(stream.match(/(?:GOTO)|(?:GOSUB)/i)) {
            state.name = "goto"
            return "keyword";
          }
          if(stream.match(/\(|\)/)) {
            return "operator";
          }
          if(stream.match(/\d+/)) {
            return "number";
          }
          break;

        case "pause":
          if(stream.eatSpace()) {
            return null;
          }

          var match = matchExpression(stream);
          if(match) { return match; }

          break;

        case "fail":
          if(stream.eatSpace()) {
            return null;
          }

          var match = matchExpression(stream);
          if(match) { return match; }

          break;

        default:
          console.error("Unknown state: ", state)
        break;
      }

      stream.next();
      return "error";

    }
  }
});
CodeMirror.defineMIME("text/x-opensbp","opensbp")

/*

CodeMirror.defineSimpleMode("opensbp", {
  // The start state contains the rules that are intially used
  start: [
    {regex: /\s*[A-Z](?:[A-Z]|[0-9]+|\#)\b/i, token: "keyword", next:"args", sol: true},
    {regex: /PAUSE/i, token: "keyword", next:"args"},

    // You can match multiple tokens at once. Note that the captured
    // groups must span the whole string in this case
    //{regex: /([A-FH-LN-Z])([+\-]?[0-9]+(?:\.[0-9]+)?)/i,
    // token: ["variable", "number"]},
    {regex: /\'., token: "comment"},
  ],

  args: [
    {regex: /,/i, token: "operator"},
    {regex: /"(?:[^\\]|\\.)*?"/, token: "string"},
    {regex: /[+\-]?[0-9]+(?:\.[0-9]+)?/i, token: "number"},
    {regex: /[^\t ,]/, next: "start"}
  ],
  // The meta property contains global information about the mode. It
  // can contain properties like lineComment, which are supported by
  // all modes, and also directives like dontIndentStates, which are
  // specific to simple modes.
  meta: {
    dontIndentStates: ["comment"],
    lineComment: "'"
  }
});*/
<commit_msg>Add raw g-codes to stream<commit_after>/* Example definition of a simple mode that understands a subset of
 * JavaScript:
 */
var CodeMirror = require('./codemirror.js');

CodeMirror.defineSimpleMode("gcode", {
  // The start state contains the rules that are intially used
  start: [
    {regex: /\([^\)]*\)/i, token: "comment"},
    {regex: /[GM]\d+/i, token: "keyword"},
    // You can match multiple tokens at once. Note that the captured
    // groups must span the whole string in this case
    {regex: /([A-FH-LN-Z])([+\-]?[0-9]+(?:\.[0-9]+)?)/i,
     token: ["variable", "number"]},
    {regex: /\?.*/, token: "comment"},
    {regex: /[^\w\s]/, token: "error"}
  ],
  // The meta property contains global information about the mode. It
  // can contain properties like lineComment, which are supported by
  // all modes, and also directives like dontIndentStates, which are
  // specific to simple modes.
  meta: {
    dontIndentStates: ["comment"],
    lineComment: "?"
  }
});

var CMD_REGEX = /^[A-Z](?:[A-Z]|[0-9]+|C\#)\b/i
var LINENO_REGEX = /^N[0-9]+\b/i
var LABEL_REGEX = /^[A-Z_][A-Z0-9_]*\:/i
var WORD_REGEX = /^[A-Z_][A-Z0-9_]*/i
var STRING_REGEX = /^"(?:[^\\]|\\.)*?"/
var NUMBER_REGEX = /^0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/i
var SYS_VAR_REGEX = /^\%\([ \t]*[0-9]+[ \t]*\)/i
var USR_VAR_REGEX = /^\&[A-Z_][A-Z0-9_]*/i
var PERSIST_VAR_REGEX = /^\$[A-Z_][A-Z0-9_]*/i

var BARE_REGEX = /^[IOT]/i
var COMMENT_REGEX = /^'.*/i
var OPERATOR_REGEX = /^[\+\-\*\/\^\!\(\)\=\>\<|\=\:]/i

function matchExpression(stream) {
  if(stream.match(SYS_VAR_REGEX)) {
    return "variable";
  }
  if(stream.match(USR_VAR_REGEX)) {
    return "variable-2";
  }
  if(stream.match(PERSIST_VAR_REGEX)) {
    return "variable-3";
  }
  if(stream.match(NUMBER_REGEX)) {
    return "number";
  }
  if(stream.match(STRING_REGEX)) {
    return "string";
  }
  if(stream.match(OPERATOR_REGEX)) {
    return "operator";
  }
  return null;
}

function matchArgument(stream) {
  var match = matchExpression(stream);
  if(match) { return match; }
  if(stream.match(BARE_REGEX)) { return "atom"; }
  return null;
}

CodeMirror.defineMode("opensbp", function() {
  return {
    startState: function() {
      return {
        name : "sol",
      }
    },

    token: function(stream, state) {
      if(stream.sol()) {
        state.name = "sol";
      }

      if(stream.eatSpace()) {
        return null;
      }
      if(stream.eat("'")) {
        stream.skipToEnd();
        return 'comment';
      }
      switch(state.name) {
        case "sol":
          if(stream.eatSpace()) {
            return null;
          }

          // Line Comment
          if(stream.match(COMMENT_REGEX)) {
            return "comment";
          }

          // ON INPUT statement
          if(stream.match("ON")) {
            state.name = "on";
            return "keyword";
          }

          // LHS of an assignment
          if(stream.match(SYS_VAR_REGEX)) {
            state.name = "assign";
            return "variable";
          }

          if(stream.match(USR_VAR_REGEX)) {
            state.name = "assign";
            return "variable-2";
          }

          if(stream.match(PERSIST_VAR_REGEX)) {
            state.name = "assign";
            return "variable-3";
          }

          // Label (for GOTOs)
          if(stream.match(LABEL_REGEX)) {
            return "property";
          }

          if(stream.match(/^IF/i)) {
            state.name = "test";
            return "keyword"
          }

          if(stream.match(LINENO_REGEX)) {
          	state.name = "gcode";
          	return "property";
          }
          // Command mnemonic
          if(stream.match(CMD_REGEX)) {
            state.name = "args";
            return "keyword";
          }

          // Pause command
          if(stream.match(/^PAUSE\s*,?\s*/i)) {
            state.name = "pause";
            return "keyword"
          }

          // Pause command
          if(stream.match(/^FAIL/i)) {
            state.name = "fail";
            return "keyword"
          }

          // Goto commands
          if(stream.match(/^GOTO|GOSUB/i)) {
            state.name = "goto";
            return "keyword"
          }

          // Singles
          if(stream.match(/^RETURN|END/i)) {
            state.name = "single";
            return "keyword";
          }
          //
          stream.skipToEnd();
        break;

        case "single":

        break;

        case "args":
          if(stream.eat(',')) {
            return null
          }
          var match = matchArgument(stream);
          if(match) { return match; }

        break;

        case "assign":
          var match = matchExpression(stream);
          if(match) { return match;}
          stream.skipToEnd();
          return 'string';

        break;

        case "test":
          var match = matchExpression(stream);
          if(match) { return match;}
          if(stream.match(/^THEN/i)) {
            return "keyword";
          }
          if(stream.match(/^GOTO|GOSUB/i)) {
            state.name = "goto"
            return "keyword";
          }
          if(stream.match(LABEL_REGEX)) {
            return "property";
          }
        break;

        case "goto":
          if(stream.match(WORD_REGEX)) {
            state.name = "sol"
            return "property"
          }
        break;

        case "on":
          if(stream.eat(',')) {
            return null;
          }
          if(stream.match(/INP(?:UT)?/i)) {
            return "keyword";
          }
          if(stream.match(/(?:GOTO)|(?:GOSUB)/i)) {
            state.name = "goto"
            return "keyword";
          }
          if(stream.match(/\(|\)/)) {
            return "operator";
          }
          if(stream.match(/\d+/)) {
            return "number";
          }
          break;

        case "pause":
          if(stream.eatSpace()) {
            return null;
          }

          var match = matchExpression(stream);
          if(match) { return match; }

          break;

        case "fail":
          if(stream.eatSpace()) {
            return null;
          }

          var match = matchExpression(stream);
          if(match) { return match; }

          break;

        default:
          console.error("Unknown state: ", state)
        break;

        case "gcode":
        	stream.skipToEnd();
        	return null;
        break;
      }

      stream.next();
      return "error";

    }
  }
});
CodeMirror.defineMIME("text/x-opensbp","opensbp")

/*

CodeMirror.defineSimpleMode("opensbp", {
  // The start state contains the rules that are intially used
  start: [
    {regex: /\s*[A-Z](?:[A-Z]|[0-9]+|\#)\b/i, token: "keyword", next:"args", sol: true},
    {regex: /PAUSE/i, token: "keyword", next:"args"},

    // You can match multiple tokens at once. Note that the captured
    // groups must span the whole string in this case
    //{regex: /([A-FH-LN-Z])([+\-]?[0-9]+(?:\.[0-9]+)?)/i,
    // token: ["variable", "number"]},
    {regex: /\'., token: "comment"},
  ],

  args: [
    {regex: /,/i, token: "operator"},
    {regex: /"(?:[^\\]|\\.)*?"/, token: "string"},
    {regex: /[+\-]?[0-9]+(?:\.[0-9]+)?/i, token: "number"},
    {regex: /[^\t ,]/, next: "start"}
  ],
  // The meta property contains global information about the mode. It
  // can contain properties like lineComment, which are supported by
  // all modes, and also directives like dontIndentStates, which are
  // specific to simple modes.
  meta: {
    dontIndentStates: ["comment"],
    lineComment: "'"
  }
});*/
<|endoftext|>


<commit_before>import DropZoneComponent from './DropZoneComponent';
import DropZoneInstanceManager from './DropZoneInstanceManager';
import DropZoneFactory from './DropZoneFactory';
import DropZoneOptionsManager from './DropZoneOptionsManager';
import DropZoneComponentUtils from './DropZoneComponentUtils';
import DropZoneComponentValidationManager from './DropZoneComponentValidationManager';
import DropZoneBodyClassManager from './DropZoneBodyClassManager';
import MimeTyper from '../libs/MimeTyper';

class DropZoneComonentFactory {
    /**
     * Create an instance of the DropZoneComponent with it's dependencies
     * @param {Element} html
     * @param {String} selector
     * @returns {DropZoneComponent}
     */
    static create (html, selector) {
        return new DropZoneComponent(
            html,
            selector,
            new DropZoneInstanceManager(
                html,
                DropZoneFactory
            ),
            new DropZoneOptionsManager(
                new DropZoneComponentUtils(
                    new MimeTyper()
                )
            ),
            new DropZoneComponentUtils(
                new MimeTyper()
            ),
            new DropZoneComponentValidationManager(),
            new DropZoneBodyClassManager()
        );
    }
}

module.exports = DropZoneComonentFactory;
<commit_msg>prevent multiple instances of utils & mimeTyper in the DropZone factory<commit_after>import DropZoneComponent from './DropZoneComponent';
import DropZoneInstanceManager from './DropZoneInstanceManager';
import DropZoneFactory from './DropZoneFactory';
import DropZoneOptionsManager from './DropZoneOptionsManager';
import DropZoneComponentUtils from './DropZoneComponentUtils';
import DropZoneComponentValidationManager from './DropZoneComponentValidationManager';
import DropZoneBodyClassManager from './DropZoneBodyClassManager';
import MimeTyper from '../libs/MimeTyper';

class DropZoneComonentFactory {
    /**
     * Create an instance of the DropZoneComponent with it's dependencies
     * @param {Element} html
     * @param {String} selector
     * @returns {DropZoneComponent}
     */
    static create (html, selector) {
        const mimeTyper = new MimeTyper(),
            utilsManager = new DropZoneComponentUtils(mimeTyper);

        return new DropZoneComponent(
            html,
            selector,
            new DropZoneInstanceManager(html, DropZoneFactory),
            new DropZoneOptionsManager(utilsManager),
            utilsManager,
            new DropZoneComponentValidationManager(),
            new DropZoneBodyClassManager()
        );
    }
}

module.exports = DropZoneComonentFactory;
<|endoftext|>


<commit_before>import { React, PropTypes, observer, action, observable, styled, modelize } from 'vendor';
import { FeatureFlags, Course } from '../../models';
import { withRouter } from 'react-router-dom';
import { Button, Dropdown } from 'react-bootstrap';
import { Icon } from 'shared';
import Theme from '../../theme';

const BecomeButton = styled(Button).attrs({
    className: 'd-inline-flex align-items-center',
    variant: 'link',
})`
  &.btn {
    padding: 0;
    border: 0;
    border-bottom-width: 1px;
  }
`;
BecomeButton.displayName = 'BecomeButton';

const Waiting = styled.div`
  color: ${Theme.colors.neutral.bright};
  display: flex;
  align-items: center;
  .ox-icon { width: 2.4rem; }
`;

const PeriodSelector = styled(Dropdown)`
.dropdown-toggle {
  display: flex;
  align-items: center;
  color: white;
  padding: 0;
  border: 0;
  border-bottom-width: 1px;
  &::after {
    display: none;
  }
  &:hover {
    color: ${Theme.colors.neutral.bright};
  }
  .ox-icon { width: 2.4rem; }
  .menu-toggle-icon { margin: 0; }
}
&.show .dropdown-toggle {
  border-bottom-color: transparent;
}
.dropdown-menu {
  width: 100%;
  box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.1);
}
.dropdown-item {
  word-wrap: break-word;
  white-space: normal;
  color: ${Theme.colors.neutral.gray};
}
.dropdown-divider:last-of-type {
  display: none;
}
`;

@withRouter
@observer
export default class TeacherBecomesStudent extends React.Component {
    static propTypes = {
        course: PropTypes.instanceOf(Course),
        history: PropTypes.object.isRequired,
    }

    @observable isCreating = false;
    @observable periodMenuIsOpen = false;

    constructor(props) {
        super(props);
        modelize(this);
    }

    @action.bound onBecomeStudentPeriodSelect(periodId) {
        this.becomeStudentInPeriod(
            this.props.course.periods.find(p => p.id == periodId)
        );
    }

    @action.bound onBecomeStudentClick() {
        this.becomeStudentInPeriod(
            this.props.course.periods.find(period => !period.is_archived)
        );
    }

    async becomeStudentInPeriod(period) {
        const { course } = this.props;
        this.isCreating = true;
        const role = await period.getTeacherStudentRole();
        this.props.history.push(`/course/${course.id}/become/${role.id}`);
    }

    @action.bound onPeriodMenuToggle(isOpen) {
        this.periodMenuIsOpen = isOpen;
    }

    render() {
        const { course } = this.props;

        if (!FeatureFlags.teacher_student_enabled ||
      !course ||
      !course.currentRole.isTeacher
        ) { return null; }

        if (this.isCreating) {
            return (
                <Waiting className="control">
                    <Icon type="spinner" spin size="2x" />
          Generating student view…
                </Waiting>
            );
        }

        if (1 === course.periods.active.length) {
            return (
                <BecomeButton onClick={this.onBecomeStudentClick}>
                    <Icon size="2x" type="glasses" />
          View as student
                </BecomeButton>
            );
        }

        return (
            <PeriodSelector
                onToggle={this.onPeriodMenuToggle}
                onSelect={this.onBecomeStudentPeriodSelect}
            >
                <Dropdown.Toggle variant="link" id="teacher-become-student">
                    <Icon size="2x" type="glasses" />
          View as student
                    <Icon
                        className="menu-toggle-icon"
                        type={this.periodMenuIsOpen ? 'close' : 'angle-down'}
                    />
                </Dropdown.Toggle>
                <Dropdown.Menu>
                    {course.periods.active.map((period) => (
                        <React.Fragment key={period.id}>
                            <Dropdown.Item eventKey={period.id}>{period.name}</Dropdown.Item>
                            <Dropdown.Divider />
                        </React.Fragment>
                    ))}
                </Dropdown.Menu>
            </PeriodSelector>
        );
    }
}
<commit_msg>style as control; otherwise it's not colored correctly<commit_after>import { React, PropTypes, observer, action, observable, styled, modelize } from 'vendor';
import { FeatureFlags, Course } from '../../models';
import { withRouter } from 'react-router-dom';
import { Button, Dropdown } from 'react-bootstrap';
import { Icon } from 'shared';
import Theme from '../../theme';

const BecomeButton = styled(Button).attrs({
    className: 'd-inline-flex align-items-center',
    variant: 'link',
})`
  &.btn {
    padding: 0;
    border: 0;
    border-bottom-width: 1px;
  }
`;
BecomeButton.displayName = 'BecomeButton';

const Waiting = styled.div`
  color: ${Theme.colors.neutral.bright};
  display: flex;
  align-items: center;
  .ox-icon { width: 2.4rem; }
`;

const PeriodSelector = styled(Dropdown)`
.dropdown-toggle {
  display: flex;
  align-items: center;
  color: white;
  padding: 0;
  border: 0;
  border-bottom-width: 1px;
  &::after {
    display: none;
  }
  &:hover {
    color: ${Theme.colors.neutral.bright};
  }
  .ox-icon { width: 2.4rem; }
  .menu-toggle-icon { margin: 0; }
}
&.show .dropdown-toggle {
  border-bottom-color: transparent;
}
.dropdown-menu {
  width: 100%;
  box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.1);
}
.dropdown-item {
  word-wrap: break-word;
  white-space: normal;
  color: ${Theme.colors.neutral.gray};
}
.dropdown-divider:last-of-type {
  display: none;
}
`;

@withRouter
@observer
export default class TeacherBecomesStudent extends React.Component {
    static propTypes = {
        course: PropTypes.instanceOf(Course),
        history: PropTypes.object.isRequired,
    }

    @observable isCreating = false;
    @observable periodMenuIsOpen = false;

    constructor(props) {
        super(props);
        modelize(this);
    }

    @action.bound onBecomeStudentPeriodSelect(periodId) {
        this.becomeStudentInPeriod(
            this.props.course.periods.find(p => p.id == periodId)
        );
    }

    @action.bound onBecomeStudentClick() {
        this.becomeStudentInPeriod(
            this.props.course.periods.find(period => !period.is_archived)
        );
    }

    async becomeStudentInPeriod(period) {
        const { course } = this.props;
        this.isCreating = true;
        const role = await period.getTeacherStudentRole();
        this.props.history.push(`/course/${course.id}/become/${role.id}`);
    }

    @action.bound onPeriodMenuToggle(isOpen) {
        this.periodMenuIsOpen = isOpen;
    }

    render() {
        const { course } = this.props;

        if (!FeatureFlags.teacher_student_enabled ||
      !course ||
      !course.currentRole.isTeacher
        ) { return null; }

        if (this.isCreating) {
            return (
                <Waiting className="control">
                    <Icon type="spinner" spin size="2x" />
          Generating student view…
                </Waiting>
            );
        }

        if (1 === course.periods.active.length) {
            return (
                <BecomeButton onClick={this.onBecomeStudentClick}>
                    <Icon size="2x" type="glasses" />
          View as student
                </BecomeButton>
            );
        }

        return (
            <PeriodSelector
                className="theme-colored-control control"
                onToggle={this.onPeriodMenuToggle}
                onSelect={this.onBecomeStudentPeriodSelect}
            >
                <Dropdown.Toggle variant="link" id="teacher-become-student">
                    <Icon size="2x" type="glasses" />
          View as student
                    <Icon
                        className="menu-toggle-icon"
                        type={this.periodMenuIsOpen ? 'close' : 'angle-down'}
                    />
                </Dropdown.Toggle>
                <Dropdown.Menu>
                    {course.periods.active.map((period) => (
                        <React.Fragment key={period.id}>
                            <Dropdown.Item eventKey={period.id}>{period.name}</Dropdown.Item>
                            <Dropdown.Divider />
                        </React.Fragment>
                    ))}
                </Dropdown.Menu>
            </PeriodSelector>
        );
    }
}
<|endoftext|>