<commit_before>var fs = require('fs');
var cl_template = require('./client.js');
var game_template = require('./../Game/game.js');
var Clients = [];
var Games = [];
var NamedClients = [];
var SciNames;
var io;

fs.readFile(__dirname + '/scientist-names.json','utf8', function(err, data)
{
	if (err)
	{
		console.Error("Cannot load JSON file for scientist-names");
		return;
	}
	SciNames = JSON.parse(data);
});

exports.init = function(ioContext)
{
	io = ioContext;
};

function request(socket, data)
{
	if ( 'undefined' == typeof socket )
	{
		return;
	}

	var res = null;
	if ( 'undefined' == typeof data || 'undefined' == typeof data.cmd )
	{
		res = {
			approved: false,
			data: "Error invaild request",
			id: data.id
		};
	}

	else
	{
		var clientContext = Clients[socket.id];
		if (clientContext.isPlaying)
			return;

		switch ( data.cmd )
		{
			//Create Game
			case 'C':
				res = createGame(clientContext, data.id);
				break;

			//Leave Game
			case 'L':
				res = leaveGame(clientContext, data.id);
				break;

			//Join Game
			case 'J':
				res = joinGame(clientContext, data.data, data.id);
				break;

			//Set Ready
			case 'R':
				res = setReady(clientContext, data.id);
				break;

			//Set Wait
			case 'W':
				res = setWait(clientContext, data.id);
				break;

			//Set Name
			case 'N':
				res = setName(clientContext, data.data, data.id);
				break;

			case 'I':
				res = lobbyInit(clientContext, data.id);
			break;

			default:
				res = {
					approved: false,
					data: "Error cannot determine command",
					id: data.id
				};
				break;
		}
	}
	socket.emit( 'lobby', res );
}

// Helper for adding clients to the lobby.
// Should be done on connect
exports.AddClient = function(socket)
{
	Clients[socket.id] = new cl_template.CreateClient(socket);

	socket.on('lobby', function(data)
	{
		request(socket, data);
	});

	socket.on('disconnect', function()
	{
		onDisconnect(socket);
	});
};

exports.GetClients = function()
{
	return Clients;
};

function createGame(clientContext, reqId)
{
	//Check if the player is already in a game
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot create a game if you are in a game"

		};
	}

	//Check if the play has a name
	if('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot create a game. client name is invaild",
			id: reqId
		};
	}

	var game = game_template.CreateGame(clientContext);

	Games[game.gameName] = game;

	pushGameCreated(game);
	pushPlayerUpdate(clientContext);

	var ret = {};
	ret.approved = true;
	ret.id = reqId;
	ret.data = {};
	ret.data.players = [];
	var player = {
		name: clientContext.name,
		state: clientContext.isReady
	};
	ret.data.players.push(player);
	return ret;
}

function leaveGame(clientContext, reqId)
{
	if(clientContext.isInGame === false)
	{
		return{
			approved: false,
			data: "Cannot leave a game if you are not in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot leave game. client name is invaild",
			id: reqId
		};
	}

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	var isGameDeleted = gameContext.leaveGame(clientContext);
	if (isGameDeleted === true)
	{
		pushGameClosed(game);
		delete Games[game.gameName];
	}
	else
	{
		pushGameUpdated(game);
	}

	pushPlayerUpdate(clientContext);
	return{
		approved: true,
		id: reqId
	};
}

function joinGame(clientContext, data, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot join a game if you are in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return{
			approved: false,
			data: "Cannot join a game if you do not have a name",
			id: reqId
		};
	}

	var gameId = NamedClients[data].gameId;

	if (gameId === -1)
		return{
			approved: false,
			data: "Player is not in a game",
			id: reqId
		};

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	if (gameContext.joinGame(clientContext) === true)
	{
		clientContext.isInGame = true;
		clientContext.gameId = gameId;

		pushGameUpdated(gameContext);

		return {
			approved: true,
			id: reqId
		};
	}
	else
		return{
			approved: false,
			data: "Game is either full or dosent exist anymore",
			id: reqId
		};
}

function setReady(clientContext, reqId)
{
	if (clientContext.isInGame === false)
	{
		return{
			approved: false,
			data: "Cannot ready whne you are not in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot ready if you do not have a name",
			id: reqId
		};
	}

	if (clientContext.isReady === true)
	{
		return {
			approved: false,
			data: "Cannot ready if you are already ready",
			id: reqId
		};
	}

	clientContext.isReady = true;

	var gameContext = {};

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	pushGameUpdated(gameContext);

	return {
		approved: true,
		id: reqId
	};
}

function setWait(clientContext, reqId)
{
	if (clientContext.isInGame === false)
	{
		return {
			approved: false,
			data: "Must be in a game to be waiting",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot wait if you do not have a name",
			id: reqId
		};
	}

	if (clientContext.isReady === false)
	{
		return {
			approved: false,
			data: "Cannot wait if you are already waiting",
			id: reqId
		};
	}

	clientContext.isReady = false;

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	pushGameUpdated(gameContext);

	return {
		approved: true,
		id: reqId
	};
}

function setName(clientContext, data, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot change your name if you are in a game",
			id: reqId
		};
	}

	var isPlayerCreated = false;

	if (clientContext.name !== "")
	{
		if ('undefined' != typeof NamedClients[clientContext.name])
			delete NamedClients[clientContext.name];

	}
	else
	{
		isPlayerCreated = true;
	}

	//Change the name
	if (data === '')
	{

		var name;
		do
		{
			var potentialName = SciNames[Math.floor(Math.random()*SciNames.length)];

			if ('undefined' == typeof NamedClients[potentialName])
			{
				name = potentialName;
				break;
			}

		} while (true);

		clientContext.name = name;
		NamedClients[name] = clientContext;

		if(isPlayerCreated)
			pushPlayerCreated(clientContext);
		else
			pushPlayerUpdate(clientContext);

		return{
			approved: true,
			data: name,
			id: reqId
		};
	}

	else
	{

		if ('undefined' != typeof NamedClients[data])
		{
			return {
				approved:false,
				data: "Name is already taken",
				id: reqId
			};
		}

		clientContext.name = data;
		NamedClients[data] = clientContext;

		if (isPlayerCreated)
			pushPlayerCreated(clientContext);
		else
			pushPlayerUpdate(clientContext);

		return {
			approved: true,
			data: data,
			id: reqId
		};
	}
}

function lobbyInit(clientContext, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "something very bad happened to the client state. contact help fast",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "get the lobby if you do not have a name",
			id: reqId
		};
	}
	var ret = {};
	ret.approved = true;
	ret.data = {};
	ret.data.players = [];

	for (var key in NamedClients)
	{
		if(NamedClients.hasOwnProperty(key))
		{
			var player = {};
			player.name = NamedClients[key].name;
			player.state = (NamedClients[key].isInGame ? 'Playing' : 'Available');
			ret.data.players.push(player);
		}
	}

	ret.data.games = [];

	for (key in Games)
	{
		if(Games.hasOwnProperty(key))
		{
			var game = {};
			game.players = [];
			for (var j = 0; j < Games[key].players.length; j++)
			{
				var gamePlayer = {};
				gamePlayer.name = Games[key].players[j].name;
				gamePlayer.ready = Games[key].players[j].isReady;
				game.players.push(gamePlayer);
			}
			ret.data.games.push(game);
		}
	}

	ret.id = reqId;
	clientContext.isInitalized = true;
	pushPlayerCreated(clientContext);
	return ret;
}

function onDisconnect(socket)
{
	var client = Clients[socket.id];
	pushPlayerDisconnect(client);
	var name = client.name;

	if (client.isInGame === true)
	{
		var gameContext;

		for (var key in Games)
		{
			if (Games.hasOwnProperty(key))
			{
				if (Games[key].id === clientContext.gameId)
				{
					gameContext = Games[key];
				}
			}
		}

		gameContext.leaveGame(client);
	}

	delete Clients[socket.id];
	delete NamedClients[name];
}

function pushPlayerCreated(clientContext)
{

	var req = {
		cmd: "PC",
		data: {
			name: clientContext.name,
			state: (clientContext.isInGame ? 'Playing' : 'Available')
		}
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushPlayerDisconnect(clientContext)
{
	var req = {
		cmd: 'PR',
		data: clientContext.name
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushPlayerUpdate(clientContext)
{
	var req = {
		cmd: 'PU',
		data: {
			name: clientContext.name,
			state: (clientContext.isInGame ? 'Playing' : 'Available')
		}
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushGameCreated(gameContext)
{

	var game = {};
	game.players = [];

	for (var i = 0; i < gameContext.players.length; i++)
	{
		var player = {
			name: gameContext.players[i].name,
			ready: gameContext.isReady
		};
		game.players.push(player);
	}

	var req = {
		cmd: 'GC',
		data: game
	};

	sendPushRequestToAllBut(req, gameContext.players[0]);
}

function pushGameClosed(gameContext)
{
	var req = {
		cmd: 'GR',
		data: gameContext.gameName
	};

	sendPushRequestToAllBut(req, gameContext.players[0]);
}

function pushGameUpdated(gameContext)
{
	var game = {};
	game.players = [];

	for (var i = 0; i < gameContext.players.length; i++)
	{
		var player = {
			name: gameContext.players[i].name,
			ready: gameContext.isReady
		};
		game.players.push(player);
	}

	var req = {
		cmd: 'GU',
		data: game
	};
}

function sendPushRequestToAllBut(req, clientContext)
{
	for (var key in NamedClients)
	{
		if (NamedClients.hasOwnProperty(key))
		{
			if (NamedClients[key] == clientContext)
				continue;
			NamedClients[key].cl_socket.emit('lobby', req);
		}
	}
}<commit_msg>fixed the non deleting issue<commit_after>var fs = require('fs');
var cl_template = require('./client.js');
var game_template = require('./../Game/game.js');
var Clients = [];
var Games = [];
var NamedClients = [];
var SciNames;
var io;

fs.readFile(__dirname + '/scientist-names.json','utf8', function(err, data)
{
	if (err)
	{
		console.Error("Cannot load JSON file for scientist-names");
		return;
	}
	SciNames = JSON.parse(data);
});

exports.init = function(ioContext)
{
	io = ioContext;
};

function request(socket, data)
{
	if ( 'undefined' == typeof socket )
	{
		return;
	}

	var res = null;
	if ( 'undefined' == typeof data || 'undefined' == typeof data.cmd )
	{
		res = {
			approved: false,
			data: "Error invaild request",
			id: data.id
		};
	}

	else
	{
		var clientContext = Clients[socket.id];
		if (clientContext.isPlaying)
			return;

		switch ( data.cmd )
		{
			//Create Game
			case 'C':
				res = createGame(clientContext, data.id);
				break;

			//Leave Game
			case 'L':
				res = leaveGame(clientContext, data.id);
				break;

			//Join Game
			case 'J':
				res = joinGame(clientContext, data.data, data.id);
				break;

			//Set Ready
			case 'R':
				res = setReady(clientContext, data.id);
				break;

			//Set Wait
			case 'W':
				res = setWait(clientContext, data.id);
				break;

			//Set Name
			case 'N':
				res = setName(clientContext, data.data, data.id);
				break;

			case 'I':
				res = lobbyInit(clientContext, data.id);
			break;

			default:
				res = {
					approved: false,
					data: "Error cannot determine command",
					id: data.id
				};
				break;
		}
	}
	socket.emit( 'lobby', res );
}

// Helper for adding clients to the lobby.
// Should be done on connect
exports.AddClient = function(socket)
{
	Clients[socket.id] = new cl_template.CreateClient(socket);

	socket.on('lobby', function(data)
	{
		request(socket, data);
	});

	socket.on('disconnect', function()
	{
		onDisconnect(socket);
	});
};

exports.GetClients = function()
{
	return Clients;
};

function createGame(clientContext, reqId)
{
	//Check if the player is already in a game
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot create a game if you are in a game"

		};
	}

	//Check if the play has a name
	if('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot create a game. client name is invaild",
			id: reqId
		};
	}

	var game = game_template.CreateGame(clientContext);

	Games[game.gameName] = game;

	pushGameCreated(game);
	pushPlayerUpdate(clientContext);

	var ret = {};
	ret.approved = true;
	ret.id = reqId;
	ret.data = {};
	ret.data.players = [];
	var player = {
		name: clientContext.name,
		state: clientContext.isReady
	};
	ret.data.players.push(player);
	return ret;
}

function leaveGame(clientContext, reqId)
{
	if(clientContext.isInGame === false)
	{
		return{
			approved: false,
			data: "Cannot leave a game if you are not in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot leave game. client name is invaild",
			id: reqId
		};
	}

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	var isGameDeleted = gameContext.leaveGame(clientContext);
	if (isGameDeleted === true)
	{
		pushGameClosed(game);
		delete Games[game.gameName];
	}
	else
	{
		pushGameUpdated(game);
	}

	pushPlayerUpdate(clientContext);
	return{
		approved: true,
		id: reqId
	};
}

function joinGame(clientContext, data, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot join a game if you are in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return{
			approved: false,
			data: "Cannot join a game if you do not have a name",
			id: reqId
		};
	}

	var gameId = NamedClients[data].gameId;

	if (gameId === -1)
		return{
			approved: false,
			data: "Player is not in a game",
			id: reqId
		};

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	if (gameContext.joinGame(clientContext) === true)
	{
		clientContext.isInGame = true;
		clientContext.gameId = gameId;

		pushGameUpdated(gameContext);

		return {
			approved: true,
			id: reqId
		};
	}
	else
		return{
			approved: false,
			data: "Game is either full or dosent exist anymore",
			id: reqId
		};
}

function setReady(clientContext, reqId)
{
	if (clientContext.isInGame === false)
	{
		return{
			approved: false,
			data: "Cannot ready whne you are not in a game",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot ready if you do not have a name",
			id: reqId
		};
	}

	if (clientContext.isReady === true)
	{
		return {
			approved: false,
			data: "Cannot ready if you are already ready",
			id: reqId
		};
	}

	clientContext.isReady = true;

	var gameContext = {};

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	pushGameUpdated(gameContext);

	return {
		approved: true,
		id: reqId
	};
}

function setWait(clientContext, reqId)
{
	if (clientContext.isInGame === false)
	{
		return {
			approved: false,
			data: "Must be in a game to be waiting",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "Cannot wait if you do not have a name",
			id: reqId
		};
	}

	if (clientContext.isReady === false)
	{
		return {
			approved: false,
			data: "Cannot wait if you are already waiting",
			id: reqId
		};
	}

	clientContext.isReady = false;

	var gameContext;

	for (var key in Games)
	{
		if (Games.hasOwnProperty(key))
		{
			if (Games[key].id === clientContext.gameId)
			{
				gameContext = Games[key];
			}
		}
	}

	pushGameUpdated(gameContext);

	return {
		approved: true,
		id: reqId
	};
}

function setName(clientContext, data, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "Cannot change your name if you are in a game",
			id: reqId
		};
	}

	var isPlayerCreated = false;

	if (clientContext.name !== "")
	{
		if ('undefined' != typeof NamedClients[clientContext.name])
			delete NamedClients[clientContext.name];

	}
	else
	{
		isPlayerCreated = true;
	}

	//Change the name
	if (data === '')
	{

		var name;
		do
		{
			var potentialName = SciNames[Math.floor(Math.random()*SciNames.length)];

			if ('undefined' == typeof NamedClients[potentialName])
			{
				name = potentialName;
				break;
			}

		} while (true);

		clientContext.name = name;
		NamedClients[name] = clientContext;

		if(isPlayerCreated)
			pushPlayerCreated(clientContext);
		else
			pushPlayerUpdate(clientContext);

		return{
			approved: true,
			data: name,
			id: reqId
		};
	}

	else
	{

		if ('undefined' != typeof NamedClients[data])
		{
			return {
				approved:false,
				data: "Name is already taken",
				id: reqId
			};
		}

		clientContext.name = data;
		NamedClients[data] = clientContext;

		if (isPlayerCreated)
			pushPlayerCreated(clientContext);
		else
			pushPlayerUpdate(clientContext);

		return {
			approved: true,
			data: data,
			id: reqId
		};
	}
}

function lobbyInit(clientContext, reqId)
{
	if (clientContext.isInGame === true)
	{
		return {
			approved: false,
			data: "something very bad happened to the client state. contact help fast",
			id: reqId
		};
	}

	if ('undefined' == typeof clientContext.name || clientContext.name === null)
	{
		return {
			approved: false,
			data: "get the lobby if you do not have a name",
			id: reqId
		};
	}
	var ret = {};
	ret.approved = true;
	ret.data = {};
	ret.data.players = [];

	for (var key in NamedClients)
	{
		if(NamedClients.hasOwnProperty(key))
		{
			var player = {};
			player.name = NamedClients[key].name;
			player.state = (NamedClients[key].isInGame ? 'Playing' : 'Available');
			ret.data.players.push(player);
		}
	}

	ret.data.games = [];

	for (key in Games)
	{
		if(Games.hasOwnProperty(key))
		{
			var game = {};
			game.players = [];
			for (var j = 0; j < Games[key].players.length; j++)
			{
				var gamePlayer = {};
				gamePlayer.name = Games[key].players[j].name;
				gamePlayer.ready = Games[key].players[j].isReady;
				game.players.push(gamePlayer);
			}
			ret.data.games.push(game);
		}
	}

	ret.id = reqId;
	clientContext.isInitalized = true;
	pushPlayerCreated(clientContext);
	return ret;
}

function onDisconnect(socket)
{
	var client = Clients[socket.id];
	pushPlayerDisconnect(client);
	var name = client.name;

	if (client.isInGame === true)
	{
		var gameContext;

		for (var key in Games)
		{
			if (Games.hasOwnProperty(key))
			{
				if (Games[key].id === clientContext.gameId)
				{
					gameContext = Games[key];
				}
			}
		}

		var isGameDeleted = gameContext.leaveGame(client);
		if (isGameDeleted === true)
		{
			pushGameClosed(game);
			delete Games[game.gameName];
		}
		else
		{
			pushGameUpdated(game);
		}

	}

	delete Clients[socket.id];
	delete NamedClients[name];
}

function pushPlayerCreated(clientContext)
{

	var req = {
		cmd: "PC",
		data: {
			name: clientContext.name,
			state: (clientContext.isInGame ? 'Playing' : 'Available')
		}
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushPlayerDisconnect(clientContext)
{
	var req = {
		cmd: 'PR',
		data: clientContext.name
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushPlayerUpdate(clientContext)
{
	var req = {
		cmd: 'PU',
		data: {
			name: clientContext.name,
			state: (clientContext.isInGame ? 'Playing' : 'Available')
		}
	};

	sendPushRequestToAllBut(req, clientContext);
}

function pushGameCreated(gameContext)
{

	var game = {};
	game.players = [];

	for (var i = 0; i < gameContext.players.length; i++)
	{
		var player = {
			name: gameContext.players[i].name,
			ready: gameContext.isReady
		};
		game.players.push(player);
	}

	var req = {
		cmd: 'GC',
		data: game
	};

	sendPushRequestToAllBut(req, gameContext.players[0]);
}

function pushGameClosed(gameContext)
{
	var req = {
		cmd: 'GR',
		data: gameContext.gameName
	};

	sendPushRequestToAllBut(req, gameContext.players[0]);
}

function pushGameUpdated(gameContext)
{
	var game = {};
	game.players = [];

	for (var i = 0; i < gameContext.players.length; i++)
	{
		var player = {
			name: gameContext.players[i].name,
			ready: gameContext.isReady
		};
		game.players.push(player);
	}

	var req = {
		cmd: 'GU',
		data: game
	};
}

function sendPushRequestToAllBut(req, clientContext)
{
	for (var key in NamedClients)
	{
		if (NamedClients.hasOwnProperty(key))
		{
			if (NamedClients[key] == clientContext)
				continue;
			NamedClients[key].cl_socket.emit('lobby', req);
		}
	}
}<|endoftext|>


<commit_before>import Ember from 'ember';
import ENV from '../config/environment';

function _getTag(tagName, property, value) {
    var tags = document.head.getElementsByTagName(tagName),
        tag,
        i = tags.length;

    while(i--) {
        tag = tags[i];

        if(tag[property] && tag[property] === value) {
            return tag;
        }
    }
}

function _createTag(tagName, property, value) {
    var tag = document.createElement('meta');
    tag.setAttribute(property, value);
    document.head.appendChild(tag);

    return tag;
}

/*
        var baseDomain = ENV.baseDomain; //gracefully deal with local development
        if (baseDomain === ''){
            baseDomain = window.location.origin;
        }
 */

export default Ember.Object.extend({
    title: null,
    description: null,
    //type: null,
    // image: null,
    // tags: null,
    url: null,

    // DOM elements
    //_ogSiteName: null,
    _ogTitle: null,
    _description: null,
    _ogDescription: null,
    // _ogImage: null,
    // _twImage: null,
    // _ogTag: null,
    _ogUrl: null,
    // _twUrl: null,

    // propagate changes to DOM elements
    // siteNameChanged: function() {
    //     this.get('_ogSiteName').setAttribute('content', this.get('site_name'));
    //     this.notifyPropertyChange('_ogSiteName');
    // }.observes('site_name'),

    titleChanged: function() {
        document.title = this.get('title');
        this.get('_ogTitle').setAttribute('content', this.get('title'));
        this.notifyPropertyChange('_ogTitle');
    }.observes('title'),

    descriptionChanged: function() {
        this.get('_description').setAttribute('content', this.get('description'));
        this.get('_ogDescription').setAttribute('content', this.get('description'));
        this.notifyPropertyChange('_ogDescription');
    }.observes('description'),

    urlChanged: function() {
        var baseDomain = ENV.baseDomain; //gracefully deal with local development
        console.log(baseDomain);
        if (baseDomain === ''){
            baseDomain = window.location.origin;
        }
        var url = baseDomain + this.get('url');
        this.get('_ogUrl').setAttribute('content', url);
        this.notifyPropertyChange('_ogUrl');
    }.observes('url'),

    setUpMetaTags: function() {

        // ogTitle
        var _ogTitle = _getTag('meta', 'property', 'og:title');
        if (!_ogTitle) {
            _ogTitle = _createTag('meta', 'property', 'og:title');
        }
        this.set('_ogTitle', _ogTitle);

        // description
        var _description = _getTag('meta', 'name', 'description');
        if (!_description) {
            _description = _createTag('meta', 'name', 'description');
        }
        this.set('_description', _description);

        // ogDescription
        var _ogDescription = _getTag('meta', 'property', 'og:description');
        if (!_ogDescription) {
            _ogDescription = _createTag('meta', 'property', 'og:description');
        }
        this.set('_ogDescription', _ogDescription);

        // ogUrl
        var _ogUrl = _getTag('meta', 'property', 'og:url');
        if (!_ogUrl) {
            _ogUrl = _createTag('meta', 'property', 'og:url');
        }
        this.set('_ogUrl', _ogUrl);

    }.on('init'),

    setTags: function(tags) {
        this.setProperties(tags);
    }
});<commit_msg>fix url<commit_after>import Ember from 'ember';
import ENV from '../config/environment';

function _getTag(tagName, property, value) {
    var tags = document.head.getElementsByTagName(tagName),
        tag,
        i = tags.length;

    while(i--) {
        tag = tags[i];

        if(tag[property] && tag[property] === value) {
            return tag;
        }
    }
}

function _createTag(tagName, property, value) {
    var tag = document.createElement('meta');
    tag.setAttribute(property, value);
    document.head.appendChild(tag);

    return tag;
}

/*
        var baseDomain = ENV.baseDomain; //gracefully deal with local development
        if (baseDomain === ''){
            baseDomain = window.location.origin;
        }
 */

export default Ember.Object.extend({
    title: null,
    description: null,
    //type: null,
    // image: null,
    // tags: null,
    url: null,

    // DOM elements
    //_ogSiteName: null,
    _ogTitle: null,
    _description: null,
    _ogDescription: null,
    // _ogImage: null,
    // _twImage: null,
    // _ogTag: null,
    _ogUrl: null,
    // _twUrl: null,

    // propagate changes to DOM elements
    // siteNameChanged: function() {
    //     this.get('_ogSiteName').setAttribute('content', this.get('site_name'));
    //     this.notifyPropertyChange('_ogSiteName');
    // }.observes('site_name'),

    titleChanged: function() {
        document.title = this.get('title');
        this.get('_ogTitle').setAttribute('content', this.get('title'));
        this.notifyPropertyChange('_ogTitle');
    }.observes('title'),

    descriptionChanged: function() {
        this.get('_description').setAttribute('content', this.get('description'));
        this.get('_ogDescription').setAttribute('content', this.get('description'));
        this.notifyPropertyChange('_ogDescription');
    }.observes('description'),

    urlChanged: function() {
        var baseDomain = ENV.baseDomain; //gracefully deal with local development
        if (baseDomain === ''){
            baseDomain = window.location.origin;
        }
        var url = baseDomain + ENV.baseURL + this.get('url');
        this.get('_ogUrl').setAttribute('content', url);
        this.notifyPropertyChange('_ogUrl');
    }.observes('url'),

    setUpMetaTags: function() {

        // ogTitle
        var _ogTitle = _getTag('meta', 'property', 'og:title');
        if (!_ogTitle) {
            _ogTitle = _createTag('meta', 'property', 'og:title');
        }
        this.set('_ogTitle', _ogTitle);

        // description
        var _description = _getTag('meta', 'name', 'description');
        if (!_description) {
            _description = _createTag('meta', 'name', 'description');
        }
        this.set('_description', _description);

        // ogDescription
        var _ogDescription = _getTag('meta', 'property', 'og:description');
        if (!_ogDescription) {
            _ogDescription = _createTag('meta', 'property', 'og:description');
        }
        this.set('_ogDescription', _ogDescription);

        // ogUrl
        var _ogUrl = _getTag('meta', 'property', 'og:url');
        if (!_ogUrl) {
            _ogUrl = _createTag('meta', 'property', 'og:url');
        }
        this.set('_ogUrl', _ogUrl);

    }.on('init'),

    setTags: function(tags) {
        this.setProperties(tags);
    }
});<|endoftext|>


<commit_before>import {VESSEL_INIT, VESSEL_ZOOM_UPDATE, VESSEL_TILE_LOADED, SHOW_LOADING, RESET_CACHE, ADD_LAYER} from '../constants';
import calculateBounds from '../lib/calculateBounds';
import PelagosClient from '../lib/pelagosClient';
var url = "https://storage.googleapis.com/skytruth-pelagos-production/pelagos/data/tiles/benthos-pipeline/gfw-vessel-scoring-602-tileset-2014-2016_2016-05-17/cluster_tiles/2015-01-01T00:00:00.000Z,2016-01-01T00:00:00.000Z;";

export function init() {
  return {
    type: VESSEL_INIT,
    payload: {
      visible: true,
      load: true
    }
  };
};

export function showLoading(show) {
  return {
    type: SHOW_LOADING,
    payload: show
  };
};

/*
** CartoDB layers:
** MPA
** EEZ
** High Seas Pockets
** RFMOs
*/
export function addLayer() {
  return {
        type: ADD_LAYER,
        payload: ["http://cartodb.skytruth.org/user/dev/api/v2/viz/d7c9313c-97b8-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/2cf0043c-97ba-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/90467e80-97ba-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/3e755a02-97cb-11e5-87b3-0242ac110002/viz.json"]
      }
  var p1 = new Promise(
    // The resolver function is called with the ability to resolve or
    // reject the promise
    function(resolve, reject) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = returnLayers;
        httpRequest.open('GET', '/workspace.json', true);
        httpRequest.responseType = "text";
        httpRequest.send();

        function returnLayers() {
          if (httpRequest.readyState == XMLHttpRequest.DONE ) {
             if (httpRequest.status == 200) {
                var data = JSON.parse(httpRequest.responseText);
                var layers = [];
                for (var prop in data.map.animations) {
                  if(data.map.animations[prop].type === "CartoDBAnimation" && data.map.animations[prop].args.source.args.url.indexOf('http') === 0) {
                    layers.push(data.map.animations[prop].args.source.args.url);
                  }
                }
                resolve(layers);
              }
           }
        }
      }
  );
  p1.then(
    function(layers) {
      return {
        type: ADD_LAYER,
        payload: ["http://cartodb.skytruth.org/user/dev/api/v2/viz/d7c9313c-97b8-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/2cf0043c-97ba-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/90467e80-97ba-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/3e755a02-97cb-11e5-87b3-0242ac110002/viz.json"]
      }
    });
};

export function resetCache() {
  return {
    type: RESET_CACHE
  };
};

export function loadZoom(map) {
  return function (dispatch) {
    dispatch({
      type: VESSEL_ZOOM_UPDATE
    });
    let bounds = calculateBounds(map);
    var obtainTile = function (key) {
      new PelagosClient().obtainTile(url + key).then(function (data) {
        let obj = {};
        obj[key] = data;
        dispatch({
          type: VESSEL_TILE_LOADED,
          payload: {
            data: obj
          }
        });
      });
    }
    for (var i = 0, length = bounds.length; i < length; i++) {
      obtainTile(bounds[i].toString());
    }

  }
}

export function move(map) {
  return function (dispatch, getState) {
    let state = getState();
    let bounds = calculateBounds(map);
    let vData = state.vessel.data;
    var obtainTile = function (key) {
      new PelagosClient().obtainTile(url + key).then(function (data) {
        let obj = {};
        obj[key] = data;
        dispatch({
          type: VESSEL_TILE_LOADED,
          payload: {
            data: obj
          }
        });
        dispatch({
          type: SHOW_LOADING,
          payload: false
        })
      });
    }

    for (var i = 0, length = bounds.length; i < length; i++) {
      if (!vData || !vData[bounds[i].toString()]) {
        obtainTile(bounds[i].toString());
      }
    }

  }

}
<commit_msg>change `var` for `let`<commit_after>import {VESSEL_INIT, VESSEL_ZOOM_UPDATE, VESSEL_TILE_LOADED, SHOW_LOADING, RESET_CACHE, ADD_LAYER} from '../constants';
import calculateBounds from '../lib/calculateBounds';
import PelagosClient from '../lib/pelagosClient';
let url = "https://storage.googleapis.com/skytruth-pelagos-production/pelagos/data/tiles/benthos-pipeline/gfw-vessel-scoring-602-tileset-2014-2016_2016-05-17/cluster_tiles/2015-01-01T00:00:00.000Z,2016-01-01T00:00:00.000Z;";

export function init() {
  return {
    type: VESSEL_INIT,
    payload: {
      visible: true,
      load: true
    }
  };
};

export function showLoading(show) {
  return {
    type: SHOW_LOADING,
    payload: show
  };
};

/*
** CartoDB layers:
** MPA
** EEZ
** High Seas Pockets
** RFMOs
*/
export function addLayer() {
  return {
        type: ADD_LAYER,
        payload: ["http://cartodb.skytruth.org/user/dev/api/v2/viz/d7c9313c-97b8-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/2cf0043c-97ba-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/90467e80-97ba-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/3e755a02-97cb-11e5-87b3-0242ac110002/viz.json"]
      }
  let p1 = new Promise(
    // The resolver function is called with the ability to resolve or
    // reject the promise
    function(resolve, reject) {
        let httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = returnLayers;
        httpRequest.open('GET', '/workspace.json', true);
        httpRequest.responseType = "text";
        httpRequest.send();

        function returnLayers() {
          if (httpRequest.readyState == XMLHttpRequest.DONE ) {
             if (httpRequest.status == 200) {
                let data = JSON.parse(httpRequest.responseText);
                let layers = [];
                for (let prop in data.map.animations) {
                  if(data.map.animations[prop].type === "CartoDBAnimation" && data.map.animations[prop].args.source.args.url.indexOf('http') === 0) {
                    layers.push(data.map.animations[prop].args.source.args.url);
                  }
                }
                resolve(layers);
              }
           }
        }
      }
  );
  p1.then(
    function(layers) {
      return {
        type: ADD_LAYER,
        payload: ["http://cartodb.skytruth.org/user/dev/api/v2/viz/d7c9313c-97b8-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/2cf0043c-97ba-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/90467e80-97ba-11e5-87b3-0242ac110002/viz.json", "http://cartodb.skytruth.org/user/dev/api/v2/viz/3e755a02-97cb-11e5-87b3-0242ac110002/viz.json"]
      }
    });
};

export function resetCache() {
  return {
    type: RESET_CACHE
  };
};

export function loadZoom(map) {
  return function (dispatch) {
    dispatch({
      type: VESSEL_ZOOM_UPDATE
    });
    let bounds = calculateBounds(map);
    let obtainTile = function (key) {
      new PelagosClient().obtainTile(url + key).then(function (data) {
        let obj = {};
        obj[key] = data;
        dispatch({
          type: VESSEL_TILE_LOADED,
          payload: {
            data: obj
          }
        });
      });
    }
    for (let i = 0, length = bounds.length; i < length; i++) {
      obtainTile(bounds[i].toString());
    }

  }
}

export function move(map) {
  return function (dispatch, getState) {
    let state = getState();
    let bounds = calculateBounds(map);
    let vData = state.vessel.data;
    let obtainTile = function (key) {
      new PelagosClient().obtainTile(url + key).then(function (data) {
        let obj = {};
        obj[key] = data;
        dispatch({
          type: VESSEL_TILE_LOADED,
          payload: {
            data: obj
          }
        });
        dispatch({
          type: SHOW_LOADING,
          payload: false
        })
      });
    }

    for (let i = 0, length = bounds.length; i < length; i++) {
      if (!vData || !vData[bounds[i].toString()]) {
        obtainTile(bounds[i].toString());
      }
    }

  }

}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import $ from 'jquery';

import * as AppActions from '../actions/AppActions';
import * as UiActions from '../actions/UiActions';
import * as SynthActions from '../actions/SynthActions';
import WebSynth from 'web-synth';

// Components
import NoAudioWarning from '../components/NoAudioWarning';
import Header from '../components/Header';
import Footer from '../components/Footer';
import Synth from '../components/Synth';
import GlobalKeys from '../components/GlobalKeys';

//Panels
import ControlPanel from '../components/ControlPanel';
import GraphPanel from '../components/Graph';

// Services
import localCacheService from '../services/localCache';
import screenService from '../services/screen';

const
    localCache = localCacheService(),
    screen = screenService(),
    localCacheKey = 'webSynth',
    nodePrefix = 'node',
    synthModules = WebSynth.describeModules(),
    headerHeight = 94,
    footerHeight = 40,
    Actions = { ...AppActions, ...UiActions, ...SynthActions };

class App extends Component {

    constructor (props) {
        super(props);

        this.audioContext = null;

        if (window && typeof window.AudioContext !== 'undefined') {
            this.audioContext = new window.AudioContext();
        } else if (typeof window.webkitAudioContext !== 'undefined') {
            this.audioContext = new window.webkitAudioContext();
        } else {
            $(document).ready(() => {
                $('#no-audio-warning').modal({
                    backdrop: 'static'
                });
                $('#no-audio-warning').modal('show');
            });
        }

        $(document).ready(() => {
            $('[data-toggle="tooltip"]').tooltip();
            $("#main-wrapper").find('li.module-builder').on('show.bs.dropdown', () => {
                $("#main-wrapper").find('li.module-builder').find('a.dropdown-toggle').addClass('selected');
            });
            $("#main-wrapper").find('li.module-builder').on('hidden.bs.dropdown', () => {
                $("#main-wrapper").find('li.module-builder').find('a.dropdown-toggle').removeClass('selected');
            });
        });
    }

    getViewActions () {
        const { dispatch, ui, synth } = this.props;
        return {
            onGraphCreated: (instance) => {
                dispatch(Actions.setGraphInstance(instance));
            },
            onClickHandler: (node, isSeletected) => {
                if (node !== WebSynth.CONST.MASTER) {
                    dispatch(Actions.setNodeSelection(node, isSeletected));
                }
            },
            onFreeHandler: (nodeId, nodePosition, graphPan, graphZoom) => {
                dispatch(Actions.setPositions(nodeId, nodePosition, graphPan, graphZoom));
            },
            linkHandler: (sourceNodeId, destNodeId) => {
                dispatch(Actions.linkNodes(sourceNodeId, destNodeId));
            },
            setViewPanel: (viewPanel) =>
                dispatch(Actions.setViewPanel(viewPanel)),
            setPianoVisibility: (isPianoVisible) =>
                dispatch(Actions.setPianoVisibility(isPianoVisible)),
            setSpectrumVisibility: (isSpectrumVisible) =>
                dispatch(Actions.setSpectrumVisibility(isSpectrumVisible)),
            saveSynth: () =>
                localCache.saveState(localCacheKey, { ui: { ...ui }, synth: { ...synth } }),
            loadSynth: () =>
                dispatch(Actions.loadState(
                    localCache.loadState(localCacheKey),
                    WebSynth.describeModules().map(e => e.type)
                )),
            resetSynth: () =>
                dispatch(Actions.resetState()),
            toggleLinkMode: () =>
                dispatch(Actions.toggleLinkMode()),
            addModule: (type) =>
                this.addModule(type),
            deleteSelectedNodes: () =>
                this.removeSelectedNodes(),
            octaveDecrease: () =>
                dispatch(Actions.octaveDecrease()),
            octaveIncrease: () =>
                dispatch(Actions.octaveIncrease())
        }
    }

    removeSelectedNodes () {
        const
            { synth, dispatch } = this.props,
            selectedNodes = synth.modules.filter(e => e.isSelected && !e.isMaster).map(e => e.id);

        if (selectedNodes.length > 0) {
            dispatch(Actions.removeNodes(selectedNodes));
        }
    }

    getKeyboardMapping () {
        const { dispatch, ui } = this.props;

        return [
            {
                keys: [16], //SHIFT
                down: () => dispatch(Actions.setLinkMode(true)),
                up: () => dispatch(Actions.setLinkMode(false)),
                specialKeys: 'shift'
            },
            {
                keys: [9], //TAB
                down: (e) => {
                    e.preventDefault();

                    let toggleView = '';

                    if (ui.viewPanel === 'graph') {
                        toggleView = 'control';
                    } else if (ui.viewPanel === 'control') {
                        toggleView = 'graph';
                    }
                    dispatch(Actions.setViewPanel(toggleView));
                },
                up: () => false
            },
            {
                keys: [90], //Z
                down: () => dispatch(Actions.octaveDecrease()),
                up: () => false,
                specialKeys: false
            },
            {
                keys: [88], //X
                down: () => dispatch(Actions.octaveIncrease()),
                up: () => false,
                specialKeys: false
            },
            {
                keys: [8], //DELETE
                down: (e) => e.preventDefault(),
                up: () => this.removeSelectedNodes(),
                specialKeys: false
            }
        ]
    }

    getMaxNodeId () {
        const
            { synth } = this.props,
            max = synth.modules.reduce((result, e) => {
                const idInt = parseInt(e.id.replace(nodePrefix, ''), 10);
                return isNaN(idInt) ? 0 : Math.max(result, idInt);
            }, 0);

        return max + 1;
    }

    addModule (type) {
        const
            { dispatch, ui } = this.props,
            newModule = synthModules.filter(e => e.type === type).pop();

        dispatch(Actions.addNode(
            {
                ...newModule,
                id: nodePrefix + this.getMaxNodeId(),
                isMaster: false,
                posX: Math.random() * (this.getGraphHeight()),
                posY: Math.random() * (this.getGraphHeight())
            },
            {
                zoom: ui.graph.instance.zoom(),
                pan: ui.graph.instance.pan()
            }
        ));
    }

    updateModule (id, propertyName, propertyValue) {
        const { dispatch } = this.props;
        dispatch(Actions.updateNode(id, propertyName, propertyValue));
    }

    getGraphHeight () {
        const
            windowSize = screen.getWindowSize(),
            graphHeight = windowSize.height - headerHeight - footerHeight;

        return graphHeight;
    }

    getGraphWidth () {
        return $('body').width() - 30;
    }

    render () {
        const
            { ui, synth, dispatch } = this.props,
            viewActions = this.getViewActions(),
            footerMarginBottom = (ui.isPianoVisible) ? 8 : 2;

        return (

                <NoAudioWarning/>
                 e.type !== WebSynth.TYPES.MASTER)}
                        numSelectedNodes={synth.modules.filter(e => e.isSelected === true).length}
                        libVersion={process.env.LIB_VERSION}
                />

                    <GraphPanel
                        isVisible={ui.viewPanel === 'graph'}
                        synth={synth}
                        ui={ui}
                        graphWidth={this.getGraphWidth()}
                        graphHeight={this.getGraphHeight()}
                        viewActions={viewActions}
                    />
                    <ControlPanel
                        isVisible={ui.viewPanel === 'control'}
                        modules={synth.modules}
                        updateModule={(id, prop, value) => this.updateModule(id, prop, value)}
                        destroyModule={(id) => dispatch(Actions.removeNode(id))}
                    />

                <Synth state={synth}
                       audioContext={this.audioContext}
                       footerHeight={footerHeight}
                       headerHeight={headerHeight}
                       isPianoVisible={ui.isPianoVisible}
                       isSpectrumVisible={ui.isSpectrumVisible}
                       updatePlayingVoices={playingVoices => dispatch(Actions.updatePlayingVoices(playingVoices))}
                />

                <GlobalKeys keyboardMapping={this.getKeyboardMapping()}/>

        );
    }
}

function mapStateToProps (state) {
    return {
        synth: state.synth,
        ui: state.ui
    };
}

export default connect(mapStateToProps)(App);
<commit_msg>style and dimensions<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import $ from 'jquery';

import * as AppActions from '../actions/AppActions';
import * as UiActions from '../actions/UiActions';
import * as SynthActions from '../actions/SynthActions';
import WebSynth from 'web-synth';

// Components
import NoAudioWarning from '../components/NoAudioWarning';
import Header from '../components/Header';
import Footer from '../components/Footer';
import Synth from '../components/Synth';
import GlobalKeys from '../components/GlobalKeys';

//Panels
import ControlPanel from '../components/ControlPanel';
import GraphPanel from '../components/Graph';

// Services
import localCacheService from '../services/localCache';
import screenService from '../services/screen';

const
    localCache = localCacheService(),
    screen = screenService(),
    localCacheKey = 'webSynth',
    nodePrefix = 'node',
    synthModules = WebSynth.describeModules(),
    headerHeight = 94,
    footerHeight = 40,
    Actions = { ...AppActions, ...UiActions, ...SynthActions };

class App extends Component {

    constructor (props) {
        super(props);

        this.audioContext = null;

        if (window && typeof window.AudioContext !== 'undefined') {
            this.audioContext = new window.AudioContext();
        } else if (typeof window.webkitAudioContext !== 'undefined') {
            this.audioContext = new window.webkitAudioContext();
        } else {
            $(document).ready(() => {
                $('#no-audio-warning').modal({
                    backdrop: 'static'
                });
                $('#no-audio-warning').modal('show');
            });
        }

        $(document).ready(() => {
            $('[data-toggle="tooltip"]').tooltip();
            $("#main-wrapper").find('li.module-builder').on('show.bs.dropdown', () => {
                $("#main-wrapper").find('li.module-builder').find('a.dropdown-toggle').addClass('selected');
            });
            $("#main-wrapper").find('li.module-builder').on('hidden.bs.dropdown', () => {
                $("#main-wrapper").find('li.module-builder').find('a.dropdown-toggle').removeClass('selected');
            });
        });
    }

    getViewActions () {
        const { dispatch, ui, synth } = this.props;
        return {
            onGraphCreated: (instance) => {
                dispatch(Actions.setGraphInstance(instance));
            },
            onClickHandler: (node, isSeletected) => {
                if (node !== WebSynth.CONST.MASTER) {
                    dispatch(Actions.setNodeSelection(node, isSeletected));
                }
            },
            onFreeHandler: (nodeId, nodePosition, graphPan, graphZoom) => {
                dispatch(Actions.setPositions(nodeId, nodePosition, graphPan, graphZoom));
            },
            linkHandler: (sourceNodeId, destNodeId) => {
                dispatch(Actions.linkNodes(sourceNodeId, destNodeId));
            },
            setViewPanel: (viewPanel) =>
                dispatch(Actions.setViewPanel(viewPanel)),
            setPianoVisibility: (isPianoVisible) =>
                dispatch(Actions.setPianoVisibility(isPianoVisible)),
            setSpectrumVisibility: (isSpectrumVisible) =>
                dispatch(Actions.setSpectrumVisibility(isSpectrumVisible)),
            saveSynth: () =>
                localCache.saveState(localCacheKey, { ui: { ...ui }, synth: { ...synth } }),
            loadSynth: () =>
                dispatch(Actions.loadState(
                    localCache.loadState(localCacheKey),
                    WebSynth.describeModules().map(e => e.type)
                )),
            resetSynth: () =>
                dispatch(Actions.resetState()),
            toggleLinkMode: () =>
                dispatch(Actions.toggleLinkMode()),
            addModule: (type) =>
                this.addModule(type),
            deleteSelectedNodes: () =>
                this.removeSelectedNodes(),
            octaveDecrease: () =>
                dispatch(Actions.octaveDecrease()),
            octaveIncrease: () =>
                dispatch(Actions.octaveIncrease())
        }
    }

    removeSelectedNodes () {
        const
            { synth, dispatch } = this.props,
            selectedNodes = synth.modules.filter(e => e.isSelected && !e.isMaster).map(e => e.id);

        if (selectedNodes.length > 0) {
            dispatch(Actions.removeNodes(selectedNodes));
        }
    }

    getKeyboardMapping () {
        const { dispatch, ui } = this.props;

        return [
            {
                keys: [16], //SHIFT
                down: () => dispatch(Actions.setLinkMode(true)),
                up: () => dispatch(Actions.setLinkMode(false)),
                specialKeys: 'shift'
            },
            {
                keys: [9], //TAB
                down: (e) => {
                    e.preventDefault();

                    let toggleView = '';

                    if (ui.viewPanel === 'graph') {
                        toggleView = 'control';
                    } else if (ui.viewPanel === 'control') {
                        toggleView = 'graph';
                    }
                    dispatch(Actions.setViewPanel(toggleView));
                },
                up: () => false
            },
            {
                keys: [90], //Z
                down: () => dispatch(Actions.octaveDecrease()),
                up: () => false,
                specialKeys: false
            },
            {
                keys: [88], //X
                down: () => dispatch(Actions.octaveIncrease()),
                up: () => false,
                specialKeys: false
            },
            {
                keys: [8], //DELETE
                down: (e) => e.preventDefault(),
                up: () => this.removeSelectedNodes(),
                specialKeys: false
            }
        ]
    }

    getMaxNodeId () {
        const
            { synth } = this.props,
            max = synth.modules.reduce((result, e) => {
                const idInt = parseInt(e.id.replace(nodePrefix, ''), 10);
                return isNaN(idInt) ? 0 : Math.max(result, idInt);
            }, 0);

        return max + 1;
    }

    addModule (type) {
        const
            { dispatch, ui } = this.props,
            newModule = synthModules.filter(e => e.type === type).pop();

        dispatch(Actions.addNode(
            {
                ...newModule,
                id: nodePrefix + this.getMaxNodeId(),
                isMaster: false,
                posX: Math.random() * (this.getGraphHeight()),
                posY: Math.random() * (this.getGraphHeight())
            },
            {
                zoom: ui.graph.instance.zoom(),
                pan: ui.graph.instance.pan()
            }
        ));
    }

    updateModule (id, propertyName, propertyValue) {
        const { dispatch } = this.props;
        dispatch(Actions.updateNode(id, propertyName, propertyValue));
    }

    getGraphHeight () {
        const
            windowSize = screen.getWindowSize(),
            graphHeight = windowSize.height - headerHeight - footerHeight - 30;

        return graphHeight;
    }

    getGraphWidth () {
        return $('body').width() - 30;
    }

    render () {
        const
            { ui, synth, dispatch } = this.props,
            viewActions = this.getViewActions(),
            footerMarginBottom = (ui.isPianoVisible) ? 8 : 2;

        return (

                <NoAudioWarning/>
                 e.type !== WebSynth.TYPES.MASTER)}
                        numSelectedNodes={synth.modules.filter(e => e.isSelected === true).length}
                        libVersion={process.env.LIB_VERSION}
                />

                    <GraphPanel
                        isVisible={ui.viewPanel === 'graph'}
                        synth={synth}
                        ui={ui}
                        graphWidth={this.getGraphWidth()}
                        graphHeight={this.getGraphHeight()}
                        viewActions={viewActions}
                    />
                    <ControlPanel
                        isVisible={ui.viewPanel === 'control'}
                        modules={synth.modules}
                        updateModule={(id, prop, value) => this.updateModule(id, prop, value)}
                        destroyModule={(id) => dispatch(Actions.removeNode(id))}
                    />

                <Synth state={synth}
                       audioContext={this.audioContext}
                       footerHeight={footerHeight}
                       headerHeight={headerHeight}
                       isPianoVisible={ui.isPianoVisible}
                       isSpectrumVisible={ui.isSpectrumVisible}
                       updatePlayingVoices={playingVoices => dispatch(Actions.updatePlayingVoices(playingVoices))}
                />

                <GlobalKeys keyboardMapping={this.getKeyboardMapping()}/>

        );
    }
}

function mapStateToProps (state) {
    return {
        synth: state.synth,
        ui: state.ui
    };
}

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


<commit_before>var app = angular.module('contribute.controllers', ['ngSanitize'])

.factory('resultHolder', function() {
    var service = {};
    var _result;
    service.store = function(result) {
        _result = result;
    };
    service.get = function() {
        return _result;
    };
    return service;
})

.controller('WhatIsThisController', ['$scope', function($scope) {

}])

.controller('SchemaController', ['$scope', function($scope) {
    hljs.highlightBlock(document.querySelector('.content-column pre code'));
}])

.controller('ValidatorController', [
    '$scope', '$location', '$http', 'resultHolder',
    function($scope, $location, $http, resultHolder) {

        document.title = '/contribute.json';

        $scope.validation = {};
        $scope.validation.url = '';
        $scope.validation.method = 'url';

        $scope.validate = function() {
            if ($scope.validation.method === 'url') {
                if (!$scope.validation.url.trim()) return;
                var url = $scope.validation.url.trim();
                $location.path('/' + encodeURIComponent(url));
                // $location.path('/' + encodeURI(url));
                return false;
            } else if ($scope.validation.method === 'text') {
                if (!$scope.validation.text.trim()) return;
                    $http.post('/validate', $scope.validation.text)
                    .success(function(response) {
                        resultHolder.store(response);
                        $location.path('/result');
                    })
                    .error(function() {
                        console.warn(arguments);
                    });
            } else if ($scope.validation.method === 'file') {
                var input = document.querySelector('form input[type="file"]');
                if (!input.files.length) return;
                var reader = new FileReader();
                reader.onload = function(content) {
                    $http.post('/validate', content.target.result)
                    .success(function(response) {
                        // console.log('RESPONSE', response);
                        resultHolder.store(response);
                        $location.path('/result');
                    })
                    .error(function() {
                        console.warn(arguments);
                    });
                }
                reader.readAsText(input.files[0]);
            }
        };

        $scope.changeValidationMethod = function(method) {
            $scope.validation.method = method;
        };
}])

.controller('ExamplesController', [
    '$scope', '$http',
    function($scope, $http) {
        $scope.loading = true;
        document.title = 'Examples of contribute.json';
        $scope.projects = [];

        $http.get('/examples.json')
        .success(function(response) {
            $scope.urls = response.urls;
            $scope.urls.forEach(function(url) {
                $http.get('/load-example?url=' + encodeURIComponent(url))
                .success(function(response) {
                    if (response.project) {
                        $scope.projects.push(response.project);
                    } else {
                        console.warn('Failed to get a project for', url);
                    }
                });
            });
        })
        .error(function(data, status) {
            console.error(data, status);
        })
        .finally(function() {
            $scope.loading = false;
        });

        $scope.getDataIcon = function(label) {
            return '';
        };

        $scope.urlToLink = function(url) {
            return '/' + encodeURIComponent(encodeURIComponent(url));
        };
}])

.controller('ValidationController', [
    '$scope', '$http', '$routeParams', '$location', 'resultHolder',
    function($scope, $http, $routeParams, $location, resultHolder) {
        var url = $routeParams.wildcard;
        if (url) {
            document.title = 'Validating ' + url;
            url = decodeURIComponent(url);
            // console.log('Look up', url);
        }
        $scope.finished = false;
        $scope.error = null;
        $scope.url = url;
        $scope.horribly_wrong = false;

        function pretty_json(obj) {
            return JSON.stringify(obj, undefined, 4);
        }

        function findUrls(struct) {
            var urls = [];
            for (var key in struct) {
                if (struct.hasOwnProperty(key)) {
                    var value = struct[key];
                    if (typeof value === 'object') {
                        urls.push.apply(urls, findUrls(value));
                    } else if (
                        (value.substr(0, 7) === 'http://' || value.substr(0, 8) === 'https://')
                        && value.indexOf(' ') === -1
                    ) {
                        if (urls.indexOf(value) === -1) {
                            urls.push(value);
                        }
                    }
                }
            }
            return urls;
        }

        function escapeRegExp(string){
            return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
        }

        function showResult(response) {
            // console.log(response);
            $scope.urls_to_check = [];
            $scope.schema = pretty_json(response.schema);
            $scope.schema_url = response.schema_url;
            if (!response.request_error) {
                $scope.response = pretty_json(response.response);  // yuck!
            } else {
                $scope.response = response.response;
            }

            if (response.schema_error) {
                $scope.schema_error = response.schema_error;
            } else if (response.validation_error) {
                $scope.error = response.validation_error;
            } else if (response.request_error) {
                $scope.request_error = response.request_error;
            } else {
                var urls = findUrls(response.response);
                $scope.urls_to_check = urls;
                urls.forEach(function(url) {
                    $http.post('/validateurl', {url: url})
                    .success(function(response) {
                        var reg = new RegExp('"' + escapeRegExp(url) + '"', 'g');
                        var tmpl;
                        if (response.status_code === 200 || response.status_code === 302) {
                            // console.log('Valid URL:', response.url);
                            tmpl = '"' + url + '"';
                        } else {
                            console.warn('Invalid URL:', response.url, response.status_code);
                            tmpl = '"' +
                                    url + '"';
                        }
                        $scope.response = $scope.response.replace(
                            reg,
                            tmpl
                        );

                    }).error(function() {
                        console.error(arguments);
                    }).finally(function() {
                        var index = $scope.urls_to_check.indexOf(url);
                        if (index > -1) {
                            $scope.urls_to_check.splice(index, 1);
                        }
                    });
                });
            }
            $scope.finished = true;
        }

        if (resultHolder.get()) {
            showResult(resultHolder.get());
        } else if (url) {
            $http({url: '/validate', method: 'POST', params: {url: url}})
            .success(showResult)
            .error(function(data, status) {
                $scope.horribly_wrong = true;
                $scope.finished = true;
                console.warn(data, status);
            });
        } else {
            $location.path('/');
        }

}])

;
<commit_msg>removed some unused things<commit_after>var app = angular.module('contribute.controllers', ['ngSanitize'])

.factory('resultHolder', function() {
    var service = {};
    var _result;
    service.store = function(result) {
        _result = result;
    };
    service.get = function() {
        return _result;
    };
    return service;
})

.controller('WhatIsThisController', ['$scope', function($scope) {

}])

.controller('SchemaController', ['$scope', function($scope) {
    hljs.highlightBlock(document.querySelector('.content-column pre code'));
}])

.controller('ValidatorController', [
    '$scope', '$location', '$http', 'resultHolder',
    function($scope, $location, $http, resultHolder) {

        document.title = '/contribute.json';

        $scope.validation = {};
        $scope.validation.url = '';
        $scope.validation.method = 'url';

        $scope.validate = function() {
            if ($scope.validation.method === 'url') {
                if (!$scope.validation.url.trim()) return;
                var url = $scope.validation.url.trim();
                $location.path('/' + encodeURIComponent(url));
                // $location.path('/' + encodeURI(url));
                return false;
            } else if ($scope.validation.method === 'text') {
                if (!$scope.validation.text.trim()) return;
                    $http.post('/validate', $scope.validation.text)
                    .success(function(response) {
                        resultHolder.store(response);
                        $location.path('/result');
                    })
                    .error(function() {
                        console.warn(arguments);
                    });
            } else if ($scope.validation.method === 'file') {
                var input = document.querySelector('form input[type="file"]');
                if (!input.files.length) return;
                var reader = new FileReader();
                reader.onload = function(content) {
                    $http.post('/validate', content.target.result)
                    .success(function(response) {
                        // console.log('RESPONSE', response);
                        resultHolder.store(response);
                        $location.path('/result');
                    })
                    .error(function() {
                        console.warn(arguments);
                    });
                }
                reader.readAsText(input.files[0]);
            }
        };

        $scope.changeValidationMethod = function(method) {
            $scope.validation.method = method;
        };
}])

.controller('ExamplesController', [
    '$scope', '$http',
    function($scope, $http) {
        $scope.loading = true;
        document.title = 'Examples of contribute.json';
        $scope.projects = [];

        $http.get('/examples.json')
        .success(function(response) {
            $scope.urls = response.urls;
            $scope.urls.forEach(function(url) {
                $http.get('/load-example?url=' + encodeURIComponent(url))
                .success(function(response) {
                    if (response.project) {
                        $scope.projects.push(response.project);
                    } else {
                        console.warn('Failed to get a project for', url);
                    }
                });
            });
        })
        .error(function(data, status) {
            console.error(data, status);
        })
        .finally(function() {
            $scope.loading = false;
        });

}])

.controller('ValidationController', [
    '$scope', '$http', '$routeParams', '$location', 'resultHolder',
    function($scope, $http, $routeParams, $location, resultHolder) {
        var url = $routeParams.wildcard;
        if (url) {
            document.title = 'Validating ' + url;
            url = decodeURIComponent(url);
            // console.log('Look up', url);
        }
        $scope.finished = false;
        $scope.error = null;
        $scope.url = url;
        $scope.horribly_wrong = false;

        function pretty_json(obj) {
            return JSON.stringify(obj, undefined, 4);
        }

        function findUrls(struct) {
            var urls = [];
            for (var key in struct) {
                if (struct.hasOwnProperty(key)) {
                    var value = struct[key];
                    if (typeof value === 'object') {
                        urls.push.apply(urls, findUrls(value));
                    } else if (
                        (value.substr(0, 7) === 'http://' || value.substr(0, 8) === 'https://')
                        && value.indexOf(' ') === -1
                    ) {
                        if (urls.indexOf(value) === -1) {
                            urls.push(value);
                        }
                    }
                }
            }
            return urls;
        }

        function escapeRegExp(string){
            return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
        }

        function showResult(response) {
            // console.log(response);
            $scope.urls_to_check = [];
            $scope.schema = pretty_json(response.schema);
            $scope.schema_url = response.schema_url;
            if (!response.request_error) {
                $scope.response = pretty_json(response.response);  // yuck!
            } else {
                $scope.response = response.response;
            }

            if (response.schema_error) {
                $scope.schema_error = response.schema_error;
            } else if (response.validation_error) {
                $scope.error = response.validation_error;
            } else if (response.request_error) {
                $scope.request_error = response.request_error;
            } else {
                var urls = findUrls(response.response);
                $scope.urls_to_check = urls;
                urls.forEach(function(url) {
                    $http.post('/validateurl', {url: url})
                    .success(function(response) {
                        var reg = new RegExp('"' + escapeRegExp(url) + '"', 'g');
                        var tmpl;
                        if (response.status_code === 200 || response.status_code === 302) {
                            // console.log('Valid URL:', response.url);
                            tmpl = '"' + url + '"';
                        } else {
                            console.warn('Invalid URL:', response.url, response.status_code);
                            tmpl = '"' +
                                    url + '"';
                        }
                        $scope.response = $scope.response.replace(
                            reg,
                            tmpl
                        );

                    }).error(function() {
                        console.error(arguments);
                    }).finally(function() {
                        var index = $scope.urls_to_check.indexOf(url);
                        if (index > -1) {
                            $scope.urls_to_check.splice(index, 1);
                        }
                    });
                });
            }
            $scope.finished = true;
        }

        if (resultHolder.get()) {
            showResult(resultHolder.get());
        } else if (url) {
            $http({url: '/validate', method: 'POST', params: {url: url}})
            .success(showResult)
            .error(function(data, status) {
                $scope.horribly_wrong = true;
                $scope.finished = true;
                console.warn(data, status);
            });
        } else {
            $location.path('/');
        }

}])

;
<|endoftext|>


<commit_before>function getPassword() {
    $.get("http://localhost:8001/getPassword", function (data) {
    });
}<commit_msg>changed url for getPassword<commit_after>function getPassword() {
    $.get("http://admissions-staging.vschool.io/getPassword", function (data) {
    });
}<|endoftext|>


<commit_before>import React from 'react';
import {Dimensions, View} from 'react-native';
import {SceneNavigator, spring} from 'navigation-react-native';

const getStyle = (translate, scale, opacity) => ({
  translate: spring(translate),
  scale: spring(scale),
  opacity: spring(opacity)
});

export default ({stateNavigator, startStateKey, visible, offset}) => (
  <SceneNavigator
    startStateKey={startStateKey}
    unmountedStyle={getStyle(1, 1, 1)}
    mountedStyle={getStyle(0, 1, 1)}
    crumbStyle={getStyle(0.05, 0.9, 0)}
    style={{flex: +visible, backgroundColor: 'black'}}
    stateNavigator={stateNavigator}>
    {({translate, scale, opacity}, scene, active) => (
        <Scene
          visible={visible}
          scale={scale}
          translate={translate}
          opacity={opacity}
          offset={offset}
          pointerEvents={active ? 'auto' : 'none'}
          dimensions={Dimensions.get('window')}>
          {scene}
        </Scene>
    )}
  </SceneNavigator>
);

const Scene = ({visible, translate, scale, opacity, pointerEvents,
  dimensions: {width, height}, offset, children}) => (
  <View
    pointerEvents={pointerEvents}
    style={{
      position: 'absolute',
      backgroundColor: 'white',
      top: visible ? 0 : -2 * height,
      width: width,
      height: height -offset,
      opacity: opacity,
      transform: [
        {translateX: width * translate},
        {scale: scale},
      ]
    }}>
    {children}
  </View>
);
<commit_msg>Removed separate component<commit_after>import React from 'react';
import {Dimensions, View} from 'react-native';
import {SceneNavigator, spring} from 'navigation-react-native';

const getStyle = (translate, scale, opacity) => ({
  translate: spring(translate),
  scale: spring(scale),
  opacity: spring(opacity)
});

export default ({stateNavigator, startStateKey, visible, offset}) => (
  <SceneNavigator
    startStateKey={startStateKey}
    unmountedStyle={getStyle(1, 1, 1)}
    mountedStyle={getStyle(0, 1, 1)}
    crumbStyle={getStyle(0.05, 0.9, 0)}
    style={{flex: +visible, backgroundColor: 'black'}}
    stateNavigator={stateNavigator}>
    {({translate, scale, opacity}, scene, active) => {
      const {width, height} = Dimensions.get('window');
      return (
        <View
          pointerEvents={active ? 'auto' : 'none'}
          style={{
            position: 'absolute',
            backgroundColor: 'white',
            top: visible ? 0 : -2 * height,
            width: width,
            height: height -offset,
            opacity: opacity,
            transform: [
              {translateX: width * translate},
              {scale: scale},
            ]
          }}>
          {scene}
        </View>
      )
    }}
  </SceneNavigator>
);
<|endoftext|>


<commit_before>var gulp = require('gulp'),
	path = require('path'), <% if (options.pre === 'less') { %>
	precompile = require('gulp-less'), <% } %><% if (options.pre === 'scss') { %>
	precompile = require('gulp-sass'), <% } %>
	minify = require('gulp-minify-css'),
	autoprefixer = require('gulp-autoprefixer'),
	install = require('gulp-install'),
	concat = require('gulp-concat'),
	watch = require('gulp-watch'),
	uglify = require('gulp-uglify'),
	plumber = require('gulp-plumber'),
	jshint = require('gulp-jshint'),
	newer = require('gulp-newer'),
	imagemin = require('gulp-imagemin'),
	pngquant = require('imagemin-pngquant'),
	cache = require('gulp-cached'),
	remember = require('gulp-remember'),
	header = require('gulp-header'),
	globby = require('globby'),
	karma = require('karma').server,
	liveServer = require('gulp-live-server'),
	browserSync = require('browser-sync'),
	compression = require('compression'),
	rename = require('gulp-rename'),<% if (options.js === 'TypeScript') { %>
	ts = require('gulp-typescript'), <% } %>
	fs = require('fs'),
	del = require('del'),
	Promise = require('es6-promise').Promise,
	cfg = require('./app/core/config');

function getSourceFiles(ext) {
	var assets = [];

	for (var key in cfg.assets) {
		if (cfg.assets.hasOwnProperty(key) && ext === path.extname(key)) {
			var asset = cfg.assets[key],
				result = {
					name: key,
					deps: [],
					src:  []
				};

			for (var fkey in asset) {
				if (asset.hasOwnProperty(fkey)) {
					var filepath = asset[fkey];
					if (filepath.indexOf('+') === 0) {
						result.deps.push(filepath.substr(1));
					}
					else {
						result.src.push(filepath);
					}
				}
			}

			assets.push(result);
		}
	}

	return assets;
}

gulp.task('compile-css', ['install-bower'], function () {
	var assets = getSourceFiles('.css');
	var promises = [];

	assets.forEach(function (asset) {
		promises.push(new Promise(function(resolve) {
			globby(asset.deps, function(err, paths) {
				var imports = '';

				paths.forEach(function(path) {
					imports += fs.readFileSync(path);
				});

				gulp.src(asset.src)
					.pipe(plumber())
					.pipe(header(imports))
					.pipe(cache(asset.name))
					.pipe(precompile()<% if (options.pre === 'scss') { %>.on('error', precompile.logError)<% } %>)
					.pipe(autoprefixer({
						browsers: ['> 1%', 'last 2 versions', 'ie 9', 'android 4', 'Firefox ESR', 'Opera 12.1'],
						cascade: true
					}))
					.pipe(remember(asset.name))
					.pipe(concat(asset.name))
					.pipe(gulp.dest('public/assets/css/'))
					.on('end', function() {
						resolve();
					})
					.pipe(browserSync.reload({stream: true}));
			});
		}));
	});

	return Promise.all(promises);
});

<% if (options.js === 'TypeScript') { %>
	function splitJsAssets(asset) {
		var tsAssets = [],
			jsAssets = [];

		asset.src.forEach(function (value) {
			if (value.indexOf('.ts') !== -1) {
				tsAssets.push(value);
			} else {
				jsAssets.push(value);
			}
		});

		return {
			ts: tsAssets,
			js: jsAssets
		};
	}

	gulp.task('compile-ts', function(){
		var assets = getSourceFiles('.js');

		var tsDefinition = {
			typescript: require('typescript'),
			declarationFiles: false,
			removeComments: true,
			target: 'ES5'
		};

		var promises = [];

		assets.forEach(function (asset) {
			var assets = splitJsAssets(asset);

			promises.push(new Promise(function(resolve) {
				gulp.src(assets.ts)
					.pipe(plumber())
					.pipe(ts(tsDefinition))
					.js
					.pipe(concat(asset.name.replace('.js', '.ts.js')))
					.pipe(gulp.dest('public/assets/js'))
					.on('end', function() {
						resolve();
					});
			}));
		});

		return Promise.all(promises);
	});
<% } %>

gulp.task('compile-js', ['install-bower'<% if (options.js === 'TypeScript') { %> ,'compile-ts'<% } %>], function () {
	var assets = getSourceFiles('.js');
	var promises = [];

	assets.forEach(function (asset) {
		<% if (options.js === 'TypeScript') { %>
			var tsAssets = splitJsAssets(asset);
			tsAssets.js.push('public/assets/js/' + asset.name.replace('.js', '.ts.js'));
		<% } %>
		promises.push(new Promise(function(resolve) {
			gulp<% if (options.js === 'TypeScript') { %>.src(tsAssets.js)<% } else { %>.src(asset.src)<% } %>
				.pipe(plumber())
				.pipe(jshint())
				.pipe(jshint.reporter('jshint-stylish'))
				.pipe(concat(asset.name))
				.pipe(gulp.dest('public/assets/js'))
				.on('end', function () {
					resolve();
				})
				.pipe(browserSync.reload({stream: true}));
		}));
	});

	return Promise.all(promises);
});

gulp.task('minify-css', ['compile-css'], function () {
	var assets = getSourceFiles('.css');

	assets.forEach(function (asset) {
		gulp
			.src('public/assets/css/' + asset.name)
			.pipe(minify())
			.pipe(rename(asset.name.replace('.css', '.min.css')))
			.pipe(gulp.dest('public/assets/css/'));
	});

	return gulp;
});

gulp.task('minify-js', ['compile-js'], function () {
	var assets = getSourceFiles('.js');

	assets.forEach(function (asset) {
		gulp
			.src('public/assets/js/' + asset.name)
			.pipe(uglify())
			.pipe(rename(asset.name.replace('.js', '.min.js')))
			.pipe(gulp.dest('public/assets/js/'));
	});

	return gulp;
});

gulp.task('minify-img', function () {
	return gulp
		.src('assets/img/**/*')
		.pipe(newer('public/assets/img'))
		.pipe(imagemin({
			optimizationLevel: 7,
			progressive: true,
			multipass: true,
			svgoPlugins: [{cleanupIDs: false}, {removeUnknownsAndDefaults: false}, {removeViewBox: false}],
			use: [pngquant()]
		}))
		.pipe(gulp.dest('public/assets/img'));
});

gulp.task('copy-assets',   function () {
	gulp
		.src(['assets/font/**/*'])
		.pipe(newer('public/assets/font'))
		.pipe(gulp.dest('public/assets/font'));

	return gulp;
});

gulp.task('assets', ['copy-assets', 'minify-img', 'minify-css', 'minify-js']);

gulp.task('watch', ['assets'], function () {
	var clearCache = function (e) {
		if ('delete' === e.type) {
			delete cache.caches.scripts[e.path];
			remember.forget('scripts', e.path);
		}
	};

	watch([
		'config.json'
	], function(e) {
		cfg = cfg.reload();
		gulp.start('compile-css');
		gulp.start('compile-js');
	});

	watch([
		'assets/**/*.<%= options.pre %>',
		'components/**/*.<%= options.pre %>'
	], function(e) {
		clearCache(e);
		gulp.start('compile-css');
	});

	watch([
		'assets/**/*.js',
		'components/**/*.js'<% if (options.js === 'TypeScript') { %>,
		'assets/**/*.ts',
		'components/**/*.ts'
		<% } %>
	], function(e) {
		clearCache(e);
		gulp.start('compile-js');
	});

	watch([
		'views/**/*.html',
		'!' + cfg.nitro.view_partials_directory + '/*.html', // exclude partials
		'views/_data/**/*.json',
		'components/**/*.html',
		'components/**/_data/*.json'
	], function(e) {
		browserSync.reload();
	});

	watch([
		'assets/img/**/*'
	], function(e) {
		gulp.start('minify-img');
	});

	watch([
		'assets/font/**/*'
	], function(e) {
		gulp.start('copy-assets');
	});
});

gulp.task('browser-sync', ['serve'], function () {
	var port = process.env.PORT || 8080,
		proxy = process.env.PROXY || 8081;

	browserSync({
		proxy: {
			target: 'localhost:' + port,
			middleware: [compression()]
		},
		port:  proxy
	}, function (err) {
		if (!err) {
			browserSync.notify('Compiling your assets, please wait!');
		}
	});
});

gulp.task('serve', ['install-npm'], function() {
	var port = process.env.PORT || 8080,
		server = liveServer(
			'server.js',
			{
				env: {
					PORT: port
				}
			}
		);

	server.start();

	watch(['server.js', 'app/core/*.js'], server.start);
});

gulp.task('install-bower', function () {
	return gulp.src(['./bower.json'])
		.pipe(install());
});

gulp.task('install-npm', function () {
	return gulp.src(['./package.json'])
		.pipe(install());
});

gulp.task('clean', function() {
	del.bind( null, ['public/assets/*'] );
});

gulp.task('test', ['compile-css', 'compile-js'], function (done) {
	karma.start({
		configFile: path.join(__dirname, 'karma.conf.js'),
		singleRun:  true,
		autoWatch:  false
	}, done);
});

gulp.task('develop', ['watch', 'browser-sync']);
gulp.task('production', ['assets', 'serve']);
gulp.task('build', ['clean'], function() {
	gulp.start('assets');
});
<commit_msg>#22 remove install from compile tasks (temp)<commit_after>var gulp = require('gulp'),
	path = require('path'), <% if (options.pre === 'less') { %>
	precompile = require('gulp-less'), <% } %><% if (options.pre === 'scss') { %>
	precompile = require('gulp-sass'), <% } %>
	minify = require('gulp-minify-css'),
	autoprefixer = require('gulp-autoprefixer'),
	install = require('gulp-install'),
	concat = require('gulp-concat'),
	watch = require('gulp-watch'),
	uglify = require('gulp-uglify'),
	plumber = require('gulp-plumber'),
	jshint = require('gulp-jshint'),
	newer = require('gulp-newer'),
	imagemin = require('gulp-imagemin'),
	pngquant = require('imagemin-pngquant'),
	cache = require('gulp-cached'),
	remember = require('gulp-remember'),
	header = require('gulp-header'),
	globby = require('globby'),
	karma = require('karma').server,
	liveServer = require('gulp-live-server'),
	browserSync = require('browser-sync'),
	compression = require('compression'),
	rename = require('gulp-rename'),<% if (options.js === 'TypeScript') { %>
	ts = require('gulp-typescript'), <% } %>
	fs = require('fs'),
	del = require('del'),
	Promise = require('es6-promise').Promise,
	cfg = require('./app/core/config');

function getSourceFiles(ext) {
	var assets = [];

	for (var key in cfg.assets) {
		if (cfg.assets.hasOwnProperty(key) && ext === path.extname(key)) {
			var asset = cfg.assets[key],
				result = {
					name: key,
					deps: [],
					src:  []
				};

			for (var fkey in asset) {
				if (asset.hasOwnProperty(fkey)) {
					var filepath = asset[fkey];
					if (filepath.indexOf('+') === 0) {
						result.deps.push(filepath.substr(1));
					}
					else {
						result.src.push(filepath);
					}
				}
			}

			assets.push(result);
		}
	}

	return assets;
}

gulp.task('compile-css', function () {
	var assets = getSourceFiles('.css');
	var promises = [];

	assets.forEach(function (asset) {
		promises.push(new Promise(function(resolve) {
			globby(asset.deps, function(err, paths) {
				var imports = '';

				paths.forEach(function(path) {
					imports += fs.readFileSync(path);
				});

				gulp.src(asset.src)
					.pipe(plumber())
					.pipe(header(imports))
					.pipe(cache(asset.name))
					.pipe(precompile()<% if (options.pre === 'scss') { %>.on('error', precompile.logError)<% } %>)
					.pipe(autoprefixer({
						browsers: ['> 1%', 'last 2 versions', 'ie 9', 'android 4', 'Firefox ESR', 'Opera 12.1'],
						cascade: true
					}))
					.pipe(remember(asset.name))
					.pipe(concat(asset.name))
					.pipe(gulp.dest('public/assets/css/'))
					.on('end', function() {
						resolve();
					})
					.pipe(browserSync.reload({stream: true}));
			});
		}));
	});

	return Promise.all(promises);
});

<% if (options.js === 'TypeScript') { %>
	function splitJsAssets(asset) {
		var tsAssets = [],
			jsAssets = [];

		asset.src.forEach(function (value) {
			if (value.indexOf('.ts') !== -1) {
				tsAssets.push(value);
			} else {
				jsAssets.push(value);
			}
		});

		return {
			ts: tsAssets,
			js: jsAssets
		};
	}

	gulp.task('compile-ts', function(){
		var assets = getSourceFiles('.js');

		var tsDefinition = {
			typescript: require('typescript'),
			declarationFiles: false,
			removeComments: true,
			target: 'ES5'
		};

		var promises = [];

		assets.forEach(function (asset) {
			var assets = splitJsAssets(asset);

			promises.push(new Promise(function(resolve) {
				gulp.src(assets.ts)
					.pipe(plumber())
					.pipe(ts(tsDefinition))
					.js
					.pipe(concat(asset.name.replace('.js', '.ts.js')))
					.pipe(gulp.dest('public/assets/js'))
					.on('end', function() {
						resolve();
					});
			}));
		});

		return Promise.all(promises);
	});
<% } %>

gulp.task('compile-js', <% if (options.js === 'TypeScript') { %>['compile-ts'], <% } %>function () {
	var assets = getSourceFiles('.js');
	var promises = [];

	assets.forEach(function (asset) {
		<% if (options.js === 'TypeScript') { %>
			var tsAssets = splitJsAssets(asset);
			tsAssets.js.push('public/assets/js/' + asset.name.replace('.js', '.ts.js'));
		<% } %>
		promises.push(new Promise(function(resolve) {
			gulp<% if (options.js === 'TypeScript') { %>.src(tsAssets.js)<% } else { %>.src(asset.src)<% } %>
				.pipe(plumber())
				.pipe(jshint())
				.pipe(jshint.reporter('jshint-stylish'))
				.pipe(concat(asset.name))
				.pipe(gulp.dest('public/assets/js'))
				.on('end', function () {
					resolve();
				})
				.pipe(browserSync.reload({stream: true}));
		}));
	});

	return Promise.all(promises);
});

gulp.task('minify-css', ['compile-css'], function () {
	var assets = getSourceFiles('.css');

	assets.forEach(function (asset) {
		gulp
			.src('public/assets/css/' + asset.name)
			.pipe(minify())
			.pipe(rename(asset.name.replace('.css', '.min.css')))
			.pipe(gulp.dest('public/assets/css/'));
	});

	return gulp;
});

gulp.task('minify-js', ['compile-js'], function () {
	var assets = getSourceFiles('.js');

	assets.forEach(function (asset) {
		gulp
			.src('public/assets/js/' + asset.name)
			.pipe(uglify())
			.pipe(rename(asset.name.replace('.js', '.min.js')))
			.pipe(gulp.dest('public/assets/js/'));
	});

	return gulp;
});

gulp.task('minify-img', function () {
	return gulp
		.src('assets/img/**/*')
		.pipe(newer('public/assets/img'))
		.pipe(imagemin({
			optimizationLevel: 7,
			progressive: true,
			multipass: true,
			svgoPlugins: [{cleanupIDs: false}, {removeUnknownsAndDefaults: false}, {removeViewBox: false}],
			use: [pngquant()]
		}))
		.pipe(gulp.dest('public/assets/img'));
});

gulp.task('copy-assets',   function () {
	gulp
		.src(['assets/font/**/*'])
		.pipe(newer('public/assets/font'))
		.pipe(gulp.dest('public/assets/font'));

	return gulp;
});

gulp.task('assets', ['copy-assets', 'minify-img', 'minify-css', 'minify-js']);

gulp.task('watch', ['assets'], function () {
	var clearCache = function (e) {
		if ('delete' === e.type) {
			delete cache.caches.scripts[e.path];
			remember.forget('scripts', e.path);
		}
	};

	watch([
		'config.json'
	], function(e) {
		cfg = cfg.reload();
		gulp.start('compile-css');
		gulp.start('compile-js');
	});

	watch([
		'assets/**/*.<%= options.pre %>',
		'components/**/*.<%= options.pre %>'
	], function(e) {
		clearCache(e);
		gulp.start('compile-css');
	});

	watch([
		'assets/**/*.js',
		'components/**/*.js'<% if (options.js === 'TypeScript') { %>,
		'assets/**/*.ts',
		'components/**/*.ts'
		<% } %>
	], function(e) {
		clearCache(e);
		gulp.start('compile-js');
	});

	watch([
		'views/**/*.html',
		'!' + cfg.nitro.view_partials_directory + '/*.html', // exclude partials
		'views/_data/**/*.json',
		'components/**/*.html',
		'components/**/_data/*.json'
	], function(e) {
		browserSync.reload();
	});

	watch([
		'assets/img/**/*'
	], function(e) {
		gulp.start('minify-img');
	});

	watch([
		'assets/font/**/*'
	], function(e) {
		gulp.start('copy-assets');
	});
});

gulp.task('browser-sync', ['serve'], function () {
	var port = process.env.PORT || 8080,
		proxy = process.env.PROXY || 8081;

	browserSync({
		proxy: {
			target: 'localhost:' + port,
			middleware: [compression()]
		},
		port:  proxy
	}, function (err) {
		if (!err) {
			browserSync.notify('Compiling your assets, please wait!');
		}
	});
});

gulp.task('serve', function () {
	var port = process.env.PORT || 8080,
		server = liveServer(
			'server.js',
			{
				env: {
					PORT: port
				}
			}
		);

	server.start();

	watch(['server.js', 'app/core/*.js'], server.start);
});

gulp.task('install-bower', function () {
	return gulp.src(['./bower.json'])
		.pipe(install());
});

gulp.task('install-npm', function () {
	return gulp.src(['./package.json'])
		.pipe(install());
});

gulp.task('clean', function() {
	del.bind( null, ['public/assets/*'] );
});

gulp.task('test', ['compile-css', 'compile-js'], function (done) {
	karma.start({
		configFile: path.join(__dirname, 'karma.conf.js'),
		singleRun:  true,
		autoWatch:  false
	}, done);
});

gulp.task('develop', ['watch', 'browser-sync']);
gulp.task('production', ['assets'], function(){
	gulp.start('serve');
});
gulp.task('build', ['clean'], function() {
	gulp.start('assets');
});
<|endoftext|>