-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfloating-panel-ui-queue.js
More file actions
1593 lines (1398 loc) · 63.3 KB
/
floating-panel-ui-queue.js
File metadata and controls
1593 lines (1398 loc) · 63.3 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
// /floating-panel-ui-queue.js
// Version: 1.3
//
// Documentation:
// This file contains the UI initialization logic for the prompt queue section
// within the floating panel. It finds the controls from the loaded HTML template
// and attaches the necessary event handlers and behavior.
// This function extends the window.MaxExtensionFloatingPanel namespace.
//
// Methods included:
// - initializeQueueSection(): Wires up the DOM structure for the queue UI.
// - renderQueueDisplay(): Updates the visual display of queued items.
// - updateQueueControlsState(): Manages the state of play/pause/reset buttons.
//
// Dependencies:
// - floating-panel.js: Provides the namespace and shared properties.
// - interface.js: Provides UI creation helpers like createToggle.
// - config.js: Provides configuration values like enableQueueMode.
'use strict';
const QUEUE_AUTOMATION_BUTTONS = [
{
flagProp: 'queueAutoScrollEnabled',
storageKey: 'queueAutoScrollBeforeSend',
label: 'Auto-scroll',
emoji: '🔚',
ariaLabel: 'Auto-scroll to the bottom before sending the queued prompt',
tooltip: 'Scrolls every detected scrollable area to the bottom (like pressing the End key three times) before dispatching the queued prompt.'
},
{
flagProp: 'queueBeepEnabled',
storageKey: 'queueBeepBeforeSend',
label: 'Beep',
emoji: '🔔',
ariaLabel: 'Play a confirmation beep before sending the queued prompt',
tooltip: 'Plays a short confirmation tone right before the queued prompt is sent so you can hear that the automation is about to run.'
},
{
flagProp: 'queueSpeakEnabled',
storageKey: 'queueSpeakBeforeSend',
label: 'Say "Next item"',
emoji: '🗣️',
ariaLabel: 'Announce “Next item” before sending the queued prompt',
tooltip: 'Uses the browser’s speech synthesis to say “Next item” just before the queued prompt is sent.'
},
{
flagProp: 'queueFinishBeepEnabled',
storageKey: 'queueBeepOnFinish',
label: 'Finish beep',
emoji: '🏁',
ariaLabel: 'Play a completion beep when the queue finishes sending all prompts',
tooltip: 'Plays a celebratory tone once all queued prompts have been sent.'
}
];
/**
* Initializes the queue section UI inside the floating panel.
* It finds elements from the pre-loaded HTML template and attaches functionality.
*/
window.MaxExtensionFloatingPanel.initializeQueueSection = function () {
// Get references to elements from the loaded HTML
this.queueSectionElement = document.getElementById('max-extension-queue-section');
const togglePlaceholder = document.getElementById('max-extension-queue-toggle-placeholder');
const expandableSection = this.queueSectionElement?.querySelector('.expandable-queue-controls');
this.delayInputElement = document.getElementById('max-extension-queue-delay-input');
this.delayUnitToggle = document.getElementById('max-extension-delay-unit-toggle');
this.playQueueButton = document.getElementById('max-extension-play-queue-btn');
this.skipQueueButton = document.getElementById('max-extension-skip-queue-btn');
this.resetQueueButton = document.getElementById('max-extension-reset-queue-btn');
this.queueDisplayArea = document.getElementById('max-extension-queue-display');
this.queueProgressContainer = document.getElementById('max-extension-queue-progress-container');
this.queueProgressBar = document.getElementById('max-extension-queue-progress-bar');
this.queueStatusLabel = document.getElementById('max-extension-queue-status-label');
if (!this.queueStatusLabel && this.queueProgressContainer) {
// Create it if not in HTML
this.queueStatusLabel = document.createElement('div');
this.queueStatusLabel.id = 'max-extension-queue-status-label';
this.queueStatusLabel.className = 'queue-status-label';
this.queueStatusLabel.style.cssText = 'font-size: 11px; margin-top: 4px; text-align: center; display: none;';
this.queueProgressContainer.parentNode.insertBefore(this.queueStatusLabel, this.queueProgressContainer.nextSibling);
}
this.randomDelayBadge = document.getElementById('max-extension-random-delay-toggle');
const tosWarningContainer = document.getElementById('max-extension-queue-tos-warning');
const tosAcceptButton = document.getElementById('max-extension-tos-accept-btn');
const tosDeclineButton = document.getElementById('max-extension-tos-decline-btn');
if (!this.queueSectionElement) {
logConCgp('[floating-panel-queue] Queue section element not found in the DOM.');
return;
}
if (!window.globalMaxExtensionConfig) {
window.globalMaxExtensionConfig = {};
}
this.queueFinishedState = false;
this.queueAutoScrollEnabled = Boolean(window.globalMaxExtensionConfig.queueAutoScrollBeforeSend);
this.queueBeepEnabled = Boolean(window.globalMaxExtensionConfig.queueBeepBeforeSend);
this.queueSpeakEnabled = Boolean(window.globalMaxExtensionConfig.queueSpeakBeforeSend);
this.queueFinishBeepEnabled = Boolean(window.globalMaxExtensionConfig.queueBeepOnFinish);
const delayContainer = this.randomDelayBadge?.closest('.delay-container');
if (delayContainer) {
delayContainer.classList.add('random-delay-container');
}
let randomPercentPopover = document.getElementById('max-extension-random-percent-popover');
if (!randomPercentPopover && delayContainer) {
randomPercentPopover = document.createElement('div');
randomPercentPopover.id = 'max-extension-random-percent-popover';
randomPercentPopover.className = 'max-extension-popover random-percent-popover';
randomPercentPopover.style.display = 'none';
const inner = document.createElement('div');
inner.className = 'max-extension-popover-inner';
const label = document.createElement('label');
label.className = 'max-extension-popover-label';
label.setAttribute('for', 'max-extension-random-percent-slider');
label.innerHTML = 'Random offset: <span id="max-extension-random-percent-value">5%</span>';
const slider = document.createElement('input');
slider.id = 'max-extension-random-percent-slider';
slider.type = 'range';
slider.min = '0';
slider.max = '100';
slider.step = '1';
inner.appendChild(label);
inner.appendChild(slider);
randomPercentPopover.appendChild(inner);
delayContainer.appendChild(randomPercentPopover);
} else if (randomPercentPopover && delayContainer && !delayContainer.contains(randomPercentPopover)) {
delayContainer.appendChild(randomPercentPopover);
}
this.randomPercentPopover = document.getElementById('max-extension-random-percent-popover');
this.randomPercentSlider = document.getElementById('max-extension-random-percent-slider');
this.randomPercentValueElement = document.getElementById('max-extension-random-percent-value');
// Prevent dragging when interacting with the queue section
this.queueSectionElement.addEventListener('mousedown', (event) => {
event.stopPropagation();
});
// --- DELAY INPUT AND UNIT TOGGLE LOGIC (Profile-specific) ---
const updateDelayUI = () => {
const unit = window.globalMaxExtensionConfig.queueDelayUnit || 'min';
if (unit === 'sec') {
this.delayUnitToggle.textContent = 'sec';
this.delayInputElement.value = window.globalMaxExtensionConfig.queueDelaySeconds;
this.delayInputElement.min = 10;
this.delayInputElement.max = 64000;
this.delayInputElement.title = "Delay in seconds between sending each queued prompt. Min: 10, Max: 64000.";
} else { // 'min'
this.delayUnitToggle.textContent = 'min';
this.delayInputElement.value = window.globalMaxExtensionConfig.queueDelayMinutes;
this.delayInputElement.min = 1;
this.delayInputElement.max = 64000;
this.delayInputElement.title = "Delay in minutes between sending each queued prompt. Min: 1, Max: 64000.";
}
};
updateDelayUI();
this.delayUnitToggle.addEventListener('click', (event) => {
event.preventDefault();
window.globalMaxExtensionConfig.queueDelayUnit = (window.globalMaxExtensionConfig.queueDelayUnit === 'min') ? 'sec' : 'min';
updateDelayUI();
this.saveCurrentProfileConfig(); // Save to profile
this.recalculateRunningTimer(); // Recalculate timer if it's running
});
this.delayInputElement.addEventListener('change', (event) => {
let delay = parseInt(event.target.value, 10);
const unit = window.globalMaxExtensionConfig.queueDelayUnit || 'min';
const minDelay = (unit === 'sec') ? 10 : 1;
const maxDelay = 64000;
if (isNaN(delay) || delay < minDelay) {
delay = minDelay;
} else if (delay > maxDelay) {
delay = maxDelay;
}
event.target.value = delay;
if (unit === 'sec') {
window.globalMaxExtensionConfig.queueDelaySeconds = delay;
} else { // 'min'
window.globalMaxExtensionConfig.queueDelayMinutes = delay;
}
this.saveCurrentProfileConfig(); // Save to profile
this.recalculateRunningTimer(); // Recalculate timer if it's running
});
if (this.randomPercentSlider && !this.randomPercentSlider.dataset.randomSliderBound) {
this.randomPercentSlider.dataset.randomSliderBound = 'true';
this.randomPercentSlider.addEventListener('input', (event) => {
const rawValue = Number(event.target.value);
const clampedValue = Math.min(100, Math.max(0, Math.round(rawValue)));
event.target.value = String(clampedValue);
if (!window.globalMaxExtensionConfig) {
window.globalMaxExtensionConfig = {};
}
window.globalMaxExtensionConfig.queueRandomizePercent = clampedValue;
if (this.lastQueueDelaySample) {
this.lastQueueDelaySample.percent = clampedValue;
}
if (typeof this.syncRandomPercentSlider === 'function') {
this.syncRandomPercentSlider();
}
this.updateRandomDelayBadge();
if (typeof this.saveCurrentProfileConfig === 'function') {
this.saveCurrentProfileConfig();
}
if (typeof this.recalculateRunningTimer === 'function') {
this.recalculateRunningTimer();
}
logConCgp(`[floating-panel-queue] Random delay offset slider set to ${clampedValue}%.`);
});
}
if (typeof this.syncRandomPercentSlider === 'function') {
this.syncRandomPercentSlider();
}
if (this.randomDelayBadge && !this.randomDelayBadge.dataset.randomPopoverBound) {
this.randomDelayBadge.dataset.randomPopoverBound = 'true';
this.randomDelayBadge.addEventListener('click', (event) => {
event.preventDefault();
if (event.shiftKey) {
if (typeof this.toggleRandomPercentPopover === 'function') {
this.toggleRandomPercentPopover();
}
return;
}
this.toggleRandomDelayFromBadge();
});
}
if (this.skipQueueButton) {
this.skipQueueButton.addEventListener('click', (event) => {
event.preventDefault();
if (typeof this.skipToNextQueueItem === 'function') {
this.skipToNextQueueItem();
}
});
}
if (this.queueProgressContainer) {
this.queueProgressContainer.addEventListener('mousedown', (event) => {
// Prevent dragging the panel while interacting with the progress bar.
event.stopPropagation();
});
this.queueProgressContainer.addEventListener('click', (event) => {
event.preventDefault();
if (!window.globalMaxExtensionConfig?.enableQueueMode) {
return;
}
const hasTimer = (this.isQueueRunning && this.queueTimerId) || this.remainingTimeOnPause > 0;
if (!hasTimer || !this.queueProgressBar) {
return;
}
const rect = this.queueProgressContainer.getBoundingClientRect();
if (!rect || rect.width <= 0) {
return;
}
const ratio = (event.clientX - rect.left) / rect.width;
if (typeof this.seekQueueTimerToRatio === 'function') {
this.seekQueueTimerToRatio(ratio);
}
});
}
// --- TOS Confirmation (Global) and Queue Toggle (Profile-specific) ---
const hideQueueToggle = Boolean(window.globalMaxExtensionConfig.queueHideActivationToggle);
let isQueueEnabled = Boolean(window.globalMaxExtensionConfig.enableQueueMode);
if (!isQueueEnabled) this.setQueueKeepTabActive?.(false);
if (hideQueueToggle) {
if (window.globalMaxExtensionConfig.enableQueueMode) {
window.globalMaxExtensionConfig.enableQueueMode = false;
}
this.setQueueKeepTabActive?.(false);
isQueueEnabled = false;
if (togglePlaceholder) {
togglePlaceholder.innerHTML = '';
const disabledNotice = document.createElement('div');
disabledNotice.className = 'queue-toggle-disabled-note';
disabledNotice.textContent = 'Queue disabled in settings';
togglePlaceholder.appendChild(disabledNotice);
}
const queueToggleFooter = document.getElementById('max-extension-queue-toggle-footer');
if (queueToggleFooter) {
queueToggleFooter.style.display = 'none';
}
if (expandableSection) {
expandableSection.style.display = 'none';
}
if (this.queueDisplayArea) {
this.queueDisplayArea.style.display = 'none';
}
if (this.queueSectionElement) {
this.queueSectionElement.style.display = 'none';
}
this.queueToggleForcedToFooter = false;
if (typeof this.updateQueueControlsState === 'function') {
this.updateQueueControlsState();
}
return;
} else {
const toggleCallback = (state) => {
// Check global TOS setting first
if (state && !window.MaxExtensionGlobalSettings.acceptedQueueTOS) {
// Make sure the queue section is visible so the warning isn't hidden by responsive/footer logic.
if (this.queueSectionElement) {
this.queueSectionElement.style.display = 'flex';
}
tosWarningContainer.style.display = 'block';
if (this.queueModeToggle) {
this.queueModeToggle.style.display = 'none'; // Hide toggle
const inputEl = this.queueModeToggle.querySelector('input');
if (inputEl) {
inputEl.checked = false; // Uncheck it
}
}
return;
}
// If TOS is accepted, proceed with profile setting
if (typeof this.clearQueueFinishedState === 'function') {
this.clearQueueFinishedState();
}
window.globalMaxExtensionConfig.enableQueueMode = state;
// Freeze-on-disable behavior:
if (!state) {
this.setQueueKeepTabActive?.(false);
// If it was running, pause (capture remaining time). Do not clear items.
if (this.isQueueRunning || this.remainingTimeOnPause > 0) {
logConCgp('[floating-panel-queue] Queue Mode disabled. Pausing to freeze state.');
} else {
logConCgp('[floating-panel-queue] Queue Mode disabled. Nothing running; preserving items.');
}
this.pauseQueue();
// Hide progress container while disabled (keeps bar width frozen).
if (this.queueProgressContainer) this.queueProgressContainer.style.display = 'none';
}
if (expandableSection) {
expandableSection.style.display = state ? 'contents' : 'none';
}
if (this.queueDisplayArea) {
this.queueDisplayArea.style.display = state ? 'flex' : 'none';
}
this.saveCurrentProfileConfig(); // Save to profile
// If the toggle lives in the footer, keep the queue section visible only when enabled.
const queueToggleFooter = document.getElementById('max-extension-queue-toggle-footer');
const queueSection = document.getElementById('max-extension-queue-section');
if (queueToggleFooter && queueToggleFooter.children.length > 0) {
queueSection.style.display = state ? 'flex' : 'none';
}
// Controls refresh after toggle
this.updateQueueControlsState();
if (typeof this.updateQueueTogglePlacement === 'function') {
this.updateQueueTogglePlacement();
}
if (typeof this.updateManualQueueAvailability === 'function') {
this.updateManualQueueAvailability(state);
}
};
this.queueModeToggle = MaxExtensionInterface.createToggle(
'enableQueueMode',
'Enable Queue Mode',
isQueueEnabled,
toggleCallback
);
this.queueModeToggle.style.margin = '0';
this.queueModeToggle.querySelector('label').style.fontSize = '12px';
this.queueModeToggle.title = 'When enabled, clicking buttons adds them to a queue instead of sending immediately.';
togglePlaceholder.appendChild(this.queueModeToggle);
if (expandableSection) {
expandableSection.style.display = isQueueEnabled ? 'contents' : 'none';
}
if (this.queueDisplayArea) {
this.queueDisplayArea.style.display = isQueueEnabled ? 'flex' : 'none';
}
// If queue mode is off on init but state exists, freeze (pause) and hide visuals (do not clear).
if (!isQueueEnabled && (this.isQueueRunning || (this.promptQueue && this.promptQueue.length > 0))) {
logConCgp('[floating-panel-queue] Queue Mode disabled on init. Freezing any lingering state.');
this.pauseQueue();
if (this.queueProgressContainer) this.queueProgressContainer.style.display = 'none';
}
// Initialize responsive positioning after toggle is created
if (this.initializeResponsiveQueueToggle) {
this.initializeResponsiveQueueToggle();
}
}
// TOS Button Listeners
tosAcceptButton.addEventListener('click', () => {
// 1. Update global setting
window.MaxExtensionGlobalSettings.acceptedQueueTOS = true;
this.saveGlobalSettings(); // Save global setting
// 2. Update profile setting to enable queue
window.globalMaxExtensionConfig.enableQueueMode = true;
this.saveCurrentProfileConfig(); // Save profile setting
// 3. Update UI
tosWarningContainer.style.display = 'none';
if (this.queueModeToggle) {
this.queueModeToggle.style.display = ''; // Show toggle again
const inputEl = this.queueModeToggle.querySelector('input');
if (inputEl) {
inputEl.checked = true;
}
}
if (expandableSection) expandableSection.style.display = 'contents';
if (this.queueDisplayArea) this.queueDisplayArea.style.display = 'flex';
// Ensure the queue section is visible after acceptance
if (this.queueSectionElement) {
this.queueSectionElement.style.display = 'flex';
}
if (typeof this.clearQueueFinishedState === 'function') {
this.clearQueueFinishedState();
}
// Controls become available again
this.updateQueueControlsState();
if (typeof this.updateQueueTogglePlacement === 'function') {
this.updateQueueTogglePlacement();
}
if (typeof this.updateManualQueueAvailability === 'function') {
this.updateManualQueueAvailability(true);
}
});
tosDeclineButton.addEventListener('click', () => {
tosWarningContainer.style.display = 'none';
if (this.queueModeToggle) {
this.queueModeToggle.style.display = ''; // Show toggle again
}
// Intentionally leave queue disabled; any responsive hiding will be handled by resize logic.
this.updateQueueControlsState();
if (typeof this.clearQueueFinishedState === 'function') {
this.clearQueueFinishedState();
}
if (typeof this.updateQueueTogglePlacement === 'function') {
this.updateQueueTogglePlacement();
}
if (typeof this.updateManualQueueAvailability === 'function') {
this.updateManualQueueAvailability(false);
}
});
// Attach event listeners to queue action buttons
this.playQueueButton.addEventListener('click', (event) => {
// Shift-click / Ctrl+Shift-click handler: when queue is empty and manual queue mode is on
// Shift+Click = add all valid cards only (don't start)
// Ctrl+Shift+Click = add all valid cards AND start
if (event.shiftKey && !this.isQueueRunning) {
logConCgp('[floating-panel-queue] Shift-click detected on play button. manualQueueExpanded:', this.manualQueueExpanded, 'ctrlKey:', event.ctrlKey);
// Only trigger if manual queue mode is on and queue is empty
if (!this.manualQueueExpanded) {
logConCgp('[floating-panel-queue] Manual queue mode is not active, ignoring shift-click.');
return;
}
const hasItems = this.promptQueue && this.promptQueue.length > 0;
if (hasItems) {
logConCgp('[floating-panel-queue] Queue has items, ignoring shift-click.');
return; // Only works when queue is empty
}
event.preventDefault();
// Add all valid manual cards to queue
const addedCount = this.addAllValidManualCardsToQueue();
if (addedCount > 0) {
if (event.ctrlKey) {
// Ctrl+Shift+Click: add AND start
logConCgp(`[floating-panel-queue] Ctrl+Shift-click added ${addedCount} manual cards to queue. Starting...`);
setTimeout(() => {
this.startQueue();
}, 100);
} else {
// Shift+Click only: add but don't start
logConCgp(`[floating-panel-queue] Shift-click added ${addedCount} manual cards to queue. Ready to start.`);
if (typeof window.showToast === 'function') {
window.showToast(`Added ${addedCount} card${addedCount > 1 ? 's' : ''} to queue. Click Play to start.`, 'success', 3000);
}
}
} else {
// No valid cards, show toast
if (typeof window.showToast === 'function') {
window.showToast('No valid manual queue cards to add. Enter text in at least one card.', 'warning', 3000);
}
}
return;
}
// Normal click: play/pause
if (this.isQueueRunning) {
this.pauseQueue();
} else {
this.startQueue();
}
});
this.resetQueueButton.addEventListener('click', () => {
this.resetQueue();
});
if (expandableSection) {
this.setupQueueAutomationButtons(expandableSection);
}
if (typeof this.initializeQueueDragAndDrop === 'function') {
this.initializeQueueDragAndDrop();
}
// ===== MANUAL QUEUE MODE INITIALIZATION =====
// Must be called BEFORE updateQueueControlsState so manualQueueExpanded is defined
this.initializeManualQueueMode();
this.updateQueueControlsState();
if (typeof this.updateManualQueueAvailability === 'function') {
this.updateManualQueueAvailability(isQueueEnabled);
}
};
// Default emojis for manual queue cards (supports up to 9)
const MANUAL_QUEUE_DEFAULT_EMOJIS = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣'];
const MANUAL_QUEUE_MIN_CARDS = 1;
const MANUAL_QUEUE_MAX_CARDS = 9;
const MANUAL_QUEUE_DEFAULT_COUNT = 6;
/**
* Initializes the Manual Queue Mode feature.
* Creates the 6 button cards and sets up toggle behavior.
*/
window.MaxExtensionFloatingPanel.initializeManualQueueMode = function () {
this.manualQueueModeButton = document.getElementById('max-extension-manual-queue-mode-btn');
this.manualQueueSection = document.getElementById('max-extension-manual-queue-section');
this.manualQueueCardsContainer = document.getElementById('max-extension-manual-queue-cards');
this.panelContent = document.getElementById('max-extension-floating-panel-content');
this.buttonsArea = document.getElementById('max-extension-buttons-area');
if (!this.manualQueueModeButton || !this.manualQueueSection || !this.manualQueueCardsContainer) {
logConCgp('[floating-panel-queue] Manual queue mode elements not found.');
return;
}
// Store card data locally
this.manualQueueCards = [];
this.manualQueueExpanded = false;
this.manualQueueWasExpandedBeforeDisable = false;
// Load saved card data from storage
this.loadManualQueueCards();
// Toggle button click handler
this.manualQueueModeButton.addEventListener('click', (event) => {
event.preventDefault();
this.toggleManualQueueMode();
});
};
/**
* Enables or hides manual queue UI based on queue toggle state.
* Remembers prior expansion so it can be restored when re-enabled.
* @param {boolean} queueEnabled
*/
window.MaxExtensionFloatingPanel.updateManualQueueAvailability = function (queueEnabled) {
if (!this.manualQueueModeButton || !this.manualQueueSection) return;
this.manualQueueModeButton.disabled = !queueEnabled;
if (!queueEnabled) {
this.manualQueueWasExpandedBeforeDisable = Boolean(this.manualQueueExpanded);
if (this.manualQueueExpanded && typeof this.hideManualQueueSection === 'function') {
this.hideManualQueueSection();
} else {
this.manualQueueSection.style.display = 'none';
this.manualQueueModeButton.classList.remove('active');
if (this.panelContent) {
this.panelContent.classList.remove('manual-queue-expanded');
}
}
return;
}
if (this.manualQueueWasExpandedBeforeDisable || this.manualQueueExpanded) {
this.manualQueueWasExpandedBeforeDisable = false;
if (typeof this.showManualQueueSection === 'function') {
this.showManualQueueSection();
}
}
};
/**
* Loads manual queue cards from storage and renders them.
*/
window.MaxExtensionFloatingPanel.loadManualQueueCards = async function () {
try {
const response = await new Promise((resolve, reject) => {
try {
chrome.runtime.sendMessage({ type: 'getManualQueueCards' }, (response) => {
if (chrome.runtime.lastError) {
// Extension context invalidated - this happens after extension reload
logConCgp('[floating-panel-queue] Extension context error loading cards:', chrome.runtime.lastError.message);
resolve(null);
return;
}
resolve(response);
});
} catch (e) {
reject(e);
}
});
if (response && response.data) {
this.manualQueueCards = response.data.cards || [];
this.manualQueueExpanded = response.data.expanded || false;
// Load card count, default to 6 if not set, or infer from cards array length
this.manualQueueCardCount = response.data.cardCount ||
(this.manualQueueCards.length > 0 ? this.manualQueueCards.length : MANUAL_QUEUE_DEFAULT_COUNT);
// Clamp the count to valid range
this.manualQueueCardCount = Math.max(MANUAL_QUEUE_MIN_CARDS,
Math.min(MANUAL_QUEUE_MAX_CARDS, this.manualQueueCardCount));
} else {
// Initialize with defaults
this.manualQueueCards = MANUAL_QUEUE_DEFAULT_EMOJIS.slice(0, MANUAL_QUEUE_DEFAULT_COUNT)
.map(emoji => ({ emoji, text: '' }));
this.manualQueueExpanded = false;
this.manualQueueCardCount = MANUAL_QUEUE_DEFAULT_COUNT;
}
this.renderManualQueueCards();
const queueEnabled = Boolean(window.globalMaxExtensionConfig?.enableQueueMode);
if (typeof this.updateManualQueueAvailability === 'function') {
this.updateManualQueueAvailability(queueEnabled);
} else if (this.manualQueueExpanded && queueEnabled) {
this.showManualQueueSection();
}
} catch (error) {
logConCgp('[floating-panel-queue] Error loading manual queue cards:', error);
// Initialize with defaults on error
this.manualQueueCards = MANUAL_QUEUE_DEFAULT_EMOJIS.slice(0, MANUAL_QUEUE_DEFAULT_COUNT)
.map(emoji => ({ emoji, text: '' }));
this.manualQueueExpanded = false;
this.manualQueueCardCount = MANUAL_QUEUE_DEFAULT_COUNT;
this.renderManualQueueCards();
const queueEnabled = Boolean(window.globalMaxExtensionConfig?.enableQueueMode);
if (typeof this.updateManualQueueAvailability === 'function') {
this.updateManualQueueAvailability(queueEnabled);
}
}
};
/**
* Saves manual queue cards to storage.
*/
window.MaxExtensionFloatingPanel.saveManualQueueCards = function () {
const data = {
cards: this.manualQueueCards,
expanded: this.manualQueueExpanded,
cardCount: this.manualQueueCardCount,
};
try {
chrome.runtime.sendMessage({ type: 'saveManualQueueCards', data }, (response) => {
if (chrome.runtime.lastError) {
// Extension context invalidated - silently ignore
logConCgp('[floating-panel-queue] Extension context error saving cards:', chrome.runtime.lastError.message);
return;
}
if (response && response.error) {
logConCgp('[floating-panel-queue] Error saving manual queue cards:', response.error);
}
});
} catch (e) {
logConCgp('[floating-panel-queue] Failed to save manual queue cards:', e);
}
};
/**
* Toggles the manual queue mode section visibility.
*/
window.MaxExtensionFloatingPanel.toggleManualQueueMode = function () {
if (this.manualQueueExpanded) {
this.hideManualQueueSection();
} else {
this.showManualQueueSection();
}
this.saveManualQueueCards();
};
/**
* Shows the manual queue section with cards.
*/
window.MaxExtensionFloatingPanel.showManualQueueSection = function () {
this.manualQueueExpanded = true;
this.manualQueueSection.style.display = 'block';
this.manualQueueModeButton.classList.add('active');
// Add scrollbar class to content area
if (this.panelContent) {
this.panelContent.classList.add('manual-queue-expanded');
}
// Update play button tooltip to reflect manual mode
if (typeof this.updateQueueControlsState === 'function') {
this.updateQueueControlsState();
}
};
/**
* Hides the manual queue section.
*/
window.MaxExtensionFloatingPanel.hideManualQueueSection = function () {
this.manualQueueExpanded = false;
this.manualQueueSection.style.display = 'none';
this.manualQueueModeButton.classList.remove('active');
// Remove scrollbar class from content area
if (this.panelContent) {
this.panelContent.classList.remove('manual-queue-expanded');
}
// Update play button tooltip to reflect normal mode
if (typeof this.updateQueueControlsState === 'function') {
this.updateQueueControlsState();
}
};
/**
* Renders manual queue cards based on current cardCount.
*/
window.MaxExtensionFloatingPanel.renderManualQueueCards = function () {
if (!this.manualQueueCardsContainer) return;
this.manualQueueCardsContainer.innerHTML = '';
const count = this.manualQueueCardCount || MANUAL_QUEUE_DEFAULT_COUNT;
for (let i = 0; i < count; i++) {
const cardData = this.manualQueueCards[i] || { emoji: MANUAL_QUEUE_DEFAULT_EMOJIS[i], text: '' };
const cardElement = this.createManualQueueCard(i, cardData);
this.manualQueueCardsContainer.appendChild(cardElement);
}
// Add the control card with +/- buttons
const controlCard = this.createManualQueueControlCard();
this.manualQueueCardsContainer.appendChild(controlCard);
};
/**
* Creates the thin control card with +/- buttons to add/remove manual queue cards.
* @returns {HTMLElement} The control card element.
*/
window.MaxExtensionFloatingPanel.createManualQueueControlCard = function () {
const card = document.createElement('div');
card.className = 'manual-queue-control-card';
const count = this.manualQueueCardCount || MANUAL_QUEUE_DEFAULT_COUNT;
// Remove button (-)
const removeBtn = document.createElement('button');
removeBtn.type = 'button';
removeBtn.className = 'manual-queue-control-btn manual-queue-control-remove';
removeBtn.textContent = '−';
removeBtn.title = 'Remove a card (minimum 1)';
removeBtn.disabled = count <= MANUAL_QUEUE_MIN_CARDS;
removeBtn.addEventListener('click', (event) => {
event.preventDefault();
this.removeManualQueueCard();
});
// Add button (+)
const addBtn = document.createElement('button');
addBtn.type = 'button';
addBtn.className = 'manual-queue-control-btn manual-queue-control-add';
addBtn.textContent = '+';
addBtn.title = 'Add a card (maximum 9)';
addBtn.disabled = count >= MANUAL_QUEUE_MAX_CARDS;
addBtn.addEventListener('click', (event) => {
event.preventDefault();
this.addManualQueueCard();
});
card.appendChild(removeBtn);
card.appendChild(addBtn);
return card;
};
/**
* Adds a new manual queue card (if under max limit).
*/
window.MaxExtensionFloatingPanel.addManualQueueCard = function () {
if (this.manualQueueCardCount >= MANUAL_QUEUE_MAX_CARDS) {
logConCgp('[floating-panel-queue] Cannot add more cards, already at maximum.');
return;
}
this.manualQueueCardCount++;
// Ensure the cards array has an entry for the new card
if (!this.manualQueueCards[this.manualQueueCardCount - 1]) {
this.manualQueueCards[this.manualQueueCardCount - 1] = {
emoji: MANUAL_QUEUE_DEFAULT_EMOJIS[this.manualQueueCardCount - 1],
text: ''
};
}
this.renderManualQueueCards();
this.saveManualQueueCards();
logConCgp(`[floating-panel-queue] Added manual queue card. Count: ${this.manualQueueCardCount}`);
};
/**
* Removes the last manual queue card (if above min limit).
*/
window.MaxExtensionFloatingPanel.removeManualQueueCard = function () {
if (this.manualQueueCardCount <= MANUAL_QUEUE_MIN_CARDS) {
logConCgp('[floating-panel-queue] Cannot remove more cards, already at minimum.');
return;
}
// Clear the text of the card being removed
const removedIndex = this.manualQueueCardCount - 1;
if (this.manualQueueCards[removedIndex]) {
this.manualQueueCards[removedIndex].text = '';
}
this.manualQueueCardCount--;
this.renderManualQueueCards();
this.saveManualQueueCards();
logConCgp(`[floating-panel-queue] Removed manual queue card. Count: ${this.manualQueueCardCount}`);
};
/**
* Creates a single manual queue card element.
* @param {number} index - The card index (0-5).
* @param {Object} cardData - The card data { emoji, text }.
* @returns {HTMLElement} The card element.
*/
window.MaxExtensionFloatingPanel.createManualQueueCard = function (index, cardData) {
const card = document.createElement('div');
card.className = 'manual-queue-card';
card.dataset.cardIndex = String(index);
// Add button (+)
const addBtn = document.createElement('button');
addBtn.type = 'button';
addBtn.className = 'manual-queue-card-add-btn';
addBtn.textContent = '+';
addBtn.title = 'Click: Add to queue | Shift+Click: Save as permanent button';
addBtn.addEventListener('click', (event) => {
if (event.shiftKey) {
// Shift+Click: Save as permanent button
this.saveManualCardAsPermanentButton(index);
} else {
// Normal click: Add to queue with visual feedback
this.addManualCardToQueue(index);
// Visual flash feedback
card.style.transition = 'background-color 0.15s ease';
card.style.backgroundColor = 'rgba(46, 204, 113, 0.35)';
setTimeout(() => {
card.style.backgroundColor = '';
}, 300);
}
});
// Emoji input
const emojiInput = document.createElement('input');
emojiInput.type = 'text';
emojiInput.className = 'manual-queue-card-emoji';
emojiInput.value = cardData.emoji || MANUAL_QUEUE_DEFAULT_EMOJIS[index];
emojiInput.title = 'Emoji for this prompt (shown in queue)';
emojiInput.addEventListener('input', () => {
this.updateManualCardEmoji(index, emojiInput.value);
});
emojiInput.addEventListener('blur', () => {
// Restore default emoji if empty
if (!emojiInput.value.trim()) {
emojiInput.value = MANUAL_QUEUE_DEFAULT_EMOJIS[index];
this.updateManualCardEmoji(index, emojiInput.value);
}
});
// Text input - using textarea for multiline support with auto-resize
const textInput = document.createElement('textarea');
textInput.className = 'manual-queue-card-text';
textInput.value = cardData.text || '';
textInput.placeholder = 'Enter prompt text...';
textInput.title = 'Prompt text to send';
textInput.rows = 1;
textInput.style.resize = 'none';
textInput.style.overflow = 'hidden';
// Auto-resize function
const autoResize = () => {
textInput.style.height = 'auto';
const computed = window.getComputedStyle(textInput);
const lineHeight = parseFloat(computed.lineHeight) || 18;
const padding = parseFloat(computed.paddingTop) + parseFloat(computed.paddingBottom);
const minHeight = lineHeight + padding;
const newHeight = Math.max(minHeight, textInput.scrollHeight);
textInput.style.height = `${newHeight}px`;
};
textInput.addEventListener('input', () => {
this.updateManualCardText(index, textInput.value);
autoResize();
});
// Initial auto-resize after DOM insertion
setTimeout(autoResize, 0);
card.appendChild(addBtn);
card.appendChild(emojiInput);
card.appendChild(textInput);
return card;
};
/**
* Saves a manual queue card as a permanent custom button in the current profile.
* @param {number} index - Card index.
*/
window.MaxExtensionFloatingPanel.saveManualCardAsPermanentButton = function (index) {
const cardData = this.manualQueueCards[index];
if (!cardData) {
logConCgp('[floating-panel-queue] Manual card data not found for index:', index);
return;
}
const text = (cardData.text || '').trim();
// Validation: text must not be empty
if (!text) {
if (typeof window.showToast === 'function') {
window.showToast('Cannot save empty prompt as button', 'error', 3000);
}
return;
}
// Get emoji (use default if empty)
let emoji = (cardData.emoji || '').trim();
if (!emoji) {
emoji = MANUAL_QUEUE_DEFAULT_EMOJIS[index];
}
// Add to current profile's customButtons
if (!window.globalMaxExtensionConfig) {
logConCgp('[floating-panel-queue] No global config available');
return;
}
if (!Array.isArray(window.globalMaxExtensionConfig.customButtons)) {
window.globalMaxExtensionConfig.customButtons = [];
}
const newButton = {
icon: emoji,
text: text,
autoSend: true // Default to autosend for convenience
};
window.globalMaxExtensionConfig.customButtons.push(newButton);
// Save the profile
if (typeof this.saveCurrentProfileConfig === 'function') {
this.saveCurrentProfileConfig();
}
if (typeof window.showToast === 'function') {
window.showToast(`Saved "${emoji}" as permanent button`, 'success', 3000);
}
logConCgp(`[floating-panel-queue] Saved manual card ${index} as permanent button:`, text.substring(0, 30) + '...');
};