-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_util.go
559 lines (464 loc) · 14.5 KB
/
js_util.go
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//go:build js && wasm
package config
import (
"encoding/json"
"fmt"
"io"
"net/http"
"slices"
"syscall/js"
"time"
)
// AddEventListener is a function that adds an event listener to the document.
func AddEventListener(event string, listener any) {
document.Call("addEventListener", event, listener)
}
// AddEventListenerToCanvas is a function that adds an event listener to the document.
func AddEventListenerToCanvas(event string, listener any) {
canvasObject.Call("addEventListener", event, listener)
}
// CanvasBoundingBox returns the bounding box of the document.
func CanvasBoundingBox() dimensions {
box := canvasObject.Call("getBoundingClientRect")
dim := dimensions{
BoxLeft: box.Get("left").Float(),
BoxTop: box.Get("top").Float(),
BoxRight: box.Get("right").Float(),
BoxBottom: box.Get("bottom").Float(),
BoxWidth: box.Get("width").Float(),
BoxHeight: box.Get("height").Float(),
OriginalWidth: originalWidth,
OriginalHeight: originalHeight,
}
dim.ScaleWidth = dim.BoxWidth / dim.OriginalWidth
dim.ScaleHeight = dim.BoxHeight / dim.OriginalHeight
return dim
}
// ClearBackground is a function that clears the invisible document.
func ClearBackground() {
invisibleCtx.Call("clearRect", 0, 0, invisibleCanvas.Get("width"), invisibleCanvas.Get("height"))
}
// ClearCanvas is a function that clears the document.
func ClearCanvas() {
canvasObjectContext.Call("clearRect", 0, 0, canvasObject.Get("width"), canvasObject.Get("height"))
}
// ConvertArrayToSlice is a function that converts an array to a slice.
func ConvertArrayToSlice(array js.Value) []any {
length := array.Length()
result := make([]any, length)
for i := 0; i < length; i++ {
element := array.Index(i)
switch element.Type() {
case js.TypeObject:
if element.InstanceOf(js.Global().Get("Array")) {
result[i] = ConvertArrayToSlice(element)
} else {
result[i] = ConvertObjectToMap(element)
}
case js.TypeString:
result[i] = element.String()
case js.TypeNumber:
result[i] = element.Float()
case js.TypeBoolean:
result[i] = element.Bool()
case js.TypeNull, js.TypeUndefined:
result[i] = nil
default:
result[i] = element
}
}
return result
}
// ConvertObjectToMap is a function that converts an object to a map.
func ConvertObjectToMap(obj js.Value) map[string]any {
result := make(map[string]any)
keys := GlobalGet("Object").Call("keys", obj)
for i := 0; i < keys.Length(); i++ {
key := keys.Index(i).String()
value := obj.Get(key)
switch value.Type() {
case js.TypeObject:
if value.InstanceOf(GlobalGet("Array")) {
result[key] = ConvertArrayToSlice(value)
} else {
result[key] = ConvertObjectToMap(value)
}
case js.TypeString:
result[key] = value.String()
case js.TypeNumber:
result[key] = value.Float()
case js.TypeBoolean:
result[key] = value.Bool()
case js.TypeNull, js.TypeUndefined:
result[key] = nil
default:
result[key] = value
}
}
return result
}
// Getenv is a function that returns the value of the environment variable key.
func Getenv(key string) string {
got := GlobalGet(goEnv).Get(key)
if !got.Truthy() {
return ""
}
return got.String()
}
// GetScores is a function that returns the scores.
func GetScores(top int) (scores []score) {
scoreBoardMutex.RLock()
defer scoreBoardMutex.RUnlock()
for i := 0; i < top && i < len(scoreBoard); i++ {
scores = append(scores, scoreBoard[i])
}
return
}
// GlobalCall is a function that calls the global function name with the specified arguments.
func GlobalCall(name string, args ...any) js.Value {
return js.Global().Call(name, args...)
}
// GlobalGet is a function that returns the global value of key.
func GlobalGet(key string) js.Value {
return js.Global().Get(key)
}
// GlobalSet is a function that sets the global value of key to value.
func GlobalSet(key string, value any) {
switch value := value.(type) {
case js.Value:
js.Global().Set(key, value)
default:
js.Global().Set(key, js.ValueOf(value))
}
}
// IsPlaying is a function that returns true if the audio track is playing.
func IsPlaying(name string) bool {
audioPlayersMutex.RLock()
player, playerOk := audioPlayers[name]
audioPlayersMutex.RUnlock()
if playerOk && player.source.Truthy() {
return true
}
return false
}
// IsTouchDevice is a function that returns true if the device is a touch device.
func IsTouchDevice() bool {
navigator := GlobalGet("navigator")
switch {
case window.Call("hasOwnProperty", "ontouchstart").Bool():
return true
case navigator.Truthy():
if maxTouchPoints := navigator.Get("maxTouchPoints"); maxTouchPoints.Truthy() && maxTouchPoints.Int() > 0 {
return true
}
if msMaxTouchPoints := navigator.Get("msMaxTouchPoints"); msMaxTouchPoints.Truthy() && msMaxTouchPoints.Int() > 0 {
return true
}
}
return false
}
// LoadAudio is a function that loads an audio file.
func LoadAudio(name string) ([]byte, error) {
protocol := windowLocation.Get("protocol").String()
hostname := windowLocation.Get("hostname").String()
port := windowLocation.Get("port").String()
url := fmt.Sprintf("%s//%s:%s/audio/%s", protocol, hostname, port, name)
if port == "" {
url = fmt.Sprintf("%s//%s/audio/%s", protocol, hostname, name)
}
response, err := http.Get(url)
if err != nil {
return nil, err
}
defer response.Body.Close()
raw, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
return raw, nil
}
// Log is a function that logs a message.
func Log(msg string) {
console.Call("log", msg)
}
// LogError is a function that logs an error.
func LogError(err error) {
if err != nil {
console.Call("error", err.Error())
}
}
// MakeObject is a function that returns a new object with the specified key-value pairs.
func MakeObject(m map[string]any) js.Value {
obj := NewInstance("Object")
for key, value := range m {
obj.Set(key, value)
}
return obj
}
// NewInstance is a function that returns a new instance of the type with the specified arguments.
func NewInstance(typ string, args ...any) js.Value {
return GlobalGet(typ).New(args...)
}
// PlayAudio is a function that plays an audio track.
func PlayAudio(name string, loop bool) {
if !*Config.Control.AudioEnabled {
return
}
// Reinitialize the audio context if it is not initialized
if !audioCtx.Truthy() {
audioCtx = getAudioContext()
if !audioCtx.Truthy() {
LogError(fmt.Errorf("failed to initialize audio context"))
return
}
}
audioPlayersMutex.RLock()
player, playerOk := audioPlayers[name]
audioPlayersMutex.RUnlock()
if playerOk && player.source.Truthy() {
if Config.Control.Debug.Get() {
Log(fmt.Sprintf("Audio source already playing: %s", name))
}
return
}
audioTracksMutex.RLock()
track, trackOk := audioTracks[name]
audioTracksMutex.RUnlock()
if !trackOk {
raw, err := LoadAudio(name)
if err != nil {
LogError(err)
return
}
audioTracksMutex.Lock()
audioTracks[name], track = raw, raw
audioTracksMutex.Unlock()
}
buffer := NewInstance("Uint8Array", len(track))
js.CopyBytesToJS(buffer, track)
audioBufferPromise := audioCtx.Call("decodeAudioData", buffer.Get("buffer"))
then := js.FuncOf(func(_ js.Value, p []js.Value) any {
player.source = audioCtx.Call("createBufferSource")
player.source.Set("buffer", p[0])
player.source.Call("connect", audioCtx.Get("destination"))
player.endedCallback = js.FuncOf(func(_ js.Value, _ []js.Value) any {
audioPlayersMutex.Lock()
audioPlayers[name] = audioPlayer{
endedCallback: player.endedCallback,
source: js.Null(),
startTime: 0,
}
audioPlayersMutex.Unlock()
if loop {
defer PlayAudio(name, loop)
}
return nil
})
player.source.Call("addEventListener", "ended", player.endedCallback)
audioPlayersMutex.Lock()
audioPlayers[name] = player
audioPlayersMutex.Unlock()
if Config.Control.Debug.Get() {
Log(fmt.Sprintf("Playing audio source: %s", name))
}
player.source.Call("start", js.ValueOf(0), js.ValueOf(player.startTime))
return nil
})
catch := js.FuncOf(func(_ js.Value, p []js.Value) any {
message := p[0].Get("message").String()
stack := p[0].Get("stack").String()
LogError(fmt.Errorf("failed to decode audio data: %s\n%s\n", message, stack))
return nil
})
audioBufferPromise.Call("then", then).Call("catch", catch)
}
// SaveScores is a function that saves the score board persistently.
func SaveScores() {
scoreBoardMutex.RLock()
serialized, err := json.Marshal(scoreBoard)
scoreBoardMutex.RUnlock()
if err != nil {
LogError(fmt.Errorf("failed to serialize score board: %v", err))
return
}
// Save the score board
SendMessage(Execute(Config.MessageBox.Messages.WaitForScoreBoardUpdate), false, false)
scoreBoardMutex.Lock()
GlobalCall("fetch", "scores.db", MakeObject(map[string]any{
"method": http.MethodPut,
"headers": MakeObject(map[string]any{"Content-Type": "application/json"}),
"body": string(serialized),
})).Call("then", js.FuncOf(func(_ js.Value, p []js.Value) any {
defer scoreBoardMutex.Unlock()
if !p[0].Get("ok").Bool() {
return p[0].Call("text").Call("then", js.FuncOf(func(_ js.Value, p []js.Value) any {
LogError(fmt.Errorf("server responded with error: %s", p[0].String()))
return nil
}))
}
// Send success message
SendMessage(Execute(Config.MessageBox.Messages.ScoreBoardUpdated), false, false)
return nil
})).Call("catch", js.FuncOf(func(_ js.Value, p []js.Value) any {
defer scoreBoardMutex.Unlock()
LogError(fmt.Errorf("failed to save score board: %s", p[0].String()))
return nil
}))
}
// SendInfoMessage sends a message to the message box.
func SendMessage(msg string, reset, event logEvent) {
channel := event.Channel()
channelBtn := event.ChannelButton()
if reset {
// Reset the content, keeping only the new message
channel.Set("innerHTML", msg)
} else {
// Create a DocumentFragment
fragment := document.Call("createDocumentFragment")
// Create a temporary container element
div := document.Call("createElement", "div")
div.Set("innerHTML", msg)
// Move all children from the temporary container to the fragment
fragment.Call("appendChild", div)
// Append the fragment to the channel, minimizing DOM manipulation
channel.Call("appendChild", fragment)
// Limit the number of messages in the DOM
for channel.Get("children").Length() > Config.MessageBox.ChannelBufferSize {
channel.Call("removeChild", channel.Get("firstChild"))
}
}
// Scroll to the beginning of the newly added message
channel.Get("lastChild").Call("scrollIntoView", MakeObject(map[string]any{
"block": "start",
"behavior": "smooth",
}))
if channelBtn.Get("classList").Call("contains", tabActiveClass).Bool() {
return // Already active, nothing to do
}
// Flash the channel
channelBtn.Get("classList").Call("add", tabFlashClass)
channelBtn.Call("addEventListener", "animationend", js.FuncOf(func(this js.Value, _ []js.Value) any {
this.Get("classList").Call("remove", tabFlashClass)
if !event { // If not event log, activate the tab
this.Get("classList").Call("add", tabActiveClass)
this.Call("click")
}
return nil
}), js.ValueOf(map[string]any{"once": true}))
}
// SendMessageThrottled sends a message to the message box with a cooldown.
func SendMessageThrottled(msg string, reset, event logEvent, cooldown time.Duration) {
if !lastLogSentTime.IsZero() && time.Since(lastLogSentTime) < cooldown {
return
}
SendMessage(msg, reset, event)
lastLogSentTime = time.Now()
}
// Setenv is a function that sets the environment variable key to value.
func Setenv(key, value string) {
environ := GlobalGet(goEnv)
environ.Set(key, value)
GlobalSet(goEnv, environ)
}
// SetScore is a function that sets the score.
func SetScore(name string, newScore int) (rank int) {
scoreBoardMutex.Lock()
// Update the score board
var exists bool
for i, s := range scoreBoard {
if s.Name == name {
if newScore <= s.Score {
scoreBoardMutex.Unlock()
return len(scoreBoard) + 1
}
scoreBoard[i].Score = newScore
exists = true
break
}
}
// Add the score if it does not exist
if !exists {
scoreBoard = append(scoreBoard, score{Name: name, Score: newScore})
}
// Sort the score board
slices.SortStableFunc(scoreBoard, scoreBoardSortFunc)
scoreBoardMutex.Unlock()
// Calculate the rank of the new score
scoreBoardMutex.RLock()
for i, s := range scoreBoard {
if s.Name == name && s.Score == newScore {
rank = i + 1
break
}
}
scoreBoardMutex.RUnlock()
// Save the score board asynchronously
go SaveScores()
return
}
// StopAudio is a function that stops an audio track.
func StopAudio(name string) {
audioPlayersMutex.RLock()
player, playerOk := audioPlayers[name]
audioPlayersMutex.RUnlock()
// Recursive function to stop the audio source.
// Recursion might be necessary if the audio source is still playing
// when the stop function is called
// and the event listener is at end of the audio source
// fires after the audio source has been stopped
var stop func(recursive int)
stop = func(recursive int) {
if playerOk && player.source.Truthy() {
if Config.Control.Debug.Get() {
Log(fmt.Sprintf("Stopping audio source: %s", name))
}
player.startTime = audioCtx.Get("currentTime").Float()
player.source.Call("removeEventListener", "ended", player.endedCallback)
player.source.Call("stop")
player.source = js.Null()
audioPlayersMutex.Lock()
audioPlayers[name] = player
audioPlayersMutex.Unlock()
}
// Stop the audio source if it is still playing
// and the recursive limit has not been reached
if IsPlaying(name) && recursive > 0 {
stop(recursive - 1)
}
}
// Stop the audio source (recursive limit: 10)
stop(10)
}
// StopAudioSources is a function that stops all audio sources that match the selector.
func StopAudioSources(selector func(name string) bool) {
audioPlayersMutex.RLock()
var stopped []string
for name, player := range audioPlayers {
if selector(name) && player.source.Truthy() {
stopped = append(stopped, name)
}
}
audioPlayersMutex.RUnlock()
for _, name := range stopped {
StopAudio(name)
}
if Config.Control.Debug.Get() {
Log(fmt.Sprintf("Stopped audio sources: %v", stopped))
}
}
// ThrowError is a function that throws an error.
func ThrowError(err error) {
if err != nil {
js.Global().Call("eval", fmt.Sprintf("throw new Error('%s')", err.Error()))
}
}
// Unsetenv is a function that unsets the environment variable key.
func Unsetenv(key string) {
environ := GlobalGet(goEnv)
environ.Delete(key)
GlobalSet(goEnv, environ)
}
// UpdateFPS is a function that updates the frames per second.
func UpdateFPS(fps float64) {
fpsDiv.Set("innerHTML", fmt.Sprintf(fpsDiv.Call("getAttribute", "data-format").String(), fps))
}