server/www/room.js

75 lines
1.8 KiB
JavaScript

function Room(modules) {
function Player(key, name) {
this.key = key;
this.name = name;
this.dom = modules.dom.make('li', {textContent: name});
this.position = null;
}
var players = {};
var sortedKeys = [];
var session = {
key: null,
loggedIn: false,
selected: null
};
modules.messaging.addEventListener(["Welcome"], populate);
modules.messaging.addEventListener(["Okaeri"], populate);
modules.messaging.addEventListener(["LogIn"], function(o) {
enter(o.from, o.as);
});
modules.messaging.addEventListener(["Relay", "LogOut"], function(o) {
leave(o.from);
});
var compareKeysByLogin = modules.fun.map(function(key) {return players[key].name;}, modules.fun.defaultCompare);
return {
filter: filter,
/*enter: enter,*/
leave: leave,
name: name
};
function filter(name) {
if(modules.session.isLoggedIn()) {
var keep = function(player) {
return player.name.match(name) && !modules.session.is(player.key);
};
} else {
var keep = function(player) {return player.name.match(name);};
}
return modules.fun.mapFilter(modules.fun.of(players), keep)(sortedKeys);
}
function enter(key, name) {
name = name || "anon";
var player = new Player(key, name);
players[key] = player;
player.position = modules.fun.insert(key, sortedKeys, compareKeysByLogin);
sortedKeys.splice(player.position, 0, key);
}
function populate(o) {
for(var key in o.room) {
enter(key, o.room[key]);
}
}
function leave(key) {
var player = players[key];
if(player != undefined) {
sortedKeys.splice(player.position, 1);
delete players[key];
}
}
function name(key) {
player = players[key];
return player && player.name;
}
}