-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchat1.js
91 lines (79 loc) · 2.39 KB
/
chat1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
Messages = new Mongo.Collection("msgs");
Meteor.methods({
sendMessage: function (message) {
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
Messages.insert({
messageText: message,
createdAt: new Date(),
username: Meteor.user().username // <-add real username
});
}
});
if (Meteor.isServer) {
// This code only runs on the server
Meteor.publish("messages", function () {
return Messages.find();
});
}
var autoScrollingIsActive = false;
var thereAreUnreadMessages = new ReactiveVar(false);
scrollToBottom = function scrollToBottom (duration) {
var messageWindow = $(".message-window");
var scrollHeight = messageWindow.prop("scrollHeight");
messageWindow.stop().animate({scrollTop: scrollHeight}, duration || 0);
};
if (Meteor.isClient) {
// This code only runs on the client
Meteor.subscribe("messages", {
onReady: function () {
scrollToBottom();
autoScrollingIsActive = true;
}
});
Template.body.helpers({
recentMessages: function () {
return Messages.find({}, {sort: {createdAt: 1}});
},
thereAreUnreadMessages: function () {
return thereAreUnreadMessages.get();
}
});
Template.message.onRendered(function () {
if (autoScrollingIsActive) {
scrollToBottom(250);
} else {
if (Meteor.user() && this.data.username !== Meteor.user().username) {
thereAreUnreadMessages.set(true);
}
}
});
Template.body.events({
"submit .new-message": function (event) {
var text = event.target.text.value;
Meteor.call("sendMessage", text);
scrollToBottom(250);
event.target.text.value = "";
event.preventDefault();
},
"scroll .message-window": function () {
var howClose = 80; // # pixels leeway to be considered "at Bottom"
var messageWindow = $(".message-window");
var scrollHeight = messageWindow.prop("scrollHeight");
var scrollBottom = messageWindow.prop("scrollTop") + messageWindow.height();
var atBottom = scrollBottom > (scrollHeight - howClose);
autoScrollingIsActive = atBottom ? true : false;
if (atBottom) { // <--new
thereAreUnreadMessages.set(false);
}
},
"click .more-messages": function () {
scrollToBottom(500);
thereAreUnreadMessages.set(false);
}
});
Accounts.ui.config({
passwordSignupFields: "USERNAME_ONLY"
});
}