Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
190 lines (178 loc) · 10.7 KB
/
Copy pathindex.html
File metadata and controls
190 lines (178 loc) · 10.7 KB
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
<!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/bootstrap@5.0.2/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="btn-close" data-bs-dismiss="modal" aria-label="Close"></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/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.13.1.3.min.js"></script>
<script>
(function() {
function makeid(length) { // Used to create new user IDs.
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
const pubnub = new PubNub({ // Set your PubNub keys here.
publishKey: 'demo',
subscribeKey: 'demo',
userId: 'Anon-' + makeid(5)
});
const messagesArea = document.getElementById('messages-area'),
input = document.getElementById('input-box'),
sendButton = document.getElementById('send-button'),
saveButton = document.getElementById('saveOptionsButton'),
nameInput = document.getElementById('nameInput'),
onlineCount = document.getElementById('online-users-count'),
channelName = 'chat-channel',
channel = pubnub.channel(channelName);
class chatControl { // Formats messages and scrolls them into view.
publishMessage(name, msg, timetoken) {
this.show(this.msg(name, msg, 'start', 'primary', timetoken));
}
receiveMessage(name, msg, timetoken) {
this.show(this.msg(name, msg, 'end', 'secondary', timetoken));
}
show(card) {
messagesArea.appendChild(card);
messagesArea.scrollIntoView(false);
}
msg(name, msg, side, style, timetoken) { // Builds a message card. textContent keeps message text from running as HTML.
const card = document.createElement('div');
card.className = `card text-white bg-${style}`;
const body = document.createElement('div');
body.className = 'card-body';
const title = document.createElement('h6');
title.className = `card-subtitle mb-2 text-${side}`;
const nameSpan = document.createElement('span');
nameSpan.textContent = name;
const time = document.createElement('small');
time.textContent = ' - ' + new Date(Math.trunc(Number(timetoken) / 10000)).toLocaleString(); // A timetoken counts 100-nanosecond intervals.
title.append(nameSpan, time);
const text = document.createElement('p');
text.className = `card-text float-${side} msg-text`;
text.textContent = msg;
body.append(title, text);
card.append(body);
return card;
}
}
const chat = new chatControl();
let displayName = localStorage.getItem('chat-display-name') || ''; // The name you send with your messages.
nameInput.value = displayName;
function readMessage(message) { // Messages from steps 2-4 are plain text; from step 5 on they carry a name.
if (message && typeof message === 'object') { // Anyone with the keys can publish, so don't trust the shape.
return { text: String(message.text ?? ''), name: typeof message.name === 'string' ? message.name : '' };
}
return { text: String(message ?? ''), name: '' };
}
const subscription = channel.subscription({ receivePresenceEvents: true }); // Subscribe to receive messages and presence events.
subscription.onMessage = (event) => { // Get new messages.
const { text, name } = readMessage(event.message);
if (event.publisher === pubnub.getUserId()) { // Check who sent the message.
chat.publishMessage('You', text, event.timetoken);
} else {
chat.receiveMessage(name || event.publisher, text, event.timetoken);
}
};
subscription.onPresence = (event) => { // Update the number of online users on join, leave, timeout and interval events.
if (event.action !== 'state-change') onlineCount.textContent = event.occupancy; // state-change events carry no occupancy.
};
window.addEventListener('pagehide', () => { // Leave the channel when the tab closes, so the others' count drops right away.
subscription.unsubscribe();
});
window.addEventListener('pageshow', (event) => { // Back button: the browser restored this page from its cache, so subscribe again.
if (event.persisted) subscription.subscribe();
});
pubnub.addListener({ // Count who is online once the connection to PubNub is up.
status: (statusEvent) => {
if (statusEvent.category === 'PNConnectedCategory') {
updateOccupancy();
}
}
});
subscription.subscribe();
function publishMessage() { // Send messages with PubNub.
const msg = input.value.trim();
input.value = '';
if (msg !== '') {
pubnub.publish({ channel: channelName, message: { text: msg, name: displayName } }) // Send your name with every message.
.catch((error) => console.log(error));
}
}
sendButton.addEventListener('click', () => {
publishMessage();
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { // Enter sends, Shift+Enter adds a new line.
e.preventDefault();
publishMessage();
}
});
function updateOccupancy() { // Ask PubNub how many users are on the channel right now.
pubnub.hereNow({ channels: [channelName] })
.then((response) => {
onlineCount.textContent = response.totalOccupancy;
})
.catch((error) => console.log(error));
}
pubnub.fetchMessages({ channels: [channelName], count: 10 }) // Get the last 10 messages sent in the chat.
.then((response) => {
(response.channels[channelName] || []).forEach((message) => {
const { text, name } = readMessage(message.message);
if (message.uuid === pubnub.getUserId()) { // Check who sent the message.
chat.publishMessage('You', text, message.timetoken);
} else {
chat.receiveMessage(name || message.uuid, text, message.timetoken);
}
});
})
.catch((error) => console.log(error));
saveButton.addEventListener('click', () => { // Save your display name. It goes with every message you send from now on.
displayName = nameInput.value.replace(/[^\p{L}\p{N} ]/gu, '').substring(0, 30); // Letters, digits and spaces, up to 30 characters.
localStorage.setItem('chat-display-name', displayName);
alert('Your username has been updated.');
bootstrap.Modal.getOrCreateInstance(document.getElementById('editNameModal')).hide(); // Close Chat Options.
});
})();
</script>
</body>
</html>