Permalink
Browse files

refactored some client code

  • Loading branch information...
1 parent ad8159f commit 260a3839a66560fbf7af4e14bf5f7a96c54210a7 @twilson63 twilson63 committed Jun 15, 2010
Showing with 96 additions and 131 deletions.
  1. +29 −53 client.coffee
  2. +45 −58 client.js
  3. +3 −2 index.html
  4. +7 −9 server.coffee
  5. +6 −7 server.js
  6. +6 −2 style.css
View
@@ -12,16 +12,16 @@ nicks: []
Date::toRelativeTime: (now_threshold) ->
delta: new Date() - this
now_threshold: parseInt(now_threshold, 10)
- if isNaN(now_threshold) then now_threshold: 0
- if delta <= now_threshold then return 'Just now'
+ now_threshold: 0 if isNaN(now_threshold)
+ return 'Just now' if delta <= now_threshold
units: null
conversions: {
- millisecond: 1, # ms -> ms
- second: 1000, # ms -> sec
- minute: 60, # sec -> min
- hour: 60, # min -> hour
- day: 24, # hour -> day
- month: 30, # day -> month (roughly)
+ millisecond: 1 # ms -> ms
+ second: 1000 # ms -> sec
+ minute: 60 # sec -> min
+ hour: 60 # min -> hour
+ day: 24 # hour -> day
+ month: 30 # day -> month (roughly)
year: 12 # month -> year
}
@@ -33,7 +33,7 @@ Date::toRelativeTime: (now_threshold) ->
delta: delta / value
delta: Math.floor(delta)
- if delta isnt 1 then units += 's'
+ units += 's' if delta isnt 1
return [delta, units].join(" ")
@@ -42,68 +42,49 @@ Date.fromString: (str) -> new Date(Date.parse(str))
#updates the users link to reflect the number of active users
updateUsersLink: ->
t: nicks.length.toString() + " user"
- if nicks.length isnt 1 then t += "s"
+ t += "s" if nicks.length isnt 1
$("#usersLink").text t
#handles another person joining chat
userJoin: (nick, timestamp) ->
#put it in the stream
addMessage nick, "joined", timestamp, "join"
- #if we already know about this user, ignore it
- for n in nicks
- if n is nick then return
- #otherwise, add the user to the list
- nicks.push(nick)
- #update the UI
- updateUsersLink()
+ if nicks.indexOf(nick) is -1
+ #otherwise, add the user to the list
+ nicks.push nick
+ #update the UI
+ updateUsersLink()
#handles someone leaving
userPart: (nick, timestamp) ->
#put it in the stream
addMessage nick, "left", timestamp, "part"
#remove the user from the list
- for n in nicks
- if n is nick
- nicks.splice(i,1)
- break
-
+ nicks.split nicks.indexOf(nick), 1
#update the UI
- updateUsersLink();
+ updateUsersLink()
# utility functions
-
-util: {
- urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g,
-
- # html sanitizer
+class Util
+ urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g
toStaticHTML: (inputHtml) ->
inputHtml: inputHtml.toString()
- return inputHtml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
-
- #pads n with zeros on the left,
- #digits is minimum length of output
- #zeroPad(3, 5); returns "005"
- #zeroPad(2, 500); returns "500"
+ inputHtml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
zeroPad: (digits, n) ->
n = n.toString()
while n.length < digits
n = '0' + n
- return n
-
- #it is almost 8 o'clock PM here
- #timeString(new Date); returns "19:49"
+ n
timeString: (date) ->
minutes: date.getMinutes().toString()
hours: date.getHours().toString()
- return @zeroPad(2, hours) + ":" + @zeroPad(2, minutes)
-
-
- #does the argument only contain whitespace?
+ @zeroPad(2, hours) + ":" + @zeroPad(2, minutes)
isBlank: (text) ->
blank: /^\s*$/
- return text.match(blank) isnt null
-}
+ text.match(blank) isnt null
+
+util: new Util()
#used to keep the most recent messages visible
scrollDown: ->
@@ -115,8 +96,7 @@ scrollDown: ->
#from is the user, text is the body and time is the timestamp, defaulting to now
#_class is a css class to apply to the message, usefull for system events
addMessage: (from, text, time, _class) ->
- if text is null then return
-
+ return if text is null
if time is null
# if the time is null or undefined, use the current time.
time: new Date()
@@ -129,20 +109,17 @@ addMessage: (from, text, time, _class) ->
# the person who caused the event,
# and the content
messageElement: $(document.createElement("table"))
-
messageElement.addClass("message")
- if _class then messageElement.addClass(_class)
+ messageElement.addClass(_class) if _class
# sanitize
text: util.toStaticHTML(text)
# If the current user said this, add a special css class
nick_re: new RegExp(CONFIG.nick)
- if nick_re.exec(text) then messageElement.addClass("personal")
-
+ messageElement.addClass("personal") if nick_re.exec(text)
# replace URLs with links
text: text.replace(util.urlRE, '<a target="_blank" href="$&">$&</a>')
-
content: """
<tr>
<td class="date">${ util.timeString(time) }</td>
@@ -229,7 +206,7 @@ longPoll: (data) ->
#don't flood the servers on error, wait 10 seconds before retrying
setTimeout(longPoll, 10*1000)
success: (data) ->
- transmission_errors = 0;
+ transmission_errors: 0
#if everything went well, begin another request immediately
#the server will take a long time to respond
#how long? well, it will wait until there is another message
@@ -330,7 +307,6 @@ who: ->
)
$(document).ready( ->
- alert('hello world')
#submit new messages when the user hits enter if the message isnt blank
$("#entry").keypress( (e) ->
if e.keyCode isnt 13 then return
View
103 client.js
@@ -1,4 +1,4 @@
-var CONFIG, addMessage, first_poll, longPoll, nicks, onConnect, outputUsers, rss, scrollDown, send, showChat, showConnect, showLoad, starttime, transmission_errors, updateRSS, updateTitle, updateUptime, updateUsersLink, userJoin, userPart, util, who;
+var CONFIG, Util, addMessage, first_poll, longPoll, nicks, onConnect, outputUsers, rss, scrollDown, send, showChat, showConnect, showLoad, starttime, transmission_errors, updateRSS, updateTitle, updateUptime, updateUsersLink, userJoin, userPart, util, who;
var __hasProp = Object.prototype.hasOwnProperty;
CONFIG = {
debug: false,
@@ -17,7 +17,9 @@ Date.prototype.toRelativeTime = function(now_threshold) {
var _a, conversions, delta, key, units, value;
delta = new Date() - this;
now_threshold = parseInt(now_threshold, 10);
- isNaN(now_threshold) ? (now_threshold = 0) : null;
+ if (isNaN(now_threshold)) {
+ now_threshold = 0;
+ }
if (delta <= now_threshold) {
return 'Just now';
}
@@ -49,7 +51,9 @@ Date.prototype.toRelativeTime = function(now_threshold) {
}
}}
delta = Math.floor(delta);
- delta !== 1 ? units += 's' : null;
+ if (delta !== 1) {
+ units += 's';
+ }
return [delta, units].join(" ");
};
Date.fromString = function(str) {
@@ -59,78 +63,58 @@ Date.fromString = function(str) {
updateUsersLink = function() {
var t;
t = nicks.length.toString() + " user";
- nicks.length !== 1 ? t += "s" : null;
+ if (nicks.length !== 1) {
+ t += "s";
+ }
return $("#usersLink").text(t);
};
//handles another person joining chat
userJoin = function(nick, timestamp) {
- var _a, _b, _c, n;
//put it in the stream
addMessage(nick, "joined", timestamp, "join");
- //if we already know about this user, ignore it
- _b = nicks;
- for (_a = 0, _c = _b.length; _a < _c; _a++) {
- n = _b[_a];
- if (n === nick) {
- return null;
- }
+ if (nicks.indexOf(nick) === -1) {
//otherwise, add the user to the list
+ nicks.push(nick);
+ //update the UI
+ return updateUsersLink();
}
- nicks.push(nick);
- //update the UI
- return updateUsersLink();
};
//handles someone leaving
userPart = function(nick, timestamp) {
- var _a, _b, _c, n;
//put it in the stream
addMessage(nick, "left", timestamp, "part");
//remove the user from the list
- _b = nicks;
- for (_a = 0, _c = _b.length; _a < _c; _a++) {
- n = _b[_a];
- if (n === nick) {
- nicks.splice(i, 1);
- break;
- }
- }
+ nicks.split(nicks.indexOf(nick), 1);
//update the UI
return updateUsersLink();
};
// utility functions
-util = {
- urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g,
- // html sanitizer
- toStaticHTML: function(inputHtml) {
- inputHtml = inputHtml.toString();
- return inputHtml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
- },
- //pads n with zeros on the left,
- //digits is minimum length of output
- //zeroPad(3, 5); returns "005"
- //zeroPad(2, 500); returns "500"
- zeroPad: function(digits, n) {
- n = n.toString();
- while (n.length < digits) {
- n = '0' + n;
- }
- return n;
- },
- //it is almost 8 o'clock PM here
- //timeString(new Date); returns "19:49"
- timeString: function(date) {
- var hours, minutes;
- minutes = date.getMinutes().toString();
- hours = date.getHours().toString();
- return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
- },
- //does the argument only contain whitespace?
- isBlank: function(text) {
- var blank;
- blank = /^\s*$/;
- return text.match(blank) !== null;
+Util = function() {};
+Util.prototype.urlRE = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g;
+Util.prototype.toStaticHTML = function(inputHtml) {
+ inputHtml = inputHtml.toString();
+ return inputHtml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+};
+Util.prototype.zeroPad = function(digits, n) {
+ n = n.toString();
+ while (n.length < digits) {
+ n = '0' + n;
}
+ return n;
};
+Util.prototype.timeString = function(date) {
+ var hours, minutes;
+ minutes = date.getMinutes().toString();
+ hours = date.getHours().toString();
+ return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
+};
+Util.prototype.isBlank = function(text) {
+ var blank;
+ blank = /^\s*$/;
+ return text.match(blank) !== null;
+};
+
+util = new Util();
//used to keep the most recent messages visible
scrollDown = function() {
window.scrollBy(0, 100000000000000000);
@@ -158,12 +142,16 @@ addMessage = function(from, text, time, _class) {
// and the content
messageElement = $(document.createElement("table"));
messageElement.addClass("message");
- _class ? messageElement.addClass(_class) : null;
+ if (_class) {
+ messageElement.addClass(_class);
+ }
// sanitize
text = util.toStaticHTML(text);
// If the current user said this, add a special css class
nick_re = new RegExp(CONFIG.nick);
- nick_re.exec(text) ? messageElement.addClass("personal") : null;
+ if (nick_re.exec(text)) {
+ messageElement.addClass("personal");
+ }
// replace URLs with links
text = text.replace(util.urlRE, '<a target="_blank" href="$&">$&</a>');
content = ("<tr>\n <td class=\"date\">" + (util.timeString(time)) + "</td>\n <td class=\"nick\">" + (util.toStaticHTML(from)) + "</td>\n <td class=\"msg-text\">" + text + "</td>\n</tr>");
@@ -348,7 +336,6 @@ who = function() {
}, "json");
};
$(document).ready(function() {
- alert('hello world');
//submit new messages when the user hits enter if the message isnt blank
$("#entry").keypress(function(e) {
var msg;
View
@@ -3,7 +3,7 @@
<link rel="stylesheet" href="style.css" type="text/css"/>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="client.js" type="text/javascript"></script>
- <title>node chat</title>
+ <title>coffee chat</title>
</head>
<body>
<div id="app">
@@ -12,7 +12,7 @@
<fieldset>
<p>
This is a chat room. Both the client-side and server-side are
- written in javascript. The source code is
+ written in coffeescript. The source code is
<a href="http://github.com/jackhq/coffee-chat">here</a>.
</p>
@@ -185,5 +185,6 @@
</ul>
<input tabindex="1" type="text" id="entry"/>
</div>
+ </div>
</body>
</html>
Oops, something went wrong.

0 comments on commit 260a383

Please sign in to comment.