Find file Copy path
0485941 Jan 6, 2015
1 contributor

Users who have contributed to this file

259 lines (213 sloc) 8.7 KB
# This should only change if the room changes, else chat box will be re-rendering a lot
Handlebars.registerHelper "currentRoom", ->
return unless Meteor.userId()?
# Return room only if it exists in the collection (not deleted)
return ChatRooms.findOne(Session.get("room"), {fields: _id: 1})?._id = ->
# Send room changes to server
# TODO this incurs a high traffic/rendering cost when switching between rooms
# TODO only subscribe to the room if found in the ChatRooms collection
this.autorun ->
roomId = Session.get("room")
# in replay mode, messages will be automatically pushed over by the server
if Router.current().route.getName() is "replay"
console.log "Room change in replay; no action taken."
# request the contents of the chat room otherwise
Session.set("chatRoomReady", false)
Meteor.subscribe("chatstate", roomId, -> Session.set("chatRoomReady", true))
"click .action-room-create": (e) ->
bootbox.prompt "Name the room", (roomName) ->
return unless !!roomName "createChat", roomName, (err, id) ->
return unless id
Session.set "room", id
"click .action-room-leave": ->
# TODO convert this to a method call ... !
# bootbox.confirm "Leave this room?", (value) ->
Session.set("room", undefined) # if value
nameDoc: -> ChatRooms.findOne(""+@, {fields: name: 1})
loaded: -> Session.equals("chatSubReady", true)
availableRooms: ->
selector = if TurkServer.isAdmin() and Session.equals("adminShowDeleted", true) then {}
else { deleted: {$exists: false} }
ChatRooms.find(selector, {sort: {name: 1}}) # For a consistent ordering
active: -> if Session.equals("room", @_id) then "active" else ""
deleted: -> if @deleted then "deleted" else ""
empty: -> @users is 0 =
"click .action-room-enter": (e) ->
unless Meteor.userId()
bootbox.alert "You must be logged in to join chat rooms."
Session.set "room", @_id"chat-join")
"click .action-room-delete": (e) ->
roomId = @_id
bootbox.confirm "This will delete the chat room and its messages. Are you sure?", (res) ->
return unless res # Only if "yes" clicked"deleteChat", roomId) if roomId
# don't select chatroom (above function) -
users: -> ChatUsers.find {}
findUser: -> Meteor.users.findOne @userId
Template.roomHeader.rendered = ->
tmplInst = this
this.autorun ->
# Trigger this whenever title changes - note only name is reactively depended on
# Destroy old editable if it exists
display: ->
success: (response, newValue) ->
roomId = Session.get("room")
return unless roomId "renameChat", roomId, newValue
showEvent = (eventId) ->
Mapper.switchTab 'events' # Make sure we are on the event page
# Set up a scroll event, then trigger a re-render
Mapper.scrollToEvent(eventId) =
"click .tweet-icon.clickme": (e) ->
tweetId = $("tweetid") + "" # Ensure string, not integer
data = Datastream.findOne(tweetId)
return unless data
# Error message if tweet is hidden, or went on a deleted event
if data.hidden or Events.findOne([0])?.deleted
bootbox.alert("That data has been deleted.")
if and > 0
showEvent[0] # Scroll to event
"click .event-icon.clickme": (e) ->
eventId = $("eventid") + ""
event = Events.findOne(eventId)
return unless event
if event.deleted
bootbox.alert("That event has been deleted.")
loaded: -> Session.equals("chatRoomReady", true)
messages: ->
# Multiple chatrooms may be loaded, to save on traffic or for the replay.
# Since we're sorting anyway, filter by room.
ChatMessages.find { room: Session.get("room") },
sort: {timestamp: 1}
# These usernames are nonreactive because find does not use any reactive variables
username: -> Meteor.users.findOne(@userId)?.username || @userId
# If updating the user, also update server notification generations.
userRegex = new RegExp('(^|\\b|\\s)(@[\\w.]+)($|\\b|\\s)','g')
tweetRegex = new RegExp('(^|\\b|\\s)(~[\\d]+)($|\\b|\\s)','g')
eventRegex = new RegExp('(^|\\b|\\s)(#[\\d]+)($|\\b|\\s)','g')
Blaze.toHTML registers reactive dependencies, so chat messages can get
re-rendered with state. However, this can cause excessive CPU usage.
As a result, we use Blaze.toHTML with static data, and use very specific
reactive dependencies below. It has to be reactive, or if the chat loads
before the events/tweets then messages will be empty.
Moving the findOne functions inside the Blaze.With won't make any difference
below as the entire chat message has to be re-rendered anyway.
# TODO: remove ugly spaces added below
userFunc = (_, p1, p2) ->
username = p2.substring(1)
# userPill uses _id, username, and status
user = Meteor.users.findOne(username: username, {fields: {username: 1, status: 1}})
return " " + if user then Blaze.toHTMLWithData(Template.userPill, user) else p2
tweetFunc = (_, p1, p2) ->
tweetNum = parseInt( p2.substring(1) )
# tweetIconClickable only uses _id and num
tweet = Datastream.findOne( {num: tweetNum}, {fields: num: 1} )
return " " + if tweet then Blaze.toHTMLWithData(Template.tweetIconClickable, tweet) else p2
eventFunc = (_, p1, p2) ->
eventNum = parseInt( p2.substring(1) )
# eventIconClickable only uses _id and num
event = Events.findOne( {num: eventNum}, {fields: num: 1} )
return " " + if event then Blaze.toHTMLWithData(Template.eventIconClickable, event) else p2
# Because messages only render when inserted, we can use this to scroll the chat window
Template.messageItem.rendered = ->
# Scroll down whenever anything happens
$messages = $(".messages-body")
$messages.scrollTop $messages[0].scrollHeight
# Replace any matched users, tweets, or events with links
renderText: ->
text = Handlebars._escape(@text)
# No SafeString needed here as long as renderText is unescaped
text = text.replace userRegex, userFunc
text = text.replace tweetRegex, tweetFunc
text = text.replace eventRegex, eventFunc
eventText: ->
username = Meteor.users.findOne(@userId).username
return username + " has " + (if @event is "enter" then "entered" else "left" ) + " the room."
Template.chatInput.rendered = ->
html: true
placement: "top"
trigger: "hover"
content: Blaze.toHTML Template.chatPopover =
submit: (e, tmpl) ->
$msg = $( tmpl.find(".chat-input") )
return unless $msg.val() "sendChat", Session.get("room"), $msg.val() # Server only method
# Auto scroll happens on messageBox render now.."chat-message")
# RegExp syntax below taken from
# We use $where because we need the regex to match on a number!
# This worked before but was removed in 0.7.1:
# However, since it's all on the client, this will result in the same performance.
numericMatcher = (filter) ->
re = new RegExp("^" + filter)
return { $where: -> re.test(@num) }
settings: -> {
position: "top"
limit: 5
rules: [
token: '@'
collection: Meteor.users
field: "username"
template: Template.userPill
token: '~'
collection: Datastream
field: "num"
template: Template.tweetNumbered
# TODO this can select tweets attached to deleted events, but error
# shows up when they are clicked
filter: { hidden: $exists: false }
selector: numericMatcher
token: '#'
collection: Events
field: "num"
template: Template.eventShort
filter: { deleted: $exists: false }
selector: numericMatcher