Repository navigation
Expand file tree
/
Copy path05-initialization.js
More file actions
2043 lines (1790 loc) · 85.1 KB
/
Copy path05-initialization.js
File metadata and controls
2043 lines (1790 loc) · 85.1 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
// SECTION 5: Initialization and Bootstrapping
// ───────────────────────────────────────────────────────────
// Cache references for UI elements (populated in injectMenu)
let bonanzaGiveawayFrame, coinHeader, countdownHeader,
coinInput, startInput, endInput, timerInput, winnersInput, customMessageInput,
scaleWinnersToggleInput, maxScaledWinnersInput, maxScaledWinnersGroup, maxScaledWinnersError,
scaleBonPerWinnerInput, scaleBonPerWinnerGroup,
donationPercentInput, donationHint,
entriesWrapper, giveawayForm,
giveawayLogPanel, giveawayLogContent,
resetButton, closeButton, minimizeButton, startButton, settingsBtn, commandsBtn, settingsMenu, commandsMenu,
remNumInput, reminderEvery, rigBadge, rigToggleInput,
hostPanelToggleBtn, hostCommandPanel, hostCommandPanelBody, hostPanelCloseBtn, hostPanelHandle,
hostPanelInitialized = false;
const hostPanelCommandState = new Map();
let maxScaledWinnersRawValue = "";
let maxScaledWinnersDebounceTimer = null;
let bonPerWinnerManuallyEdited = false;
let pendingEffectiveWinnersDisplay = null;
let lastKnownGiveawayHostKey = "";
let hostPanelResizeBound = false;
// Inject the giveaway menu into the chat UI
injectMenu();
if (REHEARSAL_MODE) {
setHostSafetyBanner(
"rehearsal",
"REHEARSAL MODE: userscript output is sent privately to the host; winner/refund gifts and BON Pool contributions are simulated only.",
"danger"
);
console.warn("[BON Giveaway] REHEARSAL MODE active: script output is redirected to a private host message; no BON-moving request will be sent.");
}
// ── Mutual exclusion with the original "Blutopia BON Giveaway" script ──
// Both scripts drive the same chat and would both try to restore and pay out
// the same giveaway after a reload. If the original is present, this script
// stands down and says so in the chat header.
function originalGiveawayScriptPresent() {
return !!document.querySelector(ORIGINAL_SCRIPT_SELECTOR);
}
function findOriginalGiveawayButton() {
const header = document.querySelector("#chatbox_header");
if (!header) return null;
const links = header.querySelectorAll("a.form__button--text");
for (const a of links) {
if (a.id === "bonanzaGiveawayBtn") continue;
const hasCoins = !!a.querySelector("i.fa-coins, i.fas.fa-coins");
const label = (a.textContent || "").trim().toLowerCase();
if (hasCoins && label === "giveaway") return a;
}
return null;
}
let conflictToastTimer = null;
function showConflictToast() {
let toast = document.getElementById("bonanzaGiveawayConflictToast");
if (!toast) {
toast = document.createElement("div");
toast.id = "bonanzaGiveawayConflictToast";
toast.setAttribute("role", "alert");
document.body.appendChild(toast);
}
toast.textContent = "DEACTIVATE THE ORIGINAL GIVEAWAY SCRIPT";
requestAnimationFrame(() => toast.classList.add("show"));
if (conflictToastTimer) clearTimeout(conflictToastTimer);
conflictToastTimer = setTimeout(() => {
toast.classList.remove("show");
conflictToastTimer = setTimeout(() => toast.remove(), 300);
}, 7000);
}
function onConflictButtonClick(ev) {
try { ev.preventDefault(); ev.stopPropagation(); } catch {}
// Ours: blink red
giveawayBTN.classList.remove("bonanza-blink-red");
void giveawayBTN.offsetWidth; // restart the animation
giveawayBTN.classList.add("bonanza-blink-red");
setTimeout(() => giveawayBTN.classList.remove("bonanza-blink-red"), 1000);
// Theirs: glow orange and shake
const orig = findOriginalGiveawayButton();
if (orig) {
orig.classList.add("bonanza-orig-btn");
orig.classList.remove("bonanza-orig-alert");
void orig.offsetWidth;
orig.classList.add("bonanza-orig-alert");
setTimeout(() => orig.classList.remove("bonanza-orig-alert"), 1000);
}
showConflictToast();
}
/**
* Put this script into conflict mode: no panel, no giveaway logic, but the
* toolbar button stays and looks normal until touched.
*/
function enterConflictMode(chatboxHeader) {
if (conflictWatchTimer) { clearInterval(conflictWatchTimer); conflictWatchTimer = null; }
try { if (bonanzaGiveawayFrame) bonanzaGiveawayFrame.remove(); } catch {}
try { releaseTabLock(); } catch {}
giveawayBTN.classList.add("bonanza-btn--conflict");
giveawayBTN.title = "Disabled: the original BON Giveaway script is also installed. Remove one of them.";
giveawayBTN.setAttribute("aria-disabled", "true");
giveawayBTN.onclick = onConflictButtonClick;
if (!giveawayBTN.isConnected) {
const host = chatboxHeader || document.querySelector("#chatbox_header div");
if (host) {
host.prepend(giveawayBTN);
giveawayBTN.parentNode.insertBefore(document.createTextNode(" "), giveawayBTN.nextSibling);
}
}
const orig = findOriginalGiveawayButton();
if (orig) orig.classList.add("bonanza-orig-btn");
console.warn("[DarkPeers BONanza Giveaway] Disabled: the original BON Giveaway script is also installed.");
}
async function injectMenu() {
const chatboxHeader = document.querySelector(`#chatbox_header div`);
if (!chatboxHeader) {
setTimeout(injectMenu, 100);
return;
}
addStyle(BUTTON_CSS, 'bonanza-giveaway-button-styles');
if (originalGiveawayScriptPresent()) {
enterConflictMode(chatboxHeader);
return;
}
// The original may inject after us; keep watching and stand down if it appears
// (unless a giveaway is already running here, in which case only warn).
let conflictWarnedDuringGiveaway = false;
conflictWatchTimer = setInterval(() => {
if (!originalGiveawayScriptPresent()) return;
if (giveawayData && isGiveawayCurrentlyActive(giveawayData)) {
if (!conflictWarnedDuringGiveaway) {
conflictWarnedDuringGiveaway = true;
logEvent("Conflict", "The original BON Giveaway script appeared while a giveaway is running. Do not reload this page until it has ended, then remove one of the scripts.");
showConflictToast();
}
return;
}
enterConflictMode(chatboxHeader);
}, 2000);
addStyle(`
/* Keep vertical spacing tight */
#bonanzaGiveawayFrame .panel__body {
gap: 2px !important;
row-gap: 2px !important;
margin-top: 2px !important;
margin-bottom: 2px !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
/* Specifically restore horizontal flex layout for the input rows */
#bonanzaGiveawayFrame .panel__body.flex-row {
display: flex !important;
flex-wrap: wrap !important;
flex-direction: row !important;
justify-content: center !important;
gap: 20px !important; /* restore horizontal spacing */
}
#bonanzaGiveawayFrame .giveaway-number-row {
width: 100%;
justify-content: center !important;
align-items: flex-end;
}
#bonanzaGiveawayFrame .giveaway-header-top-row {
display: flex;
justify-content: space-between;
align-items: center;
}
#bonanzaGiveawayFrame .giveaway-header-actions {
display: flex;
flex-direction: row;
align-items: flex-end;
justify-content: flex-end;
}
#bonanzaGiveawayFrame .giveaway-header-actions__menu-row {
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
gap: 0;
margin-top: 6px;
position: relative;
z-index: 5;
}
#bonanzaGiveawayFrame .giveaway-btn {
margin: 5px;
position: relative;
z-index: 6;
pointer-events: auto;
}
#bonanzaGiveawayFrame .giveaway-number-col {
width: 28%;
min-width: 70px;
max-width: 120px;
}
#bonanzaGiveawayFrame .giveaway-winners-row {
margin-top: 12px;
gap: 8px !important;
flex-wrap: nowrap !important;
align-self: stretch;
}
/* Custom message field should span full form width */
#bonanzaGiveawayFrame .giveaway-custom-message-row {
align-self: stretch;
width: 100% !important;
padding: 0 10px;
box-sizing: border-box;
}
/* Form groups still keep tight vertical margin */
#bonanzaGiveawayFrame .form__group {
margin-top: 2px !important;
margin-bottom: 2px !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
#bonanzaGiveawayFrame .form__text {
padding-top: 3px !important;
padding-bottom: 3px !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
#bonanzaGiveawayFrame .form__text.input-invalid {
border-color: #dc3d1d !important;
background-color: rgba(220, 61, 29, 0.16) !important;
}
#bonanzaGiveawayFrame .giveaway-inline-error {
display: none;
margin-top: 4px;
color: #ff8f7d;
font-size: 11px;
line-height: 1.2;
}
#bonanzaGiveawayFrame .giveaway-inline-error.visible {
display: block;
}
#bonanzaGiveawayFrame label.form__label {
margin-top: 0 !important;
margin-bottom: 2px !important;
line-height: 1.1 !important;
}
/* Countdown timer fix: force block and full width below form */
#bonanzaGiveawayFrame #countdownHeader {
display: block !important;
width: 100% !important;
margin-top: 10px;
margin-bottom: 10px;
text-align: center;
}
/* Entries wrapper full width with horizontal scroll if needed */
#bonanzaGiveawayFrame #entriesWrapper {
width: 100% !important;
overflow-x: auto;
margin-top: 10px;
}
/* Entries table: flex to content, but never shrink below wrapper width
and allow it to grow wider (triggering horizontal scroll). */
#bonanzaGiveawayFrame #entriesTable {
border-collapse: collapse;
table-layout: auto !important; /* override inline table-layout:fixed */
min-width: 100%; /* fill the frame at minimum */
width: auto; /* but can grow past it if needed */
}
/* General cell padding */
#bonanzaGiveawayFrame #entriesTable th,
#bonanzaGiveawayFrame #entriesTable td {
padding: 4px 6px;
}
/* User column: grow with username up to a cap, then ellipsis. */
#bonanzaGiveawayFrame #entriesTable th:nth-child(1),
#bonanzaGiveawayFrame #entriesTable td:nth-child(1) {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 260px; /* hard upper bound for username column */
}
/* Entry # column: flex to content, keep centered */
#bonanzaGiveawayFrame #entriesTable th:nth-child(2),
#bonanzaGiveawayFrame #entriesTable td:nth-child(2) {
text-align: center;
white-space: nowrap;
}
/* Prize BON column: flex to content, keep centered */
#bonanzaGiveawayFrame #entriesTable th:nth-child(3),
#bonanzaGiveawayFrame #entriesTable td:nth-child(3) {
text-align: center;
white-space: nowrap;
}
/* Gift status column: fixed-ish narrow width, centered */
#bonanzaGiveawayFrame #entriesTable th:nth-child(4),
#bonanzaGiveawayFrame #entriesTable td:nth-child(4) {
width: 70px !important;
text-align: center;
}
/* Gift verification row states (color only Entry # / Prize / Gift, not Username) */
#bonanzaGiveawayFrame #entriesTable tr.gift-pending > td:nth-child(2),
#bonanzaGiveawayFrame #entriesTable tr.gift-pending > td:nth-child(3),
#bonanzaGiveawayFrame #entriesTable tr.gift-pending > td:nth-child(4) {
background-color: rgba(255, 235, 59, 0.20) !important; /* yellow-ish */
}
#bonanzaGiveawayFrame #entriesTable tr.gift-confirmed > td:nth-child(2),
#bonanzaGiveawayFrame #entriesTable tr.gift-confirmed > td:nth-child(3),
#bonanzaGiveawayFrame #entriesTable tr.gift-confirmed > td:nth-child(4) {
background-color: rgba(76, 175, 80, 0.20) !important; /* green-ish */
}
#bonanzaGiveawayFrame #entriesTable tr.gift-self > td:nth-child(2),
#bonanzaGiveawayFrame #entriesTable tr.gift-self > td:nth-child(3),
#bonanzaGiveawayFrame #entriesTable tr.gift-self > td:nth-child(4) {
background-color: rgba(158, 158, 158, 0.20) !important; /* grey-ish */
}
#bonanzaGiveawayFrame #entriesTable tr.gift-failed > td:nth-child(2),
#bonanzaGiveawayFrame #entriesTable tr.gift-failed > td:nth-child(3),
#bonanzaGiveawayFrame #entriesTable tr.gift-failed > td:nth-child(4) {
background-color: rgba(244, 67, 54, 0.20) !important; /* red-ish */
}
/* Animated spinner for "checking" gift status */
#bonanzaGiveawayFrame .gift-spinner {
display: inline-block;
width: 14px;
height: 14px;
border-radius: 50%;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top-color: #ffeb3b; /* yellow-ish accent */
animation: giftSpinnerSpin 0.8s linear infinite;
box-sizing: border-box;
}
@keyframes giftSpinnerSpin {
to {
transform: rotate(360deg);
}
}
/* Parent container vertical stacking with spacing */
#bonanzaGiveawayFrame #giveaway_body {
display: flex !important;
flex-direction: column !important;
gap: 10px !important;
}
/* --- Improved vertical centering and layout for coinHeader --- */
#bonanzaGiveawayFrame #coinHeader.panel__heading--centered {
margin-top: 14px !important;
margin-bottom: 0 !important;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5em;
gap: 6px;
}
#bonanzaGiveawayFrame .bg-flash {
animation: bgFlashPulse 1s ease-out;
}
@keyframes bgFlashPulse {
0% {
box-shadow: 0 0 0 0 rgba(255, 192, 10, 0.6);
background-color: rgba(255, 192, 10, 0.26);
}
100% {
box-shadow: 0 0 0 10px rgba(255, 192, 10, 0);
background-color: rgba(255, 192, 10, 0);
}
}
${settingsMenuStyle}
${commandsMenuStyle}
${hostPanelStyle}
/* Silence <h1> inside <section> console warning */
#bonanzaGiveawayFrame h1.panel__heading--centered {
font-size: 1.5em;
margin: 0;
}
/* ───────── Minimized state ───────── */
#bonanzaGiveawayFrame.minimized {
height: auto !important;
min-height: 0 !important;
overflow: hidden !important;
}
#bonanzaGiveawayFrame.minimized #giveaway_body,
#bonanzaGiveawayFrame.minimized #giveaway_settings_menu,
#bonanzaGiveawayFrame.minimized #giveaway_commands_menu,
#bonanzaGiveawayFrame.minimized .giveaway-header-actions__menu-row,
#bonanzaGiveawayFrame.minimized .rigged-watermark {
display: none !important;
}
/* ───────── Rigged mode theming ───────── */
#bonanzaGiveawayFrame.rigged {
border-color: #dc3d1d !important;
box-shadow: 0 0 14px rgba(220, 61, 29, 0.75);
}
#bonanzaGiveawayFrame.rigged header.panel__heading {
background: linear-gradient(90deg, #dc3d1d, #4e0000);
color: #fff;
}
/* Watermark sits behind the content */
#bonanzaGiveawayFrame .rigged-watermark {
position: absolute;
inset: 0;
pointer-events: none;
display: none; /* default hidden */
align-items: center;
justify-content: center;
font-size: 4rem;
font-weight: 900;
opacity: 0.06;
text-transform: uppercase;
transform: rotate(-22deg);
letter-spacing: 0.25em;
}
#bonanzaGiveawayFrame.rigged .rigged-watermark {
display: flex;
animation: rigWatermarkPulse 4s ease-in-out infinite;
}
/* Pulsing badge animation */
#riggedBadge.rigged-pulse {
animation: rigPulse 1.2s ease-in-out infinite;
}
@keyframes rigPulse {
0% {
transform: scale(1);
box-shadow: none;
}
50% {
transform: scale(1.08);
box-shadow: 0 0 8px rgba(220, 61, 29, 0.8);
}
100% {
transform: scale(1);
box-shadow: none;
}
}
@keyframes rigWatermarkPulse {
0% {
opacity: 0.03;
text-shadow: none;
transform: rotate(-22deg) scale(1);
}
50% {
opacity: 0.10;
text-shadow: 0 0 10px rgba(220, 61, 29, 0.45);
transform: rotate(-22deg) scale(1.03);
}
100% {
opacity: 0.03;
text-shadow: none;
transform: rotate(-22deg) scale(1);
}
}
#bonanzaGiveawayFrame.rigged #startButton {
animation: rigStopPulse 1.5s ease-in-out infinite;
}
@keyframes rigStopPulse {
0% { transform: scale(1); }
50% { transform: scale(1.03); }
100% { transform: scale(1); }
}
`, 'bonanza-giveaway-styles');
const existingGiveawayFrame = document.getElementById("bonanzaGiveawayFrame");
if (existingGiveawayFrame) existingGiveawayFrame.remove();
document.body.insertAdjacentHTML("beforeend", frameHTML);
settingsMenu = document.getElementById('giveaway_settings_menu');
commandsMenu = document.getElementById('giveaway_commands_menu');
timerInput = document.getElementById("timerNum");
remNumInput = document.getElementById("reminderNum");
reminderEvery = document.getElementById("reminderEvery");
// Enforce whole-number minutes in the Time field (no decimals / exponent notation)
// (No page refresh required; prevents accidental fractional minutes.)
(function enforceWholeMinutesOnTimerField() {
if (!timerInput) return;
let lastValid = String(timerInput.value || "5");
const blockedKeys = new Set(['.', ',', 'e', 'E', '+', '-']);
timerInput.addEventListener('keydown', (e) => {
if (blockedKeys.has(e.key)) e.preventDefault();
});
timerInput.addEventListener('input', () => {
const v = String(timerInput.value ?? "").trim();
if (v === "") {
timerInput.setCustomValidity("");
return;
}
if (/^\d+$/.test(v)) {
const n = parseInt(v, 10);
if (Number.isFinite(n) && n >= 1) {
timerInput.setCustomValidity("");
lastValid = v;
return;
}
}
timerInput.setCustomValidity("Please enter a whole number of minutes (no decimals).");
timerInput.value = lastValid;
});
})();
bonanzaGiveawayFrame = document.getElementById('bonanzaGiveawayFrame');
settingsBtn = bonanzaGiveawayFrame.querySelector('#giveawaySettingsBtn');
commandsBtn = bonanzaGiveawayFrame.querySelector('#commandsButton');
// Create / attach "RIGGED" badge next to the version
const versionSmall = bonanzaGiveawayFrame.querySelector('header.panel__heading small');
if (versionSmall) {
rigBadge = document.createElement('span');
rigBadge.id = 'riggedBadge';
rigBadge.textContent = 'RIGGED';
rigBadge.title = "Rigged mode is purely cosmetic… allegedly.";
rigBadge.setAttribute("aria-label", "Rigged mode indicator");
rigBadge.style.cssText = `
margin-left: 8px;
padding: 2px 6px;
border-radius: 4px;
background: #dc3d1d;
color: #fff;
font-size: 0.75em;
font-weight: 700;
`;
rigBadge.hidden = true;
versionSmall.insertAdjacentElement('afterend', rigBadge);
}
// Update both when either changes
timerInput.addEventListener("input", syncReminderNumUI);
remNumInput.addEventListener("input", syncReminderNumUI);
// Call on init
syncReminderNumUI();
/* kick-start synchronisation so defaults line up on first render */
remNumInput.dispatchEvent(new Event("input"));
settingsBtn.addEventListener('click', e => {
e.stopPropagation(); // don’t bubble to outside-click
if (commandsMenu.classList.contains('open')) hardCloseCommands(); // close the other pane first
const open = settingsMenu.classList.toggle('open');
if (open) { // ---------- OPEN ----------
syncSettingsFromStorage();
settingsMenu.style.display = 'flex';
renderGiveawayLogPanel();
fitSettingsMenuHeight();
document.addEventListener('click', handleOutsideClick);
} else { // ---------- CLOSE ----------
hardCloseSettings();
}
});
chatboxHeader.prepend(giveawayBTN);
giveawayBTN.parentNode.insertBefore(document.createTextNode(" "), giveawayBTN.nextSibling);
resetButton = document.getElementById("resetButton");
resetButton.onclick = function () {
if (hasIncompleteSettlement(giveawayData)) {
window.alert(
"Reset is disabled while a giveaway settlement is incomplete. " +
"Use Retry settlement after resolving the warning; the recovery snapshot must be preserved."
);
return;
}
if (giveawayData && isGiveawayCurrentlyActive(giveawayData)) {
if (window.confirm("Are you sure you want to reset the giveaway? This will clear all entries and cannot be undone.")) {
resetGiveaway();
}
} else {
resetGiveaway();
}
};
closeButton = document.getElementById("closeButton");
closeButton.onclick = function () {
// Check if a giveaway is active
if (giveawayData && isGiveawayCurrentlyActive(giveawayData)) {
if (window.confirm("A giveaway is currently running. Are you sure you want to close the menu? This will NOT end the giveaway, but you may lose track of its progress.")) {
toggleMenu();
}
} else {
toggleMenu();
}
};
minimizeButton = document.getElementById("minimizeButton");
minimizeButton.onclick = function () {
toggleMinimize();
};
// Restore minimized state from localStorage
if (localStorage.getItem(LS_MINIMIZED) === "true") {
setMinimized(true);
}
// Toggles
const toggles = [
// For these, localStorage stores "disabled/suppressed" (true), so checked means NOT stored.
["randomToggle", "bonanza-giveaway-disableRandom", "disable_random", false],
["luckyToggle", "bonanza-giveaway-disableLucky", "disable_lucky", false],
["freeToggle", "bonanza-giveaway-disableFree", "disable_free", false],
["entryrepliesToggle", LS_SUPPRESS, "suppress_entry_replies", false],
// For silent mode / giveaway log, localStorage stores "enabled" (true), so checked mirrors stored.
["silentmodeToggle", LS_SILENT, "silent_mode", true],
["showgiveawaylogToggle", LS_SHOW_GIVEAWAY_LOG, "show_giveaway_log", true]
];
function syncSettingsFromStorage() {
for (const [id, key, setting, checkedWhenTrue = false] of toggles) {
const el = document.getElementById(id);
if (!el) continue;
const fallback = checkedWhenTrue ? false : GENERAL_SETTINGS[setting] === true;
const stored = readStoredBooleanSetting(key, fallback, true);
// If stored=true means "disabled", checkbox should be unchecked; otherwise mirror stored.
el.checked = checkedWhenTrue ? stored : !stored;
// Keep GENERAL_SETTINGS value as the stored meaning (disabled/suppressed/enabled-for-silent/show-log)
GENERAL_SETTINGS[setting] = stored;
}
}
syncSettingsFromStorage();
for (const [id, key, setting, checkedWhenTrue = false] of toggles) {
const el = document.getElementById(id);
if (!el) continue;
el.addEventListener("change", () => {
const newVal = checkedWhenTrue ? el.checked : !el.checked;
GENERAL_SETTINGS[setting] = newVal;
localStorage.setItem(key, String(newVal));
if (setting === "show_giveaway_log") {
renderGiveawayLogPanel();
}
updateHostPanelUI();
});
}
const rehearsalModeToggle = document.getElementById("rehearsalModeToggle");
if (rehearsalModeToggle) {
rehearsalModeToggle.checked = REHEARSAL_MODE;
rehearsalModeToggle.disabled = REHEARSAL_FORCED_BY_DEBUG;
if (REHEARSAL_FORCED_BY_DEBUG) {
rehearsalModeToggle.title =
"Rehearsal / Debug mode is forced by DEBUG_SETTINGS.dry_run in the userscript source.";
}
rehearsalModeToggle.addEventListener("change", () => {
const requested = !!rehearsalModeToggle.checked;
const activeHere = !!giveawayData;
const activeElsewhere = isLockedByAnotherTab();
if (activeHere || activeElsewhere) {
rehearsalModeToggle.checked = REHEARSAL_MODE;
window.alert(
"Rehearsal / Debug mode cannot be changed while a giveaway is active or recoverable. " +
"Finish or settle the giveaway first."
);
return;
}
try {
localStorage.setItem(REHEARSAL_FLAG, String(requested));
} catch {
rehearsalModeToggle.checked = REHEARSAL_MODE;
window.alert("Unable to save the Rehearsal / Debug mode setting.");
return;
}
if (!requested && REHEARSAL_FORCED_BY_QUERY) {
const cleanUrl = new URL(window.location.href);
for (const key of Array.from(cleanUrl.searchParams.keys())) {
if (key.toLowerCase() === "bg_rehearsal") {
cleanUrl.searchParams.delete(key);
}
}
window.history.replaceState(window.history.state, "", cleanUrl.toString());
}
window.location.reload();
});
}
bindSettingsSectionToggleButtons();
updateHostPanelUI();
rigToggleInput = document.getElementById("rigModeToggle");
if (rigToggleInput) {
rigToggleInput.addEventListener("change", () => {
const hostName = getLoggedInUsername();
const ctx = {
author: hostName,
fancyName: "",
args: [],
giveawayData: giveawayData || { host: hostName },
safeAuthor: sanitizeNick(hostName),
safeHost: sanitizeNick(hostName)
};
if (rigToggleInput.checked && !riggedMode) {
COMMAND_HANDLERS.rig(ctx);
} else if (!rigToggleInput.checked && riggedMode) {
COMMAND_HANDLERS.unrig(ctx);
} else {
updateRigToggleUI();
}
});
updateRigToggleUI();
}
coinHeader = document.getElementById("coinHeader");
const hostBalance = readHostBalance();
coinHeader.textContent = `${fmtBONCurrency(hostBalance)} BON`;
coinHeader.prepend(goldCoins.cloneNode(false));
coinInput = document.getElementById("giveawayAmount");
// remove formatting while editing
coinInput.addEventListener('focus', () => {
coinInput.value = coinInput.value.replace(/[^0-9]/g, '');
});
// add locale formatting on blur if it’s a valid integer
coinInput.addEventListener('blur', () => {
const raw = coinInput.value.replace(/[^0-9]/g, '');
if (/^\d+$/.test(raw)) {
coinInput.value = parseInt(raw, 10).toLocaleString();
}
});
startInput = document.getElementById("startNum");
endInput = document.getElementById("endNum");
winnersInput = document.getElementById("winnersNum");
if (pendingEffectiveWinnersDisplay != null) syncWinnersDisplayValue(pendingEffectiveWinnersDisplay);
scaleWinnersToggleInput = document.getElementById("scaleWinnersToggle");
maxScaledWinnersInput = document.getElementById("maxScaledWinnersNum");
maxScaledWinnersGroup = document.getElementById("maxScaledWinnersGroup");
maxScaledWinnersError = document.getElementById("maxScaledWinnersError");
maxScaledWinnersRawValue = String(maxScaledWinnersInput?.value || "1");
scaleBonPerWinnerInput = document.getElementById("scaleBonPerWinnerNum");
scaleBonPerWinnerGroup = document.getElementById("scaleBonPerWinnerGroup");
customMessageInput = document.getElementById("customMessage");
donationPercentInput = document.getElementById("donationPercent");
donationHint = document.getElementById("donationHint");
if (donationPercentInput) {
donationPercentInput.value = String(normalizeDonationPercent(localStorage.getItem(LS_DONATION_PERCENT)));
donationPercentInput.addEventListener("change", () => {
const pct = normalizeDonationPercent(donationPercentInput.value);
donationPercentInput.value = String(pct);
try { localStorage.setItem(LS_DONATION_PERCENT, String(pct)); } catch {}
updateDonationHint();
});
}
giveawayForm = document.getElementById("giveawayForm");
startButton = document.getElementById("startButton");
startButton.onclick = startGiveaway;
startButton.title = "Start the giveaway";
// Presets
bindPresetButtons();
refreshPresetDropdown();
countdownHeader = document.getElementById("countdownHeader");
entriesWrapper = document.getElementById("entriesWrapper");
giveawayLogPanel = document.getElementById("giveawayLogPanel");
document.getElementById("bonanzaSaveStatementBtn")?.addEventListener("click", () => downloadSelectedStatement());
document.getElementById("bonanzaCopyStatementBtn")?.addEventListener("click", () => copySelectedStatement());
renderStatementControls();
giveawayLogContent = document.getElementById("giveawayLogContent");
document.getElementById("copyGiveawayLogButton")?.addEventListener("click", copyGiveawayLogToClipboard);
document.getElementById("clearGiveawayLogButton")?.addEventListener("click", clearGiveawayLog);
renderGiveawayLogPanel();
document.body.appendChild(bonanzaGiveawayFrame);
// Draggable panel (header title row only; menu/button row is excluded)
bindHeaderInteractions();
window.addEventListener('resize', () => {
if (settingsMenu?.classList.contains('open')) fitSettingsMenuHeight();
});
timerInput.addEventListener("input", reminderAutoScaling);
startInput.addEventListener("input", entryRangeValidation);
endInput.addEventListener("input", entryRangeValidation);
winnersInput.addEventListener("input", winnersValidation);
coinInput.addEventListener("input", syncBonPerWinnerValue);
winnersInput.addEventListener("input", syncBonPerWinnerValue);
coinInput.addEventListener("input", updateDonationHint);
updateDonationHint();
if (scaleBonPerWinnerInput) {
scaleBonPerWinnerInput.addEventListener("input", () => { bonPerWinnerManuallyEdited = true; });
// If user clears the field entirely, revert to auto mode
scaleBonPerWinnerInput.addEventListener("blur", () => {
if (!String(scaleBonPerWinnerInput.value || "").trim()) {
bonPerWinnerManuallyEdited = false;
syncBonPerWinnerValue();
}
});
}
scaleWinnersToggleInput.addEventListener("change", updateScaleWinnersControls);
maxScaledWinnersInput.addEventListener("input", handleMaxScaledWinnersInput);
maxScaledWinnersInput.addEventListener("blur", () => validateMaxScaledWinnersInput({ forceMessage: true }));
updateScaleWinnersControls();
reminderAutoScaling();
updateHostPanelUI();
// ── Attempt to restore a giveaway that survived a page reload ──
const savedSnap = loadGiveawaySnapshot();
if (savedSnap) {
if (isLockedByAnotherTab()) {
// Another tab is actively running this giveaway. Do not duplicate it
console.info("[BON Giveaway] Active giveaway detected in another tab, skipping restore.");
} else {
const restored = await restoreGiveawayFromSnapshot(savedSnap);
if (restored) {
// Show the panel automatically so the host sees the restored state
bonanzaGiveawayFrame.hidden = false;
setMinimized(false);
console.info("[BON Giveaway] Restored active giveaway from snapshot.");
}
}
}
}
function ensureHostPanelToggleButton() {
if (!bonanzaGiveawayFrame) return null;
const actionsRow = bonanzaGiveawayFrame.querySelector('.giveaway-header-actions__menu-row');
if (!actionsRow) return null;
let toggle = actionsRow.querySelector('#hostPanelToggle');
if (!toggle) {
actionsRow.insertAdjacentHTML('beforeend', `
<button id="hostPanelToggle" class="form__button form__button--text giveaway-btn no-drag" data-no-drag="1" style="background-color:#ff9600;" title="Open/close host command panel.">
<i class="fa-solid fa-sliders"></i> Host Panel
</button>`);
toggle = actionsRow.querySelector('#hostPanelToggle');
}
return toggle;
}
function toggleMenu() {
bonanzaGiveawayFrame.hidden = !bonanzaGiveawayFrame.hidden;
if (!bonanzaGiveawayFrame.hidden) {
ensureHostPanelToggleButton();
updateHostPanelUI();
}
}
function setMinimized(minimized) {
if (!bonanzaGiveawayFrame) return;
const icon = minimizeButton?.querySelector("i");
if (minimized) {
bonanzaGiveawayFrame.classList.add("minimized");
if (icon) { icon.className = "fa-solid fa-window-maximize"; }
if (minimizeButton) minimizeButton.title = "Restore panel";
} else {
bonanzaGiveawayFrame.classList.remove("minimized");
if (icon) { icon.className = "fa-solid fa-window-minimize"; }
if (minimizeButton) minimizeButton.title = "Minimize panel";
}
localStorage.setItem(LS_MINIMIZED, String(minimized));
}
function toggleMinimize() {
setMinimized(!bonanzaGiveawayFrame.classList.contains("minimized"));
}
// ───────────────────────────────────────────────────────────
// Presets: save / load / delete form configurations
// ───────────────────────────────────────────────────────────
function loadPresetList() {
try {
return JSON.parse(localStorage.getItem(LS_PRESETS) || "[]");
} catch { return []; }
}
function savePresetList(presets) {
try { localStorage.setItem(LS_PRESETS, JSON.stringify(presets)); } catch {}
}
function captureFormPreset() {
return {
amount: coinInput?.value || "",
startNum: startInput?.value || "1",
endNum: endInput?.value || "50",
timer: timerInput?.value || "5",
reminders: remNumInput?.value || "0",
winners: winnersInput?.value || "1",
scaleWinners: scaleWinnersToggleInput?.checked || false,
maxScaledWinners: maxScaledWinnersInput?.value || "1",
scaleBonPerWinner: scaleBonPerWinnerInput?.value || "",
scaleBonPerWinnerCustom: bonPerWinnerManuallyEdited,
customMessage: customMessageInput?.value || "",
donationPercent: normalizeDonationPercent(donationPercentInput?.value)
};
}
function applyFormPreset(preset) {
if (!preset) return;
if (coinInput && preset.amount) coinInput.value = preset.amount;
if (startInput && preset.startNum) startInput.value = preset.startNum;
if (endInput && preset.endNum) endInput.value = preset.endNum;
if (timerInput && preset.timer) timerInput.value = preset.timer;
if (remNumInput && preset.reminders != null) remNumInput.value = preset.reminders;
if (winnersInput && preset.winners) winnersInput.value = preset.winners;
if (scaleWinnersToggleInput) {
scaleWinnersToggleInput.checked = !!preset.scaleWinners;
scaleWinnersToggleInput.dispatchEvent(new Event("change", { bubbles: true }));
}
if (maxScaledWinnersInput && preset.maxScaledWinners) maxScaledWinnersInput.value = preset.maxScaledWinners;
if (scaleBonPerWinnerInput) {
const presetBonPerWinner = String(preset.scaleBonPerWinner || "").trim();
if (preset.scaleBonPerWinnerCustom && presetBonPerWinner) {
scaleBonPerWinnerInput.value = presetBonPerWinner;
bonPerWinnerManuallyEdited = true;
} else {
bonPerWinnerManuallyEdited = false;
syncBonPerWinnerValue();
}
}
if (customMessageInput && preset.customMessage != null) customMessageInput.value = preset.customMessage;
if (donationPercentInput && preset.donationPercent != null) {
donationPercentInput.value = String(normalizeDonationPercent(preset.donationPercent));
donationPercentInput.dispatchEvent(new Event("change", { bubbles: true }));
}
// Re-sync dependent UI
syncReminderNumUI();
if (typeof entryRangeValidation === "function") entryRangeValidation();
if (typeof winnersValidation === "function") winnersValidation();
if (typeof updateScaleWinnersControls === "function") updateScaleWinnersControls();
}