Skip to content

Instantly share code, notes, and snippets.

@Yoric
Created May 26, 2011 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yoric/993179 to your computer and use it in GitHub Desktop.
Save Yoric/993179 to your computer and use it in GitHub Desktop.
chat.opajs
/**
* {1 Network infrastructure}
*/
/**
* The type of messages sent by a client to the chatroom
*/
type message = {author: string /**Arbitrary, untrusted, name*/
,text: 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".
*/
Network.network(message) room = Network.cloud("mushroom")
/**
* {1 User interface}
*/
/**
* 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
*/
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.
*/
broadcast(author){
Network.broadcast({~author, text:Dom.get_value(#entry)}, 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.
*/
start() {
author = Random.string(8);
<div id=#conversation
onready={ * -> Network.add_callback(user_update, room) }></div>
<input id=#entry onnewline={ * -> broadcast(author)} />
<div class="button" onclick={ * -> broadcast(author)} >Send!</div>
}
/**
* {1 Application}
*/
/**
* 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].
*/
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