-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
3746 lines (3245 loc) · 123 KB
/
content.js
File metadata and controls
3746 lines (3245 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Utility functions
const debounce = (func, timeout = 300) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), timeout);
};
};
// Extension toggle functionality
let extensionEnabled = localStorage.getItem("extension_enabled") !== "false";
// Check extension state on page load and hide/show buttons accordingly
function initializeExtensionState() {
extensionEnabled = localStorage.getItem("extension_enabled") !== "false";
if (!extensionEnabled) {
// Remove all existing buttons when disabled
document.querySelectorAll(".reply-button-inner").forEach((btn) => {
btn.parentElement?.remove();
});
// Hide popup if open
if (popup) {
popup.style.display = "none";
}
}
}
// Listen for extension toggle messages
try {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "EXTENSION_TOGGLE") {
extensionEnabled = message.enabled;
localStorage.setItem("extension_enabled", message.enabled);
if (!extensionEnabled) {
// Remove all existing buttons when disabled
document.querySelectorAll(".reply-button-inner").forEach((btn) => {
btn.parentElement?.remove();
});
// Hide popup if open
if (popup) {
popup.style.display = "none";
}
} else {
// Re-run the service to add buttons back
setTimeout(() => {
outletService();
}, 100);
}
sendResponse({ success: true });
}
});
} catch (error) {
// Chrome extension APIs might not be available
console.log("Chrome extension APIs not available");
}
// Check if extension is enabled before adding buttons
function isExtensionEnabled() {
return extensionEnabled;
}
// API Configuration
function getConfig() {
const provider = localStorage.getItem("ai_provider") || "mistral";
const configs = {
ollama: {
provider: "ollama",
model: localStorage.getItem("ollama_model") || "llama2",
host: localStorage.getItem("ollama_host") || "http://localhost:11434",
apiKey: localStorage.getItem("ollama_api_key"),
apiEndpoint: `${
localStorage.getItem("ollama_host") || "http://localhost:11434"
}/api/generate`,
},
mistral: {
provider: "mistral",
apiKey: localStorage.getItem("mistral_api_key"),
model: localStorage.getItem("mistral_model") || "mistral-large-latest",
apiEndpoint: "https://api.mistral.ai/v1/chat/completions",
},
openai: {
provider: "openai",
apiKey: localStorage.getItem("openai_api_key"),
model: localStorage.getItem("openai_model") || "gpt-3.5-turbo",
apiEndpoint: "https://api.openai.com/v1/chat/completions",
},
claude: {
provider: "claude",
apiKey: localStorage.getItem("claude_api_key"),
model: localStorage.getItem("claude_model") || "claude-3-haiku-20240307",
apiEndpoint: "https://api.anthropic.com/v1/messages",
},
gemini: {
provider: "gemini",
apiKey: localStorage.getItem("gemini_api_key"),
model: localStorage.getItem("gemini_model") || "gemini-pro",
apiEndpoint: `https://generativelanguage.googleapis.com/v1beta/models/${
localStorage.getItem("gemini_model") || "gemini-pro"
}:generateContent`,
},
};
return configs[provider] || configs.mistral;
}
const popup = document.createElement("div");
popup.className = "reply-idea-popup";
popup.innerHTML = `
<div class="reply-idea-content">
<div class="reply-idea-header">
<h3 class="reply-idea-title">
<img
alt="dragonfruit"
style="width: 30px; height: 30px;"
src="https://i.ibb.co/TxFbv3kt/dragonfruit.png"
/>
</h3>
<button class="reply-idea-close" title="Close popup">×</button>
</div>
<!-- Tab Switcher -->
<div class="tab-switcher">
<button class="tab-button active" data-tab="regular">Regular</button>
<button class="tab-button" data-tab="personas">Personas</button>
</div>
<!-- Regular Tab Content -->
<div class="tab-content" id="regular-tab">
<div class="regular-main-layout">
<!-- Column 1: Left Sidebar -->
<div class="regular-left-column">
<div class="success-content"></div>
<div class="regular-info">
<h4>Quick Reply Generator</h4>
<p style="font-size: 12px; opacity: 0.7; margin-top: 8px; margin-bottom: 16px;">
Generate AI-powered replies with customizable mood and style settings.
</p>
<div style="border-top: 1px solid rgba(140, 140, 140, 0.2); padding-top: 12px;">
<h5 style="font-size: 11px; margin: 0 0 8px 0; color: rgba(140, 140, 140, 0.9); font-family: 'Geist Mono';">How it works:</h5>
<ul style="font-size: 10px; opacity: 0.7; margin: 0; padding-left: 16px; line-height: 1.4;">
<li>Select a mood or create custom</li>
<li>Adjust brainrot intensity (0-100%)</li>
<li>Add custom instructions if needed</li>
<li>AI generates contextual reply</li>
</ul>
</div>
<div style="border-top: 1px solid rgba(140, 140, 140, 0.2); padding-top: 12px; margin-top: 12px;">
<h5 style="font-size: 11px; margin: 0 0 8px 0; color: rgba(140, 140, 140, 0.9); font-family: 'Geist Mono';">Mood Options:</h5>
<div style="font-size: 10px; opacity: 0.7; line-height: 1.4;">
<span style="display: block; margin-bottom: 4px;"><strong>Auto:</strong> AI decides tone</span>
<span style="display: block; margin-bottom: 4px;"><strong>Agree/Disagree:</strong> Support or counter</span>
<span style="display: block; margin-bottom: 4px;"><strong>Motivate:</strong> Inspirational response</span>
<span style="display: block; margin-bottom: 4px;"><strong>Roast:</strong> Humorous criticism</span>
<span style="display: block; margin-bottom: 4px;"><strong>Cute:</strong> Friendly and warm</span>
<span style="display: block;"><strong>Custom:</strong> Define your own mood</span>
</div>
</div>
<div style="border-top: 1px solid rgba(140, 140, 140, 0.2); padding-top: 12px; margin-top: 12px;">
<h5 style="font-size: 11px; margin: 0 0 8px 0; color: rgba(140, 140, 140, 0.9); font-family: 'Geist Mono';">Tips:</h5>
<div style="font-size: 10px; opacity: 0.7; line-height: 1.4;">
<span style="display: block; margin-bottom: 4px;">• Use Ctrl+Enter to regenerate</span>
<span style="display: block; margin-bottom: 4px;">• Press Escape to close popup</span>
<span style="display: block; margin-bottom: 4px;">• Higher intensity = more casual/bold</span>
<span style="display: block;">• Custom instructions refine output</span>
</div>
</div>
</div>
</div>
<!-- Column 2: Reply Controls & Generation -->
<div class="regular-right-column">
<h4>Reply Controls</h4>
<div class="tweet-content-body"></div>
<textarea class="reply-idea-body-editable" placeholder="Your generated reply will appear here... You can edit it directly!"></textarea>
<div class="reply-char-counter">0/280 characters</div>
<div class="reply-tip" style="text-align: left; margin-top: -0.3rem; font-size: 10px; opacity: 0.6;">
💡 Tip: Press Ctrl+Enter to regenerate reply.
</div>
<div class="brainrot-slider-container">
<div class="slider-label" style="margin-bottom: 10px">
<span>Mood:</span>
<select class="select-mood" id="select-mood">
<option selected value="Auto">Auto</option>
<option value="Agree">Agree</option>
<option value="Disagree">Disagree</option>
<option value="Motivate">Motivate</option>
<option value="Roast">Roast</option>
<option value="Cute">Cute</option>
<option value="Custom">Custom</option>
</select>
</div>
<input
type="text"
class="user-need"
placeholder="Enter custom mood (e.g., Sarcastic, Professional, Funny...)"
id="custom-mood-input"
style="display: none; height: 40px; margin-top: 0.5rem; margin-bottom: 1rem;"
/>
<div class="slider-label">
<span>Brainrot Intensity:</span>
<span id="slider-value">69%</span>
</div>
<input type="range" min="0" max="100" value="69" class="brainrot-slider" id="brainrot-slider">
<div class="thinking-checkbox-container">
<input type="checkbox" id="thinking-checkbox" class="thinking-checkbox">
<label for="thinking-checkbox" class="thinking-checkbox-label">Remove thinking tags (for thinking models)</label>
</div>
<textarea placeholder="I want this reply to..." class="user-need-textarea" id="user-need-textarea"></textarea>
</div>
<div class="reply-actions">
<button class="copy-button">Copy</button>
<button class="new-reply-button">New Reply</button>
<button class="go-to-tweet-button">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
<path d="m22 2-7 20-4-9-9-4Z"/>
<path d="M22 2 11 13"/>
</svg>
Reply this
</button>
</div>
</div>
</div>
</div>
<!-- Personas Tab Content -->
<div class="tab-content" id="personas-tab" style="display: none;">
<div class="personas-main-layout">
<!-- Column 1: Personas Management -->
<div class="personas-left-column">
<div class="success-content"></div>
<div class="personas-header">
<h4>Available Personas</h4>
<button class="create-persona-btn">+ Create</button>
</div>
<div class="personas-list" id="personas-list">
<!-- Personas will be dynamically loaded here -->
</div>
<div class="selected-personas" id="selected-personas">
<h4>Selected Personas</h4>
<div class="selected-personas-chips"></div>
</div>
</div>
<!-- Column 2: Reply Controls & Generation -->
<div class="personas-right-column">
<h4>Reply Controls</h4>
<div class="tweet-content-body"></div>
<textarea class="reply-idea-body-editable" placeholder="AI will generate reply based on selected personas..."></textarea>
<div class="reply-char-counter">0/280 characters</div>
<div class="reply-tip" style="text-align: left; margin-top: -0.3rem; font-size: 10px; opacity: 0.6;">
💡 Tip: Press Ctrl+Enter to regenerate reply.
</div>
<div class="brainrot-slider-container">
<div class="slider-label" style="margin-bottom: 10px">
<span>Mood:</span>
<select class="select-mood personas-mood" id="personas-select-mood">
<option selected value="Auto">Auto</option>
<option value="Agree">Agree</option>
<option value="Disagree">Disagree</option>
<option value="Motivate">Motivate</option>
<option value="Roast">Roast</option>
<option value="Cute">Cute</option>
<option value="Custom">Custom</option>
</select>
</div>
<input
type="text"
class="user-need personas-custom-mood"
placeholder="Enter custom mood (e.g., Sarcastic, Professional, Funny...)"
id="personas-custom-mood-input"
style="display: none; height: 40px; margin-top: 0.5rem; margin-bottom: 1rem;"
/>
<div class="slider-label">
<span>Brainrot Intensity:</span>
<span id="personas-slider-value">69%</span>
</div>
<input type="range" min="0" max="100" value="69" class="brainrot-slider personas-slider" id="personas-brainrot-slider">
<div class="thinking-checkbox-container">
<input type="checkbox" id="personas-thinking-checkbox" class="thinking-checkbox personas-thinking">
<label for="personas-thinking-checkbox" class="thinking-checkbox-label">Remove thinking tags (for thinking models)</label>
</div>
<textarea placeholder="I want this reply to..." class="user-need-textarea personas-user-need" id="personas-user-need-textarea"></textarea>
</div>
<div class="reply-actions">
<button class="copy-button">Copy</button>
<button class="new-reply-button">New Reply</button>
<button class="go-to-tweet-button">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
<path d="m22 2-7 20-4-9-9-4Z"/>
<path d="M22 2 11 13"/>
</svg>
Reply this
</button>
</div>
</div>
</div>
</div>
<!-- Persona Creation/Edit Modal -->
<div class="persona-modal" id="persona-modal" style="display: none;">
<div class="persona-modal-content">
<div class="persona-modal-header">
<h4 id="persona-modal-title">Create Persona</h4>
<button class="persona-modal-close">×</button>
</div>
<div class="persona-form">
<input type="text" id="persona-title" class="persona-input" placeholder="Persona Title" maxlength="50">
<textarea id="persona-description" class="persona-textarea" placeholder="Description (optional)" rows="3"></textarea>
<textarea id="persona-tweets" class="persona-textarea" placeholder="Paste up to 100 tweets from this person here..." rows="8"></textarea>
<textarea id="persona-prompt" class="persona-textarea" placeholder="Additional prompting about this persona (optional)" rows="3"></textarea>
<div class="persona-actions">
<button class="cancel-persona-btn">Cancel</button>
<button class="save-persona-btn">Save</button>
</div>
</div>
</div>
</div>
</div>
`;
document.body.appendChild(popup);
// Personas functionality
class PersonaManager {
constructor() {
this.personas = this.loadPersonas();
this.selectedPersonas = [];
this.currentEditingId = null;
this.eventListenersAttached = false;
this.updateThrottle = null;
}
loadPersonas() {
const saved = localStorage.getItem("dragon_fruit_personas");
return saved ? JSON.parse(saved) : [];
}
savePersonas() {
localStorage.setItem(
"dragon_fruit_personas",
JSON.stringify(this.personas)
);
}
createPersona(title, description, tweets, prompt) {
const id = Date.now().toString();
const persona = {
id,
title: title.trim(),
description: description.trim(),
tweets: tweets.trim(),
prompt: prompt.trim(),
createdAt: new Date().toISOString(),
};
this.personas.push(persona);
this.savePersonas();
return persona;
}
updatePersona(id, updates) {
const index = this.personas.findIndex((p) => p.id === id);
if (index !== -1) {
this.personas[index] = { ...this.personas[index], ...updates };
this.savePersonas();
return this.personas[index];
}
return null;
}
deletePersona(id) {
this.personas = this.personas.filter((p) => p.id !== id);
this.selectedPersonas = this.selectedPersonas.filter((p) => p !== id);
this.savePersonas();
}
getPersona(id) {
return this.personas.find((p) => p.id === id);
}
togglePersonaSelection(id) {
const index = this.selectedPersonas.indexOf(id);
if (index === -1) {
this.selectedPersonas.push(id);
} else {
this.selectedPersonas.splice(index, 1);
}
// Only update UI elements that changed, not the entire list
this.updatePersonaItemSelection(id);
// Throttle the chips update to prevent excessive DOM manipulation
if (this.updateThrottle) {
clearTimeout(this.updateThrottle);
}
this.updateThrottle = setTimeout(() => {
this.updateSelectedPersonasDisplay();
}, 100);
}
updatePersonaItemSelection(personaId) {
const personaItem = document.querySelector(
`[data-persona-id="${personaId}"]`
);
if (personaItem) {
const isSelected = this.selectedPersonas.includes(personaId);
if (isSelected) {
personaItem.classList.add("selected");
} else {
personaItem.classList.remove("selected");
}
}
}
attachEventListeners() {
if (this.eventListenersAttached) return;
const container = document.getElementById("personas-list");
if (!container) return;
// Use event delegation for better performance
container.addEventListener("click", this.handleClick.bind(this));
this.eventListenersAttached = true;
}
handleClick(e) {
const personaItem = e.target.closest(".persona-item");
const actionBtn = e.target.closest(".persona-action-btn");
if (actionBtn) {
e.stopPropagation();
const action = actionBtn.dataset.action;
const personaId = actionBtn.dataset.personaId;
if (action === "edit") {
this.openPersonaModal(personaId);
} else if (action === "delete") {
// Single click delete with confirmation
const persona = this.getPersona(personaId);
if (persona && confirm(`Delete persona "${persona.title}"?`)) {
this.deletePersona(personaId);
this.renderPersonasList();
this.updateSelectedPersonasDisplay();
this.showFeedback(`Deleted "${persona.title}"`, "error");
}
}
} else if (personaItem) {
const personaId = personaItem.dataset.personaId;
// Use requestAnimationFrame for smooth UI updates
requestAnimationFrame(() => {
this.togglePersonaSelection(personaId);
});
}
}
showFeedback(message, type = "info") {
const feedback = document.createElement("div");
const bgColor =
type === "error" ? "rgba(220, 38, 38, 0.9)" : "rgba(34, 197, 94, 0.9)";
feedback.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: ${bgColor};
color: white;
padding: 8px 16px;
border-radius: 6px;
font-size: 12px;
z-index: 10000;
pointer-events: none;
opacity: 0;
transition: opacity 0.3s ease;
`;
feedback.textContent = message;
document.body.appendChild(feedback);
// Animate in
requestAnimationFrame(() => {
feedback.style.opacity = "1";
});
setTimeout(() => {
feedback.style.opacity = "0";
setTimeout(() => {
if (document.body.contains(feedback)) {
document.body.removeChild(feedback);
}
}, 300);
}, 1500);
}
renderPersonasList() {
const container = document.getElementById("personas-list");
if (!container) return;
if (this.personas.length === 0) {
container.innerHTML = `
<div style="text-align: center; padding: 2rem; color: rgba(140, 140, 140, 0.6); font-family: 'Geist Mono'; font-size: 12px;">
No personas created yet.<br/>
Click "Create Persona" to get started.
</div>
`;
return;
}
// Create document fragment for better performance
const fragment = document.createDocumentFragment();
// Add instruction header
const instructionHeader = document.createElement("div");
instructionHeader.style.cssText =
"text-align: center; padding: 0.5rem; margin-bottom: 1rem; color: rgba(140, 140, 140, 0.6); font-family: 'Geist Mono'; font-size: 10px; border-bottom: 1px solid rgba(140, 140, 140, 0.2);";
instructionHeader.textContent =
"Click to select • ✏️ to edit • 🗑️ to delete";
fragment.appendChild(instructionHeader);
// Create persona items efficiently
this.personas.forEach((persona) => {
const personaDiv = document.createElement("div");
personaDiv.className = `persona-item ${
this.selectedPersonas.includes(persona.id) ? "selected" : ""
}`;
personaDiv.dataset.personaId = persona.id;
personaDiv.innerHTML = `
<div class="persona-info">
<div class="persona-title">${this.escapeHtml(persona.title)}</div>
${
persona.description
? `<div class="persona-description">${this.escapeHtml(
persona.description
)}</div>`
: ""
}
</div>
<div class="persona-actions">
<button class="persona-action-btn edit" data-action="edit" data-persona-id="${
persona.id
}">✏️</button>
<button class="persona-action-btn delete" data-action="delete" data-persona-id="${
persona.id
}" title="Click to delete">🗑️</button>
</div>
`;
fragment.appendChild(personaDiv);
});
// Clear and append all at once
container.innerHTML = "";
container.appendChild(fragment);
// Attach event listeners only once
this.attachEventListeners();
}
updatePersonasList() {
// Use the optimized render method
this.renderPersonasList();
}
updateSelectedPersonasDisplay() {
const container = popup.querySelector(".selected-personas-chips");
if (!container) return;
// Clear existing event listeners to prevent memory leaks
const oldContainer = container.cloneNode(false);
container.parentNode.replaceChild(oldContainer, container);
if (this.selectedPersonas.length === 0) {
oldContainer.innerHTML =
'<span style="color: rgba(140, 140, 140, 0.6); font-style: italic; font-size: 11px;">No personas selected</span>';
return;
}
// Use document fragment for better performance
const fragment = document.createDocumentFragment();
this.selectedPersonas.forEach((id) => {
const persona = this.getPersona(id);
if (!persona) return;
const chip = document.createElement("div");
chip.className = "persona-chip";
chip.innerHTML = `
${this.escapeHtml(persona.title)}
<span class="persona-chip-remove" data-persona-id="${id}">×</span>
`;
fragment.appendChild(chip);
});
oldContainer.appendChild(fragment);
// Add single delegated event listener
oldContainer.addEventListener("click", (e) => {
if (e.target.classList.contains("persona-chip-remove")) {
const personaId = e.target.dataset.personaId;
// Use requestAnimationFrame for smooth updates
requestAnimationFrame(() => {
this.togglePersonaSelection(personaId);
});
}
});
}
openPersonaModal(personaId = null) {
this.currentEditingId = personaId;
const modal = document.getElementById("persona-modal");
const title = document.getElementById("persona-modal-title");
const titleInput = document.getElementById("persona-title");
const descriptionInput = document.getElementById("persona-description");
const tweetsInput = document.getElementById("persona-tweets");
const promptInput = document.getElementById("persona-prompt");
if (personaId) {
const persona = this.getPersona(personaId);
if (persona) {
title.textContent = "Edit Persona";
titleInput.value = persona.title;
descriptionInput.value = persona.description;
tweetsInput.value = persona.tweets;
promptInput.value = persona.prompt;
}
} else {
title.textContent = "Create Persona";
titleInput.value = "";
descriptionInput.value = "";
tweetsInput.value = "";
promptInput.value = "";
}
modal.style.display = "flex";
titleInput.focus();
}
closePersonaModal() {
const modal = document.getElementById("persona-modal");
modal.style.display = "none";
this.currentEditingId = null;
}
saveCurrentPersona() {
const titleInput = document.getElementById("persona-title");
const descriptionInput = document.getElementById("persona-description");
const tweetsInput = document.getElementById("persona-tweets");
const promptInput = document.getElementById("persona-prompt");
const title = titleInput.value.trim();
const description = descriptionInput.value.trim();
const tweets = tweetsInput.value.trim();
const prompt = promptInput.value.trim();
if (!title) {
alert("Please enter a persona title");
titleInput.focus();
return;
}
if (!tweets) {
alert("Please paste some tweets for this persona");
tweetsInput.focus();
return;
}
if (this.currentEditingId) {
this.updatePersona(this.currentEditingId, {
title,
description,
tweets,
prompt,
});
} else {
this.createPersona(title, description, tweets, prompt);
}
this.updatePersonasList();
this.closePersonaModal();
}
escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
generatePersonaPrompt() {
if (this.selectedPersonas.length === 0) {
return null;
}
const selectedPersonaData = this.selectedPersonas
.map((id) => this.getPersona(id))
.filter(Boolean);
let prompt = "You must embody these personas completely and naturally:\n\n";
selectedPersonaData.forEach((persona, index) => {
prompt += `PERSONA ${index + 1}: ${persona.title}\n`;
if (persona.description) {
prompt += `Background: ${persona.description}\n`;
}
if (persona.prompt) {
prompt += `Context: ${persona.prompt}\n`;
}
prompt += `Writing samples:\n${persona.tweets}\n\n`;
});
prompt += `CRITICAL INSTRUCTIONS:
- You ARE this person/combination of people - don't reference being an AI
- Study their exact writing patterns: punctuation, capitalization, slang, emoji use, sentence length
- Mirror their vocabulary choices and avoid words/phrases they wouldn't use
- Copy their grammar patterns and any "mistakes" they make consistently
- Don't be overly articulate if they're casual - match their intelligence level
- Never use corporate/AI language like "delighted", "thrilled", "incredible", "amazing"
- Don't give advice or be helpful unless that's clearly their personality
- Avoid buzzwords, marketing speak, or anything that sounds "generated"
- Be authentic to THEIR voice, not a polished version
- If they use poor grammar, incomplete sentences, or internet slang - copy that
- Don't explain or analyze - just respond as they naturally would
- Keep responses focused and short unless they typically write long posts
- Use their authentic reactions and emotional expressions
STRICT NO-COPYING RULES:
- NEVER copy exact phrases, sentences, or paragraphs from the provided tweets
- NEVER reference specific events, dates, or situations mentioned in their old posts
- NEVER use identical word combinations or unique expressions from their tweets
- DO NOT quote or paraphrase their previous content
- Create ORIGINAL content that matches their STYLE only, not their substance
- Think of how they WOULD respond, not how they DID respond to similar topics
- Generate fresh thoughts in their voice, don't recycle their old thoughts
Reply as if you're genuinely this person having a real conversation with completely new, original thoughts.`;
return prompt;
}
}
// Initialize persona manager
const personaManager = new PersonaManager();
// Tab switching functionality
function initTabSwitching() {
const tabButtons = popup.querySelectorAll(".tab-button");
const tabContents = popup.querySelectorAll(".tab-content");
// Load last opened tab from localStorage
const lastTab = localStorage.getItem("dragon_fruit_last_tab") || "regular";
// Function to switch to a specific tab
const switchToTab = (targetTab) => {
// Update button states
tabButtons.forEach((btn) => btn.classList.remove("active"));
const targetButton = popup.querySelector(`[data-tab="${targetTab}"]`);
if (targetButton) {
targetButton.classList.add("active");
}
// Update content visibility
tabContents.forEach((content) => {
content.style.display = "none";
});
const targetContent = document.getElementById(`${targetTab}-tab`);
if (targetContent) {
targetContent.style.display = "block";
}
// Save to localStorage
localStorage.setItem("dragon_fruit_last_tab", targetTab);
// Initialize personas list if switching to personas tab
if (targetTab === "personas") {
personaManager.updatePersonasList();
personaManager.updateSelectedPersonasDisplay();
}
// Auto-generate reply when switching tabs if there's tweet content
const tweetContentBody = popup.querySelector(".tweet-content-body");
if (
tweetContentBody &&
tweetContentBody.textContent &&
tweetContentBody.textContent.trim()
) {
const tweetText = tweetContentBody.textContent.trim();
const replyBody = popup.querySelector(
`#${targetTab}-tab .reply-idea-body-editable`
);
if (replyBody) {
replyBody.value = "Generating reply...";
replyBody.disabled = true;
// Get form values for the target tab
const formValues = getFormValues();
// Generate reply for the new tab
generateReply(tweetText, formValues.userNeed, formValues.mood)
.then((reply) => {
const processedReply = processThinkingTags(reply);
replyBody.value = processedReply;
replyBody.disabled = false;
// Trigger character counter update
const event = new Event("input");
replyBody.dispatchEvent(event);
})
.catch((error) => {
console.error("Error generating reply on tab switch:", error);
replyBody.value =
"Error generating reply. Check your configuration.";
replyBody.disabled = false;
});
}
}
// Re-establish event handlers for the newly active tab
if (popup.style.display === "flex") {
setupTabEventHandlers();
setupPopupCloseHandlers();
}
};
// Set up click handlers
tabButtons.forEach((button) => {
button.addEventListener("click", () => {
const targetTab = button.dataset.tab;
switchToTab(targetTab);
});
});
// Restore last opened tab
switchToTab(lastTab);
}
// Initialize modal event listeners
function initPersonaModal() {
const modal = document.getElementById("persona-modal");
const closeBtn = modal.querySelector(".persona-modal-close");
const cancelBtn = modal.querySelector(".cancel-persona-btn");
const saveBtn = modal.querySelector(".save-persona-btn");
const createBtn = popup.querySelector(".create-persona-btn");
createBtn?.addEventListener("click", () => {
personaManager.openPersonaModal();
});
closeBtn?.addEventListener("click", () => {
personaManager.closePersonaModal();
});
cancelBtn?.addEventListener("click", () => {
personaManager.closePersonaModal();
});
saveBtn?.addEventListener("click", () => {
personaManager.saveCurrentPersona();
});
// Close modal when clicking outside
modal?.addEventListener("click", (e) => {
if (e.target === modal) {
personaManager.closePersonaModal();
}
});
// Handle Enter key in title input
const titleInput = document.getElementById("persona-title");
titleInput?.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
personaManager.saveCurrentPersona();
}
});
}
// Initialize everything after popup is created
initTabSwitching();
initPersonaModal();
initializeExtensionState();
// Update existing slider functionality to work with the new structure
// Slider functionality - for both regular and personas tabs
const setupSliders = () => {
// Regular tab slider
const slider = popup.querySelector("#brainrot-slider");
const sliderValue = popup.querySelector("#slider-value");
if (slider && sliderValue) {
slider.addEventListener("input", (e) => {
sliderValue.textContent = `${e.target.value}%`;
});
}
// Personas tab slider
const personasSlider = popup.querySelector("#personas-brainrot-slider");
const personasSliderValue = popup.querySelector("#personas-slider-value");
if (personasSlider && personasSliderValue) {
personasSlider.addEventListener("input", (e) => {
personasSliderValue.textContent = `${e.target.value}%`;
});
}
};
setupSliders();
// Character counter for reply textarea - works for both tabs
function setupCharacterCounters() {
const textareas = popup.querySelectorAll(".reply-idea-body-editable");
const counters = popup.querySelectorAll(".reply-char-counter");
textareas.forEach((textarea, index) => {
const counter = counters[index];
if (!counter) return;
const updateCharCounter = () => {
const length = textarea.value.length;
const maxLength = 280;
counter.textContent = `${length}/${maxLength} characters`;
// Update styling based on character count
counter.classList.remove("warning", "error");
if (length > maxLength * 0.9) {
counter.classList.add("warning");
}
if (length > maxLength) {
counter.classList.add("error");
}
};
textarea.addEventListener("input", updateCharCounter);
textarea.addEventListener("paste", () => setTimeout(updateCharCounter, 10));
// Initialize counter
updateCharCounter();
});
}
setupCharacterCounters();
// Custom mood functionality - for both tabs
const setupMoodFunctionality = () => {
// Regular tab
const moodSelect = popup.querySelector("#select-mood");
const customMoodInput = popup.querySelector("#custom-mood-input");
if (moodSelect && customMoodInput) {
moodSelect.addEventListener("change", (e) => {
const isCustom = e.target.value === "Custom";
customMoodInput.style.display = isCustom ? "block" : "none";
if (isCustom) {
customMoodInput.focus();
}
});
}
// Personas tab
const personasMoodSelect = popup.querySelector("#personas-select-mood");
const personasCustomMoodInput = popup.querySelector(
"#personas-custom-mood-input"
);
if (personasMoodSelect && personasCustomMoodInput) {
personasMoodSelect.addEventListener("change", (e) => {
const isCustom = e.target.value === "Custom";
personasCustomMoodInput.style.display = isCustom ? "block" : "none";
if (isCustom) {
personasCustomMoodInput.focus();
}
});
}
};
setupMoodFunctionality();
// Thinking checkbox functionality - for both tabs
const setupThinkingCheckbox = () => {
const thinkingCheckbox = popup.querySelector("#thinking-checkbox");
const personasThinkingCheckbox = popup.querySelector(
"#personas-thinking-checkbox"
);
const handleThinkingChange = (checkbox) => {