-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbuttons.js
More file actions
1768 lines (1564 loc) · 73.5 KB
/
Copy pathbuttons.js
File metadata and controls
1768 lines (1564 loc) · 73.5 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
// buttons.js
/*
Version: 1.0
Documentation:
Button creation + click orchestration.
- Builds both custom send buttons (from profile/global config) and Cross-Chat buttons ("Copy", "Paste").
- Assigns numeric shortcuts (1–10) to the first 10 non-separator buttons (configurable via globalMaxExtensionConfig.enableShortcuts).
- Composes titles that include autosend status and shortcut hints.
- Handles click behavior across supported sites and integrates with queue mode in the floating panel.
Exposed methods:
- MaxExtensionButtons.createCustomSendButton(buttonConfig, index, onClickHandler, overrideShortcutKey?)
- MaxExtensionButtons.createCrossChatButton(type: 'copy'|'paste', shortcutKey?)
- MaxExtensionButtons.determineShortcutKeyForButtonIndex(buttonIndex, offset?)
Click flow:
- processCustomSendButtonClick(event, customText, autoSend)
* Shift inverts autoSend at click time.
* If the floating panel is visible and queue mode is enabled, the button is enqueued instead of sending immediately.
* Routes to site-specific handlers based on InjectionTargetsOnWebsite.activeSite:
- ChatGPT, Claude, Copilot, DeepSeek, AIStudio, Grok, Gemini
Cross-Chat notes:
- "Copy": reads from the active editor, saves via service worker, briefly shows "Copied!" in tooltip,
and triggers autosend with the existing text when configured.
- "Paste": fetches stored prompt; tooltip shows a debounced preview on hover.
Usage:
Load order should ensure `utils.js` and any site-specific clicking modules are present before use.
Rendering order and placement are orchestrated by buttons-init-and-render.js; this file focuses on element creation and behavior.
Depends on:
- utils.js (selectors and shared utilities)
- buttons-init-and-render.js (composition/placement)
- per-website-button-clicking-mechanics/buttons-clicking-*.js (site handlers: chatgpt/claude/copilot/deepseek/aistudio/grok/gemini)
Instructions for AI: do not remove comments! MUST NOT REMOVE COMMENTS. This one too!
*/
'use strict';
// Escape tooltip body text so user-provided strings don't break HTML parsing in the tooltip renderer.
const escapeTooltipHtml = (text) => {
if (text === null || text === undefined) return '';
return String(text)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
const OCP_PROMPT_VARIABLES_STORAGE_KEY = 'ocpPromptVariablesSettings';
window.MaxExtensionPromptVariables = {
storageKey: OCP_PROMPT_VARIABLES_STORAGE_KEY,
dateExampleText: 'Today is {{today}}.',
dateExampleIcon: '📅',
shineDurationMs: 15000,
shineState: null,
createTokenPattern() {
return /\{\{\s*(today|date|time)\s*\}\}|\{\{\s*(?:var|variable)\s*:\s*([^}]+?)\s*\}\}|\{%\{\s*([^}%]+?)\s*\}%\}/gi;
},
normalizeSettings(settings = {}) {
const rawVariables = Array.isArray(settings.customVariables) ? settings.customVariables : [];
return {
enabled: settings.enabled === true,
dateExampleInitialized: settings.dateExampleInitialized === true,
customVariables: rawVariables
.filter(item => item && typeof item === 'object')
.map(item => ({
name: String(item.name || '').trim(),
value: String(item.value ?? '')
}))
.filter(item => item.name)
};
},
async loadSettings() {
try {
const result = await chrome.storage.local.get([this.storageKey]);
return this.normalizeSettings(result?.[this.storageKey]);
} catch (error) {
logConCgp('[prompt-vars] Failed loading settings:', error?.message || error);
return this.normalizeSettings();
}
},
async saveSettings(settings, options = {}) {
const normalized = this.normalizeSettings(settings);
await chrome.storage.local.set({ [this.storageKey]: normalized });
return normalized;
},
async ensureFirstRunDateExampleButton(config) {
if (!config || !Array.isArray(config.customButtons)) {
return config;
}
const settings = await this.loadSettings();
if (settings.dateExampleInitialized) {
return config;
}
const alreadyExists = config.customButtons.some(button => (
button &&
!button.separator &&
(button.__ocpSmartVariableExample === 'today' || button.text === this.dateExampleText)
));
await this.saveSettings({ ...settings, dateExampleInitialized: true }, { silent: true });
if (alreadyExists) {
return config;
}
const exampleButton = {
icon: this.dateExampleIcon,
text: this.dateExampleText,
autoSend: false,
__ocpSmartVariableExample: 'today'
};
config.customButtons.push(exampleButton);
this.markButtonForShine(config.customButtons.length - 1, 'today');
try {
const { currentProfile } = await chrome.storage.local.get('currentProfile');
const profileName = currentProfile || config.PROFILE_NAME;
if (profileName) {
await chrome.runtime.sendMessage({
type: 'saveConfig',
profileName,
config
});
}
} catch (error) {
logConCgp('[prompt-vars] Failed saving first-run date example:', error?.message || error);
}
return config;
},
markButtonForShine(profileIndex, kind = '') {
this.shineState = {
profileIndex,
kind,
until: Date.now() + this.shineDurationMs
};
},
shouldShineButton(buttonConfig, profileIndex) {
const state = this.shineState;
if (!state || Date.now() > state.until) {
this.shineState = null;
return false;
}
if (Number.isInteger(profileIndex) && profileIndex === state.profileIndex) {
return true;
}
return state.kind && buttonConfig?.__ocpSmartVariableExample === state.kind;
},
applyShine(buttonElement) {
if (!buttonElement) return;
this.ensureStyles();
buttonElement.classList.add('ocp-smart-vars-new-button');
setTimeout(() => {
buttonElement.classList.remove('ocp-smart-vars-new-button');
}, this.shineDurationMs);
},
async resolvePromptText(rawText, context = {}) {
if (typeof rawText !== 'string') {
return rawText;
}
if (!rawText.includes('{{') && !rawText.includes('{%{')) {
return rawText;
}
const settings = await this.loadSettings();
if (!settings.enabled) {
return rawText;
}
const tokens = this.collectTokens(rawText);
if (!tokens.hasAny) {
return rawText;
}
const builtins = {};
if (tokens.builtins.has('today')) {
builtins.today = this.formatToday();
}
if (tokens.builtins.has('date')) {
builtins.date = this.formatDate();
}
if (tokens.builtins.has('time')) {
builtins.time = this.formatTime();
}
const customValues = {};
const customLookup = new Map(
settings.customVariables.map(variable => [variable.name.toLowerCase(), variable])
);
for (const name of tokens.customNames) {
const variable = customLookup.get(name.toLowerCase());
customValues[name] = variable ? variable.value : '';
}
return rawText.replace(this.createTokenPattern(), (match, builtinName, customName, aliasName) => {
if (builtinName) {
return builtins[builtinName.toLowerCase()] ?? '';
}
const resolvedCustomName = this.normalizeVariableName(customName || aliasName);
return customValues[resolvedCustomName] ?? '';
});
},
collectTokens(rawText) {
const builtins = new Set();
const customNames = [];
const addUnique = (list, value) => {
const normalized = this.normalizeVariableName(value);
if (normalized && !list.includes(normalized)) {
list.push(normalized);
}
};
for (const match of rawText.matchAll(this.createTokenPattern())) {
if (match[1]) {
builtins.add(match[1].toLowerCase());
} else if (match[2]) {
addUnique(customNames, match[2]);
} else if (match[3]) {
addUnique(customNames, match[3]);
}
}
return {
builtins,
customNames,
hasAny: builtins.size > 0 || customNames.length > 0
};
},
normalizeVariableName(name) {
return String(name || '').trim();
},
formatToday(date = new Date()) {
const pad = (value) => String(value).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
},
formatDate(date = new Date()) {
const pad = (value) => String(value).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
},
formatTime(date = new Date()) {
const pad = (value) => String(value).padStart(2, '0');
return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
},
ensureStyles() {
if (document.getElementById('ocp-smart-vars-styles')) return;
const style = document.createElement('style');
style.id = 'ocp-smart-vars-styles';
style.textContent = `
@keyframes ocp-smart-vars-button-shine {
0%, 100% {
box-shadow: 0 0 0 rgba(37, 99, 235, 0);
transform: translateY(0);
}
45% {
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.25), 0 0 18px rgba(37, 99, 235, 0.9);
transform: translateY(-1px);
}
}
.ocp-smart-vars-new-button {
border-radius: 8px !important;
animation: ocp-smart-vars-button-shine 1.25s ease-in-out infinite;
}
`;
document.documentElement.appendChild(style);
},
__toast(message, type = 'info', options = 3000) {
if (typeof window.showToast === 'function') {
window.showToast(message, type, options);
}
}
};
/**
* Namespace object containing functions related to creating and managing custom buttons.
*/
window.MaxExtensionButtons = {
/**
* Creates a cross-chat prompt sharing button ('Copy' or 'Paste').
* @param {string} type - The type of button, either 'copy' or 'paste'.
* @param {number|null} shortcutKey - The shortcut key (1-10) to assign, or null.
* @returns {HTMLButtonElement} - The newly created button element.
*/
createCrossChatButton: function (type, shortcutKey) {
const buttonElement = document.createElement('button');
buttonElement.type = 'button';
buttonElement.style.cssText = `
background-color: transparent;
border: none;
cursor: pointer;
padding: 1px;
font-size: 20px;
margin-right: 5px;
margin-bottom: 5px;
`;
if (type === 'broadcast') {
const ICON_ACTIVE = '⬆️';
const ICON_SHIELD = '😷';
const isShielded = () => window.__OCP_dangerReceiveBlocked === true;
const setShielded = (value) => {
window.__OCP_dangerReceiveBlocked = !!value;
};
const buildTooltip = () => {
const intro = 'Broadcast stored prompt to every supported tab - resulting in the other tabs will autosend messages.';
const shieldInfo = isShielded()
? ' • This tab is shielding itself from incoming broadcasts.'
: ' • This tab will receive and auto-send broadcasts.';
return `${intro}. Danger: this .${shieldInfo} Shift+Click to toggle the shield.`;
};
const updateBroadcastVisuals = () => {
buttonElement.innerHTML = isShielded() ? ICON_SHIELD : ICON_ACTIVE;
buttonElement.setAttribute('title', buildTooltip());
};
updateBroadcastVisuals();
buttonElement.addEventListener('click', (event) => {
event.preventDefault();
if (event.shiftKey) {
const nextState = !isShielded();
setShielded(nextState);
updateBroadcastVisuals();
if (typeof window.showToast === 'function') {
window.showToast(nextState
? 'Incoming danger broadcasts are blocked in this tab.'
: 'This tab will accept danger broadcasts again.', 'info');
}
return;
}
if (!window.globalCrossChatConfig?.dangerAutoSendAll) {
if (typeof window.showToast === 'function') {
window.showToast('Enable "Danger: Auto sent to all instances of chats" in the popup first.', 'warning');
}
return;
}
const selectors = window?.InjectionTargetsOnWebsite?.selectors?.editors || [];
const editor = selectors
.map(selector => document.querySelector(selector))
.find(el => el);
if (!editor) {
logConCgp('[buttons-cross-chat] Editor area not found for broadcast.');
if (typeof window.showToast === 'function') {
window.showToast('Could not locate the chat editor for broadcasting.', 'error');
}
return;
}
const rawText = editor.value || editor.innerText || '';
const trimmed = typeof rawText === 'string' ? rawText.trim() : '';
if (!trimmed) {
if (typeof window.showToast === 'function') {
window.showToast('Nothing to send. Type your prompt first.', 'warning');
}
return;
}
chrome.runtime.sendMessage({ type: 'saveStoredPrompt', promptText: rawText }, () => {
logConCgp('[buttons-cross-chat] Prompt saved for broadcast.');
});
const localDispatchEvent = {
preventDefault() { },
stopPropagation() { },
__fromDangerBroadcast: true,
__fromQueue: true,
shiftKey: false,
};
processCustomSendButtonClick(localDispatchEvent, '', true);
chrome.runtime.sendMessage({
type: 'triggerDangerCrossChatSend',
promptText: trimmed
}, (response) => {
const dispatched = response?.dispatched || 0;
const failed = response?.failed || 0;
const skipped = response?.skipped || 0;
if (!response?.success) {
logConCgp('[buttons-cross-chat] Danger broadcast request failed or was rejected.', {
reason: response?.reason || response?.error || '',
dispatched,
failed,
skipped,
reasons: response?.reasons || []
});
if (typeof window.showToast === 'function') {
let failMessage;
if (failed > 0) {
failMessage = `Broadcast rejected by all ${failed} tab${failed === 1 ? '' : 's'}.`;
} else if ((response?.reason === 'noRecipientsReachable') && skipped > 0) {
failMessage = 'No other tabs are ready to receive this broadcast.';
} else {
failMessage = 'Broadcast failed or was rejected by other tabs.';
}
window.showToast(failMessage, 'error');
}
return;
}
logConCgp('[buttons-cross-chat] Danger broadcast results.', { dispatched, failed, skipped, reasons: response?.reasons || [] });
if (typeof window.showToast === 'function') {
let message = `Broadcast sent to ${dispatched} other tab${dispatched === 1 ? '' : 's'}.`;
if (failed > 0) {
message += ` ${failed} tab${failed === 1 ? '' : 's'} declined.`;
}
const toastType = failed > 0 ? 'warning' : 'success';
window.showToast(message, toastType);
}
});
});
return buttonElement;
}
const icons = { copy: '📋', paste: '📥' };
const baseTooltips = { copy: 'Copy prompt from input area', paste: 'Paste stored prompt' };
buttonElement.innerHTML = icons[type];
const autoSendEnabled = (type === 'copy')
? window.globalCrossChatConfig?.autosendCopy
: window.globalCrossChatConfig?.autosendPaste;
const autoSendDescription = autoSendEnabled
? ' <span class="ocp-tooltip__system-msg"><i><b>(Auto-sends)</b></i></span>'
: '';
let shortcutDescription = '';
if (shortcutKey) {
const fallbackHotkey = window.MaxExtensionHotkeys?.fromLegacyShortcutKey(shortcutKey);
buttonElement.dataset.shortcutKey = shortcutKey.toString();
if (fallbackHotkey) {
buttonElement.dataset.hotkeyCombo = fallbackHotkey.combo;
shortcutDescription = ` <span class="ocp-tooltip__system-msg"><i><b>(Shortcut: ${fallbackHotkey.label})</b></i></span>`;
}
}
const updateTooltip = (text) => {
const safeText = escapeTooltipHtml(text);
buttonElement.setAttribute('title', safeText + autoSendDescription + shortcutDescription);
};
updateTooltip(baseTooltips[type]);
buttonElement.addEventListener('click', (event) => {
event.preventDefault();
if (type === 'copy') {
const editorSelectors = window?.InjectionTargetsOnWebsite?.selectors?.editors;
const editor = (Array.isArray(editorSelectors) ? editorSelectors : [])
.map((selector) => {
try {
return document.querySelector(selector);
} catch (_) {
return null;
}
})
.find((el) => el);
if (!editor) {
logConCgp('[buttons-cross-chat] Editor area not found for copy.');
return;
}
const text = editor.value || editor.innerText || '';
chrome.runtime.sendMessage({ type: 'saveStoredPrompt', promptText: text }, () => {
logConCgp('[buttons-cross-chat] Prompt saved.');
updateTooltip('Copied!');
setTimeout(() => updateTooltip(baseTooltips.copy), 1500);
});
const autoSend = window.globalCrossChatConfig?.autosendCopy;
processCustomSendButtonClick(event, '', autoSend);
} else if (type === 'paste') {
chrome.runtime.sendMessage({ type: 'getStoredPrompt' }, (response) => {
if (response?.promptText) {
const autoSend = window.globalCrossChatConfig.autosendPaste;
processCustomSendButtonClick(event, response.promptText, autoSend);
} else {
logConCgp('[buttons-cross-chat] No prompt to paste.');
updateTooltip('*No prompt has been saved*');
setTimeout(() => updateTooltip(baseTooltips.paste), 2000);
}
});
}
});
if (type === 'paste') {
let tooltipFetchTimeout;
buttonElement.addEventListener('mouseover', () => {
clearTimeout(tooltipFetchTimeout);
tooltipFetchTimeout = setTimeout(() => {
chrome.runtime.sendMessage({ type: 'getStoredPrompt' }, (response) => {
const promptText = response?.promptText;
if (promptText) {
const truncatedPrompt = promptText.length > 200 ? promptText.substring(0, 197) + '...' : promptText;
updateTooltip(truncatedPrompt);
} else {
updateTooltip('*No prompt has been saved*');
}
});
}, 300);
});
buttonElement.addEventListener('mouseout', () => {
clearTimeout(tooltipFetchTimeout);
updateTooltip(baseTooltips.paste);
});
}
return buttonElement;
},
/**
* Creates a custom send button based on the provided configuration.
* @param {Object} buttonConfig - The configuration object for the custom button.
* @param {number} buttonIndex - The index of the button in the custom buttons array.
* @param {Function} onClickHandler - The function to handle the button's click event.
* @param {number|null|undefined} [overrideShortcutKey] - Optional shortcut key. Use null to suppress legacy fallback.
* @returns {HTMLButtonElement} - The newly created custom send button element.
*/
createCustomSendButton: function (buttonConfig, buttonIndex, onClickHandler, overrideShortcutKey = undefined) {
const customButtonElement = document.createElement('button');
customButtonElement.type = 'button'; // Prevent form being defaut type, that is "submit".
customButtonElement.innerHTML = buttonConfig.icon;
customButtonElement.setAttribute('data-testid', `custom-send-button-${buttonIndex}`);
// Assign keyboard shortcuts to the first 10 non-separator buttons if shortcuts are enabled
let assignedShortcutKey = overrideShortcutKey;
if (assignedShortcutKey === undefined && globalMaxExtensionConfig.enableShortcuts) {
assignedShortcutKey = this.determineShortcutKeyForButtonIndex(buttonIndex, 0); // Pass 0 as offset for old logic
}
const explicitHotkey = window.MaxExtensionHotkeys?.normalizeStoredHotkey(buttonConfig.hotkey);
const fallbackHotkey = explicitHotkey
? null
: window.MaxExtensionHotkeys?.fromLegacyShortcutKey(assignedShortcutKey);
const effectiveHotkey = explicitHotkey || fallbackHotkey;
if (assignedShortcutKey !== null && assignedShortcutKey !== undefined && !explicitHotkey) {
customButtonElement.dataset.shortcutKey = assignedShortcutKey.toString();
}
if (effectiveHotkey) {
customButtonElement.dataset.hotkeyCombo = effectiveHotkey.combo;
}
// Prepare tooltip parts: append (Auto-sends) if autoSend behavior is enabled
// We wrap these in a specific class so the tooltip system can strip them out and place them in the footer,
// preventing them from being truncated if the main text is long.
const autoSendDescription = buttonConfig.autoSend
? ' <span class="ocp-tooltip__system-msg"><i><b>(Auto-sends)</b></i></span>'
: '';
const shortcutDescription = effectiveHotkey
? ` <span class="ocp-tooltip__system-msg"><i><b>(Shortcut: ${effectiveHotkey.label})</b></i></span>`
: '';
// Set the tooltip (title attribute) combining the button text (or a custom tooltip) with auto-send and shortcut info
const baseTooltipText = escapeTooltipHtml(buttonConfig.tooltip || buttonConfig.text);
customButtonElement.setAttribute('title', `${baseTooltipText}${autoSendDescription}${shortcutDescription}`);
customButtonElement.style.cssText = `
background-color: transparent;
border: none;
cursor: pointer;
padding: 1px;
font-size: 20px;
margin-right: 5px;
margin-bottom: 5px;
`;
// Attach the click event listener to handle custom send actions
customButtonElement.addEventListener('click', (event) => onClickHandler(event, buttonConfig.text, buttonConfig.autoSend));
return customButtonElement;
},
/**
* Copies the last ChatGPT assistant response. It prefers ChatGPT's native copy
* button so copied formatting matches ChatGPT behavior, with a direct text
* clipboard fallback if that button is unavailable.
* @param {Event} event
* @returns {Promise<Object>}
*/
copyLastChatGPTResponse: async function (event) {
if (event && typeof event.preventDefault === 'function') {
event.preventDefault();
}
if (event && typeof event.stopPropagation === 'function') {
event.stopPropagation();
}
const activeSite = window?.InjectionTargetsOnWebsite?.activeSite;
if (activeSite !== 'ChatGPT') {
this.__toast('Copy last response is only active on ChatGPT.', 'info');
return { status: 'failed', reason: 'wrong_site' };
}
const messageRoot = this.__findLastChatGPTAssistantMessage();
if (!messageRoot) {
this.__toast('Could not find the last ChatGPT response.', 'error');
logConCgp('[buttons][ChatGPT-copy] Last assistant response not found.');
return { status: 'failed', reason: 'response_not_found' };
}
const nativeCopyButton = this.__findChatGPTResponseCopyButton(messageRoot);
if (nativeCopyButton) {
nativeCopyButton.click();
this.__toast('Copied last ChatGPT response.', 'success');
logConCgp('[buttons][ChatGPT-copy] Clicked native ChatGPT copy button.');
return { status: 'success', copiedVia: 'native_copy_button' };
}
const responseText = this.__extractChatGPTResponseText(messageRoot);
if (!responseText.trim()) {
this.__toast('Found the response, but it looked empty.', 'warning');
logConCgp('[buttons][ChatGPT-copy] Response text extraction returned empty text.');
return { status: 'failed', reason: 'empty_response' };
}
try {
await this.__writeTextToClipboard(responseText);
this.__toast('Copied last ChatGPT response.', 'success');
logConCgp('[buttons][ChatGPT-copy] Copied response text with fallback clipboard path.');
return { status: 'success', copiedVia: 'text_fallback' };
} catch (error) {
this.__toast('Could not copy the last ChatGPT response.', 'error');
logConCgp('[buttons][ChatGPT-copy] Clipboard write failed:', error?.message || error);
return { status: 'failed', reason: 'clipboard_failed' };
}
},
/**
* Queues the current editor text, clears the editor for the next item, and
* starts the existing queue engine with the configured initial delay.
* @param {Event} event
* @returns {Promise<Object>}
*/
queueCurrentEditorText: async function (event, defaultDelaySeconds) {
if (event && typeof event.preventDefault === 'function') {
event.preventDefault();
}
if (event && typeof event.stopPropagation === 'function') {
event.stopPropagation();
}
// Shift + click on Queue button opens slider + entry flyout over cursor to edit delay in seconds
if (event && event.shiftKey) {
try {
window.MaxExtensionButtons.__showDelayFlyout(event);
} catch (err) {
logConCgp('[buttons][queue] Error showing delay flyout:', err?.message || err);
if (typeof window.showToast === 'function') {
window.showToast('Could not open queue delay settings.', 'error');
}
}
return { status: 'flyout_opened' };
}
const queue = window.MaxExtensionFloatingPanel;
// Apply custom defaultDelaySeconds if provided on regular click and no config exists yet
if (defaultDelaySeconds !== undefined && defaultDelaySeconds !== null) {
const parsedDelay = parseInt(defaultDelaySeconds, 10);
if (Number.isFinite(parsedDelay) && parsedDelay > 0) {
if (!window.globalMaxExtensionConfig) {
window.globalMaxExtensionConfig = {};
}
if (window.globalMaxExtensionConfig.queueDelaySeconds === undefined) {
window.globalMaxExtensionConfig.queueDelaySeconds = parsedDelay;
window.globalMaxExtensionConfig.queueDelayUnit = 'sec';
if (queue && typeof queue.recalculateRunningTimer === 'function') {
queue.recalculateRunningTimer();
}
if (queue && typeof queue.syncQueueModeUiFromConfig === 'function') {
queue.syncQueueModeUiFromConfig();
}
}
}
}
const editor = this.__findActiveEditor();
if (!editor) {
this.__toast('Could not find the chat editor.', 'error');
logConCgp('[buttons][queue] Editor not found.');
return { status: 'failed', reason: 'editor_not_found' };
}
const text = this.__readEditorText(editor).trim();
if (!text) {
this.__toast('Nothing to queue. Type text in the editor first.', 'warning');
return { status: 'failed', reason: 'empty_editor' };
}
if (!queue || typeof queue.addToQueue !== 'function' || typeof queue.startQueue !== 'function') {
this.__toast('Queue engine is not ready on this page.', 'error');
return { status: 'failed', reason: 'queue_unavailable' };
}
if (!window.globalMaxExtensionConfig) {
window.globalMaxExtensionConfig = {};
}
window.globalMaxExtensionConfig.enableQueueMode = true;
if (typeof queue.syncQueueModeUiFromConfig === 'function') {
queue.syncQueueModeUiFromConfig();
}
if (typeof queue.saveCurrentProfileConfig === 'function') {
queue.saveCurrentProfileConfig();
}
const container = event?.target?.closest?.('[id$="-custom-buttons-container"]');
if (container && typeof queue.ensureInlineQueueControls === 'function') {
queue.ensureInlineQueueControls(container);
}
const queuedItem = queue.addToQueue({
icon: event?.target?.innerHTML || '⏳',
text,
autoSend: true,
source: 'editor-queue-button'
});
if (!queuedItem) {
this.__toast('Queue is full or unavailable. Editor text was not cleared.', 'error');
return { status: 'failed', reason: 'queue_add_failed' };
}
queue.lastQueuedEditorText = text;
queue.queuedEditorTextCache = Array.isArray(queue.queuedEditorTextCache)
? queue.queuedEditorTextCache
: [];
queue.queuedEditorTextCache.push({
text,
timestamp: Date.now()
});
const cleared = this.__clearEditor(editor);
if (!cleared) {
this.__toast('Queued, but could not clear the editor.', 'warning');
}
queue.startQueue({ waitBeforeFirstSend: true });
const count = Array.isArray(queue.promptQueue) ? queue.promptQueue.length : 0;
this.__toast(`Queued. ${count} item${count === 1 ? '' : 's'} waiting.`, 'success');
return { status: 'queued', count };
},
/**
* Creates a normal custom prompt button from the current editor text.
* The editor is intentionally left unchanged.
* @param {Event} event
* @returns {Promise<Object>}
*/
createButtonFromEditorText: async function (event) {
if (event && typeof event.preventDefault === 'function') {
event.preventDefault();
}
if (event && typeof event.stopPropagation === 'function') {
event.stopPropagation();
}
const editor = this.__findActiveEditor();
const text = editor ? this.__readEditorText(editor).trim() : '';
if (!text) {
const reason = editor ? 'empty_editor' : 'editor_not_found';
this.__toast(
editor
? 'Editor is empty. Enter button text manually.'
: 'Could not find the chat editor. Enter button text manually.',
'warning',
3500
);
if (!editor) {
logConCgp('[buttons][create] Editor not found; opening manual create flyout.');
}
this.__showCreatedButtonFlyout(event, {
success: false,
reason,
manualEntry: true,
button: {
icon: '✨',
text: '',
autoSend: false
}
});
return { status: 'manual_entry', reason };
}
try {
const response = await chrome.runtime.sendMessage({
type: 'createCustomButtonFromEditorText',
text,
autoSend: false
});
if (!response?.success) {
const reason = response?.reason || response?.error || 'unknown';
this.__toast('Could not create button from editor text.', 'error');
logConCgp('[buttons][create] Create button request failed:', reason);
return { status: 'failed', reason };
}
this.__toast('Button created from editor text.', 'success');
this.__showCreatedButtonFlyout(event, { ...response, capturedFromEditor: true });
return { status: 'created', ...response };
} catch (error) {
this.__toast('Could not create button from editor text.', 'error');
logConCgp('[buttons][create] Create button request error:', error?.message || error);
return { status: 'failed', reason: 'message_error' };
}
},
__showCreatedButtonFlyout: function (event, created) {
const existing = document.getElementById('ocp-create-button-flyout');
if (existing) {
if (typeof existing.__ocp_cleanup === 'function') {
existing.__ocp_cleanup();
}
existing.remove();
}
const state = {
...created,
mode: created?.mode || 'create',
lookupText: created?.button?.text || '',
button: {
icon: created?.button?.icon || '✨',
text: created?.button?.text || '',
autoSend: created?.button?.autoSend === true
}
};
const isEditMode = state.mode === 'edit';
const hasCreatedButton = () => !!state.success && Number.isInteger(Number(state.buttonIndex)) && !!state.profileName;
const flyout = document.createElement('div');
flyout.id = 'ocp-create-button-flyout';
flyout.style.cssText = `
position: fixed;
z-index: 2147483647;
box-sizing: border-box;
width: min(300px, calc(100vw - 20px));
max-height: calc(100vh - 20px);
overflow: auto;
padding: 12px;
display: grid;
gap: 10px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 12px;
background: rgba(25, 25, 25, 0.82);
backdrop-filter: blur(12px) saturate(180%);
-webkit-backdrop-filter: blur(12px) saturate(180%);
box-shadow: 0 10px 34px rgba(0, 0, 0, 0.34);
color: #ffffff;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 13px;
pointer-events: auto;
opacity: 0;
transform: scale(0.96) translateY(4px);
transition: opacity 150ms ease, transform 150ms ease, border-color 300ms ease;
`;
const header = document.createElement('div');
header.style.cssText = 'display: flex; align-items: center; justify-content: space-between; gap: 8px; font-weight: 700; cursor: move; user-select: none;';
const title = document.createElement('span');
title.textContent = isEditMode ? 'Edit button' : (hasCreatedButton() ? '+ Button created' : '+ Create button');
const closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L13 13M13 1L1 13" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>';
closeButton.setAttribute('aria-label', 'Close');
closeButton.style.cssText = `
display: flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border: 0;
border-radius: 6px;
background: rgba(255, 255, 255, 0.1);
color: #fff;
cursor: pointer;
transition: background 150ms ease, transform 100ms ease;
`;
closeButton.addEventListener('mouseenter', () => { closeButton.style.background = 'rgba(255, 255, 255, 0.18)'; });
closeButton.addEventListener('mouseleave', () => { closeButton.style.background = 'rgba(255, 255, 255, 0.1)'; });
closeButton.addEventListener('mousedown', () => { closeButton.style.transform = 'scale(0.92)'; });
closeButton.addEventListener('mouseup', () => { closeButton.style.transform = ''; });
header.append(title, closeButton);
const textDetails = document.createElement('details');
textDetails.open = isEditMode || !hasCreatedButton();
textDetails.style.cssText = 'display: grid; gap: 8px;';
const textSummary = document.createElement('summary');
textSummary.textContent = hasCreatedButton() ? 'Button text' : 'Button text required';
textSummary.style.cssText = 'cursor: pointer; color: rgba(255, 255, 255, 0.84);';
const textInput = document.createElement('textarea');
textInput.value = state.button.text || '';
textInput.rows = hasCreatedButton() ? 3 : 5;
textInput.placeholder = 'Type the text this button should insert...';
textInput.setAttribute('aria-label', 'Button text');
textInput.style.cssText = `
width: 100%;
min-height: 72px;
box-sizing: border-box;
resize: vertical;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 8px;
background: rgba(255, 255, 255, 0.1);
color: #fff;
font: inherit;
line-height: 1.35;
outline: none;
padding: 8px;
`;
textDetails.append(textSummary, textInput);
const iconLabel = document.createElement('label');
iconLabel.style.cssText = 'display: flex; align-items: center; justify-content: space-between; gap: 10px;';
const iconText = document.createElement('span');
iconText.textContent = 'Icon';
const iconInput = document.createElement('input');
iconInput.type = 'text';
iconInput.value = created?.button?.icon || '✨';
iconInput.setAttribute('aria-label', 'New button icon');
iconInput.style.cssText = `
width: 72px;
min-height: 28px;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 8px;
background: rgba(255, 255, 255, 0.1);
color: #fff;
font-size: 18px;
text-align: center;
outline: none;
`;
iconLabel.append(iconText, iconInput);
const toggleLabel = document.createElement('label');
toggleLabel.style.cssText = 'display: flex; align-items: center; justify-content: space-between; gap: 10px; cursor: pointer;';
const toggleText = document.createElement('span');
toggleText.textContent = 'Auto-send';
const toggle = document.createElement('input');
toggle.type = 'checkbox';
toggle.checked = created?.button?.autoSend === true;
toggle.style.cssText = 'position: absolute; opacity: 0; width: 0; height: 0; pointer-events: none;';
const toggleTrack = document.createElement('span');
const toggleThumb = document.createElement('span');
const syncToggleVisual = () => {
toggleTrack.style.background = toggle.checked ? '#10a37f' : 'rgba(255, 255, 255, 0.2)';
toggleThumb.style.left = toggle.checked ? '18px' : '2px';
};
toggleTrack.style.cssText = `
position: relative;
display: inline-block;
width: 36px;
height: 20px;
border-radius: 10px;
background: ${toggle.checked ? '#10a37f' : 'rgba(255, 255, 255, 0.2)'};
transition: background 200ms ease;
flex-shrink: 0;
`;
toggleThumb.style.cssText = `