<commit_before>var searchbarCachedText = "";
var METADATA_SEPARATOR = "·";
var didFireKeydownSelChange = false;
var currentsearchbarInput;

//https://remysharp.com/2010/07/21/throttling-function-calls#

function throttle(fn, threshhold, scope) {
	threshhold || (threshhold = 250);
	var last,
		deferTimer;
	return function () {
		var context = scope || this;

		var now = +new Date,
			args = arguments;
		if (last && now < last + threshhold) {
			// hold on to it
			clearTimeout(deferTimer);
			deferTimer = setTimeout(function () {
				last = now;
				fn.apply(context, args);
			}, threshhold);
		} else {
			last = now;
			fn.apply(context, args);
		}
	};
}

function debounce(fn, delay) {
	var timer = null;
	return function () {
		var context = this,
			args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function () {
			fn.apply(context, args);
		}, delay);
	};
}

function empty(node) {
	var n;
	while (n = node.firstElementChild) {
		node.removeChild(n);
	}
}

function removeTags(text) {
	return text.replace(/<.*?>/g, "");
}

/* this is used by navbar-tabs.js. When a url is entered, endings such as ? need to be parsed and removed. */
function parsesearchbarURL(url) {
	//always use a search engine if the query starts with "?"

	if (url.indexOf("?") == 0) {
		url = urlParser.searchBaseURL.replace("%s", encodeURIComponent(url.replace("?", "")));
	}

	if (url.indexOf("^") == 0) {
		url = url.replace("^", "");
	}

	if (url.indexOf("*") == 0) {
		url = url.replace("*", "");
	}

	return url;
}

function openURLInBackground(url) { //used to open a url in the background, without leaving the searchbar
	var newTab = tabs.add({
		url: url,
		private: tabs.get(tabs.getSelected()).private
	}, tabs.getIndex(tabs.getSelected()) + 1);
	addTab(newTab, {
		enterEditMode: false,
		openInBackground: true,
		leaveEditMode: false,
	});
	$(".result-item:focus").blur(); //remove the highlight from an awesoembar result item, if there is one
}

//when clicking on a result item, this function should be called to open the URL

function openURLFromsearchbar(event, url) {
	if (event.metaKey) {
		openURLInBackground(url);
		return true;
	} else {
		navigate(tabs.getSelected(), url);

		if (!tabs.get(tabs.getSelected()).private) {

			//show the color and title of the new page immediately, to make the page load time seem faster
			currentHistoryResults.forEach(function (res) {
				if (res.url == url) {
					setColor(res.color, getTextColor(getRGBObject(res.color)));
					tabs.update(tabs.getSelected(), {
						title: res.title,
					});
					rerenderTabElement(tabs.getSelected());
				}
			});

		}

		return false;
	}
}

//attempts to shorten a page title, removing useless text like the site name

function getRealTitle(text) {

	//don't try to parse URL's
	if (urlParser.isURL(text)) {
		return text;
	}

	var possibleCharacters = ["|", ":", " - ", " — "];

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

		var char = possibleCharacters[i];
		//match url's of pattern: title | website name
		var titleChunks = text.split(char);

		if (titleChunks.length >= 2) {
			titleChunks[0] = titleChunks[0].trim();
			titleChunks[1] = titleChunks[1].trim();

			if (titleChunks[1].length < 5 || titleChunks[1].length / titleChunks[0].length <= 0.5) {
				return titleChunks[0]
			}
		}
	}

	//fallback to the regular title

	return text;

}

//creates a result item

/*

data:

title: string - the title of the item
secondaryText: string - the item's secondary text
url: string - the item's url (if there is one).
icon: string - the name of a font awesome icon.
image: string - the URL of an image to show
descriptionBlock: string - the text in the description block

classList: array - a list of classes to add to the item
*/

function createSearchbarItem(data) {
	var item = document.createElement("div");
	item.classList.add("result-item");

	item.setAttribute("tabindex", "-1");

	if (data.classList) {
		for (var i = 0; i < data.classList.length; i++) {
			item.classList.add(data.classList[i]);
		}
	}

	if (data.icon) {
		var i = document.createElement("i");
		i.className = "fa" + " " + data.icon;

		item.appendChild(i);
	}

	if (data.title) {
		var title = document.createElement("span");
		title.classList.add("title");

		title.textContent = data.title;

		item.appendChild(title);
	}

	if (data.url) {
		item.setAttribute("data-url", data.url);
	}

	if (data.secondaryText) {
		var secondaryText = document.createElement("span");
		secondaryText.classList.add("secondary-text");

		secondaryText.textContent = data.secondaryText;

		item.appendChild(secondaryText);
	}

	if (data.image) {
		var image = document.createElement("img");
		image.className = "result-icon image low-priority-image";
		image.src = data.image;

		if (data.imageIsInline) {
			image.classList.add("inline");
		}

		item.insertBefore(image, item.childNodes[0]);
	}

	if (data.descriptionBlock) {
		var dBlock = document.createElement("span");
		dBlock.classList.add("description-block");

		dBlock.textContent = data.descriptionBlock;
		item.appendChild(dBlock);
	}

	return item;
}

var searchbar = document.getElementById("searchbar");
var $searchbar = $(searchbar);

function clearsearchbar() {
	empty(opentabarea);
	empty(topAnswerarea);
	empty(bookmarkarea);
	empty(historyarea);
	empty(iaarea);
	empty(suggestedsitearea);
	empty(serarea);

	//prevent memory leak
	cachedBangSnippets = {};
}

function showSearchbar(triggerInput) {
	searchbarCachedText = triggerInput.val();
	$(document.body).addClass("searchbar-shown");

	clearsearchbar();

	searchbar.hidden = false;

	currentsearchbarInput = triggerInput.get(0);

}

//gets the typed text in an input, ignoring highlighted suggestions

function getValue(input) {
	var text = input.value;
	return text.replace(text.substring(input.selectionStart, input.selectionEnd), "");
}

function hidesearchbar() {
	currentsearchbarInput = null;
	$(document.body).removeClass("searchbar-shown");
	searchbar.hidden = true;
	cachedBangSnippets = {};
}
var showSearchbarResults = function (text, input, event) {

	if (event && event.metaKey) {
		return;
	}

	deleteKeyPressed = event && event.keyCode == 8;

	//find the real input value, accounting for highlighted suggestions and the key that was just pressed

	//delete key doesn't behave like the others, String.fromCharCode returns an unprintable character (which has a length of one)

	if (event && event.keyCode != 8) {

		text = text.substring(0, input.selectionStart) + String.fromCharCode(event.keyCode) + text.substring(input.selectionEnd, text.length);

	}

	console.log("searchbar: ", "'" + text + "'", text.length);

	//there is no text, show only topsites
	if (text.length < 1) {
		showHistoryResults("", input);
		clearsearchbar();
		return;
	}

	//when you start with ?, always search with duckduckgo

	if (text.indexOf("?") == 0) {
		clearsearchbar();

		currentSuggestionLimit = 5;
		showSearchSuggestions(text.replace("?", ""), input);
		return;
	}

	//when you start with ^, always search history (only)

	if (text.indexOf("^") == 0) {
		clearsearchbar();
		showHistoryResults(text.replace("^", ""), input);
		return;
	}

	//when you start with *, always search bookmarks (only)

	if (text.indexOf("*") == 0) {
		clearsearchbar();
		showBookmarkResults(text.replace("*", ""), input);
		return;
	}

	//show searchbar results

	showBookmarkResults(text);

	showHistoryResults(text, input);
	showInstantAnswers(text, input);
	searchOpenTabs(text, input);

	//update cache
	searchbarCachedText = text;
};

function focussearchbarItem(options) {
	options = options || {}; //fallback if options is null
	var previous = options.focusPrevious;
	var allItems = $("#searchbar .result-item:not(.unfocusable)");
	var currentItem = $("#searchbar .result-item:focus, .result-item.fakefocus");
	var index = allItems.index(currentItem);
	var logicalNextItem = allItems.eq((previous) ? index - 1 : index + 1);

	$searchbar.find(".fakefocus").removeClass("fakefocus"); //clear previously focused items

	if (currentItem[0] && logicalNextItem[0]) { //an item is focused and there is another item after it, move onto the next one
		logicalNextItem.get(0).focus();
	} else if (currentItem[0]) { //the last item is focused, focus the searchbar again
		getTabElement(tabs.getSelected()).getInput().get(0).focus();
	} else { // no item is focused.
		$("#searchbar .result-item").first().get(0).focus();
	}

	var focusedItem = $("#searchbar .result-item:focus");

	if (focusedItem.hasClass("iadata-onfocus")) {

		setTimeout(function () {
			if (document.activeElement == focusedItem[0]) {
				var itext = focusedItem.find(".title").text();

				showInstantAnswers(itext, currentsearchbarInput, {
					alwaysShow: true,
					destroyPrevious: false,
				});
			}
		}, 200);
	}
}

//return key on result items should trigger click
//tab key or arrowdown key should focus next item
//arrowup key should focus previous item

$searchbar.on("keydown", ".result-item", function (e) {
	if (e.keyCode == 13) {
		$(this).trigger("click");
	} else if (e.keyCode == 9 || e.keyCode == 40) { //tab or arrowdown key
		e.preventDefault();
		focussearchbarItem();
	} else if (e.keyCode == 38) {
		e.preventDefault();
		focussearchbarItem({
			focusPrevious: true
		});
	}
});

//swipe left on history items to delete them

var lastItemDeletion = Date.now();

$searchbar.on("mousewheel", ".history-results .result-item, .top-answer-results .result-item", function (e) {
	var self = $(this)
	if (e.originalEvent.deltaX > 50 && e.originalEvent.deltaY < 3 && self.attr("data-url") && Date.now() - lastItemDeletion > 700) {
		lastItemDeletion = Date.now();
		self.animate({
			opacity: "0",
			"margin-left": "-100%"
		}, 200, function () {
			self.remove();
			bookmarks.deleteHistory(self.attr("data-url"));
			lastItemDeletion = Date.now();
		});
	}
});

//when we get keywords data from the page, we show those results in the searchbar

bindWebviewIPC("keywordsData", function (webview, tabId, arguements) {

	var data = arguements[0];

	var itemsCt = 0;

	var itemsShown = [];

	data.entities.forEach(function (item, index) {

		//ignore one-word items, they're usually useless
		if (!/\s/g.test(item.trim())) {
			return;
		}

		if (itemsCt >= 5 || itemsShown.indexOf(item.trim()) != -1) {
			return;
		}

		var div = createSearchbarItem({
			icon: "fa-search",
			title: item,
			classList: ["iadata-onfocus"]
		});

		div.addEventListener("click", function (e) {
			if (e.metaKey) {
				openURLInBackground(item);
			} else {
				navigate(tabs.getSelected(), item);
			}
		});

		serarea.appendChild(div);

		itemsCt++;
		itemsShown.push(item.trim());
	});
});
<commit_msg>bug fix<commit_after>var searchbarCachedText = "";
var METADATA_SEPARATOR = "·";
var didFireKeydownSelChange = false;
var currentsearchbarInput;

//https://remysharp.com/2010/07/21/throttling-function-calls#

function throttle(fn, threshhold, scope) {
	threshhold || (threshhold = 250);
	var last,
		deferTimer;
	return function () {
		var context = scope || this;

		var now = +new Date,
			args = arguments;
		if (last && now < last + threshhold) {
			// hold on to it
			clearTimeout(deferTimer);
			deferTimer = setTimeout(function () {
				last = now;
				fn.apply(context, args);
			}, threshhold);
		} else {
			last = now;
			fn.apply(context, args);
		}
	};
}

function debounce(fn, delay) {
	var timer = null;
	return function () {
		var context = this,
			args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function () {
			fn.apply(context, args);
		}, delay);
	};
}

function empty(node) {
	var n;
	while (n = node.firstElementChild) {
		node.removeChild(n);
	}
}

function removeTags(text) {
	return text.replace(/<.*?>/g, "");
}

/* this is used by navbar-tabs.js. When a url is entered, endings such as ? need to be parsed and removed. */
function parsesearchbarURL(url) {
	//always use a search engine if the query starts with "?"

	if (url.indexOf("?") == 0) {
		url = urlParser.searchBaseURL.replace("%s", encodeURIComponent(url.replace("?", "")));
	}

	if (url.indexOf("^") == 0) {
		url = url.replace("^", "");
	}

	if (url.indexOf("*") == 0) {
		url = url.replace("*", "");
	}

	return url;
}

function openURLInBackground(url) { //used to open a url in the background, without leaving the searchbar
	var newTab = tabs.add({
		url: url,
		private: tabs.get(tabs.getSelected()).private
	}, tabs.getIndex(tabs.getSelected()) + 1);
	addTab(newTab, {
		enterEditMode: false,
		openInBackground: true,
		leaveEditMode: false,
	});
	$(".result-item:focus").blur(); //remove the highlight from an awesoembar result item, if there is one
}

//when clicking on a result item, this function should be called to open the URL

function openURLFromsearchbar(event, url) {
	if (event.metaKey) {
		openURLInBackground(url);
		return true;
	} else {
		navigate(tabs.getSelected(), url);

		if (!tabs.get(tabs.getSelected()).private) {

			//show the color and title of the new page immediately, to make the page load time seem faster
			currentHistoryResults.forEach(function (res) {
				if (res.url == url) {
					setColor(res.color, getTextColor(getRGBObject(res.color)));
					tabs.update(tabs.getSelected(), {
						title: res.title,
					});
					rerenderTabElement(tabs.getSelected());
				}
			});

		}

		return false;
	}
}

//attempts to shorten a page title, removing useless text like the site name

function getRealTitle(text) {

	//don't try to parse URL's
	if (urlParser.isURL(text)) {
		return text;
	}

	var possibleCharacters = ["|", ":", " - ", " — "];

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

		var char = possibleCharacters[i];
		//match url's of pattern: title | website name
		var titleChunks = text.split(char);

		if (titleChunks.length >= 2) {
			titleChunks[0] = titleChunks[0].trim();
			titleChunks[1] = titleChunks[1].trim();

			if (titleChunks[1].length < 5 || titleChunks[1].length / titleChunks[0].length <= 0.5) {
				return titleChunks[0]
			}
		}
	}

	//fallback to the regular title

	return text;

}

//creates a result item

/*

data:

title: string - the title of the item
secondaryText: string - the item's secondary text
url: string - the item's url (if there is one).
icon: string - the name of a font awesome icon.
image: string - the URL of an image to show
descriptionBlock: string - the text in the description block

classList: array - a list of classes to add to the item
*/

function createSearchbarItem(data) {
	var item = document.createElement("div");
	item.classList.add("result-item");

	item.setAttribute("tabindex", "-1");

	if (data.classList) {
		for (var i = 0; i < data.classList.length; i++) {
			item.classList.add(data.classList[i]);
		}
	}

	if (data.icon) {
		var i = document.createElement("i");
		i.className = "fa" + " " + data.icon;

		item.appendChild(i);
	}

	if (data.title) {
		var title = document.createElement("span");
		title.classList.add("title");

		title.textContent = data.title;

		item.appendChild(title);
	}

	if (data.url) {
		item.setAttribute("data-url", data.url);
	}

	if (data.secondaryText) {
		var secondaryText = document.createElement("span");
		secondaryText.classList.add("secondary-text");

		secondaryText.textContent = data.secondaryText;

		item.appendChild(secondaryText);
	}

	if (data.image) {
		var image = document.createElement("img");
		image.className = "result-icon image low-priority-image";
		image.src = data.image;

		if (data.imageIsInline) {
			image.classList.add("inline");
		}

		item.insertBefore(image, item.childNodes[0]);
	}

	if (data.descriptionBlock) {
		var dBlock = document.createElement("span");
		dBlock.classList.add("description-block");

		dBlock.textContent = data.descriptionBlock;
		item.appendChild(dBlock);
	}

	return item;
}

var searchbar = document.getElementById("searchbar");
var $searchbar = $(searchbar);

function clearsearchbar() {
	empty(opentabarea);
	empty(topAnswerarea);
	empty(bookmarkarea);
	empty(historyarea);
	empty(iaarea);
	empty(suggestedsitearea);
	empty(serarea);

	//prevent memory leak
	cachedBangSnippets = {};
}

function showSearchbar(triggerInput) {

	currentACItem = null

	searchbarCachedText = triggerInput.val();
	$(document.body).addClass("searchbar-shown");

	clearsearchbar();

	searchbar.hidden = false;

	currentsearchbarInput = triggerInput.get(0);

}

//gets the typed text in an input, ignoring highlighted suggestions

function getValue(input) {
	var text = input.value;
	return text.replace(text.substring(input.selectionStart, input.selectionEnd), "");
}

function hidesearchbar() {
	currentsearchbarInput = null;
	$(document.body).removeClass("searchbar-shown");
	searchbar.hidden = true;
	cachedBangSnippets = {};
}
var showSearchbarResults = function (text, input, event) {

	if (event && event.metaKey) {
		return;
	}

	deleteKeyPressed = event && event.keyCode == 8;

	//find the real input value, accounting for highlighted suggestions and the key that was just pressed

	//delete key doesn't behave like the others, String.fromCharCode returns an unprintable character (which has a length of one)

	if (event && event.keyCode != 8) {

		text = text.substring(0, input.selectionStart) + String.fromCharCode(event.keyCode) + text.substring(input.selectionEnd, text.length);

	}

	console.log("searchbar: ", "'" + text + "'", text.length);

	//there is no text, show only topsites
	if (text.length < 1) {
		showHistoryResults("", input);
		clearsearchbar();
		return;
	}

	//when you start with ?, always search with duckduckgo

	if (text.indexOf("?") == 0) {
		clearsearchbar();

		currentSuggestionLimit = 5;
		showSearchSuggestions(text.replace("?", ""), input);
		return;
	}

	//when you start with ^, always search history (only)

	if (text.indexOf("^") == 0) {
		clearsearchbar();
		showHistoryResults(text.replace("^", ""), input);
		return;
	}

	//when you start with *, always search bookmarks (only)

	if (text.indexOf("*") == 0) {
		clearsearchbar();
		showBookmarkResults(text.replace("*", ""), input);
		return;
	}

	//show searchbar results

	showBookmarkResults(text);

	showHistoryResults(text, input);
	showInstantAnswers(text, input);
	searchOpenTabs(text, input);

	//update cache
	searchbarCachedText = text;
};

function focussearchbarItem(options) {
	options = options || {}; //fallback if options is null
	var previous = options.focusPrevious;
	var allItems = $("#searchbar .result-item:not(.unfocusable)");
	var currentItem = $("#searchbar .result-item:focus, .result-item.fakefocus");
	var index = allItems.index(currentItem);
	var logicalNextItem = allItems.eq((previous) ? index - 1 : index + 1);

	$searchbar.find(".fakefocus").removeClass("fakefocus"); //clear previously focused items

	if (currentItem[0] && logicalNextItem[0]) { //an item is focused and there is another item after it, move onto the next one
		logicalNextItem.get(0).focus();
	} else if (currentItem[0]) { //the last item is focused, focus the searchbar again
		getTabElement(tabs.getSelected()).getInput().get(0).focus();
	} else { // no item is focused.
		$("#searchbar .result-item").first().get(0).focus();
	}

	var focusedItem = $("#searchbar .result-item:focus");

	if (focusedItem.hasClass("iadata-onfocus")) {

		setTimeout(function () {
			if (document.activeElement == focusedItem[0]) {
				var itext = focusedItem.find(".title").text();

				showInstantAnswers(itext, currentsearchbarInput, {
					alwaysShow: true,
					destroyPrevious: false,
				});
			}
		}, 200);
	}
}

//return key on result items should trigger click
//tab key or arrowdown key should focus next item
//arrowup key should focus previous item

$searchbar.on("keydown", ".result-item", function (e) {
	if (e.keyCode == 13) {
		$(this).trigger("click");
	} else if (e.keyCode == 9 || e.keyCode == 40) { //tab or arrowdown key
		e.preventDefault();
		focussearchbarItem();
	} else if (e.keyCode == 38) {
		e.preventDefault();
		focussearchbarItem({
			focusPrevious: true
		});
	}
});

//swipe left on history items to delete them

var lastItemDeletion = Date.now();

$searchbar.on("mousewheel", ".history-results .result-item, .top-answer-results .result-item", function (e) {
	var self = $(this)
	if (e.originalEvent.deltaX > 50 && e.originalEvent.deltaY < 3 && self.attr("data-url") && Date.now() - lastItemDeletion > 700) {
		lastItemDeletion = Date.now();
		self.animate({
			opacity: "0",
			"margin-left": "-100%"
		}, 200, function () {
			self.remove();
			bookmarks.deleteHistory(self.attr("data-url"));
			lastItemDeletion = Date.now();
		});
	}
});

//when we get keywords data from the page, we show those results in the searchbar

bindWebviewIPC("keywordsData", function (webview, tabId, arguements) {

	var data = arguements[0];

	var itemsCt = 0;

	var itemsShown = [];

	data.entities.forEach(function (item, index) {

		//ignore one-word items, they're usually useless
		if (!/\s/g.test(item.trim())) {
			return;
		}

		if (itemsCt >= 5 || itemsShown.indexOf(item.trim()) != -1) {
			return;
		}

		var div = createSearchbarItem({
			icon: "fa-search",
			title: item,
			classList: ["iadata-onfocus"]
		});

		div.addEventListener("click", function (e) {
			if (e.metaKey) {
				openURLInBackground(item);
			} else {
				navigate(tabs.getSelected(), item);
			}
		});

		serarea.appendChild(div);

		itemsCt++;
		itemsShown.push(item.trim());
	});
});
<|endoftext|>


<commit_before>// var channelName = "<%= channelName %>",
var channelName = $('#channelName').val(),
    sendMessage = $('#sendMessage'),
    messageText = $('#messageText'),
    chatDisplay = $('#chatDisplay'),
    usersDisplay = $('#usersDisplay'),
    channelList = $('#channelList'),
    channelCount = $('#channelCount');
    // loggedUser = $('#loggedUser').val();

console.log('CHANNEL NAME IS' + channelName);
var ChannelFunctions = {
  socketConnect : function(channelName){
    return io('localhost:3000', {
      query : 'channelName=' + channelName
    });
  },

  sendMessage : function(){
    var messageText = $('#messageText').val();
    if(messageText == ''){
      alert('Message Field is required!');
    }
    else{
      socket.emit('new channel message', {'messageText' : messageText});
      $('#messageText').val('');
    }
  }
}

var socket = ChannelFunctions.socketConnect(channelName);

sendMessage.on('click', function(){
  ChannelFunctions.sendMessage();
});

messageText.on('keypress', function(e){
  if(e.keyCode == 13){
    ChannelFunctions.sendMessage();
  }
});

socket.on('new channel message', function(data){
  var sender = data.sender,
      messageText = data.messageText,
      // item = sender + ':' + messageText + '
';
      item = "
"+ sender +" : "+ messageText +"
";
  chatDisplay.append(item);
});

socket.on('channel user update', function(data){
  usersDisplay.empty();
  var users = data.users;
  users.forEach(function(user){
    var item = "" + user + "";
    usersDisplay.append(item);
  });
});

socket.on('set channel messages' , function(data){
  chatDisplay.empty();
  var messages = data.messages;
  messages.forEach(function(message, i){
    var messageText = message.messageText,
        date = message.date,
        username = message.username,
        dateStringCurr = date.split("T")[0];
    if(i > 0){
      dateStringPrev = messages[i-1].date.split("T")[0];
      if(dateStringCurr != dateStringPrev){
        var logLastDate = messages[i-1].date;
        chatDisplay.append("
------------------------Above session logs from " + logLastDate +"-------------------
");
      }
    }
    var item = "
"+ username +" : "+ messageText +"
";
    chatDisplay.append(item);
  });
  if(messages.length > 0){
    var logLastDate = messages[messages.length - 1].date;
    chatDisplay.append("
------------------------Above session logs from " + logLastDate +"-------------------
");
  }
});

socket.on('set channels', function(data){
  channelList.empty();
  var channels = data.channels;
  channelCount.val(channels.length);
  channelList.append("Global Chat");
  channels.forEach(function(channel){
    if(!(channel.channelName == channelName)){
      var channelNameVal = channel.channelName;
      var item = ""+ channelNameVal +"";
      channelList.append(item);
    }
  });
});
<commit_msg>debug4<commit_after>// var channelName = "<%= channelName %>",
var channelName = $('#channelName').val(),
    sendMessage = $('#sendMessage'),
    messageText = $('#messageText'),
    chatDisplay = $('#chatDisplay'),
    usersDisplay = $('#usersDisplay'),
    channelList = $('#channelList'),
    channelCount = $('#channelCount');

console.log('CHANNEL NAME IS' + channelName);
var ChannelFunctions = {
  console.log('IN THE SOCKET FUNCTIONS' + channelName);
  socketConnect : function(channelName){
    return io('139.59.7.137:3000', {
      query : 'channelName=' + channelName
    });
  },

  sendMessage : function(){
    var messageText = $('#messageText').val();
    if(messageText == ''){
      alert('Message Field is required!');
    }
    else{
      socket.emit('new channel message', {'messageText' : messageText});
      $('#messageText').val('');
    }
  }
}

var socket = ChannelFunctions.socketConnect(channelName);

sendMessage.on('click', function(){
  ChannelFunctions.sendMessage();
});

messageText.on('keypress', function(e){
  if(e.keyCode == 13){
    ChannelFunctions.sendMessage();
  }
});

socket.on('new channel message', function(data){
  var sender = data.sender,
      messageText = data.messageText,
      // item = sender + ':' + messageText + '
';
      item = "
"+ sender +" : "+ messageText +"
";
  chatDisplay.append(item);
});

socket.on('channel user update', function(data){
  usersDisplay.empty();
  var users = data.users;
  users.forEach(function(user){
    var item = "" + user + "";
    usersDisplay.append(item);
  });
});

socket.on('set channel messages' , function(data){
  chatDisplay.empty();
  var messages = data.messages;
  messages.forEach(function(message, i){
    var messageText = message.messageText,
        date = message.date,
        username = message.username,
        dateStringCurr = date.split("T")[0];
    if(i > 0){
      dateStringPrev = messages[i-1].date.split("T")[0];
      if(dateStringCurr != dateStringPrev){
        var logLastDate = messages[i-1].date;
        chatDisplay.append("
------------------------Above session logs from " + logLastDate +"-------------------
");
      }
    }
    var item = "
"+ username +" : "+ messageText +"
";
    chatDisplay.append(item);
  });
  if(messages.length > 0){
    var logLastDate = messages[messages.length - 1].date;
    chatDisplay.append("
------------------------Above session logs from " + logLastDate +"-------------------
");
  }
});

socket.on('set channels', function(data){
  channelList.empty();
  var channels = data.channels;
  channelCount.val(channels.length);
  channelList.append("Global Chat");
  channels.forEach(function(channel){
    if(!(channel.channelName == channelName)){
      var channelNameVal = channel.channelName;
      var item = ""+ channelNameVal +"";
      channelList.append(item);
    }
  });
});
<|endoftext|>


<commit_before>var test = require('tape').test
  , css = require('./../dist/tree.css')
  , Transform = require('stream').Transform
  , Tree = require('../')
  , stream = require('./tree-stream')
  , util = require('util')

function _container () {
  var container = document.createElement('div')
  container.className = 'container'
  container.style.height = '300px'
  document.body.appendChild(container)
  return container
}

var Extender = function () {
  Transform.apply(this, arguments)
}

util.inherits(Extender, Transform)

Extender.prototype._transform = function (obj, encoding, done) {
  this.push(obj)

  if (obj.id === 1004) {
    // Append an extra 5000 nodes to 1004i
    for (var i = 1; i < 5000; i++) {
      var _id = 100000 + i
      this.push({id: _id, label: 'Extra Node ' + _id, parentId: 1004, nodeType: 'metric', color: 'red'})
    }
    return done()
  }

  done()
}

test('tree is in performance mode', function (t) {
  var s = stream().pipe(new Extender({objectMode: true}))
    , container = _container()
    , tree = new Tree({stream: s}).render()
  container.appendChild(tree.el.node())

  s.on('end', function () {
    tree.expandAll()
    t.equal(tree.el.node().querySelectorAll('.tree ul li').length, Math.floor(300 / tree.options.height) + 3, 'Show a subset of nodes based on scroll height')

    t.ok(tree._tuned, 'tree is tuned')
    // Check height overrides
    t.equal(tree.el.select('.tree ul').node().style.height, Object.keys(tree.nodes).length * tree.options.height + 'px', 'Overrides .tree ul height')
    tree.collapseAll()
    t.ok(!tree._tuned, 'tree is no longer tuned')
    t.equal(tree.el.select('.tree ul').node().style.height, 'auto', 'Sets height back to auto')

    // Check selecting a node that's hidden from performance tuning
    tree.expandAll()
    t.equal(tree.el.select('.tree').node().scrollTop, 0, 'scroll top is 0')

    tree.select(104000)

    t.equal(tree.el.select('.tree ul li.node[data-id="104000"]').size(), 1, '104000 is in the dom')
    t.equal(tree.el.select('.tree').node().scrollTop, 144108, 'scroll top adjusted')

    // Remove the style since the browser is a global nightmare
    document.querySelector('head style').remove()
    container.remove()

    t.end()
  })
})
<commit_msg>Generally speaking, fuck the dom.<commit_after>var test = require('tape').test
  , css = require('./../dist/tree.css')
  , Transform = require('stream').Transform
  , Tree = require('../')
  , stream = require('./tree-stream')
  , util = require('util')

function _container () {
  var container = document.createElement('div')
  container.className = 'container'
  container.style.height = '300px'
  document.body.appendChild(container)
  return container
}

var Extender = function () {
  Transform.apply(this, arguments)
}

util.inherits(Extender, Transform)

Extender.prototype._transform = function (obj, encoding, done) {
  this.push(obj)

  if (obj.id === 1004) {
    // Append an extra 5000 nodes to 1004i
    for (var i = 1; i < 5000; i++) {
      var _id = 100000 + i
      this.push({id: _id, label: 'Extra Node ' + _id, parentId: 1004, nodeType: 'metric', color: 'red'})
    }
    return done()
  }

  done()
}

test('tree is in performance mode', function (t) {
  var s = stream().pipe(new Extender({objectMode: true}))
    , container = _container()
    , tree = new Tree({stream: s}).render()
  container.appendChild(tree.el.node())

  s.on('end', function () {
    tree.expandAll()
    t.equal(tree.el.node().querySelectorAll('.tree ul li').length, Math.floor(300 / tree.options.height) + 3, 'Show a subset of nodes based on scroll height')

    t.ok(tree._tuned, 'tree is tuned')
    // Check height overrides
    t.equal(tree.el.select('.tree ul').node().style.height, Object.keys(tree.nodes).length * tree.options.height + 'px', 'Overrides .tree ul height')
    tree.collapseAll()
    t.ok(!tree._tuned, 'tree is no longer tuned')
    t.equal(tree.el.select('.tree ul').node().style.height, 'auto', 'Sets height back to auto')

    // Check selecting a node that's hidden from performance tuning
    tree.expandAll()
    t.equal(tree.el.select('.tree').node().scrollTop, 0, 'scroll top is 0')

    tree.select(104000)

    t.equal(tree.el.select('.tree ul li.node[data-id="104000"]').size(), 1, '104000 is in the dom')
    t.equal(tree.el.select('.tree').node().scrollTop, 144108, 'scroll top adjusted')

    container.remove()
    t.end()
  })
})
<|endoftext|>


<commit_before>// Load modules

var Code = require('code');
var Hapi = require('hapi');
var Lab = require('lab');
var Ws = require('ws');
var Tv = require('../');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;
var waitForSocketMessages = function(fn) { setTimeout(fn, 50); };

it('reports a request event', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0 } }, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            var port = res.result.match(/var port = (\d+)/)[1];
            var ws = new Ws('ws://' + host + ':' + port);

            ws.once('open', function () {

                ws.send('subscribe:*');

                waitForSocketMessages(function () {

                    server.inject('/?debug=123', function (res) {

                        expect(res.result).to.equal('1');
                    });
                });
            });

            ws.once('message', function (data, flags) {

                expect(JSON.parse(data).data.agent).to.equal('shot');
                done();
            });
        });
    });
});

it('handles subscribe and unsubscribe', function(done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0 } }, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            var port = res.result.match(/var port = (\d+)/)[1];
            var ws = new Ws('ws://' + host + ':' + port);
            var messageCount = 0;

            ws.once('open', function () {

                ws.send('subscribe:*');

                waitForSocketMessages(function () {

                    server.inject('/?debug=123', function() {

                        waitForSocketMessages(function() {

                            var singleRequestMessageCount = messageCount;
                            ws.send('unsubscribe:*');

                            waitForSocketMessages(function() {

                                server.inject('/?debug=123', function() {

                                    waitForSocketMessages(function() {

                                        expect(messageCount).to.equal(singleRequestMessageCount);

                                        done();
                                    });
                                });
                            });
                        });
                    });
                });
            });

            ws.on('message', function (data, flags) {
                ++messageCount;
            });
        });
    });
});

it('does not resubscribe for the same socket', function(done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0 } }, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            var port = res.result.match(/var port = (\d+)/)[1];
            var ws = new Ws('ws://' + host + ':' + port);
            var messageCount = 0;

            ws.once('open', function () {

                ws.send('subscribe:*');

                waitForSocketMessages(function () {

                    server.inject('/?debug=123', function() {

                        waitForSocketMessages(function() {

                            var singleRequestMessageCount = messageCount;
                            ws.send('subscribe:*');

                            waitForSocketMessages(function() {

                                server.inject('/?debug=123', function() {

                                    waitForSocketMessages(function() {

                                        expect(messageCount).to.equal(singleRequestMessageCount * 2);

                                        done();
                                    });
                                });
                            });
                        });
                    });
                });
            });

            ws.on('message', function (data, flags) {
                ++messageCount;
            });
        });
    });
});

it('handles reconnects gracefully', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0, host: 'localhost' }}, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            var port = res.result.match(/var port = (\d+)/)[1];
            var ws1 = new Ws('ws://' + host + ':' + port);

            ws1.once('open', function () {

                ws1.send('subscribe:*');
                ws1.close();
                var ws2 = new Ws('ws://' + host + ':' + port);

                ws2.once('open', function () {

                    ws2.send('subscribe:*');
                    waitForSocketMessages(function () {

                        server.inject('/?debug=123', function (res) {

                            expect(res.result).to.equal('1');
                        });
                    });
                });

                // Shouldn't get called
                ws2.once('message', function (data, flags) {

                    expect(JSON.parse(data).data.agent).to.equal('shot');
                    done();
                });
            });
        });
    });
});

it('uses specified hostname', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({register: Tv, options: { host: '127.0.0.1', port: 0 } }, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            expect(host).to.equal('127.0.0.1');
            done();

        });
    });
});

it('uses specified public hostname', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0, host: 'localhost', publicHost: '127.0.0.1' }}, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            expect(host).to.equal('127.0.0.1');
            done();

        });
    });
});
<commit_msg>Tests for default host value<commit_after>// Load modules

var Code = require('code');
var Hapi = require('hapi');
var Lab = require('lab');
var Ws = require('ws');
var Tv = require('../');
var Os = require('os');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;
var waitForSocketMessages = function(fn) { setTimeout(fn, 50); };

it('reports a request event', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0 } }, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            var port = res.result.match(/var port = (\d+)/)[1];
            var ws = new Ws('ws://' + host + ':' + port);

            ws.once('open', function () {

                ws.send('subscribe:*');

                waitForSocketMessages(function () {

                    server.inject('/?debug=123', function (res) {

                        expect(res.result).to.equal('1');
                    });
                });
            });

            ws.once('message', function (data, flags) {

                expect(JSON.parse(data).data.agent).to.equal('shot');
                done();
            });
        });
    });
});

it('handles subscribe and unsubscribe', function(done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0 } }, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            var port = res.result.match(/var port = (\d+)/)[1];
            var ws = new Ws('ws://' + host + ':' + port);
            var messageCount = 0;

            ws.once('open', function () {

                ws.send('subscribe:*');

                waitForSocketMessages(function () {

                    server.inject('/?debug=123', function() {

                        waitForSocketMessages(function() {

                            var singleRequestMessageCount = messageCount;
                            ws.send('unsubscribe:*');

                            waitForSocketMessages(function() {

                                server.inject('/?debug=123', function() {

                                    waitForSocketMessages(function() {

                                        expect(messageCount).to.equal(singleRequestMessageCount);

                                        done();
                                    });
                                });
                            });
                        });
                    });
                });
            });

            ws.on('message', function (data, flags) {
                ++messageCount;
            });
        });
    });
});

it('does not resubscribe for the same socket', function(done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0 } }, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            var port = res.result.match(/var port = (\d+)/)[1];
            var ws = new Ws('ws://' + host + ':' + port);
            var messageCount = 0;

            ws.once('open', function () {

                ws.send('subscribe:*');

                waitForSocketMessages(function () {

                    server.inject('/?debug=123', function() {

                        waitForSocketMessages(function() {

                            var singleRequestMessageCount = messageCount;
                            ws.send('subscribe:*');

                            waitForSocketMessages(function() {

                                server.inject('/?debug=123', function() {

                                    waitForSocketMessages(function() {

                                        expect(messageCount).to.equal(singleRequestMessageCount * 2);

                                        done();
                                    });
                                });
                            });
                        });
                    });
                });
            });

            ws.on('message', function (data, flags) {
                ++messageCount;
            });
        });
    });
});

it('handles reconnects gracefully', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0, host: 'localhost' }}, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            var port = res.result.match(/var port = (\d+)/)[1];
            var ws1 = new Ws('ws://' + host + ':' + port);

            ws1.once('open', function () {

                ws1.send('subscribe:*');
                ws1.close();
                var ws2 = new Ws('ws://' + host + ':' + port);

                ws2.once('open', function () {

                    ws2.send('subscribe:*');
                    waitForSocketMessages(function () {

                        server.inject('/?debug=123', function (res) {

                            expect(res.result).to.equal('1');
                        });
                    });
                });

                // Shouldn't get called
                ws2.once('message', function (data, flags) {

                    expect(JSON.parse(data).data.agent).to.equal('shot');
                    done();
                });
            });
        });
    });
});

it('uses specified hostname', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({register: Tv, options: { host: '127.0.0.1', port: 0 } }, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            expect(host).to.equal('127.0.0.1');
            done();

        });
    });
});

it('uses specified public hostname', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0, host: 'localhost', publicHost: '127.0.0.1' }}, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            expect(host).to.equal('127.0.0.1');
            done();

        });
    });
});

it('defaults to os hostname if unspecified', function (done) {

    var server = new Hapi.Server();
    server.connection();

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            return reply('1');
        }
    });

    server.register({ register: Tv, options: { port: 0, host: 'localhost', publicHost: '0.0.0.0' }}, function (err) {

        expect(err).to.not.exist();

        server.inject('/debug/console', function (res) {

            expect(res.statusCode).to.equal(200);
            expect(res.result).to.contain('Debug Console');

            var host = res.result.match(/var host = '([^']+)'/)[1];
            expect(host).to.equal(Os.hostname());
            done();

        });
    });
});
<|endoftext|>


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

    var menuItems = {};

    function createMenuItem(opt) {
        var item;

        if (opt !== null && opt.id) {
            var themeSetting = RED.settings.theme("menu."+opt.id);
            if (themeSetting === false) {
                return null;
            }
        }

        function setInitialState() {
            var savedStateActive = RED.settings.get("menu-" + opt.id);
            if (opt.setting) {
                // May need to migrate pre-0.17 setting

                if (savedStateActive !== null) {
                    RED.settings.set(opt.setting,savedStateActive);
                    RED.settings.remove("menu-" + opt.id);
                } else {
                    savedStateActive = RED.settings.get(opt.setting);
                }
            }
            if (savedStateActive) {
                link.addClass("active");
                triggerAction(opt.id,true);
            } else if (savedStateActive === false) {
                link.removeClass("active");
                triggerAction(opt.id,false);
            } else if (opt.hasOwnProperty("selected")) {
                if (opt.selected) {
                    link.addClass("active");
                } else {
                    link.removeClass("active");
                }
                triggerAction(opt.id,opt.selected);
            }
        }

        if (opt === null) {
            item = $('

');
        } else {
            item = $('

');

            if (opt.group) {
                item.addClass("red-ui-menu-group-"+opt.group);

            }
            var linkContent = '';
            if (opt.toggle) {
                linkContent += '';
                linkContent += '';

            }
            if (opt.icon !== undefined) {
                if (/\.(png|svg)/.test(opt.icon)) {
                    linkContent += ' ';
                } else {
                    linkContent += ' ';
                }
            }

            if (opt.sublabel) {
                linkContent += ''+opt.label+''+
                               ''+opt.sublabel+''
            } else {
                linkContent += ''+opt.label+''
            }

            linkContent += '';

            var link = $(linkContent).appendTo(item);
            opt.link = link;
            if (typeof opt.onselect === 'string') {
                var shortcut = RED.keyboard.getShortcut(opt.onselect);
                if (shortcut && shortcut.key) {
                    opt.shortcutSpan = $(''+RED.keyboard.formatKey(shortcut.key, true)+'').appendTo(link.find(".red-ui-menu-label"));
                }
            }

            menuItems[opt.id] = opt;

            if (opt.onselect) {
                link.on("click", function(e) {
                    e.preventDefault();
                    if ($(this).parent().hasClass("disabled")) {
                        return;
                    }
                    if (opt.toggle) {
                        if (opt.toggle === true) {
                            setSelected(opt.id, !isSelected(opt.id));
                        } else {
                            setSelected(opt.id, true);
                        }
                    } else {
                        triggerAction(opt.id);
                    }
                });
                if (opt.toggle) {
                    setInitialState();
                }
            } else if (opt.href) {
                link.attr("target","_blank").attr("href",opt.href);
            } else if (!opt.options) {
                item.addClass("disabled");
                link.on("click", function(event) {
                    event.preventDefault();
                });
            }
            if (opt.options) {
                item.addClass("red-ui-menu-dropdown-submenu pull-left");
                var submenu = $('

').appendTo(item);

                for (var i=0;i<opt.options.length;i++) {
                    var li = createMenuItem(opt.options[i]);
                    if (li) {
                        li.appendTo(submenu);
                    }
                }
            }
            if (opt.disabled) {
                item.addClass("disabled");
            }
        }

        return item;

    }
    function createMenu(options) {
        var topMenu = $("
",{class:"red-ui-menu red-ui-menu-dropdown pull-right"});

        if (options.id) {
            topMenu.attr({id:options.id+"-submenu"});
            var menuParent = $("#"+options.id);
            if (menuParent.length === 1) {
                topMenu.insertAfter(menuParent);
                menuParent.on("click", function(evt) {
                    evt.stopPropagation();
                    evt.preventDefault();
                    if (topMenu.is(":visible")) {
                        $(document).off("click.red-ui-menu");
                        topMenu.hide();
                    } else {
                        $(document).on("click.red-ui-menu", function(evt) {
                            $(document).off("click.red-ui-menu");
                            activeMenu = null;
                            topMenu.hide();
                        });
                        $(".red-ui-menu.red-ui-menu-dropdown").hide();
                        topMenu.show();
                    }
                })
            }
        }

        var lastAddedSeparator = false;
        for (var i=0;i<options.options.length;i++) {
            var opt = options.options[i];
            if (opt !== null || !lastAddedSeparator) {
                var li = createMenuItem(opt);
                if (li) {
                    li.appendTo(topMenu);
                    lastAddedSeparator = (opt === null);
                }
            }
        }

        return topMenu;
    }

    function triggerAction(id, args) {
        var opt = menuItems[id];
        var callback = opt.onselect;
        if (typeof opt.onselect === 'string') {
            callback = RED.actions.get(opt.onselect);
        }
        if (callback) {
            callback.call(opt,args);
        } else {
            console.log("No callback for",id,opt.onselect);
        }
    }

    function isSelected(id) {
        return $("#" + id).hasClass("active");
    }

    function setSelected(id,state) {
        var alreadySet = false;
        if (isSelected(id) == state) {
            alreadySet = true;
        }
        var opt = menuItems[id];
        if (state) {
            $("#"+id).addClass("active");
        } else {
            $("#"+id).removeClass("active");
        }
        if (opt) {
            if (opt.toggle && typeof opt.toggle === "string") {
                if (state) {
                    for (var m in menuItems) {
                        if (menuItems.hasOwnProperty(m)) {
                            var mi = menuItems[m];
                            if (mi.id != opt.id && opt.toggle == mi.toggle) {
                                setSelected(mi.id,false);
                            }
                        }
                    }
                }
            }
            if (!alreadySet && opt.onselect) {
                triggerAction(opt.id,state);
            }
            if (!opt.local && !alreadySet) {
                RED.settings.set(opt.setting||("menu-"+opt.id), state);
            }
        }
    }

    function toggleSelected(id) {
        setSelected(id,!isSelected(id));
    }

    function setDisabled(id,state) {
        if (state) {
            $("#"+id).parent().addClass("disabled");
        } else {
            $("#"+id).parent().removeClass("disabled");
        }
    }

    function addItem(id,opt) {
        var item = createMenuItem(opt);
        if (opt !== null && opt.group) {
            var groupItems = $("#"+id+"-submenu").children(".red-ui-menu-group-"+opt.group);
            if (groupItems.length === 0) {
                item.appendTo("#"+id+"-submenu");
            } else {
                for (var i=0;i<groupItems.length;i++) {
                    var groupItem = groupItems[i];
                    var label = $(groupItem).find(".red-ui-menu-label").html();
                    if (opt.label < label) {
                        $(groupItem).before(item);
                        break;
                    }
                }
                if (i === groupItems.length) {
                    item.appendTo("#"+id+"-submenu");
                }
            }
        } else {
            item.appendTo("#"+id+"-submenu");
        }
    }
    function removeItem(id) {
        $("#"+id).parent().remove();
    }

    function setAction(id,action) {
        var opt = menuItems[id];
        if (opt) {
            opt.onselect = action;
        }
    }

    function refreshShortcuts() {
        for (var id in menuItems) {
            if (menuItems.hasOwnProperty(id)) {
                var opt = menuItems[id];
                if (typeof opt.onselect === "string" && opt.shortcutSpan) {
                    opt.shortcutSpan.remove();
                    delete opt.shortcutSpan;
                    var shortcut = RED.keyboard.getShortcut(opt.onselect);
                    if (shortcut && shortcut.key) {
                        opt.shortcutSpan = $(''+RED.keyboard.formatKey(shortcut.key, true)+'').appendTo(opt.link.find(".red-ui-menu-label"));
                    }
                }
            }
        }
    }

    return {
        init: createMenu,
        setSelected: setSelected,
        isSelected: isSelected,
        toggleSelected: toggleSelected,
        setDisabled: setDisabled,
        addItem: addItem,
        removeItem: removeItem,
        setAction: setAction,
        refreshShortcuts: refreshShortcuts
    }
})();
<commit_msg>Add onpre/postselect, direction opts to menu and make id optional<commit_after>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
RED.menu = (function() {

    var menuItems = {};
    let menuItemCount = 0

    function createMenuItem(opt) {
        var item;

        if (opt !== null && opt.id) {
            var themeSetting = RED.settings.theme("menu."+opt.id);
            if (themeSetting === false) {
                return null;
            }
        }

        function setInitialState() {
            var savedStateActive = RED.settings.get("menu-" + opt.id);
            if (opt.setting) {
                // May need to migrate pre-0.17 setting

                if (savedStateActive !== null) {
                    RED.settings.set(opt.setting,savedStateActive);
                    RED.settings.remove("menu-" + opt.id);
                } else {
                    savedStateActive = RED.settings.get(opt.setting);
                }
            }
            if (savedStateActive) {
                link.addClass("active");
                triggerAction(opt.id,true);
            } else if (savedStateActive === false) {
                link.removeClass("active");
                triggerAction(opt.id,false);
            } else if (opt.hasOwnProperty("selected")) {
                if (opt.selected) {
                    link.addClass("active");
                } else {
                    link.removeClass("active");
                }
                triggerAction(opt.id,opt.selected);
            }
        }

        if (opt === null) {
            item = $('

');
        } else {
            item = $('

');
            if (!opt.id) {
                opt.id = 'red-ui-menu-item-'+(menuItemCount++)
            }
            if (opt.group) {
                item.addClass("red-ui-menu-group-"+opt.group);
            }
            var linkContent = '';
            if (opt.toggle) {
                linkContent += '';
                linkContent += '';

            }
            if (opt.icon !== undefined) {
                if (/\.(png|svg)/.test(opt.icon)) {
                    linkContent += ' ';
                } else {
                    linkContent += ' ';
                }
            }
            let label = opt.label
            if (!opt.label && typeof opt.onselect === 'string') {
                label = RED.actions.getLabel(opt.onselect)
            }
            if (opt.sublabel) {
                linkContent += ''+label+''+
                               ''+opt.sublabel+''
            } else {
                linkContent += ''+label+''
            }

            linkContent += '';

            var link = $(linkContent).appendTo(item);
            opt.link = link;
            if (typeof opt.onselect === 'string') {
                var shortcut = RED.keyboard.getShortcut(opt.onselect);
                if (shortcut && shortcut.key) {
                    opt.shortcutSpan = $(''+RED.keyboard.formatKey(shortcut.key, true)+'').appendTo(link.find(".red-ui-menu-label"));
                }
            }

            menuItems[opt.id] = opt;

            if (opt.onselect) {
                link.on("click", function(e) {
                    e.preventDefault();
                    if ($(this).parent().hasClass("disabled")) {
                        return;
                    }
                    if (opt.toggle) {
                        if (opt.toggle === true) {
                            setSelected(opt.id, !isSelected(opt.id));
                        } else {
                            setSelected(opt.id, true);
                        }
                    } else {
                        triggerAction(opt.id);
                    }
                });
                if (opt.toggle) {
                    setInitialState();
                }
            } else if (opt.href) {
                link.attr("target","_blank").attr("href",opt.href);
            } else if (!opt.options) {
                item.addClass("disabled");
                link.on("click", function(event) {
                    event.preventDefault();
                });
            }
            if (opt.options) {
                item.addClass("red-ui-menu-dropdown-submenu"+(opt.direction!=='right'?" pull-left":""));
                var submenu = $('

').appendTo(item);

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

                    if (opt.options[i]) {
                        if (opt.onpreselect && opt.options[i].onpreselect === undefined) {
                            opt.options[i].onpreselect = opt.onpreselect
                        }
                        if (opt.onpostselect && opt.options[i].onpostselect === undefined) {
                            opt.options[i].onpostselect = opt.onpostselect
                        }
                        opt.options[i].direction = opt.direction
                    }

                    var li = createMenuItem(opt.options[i]);
                    if (li) {
                        li.appendTo(submenu);
                    }
                }
            }
            if (opt.disabled) {
                item.addClass("disabled");
            }
        }

        return item;

    }
    function createMenu(options) {
        var topMenu = $("
",{class:"red-ui-menu red-ui-menu-dropdown pull-right"});
        if (options.direction) {
            topMenu.addClass("red-ui-menu-dropdown-direction-"+options.direction)
        }
        if (options.id) {
            topMenu.attr({id:options.id+"-submenu"});
            var menuParent = $("#"+options.id);
            if (menuParent.length === 1) {
                topMenu.insertAfter(menuParent);
                menuParent.on("click", function(evt) {
                    evt.stopPropagation();
                    evt.preventDefault();
                    if (topMenu.is(":visible")) {
                        $(document).off("click.red-ui-menu");
                        topMenu.hide();
                    } else {
                        $(document).on("click.red-ui-menu", function(evt) {
                            $(document).off("click.red-ui-menu");
                            activeMenu = null;
                            topMenu.hide();
                        });
                        $(".red-ui-menu.red-ui-menu-dropdown").hide();
                        topMenu.show();
                    }
                })
            }
        }

        var lastAddedSeparator = false;
        for (var i=0;i<options.options.length;i++) {
            var opt = options.options[i];
            if (opt) {
                if (options.onpreselect && opt.onpreselect === undefined) {
                    opt.onpreselect = options.onpreselect
                }
                if (options.onpostselect && opt.onpostselect === undefined) {
                    opt.onpostselect = options.onpostselect
                }
                opt.direction = options.direction || 'left'
            }
            if (opt !== null || !lastAddedSeparator) {
                var li = createMenuItem(opt);
                if (li) {
                    li.appendTo(topMenu);
                    lastAddedSeparator = (opt === null);
                }
            }
        }

        return topMenu;
    }

    function triggerAction(id, args) {
        var opt = menuItems[id];
        var callback = opt.onselect;
        if (opt.onpreselect) {
            opt.onpreselect.call(opt,args)
        }
        if (typeof opt.onselect === 'string') {
            callback = RED.actions.get(opt.onselect);
        }
        if (callback) {
            callback.call(opt,args);
        } else {
            console.log("No callback for",id,opt.onselect);
        }
        if (opt.onpostselect) {
            opt.onpostselect.call(opt,args)
        }
    }

    function isSelected(id) {
        return $("#" + id).hasClass("active");
    }

    function setSelected(id,state) {
        var alreadySet = false;
        if (isSelected(id) == state) {
            alreadySet = true;
        }
        var opt = menuItems[id];
        if (state) {
            $("#"+id).addClass("active");
        } else {
            $("#"+id).removeClass("active");
        }
        if (opt) {
            if (opt.toggle && typeof opt.toggle === "string") {
                if (state) {
                    for (var m in menuItems) {
                        if (menuItems.hasOwnProperty(m)) {
                            var mi = menuItems[m];
                            if (mi.id != opt.id && opt.toggle == mi.toggle) {
                                setSelected(mi.id,false);
                            }
                        }
                    }
                }
            }
            if (!alreadySet && opt.onselect) {
                triggerAction(opt.id,state);
            }
            if (!opt.local && !alreadySet) {
                RED.settings.set(opt.setting||("menu-"+opt.id), state);
            }
        }
    }

    function toggleSelected(id) {
        setSelected(id,!isSelected(id));
    }

    function setDisabled(id,state) {
        if (state) {
            $("#"+id).parent().addClass("disabled");
        } else {
            $("#"+id).parent().removeClass("disabled");
        }
    }

    function addItem(id,opt) {
        var item = createMenuItem(opt);
        if (opt !== null && opt.group) {
            var groupItems = $("#"+id+"-submenu").children(".red-ui-menu-group-"+opt.group);
            if (groupItems.length === 0) {
                item.appendTo("#"+id+"-submenu");
            } else {
                for (var i=0;i<groupItems.length;i++) {
                    var groupItem = groupItems[i];
                    var label = $(groupItem).find(".red-ui-menu-label").html();
                    if (opt.label < label) {
                        $(groupItem).before(item);
                        break;
                    }
                }
                if (i === groupItems.length) {
                    item.appendTo("#"+id+"-submenu");
                }
            }
        } else {
            item.appendTo("#"+id+"-submenu");
        }
    }
    function removeItem(id) {
        $("#"+id).parent().remove();
    }

    function setAction(id,action) {
        var opt = menuItems[id];
        if (opt) {
            opt.onselect = action;
        }
    }

    function refreshShortcuts() {
        for (var id in menuItems) {
            if (menuItems.hasOwnProperty(id)) {
                var opt = menuItems[id];
                if (typeof opt.onselect === "string" && opt.shortcutSpan) {
                    opt.shortcutSpan.remove();
                    delete opt.shortcutSpan;
                    var shortcut = RED.keyboard.getShortcut(opt.onselect);
                    if (shortcut && shortcut.key) {
                        opt.shortcutSpan = $(''+RED.keyboard.formatKey(shortcut.key, true)+'').appendTo(opt.link.find(".red-ui-menu-label"));
                    }
                }
            }
        }
    }

    return {
        init: createMenu,
        setSelected: setSelected,
        isSelected: isSelected,
        toggleSelected: toggleSelected,
        setDisabled: setDisabled,
        addItem: addItem,
        removeItem: removeItem,
        setAction: setAction,
        refreshShortcuts: refreshShortcuts
    }
})();
<|endoftext|>


<commit_before>var d3 = require('d3');

var _data = [],
    _width = 500,
    _height = 500,
    _layout = 'force',
    _svg = null,
    _colors = d3.scale.category20c();

var _tick = function(){
    _svg.selectAll('.link')
        .attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

    _svg.selectAll('.node')
        .attr('cx', function(d) { return d.x; })
        .attr('cy', function(d) { return d.y; });
};

var _force = function(){
    var nodes = _data.get('interactors').toJSON(),
        links = _data.get('interactions').toJSON();

    _.each(links, function(l){

        l.target = _.find(nodes, function(n){
            return n.id == l.target;
        });

        l.source = _.find(nodes, function(n){
            return n.id == l.source;
        });
    });

    var max = _.max(nodes, function(d){ return d.weight; });

    var size = d3.scale.ordinal().domain([1, max]).range([2,6]);

    // start the force layout.
    var force = d3.layout.force()
        .size([_width, _height])
        .on('tick', _tick)
        .nodes(nodes)
        .links(links)
        .start();

    _svg.selectAll('.link').remove();
    links = _svg.selectAll('.link').data(links);

    links.enter().append('line')
        .attr('class', 'link')
        .attr('fill', 'none')
        .attr('stroke', '#ccc')
        .attr('stroke-width', 1.5)
        .attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

    nodes = _svg.selectAll('.node').data(nodes);

    nodes.enter().append('circle')
            .attr('class', 'node')
            .attr('stroke-width', 1.5)
            .attr('stroke', 'gray')
            .attr('r', function(d){return size(d.weight);})
            .on('mouseover', function(d){
                d3.select(this).style('cursor','pointer');
            })
            .on('mouseout', function(d){
                d3.select(this).style('cursor','default');
            })
            .on('click', function(d){
                console.log(d);
            })
            .call(force.drag);

    _svg.transition().attr('transform', '');

    nodes.attr('fill', function(d){return _colors(d.taxonomy ? d.taxonomy[0] : null);})
        .attr('cx', function(d) { return d.x; })
        .attr('cy', function(d) { return d.y; });

    links.exit().remove();
    nodes.exit().remove();
};

// Public members
var network = function(){};

network.data = function(_){
    if (!arguments.length)
        return _data;
    _data = _;
    return network;
};

network.width = function(_){
    if (!arguments.length)
        return _width;
    _width = _;
    return network;
};

network.height = function(_){
    if (!arguments.length)
        return _height;
    _height = _;
    return network;
};

network.layout = function(_){
    if (!arguments.length)
        return _layout;
    _layout = _;
    return network;
};

network.selector = function(_){

    if (!arguments.length)
        return _svg;
    _svg = d3.selectAll(_);
    return network;
};

network.update = function(){
    _svg.attr('width', _width).attr('height', _height);

    if (_layout == 'radial'){
        _radial();
    }else{
        _force();
    }
    return network;
};

module.exports = network;<commit_msg>added functions for svg initialization and mouseover/out thus highlighting nodes accordingly<commit_after>var d3 = require('d3');

var _data = [],
    _width = 500,
    _height = 500,
    _layout = 'force',
    _svg = null,
    _g = null,
    _colors = d3.scale.category20c();

var _mouseover = function(d){
    d3.select(this)
        .style('cursor','pointer')
        .attr('stroke', '#000')
        .attr('stroke-width', 2);
};

var _mouseout = function(d){
    d3.select(this)
        .style('cursor','default')
        .attr('stroke', 'gray')
        .attr('stroke-width', 1.5);
};

var _initSelector = function(_){
    _svg = d3.selectAll(_);

    var zoom = d3.behavior.zoom()
        .on('zoom', function(){
            _g.attr('transform', 'translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')');
        });

    _g = _svg.call(zoom).append('g');
};

var _tick = function(){
    _g.selectAll('.link')
        .attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

    _g.selectAll('.node')
        .attr('cx', function(d) { return d.x; })
        .attr('cy', function(d) { return d.y; });
};

var _force = function(){
    var nodes = _data.get('interactors').toJSON(),
        links = _data.get('interactions').toJSON();

    _.each(links, function(l){

        l.target = _.find(nodes, function(n){
            return n.id == l.target;
        });

        l.source = _.find(nodes, function(n){
            return n.id == l.source;
        });
    });

    var max = _.max(nodes, function(d){ return d.weight; });

    var size = d3.scale.ordinal().domain([1, max]).range([3,7]);

    // start the force layout.
    var force = d3.layout.force()
        .size([_width, _height])
        .on('tick', _tick)
        .nodes(nodes)
        .links(links)
        .start();

    _g.selectAll('.link').remove();
    links = _g.selectAll('.link').data(links);

    links.enter().append('line')
        .attr('class', 'link')
        .attr('fill', 'none')
        .attr('stroke', '#ccc')
        .attr('stroke-width', 1.5)
        .attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

    nodes = _g.selectAll('.node').data(nodes);

    nodes.enter().append('circle')
            .attr('class', 'node')
            .attr('stroke-width', 1.5)
            .attr('stroke', 'gray')
            .attr('r', function(d){return size(d.weight);})
            .on('mouseover', _mouseover)
            .on('mouseout', _mouseout)
            .on('click', function(d){
                console.log(d);
            })
            .call(force.drag);

    _g.transition().attr('transform', '');

    nodes.attr('fill', function(d){return _colors(d.taxonomy ? d.taxonomy[0] : null);})
        .attr('cx', function(d) { return d.x; })
        .attr('cy', function(d) { return d.y; });

    links.exit().remove();
    nodes.exit().remove();
};

// Public members
var network = function(){};

network.data = function(_){
    if (!arguments.length)
        return _data;
    _data = _;
    return network;
};

network.width = function(_){
    if (!arguments.length)
        return _width;
    _width = _;
    return network;
};

network.height = function(_){
    if (!arguments.length)
        return _height;
    _height = _;
    return network;
};

network.layout = function(_){
    if (!arguments.length)
        return _layout;
    _layout = _;
    return network;
};

network.selector = function(_){

    if (!arguments.length)
        return _svg;

    _initSelector(_);
    return network;
};

network.update = function(){
    _svg.attr('width', _width).attr('height', _height);

    if (_layout == 'radial'){
        _radial();
    }else{
        _force();
    }
    return network;
};

module.exports = network;<|endoftext|>


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

// Dreem/Dali server
require = require('./system/base/define') // support define.js modules

// load up math core and make it global
require('$system/base/math')

if(process.argv.indexOf('-nomoni') != -1){
	define.atRequire = function(filename){
		process.stderr.write('\x0F' + filename + '\n', function(){})
	}
}

var fs = require('fs')
var path = require('path')

// ok now we can require components
var ansicolor = require('$system/debug/ansicolor')
console.color = ansicolor(function(v){
	process.stdout.write(v)
})

console.clear = function(){
	process.stdout.write("\033[2J");
}

console.setposition = function(x, y){
	process.stdout.write("\033[" + y.toString() + ";" + x.toString() + "f")
}

// make a nice console.dump function
var dump = require('$system/debug/dump')
console.dump = function(){
	// lets grab where we are called
	console.log(new Error().stack)
	console.color(dump(Array.prototype.slice.apply(arguments), 1000000, dump.colors))
}

function main(){
	var argv = process.argv
	var args = {}
	for(var lastkey = '', arg, i = 0; i<argv.length; i++){
		arg = argv[i]
		if(arg.charAt(0) == '-') lastkey = arg, args[lastkey] = true
		else {
			if(lastkey in args && args[lastkey] !== true){
				if(!Array.isArray(args[lastkey])) args[lastkey] = [args[lastkey]]
				args[lastkey].push(arg)
			}
			else args[lastkey] = arg
		}
	}

	if(args['-nomoni'] && args['-trace']){
		var trace = require('$system/debug/trace')
		define.atModule = function(module){
			module.exports = trace(module.exports, module.filename, args['-trace'])
		}
	}

	if(args['-h'] || args['-help'] || args['--h'] || args['--help']){
		console.color('~by~Teem~~ Server ~bm~2.0~~\n')
		console.color('commandline: node server.js <flags>\n')
		console.color('~bc~-port ~br~[port]~~ Server port\n')
		console.color('~bc~-nomoni ~~ Start process without monitor\n')
		console.color('~bc~-iface ~br~[interface]~~ Server interface\n')
		console.color('~bc~-restart~~ Auto restarts after crash (Handy for client dev, not server dev)\n')
		console.color('~bc~-path~~ [name]:~br~[directory]~~ add a path to the server under name $name\n')
		console.color('~bc~-dali~~ run a composition in DALi\n')
		console.color('~bc~-dalilib~~ can be used to point to the DALi node-addon installation folder on Ubuntu (only to be used in combination with the ~bc~-dali~~ flag)\n')
		console.color('~bc~-writefile ~~ Allow server to write files to disk\n')
		return process.exit(0)
	}

	// our default pathmap
	// NOTE: if you change this, also update README.md
	define.paths = {
		'system':'$root/system',
		'resources':'$root/resources',
		'3d':'$root/classes/3d',
		'behaviors':'$root/classes/behaviors',
		'server':'$root/classes/server',
		'ui':'$root/classes/ui',
		'flow':'$root/classes/flow',
		'testing':'$root/classes/testing',
		'widgets':'$root/classes/widgets',
		'sensors':'$root/classes/sensors',
		'iot':'$root/classes/iot',
		'examples':'$root/examples',
		'apps':'$root/apps',
		'docs':'$root/docs',
		'test':'$root/test'
	}

	if(args['-writefile']){
		Object.defineProperty(define, "$writefile", {
		    value: true,
		    writable: false
		});
	}
	else{
		Object.defineProperty(define, "$writefile", {
		    value: false,
		    writable: false
		});
	}

	if(args['-unsafeorigin']){
		Object.defineProperty(define, "$unsafeorigin", {
			value: true,
			writable: false
		});
	}
	else{
		Object.defineProperty(define, "$unsafeorigin", {
			value: false,
			writable: false
		});
	}

	if(args['-nomoni']){
		var paths = Array.isArray(args['-path'])?args['-path']:[args['-path']]
		for(var i = 0; i < paths.length; i++){
			if(!paths[i]) continue
			var parts = paths[i].split(':')
			var mypath =	parts[1].charAt(0) === '/'? parts[1]: define.joinPath(define.$root, parts[1])
			console.log('Mapping '+parts[0]+' to ' + mypath)
			define.paths[parts[0]] = mypath
		}
		// put them on the define
		for(var key in define.paths){
			define['$'+key] = define.paths[key]
		}
	}

	define.$platform = 'headless'

	if (args['-jsduckgen']) {
		define.$platform = 'nodejs'
		for(var key in define.paths){
			define['$'+key] = define.paths[key]
		}

		var DocBuilder = require('$system/server/docbuilder')
		new DocBuilder(args)

	} else if(args['-nodegl']){
		// lets do an async require on our UI
		define.$platform = 'nodegl'
		var NodeGL = require('$system/platform/nodegl/bootnodegl')
		new NodeGL(args)
	}
	else if(args['-nomoni']){
		if(args['-sync']){
			var GitSync = require('$system/server/gitsync')

			new GitSync(args)
		}
		else if(args['-headless']){
				var composition = args['-headless'];
				define.$platform = 'headless'
				define.$environment = 'headless' // Otherwise it is nodejs

			//TODO
			// Store the path from the root to the specified directory.
			// There is a mismatch between headless and dreem server.
			var index = composition.lastIndexOf('/');
			if (index < 0) index = composition.lastIndexOf('\\');
			define.$example = (index >= 0) ? composition.substring(0,index+1) : './'
			try {
				// The images are relative to ths specified directory
				if (fs.statSync(composition).isDirectory())
					define.$example = './' + composition + '/'
			}
			catch (e) {
			}

			var BootHeadless = require('$system/platform/headless/bootheadless')
			new BootHeadless(args, composition);
		}
		else if(args['-dali']){
			// Place the dali/nodejs package at the root of dreemgl

				var composition = args['-dali'];
				if (composition === true)
					composition = 'examples/rendertest'

				define.$platform = 'dali'
				define.$environment = 'dali' // Otherwise it is nodejs

			//TODO
			// Store the path from the root to the specified directory.
			// There is a mismatch between dali and dreem server.
			var index = composition.lastIndexOf('/');
			define.$example = (index >= 0) ? composition.substring(0,index+1) : './'
			try {
				// The images are relative to ths specified directory
				if (fs.statSync(composition).isDirectory())
					define.$example = './' + composition + '/'
			}
			catch (e) {
			}

				var BootDali = require('$system/platform/dali/bootdali')
				new BootDali(args, composition);
		}
		else if(args['-test']){
			require('$system/server/test.js')

		}
		else{
			define.$platform = 'nodejs'
			var RootServer = require('$system/server/rootserver')
			new RootServer(args)
		}

	}
	else{
		var RunMonitor = require('$system/server/runmonitor')
		new RunMonitor(args)
	}
}

main()
<commit_msg>Updated comment for default path doc<commit_after>/* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
   Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License.
   You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and limitations under the License.*/

// Dreem/Dali server
require = require('./system/base/define') // support define.js modules

// load up math core and make it global
require('$system/base/math')

if(process.argv.indexOf('-nomoni') != -1){
	define.atRequire = function(filename){
		process.stderr.write('\x0F' + filename + '\n', function(){})
	}
}

var fs = require('fs')
var path = require('path')

// ok now we can require components
var ansicolor = require('$system/debug/ansicolor')
console.color = ansicolor(function(v){
	process.stdout.write(v)
})

console.clear = function(){
	process.stdout.write("\033[2J");
}

console.setposition = function(x, y){
	process.stdout.write("\033[" + y.toString() + ";" + x.toString() + "f")
}

// make a nice console.dump function
var dump = require('$system/debug/dump')
console.dump = function(){
	// lets grab where we are called
	console.log(new Error().stack)
	console.color(dump(Array.prototype.slice.apply(arguments), 1000000, dump.colors))
}

function main(){
	var argv = process.argv
	var args = {}
	for(var lastkey = '', arg, i = 0; i<argv.length; i++){
		arg = argv[i]
		if(arg.charAt(0) == '-') lastkey = arg, args[lastkey] = true
		else {
			if(lastkey in args && args[lastkey] !== true){
				if(!Array.isArray(args[lastkey])) args[lastkey] = [args[lastkey]]
				args[lastkey].push(arg)
			}
			else args[lastkey] = arg
		}
	}

	if(args['-nomoni'] && args['-trace']){
		var trace = require('$system/debug/trace')
		define.atModule = function(module){
			module.exports = trace(module.exports, module.filename, args['-trace'])
		}
	}

	if(args['-h'] || args['-help'] || args['--h'] || args['--help']){
		console.color('~by~Teem~~ Server ~bm~2.0~~\n')
		console.color('commandline: node server.js <flags>\n')
		console.color('~bc~-port ~br~[port]~~ Server port\n')
		console.color('~bc~-nomoni ~~ Start process without monitor\n')
		console.color('~bc~-iface ~br~[interface]~~ Server interface\n')
		console.color('~bc~-restart~~ Auto restarts after crash (Handy for client dev, not server dev)\n')
		console.color('~bc~-path~~ [name]:~br~[directory]~~ add a path to the server under name $name\n')
		console.color('~bc~-dali~~ run a composition in DALi\n')
		console.color('~bc~-dalilib~~ can be used to point to the DALi node-addon installation folder on Ubuntu (only to be used in combination with the ~bc~-dali~~ flag)\n')
		console.color('~bc~-writefile ~~ Allow server to write files to disk\n')
		return process.exit(0)
	}

	// our default pathmap
	// NOTE: if you change this, also update /docs/guides/dreem_in_10/README.md
	define.paths = {
		'system':'$root/system',
		'resources':'$root/resources',
		'3d':'$root/classes/3d',
		'behaviors':'$root/classes/behaviors',
		'server':'$root/classes/server',
		'ui':'$root/classes/ui',
		'flow':'$root/classes/flow',
		'testing':'$root/classes/testing',
		'widgets':'$root/classes/widgets',
		'sensors':'$root/classes/sensors',
		'iot':'$root/classes/iot',
		'examples':'$root/examples',
		'apps':'$root/apps',
		'docs':'$root/docs',
		'test':'$root/test'
	}

	if(args['-writefile']){
		Object.defineProperty(define, "$writefile", {
		    value: true,
		    writable: false
		});
	}
	else{
		Object.defineProperty(define, "$writefile", {
		    value: false,
		    writable: false
		});
	}

	if(args['-unsafeorigin']){
		Object.defineProperty(define, "$unsafeorigin", {
			value: true,
			writable: false
		});
	}
	else{
		Object.defineProperty(define, "$unsafeorigin", {
			value: false,
			writable: false
		});
	}

	if(args['-nomoni']){
		var paths = Array.isArray(args['-path'])?args['-path']:[args['-path']]
		for(var i = 0; i < paths.length; i++){
			if(!paths[i]) continue
			var parts = paths[i].split(':')
			var mypath =	parts[1].charAt(0) === '/'? parts[1]: define.joinPath(define.$root, parts[1])
			console.log('Mapping '+parts[0]+' to ' + mypath)
			define.paths[parts[0]] = mypath
		}
		// put them on the define
		for(var key in define.paths){
			define['$'+key] = define.paths[key]
		}
	}

	define.$platform = 'headless'

	if (args['-jsduckgen']) {
		define.$platform = 'nodejs'
		for(var key in define.paths){
			define['$'+key] = define.paths[key]
		}

		var DocBuilder = require('$system/server/docbuilder')
		new DocBuilder(args)

	} else if(args['-nodegl']){
		// lets do an async require on our UI
		define.$platform = 'nodegl'
		var NodeGL = require('$system/platform/nodegl/bootnodegl')
		new NodeGL(args)
	}
	else if(args['-nomoni']){
		if(args['-sync']){
			var GitSync = require('$system/server/gitsync')

			new GitSync(args)
		}
		else if(args['-headless']){
				var composition = args['-headless'];
				define.$platform = 'headless'
				define.$environment = 'headless' // Otherwise it is nodejs

			//TODO
			// Store the path from the root to the specified directory.
			// There is a mismatch between headless and dreem server.
			var index = composition.lastIndexOf('/');
			if (index < 0) index = composition.lastIndexOf('\\');
			define.$example = (index >= 0) ? composition.substring(0,index+1) : './'
			try {
				// The images are relative to ths specified directory
				if (fs.statSync(composition).isDirectory())
					define.$example = './' + composition + '/'
			}
			catch (e) {
			}

			var BootHeadless = require('$system/platform/headless/bootheadless')
			new BootHeadless(args, composition);
		}
		else if(args['-dali']){
			// Place the dali/nodejs package at the root of dreemgl

				var composition = args['-dali'];
				if (composition === true)
					composition = 'examples/rendertest'

				define.$platform = 'dali'
				define.$environment = 'dali' // Otherwise it is nodejs

			//TODO
			// Store the path from the root to the specified directory.
			// There is a mismatch between dali and dreem server.
			var index = composition.lastIndexOf('/');
			define.$example = (index >= 0) ? composition.substring(0,index+1) : './'
			try {
				// The images are relative to ths specified directory
				if (fs.statSync(composition).isDirectory())
					define.$example = './' + composition + '/'
			}
			catch (e) {
			}

				var BootDali = require('$system/platform/dali/bootdali')
				new BootDali(args, composition);
		}
		else if(args['-test']){
			require('$system/server/test.js')

		}
		else{
			define.$platform = 'nodejs'
			var RootServer = require('$system/server/rootserver')
			new RootServer(args)
		}

	}
	else{
		var RunMonitor = require('$system/server/runmonitor')
		new RunMonitor(args)
	}
}

main()
<|endoftext|>


<commit_before>'use strict';

// Parses the cliArgs, check if all constraints for the specified command are
// fullfilled and if so it returns { command: Object, commandOptions: Object }
// else it return null.

var nopt  = require('nopt');
var chalk = require('chalk');

module.exports = parseCLIArgs;
function parseCLIArgs(ui, environment) {
  var commands        = environment.commands;
  var commandName     = environment.cliArgs[0];
  var cliArgs         = environment.cliArgs;
  var knownOpts       = {}; // Parse options
  var commandOptions  = {}; // Set defaults and check if required options are present
  var isWithinProject = environment.isWithinProject;
  var parsedOptions;

  var assembleAndValidateOption = function(option) {
    if (parsedOptions[option.name] === undefined) {
      if (option.default !== undefined) {
        commandOptions[option.key] = option.default;
      } else if (option.required) {
        ui.write('The specified command ' + chalk.green(commandName) +
                 ' requires the option ' + chalk.green(option.name) + '.\n');
        return false;
      }
    } else {
      commandOptions[option.key] = parsedOptions[option.name];
    }
    return true;
  };

  // Find the first command which name or one of it's aliases matches
  var command = (function findMatchingCommand() {
    function aliasMatches(alias) {
      return alias === commandName;
    }

    for (var key in commands) {
      var command = commands[key];
      if (command.name === commandName || command.aliases.some(aliasMatches)) {
        return command;
      }
    }
  })();

  // Complain if no command was found
  if (!command) {
    ui.write('The specified command ' + chalk.green(commandName) +
             ' is invalid, for available options see ' +
              chalk.green('ember help') + '.\n');
    return null;
  }

  if (command.works === 'insideProject') {
    if (!isWithinProject) {
      ui.write('You have to be inside an ember-cli project in order to use ' +
               'the ' + chalk.green(commandName) + ' command.\n');
      return null;
    }
  }

  if (command.works === 'outsideProject') {
    if (isWithinProject) {
      ui.write('You cannot use the '+  chalk.green(commandName) +
               ' command inside an ember-cli project.\n');
      return null;
    }
  }

  command.availableOptions.forEach(function(option) {
    knownOpts[option.name] = option.type;
  });

  parsedOptions = nopt(knownOpts, {}, cliArgs, 1);

  if (!command.availableOptions.every(assembleAndValidateOption)) {
    return null;
  }

  return {
    command: command,
    commandOptions: commandOptions
  };
}
<commit_msg>small cleanup to parse-cli-args, hopefully it gets more soon<commit_after>'use strict';

// Parses the cliArgs, check if all constraints for the specified command are
// fullfilled and if so it returns { command: Object, commandOptions: Object }
// else it return null.

var nopt  = require('nopt');
var chalk = require('chalk');

module.exports = parseCLIArgs;

function findCommand(commands, commandName) {
  function aliasMatches(alias) {
    return alias === commandName;
  }

  for (var key in commands) {
    var command = commands[key];

    if (command.name === commandName || command.aliases.some(aliasMatches)) {
      return command;
    }
  }
}

function parseCLIArgs(ui, environment) {
  // TODO: drop the environment god object
  var commands        = environment.commands;
  var commandName     = environment.cliArgs[0];
  var cliArgs         = environment.cliArgs;
  var knownOpts       = {}; // Parse options
  var commandOptions  = {}; // Set defaults and check if required options are present
  var isWithinProject = environment.isWithinProject;
  var parsedOptions;

  // TODO: clean this up
  var assembleAndValidateOption = function(option) {
    if (parsedOptions[option.name] === undefined) {
      if (option.default !== undefined) {
        commandOptions[option.key] = option.default;
      } else if (option.required) {
        ui.write('The specified command ' + chalk.green(commandName) +
                 ' requires the option ' + chalk.green(option.name) + '.\n');
        return false;
      }
    } else {
      commandOptions[option.key] = parsedOptions[option.name];
    }
    return true;
  };

  var command = findCommand(commands, commandName);

  if (!command) {
    ui.write('The specified command ' + chalk.green(commandName) +
             ' is invalid, for available options see ' +
              chalk.green('ember help') + '.\n');
    return null;
  }

  if (command.works === 'insideProject') {
    if (!isWithinProject) {
      ui.write('You have to be inside an ember-cli project in order to use ' +
               'the ' + chalk.green(commandName) + ' command.\n');
      return null;
    }
  }

  if (command.works === 'outsideProject') {
    if (isWithinProject) {
      ui.write('You cannot use the '+  chalk.green(commandName) +
               ' command inside an ember-cli project.\n');
      return null;
    }
  }

  command.availableOptions.forEach(function(option) {
    knownOpts[option.name] = option.type;
  });

  parsedOptions = nopt(knownOpts, {}, cliArgs, 1);

  if (!command.availableOptions.every(assembleAndValidateOption)) {
    return null;
  }

  return {
    command: command,
    commandOptions: commandOptions
  };
}
<|endoftext|>