-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
306 lines (272 loc) · 8.74 KB
/
index.html
File metadata and controls
306 lines (272 loc) · 8.74 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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#2196F1" />
<title>Korona P2P Chat</title>
<style>
html, body {
margin: 0;
padding: 0;
}
code {
color: #f50;
/* border: 1px solid #f50;
padding: 2px 6px;
border-radius: 4px;*/
}
body {
display: flex;
flex-direction: column;
background-color: #222;
color: #fff;
font-family: Arial;
height: 100%;
}
#shareable-link {
cursor: pointer;
}
#top-panel {
padding: 8px;
}
#top-panel p {
margin: 2px;
}
#chat-panel {
flex: 1;
padding: 0 8px;
overflow-y: auto;
}
#bottom-panel {
padding: 8px;
display: flex;
flex-direction: row;
}
#message-input {
flex: 1;
padding: 8px;
margin-right: 4px;
}
#send-button {
cursor: pointer;
}
.message-container {
display: flex;
flex-direction: row;
align-items: center;
margin: 8px 0;
overflow-y: auto;
overflow-x: hidden;
}
code.sender {
margin-right: 8px;
}
p.message {
margin: 0;
word-break: break-all;
}
</style>
</head>
<body>
<div id="top-panel">
<p>Your id is <code id="peer-id">connecting...</code>, currently <code id="peers-number">0</code> peer(s) online</code></p>
<p>
Copy <code id="shareable-link" onclick="selectText(this.id)">connecting...</code> to your friends to let
them join your chat
</p>
</div>
<div id="chat-panel">
</div>
<div id="bottom-panel">
<input id="message-input" placeholder="Please wait..." autofocus disabled />
<button id="send-button">Send</button>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/peerjs@1.4.6/dist/peerjs.min.js"></script>
<script src="./build/bundle.js"></script>
<script>
function randomId() {
return Math.random()
.toString(36)
.substr(2, 9);
}
function copyToClipboard() {
const copyText = document.getElementById("shareable-link").innerText;
const textArea = document.createElement("textarea");
textArea.value = copyText;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
textArea.remove();
}
class RandomColorGenerator {
constructor() {
this.cache = {};
}
hashCode(s) {
let n = s.split("").reduce(function(a, b) {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
n = Math.abs(n);
const x = "0." + n.toString();
return parseFloat(x);
}
generateColor(key) {
if (key in this.cache) {
return this.cache[key];
} else {
const color =
"#" +
(((1 << 24) * /* Math.random() */ this.hashCode(key)) | 0).toString(16);
this.cache[key] = color;
return color;
}
}
}
function selectText(id){
var sel, range;
var el = document.getElementById(id); //get element id
if (window.getSelection && document.createRange) { //Browser compatibility
sel = window.getSelection();
if(sel.toString() == ''){ //no text selection
window.setTimeout(function(){
range = document.createRange(); //range object
range.selectNodeContents(el); //sets Range
sel.removeAllRanges(); //remove all ranges from selection
sel.addRange(range);//add Range to a Selection.
},1);
}
}else if (document.selection) { //older ie
sel = document.selection.createRange();
if(sel.text == ''){ //no text selection
range = document.body.createTextRange();//Creates TextRange object
range.moveToElementText(el);//sets Range
range.select(); //make selection.
}
}
copyToClipboard()
}
async function main() {
const randomColorGenerator = new RandomColorGenerator();
const maxPeers = 5;
const peerId = randomId();
const chatMessages = [];
const chatPanel = document.getElementById("chat-panel");
const messageInput = document.getElementById("message-input");
const sendButton = document.getElementById("send-button");
const appendMessageElement = (messageID, peerId, message)=> {
console.log("* appendMessageElement: ", messageID, peerId, message);
if (chatMessages.find(m => m.id === messageID)) { // Message already exists
return;
}
chatMessages.push({id: messageID, peerId: peerId, message: message});
const messageContainer = document.createElement("div");
messageContainer.classList.add("message-container")
const sender = document.createElement("code");
sender.classList.add("sender")
sender.innerText = peerId
sender.style.color = randomColorGenerator.generateColor(peerId);
const messageElement = document.createElement("p");
messageElement.classList.add("message");
messageElement.innerText = message;
messageContainer.appendChild(sender);
messageContainer.appendChild(messageElement);
chatPanel.appendChild(messageContainer)
chatPanel.scrollTop = chatPanel.scrollHeight * 2;
}
const targetRoomIdMatch = location.search.match(/roomId\=(.+)$/);
let roomId = "";
if (targetRoomIdMatch) {
roomId = targetRoomIdMatch[1];
}
const peer = new Korona.Korona({
peerId: peerId,
roomId: roomId,
peerJSOptions: {
// debug: 2,
// host: "crossnote.app",
// path: "/peer",
// secure: true,
},
maxPeers: maxPeers,
});
peer.on("open", async(peerId)=> {
document.getElementById("peer-id").innerText = peerId;
document.getElementById("peer-id").style.color = randomColorGenerator.generateColor(peerId);
document.getElementById("shareable-link").innerText =
location.protocol + "//" + location.host + location.pathname + "?peerId=" + peer.peer.id;
messageInput.placeholder = "Enter your message here"
messageInput.disabled = false;
const sendMessage = ()=> {
const value = messageInput.value.trim();
if (!value.length) {
messageInput.value = "";
return;
}
messageInput.value = "";
messageInput.focus();
// broadcast
const messageID = randomId();
peer.broadcast({
type: "SendMessage",
id: messageID,
peerId: peerId,
message: value
});
// create dom element
appendMessageElement(messageID, peerId, value);
}
messageInput.addEventListener("keydown", (event)=> {
if (event.which === 13) {
sendMessage();
}
})
sendButton.addEventListener("click", ()=> {
sendMessage();
})
const targetPeerIDMatch = location.search.match(/peerId\=(.+)$/);
if (targetPeerIDMatch) {
const targetPeerID = targetPeerIDMatch[1];
peer.requestConnection(targetPeerID);
}
peer.on("peerJoined", async (peerId) => {
console.log("peer joined: ", peerId);
document.getElementById("peers-number").innerText = peer.network.size;
})
peer.on("peerLeft", async (peerId) => {
console.log("peer left: ", peerId);
document.getElementById("peers-number").innerText = peer.network.size;
})
peer.on("data", (data)=> {
console.log("received data: ", data)
if (data.type === "SendMessage") {
appendMessageElement(data.id, data.peerId, data.message);
} else if (data.type === "ChatMessages") {
const chatMessages = data.messages;
chatMessages.forEach((chatMessage)=> {
appendMessageElement(chatMessage.id, chatMessage.peerId, chatMessage.message);
})
}
})
peer.on("disconnected", ()=> {
console.log("Disconnected");
})
peer.on("close", ()=> {
console.log("Close")
})
peer.on("pubsubHostChanged", ()=> {
console.log("pubsubHostChanged")
})
peer.on("sync", async (send)=> {
send({
type: "ChatMessages",
messages: chatMessages,
})
})
})
window["peer"] = peer;
}
main();
</script>
</html>