-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.js
302 lines (259 loc) · 8.2 KB
/
index.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
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
import './register-components'
import createSocketIoClient from 'socket.io-client'
import cameraPreview from './camera-preview'
import captureFrames from './capture-frames'
import getFingerprint from './fingerprint'
import NotificationCounter from './notification-counter'
import StoredSet from './stored-set'
import createCharCounter from './char-counter'
import initProgressSpinner from './progress'
import theme from './theme'
import createAbout from './about'
import Tracker from './analytics'
import { PROTOCOL_VERSION } from '../protocol-version'
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/serviceworker.js')
})
}
const io = createSocketIoClient()
const muteSet = new StoredSet('mutes')
const progressSpinner = initProgressSpinner(document.querySelector('.progress'))
const tracker = new Tracker()
const messageList = document.querySelector('#message-list')
messageList.muteSet = muteSet
messageList.tracker = tracker
const possibleEvents = {
transition: 'transitionend',
OTransition: 'oTransitionEnd',
MozTransition: 'transitionend',
WebkitTransition: 'webkitTransitionEnd',
}
let transitionEvent
for (const t in possibleEvents) {
if (document.body.style[t] !== undefined) {
transitionEvent = possibleEvents[t]
break
}
}
let active = 0
io.on('connect', function () {
io.emit('fingerprint', getFingerprint())
io.emit('join', 'mp4')
}).on('disconnect', function () {
active = 0
updateActiveUsers()
})
io.on('protocolVersion', version => {
if (PROTOCOL_VERSION !== version) {
// TODO: display a dialog to refresh
console.log('protocol version mismatch!')
}
})
io.on('userid', function (id) {
messageList.myId = id
})
let isAutoScrolling = true
let autoScrollCalcCallback = null
function calcAutoScroll() {
autoScrollCalcCallback = null
const visibleEnd = window.pageYOffset + window.innerHeight
// the 16px is for some extra slop in this calculation (you can be slightly scrolled up and we
// still autoscroll)
const contentHeight = document.body.clientHeight - 16
isAutoScrolling = visibleEnd > contentHeight
}
document.addEventListener('scroll', () => {
if (!autoScrollCalcCallback) {
autoScrollCalcCallback = requestAnimationFrame(calcAutoScroll)
}
})
let maintainAutoScrollCallback = null
function maintainAutoScroll() {
maintainAutoScrollCallback = null
if (isAutoScrolling) {
// A resize should never move the scroll position away from the bottom of the message list if
// we were scrolled there (really it should always keep the previous last message visible, but
// that's more complex to implement for minimal gain)
window.scrollTo(0, document.body.scrollHeight)
}
}
window.addEventListener('resize', () => {
if (!maintainAutoScrollCallback) {
maintainAutoScrollCallback = requestAnimationFrame(maintainAutoScroll)
}
})
let unreadMessages = 0
let historyComplete = false
io.on('chat', chat => {
const messageAdded = messageList.addMessage(chat, isAutoScrolling)
if (messageAdded) {
hideEmptyState()
}
if (historyComplete && messageAdded && document.hidden) {
unreadMessages++
updateNotificationCount()
}
})
.on('active', numActive => {
active = numActive
updateActiveUsers()
})
.on('historyComplete', () => {
if (!historyComplete) {
historyComplete = true
if (!messageList.hasMessages()) {
showEmptyState()
}
}
})
function updateActiveUsers() {
const elem = document.querySelector('#active-users')
if (active > 0) {
elem.innerHTML = '' + active
elem.title = `${active} active users`
} else {
elem.innerHTML = '?'
elem.title = 'not connected'
}
}
document.querySelector('#options-dropdown').actions = {
unmute: () => {
muteSet.clear()
tracker.onUnmute()
},
changeTheme: () => {
const newTheme = theme.isDark() ? 'light' : 'dark'
theme.setTheme(newTheme)
tracker.onChangeTheme(newTheme)
},
about: () => {
showDialog(createAbout())
tracker.onShowAbout()
},
}
const updateTheme = newTheme => {
let curTheme
if (document.body.classList.contains('dark')) {
curTheme = 'dark'
document.body.classList.remove('dark')
} else if (document.body.classList.contains('light')) {
curTheme = 'light'
document.body.classList.remove('light')
} else {
curTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
const otherTheme = (newTheme || curTheme) === 'light' ? 'dark' : 'light'
document.querySelector('#change-theme').textContent = `Use ${otherTheme} theme`
if ((newTheme && newTheme === 'light') || newTheme === 'dark') {
document.body.classList.add(newTheme)
}
}
theme.on('themeChange', updateTheme)
updateTheme(theme.getTheme())
const messageInput = document.querySelector('#message')
const sendButton = document.querySelector('#send')
createCharCounter(messageInput, document.querySelector('#char-counter'), 250)
document.querySelector('form').addEventListener('submit', function (event) {
event.preventDefault()
const messageText = messageInput.value
messageInput.readOnly = true
sendButton.setAttribute('disabled', true)
progressSpinner.setValue(0).show()
captureFrames(
document.querySelector('#preview'),
{
format: 'image/jpeg',
width: 400,
height: 300,
},
function (err, frames) {
setTimeout(() => {
progressSpinner.hide()
setTimeout(() => progressSpinner.setValue(0), 400)
}, 400)
messageInput.value = ''
messageInput.readOnly = false
sendButton.removeAttribute('disabled')
if (err) {
// TODO(tec27): show to user
tracker.onMessageCaptureError(err.message)
console.error(err)
return
}
const formData = new FormData()
formData.append('fingerprint', getFingerprint())
formData.append('message', messageText)
formData.append('format', 'image/jpeg')
for (const frame of frames) {
formData.append('frames', frame)
}
const sendTime = Date.now()
fetch('/message', {
method: 'POST',
body: formData,
})
.then(res => {
if (!res.ok) {
throw new Error(`Failed to post message: ${res.status} ${res.statusText}`)
}
const timing = Date.now() - sendTime
tracker.onMessageSent(timing)
})
.catch(err => {
// TODO(tec27): display to user
const timing = Date.now() - sendTime
console.error('Error: ' + err)
tracker.onMessageSendError('' + err, timing)
})
// fire 'change'
const event = document.createEvent('HTMLEvents')
event.initEvent('change', false, true)
messageInput.dispatchEvent(event)
},
).on('progress', percentDone => progressSpinner.setValue(percentDone))
})
cameraPreview(document.querySelector('#preview').parentNode, tracker)
document.addEventListener('visibilitychange', () => {
document.body.classList.toggle('backgrounded', document.hidden)
if (!document.hidden) {
unreadMessages = 0
updateNotificationCount()
}
})
const notificationCounter = new NotificationCounter()
function updateNotificationCount() {
if (!unreadMessages) {
notificationCounter.clear()
} else {
notificationCounter.setCount(unreadMessages)
}
}
function showDialog({ scrim, container, dialog }) {
document.body.appendChild(scrim)
document.body.appendChild(container)
setTimeout(() => {
scrim.classList.remove('entering')
dialog.classList.remove('entering')
}, 15)
const clickListener = e => {
if (e.target !== container) return
container.removeEventListener('click', clickListener)
// remove the dialog
scrim.classList.add('will-leave')
dialog.classList.add('will-leave')
setTimeout(() => {
scrim.classList.add('leaving')
dialog.classList.add('leaving')
scrim.addEventListener(transitionEvent, () => document.body.removeChild(scrim))
dialog.addEventListener(transitionEvent, () => document.body.removeChild(container))
}, 15)
}
container.addEventListener('click', clickListener)
}
function showEmptyState() {
document.body.classList.add('no-messages')
}
function hideEmptyState() {
document.body.classList.remove('no-messages')
}