Skip to content

Instantly share code, notes, and snippets.

@mads-hartmann
Created June 26, 2010 22:08
Show Gist options
  • Save mads-hartmann/454381 to your computer and use it in GitHub Desktop.
Save mads-hartmann/454381 to your computer and use it in GitHub Desktop.
package code.comet
import scala.xml.{NodeSeq, Text}
import net.liftweb._
import http._
import actor._
import http.js._
import JsCmds._
import JE._
import java.util.Date
object MessageStaus extends Enumeration {
type MessageStaus = Value
val Normal = Value("normal")
val Add = Value("Add")
val Delete = Value("Delete")
}
import MessageStaus._
case class ChatMessage(message: String, status: MessageStaus, timestamp: Date){
def removeBtn = SHtml.ajaxButton("delete", () => {
NewChatServer ! ChatMessage(this.message,MessageStaus.Delete,this.timestamp)
Noop
})
def toXhtml = {
<li class={this.status.toString}>
{ this.toString }
{ this.removeBtn }
</li>
}
override def equals(obj: Any) = obj match {
case msg: ChatMessage => (this.message == msg.message && this.timestamp == msg.timestamp)
case _ => false
}
override def toString = "(%s) %s, %s".format(status.toString, message, timestamp.toString)
}
object NewChatServer extends LiftActor with ListenerManager {
private var messages = List(ChatMessage("Welcome",MessageStaus.Normal, new Date()))
def updateMessages = {
messages = messages.map{ msg => msg match {
case msg if msg.status == MessageStaus.Add =>
ChatMessage(msg.message,MessageStaus.Normal,msg.timestamp)
case msg: ChatMessage => msg
}}
.filter { msg => msg.status != MessageStaus.Delete }
}
def createUpdate = messages
override def lowPriority = {
case msg @ ChatMessage(_,MessageStaus.Delete,_) => {
messages = messages.map{ message =>
if (message == msg) {
ChatMessage(msg.message,MessageStaus.Delete,msg.timestamp)
} else {
message
}
}
updateListeners()
updateMessages
}
case msg @ ChatMessage(_,_,_) =>
messages ::= msg ; updateListeners(); updateMessages
}
}
class NewChat extends CometActor with CometListener {
private var msgs: List[ChatMessage] = Nil
def registerWith = NewChatServer
override def lowPriority = {
case m: List[ChatMessage] => msgs = m; reRender(true)
}
def render = {
<div>
<ul> { msgs.reverse.map( _.toXhtml ) } </ul>
<lift:form>
{
SHtml.text("", s => NewChatServer ! ChatMessage(s,MessageStaus.Add, new Date))
}
<input type="submit" value="Chat"/>
<script type="text/javascript">
{
Call("update")
}
</script>
</lift:form>
</div>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment