Skip to content

Instantly share code, notes, and snippets.

@Yoric
Created May 26, 2011 14:38
Show Gist options
  • Save Yoric/993277 to your computer and use it in GitHub Desktop.
Save Yoric/993277 to your computer and use it in GitHub Desktop.
chat.opapy
/**
*{1 Network infrastructure}
*/
/**
*The type of messages sent by a client to the chatroom
*/
type message:
author as string //Arbitrary, untrusted, name
text as string //Content entered by the user
/**
*A structure for routing and broadcasting values of type
*[message].
*
*Clients can send values to be broadcasted or register
*callbacks to be informed of the broadcast. Note that
*this routing can work cross-client and cross-server.
*
*For distribution purposes, this network will be
*registered to the network as "mushroom".
*/
room = Network.cloud("mushroom") as Network.network(message)
/**
*Update the user interface in reaction to reception of a message.
*
*This function is meant to be registered with [room] as a callback.
*Its sole role is to display the new message in [#conversation].
*
*@param x The message received from the chatroom
*/
def user_update(x):
line = <div>
<div>{x.author}:</div>
<div>{x.text}</div>
</div>
Dom.transform([#conversation +<- line ])//Note: If we want to change the syntax of actions, now is the right time
Dom.scroll_to_bottom(#conversation)
/**
*Broadcast text to the [room].
*
*Read the contents of [#entry], clear these contents and send
*the message to [room].
*
*@param author The name of the author. Will be included in the
*message broadcasted.
*/
def broadcast(author):
message = new:
author: author
text: Dom.get_value(#entry)
Network.broadcast(message, room)
Dom.clear_value(#entry)
/**
*Build the user interface for a client.
*
*Pick a random author name which will be used throughout the chat.
*
*@return The user interface, ready to be sent by the server to the client
*on connection.
*/
def start():
author = Random.string(8)
html:
<div id=#conversation onready={def *: Network.add_callback(user_update, room)}></div>
<input id=$entry onnewline={def *: broadcast(author)}/>
<div onclick={def *: broadcast(author)}>Send!</div>
/**
*Main entry point.
*
*Construct an application called "Chat" (users will see the name in the title bar),
*embedding statically the contents of directory "resources", using the global
*stylesheet "resources/css.css" and the user interface defined in [start].
*/
server:
Server.one_page_bundle("Chat",
[@static_resource_directory("resources")],
["resources/css.css"], start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment