-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
219 lines (209 loc) · 11.4 KB
/
index.html
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="icon.png">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<title>JavaScript Chat</title>
</head>
<body>
<div class="modal" id="editNameModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Chat Options</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p>Change your display name here.</p>
<input class="form-control" id="nameInput" placeholder="New Display Name">
</div>
<div class="modal-footer">
<button type="button" data-bs-dismiss="modal" class="btn btn-secondary">Cancel</button>
<button id="saveOptionsButton" type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
<div class="msg-group" id="messages-area">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<button data-bs-toggle="modal" data-bs-target="#editNameModal" class="btn btn-secondary input-btn" type="button">Chat Options</button>
</div>
<textarea id="input-box" class="form-control" rows="1"></textarea>
<div class="input-group-append">
<button id="send-button" class="btn btn-primary input-btn" type="button">Send Message</button>
</div>
</div>
<span class="badge bg-primary online-users-label">Online Users: <span id="online-users-count">NA</span></span>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.7.1.2.min.js"></script>
<script>
(function() {
function makeid(length) { // Used to create new user ids
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
var pubnub = new PubNub({ // Set your PubNub keys here
publishKey: 'demo',
subscribeKey: 'demo',
uuid: 'Anon-' + makeid(5)
});
var messagesArea = document.getElementById('messages-area'),
input = document.getElementById('input-box'),
sendButton = document.getElementById('send-button'),
saveButton = document.getElementById('saveOptionsButton'),
nameInput = document.getElementById('nameInput'),
channel = 'chat-channel'
usernames = [];
class chatControl { // Formats messages and scrolls into view.
publishMessage(uuid, msg) {
if (msg != pubnub.getUUID()+"NEWUSERNAME"){
messagesArea.innerHTML = messagesArea.innerHTML + this.msg(uuid, "You", msg, 'start', 'primary');
messagesArea.scrollIntoView(false);
}
}
receiveMessage(uuid, msg) {
if (msg == uuid+"NEWUSERNAME"){
pubnub.objects.getUUIDMetadata({ // Recheck metadata for new username and update previous messages.
uuid: uuid,
},
function (status, response) {
if (response) {
usernames[uuid] = response.data.name; // Set username from metadata.
for(var i = 0; i < document.getElementsByClassName('display-'+response.data.id).length; i++){
document.getElementsByClassName('display-'+response.data.id)[i].innerText = response.data.name;
}
}
}
);
} else {
if (!usernames[uuid]) { // Get the username if not stored.
usernames[uuid] = uuid; // If username not set then set to the UUID.
pubnub.objects.getUUIDMetadata({
uuid: uuid,
},
function (status, response) {
if (response) {
usernames[uuid] = response.data.name; // Set username from metadata.
for(var i = 0; i < document.getElementsByClassName('display-'+response.data.id).length; i++){
document.getElementsByClassName('display-'+response.data.id)[i].innerText = response.data.name;
}
}
}
);
}
messagesArea.innerHTML = messagesArea.innerHTML + this.msg(uuid, usernames[uuid], msg, 'end', 'secondary');
messagesArea.scrollIntoView(false);
}
}
msg(uuid, name, msg, side, style) {
var msgTemp = `
<div class="card text-white bg-${style}">
<div class="card-body">
<h6 class="card-subtitle mb-2 text-${side}"><span class="display-${uuid}">${name}<span></h6>
<p class="card-text float-${side}">${msg}</p>
</div>
</div>
`;
return msgTemp;
}
}
var chat = new chatControl();
pubnub.addListener({ // Get new messages.
message: function(msg) {
// console.log(msg);
if (msg.publisher == pubnub.getUUID()) { // Check who sent the message.
chat.publishMessage('You', msg.message);
} else {
chat.receiveMessage(msg.publisher, msg.message);
}
},
presence: (presenceEvent) => { // Update the number of online members.
document.getElementById("online-users-count").innerHTML = presenceEvent.occupancy;
}
});
pubnub.subscribe({ // Subscribe to wait for messages
channels: [channel]
});
function publishMessage() { // Send messages with PubNub.
var msg = input.value.trim().replace(/(?:\r\n|\r|\n)/g, '<br>'); // Format message.
input.value = '';
if (msg != '') {
var publishConfig = {
channel: channel,
message: msg
};
pubnub.publish(publishConfig, function(status, response) { // Publish message to current channel.
// console.log(status, response);
});
}
};
sendButton.addEventListener("click", function(e) {
publishMessage();
});
input.addEventListener('keyup', function(e) {
if ((e.keyCode || e.charCode) === 13) {
publishMessage();
}
});
pubnub.hereNow({ // Update the number of online members.
channels: [channel],
}).then((response) => {
document.getElementById("online-users-count").innerHTML = response.totalOccupancy;
}).catch((error) => {
console.log(error)
});
pubnub.fetchMessages( // Get the last 10 messages sent in the chat.
{
channels: [channel],
count: 10,
},
function (status, response) {
if (response.channels[channel] && channel in response.channels) {
response.channels[channel].forEach((message) => {
// console.log(message);
if (message.uuid == pubnub.getUUID()) { // Check who sent the message.
chat.publishMessage('You', message.message);
} else {
chat.receiveMessage(message.uuid, message.message);
}
});
}
}
);
saveButton.addEventListener("click", function(e) { // Save new username
username = nameInput.value.replace(/[^a-zA-Z0-9 ]/g, '').substring(0, 30);
pubnub.objects.setUUIDMetadata({
data: {
name: username
}
})
.then((resp) => {
alert("Your username has been updated.");
var publishConfig = { // Send a message to force username to update on other clients.
channel: channel,
message: pubnub.getUUID() + "NEWUSERNAME"
};
pubnub.publish(publishConfig, function(status, response) { // Publish message to current channel.
// console.log(status, response);
});
// console.log(resp);
})
.catch((error) => {
alert("Your username was not updated. See console for details.");
console.log(err);
});
});
})();
</script>
</body>
</html>