-
Notifications
You must be signed in to change notification settings - Fork 0
/
peerjs-connection.js
79 lines (66 loc) · 2.09 KB
/
peerjs-connection.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
let peer
let conn
function setupPeerJS() {
peer = new Peer()
peer.on('open', (id) => {
const statusElement = document.getElementById('status');
statusElement.textContent = id
document.getElementById('connectBtn').disabled = false
statusElement.style.cursor = 'pointer';
statusElement.title = 'Click to copy ID';
statusElement.addEventListener('click', copyPeerIdToClipboard);
})
peer.on('connection', (connection) => {
conn = connection
setupConnection()
})
}
function copyPeerIdToClipboard() {
const peerId = document.getElementById('status').textContent;
navigator.clipboard.writeText(peerId).then(() => {
alert('Peer ID copied to clipboard!');
}).catch(err => {
console.error('Failed to copy: ', err);
});
}
function connect() {
const peerId = document.getElementById('connectionBox').value
conn = peer.connect(peerId)
setupConnection()
}
function setupConnection() {
conn.on('open', () => {
updateConnectionStatus('Connected!')
document.getElementById('connectBtn').disabled = true
document.getElementById('connectionBox').value = ''
})
conn.on('data', (data) => {
receivePineapple(data.xPercent, data.yPercent)
})
conn.on('close', () => {
updateConnectionStatus('Disconnected')
document.getElementById('connectBtn').disabled = false
})
}
function updateConnectionStatus(status) {
const statusElement = document.getElementById('status');
statusElement.textContent = status
if (status === 'Connected!') {
statusElement.style.color = 'green'
statusElement.style.cursor = 'default';
statusElement.title = '';
statusElement.removeEventListener('click', copyPeerIdToClipboard);
} else {
statusElement.style.color = 'red'
}
}
function sendPineapplePosition(xPercent, yPercent) {
if (conn && conn.open) {
conn.send({ xPercent, yPercent })
}
}
document.getElementById('connectBtn').addEventListener('click', connect)
document.getElementById('connectionBox').addEventListener('input', function () {
document.getElementById('connectBtn').disabled = this.value.length === 0
})
setupPeerJS()