-
Notifications
You must be signed in to change notification settings - Fork 0
/
scripts.js
117 lines (90 loc) · 2.5 KB
/
scripts.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
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
/*
global
localStorage,
*/
import Chat from './hypercore-fetch-chat.js'
const {
urlPrompt,
chatURLInput,
inputForm,
textInput,
historyBox,
messageTemplate,
namePrompt,
chatNameInput,
nameChangeButton,
aboutBox,
aboutButton
} = window
let chat = null
displaySystem('Type a message below to send it to available peers')
if (localStorage.lastURL) {
chatURLInput.value = localStorage.lastURL
}
if (localStorage.username) {
updateName(localStorage.username)
} else {
namePrompt.showModal()
}
urlPrompt.showModal()
aboutButton.addEventListener('click', (e) => {
e.preventDefault(true)
aboutBox.showModal()
})
nameChangeButton.addEventListener('click', () => {
namePrompt.showModal()
})
namePrompt.addEventListener('close', () => {
updateName(chatNameInput.value)
})
urlPrompt.addEventListener('close', async () => {
const appURL = chatURLInput.value
localStorage.lastURL = appURL
displaySystem(`Connecting to ${appURL}`)
chat = new Chat(localStorage.lastURL, {
username: localStorage.username
})
await chat.open()
chat.addEventListener('text', onText)
chat.addEventListener('identity', onIdentity)
function onText (e) {
const { username, fromID, content } = e
const formatted = formatUser(username, fromID)
displayMessage(formatted, content, fromID)
}
function onIdentity (e) {
const { username, fromID } = e
const formatted = formatUser(username, fromID)
displaySystem(`Saw new user ${formatted}`)
}
})
inputForm.addEventListener('submit', (e) => {
e.preventDefault()
const content = textInput.value
textInput.value = ''
chat.sendText(content)
})
urlPrompt.showModal()
function displayMessage (username, text, additional = '') {
console.log(username, text, additional)
const messageElement = messageTemplate.content.cloneNode(true)
messageElement.querySelector('.message-username').innerText = username
messageElement.querySelector('.message-text').innerText = text
if (additional) {
messageElement.querySelector('.message').classList.add(`message-${additional}`)
}
historyBox.appendChild(messageElement)
}
function displaySystem(content) {
displayMessage('System', content, 'system')
}
function updateName (username) {
localStorage.username = username
nameChangeButton.innerText = username
chatNameInput.value = localStorage.username
displaySystem(`Set your username to ${username}`)
if (chat) chat.username = username
}
function formatUser (username, fromID) {
return `${username}@${fromID.slice(0, 8)}`
}