summaryrefslogtreecommitdiff
path: root/static/chat.js
blob: d9c89fe7f6140741b4ce6a8fb56fb0afb983e225 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
function askTryAgain(reason, ws_url) {
	if(confirm("Could not join chat (Reason: "+ reason +"). Try again?")) {
		window.setTimeout(RunChat, 1, ws_url); // We use a timeout, so we don't accidentally fill up the call stack.
	}
}

function addBuddy(nick) {
	var found = false;
	$("#buddies li").each(function(index) {
		if($(this).text() == nick) {
			found = true;
		}
	});
	if(!found) {
		$("#buddies").append($("<li/>").text(nick));
	}
}

function removeBuddy(nick) {
	$("#buddies li").each(function(index) {
		var self = $(this);
		if(self.text() == nick) {
			self.remove();
		}
	});
}

function chatlogWriter(event) {
	var data = JSON.parse(event.data);
	var msgtext = "";
	switch(data.type) {
	case "chat":
		msgtext = data.text;
		break;
	case "join":
		msgtext = "joined the room";
		addBuddy(data.user);
		break;
	case "leave":
		msgtext = "left the room";
		removeBuddy(data.user);
		break;
	}
	
	var elemNick = $("<span/>").addClass("nick").text(data.user);
	var elemText = $("<span/>").addClass("msg").text(msgtext);
	var logentry = $("<li/>").addClass(data.type).append(elemNick).append(elemText);
	$("#chatlog").append(logentry);
	window.scrollTo(0, logentry.offset().top);
}

function initChatSender(ws) {
	var send = function() {
		var ct = $("#chattext")
		ws.send(ct.prop("value"));
		ct.prop("value","");
		ct.focus();
	};
	
	$("#sendbtn").click(send);
	$("#chattext").keyup(function(event) {
		if(event.keyCode==13) {
			send();
		}
	});
}

function Join(ws_url, nick) {
	var ws = new WebSocket(ws_url, "chat");
	ws.onopen = function(_) {
		ws.send(nick); 
		ws.onmessage = function(event) {
			var data = JSON.parse(event.data);
			if(data.ok) {
				ws.onmessage = chatlogWriter;
				for(i in data.buddies) {
					addBuddy(data.buddies[i]);
				}
				initChatSender(ws);
				ws.onclose = function(_) {
					alert("Connection lost. Try refreshing the page.");
				};
			} else {
				ws.close();
				askTryAgain(data.error, ws_url);
			}
		};
	};
}

function RunChat(ws_url) {
	var nick = "";
	while(nick == "") {
		nick = prompt("Choose a nickname");
		if(nick === null) {
			return;
		}
	}
	Join(ws_url, nick);
}