-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1576 lines (1515 loc) · 65.2 KB
/
Copy pathscript.js
File metadata and controls
1576 lines (1515 loc) · 65.2 KB
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
// Utility to fetch JSON data
/**
* Loads grid configuration from `data.json`, converting legacy button action names to action IDs when necessary.
* @returns {Promise<Object>} Resolves with the parsed grid data object, including any patched button definitions.
*/
async function fetchGridData() {
try {
const res = await fetch('data.json');
const data = await res.json();
// Patch: convert legacy action name to action_id if possible
if (Array.isArray(data.buttons)) {
data.buttons.forEach(btn => {
if (!btn.action_id && btn.action) {
btn.action_id = getActionIdByName(btn.action);
}
});
}
return data;
} catch (e) {
console.error('Error fetching grid data:', e);
throw e;
}
}
// Status bar update
/**
* Updates the UI to reflect the current connection status with Streamer.bot.
* Changes the status text and indicator styling based on the connection state.
* @param {boolean} connected - True if connected to Streamer.bot; false otherwise.
*/
function SetConnectionStatus(connected) {
const bar = document.getElementById('status-text');
const indicator = document.getElementById('status-indicator');
if (connected) {
bar.textContent = 'Connected to Streamer.bot';
indicator.classList.add('connected');
indicator.classList.remove('disconnected');
} else {
bar.textContent = 'Disconnected from Streamer.bot';
indicator.classList.add('disconnected');
indicator.classList.remove('connected');
}
}
// Refactored: Encapsulate app state in a single object
const appState = {
gridData: null,
editMode: false,
availableActions: [],
dragSrcIdx: null,
gridBlurMin: 4,
gridBlurMax: 12,
unsavedChanges: false,
};
window.appState = appState;
// Utility to map action_id to action name
/**
* Returns the action name corresponding to a given action ID from the available actions list.
* If the action ID is not found, returns an empty string and logs a warning.
* @param {string} action_id - The unique identifier of the action.
* @returns {string} The name of the action, or an empty string if not found.
*/
function getActionNameById(action_id) {
if (!appState.availableActions || !Array.isArray(appState.availableActions)) return '';
const found = appState.availableActions.find(a => a.id === action_id);
if (!found) {
console.warn(`getActionNameById: Action name not found for id: ${action_id}`);
}
return found ? found.name : '';
}
// Utility to map action name to action_id
/**
* Returns the action ID corresponding to a given action name from the available actions.
* Logs a warning if the action name is not found.
* @param {string} action_name - The name of the action to look up.
* @returns {string} The action ID if found; otherwise, an empty string.
*/
function getActionIdByName(action_name) {
if (!appState.availableActions || !Array.isArray(appState.availableActions)) return '';
const found = appState.availableActions.find(a => a.name === action_name);
if (!found) {
console.warn(`getActionIdByName: Action id not found for name: ${action_name}`);
}
return found ? found.id : '';
}
/**
* Renders the interactive grid of buttons and empty cells in the UI based on the provided layout and parameters.
*
* In edit mode, enables drag-and-drop reordering, button editing, and adding new buttons to empty cells. In normal mode, attaches handlers to trigger Streamer.bot actions when buttons are pressed. Applies grid sizing, gap, and blur settings, and displays optional debug overlays.
*
* @param {Object} params - Grid configuration.
* @param {number} params.rows - Number of grid rows.
* @param {number} params.cols - Number of grid columns.
* @param {Array} params.buttons - Array of button objects with position and action data.
* @param {number} [params.gap] - Gap size between grid cells in pixels.
* @param {number} [params.blurMin] - Minimum blur value for grid background.
* @param {number} [params.blurMax] - Maximum blur value for grid background.
*/
function renderGrid({ rows, cols, buttons, gap, blurMin, blurMax }) {
const grid = document.getElementById('grid-container');
if (!grid) {
console.error('renderGrid: Grid container not found in DOM');
return;
}
if (!Array.isArray(buttons)) {
console.warn('renderGrid: buttons is not an array', buttons);
return;
}
grid.innerHTML = '';
// Set CSS variables for grid sizing
grid.style.setProperty('--grid-rows', rows);
grid.style.setProperty('--grid-cols', cols);
grid.style.gap = (gap !== undefined ? gap : 16) + 'px';
appState.gridBlurMin = (blurMin !== undefined ? blurMin : 4);
appState.gridBlurMax = (blurMax !== undefined ? blurMax : 12);
// Create a map for quick lookup
const btnMap = {};
buttons.forEach((btn, idx) => {
// Log and skip out-of-bounds buttons
if (btn.row < 0 || btn.row >= rows || btn.col < 0 || btn.col >= cols) {
console.warn(`renderGrid: Button at idx ${idx} has out-of-bounds row/col:`, btn);
return;
}
btnMap[`${btn.row},${btn.col}`] = { ...btn, idx };
});
/**
* Handles grid button activation for both click and touch events, triggering the associated Streamer.bot action if the client is connected.
* Prevents duplicate action triggers on touch devices.
*/
function handleGridButtonAction(e) {
// Prevent double-firing on touch devices
if (e.type === 'touchend') {
e.preventDefault();
e.target.__handledTouch = true;
}
if (e.type === 'click' && e.target.__handledTouch) {
e.target.__handledTouch = false;
return;
}
const btn = e.currentTarget.__btnData;
// Use optional chaining for cleaner code
if (window.sbClient?.doAction) {
window.sbClient.doAction(btn.action_id).catch(err => {
console.error('Failed to trigger action:', btn.action_id, err);
alert('Failed to trigger action: ' + btn.action_id);
});
}
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const btn = btnMap[`${r},${c}`];
if (btn) {
const el = document.createElement('button');
el.className = 'grid-button';
el.dataset.row = r;
el.dataset.col = c;
el.dataset.idx = btn.idx;
// In renderGrid, sanitize all user-provided content before inserting into innerHTML
el.innerHTML = '';
if (btn.icon) {
el.innerHTML += `<span class="button-icon iconify" data-icon="${sanitizeString(btn.icon)}"></span>`;
}
el.innerHTML += `<span class="button-title">${sanitizeString(btn.title)}</span>`;
if (appState.editMode) {
el.setAttribute('draggable', 'true');
el.ondragstart = handleDragStart;
el.ondragover = handleDragOver;
el.ondrop = handleDrop;
el.ondragend = handleDragEnd;
el.ondragleave = handleDragLeave;
el.onclick = (e) => {
// Only open edit modal on left click
if (e.button === 0) {
e.preventDefault();
openEditModal(btn.idx);
}
};
// Allow middle click to trigger normal action
el.onmousedown = (e) => {
if (e.button === 1) {
e.preventDefault();
// Apply optional chaining consistently and add error handling
if (window.sbClient?.doAction && btn.action_id) {
window.sbClient.doAction(btn.action_id).catch(err => {
console.error('Failed to trigger action:', btn.action_id, err);
alert('Failed to trigger action: ' + btn.action_id);
});
}
}
};
} else {
el.removeAttribute('draggable');
el.ondragstart = null;
el.ondragover = null;
el.ondrop = null;
el.ondragend = null;
el.ondragleave = null;
// Remove old handlers
el.onclick = null;
el.ontouchend = null;
// Attach unified handler
el.__btnData = btn;
el.addEventListener('click', handleGridButtonAction, false);
el.addEventListener('touchend', handleGridButtonAction, false);
}
// Debug overlay
if (gridDebugOverlay) {
el.style.border = '2px solid red';
el.style.position = 'relative';
const label = document.createElement('span');
label.textContent = `[${r},${c}]`;
label.style.position = 'absolute';
label.style.top = '2px';
label.style.left = '4px';
label.style.fontSize = '0.8em';
label.style.color = 'red';
label.style.background = 'rgba(0,0,0,0.3)';
label.style.padding = '0 2px';
label.style.borderRadius = '3px';
el.appendChild(label);
} else {
el.style.border = '';
}
grid.appendChild(el);
} else {
// Always render empty cells
const empty = document.createElement('div');
empty.className = 'empty-cell' + (appState.editMode ? '' : ' hidden-cell');
empty.dataset.row = r;
empty.dataset.col = c;
if (appState.editMode) {
empty.onclick = () => openAddButtonModal(r, c);
empty.ondragover = handleDragOver;
empty.ondrop = handleDrop;
empty.ondragleave = handleDragLeave;
}
// Debug overlay
if (gridDebugOverlay) {
empty.style.border = '2px solid red';
empty.style.position = 'relative';
const label = document.createElement('span');
label.textContent = `[${r},${c}]`;
label.style.position = 'absolute';
label.style.top = '2px';
label.style.left = '4px';
label.style.fontSize = '0.8em';
label.style.color = 'red';
label.style.background = 'rgba(0,0,0,0.3)';
label.style.padding = '0 2px';
label.style.borderRadius = '3px';
empty.appendChild(label);
} else {
empty.style.border = '';
}
grid.appendChild(empty);
}
}
}
if (window.Iconify) {
window.Iconify.scan(grid);
}
setSaveButtonState();
}
let dragSrcIdx = null;
function handleDragStart(e) {
dragSrcIdx = this.dataset.idx;
this.style.opacity = '0.4';
}
/**
* Handles the dragover event for grid cells or buttons, enabling drop by preventing default behavior and adding a visual indicator.
* @param {DragEvent} e - The dragover event object.
*/
function handleDragOver(e) {
e.preventDefault();
this.classList.add('drag-over');
}
/**
* Handles dropping a dragged button onto another button or an empty cell in the grid, updating button positions and triggering a re-render.
*
* If dropped onto another button, swaps their positions. If dropped onto an empty cell, moves the dragged button to that cell. Marks the layout as having unsaved changes and updates the save button state.
*
* @param {DragEvent} e - The drop event.
*/
function handleDrop(e) {
e.preventDefault();
this.classList.remove('drag-over');
const targetIdx = this.dataset.idx;
const targetRow = parseInt(this.dataset.row, 10);
const targetCol = parseInt(this.dataset.col, 10);
if (dragSrcIdx === null) {
console.warn('handleDrop: dragSrcIdx is null');
}
if (dragSrcIdx !== null) {
if (typeof targetIdx !== 'undefined') {
// Swap with another button
if (dragSrcIdx !== targetIdx) {
if (!appState.gridData.buttons[dragSrcIdx] || !appState.gridData.buttons[targetIdx]) {
console.warn('handleDrop: Invalid button indices', dragSrcIdx, targetIdx);
}
const temp = { ...appState.gridData.buttons[dragSrcIdx] };
appState.gridData.buttons[dragSrcIdx].row = appState.gridData.buttons[targetIdx].row;
appState.gridData.buttons[dragSrcIdx].col = appState.gridData.buttons[targetIdx].col;
appState.gridData.buttons[targetIdx].row = temp.row;
appState.gridData.buttons[targetIdx].col = temp.col;
appState.unsavedChanges = true;
setSaveButtonState();
renderGrid(appState.gridData);
}
} else {
// Move to empty cell
if (!appState.gridData.buttons[dragSrcIdx]) {
console.warn('handleDrop: Invalid dragSrcIdx for empty cell', dragSrcIdx);
}
appState.gridData.buttons[dragSrcIdx].row = targetRow;
appState.gridData.buttons[dragSrcIdx].col = targetCol;
appState.unsavedChanges = true;
setSaveButtonState();
renderGrid(appState.gridData);
}
}
dragSrcIdx = null;
}
function handleDragEnd(e) {
this.style.opacity = '';
this.style.outline = '';
}
/**
* Removes the visual drag-over indicator from a grid cell or button during a drag-and-drop operation.
*/
function handleDragLeave(e) {
this.classList.remove('drag-over');
}
/**
* Initializes the edit mode toggle functionality and inline grid settings UI, enabling users to switch between edit and normal modes, adjust grid dimensions, and save layout changes.
*
* Sets up event handlers for toggling edit mode, validating and applying grid row/column changes, and exporting the current layout as a JSON file. Updates UI elements and application state accordingly.
*/
function setupEditModeToggle() {
const editBtn = document.getElementById('edit-toggle');
const saveBtn = document.getElementById('save-layout');
const statusBarButtons = document.querySelector('.status-bar-buttons');
if (!editBtn || !saveBtn || !statusBarButtons) {
console.error('setupEditModeToggle: Required DOM elements missing', { editBtn, saveBtn, statusBarButtons });
return;
}
let gridSettingsInline = document.getElementById('grid-settings-inline');
/**
* Updates the inline grid settings UI based on edit mode state.
*
* Displays or hides inline controls for editing grid rows and columns when entering or exiting edit mode. Handles input validation, applies changes to the grid configuration, and updates the UI accordingly.
*/
function updateInlineSettings() {
if (appState.editMode) {
document.body.classList.add('edit-mode');
if (!gridSettingsInline) {
gridSettingsInline = document.createElement('span');
gridSettingsInline.id = 'grid-settings-inline';
gridSettingsInline.style.display = 'flex';
gridSettingsInline.style.alignItems = 'center';
gridSettingsInline.style.gap = '8px';
gridSettingsInline.innerHTML = `
<label style="color:#b0eaff;font-size:0.98em;">Rows <input id="inline-edit-rows" type="number" min="1" max="20" value="${appState.gridData.rows}" class="inline-grid-input" /></label>
<label style="color:#b0eaff;font-size:0.98em;">Cols <input id="inline-edit-cols" type="number" min="1" max="20" value="${appState.gridData.cols}" class="inline-grid-input" /></label>
<button id="inline-grid-save" style="background:#23272f;color:#00ffff;border-radius:8px;padding:2px 12px;border:none;font-weight:600;">Apply</button>
<span id="inline-grid-error" style="color:#ff5c5c;font-size:0.95em;display:none;margin-left:8px;"></span>
`;
// Insert before editBtn inside statusBarButtons
statusBarButtons.insertBefore(gridSettingsInline, editBtn);
// Style the number inputs
const style = document.createElement('style');
style.innerHTML = `.inline-grid-input { background: #181a1b; color: #b0eaff; border: 1.5px solid #00ffff44; border-radius: 6px; padding: 2px 8px; font-size: 1em; width: 48px; outline: none; transition: border 0.2s; } .inline-grid-input:invalid { border-color: #ff5c5c; background: #2a1818; }`;
document.head.appendChild(style);
// Validation logic
function validate() {
const rowsInput = document.getElementById('inline-edit-rows');
const colsInput = document.getElementById('inline-edit-cols');
const error = document.getElementById('inline-grid-error');
let valid = true;
let msg = '';
const rows = parseInt(rowsInput.value, 10);
const cols = parseInt(colsInput.value, 10);
if (isNaN(rows) || rows < 1 || rows > 20) {
valid = false;
msg = 'Rows must be 1-20.';
rowsInput.style.borderColor = '#ff5c5c';
rowsInput.style.background = '#2a1818';
} else {
rowsInput.style.borderColor = '#00ffff44';
rowsInput.style.background = '#181a1b';
}
if (isNaN(cols) || cols < 1 || cols > 20) {
valid = false;
msg = 'Cols must be 1-20.';
colsInput.style.borderColor = '#ff5c5c';
colsInput.style.background = '#2a1818';
} else {
colsInput.style.borderColor = '#00ffff44';
colsInput.style.background = '#181a1b';
}
error.textContent = msg;
error.style.display = valid ? 'none' : 'inline';
document.getElementById('inline-grid-save').disabled = !valid;
return valid;
}
document.getElementById('inline-edit-rows').addEventListener('input', validate);
document.getElementById('inline-edit-cols').addEventListener('input', validate);
document.getElementById('inline-grid-save').onclick = () => {
if (!validate()) return;
const newRows = parseInt(document.getElementById('inline-edit-rows').value, 10);
const newCols = parseInt(document.getElementById('inline-edit-cols').value, 10);
appState.gridData.rows = newRows;
appState.gridData.cols = newCols;
renderGrid(appState.gridData);
appState.unsavedChanges = true;
setSaveButtonState();
};
validate();
} else {
document.getElementById('inline-edit-rows').value = appState.gridData.rows;
document.getElementById('inline-edit-cols').value = appState.gridData.cols;
gridSettingsInline.style.display = 'flex';
}
} else if (gridSettingsInline) {
document.body.classList.remove('edit-mode');
gridSettingsInline.style.display = 'none';
}
}
editBtn.onclick = async () => {
appState.editMode = !appState.editMode;
editBtn.textContent = appState.editMode ? 'Exit Edit Mode' : 'Edit Mode';
appState.unsavedChanges = false;
setSaveButtonState();
if (appState.editMode && window.sbClient && window.sbClient.getActions) {
try {
const response = await window.sbClient.getActions();
if (response && response.status === 'ok' && Array.isArray(response.actions)) {
// Uncomment for debugging:
// if (window.DEBUG) console.log(response.actions);
appState.availableActions = response.actions;
}
} catch (e) {
appState.availableActions = [];
}
}
updateInlineSettings();
renderGrid(appState.gridData);
};
saveBtn.onclick = () => {
// Download the new layout as data.json
const exportData = {
...appState.gridData,
buttons: appState.gridData.buttons.map(btn => ({
row: btn.row,
col: btn.col,
title: btn.title,
icon: btn.icon,
action_id: btn.action_id
}))
};
const dataStr = JSON.stringify(exportData, null, 2);
const blob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'data.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
appState.unsavedChanges = false;
setSaveButtonState();
};
updateInlineSettings();
setSaveButtonState();
}
/**
* Updates the visibility and enabled state of the save button according to the current edit mode and whether there are unsaved changes.
*/
function setSaveButtonState() {
const saveBtn = document.getElementById('save-layout');
if (!saveBtn) {
console.warn('setSaveButtonState: Save button not found');
return;
}
if (appState.editMode) {
saveBtn.style.display = 'inline-block';
saveBtn.disabled = !appState.unsavedChanges;
saveBtn.classList.toggle('disabled', !appState.unsavedChanges);
} else {
saveBtn.style.display = 'none';
}
}
/**
* Attempts to establish a connection to a Streamer.bot instance on localhost at the specified port.
* Resolves with the connected client instance if successful, or rejects with a reason if the connection fails, times out, or encounters an error.
* @param {string} port - The port number to connect to.
* @param {number} [timeout=2000] - The connection timeout in milliseconds.
* @param {Function} [onConnectionLost] - Called when a connected client later disconnects or errors.
* @returns {Promise<Object>} Resolves with the connected client instance.
*/
async function tryStreamerbotClientConnect(port, timeout = 2000, onConnectionLost = () => {}) {
return new Promise((resolve, reject) => {
let resolved = false;
let connected = false;
let timer = setTimeout(() => {
if (!resolved) {
resolved = true;
if (client && client.disconnect) client.disconnect();
console.error(`[DiceDeck] Streamer.bot connection timed out (port: ${port})`);
reject({ reason: 'timeout', port });
}
}, timeout);
let client;
try {
client = new window.StreamerbotClient({
host: "127.0.0.1",
port,
onConnect: async (info) => {
clearTimeout(timer);
if (!resolved) {
resolved = true;
connected = true;
resolve(client); // Return the client instance
}
},
onDisconnect: () => {
if (!resolved) {
clearTimeout(timer);
resolved = true;
console.error(`[DiceDeck] Streamer.bot disconnected (port: ${port})`);
reject({ reason: 'disconnect', port });
} else if (connected) {
connected = false;
onConnectionLost({ reason: 'disconnect', port });
}
},
onError: () => {
if (!resolved) {
clearTimeout(timer);
resolved = true;
console.error(`[DiceDeck] Streamer.bot connection error (port: ${port})`);
reject({ reason: 'error', port });
} else if (connected) {
connected = false;
onConnectionLost({ reason: 'error', port });
}
}
});
if (getQueryParam('proxy') !== null)
client.on("General.Custom", onCustomMessage);
} catch (e) {
clearTimeout(timer);
if (!resolved) {
resolved = true;
console.error(`[DiceDeck] Exception during Streamer.bot connection (port: ${port}):`, e);
reject({ reason: e && e.message ? e.message : 'exception', port });
}
}
});
}
let pendingStreamerBotClient = null;
/**
* Processes custom backend messages, specifically handling action list responses for proxy clients.
* If the message type is `StreamerBotProxyGetActions`, routes the response to the initializing or connected proxy client.
* Logs a warning for unknown message types.
* @param {Object} message - The message object received from the backend.
*/
function onCustomMessage(message){
try {
if(message?.data?.type === "StreamerBotProxyGetActions"){
const target = pendingStreamerBotClient instanceof ProxyStreamerBotClient
? pendingStreamerBotClient
: window.sbClient;
if (target instanceof ProxyStreamerBotClient) {
// Refined JSON.parse error handling as suggested
try {
const actions = JSON.parse(message?.data?.json || '[]');
target._handleGetActionsResponse(actions);
} catch (err) {
console.error('Failed to parse actions JSON:', err);
target._rejectPendingGetActions(new Error('Failed to parse proxy action list'));
}
}
} else {
// Log unknown message types for debugging
console.warn('onCustomMessage: Unknown message type', message?.type, message);
}
}
catch (e) {
console.error(e);
}
}
/**
* Retrieves the value of a URL query parameter by name.
* @param {string} name - The name of the query parameter to retrieve.
* @return {string|null} The value of the query parameter, or null if not present.
*/
function getQueryParam(name) {
return new URLSearchParams(window.location.search).get(name);
}
// --- Adaptive Mesh Complexity ---
let meshRows = 13, meshCols = 22;
if (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4) { meshRows = 7; meshCols = 12; }
if (navigator.deviceMemory && navigator.deviceMemory <= 4) { meshRows = 7; meshCols = 12; }
const noAnim = getQueryParam('noanim') !== null;
// --- DiceDeckClient Abstraction ---
/**
* Base class for DiceDeck client implementations.
* @abstract
*/
class DiceDeckClient {
/**
* Fetches available actions.
* @returns {Promise<{status: string, actions: Array}>}
*/
async getActions() { throw new Error('Not implemented'); }
/**
* Triggers an action.
* @param {Object} params
* @returns {Promise<{status: string}>}
*/
async doAction(params) { throw new Error('Not implemented'); }
/**
* Initializes the client. Should be overridden by subclasses.
* @returns {Promise<void>}
* @throws {Error} If not implemented in subclass.
*/
async init() { throw new Error("Not implemented");}
}
/**
* Direct client implementation using the native Streamer.bot WebSocket API.
*/
class DirectStreamerBotClient extends DiceDeckClient {
/**
* @param {Object} client - The native Streamer.bot client instance.
*/
constructor(client) {
super();
this.client = client;
}
/**
* Initializes the DirectStreamerBotClient.
* This implementation does nothing and resolves immediately.
* @returns {Promise<void>}
*/
async init() {
console.log("Direct client is already connected");
return Promise.resolve();
}
/**
* Fetches available actions from the native client.
* @returns {Promise<{status: string, actions: Array}>}
*/
async getActions() {
return this.client.getActions();
}
/**
* Triggers an action on the native client.
* @param {Object} params
* @returns {Promise<{status: string}>}
*/
async doAction(params) {
return this.client.doAction(params);
}
disconnect() {
this.client.disconnect?.();
}
}
const remoteGetActions = "remoteGetActions";
const remoteDoAction = "remoteDoAction";
/**
* Proxy client implementation using RPC via localClient.doAction and async responses.
* Only one in-flight getActions is supported at a time.
*/
class ProxyStreamerBotClient extends DiceDeckClient {
constructor(localClient) {
super();
this.localClient = localClient;
this._pendingGetActions = null; // {resolve, reject, timeoutId}
this.remoteGetActionsId = null;
this.remoteDoActionId = null;
}
/**
* Initializes the ProxyStreamerBotClient by fetching local actions and mapping remote action IDs.
* @returns {Promise<void>}
*/
async init() {
try {
const localActions = await this.localClient.getActions();
this.remoteGetActionsId = localActions.actions.find(a => a.name === remoteGetActions)?.id;
this.remoteDoActionId = localActions.actions.find(a => a.name === remoteDoAction)?.id;
if (!this.remoteGetActionsId || !this.remoteDoActionId) {
const error = 'ProxyStreamerBotClient.init: Could not find remote action IDs.';
console.error(error);
throw new Error(error);
}
} catch (err) {
console.error('ProxyStreamerBotClient.init: Failed to fetch local actions:', err);
throw err;
}
}
/**
* Fetches available actions via RPC. Resolves when the response is received.
* @returns {Promise<{status: string, actions: Array}>}
*/
async getActions() {
if (this._pendingGetActions) {
return Promise.reject(new Error('A getActions call is already pending'));
}
return new Promise((resolve, reject) => {
// Set up a timeout to avoid hanging forever
const timeoutId = setTimeout(() => {
this._rejectPendingGetActions(new Error('ProxyStreamerBotClient.getActions timed out'));
}, 5000);
this._pendingGetActions = { resolve, reject, timeoutId };
this.localClient.doAction(this.remoteGetActionsId);
});
}
/**
* Called by onCustomMessage when the remote actions response arrives.
* Maps [{Item1, Item2}] to [{id, name}].
* @param {Array} actions - The actions array from the remote response.
*/
_handleGetActionsResponse(actions) {
if (!Array.isArray(actions)) {
console.error('ProxyStreamerBotClient._handleGetActionsResponse: Malformed response, expected array:', actions);
this._rejectPendingGetActions(new Error('Malformed proxy action list response'));
return;
}
if (this._pendingGetActions) {
clearTimeout(this._pendingGetActions.timeoutId);
// Map [{Item1, Item2}] to [{id, name}]
const mapped = Array.isArray(actions)
? actions.map(a => ({ id: a.Item1, name: a.Item2 }))
: [];
this._pendingGetActions.resolve({ status: 'ok', actions: mapped });
this._pendingGetActions = null;
}
}
_rejectPendingGetActions(error) {
if (!this._pendingGetActions) return;
clearTimeout(this._pendingGetActions.timeoutId);
this._pendingGetActions.reject(error);
this._pendingGetActions = null;
}
/**
* Triggers a remote action via RPC. Handles errors and parameter passing.
* @param {Object|string} params - The remote action ID or parameter object.
* @returns {Promise<{status: string, error?: any}>}
*/
async doAction(params) {
try {
// If params is just the action ID, wrap as expected by remote
const payload = typeof params === 'string' ? { remoteActionId: params } : params;
await this.localClient.doAction(this.remoteDoActionId, payload);
return { status: 'ok' };
} catch (err) {
console.error('ProxyStreamerBotClient.doAction: Failed to trigger remote action', err);
return { status: 'error', error: err };
}
}
disconnect() {
this._rejectPendingGetActions(new Error('Proxy Streamer.bot client disconnected'));
this.localClient.disconnect?.();
}
}
/**
* Returns a DiceDeck client instance, selecting either a proxy or direct implementation based on the presence of the 'proxy' URL query parameter.
* @param {Object} client - The native Streamer.bot client instance.
* @returns {DiceDeckClient} A client abstraction for communicating with Streamer.bot.
*/
function createDiceDeckClient(client) {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('proxy')) {
console.log('Creating ProxyStreamerBotClient');
return new ProxyStreamerBotClient(client);
} else {
console.log('Creating DirectStreamerBotClient');
return new DirectStreamerBotClient(client);
}
}
/**
* Performs one complete Streamer.bot connection and initialization attempt.
*
* @param {string} port - The port to connect to Streamer.bot.
* @param {Function} [onConnectionLost] - Called if the native connection is lost after opening.
* @returns {Promise<{nativeClient: Object, sbClient: DiceDeckClient, actions: Array}>} A fully initialized connection.
*/
async function setupStreamerBot(port, onConnectionLost = () => {}) {
if (!window.StreamerbotClient) {
throw new Error('StreamerbotClient not available');
}
let initializingClient = null;
const nativeClient = await tryStreamerbotClientConnect(
port || '8080',
2000,
reason => {
initializingClient?.disconnect();
onConnectionLost(reason);
},
);
return initializeDiceDeckClient(
nativeClient,
createDiceDeckClient,
client => {
initializingClient = client;
pendingStreamerBotClient = client;
},
);
}
function formatRetryDelay(delayMs) {
const seconds = delayMs / 1000;
if (seconds >= 60 && seconds % 60 === 0) {
const minutes = seconds / 60;
return `${minutes} minute${minutes === 1 ? '' : 's'}`;
}
return `${seconds} second${seconds === 1 ? '' : 's'}`;
}
function startStreamerBotConnection(port) {
const supervisor = new ConnectionSupervisor({
connect: onConnectionLost => setupStreamerBot(port, onConnectionLost),
disconnect: connection => connection.sbClient.disconnect(),
onStateChange({ state, connection, reason, delayMs }) {
const bar = document.getElementById('status-text');
if (state === 'ready') {
window.sbClient = connection.sbClient;
appState.availableActions = connection.actions;
SetConnectionStatus(true);
return;
}
window.sbClient = null;
SetConnectionStatus(false);
if (state === 'connecting') {
bar.textContent = 'Connecting to Streamer.bot...';
return;
}
const detail = reason?.reason || reason?.message || String(reason || 'disconnected');
bar.textContent = `Streamer.bot unavailable (${detail}). Retrying in ${formatRetryDelay(delayMs)}.`;
},
});
window.connectionSupervisor = supervisor;
void supervisor.start();
return supervisor;
}
/**
* Opens a modal dialog to edit the properties of a grid button, allowing changes to its title, icon, and associated action, or removal of the button.
*
* @param {number} idx - Index of the button in the grid's button array to edit.
*/
function openEditModal(idx) {
const btn = appState.gridData.buttons[idx];
if (!btn) {
console.error('openEditModal: Button not found at idx', idx);
return;
}
// Modal backdrop
const backdrop = document.createElement('div');
backdrop.className = 'edit-modal-backdrop';
// Modal
const modal = document.createElement('div');
modal.className = 'edit-modal';
modal.innerHTML = `
<button class="modal-close" title="Close">×</button>
<div class="modal-title">Edit Button</div>
<label for="edit-title">Title</label>
<input id="edit-title" type="text" value="${sanitizeString(btn.title)}" />
<label for="edit-icon">Icon Name (e.g. ic:outline-question-mark)</label>
<input id="edit-icon" type="text" value="${sanitizeString(btn.icon || '')}" placeholder="Optional iconify name" />
<label for="edit-action">Action</label>
<select id="edit-action"></select>
<div class="add-remove-btns">
<button class="remove-btn">Remove Button</button>
</div>
<div class="modal-actions">
<button id="edit-save">Save</button>
<button id="edit-cancel">Cancel</button>
</div>
`;
// Populate actions
const actionSelect = modal.querySelector('#edit-action');
if (appState.availableActions && appState.availableActions.length > 0) {
appState.availableActions.forEach(a => {
const opt = document.createElement('option');
opt.value = a.id;
opt.textContent = a.name;
// Select by action_id, fallback to action name for legacy
if ((btn.action_id && a.id === btn.action_id) || (!btn.action_id && btn.action && a.name === btn.action)) opt.selected = true;
actionSelect.appendChild(opt);
});
} else {
const opt = document.createElement('option');
opt.value = btn.action_id || '';
opt.textContent = btn.action || '';
opt.selected = true;
actionSelect.appendChild(opt);
}
// Save handler
modal.querySelector('#edit-save').onclick = () => {
btn.title = modal.querySelector('#edit-title').value;
btn.icon = modal.querySelector('#edit-icon').value.trim() || undefined;
btn.action_id = actionSelect.value;
// Remove legacy action name if present
delete btn.action;
document.body.removeChild(backdrop);
document.body.removeChild(modal);
renderGrid(appState.gridData);
appState.unsavedChanges = true;
setSaveButtonState();
};
// Remove handler
modal.querySelector('.remove-btn').onclick = () => {
appState.gridData.buttons.splice(idx, 1);
document.body.removeChild(backdrop);
document.body.removeChild(modal);
renderGrid(appState.gridData);
appState.unsavedChanges = true;
setSaveButtonState();
};
// Cancel/close handler
function closeModal() {
document.body.removeChild(backdrop);
document.body.removeChild(modal);
}
modal.querySelector('#edit-cancel').onclick = closeModal;
modal.querySelector('.modal-close').onclick = closeModal;
// Show
document.body.appendChild(backdrop);
document.body.appendChild(modal);
// Live icon preview
const iconInput = modal.querySelector('#edit-icon');
iconInput.addEventListener('input', () => {
const val = iconInput.value.trim();
let preview = modal.querySelector('.icon-preview');
if (!preview) {
preview = document.createElement('span');
preview.className = 'icon-preview button-icon';
iconInput.parentNode.insertBefore(preview, iconInput.nextSibling);
}
preview.innerHTML = val ? `<span class="iconify" data-icon="${val}"></span>` : '';
if (window.Iconify) window.Iconify.scan(preview);
});
// Initial preview
iconInput.dispatchEvent(new Event('input'));
}
/**
* Opens a modal dialog to add a new button to the grid at the specified row and column.
*
* The modal allows the user to enter a title, select an action from available actions, and optionally specify an icon. A live icon preview is shown as the icon name is entered. On saving, the new button is added to the grid, the UI is updated, and unsaved changes are marked.
* @param {number} row - The row index where the new button will be placed.
* @param {number} col - The column index where the new button will be placed.
*/
function openAddButtonModal(row, col) {
if (!appState.gridData) {
console.error('openAddButtonModal: appState.gridData is missing');
return;
}
// Modal backdrop
const backdrop = document.createElement('div');
backdrop.className = 'edit-modal-backdrop';