Permalink
Browse files

refactoring: divide into widgets

  • Loading branch information...
1 parent 50ef0f8 commit 8bc8b204b3757a01d4086bc0a98fb7b64561e3d2 Daniel Hobi committed Jan 31, 2014
View
125 src/main/scala/code/comet/ChatUser.scala
@@ -10,117 +10,98 @@ import net.liftweb.http.js.JsCmds
import code.util.Coords
import net.liftweb.common.Full
import net.liftweb.util.Helpers._
+import code.widget.{ColorPicker, Chat, Earth, GoogleMaps}
class ChatUser extends User with CometActor {
var message = ""
+
lazy val id = Helpers.nextFuncName
+ val googleMaps = new GoogleMaps("googleMap")
+ val earth = new Earth
+ val chat = new Chat("messages")
+ val colorpicker = new ColorPicker("colorpicker")
+
+ val validations = List((() => this.coords.isDefined, "Please set your location on the map first."))
+
override def lowPriority = {
- case NewConnection(user) =>
- val connection = JsRaw("earth.createConnection('" + user.id + "',{latitude:" + user.latToString + ",longitude:" + user.longToString + "}, " + user.colorToHexInt + ")").cmd
- val chat = JsRaw( """document.getElementById("messages").innerHTML += "<div style='color: """ + user.color + """;'>New Connection</div>"""").cmd
- partialUpdate(connection & chat)
- case ClosedConnection(user) =>
- val connection = JsRaw("earth.removeConnection('" + user.id + "')").cmd
- val chat = JsRaw( """document.getElementById("messages").innerHTML += "<div style='color: """ + user.color + """;'>Connection lost</div>"""").cmd
- partialUpdate(connection & chat)
- case Message(user, msg) => partialUpdate(JsRaw("earth.newMessage('" + user.id + "','" + msg.replace("'", "\\'") + "')").cmd)
+ case NewConnection(user) => partialUpdate(
+ earth.createConnection(user.id, user.lat, user.long, user.colorToHexInt) &
+ chat.newMessage("New Connection", user.color)
+ )
+ case ClosedConnection(user) => partialUpdate(
+ earth.removeConnection(user.id) &
+ chat.newMessage("Connection lost", user.color)
+ )
+ case Message(user, msg) => partialUpdate(earth.newMessage(user.id, msg))
case _ => //no no
}
override def lifespan = Full(0 seconds)
- def initUserForm = {
- def callback(forValue: String) = SHtml.ajaxCall(JsRaw(forValue), str => {
- this.coords = Helpers.tryo {
- val splitted = str.split(",")
- Coords(splitted.head.toDouble, splitted.last.toDouble)
- }
- SetHtml("connectButton", generateConnectButton)
- })
-
- def initPosition = coords match {
- case Full(Coords(lat, long)) => JsRaw("map.setPosition(new google.maps.LatLng(" + lat + "," + long + "))").cmd
- case _ => JsCmds.Noop
- }
-
- def markerDrop = {
- JsRaw( """map.registerMarkerCallback(function(event) {
- var lat = event.latLng.lat();
- var lng = event.latLng.lng();
- var value = lat+","+lng;
- """ + callback("value").toJsCmd + """})""").cmd
- }
+ def render = {
- def showForm = SetHtml("userform", userForm)
+ def initUserForm = {
+ def userForm = {
+ ("#colorpicker" #> colorpicker.onChange(this.color, str => {
+ this.color = str
+ JsCmds.Noop
+ }) &
+ "#userSubmit" #> generateConnectButton)(Templates(List("templates", "userSetup")).openOr(NodeSeq.Empty))
+ }
- def initColorPicker = JsRaw( """$("#colorpicker").colorpicker();""").cmd
+ def showForm = SetHtml("userform", userForm)
- def initMaps(elem: String) = JsRaw("map = new GoogleMaps('" + elem + "');").cmd
+ def onDrop(lat: Double, long: Double) = {
+ coords = Full(Coords(lat, long))
+ SetHtml("connectButton", generateConnectButton)
+ }
- showForm & initColorPicker & initMaps("googleMap") & initPosition & markerDrop
- }
+ showForm & colorpicker.init & googleMaps.init & googleMaps.initPosition(coords) & googleMaps.markerDrop(onDrop)
+ }
- def noWebGL = {
+ def noWebGL = SetHtml("userform", Templates(List("templates", "nowebgl")).openOr(NodeSeq.Empty))
- SetHtml("userform", Templates(List("templates", "nowebgl")).openOr(NodeSeq.Empty))
- }
-
- def render = {
- ChatServer ! ClosedConnection(this)
- val exp = SHtml.ajaxCall(JsRaw("Detector.webgl ? 'true' : 'false'"), str => Helpers.asBoolean(str) match {
+ def onload = SHtml.ajaxCall(JsRaw("Detector.webgl ? 'true' : 'false'"), str => Helpers.asBoolean(str) match {
case Full(true) => initUserForm
case _ => noWebGL
- })
+ }).cmd
- val chatNode = ("#message" #> SHtml.text(message, str => {
+ ChatServer ! ClosedConnection(this)
+ ("#message" #> SHtml.text(message, str => {
message = str
}) &
"#sendMessage" #> SHtml.ajaxSubmit("Send", () => {
if (message.nonEmpty) {
ChatServer ! Message(this, message)
}
JsCmds.SetValueAndFocus("message", "")
- }))(defaultHtml)
- chatNode ++ <div>
- {Script(OnLoad(exp.cmd))}
- </div>
+ }))(defaultHtml) ++ Script(OnLoad(onload))
}
override def localShutdown() {
ChatServer ! ClosedConnection(this)
}
- def initGlobalChat = {
- def initEarth = JsRaw("earth = new Earth()").cmd & JsRaw("earth.setId('" + id + "')").cmd
- def showChat = JsCmds.JsShowId("chat")
- def closeSetup = JsCmds.JsHideId("userform")
+ def generateConnectButton = {
+
+ def initGlobalChat = {
+ def initEarth = earth.init & earth.setUserId(id)
+ def showChat = JsCmds.JsShowId("chat")
+ def closeSetup = JsCmds.JsHideId("userform")
- if (this.coords.isDefined) {
ChatServer ! NewConnection(this)
initEarth & showChat & closeSetup
- } else {
- JsCmds.Alert("Please set your location on the map first.")
}
- }
- def userForm = {
- ("#colorpicker" #> SHtml.ajaxText(this.color, str => {
- this.color = str
- JsCmds.Noop
- }) &
- "#userSubmit" #> generateConnectButton)(Templates(List("templates", "userSetup")).openOr(NodeSeq.Empty))
- }
-
- def validations = List((() => this.coords.isDefined,"Please set your location on the map first."))
-
- def getErrors = validations.collect {
- case (validfunc, msg) if !validfunc() => msg
- }
+ def getErrors = validations.collect {
+ case (validfunc, msg) if !validfunc() => msg
+ }
- def generateConnectButton = getErrors match {
- case l if l.isEmpty => SHtml.ajaxButton(Text("Connect"), () => initGlobalChat, "id" -> "userSubmit")
- case l => SHtml.ajaxButton(Text(l.mkString(",")), () => JsCmds.Noop)
+ getErrors match {
+ case l if l.isEmpty => SHtml.ajaxButton(Text("Connect"), () => initGlobalChat, "id" -> "userSubmit")
+ case l => SHtml.ajaxButton(Text(l.mkString(",")), () => JsCmds.Noop)
+ }
}
}
View
4 src/main/scala/code/model/User.scala
@@ -9,6 +9,6 @@ class User {
var color: String = "#FFFFFF"
def colorToHexInt = "0x"+color.replace("#","")
- def latToString = coords.map(_.lat).openOr(0.0f)
- def longToString = coords.map(_.long).openOr(0.0f)
+ def lat = coords.map(_.lat).openOr(0.0)
+ def long = coords.map(_.long).openOr(0.0)
}
View
10 src/main/scala/code/widget/Chat.scala
@@ -0,0 +1,10 @@
+package code.widget
+
+import net.liftweb.http.js.JE.JsRaw
+
+/**
+ * Small scala wrapper around chat window
+ */
+class Chat(domElem : String) {
+ def newMessage(msg : String, color : String) = JsRaw( """$('#"""+domElem+"""').append("<div style='color: """ + color + """;'>"""+msg+"""</div>")""").cmd
+}
View
14 src/main/scala/code/widget/ColorPicker.scala
@@ -0,0 +1,14 @@
+package code.widget
+
+import net.liftweb.http.js.JE.JsRaw
+import net.liftweb.http.js.JsCmd
+import net.liftweb.http.SHtml
+
+/**
+ * Small wrapper around color picker
+ */
+class ColorPicker(domElem : String) {
+ def init = JsRaw( """$("#"""+domElem+"""").colorpicker();""").cmd
+
+ def onChange(oldValue : String, change : String => JsCmd) = SHtml.ajaxText(oldValue ,change)
+}
View
22 src/main/scala/code/widget/Earth.scala
@@ -0,0 +1,22 @@
+package code.widget
+
+import net.liftweb.http.js.JE.JsRaw
+import net.liftweb.util.Helpers
+
+/**
+ * Small scala wrapper around earth.js
+ */
+class Earth {
+
+ private lazy val globalVariableName = "earth_" + Helpers.nextFuncName
+
+ def init = JsRaw(globalVariableName + " = new Earth()").cmd
+
+ def setUserId(id: String) = JsRaw(globalVariableName + ".setId('" + id + "')").cmd
+
+ def createConnection(id: String, lat: Double, long: Double, color: String) = JsRaw(globalVariableName + ".createConnection('" + id + "',{latitude:" + lat + ",longitude:" + long + "}, " + color + ")").cmd
+
+ def removeConnection(id: String) = JsRaw(globalVariableName + ".removeConnection('" + id + "')").cmd
+
+ def newMessage(id: String, msg: String) = JsRaw(globalVariableName + ".newMessage('" + id + "','" + msg.replace("'", "\\'") + "')").cmd
+}
View
43 src/main/scala/code/widget/GoogleMaps.scala
@@ -0,0 +1,43 @@
+package code.widget
+
+import net.liftweb.http.js.JE.JsRaw
+import net.liftweb.util.Helpers
+import net.liftweb.http.SHtml
+import code.util.Coords
+import net.liftweb.common.{Box, Full}
+import net.liftweb.http.js.{JsCmd, JsCmds}
+
+/**
+ * Small scala wrapper around googlemaps.js
+ */
+
+class GoogleMaps(domElem: String) {
+
+ private lazy val globalVariableName = "map_" + Helpers.nextFuncName
+
+ def init = JsRaw(globalVariableName + " = new GoogleMaps('" + domElem + "')").cmd
+
+ def initPosition(coords: Box[Coords]) = coords match {
+ case Full(Coords(lat, long)) => JsRaw(globalVariableName+".setPosition(new google.maps.LatLng(" + lat + "," + long + "))").cmd
+ case _ => JsCmds.Noop
+ }
+
+ def markerDrop(onDrop: (Double, Double) => JsCmd) = {
+
+ def callback(forValue: String, markerFunc: (Double, Double) => JsCmd) = SHtml.ajaxCall(JsRaw(forValue), str => {
+ Helpers.tryo {
+ val splitted = str.split(",")
+ (splitted.head.toDouble, splitted.last.toDouble)
+ } match {
+ case Full((lat, long)) => markerFunc(lat, long)
+ case _ => JsCmds.Noop
+ }
+ })
+
+ JsRaw(globalVariableName + """.registerMarkerCallback(function(event) {
+ var lat = event.latLng.lat();
+ var lng = event.latLng.lng();
+ var value = lat+","+lng;
+ """ + callback("value", onDrop).toJsCmd + """})""").cmd
+ }
+}
View
4 src/main/webapp/index.html
@@ -20,10 +20,6 @@
<script>
//where it all began (Glarus ;-))
var start = {latitude:47.023007,longitude:8.962402}
- //holder for three.js earth object
- var earth;
- //holder for google maps object
- var map;
</script>
</head>
<body>
View
2 src/main/webapp/js/earth.js
@@ -200,7 +200,7 @@ function Earth() {
var message2 = {message : miniSphere2, text: textMesh2, send:false, lastPosition: 0, onEnd : function(fromUser) {
if(fromUser.id == yourId) {
var tc = new THREE.Color(user.color);
-
+ //TODO: this is pretty ugly
var messageElem = document.getElementById("messages")
messageElem.innerHTML += "<div style='color:rgb("+tc.r*255+","+tc.g*255+","+tc.b*255+");'>"+text.replace("<","&lt;").replace(">","&gt;")+"</div>";
messageElem.scrollTop = messageElem.scrollHeight;

0 comments on commit 8bc8b20

Please sign in to comment.