-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
1285 lines (1184 loc) · 41.8 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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import $ from 'jquery'
import fontawesome from '@fortawesome/fontawesome'
import faChevronDown from '@fortawesome/fontawesome-free-solid/faChevronDown'
import faChevronUp from '@fortawesome/fontawesome-free-solid/faChevronUp'
import faInfoCircle from '@fortawesome/fontawesome-free-solid/faInfoCircle'
import faPencilAlt from '@fortawesome/fontawesome-free-solid/faPencilAlt'
import faPrint from '@fortawesome/fontawesome-free-solid/faPrint'
import faTrashAlt from '@fortawesome/fontawesome-free-solid/faTrashAlt'
require('popper.js')
require('bootstrap/js/src/button')
require('bootstrap/js/src/collapse')
require('bootstrap/js/src/dropdown')
require('bootstrap/js/src/modal')
require('bootstrap/js/src/popover')
require('bootstrap/js/src/tooltip')
require('bootstrap/js/src/util')
// Configure jquery
window.$ = $
window.jQuery = $
// Configure analytics
var service = analytics.getService('browser_websocket_client_app')
var tracker = service.getTracker('UA-159094697-1')
// Define savedOptions object
const savedOptions = {
preferences: {
preventSavingUrl: true,
preventUsingUrl: false,
preventSavingMessage: true,
preventUsingMessage: true
},
messages: [],
protocols: [],
urls: []
}
// Mock chrome.storage.sync
const mockChromeStorage = function (browser) {
if (browser === 'chrome') {
console.warn('Chrome is using mocked chrome.storage.sync')
} else {
console.warn('Browser is using mocked chrome.storage.sync')
window.chrome = {}
// eslint-disable-next-line no-global-assign
chrome = window.chrome
}
chrome.downloads = {}
chrome.downloads.download = function (options) {
console.log('Mocking chrome.downloads.download() with the following options:')
console.dir(options)
}
chrome.storage = {}
chrome.storage.sync = {
data: {
savedOptions: savedOptions
},
get: function (key, callback) {
callback({key: chrome.storage.sync.data[key]})
},
set: function ({key, value}, callback) {
chrome.storage.sync.data[key] = value
callback()
}
}
}
// Use mocked chrome.storage.sync if not running as extension
if (typeof chrome === 'undefined') {
mockChromeStorage()
} else if (typeof chrome.permissions === 'undefined') {
mockChromeStorage('chrome')
}
// Add Font Awesome icons to its library
fontawesome.library.add(
faChevronDown,
faChevronUp,
faInfoCircle,
faPencilAlt,
faPrint,
faTrashAlt
)
// Use Unicode BELL character as string separator
const SEPARATOR = '\u0007'
// HTML snippets for saved table row items
const messageTableRow = `
<div class="bwc-table-row rounded">
<span>
REPLACE_NAME
</span>
<span class="deleteMessage bwc-table-row-icon float-right" data-toggle="tooltip" data-placement="top" title="Click to delete this message" data-message='REPLACE_ALL'>
<i class="fa fa-trash-alt" aria-hidden="true"></i>
</span>
<span class="editMessage bwc-table-row-icon float-right" data-toggle="tooltip" data-placement="top" title="Click to edit this message" data-message='REPLACE_ALL'>
<i class="fa fa-pencil-alt" aria-hidden="true"></i>
</span>
<span class="printMessage bwc-table-row-icon float-right" data-toggle="tooltip" data-placement="top" title="Click to pretty-print this message" data-message='REPLACE_ALL'>
<i class="fa fa-print" aria-hidden="true"></i>
</span>
</div>
`
const protocolTableRow = `
<div class="bwc-table-row rounded">
<span>
REPLACE_PROTOCOL
</span>
<span class="deleteProtocol bwc-table-row-icon float-right" data-toggle="tooltip" data-placement="top" title="Click to delete this protocol" data-protocol='REPLACE_PROTOCOL'>
<i class="fa fa-trash-alt" aria-hidden="true"></i>
</span>
<span class="editProtocol bwc-table-row-icon float-right" data-toggle="tooltip" data-placement="top" title="Click to edit this protocol" data-protocol='REPLACE_PROTOCOL'>
<i class="fa fa-pencil-alt" aria-hidden="true"></i>
</span>
</div>
`
const urlTableRow = `
<div class="bwc-table-row rounded">
<span>
REPLACE_URL
</span>
<span class="deleteUrl bwc-table-row-icon float-right" data-toggle="tooltip" data-placement="top" title="Click to delete this URL" data-url='REPLACE_URL'>
<i class="fa fa-trash-alt" aria-hidden="true"></i>
</span>
<span class="editUrl bwc-table-row-icon float-right" data-toggle="tooltip" data-placement="top" title="Click to edit this URL" data-url='REPLACE_URL'>
<i class="fa fa-pencil-alt" aria-hidden="true"></i>
</span>
</div>
`
// Preferences HTML elements
const preferencesOptionsUrlCheckbox = $('#preferencesOptionsUrlCheckbox')
const preferencesClientUrlCheckbox = $('#preferencesClientUrlCheckbox')
const preferencesOptionsMessageCheckbox = $('#preferencesOptionsMessageCheckbox')
const preferencesClientMessageCheckbox = $('#preferencesClientMessageCheckbox')
// Options HTML elements
const deleteModal = $('#deleteModal')
const deleteModalBody = $('#deleteModalBody')
const deleteModalCancelButton = $('#deleteModalCancelButton')
const deleteModalDeleteButton = $('#deleteModalDeleteButton')
const deleteModalName = $('#deleteModalName')
const importModal = $('#importModal')
const importModalBody = $('#importModalBody')
const importModalCancelButton = $('#importModalCancelButton')
const importModalContinueButton = $('#importModalContinueButton')
const importModalDescription = $('#importModalDescription')
const options = $('#options')
const optionsExportImportExportButton = $('#optionsExportImportExportButton')
const optionsExportImportFileInput = $('#optionsExportImportFileInput')
const optionsExportImportFileName = $('#optionsExportImportFileName')
const optionsExportImportImportButton = $('#optionsExportImportImportButton')
const optionsMessageCancelEditButton = $('#optionsMessageCancelEditButton')
const optionsMessageJsonInvalidWarning = $('#optionsMessageJsonInvalidWarning')
const optionsMessageNameInput = $('#optionsMessageNameInput')
const optionsMessageNameInputLabel = $('#optionsMessageNameInputLabel')
const optionsMessageNameInvalid = $('#optionsMessageNameInvalid')
const optionsMessageNoneSaved = $('#optionsMessageNoneSaved')
const optionsMessageSaveButton = $('#optionsMessageSaveButton')
const optionsMessageSavedTable = $('#optionsMessageSavedTable')
const optionsMessageStatus = $('#optionsMessageStatus')
const optionsMessageTextarea = $('#optionsMessageTextarea')
const optionsMessageTextareaEmpty = $('#optionsMessageTextareaEmpty')
const optionsMessageTextareaFormatCheckbox = $('#optionsMessageTextareaFormatCheckbox')
const optionsMessageTextareaFormatSlider = $('#optionsMessageTextareaFormatSlider')
const optionsProtocolCancelEditButton = $('#optionsProtocolCancelEditButton')
const optionsProtocolInput = $('#optionsProtocolInput')
const optionsProtocolInputEmpty = $('#optionsProtocolInputEmpty')
const optionsProtocolInputLabel = $('#optionsProtocolInputLabel')
const optionsProtocolNoneSaved = $('#optionsProtocolNoneSaved')
const optionsProtocolSaveButton = $('#optionsProtocolSaveButton')
const optionsProtocolSavedTable = $('#optionsProtocolSavedTable')
const optionsProtocolStatus = $('#optionsProtocolStatus')
const optionsUrlCancelEditButton = $('#optionsUrlCancelEditButton')
const optionsUrlInput = $('#optionsUrlInput')
const optionsUrlInputEmpty = $('#optionsUrlInputEmpty')
const optionsUrlInputLabel = $('#optionsUrlInputLabel')
const optionsUrlInvalidWarning = $('#optionsUrlInvalidWarning')
const optionsUrlNoneSaved = $('#optionsUrlNoneSaved')
const optionsUrlSaveButton = $('#optionsUrlSaveButton')
const optionsUrlSavedTable = $('#optionsUrlSavedTable')
const optionsUrlStatus = $('#optionsUrlStatus')
// Client HTML elements
const clearMessagesButton = $('#clearMessagesButton')
const client = $('#client')
const connectButton = $('#connectButton')
const connectionStatus = $('#connectionStatus')
const disconnectButton = $('#disconnectButton')
const jsonModal = $('#jsonModal')
const jsonModalBody = $('#jsonModalBody')
const jsonModalTitle = $('#jsonModalTitle')
const messageJsonInvalidWarning = $('#messageJsonInvalidWarning')
const messages = $('#messages')
const messageSelect = $('#messageSelect')
const messageSelectOptions = $('#messageSelectOptions')
const messageSendButton = $('#messageSendButton')
const messageTextarea = $('#messageTextarea')
const messageTextareaFormatCheckbox = $('#messageTextareaFormatCheckbox')
const messageTextareaFormatSlider = $('#messageTextareaFormatSlider')
const protocolInput = $('#protocolInput')
const protocolSelect = $('#protocolSelect')
const protocolSelectOptions = $('#protocolSelectOptions')
const urlInput = $('#urlInput')
const urlInvalidWarning = $('#urlInvalidWarning')
const urlSelect = $('#urlSelect')
const urlSelectOptions = $('#urlSelectOptions')
// Immutable variables
const url = document.location.toString()
const optionsUrlInputLabelDefaultText = 'The URL should begin with <code>ws://</code> or <code>wss://</code>:'
const optionsMessageNameInputLabelDefaultText = 'The display name appears in the "Saved Messages" table and client drop-down menu:'
const optionsProtocolInputLabelDefaultText = 'Enter a single protocol name or multiple comma-separated names:'
// Mutable variables
let editingMessage = false
let editingMessageTargetBody = ''
let editingMessageTargetName = ''
let editingProtocol = false
let editingProtocolTarget = ''
let editingUrl = false
let editingUrlTarget = ''
let ws = null
let wsConnected = false
let wsPoliteDisconnection = false
// Used only by background.js to show the options section
// when user chooses extension options in browser settings
if (url.match(/#options/)) {
client.removeClass('show')
options.addClass('show')
}
// PREFERENCES SECTION
// Set checkbox properties
const setPreferencesCheckboxes = function () {
const preferences = savedOptions.preferences
preferencesOptionsUrlCheckbox.prop('checked', preferences.preventSavingUrl)
preferencesClientUrlCheckbox.prop('checked', preferences.preventUsingUrl)
preferencesOptionsMessageCheckbox.prop('checked', preferences.preventSavingMessage)
preferencesClientMessageCheckbox.prop('checked', preferences.preventUsingMessage)
}
// React to preventSavingUrl checkbox changes
preferencesOptionsUrlCheckbox.on('change', function () {
savedOptions.preferences.preventSavingUrl = preferencesOptionsUrlCheckbox.is(':checked')
saveOptions()
tracker.sendEvent('Options', 'PreventSavingUrl', savedOptions.preferences.preventSavingUrl)
})
// React to preventUsingUrl checkbox changes
preferencesClientUrlCheckbox.on('change', function () {
savedOptions.preferences.preventUsingUrl = preferencesClientUrlCheckbox.is(':checked')
saveOptions()
tracker.sendEvent('Options', 'PreventUsingUrl', savedOptions.preferences.preventUsingUrl)
})
// React to preventSavingMessage checkbox changes
preferencesOptionsMessageCheckbox.on('change', function () {
savedOptions.preferences.preventSavingMessage = preferencesOptionsMessageCheckbox.is(':checked')
saveOptions()
tracker.sendEvent('Options', 'PreventSavingMessage', savedOptions.preferences.preventSavingMessage)
})
// React to preventUsingMessage checkbox changes
preferencesClientMessageCheckbox.on('change', function () {
savedOptions.preferences.preventUsingMessage = preferencesClientMessageCheckbox.is(':checked')
saveOptions()
tracker.sendEvent('Options', 'PreventUsingMessage', savedOptions.preferences.preventUsingMessage)
})
// OPTIONS SECTION
// Save options to storage
const saveOptions = function () {
chrome.storage.sync.set({
'savedOptions': savedOptions
}, function () {
loadOptions()
})
}
// Fetch extension options from storage and update all related objects and elements
const loadOptions = function () {
chrome.storage.sync.get('savedOptions', function (result) {
if (result.savedOptions) {
if (result.savedOptions.preferences) {
savedOptions.preferences = result.savedOptions.preferences
}
if (result.savedOptions.messages) {
savedOptions.messages = result.savedOptions.messages
}
if (result.savedOptions.protocols) {
savedOptions.protocols = result.savedOptions.protocols
}
if (result.savedOptions.urls) {
savedOptions.urls = result.savedOptions.urls
}
}
setPreferencesCheckboxes()
if (savedOptions.messages.length > 0) {
populateMessageTable()
populateSavedMessageSelect()
messageSelect.show()
optionsMessageNoneSaved.hide()
optionsMessageSavedTable.show()
} else {
messageSelect.hide()
optionsMessageNoneSaved.show()
optionsMessageSavedTable.hide()
}
if (savedOptions.protocols.length > 0) {
populateProtocolTable()
populateSavedProtocolSelect()
optionsProtocolNoneSaved.hide()
optionsProtocolSavedTable.show()
protocolSelect.show()
} else {
optionsProtocolNoneSaved.show()
optionsProtocolSavedTable.hide()
protocolSelect.hide()
}
if (savedOptions.urls.length > 0) {
populateUrlTable()
populateSavedUrlSelect()
optionsUrlNoneSaved.hide()
optionsUrlSavedTable.show()
urlSelect.show()
} else {
optionsUrlNoneSaved.show()
optionsUrlSavedTable.hide()
urlSelect.hide()
}
optionsExportImportFileInput.val(undefined)
optionsExportImportFileInput.change()
})
}
// Delete from savedOptions
const deleteSavedOptions = function (option, target) {
const options = deleteOptions(option, target, savedOptions)
savedOptions.messages = options.messages
savedOptions.protocols = options.protocols
savedOptions.urls = options.urls
}
// Delete options
const deleteOptions = function (option, target, options) {
let messages, protocols, urls
switch (option) {
case 'message':
messages = options.messages.filter(e => !e.toString().startsWith(target))
protocols = options.protocols ? options.protocols : []
urls = options.urls ? options.urls : []
break
case 'protocol':
messages = options.messages ? options.messages : []
protocols = options.protocols.filter(e => e !== target)
urls = options.urls ? options.urls : []
break
case 'url':
messages = options.messages ? options.messages : []
protocols = options.protocols ? options.protocols : []
urls = options.urls.filter(e => e !== target)
break
default:
return false
}
return {messages, protocols, urls}
}
// OPTIONS: URL PERSISTENCE
// Populate the saved URLs table
const populateUrlTable = function () {
const urls = savedOptions.urls.sort()
let table = ''
$.each(urls, function (key, url) {
table += urlTableRow.replace(/REPLACE_URL/g, url)
})
optionsUrlSavedTable
.html('')
.append(table)
$('.editUrl').on('click', function () {
editUrl(jQuery(this).data('url'))
})
$('.deleteUrl').on('click', function () {
deleteUrl(jQuery(this).data('url'))
})
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
}
// Test if URL begins with ws:// or wss:// and has no spaces
const isValidUrl = function (url) {
return /^(ws|wss):\/\/[^ "]+$/.test(url)
}
// Copy a saved URL to the input element and show cancel button
const editUrl = function (url) {
editingUrl = true
editingUrlTarget = url
optionsUrlCancelEditButton.show()
optionsUrlInput.val(url)
optionsUrlInputEmpty.hide()
optionsUrlInputLabel.text(`Editing URL: ${url}`)
optionsUrlInvalidWarning.hide()
optionsUrlSaveButton.prop('disabled', false)
optionsUrlStatus.hide()
}
// Delete a saved URL from storage
const deleteUrl = function (url) {
deleteModalBody.text('Are you sure you want to delete the URL shown below?')
deleteModalName.text(url)
deleteModalDeleteButton.show()
deleteModalDeleteButton
.data('target', url)
.on('click', function () {
const url = jQuery(this).data('target')
deleteSavedOptions('url', url)
saveOptions()
tracker.sendEvent('Options', 'Deleted', 'Url')
deleteModalBody.text('URL deleted:')
deleteModalName.text(url)
deleteModalDeleteButton.hide()
deleteModalCancelButton.text('Close')
})
deleteModal.modal('show')
}
// Validate URL input on input change
optionsUrlInput.on('keyup', function () {
if (optionsUrlInput.val().length > 0) {
optionsUrlInputEmpty.hide()
} else {
optionsUrlInputEmpty.show()
}
if (isValidUrl(optionsUrlInput.val())) {
optionsUrlInvalidWarning.hide()
} else {
optionsUrlInvalidWarning.show()
}
if (optionsUrlInput.val().length > 0 && isValidUrl(optionsUrlInput.val())) {
optionsUrlSaveButton.prop('disabled', false)
} else {
optionsUrlSaveButton.prop('disabled', savedOptions.preferences.preventSavingUrl)
}
})
// Cancel URL edit and reset variables
optionsUrlCancelEditButton.on('click', function () {
editingUrl = false
editingUrlTarget = ''
optionsUrlInput.val('')
optionsUrlInputLabel.html(optionsUrlInputLabelDefaultText)
optionsUrlInputEmpty.hide()
optionsUrlInvalidWarning.hide()
optionsUrlSaveButton.prop('disabled', savedOptions.preferences.preventSavingUrl)
})
// Persist URL to storage on save button click
optionsUrlSaveButton.on('click', function () {
const url = optionsUrlInput.val()
if (editingUrl) {
deleteSavedOptions('url', editingUrlTarget)
} else {
deleteSavedOptions('url', url)
}
savedOptions.urls.push(url)
saveOptions()
tracker.sendEvent('Options', 'Saved', 'Url')
optionsUrlInput.val('')
optionsUrlInputLabel.html(optionsUrlInputLabelDefaultText)
optionsUrlSaveButton.prop('disabled', savedOptions.preferences.preventSavingUrl)
optionsUrlStatus
.text('URL saved.')
.show()
})
// OPTIONS: PROTOCOL PERSISTENCE
// Convert protocol input value to an array if necessary and
// trim unnecessary commas and spaces
const getProtocols = function (input) {
const protocolsInput = input.val()
const protocolsResult = protocolsInput
.split(',')
.map(item => item.trim())
.filter(item => item !== '')
let protocols
if (protocolsResult.length === 1) {
protocols = protocolsResult[0].trim()
} else if (protocolsResult.length > 1) {
protocols = protocolsResult
} else {
protocols = null
}
return protocols
}
// Populate the saved protocols table
const populateProtocolTable = function () {
const protocols = savedOptions.protocols.sort()
let table = ''
$.each(protocols, function (key, protocol) {
table += protocolTableRow.replace(/REPLACE_PROTOCOL/g, protocol)
})
optionsProtocolSavedTable
.html('')
.append(table)
$('.editProtocol').on('click', function () {
editProtocol(jQuery(this).data('protocol'))
})
$('.deleteProtocol').on('click', function () {
deleteProtocol(jQuery(this).data('protocol'))
})
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
}
// Copy a saved protocol to the input element and show cancel button
const editProtocol = function (protocol) {
editingProtocol = true
editingProtocolTarget = protocol
optionsProtocolCancelEditButton.show()
optionsProtocolInput.val(protocol)
optionsProtocolInputEmpty.hide()
optionsProtocolInputLabel.text(`Editing protocol: ${protocol}`)
optionsProtocolSaveButton.prop('disabled', false)
optionsProtocolStatus.hide()
}
// Delete a saved protocol from storage
const deleteProtocol = function (protocol) {
deleteModalBody.text('Are you sure you want to delete the protocol shown below?')
deleteModalName.text(protocol)
deleteModalDeleteButton.show()
deleteModalDeleteButton
.data('target', protocol)
.on('click', function () {
const protocol = jQuery(this).data('target')
deleteSavedOptions('protocol', protocol)
saveOptions()
tracker.sendEvent('Options', 'Deleted', 'Protocol')
deleteModalBody.text('Protocol deleted:')
deleteModalName.text(protocol)
deleteModalDeleteButton.hide()
deleteModalCancelButton.text('Close')
})
deleteModal.modal('show')
}
// Enable protocol save button if input is not empty
optionsProtocolInput.on('keyup', function () {
if (optionsProtocolInput.val().replace(/\s/g, '').length > 0) {
optionsProtocolInputEmpty.hide()
optionsProtocolSaveButton.prop('disabled', false)
} else {
optionsProtocolInputEmpty.show()
optionsProtocolSaveButton.prop('disabled', true)
}
})
// Cancel protocol edit and reset variables
optionsProtocolCancelEditButton.on('click', function () {
editingProtocol = false
editingProtocolTarget = ''
optionsProtocolInput.val('')
optionsProtocolInputLabel.text(optionsProtocolInputLabelDefaultText)
optionsProtocolInputEmpty.hide()
optionsProtocolSaveButton.prop('disabled', true)
})
// Persist protocol to storage on save button click
optionsProtocolSaveButton.on('click', function () {
const protocol = getProtocols(optionsProtocolInput)
if (editingProtocol) {
deleteSavedOptions('protocol', editingProtocolTarget)
} else {
deleteSavedOptions('protocol', protocol)
}
savedOptions.protocols.push(protocol.toString().replace(/,/g, ', '))
saveOptions()
tracker.sendEvent('Options', 'Saved', 'Protocol')
optionsProtocolInput.val('')
optionsProtocolInputLabel.text(optionsProtocolInputLabelDefaultText)
optionsProtocolSaveButton.prop('disabled', true)
optionsProtocolStatus
.text('Protocol saved.')
.show()
})
// OPTIONS: MESSAGE PERSISTENCE
// Populate the saved messages table
const populateMessageTable = function () {
const messages = savedOptions.messages.sort()
let table = ''
$.each(messages, function (key, message) {
const [name, body] = message.split(SEPARATOR)
table += messageTableRow
.replace(/REPLACE_ALL/g, message)
.replace(/REPLACE_MESSAGE/g, body)
.replace(/REPLACE_NAME/g, name)
})
optionsMessageSavedTable
.html('')
.append(table)
$('.printMessage').on('click', function () {
printMessage(jQuery(this).data('message'))
})
$('.editMessage').on('click', function () {
editMessage(jQuery(this).data('message'))
})
$('.deleteMessage').on('click', function () {
deleteMessage(jQuery(this).data('message'))
})
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
}
// Test a string to determine if it is valid JSON
const isValidJson = function (string) {
try {
const test = JSON.parse(string)
if (test && typeof test === 'object') {
return true
}
} catch (e) {
}
return false
}
// Convert JSON object to a string
const stringifyJson = function (input) {
if (typeof input === 'object') {
return JSON.stringify(input)
} else {
return input
}
}
// Toggle JSON formatting from single line to multi-line and vice versa
const formatTextarea = function (checkbox, textarea) {
const checked = checkbox.is(':checked')
const message = textarea.val()
const valid = isValidJson(message)
if (!valid) {
checkbox.prop('checked', false)
} else if (checked) {
textarea.val(JSON.stringify(JSON.parse(message), null, 2))
} else {
textarea.val(editingMessageTargetBody)
}
}
// Validate message name input and message textarea values
// Enable or disable save button and JSON formatting toggle
const validateOptionsMessage = function () {
const validMessageName = optionsMessageNameInput.val().trim().length > 0
const validMessageLength = optionsMessageTextarea.val().trim().length > 0
const validMessageJson = isValidJson(optionsMessageTextarea.val())
if (validMessageName && validMessageLength && validMessageJson) {
optionsMessageSaveButton.prop('disabled', false)
optionsMessageTextareaFormatSlider.removeClass('bwc-slider-disabled')
} else {
optionsMessageSaveButton.prop('disabled', savedOptions.preferences.preventSavingMessage)
optionsMessageTextareaFormatSlider.addClass('bwc-slider-disabled')
}
}
// Validate message name input and show user feedback
const validateOptionsMessageName = function () {
const validMessageName = optionsMessageNameInput.val().trim().length > 0
let valid = true
if (validMessageName) {
optionsMessageNameInvalid.hide()
} else {
valid = false
optionsMessageNameInvalid.show()
}
if (valid) {
validateOptionsMessage()
}
}
// Validate message textarea value and show user feedback
const validateOptionsMessageTextarea = function () {
const validMessageLength = optionsMessageTextarea.val().trim().length > 0
const validMessageJson = isValidJson(optionsMessageTextarea.val())
let valid = true
optionsMessageJsonInvalidWarning.hide()
if (validMessageLength) {
optionsMessageTextareaEmpty.hide()
if (!validMessageJson) {
valid = false
optionsMessageJsonInvalidWarning.show()
}
} else {
valid = false
optionsMessageTextareaEmpty.show()
}
if (valid) {
validateOptionsMessage()
}
}
// Copy a saved message to the input elements
const editMessage = function (message) {
const [name, body] = message.split(SEPARATOR)
editingMessage = true
editingMessageTargetBody = body
editingMessageTargetName = `${name}${SEPARATOR}`
optionsMessageCancelEditButton.show()
optionsMessageTextareaEmpty.hide()
optionsMessageNameInput.val(name)
optionsMessageNameInputLabel.text(`Editing message: ${name}`)
optionsMessageNameInvalid.hide()
optionsMessageSaveButton.prop('disabled', false)
optionsMessageStatus.hide()
optionsMessageTextarea.val(body)
validateOptionsMessage()
}
// Delete a saved message from storage
const deleteMessage = function (all) {
const name = all.split(SEPARATOR)[0]
deleteModalBody.text('Are you sure you want to delete the message shown below?')
deleteModalName.text(name)
deleteModalDeleteButton.show()
deleteModalDeleteButton
.data('target', all)
.on('click', function () {
deleteSavedOptions('message', `${name}${SEPARATOR}`)
saveOptions()
tracker.sendEvent('Options', 'Deleted', 'Message')
deleteModalBody.text('Message deleted:')
deleteModalName.text(name)
deleteModalDeleteButton.hide()
deleteModalCancelButton.text('Close')
})
deleteModal.modal('show')
}
// Format JSON for pretty-print modal
const highlightJson = function (string) {
return JSON.stringify(JSON.parse(string), null, 2)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
let cls = 'bwc-number'
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'bwc-key'
} else {
cls = 'bwc-string'
}
} else if (/true|false/.test(match)) {
cls = 'bwc-boolean'
} else if (/null/.test(match)) {
cls = 'bwc-null'
}
return `<span class="${cls}">${match}</span>`
})
}
// Pretty-print a saved message body
const printMessage = function (message) {
const [title, body] = message.split(SEPARATOR)
jsonModalTitle.html(title)
jsonModalBody.html(getJsonModalBody(body))
jsonModal.modal('show')
}
// Validate message name input value
optionsMessageNameInput.on('keyup', function () {
validateOptionsMessageName()
})
// Validate message textarea value
optionsMessageTextarea.on('keyup', function () {
validateOptionsMessageTextarea()
})
// Toggle message textarea JSON formatting
optionsMessageTextareaFormatCheckbox.on('change', function () {
formatTextarea($(this), optionsMessageTextarea)
})
// Cancel message edit and reset elements
optionsMessageCancelEditButton.on('click', function () {
editingMessage = false
editingMessageTargetBody = ''
editingMessageTargetName = ''
optionsMessageTextareaEmpty.hide()
optionsMessageJsonInvalidWarning.hide()
optionsMessageNameInput.val('')
optionsMessageNameInputLabel.text(optionsMessageNameInputLabelDefaultText)
optionsMessageNameInvalid.hide()
optionsMessageSaveButton.prop('disabled', savedOptions.preferences.preventSavingMessage)
optionsMessageStatus.hide()
optionsMessageTextarea.val('')
optionsMessageTextareaFormatSlider.addClass('bwc-slider-disabled')
optionsMessageTextareaFormatCheckbox.prop('checked', false)
})
// Persist message to storage on save button click
optionsMessageSaveButton.on('click', function () {
const name = optionsMessageNameInput.val()
const body = optionsMessageTextarea.val()
const message = `${name}${SEPARATOR}${body}`
if (editingMessage) {
deleteSavedOptions('message', editingMessageTargetName)
} else {
deleteSavedOptions('message', `${name}${SEPARATOR}`)
}
savedOptions.messages.push(message)
saveOptions()
tracker.sendEvent('Options', 'Saved', 'Message')
optionsMessageTextareaEmpty.hide()
optionsMessageJsonInvalidWarning.hide()
optionsMessageNameInput.val('')
optionsMessageNameInputLabel.text(optionsMessageNameInputLabelDefaultText)
optionsMessageNameInvalid.hide()
optionsMessageSaveButton.prop('disabled', savedOptions.preferences.preventSavingMessage)
optionsMessageStatus
.text('Message saved.')
.show()
optionsMessageTextarea.val('')
optionsMessageTextareaFormatSlider.addClass('bwc-slider-disabled')
optionsMessageTextareaFormatCheckbox.prop('checked', false)
})
// OPTIONS: EXPORT IMPORT
function downloadFile (options) {
if (!options.url) {
const blob = new Blob([options.content], {type: 'application/json;charset=UTF-8'})
options.url = window.URL.createObjectURL(blob)
}
chrome.downloads.download({
url: options.url,
filename: options.filename,
saveAs: true
})
}
// Exports current configuration
optionsExportImportExportButton.on('click', function () {
downloadFile({
filename: 'wsclient.json',
content: JSON.stringify(savedOptions)
})
tracker.sendEvent('Options', 'Exported')
})
optionsExportImportFileInput.on('change', function () {
const file = optionsExportImportFileInput[0].files[0]
if (file) {
optionsExportImportFileName.html(`Configuration file: <code>${file.name}</code>`)
}
optionsExportImportImportButton.prop('disabled', file === undefined)
})
// Imports configuration
optionsExportImportImportButton.on('click', function () {
const file = optionsExportImportFileInput[0].files[0]
if (file === undefined) {
return
}
importConfiguration(file)
tracker.sendEvent('Options', 'Imported')
})
// Imports configuration from file by using confirmation
const importConfiguration = function (file) {
importModalBody.text('Are you sure you want to overwrite your current settings?')
importModalContinueButton.show()
importModalDescription.hide()
importModalContinueButton.on('click', function () {
importModalDescription.hide()
importModalContinueButton.hide()
const reader = new FileReader()
reader.onload = function (e) {
let data = null
try {
data = JSON.parse(e.target.result)
} catch (e) {
importModalBody.text('Error parsing JSON')
importModalDescription.text(e)
importModalDescription.show()
importModalCancelButton.text('Close')
return
}
// eslint-disable-next-line no-prototype-builtins
if (data != null && data.hasOwnProperty('messages') && data.hasOwnProperty('protocols') && data.hasOwnProperty('urls') && data.hasOwnProperty('preferences')) {
savedOptions.messages = data.messages
savedOptions.protocols = data.protocols
savedOptions.urls = data.urls
savedOptions.preferences = data.preferences
saveOptions()
importModalDescription.hide()
importModalBody.text('File successfully imported')
importModalCancelButton.text('Close')
} else {
importModalBody.text('Error parsing JSON')
importModalDescription.text('Unexpected file format found.')
importModalDescription.show()
importModalCancelButton.text('Close')
}
}
reader.readAsText(file)
})
importModal.modal('show')
}
// CLIENT SECTION
// Populate URL select menu
const populateSavedUrlSelect = function () {
const urls = savedOptions.urls.sort()
let options = ''
$.each(urls, function (key, url) {
options += `<button class="dropdown-item url" type="button" data-value="${url}">${url}</button>`
})
urlSelectOptions
.html('')
.append(options)
$('.dropdown-item.url').on('click', function () {
urlInput.val(jQuery(this).data('value'))
connectButton.prop('disabled', false)
})
}
// Populate protocol select menu
const populateSavedProtocolSelect = function () {
const protocols = savedOptions.protocols.sort()
let options = ''
$.each(protocols, function (key, protocol) {
options += `<button class="dropdown-item protocol" type="button" data-value="${protocol}">${protocol}</button>`
})
protocolSelectOptions
.html('')
.append(options)
$('.dropdown-item.protocol').on('click', function () {
protocolInput.val(jQuery(this).data('value'))
})
}
// Populate message select menu
const populateSavedMessageSelect = function () {
const messages = savedOptions.messages.sort()
let options = ''
$.each(messages, function (key, message) {
const [name, body] = message.split(SEPARATOR)
options += `<button class="dropdown-item message" type="button" data-value='${body}'>${name}</button>`
})
messageSelectOptions
.html('')
.append(options)
$('.dropdown-item.message').on('click', function () {
messageTextarea.val(stringifyJson(jQuery(this).data('value')))
validateClientMessage()
})
}
// Validate message textarea value, show user feedback,
// and enable or disable send button
const validateClientMessage = function () {
const validJson = isValidJson(messageTextarea.val())
if (validJson) {
if (wsConnected) {
messageSendButton.prop('disabled', false)
} else {
messageSendButton.prop('disabled', savedOptions.preferences.preventUsingMessage)
}
messageJsonInvalidWarning.hide()
messageTextareaFormatSlider.removeClass('bwc-slider-disabled')
} else {
if (messageTextarea.val().length === 0) {
messageJsonInvalidWarning.hide()
} else {
messageJsonInvalidWarning.show()
}
messageSendButton.prop('disabled', savedOptions.preferences.preventUsingMessage)
messageTextareaFormatSlider.addClass('bwc-slider-disabled')
}
return validJson
}
// Enable and disable connect button based on URL input length and validation
urlInput.on('keyup', function () {
if (urlInput.val().length === 0) {