generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.ts
More file actions
3364 lines (2903 loc) · 96.2 KB
/
main.ts
File metadata and controls
3364 lines (2903 loc) · 96.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { App, Notice, Plugin, PluginSettingTab, Setting, MarkdownView, Editor } from "obsidian";
import { GeminiService, WebSearchResponse } from "./src/services/GeminiService";
import { RAGService } from "./src/services/RAGService";
import { LanguageSelectionModal } from "./src/modals/LanguageSelectionModal";
import { MarkdownRenderer } from "obsidian";
import { FileSelectionModal } from "./src/modals/FileSelectionModal";
import { CustomPromptModal } from "./src/modals/CustomPromptModal";
// Core interfaces for chat functionality
interface ChatMessage {
role: "user" | "bot";
content: string;
timestamp: number;
}
interface ChatSession {
id: string;
title: string;
timestamp: number;
messages: ChatMessage[];
}
interface CustomPrompt {
id: string;
name: string;
description: string;
prompt: string;
}
interface GeminiChatbotSettings {
apiKey: string;
floatingPosition: { x: number; y: number };
isDocked: boolean;
chatSessions: ChatSession[];
customPrompts: CustomPrompt[];
// RAG settings
ragEnabled: boolean;
ragFolderPath: string;
ragStoreName: string | null;
ragSyncedFiles: Record<string, any>;
// Model configuration
modelName: string;
temperature: number;
topK: number;
topP: number;
maxOutputTokens: number;
}
// Default plugin settings
const DEFAULT_SETTINGS: GeminiChatbotSettings = {
apiKey: "",
floatingPosition: { x: 20, y: 20 },
isDocked: false,
chatSessions: [],
customPrompts: [],
// RAG defaults
ragEnabled: false,
ragFolderPath: "/",
ragStoreName: null,
ragSyncedFiles: {},
// Model configuration defaults
modelName: "gemini-2.0-flash-exp",
temperature: 1.0,
topK: 40,
topP: 0.95,
maxOutputTokens: 8192,
};
export default class GeminiChatbotPlugin extends Plugin {
// Core plugin properties
settings: GeminiChatbotSettings;
chatIcon: HTMLElement;
chatContainer: HTMLElement;
private geminiService: GeminiService | null = null;
public ragService: RAGService | null = null;
private messagesContainer: HTMLElement | null = null;
private inputField: HTMLTextAreaElement | null = null;
private currentFileContent: string | null = null;
private chatHistory: ChatMessage[] = [];
private isFullPage = false;
private currentSession: ChatSession | null = null;
private referencedFiles: Map<string, string> | null = null;
// Editor integration properties
private activeEditor: Editor | null = null;
private cursorPosition: { line: number; ch: number } | null = null;
private editorContext: { fileName: string; lineContent: string; surroundingLines: string[] } | null = null;
private insertMode = false;
// RAG mode toggle
private ragMode = false;
// Web search mode toggle
private webSearchMode = false;
// Rate limiting and context management
private lastApiCall = 0;
private readonly API_COOLDOWN = 1000; // Prevent rapid-fire API calls
private readonly MAX_CONTEXT_LENGTH = 30000; // Prevent token limit issues
async onload() {
await this.loadSettings();
if (this.settings.apiKey) {
this.initializeGeminiService();
}
// Add command palette commands
this.addCommand({
id: 'open-vaultai-chat',
name: 'Open VaultAI Chat',
callback: () => {
this.openChatFromCommand();
}
});
this.addCommand({
id: 'toggle-vaultai-chat',
name: 'Toggle VaultAI Chat',
hotkeys: [{ modifiers: ["Mod", "Shift"], key: "v" }],
callback: () => {
this.toggleChatContainer();
}
});
// Register custom prompt commands
this.registerCustomPromptCommands();
// Add editor integration commands
this.addCommand({
id: 'vaultai-generate-at-cursor',
name: 'VaultAI: Generate content at cursor',
editorCallback: (editor: Editor) => {
this.generateAtCursor(editor);
}
});
this.addCommand({
id: 'vaultai-complete-line',
name: 'VaultAI: Complete current line',
editorCallback: (editor: Editor) => {
this.completeLine(editor);
}
});
this.addCommand({
id: 'vaultai-explain-selection',
name: 'VaultAI: Explain selected text',
editorCallback: (editor: Editor) => {
this.explainSelection(editor);
}
});
this.addCommand({
id: 'vaultai-improve-selection',
name: 'VaultAI: Improve selected text',
editorCallback: (editor: Editor) => {
this.improveSelection(editor);
}
});
// Add settings tab
this.addSettingTab(new GeminiChatbotSettingTab(this.app, this));
// Add floating chat icon
this.addFloatingIcon();
// Add chat container
this.addChatContainer();
// Add workspace event listener for active file changes
this.registerEvent(
this.app.workspace.on("active-leaf-change", async () => {
if (
this.chatContainer &&
!this.chatContainer.hasClass("initially-hidden") &&
!this.chatContainer.hasClass("gemini-hidden")
) {
const activeFile = this.app.workspace.getActiveFile();
if (activeFile) {
this.currentFileContent = await this.app.vault.read(
activeFile
);
this.updateChatHeader();
} else {
this.currentFileContent = null;
this.updateChatHeader();
}
}
// Update editor context when active file changes
this.updateEditorContext();
})
);
// Add cursor position tracking
this.registerEvent(
this.app.workspace.on("editor-change", () => {
this.updateEditorContext();
})
);
// Initial editor context update
this.updateEditorContext();
}
public initializeGeminiService() {
try {
if (this.settings.apiKey) {
const decryptedKey = this.decryptApiKey(this.settings.apiKey);
const modelConfig = {
modelName: this.settings.modelName,
temperature: this.settings.temperature,
topK: this.settings.topK,
topP: this.settings.topP,
maxOutputTokens: this.settings.maxOutputTokens
};
this.geminiService = new GeminiService(decryptedKey, modelConfig);
// Initialize RAG service if enabled
if (this.settings.ragEnabled) {
this.initializeRAGService();
}
}
} catch (error) {
console.error("Failed to initialize Gemini service:", error);
}
}
public initializeRAGService() {
try {
if (!this.geminiService) {
return;
}
const apiKey = this.geminiService.getApiKey();
this.ragService = new RAGService(apiKey, this.app.vault);
// Load existing store if available
if (this.settings.ragStoreName) {
this.ragService.setFileSearchStoreName(this.settings.ragStoreName);
}
// Load synced files metadata
if (this.settings.ragSyncedFiles) {
this.ragService.loadSyncedFilesMetadata(this.settings.ragSyncedFiles);
}
console.log("RAG service initialized");
} catch (error) {
console.error("Failed to initialize RAG service:", error);
}
}
private openChatFromCommand() {
// Open chat if it's closed
if (this.chatContainer?.classList.contains("initially-hidden")) {
this.toggleChatContainer();
}
// Focus the input field
if (this.inputField) {
this.inputField.focus();
}
}
public registerCustomPromptCommands() {
// First, remove any existing custom prompt commands
// Note: Obsidian doesn't have a direct way to remove commands,
// so we rely on plugin reload for cleanup
// Register commands for each custom prompt
this.settings.customPrompts.forEach((prompt) => {
this.addCommand({
id: `custom-prompt-${prompt.id}`,
name: `Custom Prompt: ${prompt.name}`,
callback: () => {
this.executeCustomPrompt(prompt);
}
});
});
}
private async executeCustomPrompt(prompt: CustomPrompt) {
// Open chat if it's closed
if (this.chatContainer?.classList.contains("initially-hidden")) {
this.toggleChatContainer();
}
let processedPrompt = prompt.prompt;
// Replace placeholders with actual content
const activeFile = this.app.workspace.getActiveFile();
if (activeFile) {
// Get selected text
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
const selection = activeView?.editor?.getSelection() || "";
// Get full content
const fileContent = await this.app.vault.read(activeFile);
// Replace placeholders
processedPrompt = processedPrompt
.replace(/\{\{selection\}\}/g, selection)
.replace(/\{\{content\}\}/g, fileContent);
}
// Insert the processed prompt into the input field
if (this.inputField) {
this.inputField.value = processedPrompt;
this.inputField.focus();
// Optionally auto-send the prompt
// Uncomment the next line if you want prompts to be sent automatically
// this.handleMessage(processedPrompt);
}
}
private showCustomPromptsDropdown() {
// Remove any existing dropdown
const existingDropdown = document.querySelector('.custom-prompts-dropdown');
if (existingDropdown) {
existingDropdown.remove();
return; // Toggle behavior - close if already open
}
if (this.settings.customPrompts.length === 0) {
new Notice("No custom prompts available. Add some in Settings → VaultAI.");
return;
}
// Create dropdown
const dropdown = document.createElement('div');
dropdown.classList.add('custom-prompts-dropdown');
// Position it near the prompts button
const promptsButton = this.chatContainer.querySelector('.prompts-button') as HTMLElement;
if (!promptsButton) return;
const buttonRect = promptsButton.getBoundingClientRect();
dropdown.style.position = 'fixed';
dropdown.style.bottom = `${window.innerHeight - buttonRect.top + 10}px`;
dropdown.style.right = `${window.innerWidth - buttonRect.right}px`;
dropdown.style.maxWidth = '300px';
dropdown.style.maxHeight = '200px';
dropdown.style.overflowY = 'auto';
dropdown.style.backgroundColor = 'var(--background-primary)';
dropdown.style.border = '1px solid var(--background-modifier-border)';
dropdown.style.borderRadius = '8px';
dropdown.style.boxShadow = '0 4px 16px rgba(0, 0, 0, 0.15)';
dropdown.style.zIndex = '1000';
dropdown.style.padding = '8px';
// Add prompts to dropdown
this.settings.customPrompts.forEach((prompt) => {
const promptItem = document.createElement('div');
promptItem.classList.add('custom-prompt-item');
promptItem.style.padding = '8px 12px';
promptItem.style.cursor = 'pointer';
promptItem.style.borderRadius = '6px';
promptItem.style.marginBottom = '4px';
const promptName = document.createElement('div');
promptName.textContent = prompt.name;
promptName.style.fontWeight = '500';
promptName.style.fontSize = '14px';
const promptDesc = document.createElement('div');
promptDesc.textContent = prompt.description || 'No description';
promptDesc.style.fontSize = '12px';
promptDesc.style.color = 'var(--text-muted)';
promptDesc.style.marginTop = '2px';
promptItem.appendChild(promptName);
if (prompt.description) {
promptItem.appendChild(promptDesc);
}
// Hover effects
promptItem.addEventListener('mouseenter', () => {
promptItem.style.backgroundColor = 'var(--background-modifier-hover)';
});
promptItem.addEventListener('mouseleave', () => {
promptItem.style.backgroundColor = 'transparent';
});
// Click handler
promptItem.addEventListener('click', () => {
this.executeCustomPrompt(prompt);
dropdown.remove();
});
dropdown.appendChild(promptItem);
});
// Add to body
document.body.appendChild(dropdown);
// Close dropdown when clicking outside
const closeDropdown = (e: MouseEvent) => {
if (!dropdown.contains(e.target as Node) && !promptsButton.contains(e.target as Node)) {
dropdown.remove();
document.removeEventListener('click', closeDropdown);
}
};
// Use setTimeout to avoid immediate closure
setTimeout(() => {
document.addEventListener('click', closeDropdown);
}, 100);
}
private async handleMessage(message: string) {
if (!this.geminiService || !message.trim()) return;
// Check API cooldown
const now = Date.now();
if (now - this.lastApiCall < this.API_COOLDOWN) {
this.addErrorMessage(
"Please wait a moment before sending another message"
);
return;
}
this.toggleSuggestedActions(false);
// Build context more efficiently
let contextMessage = message;
let context = "";
// Skip context building if RAG mode is enabled
if (!this.ragMode) {
// Add referenced file content if any
const fileReferences = message.match(/@([^\s]+)/g);
if (fileReferences) {
contextMessage = message.replace(/@([^\s]+)/g, "").trim();
for (const ref of fileReferences) {
const fileName = ref.slice(1);
const fileContent = this.referencedFiles?.get(fileName);
if (fileContent) {
// Add only the first part of long files
const truncatedContent = this.truncateContent(fileContent);
context += `\nRelevant content from ${fileName}:\n${truncatedContent}\n`;
}
}
}
// Add current file content if available and no specific file was referenced
const activeFile = this.app.workspace.getActiveFile();
if (activeFile && !fileReferences) {
const content = await this.app.vault.read(activeFile);
// Add only relevant parts of the current file
const truncatedContent = this.truncateContent(content);
context += `\nRelevant content from current note:\n${truncatedContent}\n`;
}
// Add editor context (cursor position and surrounding lines)
const editorContext = this.getEditorContextString();
if (editorContext) {
context += editorContext;
}
}
// Prepare the final message
const finalMessage = context
? `${context}\n\nUser question: ${contextMessage}`
: contextMessage;
const userMessage: ChatMessage = {
role: "user",
content: finalMessage,
timestamp: Date.now(),
};
await this.addMessageToChat({
...userMessage,
content: contextMessage,
});
// Add typing indicator
const typingIndicator = document.createElement("div");
typingIndicator.addClass("typing-indicator");
// Create spans using DOM API
for (let i = 0; i < 3; i++) {
const span = document.createElement("span");
typingIndicator.appendChild(span);
}
this.messagesContainer?.appendChild(typingIndicator);
try {
this.lastApiCall = Date.now();
// Use RAG, Web Search, or Normal mode
let response: string;
if (this.ragMode && this.ragService && this.ragService.getFileSearchStoreName()) {
const ragResult = await this.ragService.queryWithRAG(
contextMessage || finalMessage,
this.settings.modelName
);
response = ragResult.text;
// Add citation info if available
if (ragResult.citations) {
response += this.formatCitations(ragResult.citations);
}
} else if (this.ragMode && (!this.ragService || !this.ragService.getFileSearchStoreName())) {
// RAG mode is on but not initialized
typingIndicator.remove();
this.addErrorMessage(
"RAG mode is enabled but your vault hasn't been synced yet. Please sync your vault in Settings → VaultAI → RAG Settings."
);
return;
} else if (this.webSearchMode) {
// Use web search mode
const webSearchResult: WebSearchResponse = await this.geminiService.sendMessageWithWebSearch(finalMessage);
response = webSearchResult.text;
// Add web search sources if available
if (webSearchResult.groundingMetadata) {
response += this.formatWebSearchSources(webSearchResult.groundingMetadata);
}
} else {
response = await this.geminiService.sendMessage(finalMessage);
}
typingIndicator.remove();
const botMessage: ChatMessage = {
role: "bot",
content: response,
timestamp: Date.now(),
};
await this.addMessageToChat(botMessage);
// If insert mode is on, automatically insert the response at cursor
if (this.insertMode && this.activeEditor) {
await this.insertAtCursor(response);
new Notice("AI response inserted at cursor");
}
// Update chat session
if (this.currentSession) {
if (this.currentSession.messages.length === 2) {
this.currentSession.title = this.generateSessionTitle(
userMessage.content
);
}
this.settings.chatSessions = [
this.currentSession,
...this.settings.chatSessions.filter(
(s) => s.id !== this.currentSession?.id
),
];
await this.saveSettings();
}
} catch (error) {
typingIndicator.remove();
let errorMessage = "Failed to get response from Gemini";
if (error instanceof Error) {
// Handle safety-related errors
if (error.message.includes("SAFETY")) {
errorMessage =
"I cannot provide a response to that as it may violate content safety guidelines.";
}
// Handle blocked content
else if (
error.message.includes("blocked") ||
error.message.includes("OTHER")
) {
errorMessage =
"I cannot process that request as it was blocked by content filters.";
}
// Handle rate limits
else if (
error.message.includes("429") ||
error.message.includes("quota")
) {
errorMessage =
"API rate limit reached. Please wait a moment before trying again.";
}
// Handle invalid requests
else if (error.message.includes("400")) {
errorMessage =
"Invalid request. Please try rephrasing your message.";
}
// Handle authentication errors
else if (
error.message.includes("401") ||
error.message.includes("403")
) {
errorMessage =
"API authentication failed. Please check your API key in settings.";
}
// Handle server errors
else if (error.message.includes("500")) {
errorMessage =
"Gemini service is currently experiencing issues. Please try again later.";
}
// Log the actual error for debugging
console.error("Gemini API Error:", error);
}
this.addErrorMessage(errorMessage);
}
}
private async addMessageToChat(message: ChatMessage) {
if (!this.messagesContainer) return;
// Hide bot info and suggested actions after first message
if (this.currentSession?.messages.length === 0) {
const botInfo = this.chatContainer?.querySelector(".bot-info");
const suggestedActions = this.chatContainer?.querySelector(
".vaultai-suggested-actions"
);
botInfo?.addClass("hidden");
suggestedActions?.addClass("hidden");
// Remove elements after animation
setTimeout(() => {
botInfo?.remove();
suggestedActions?.remove();
}, 300);
}
const messageEl = document.createElement("div");
messageEl.addClass(`gemini-message-${message.role}`);
if (message.role === "bot") {
// Add copy button
const copyButton = messageEl.createEl("button", {
text: "Copy to new note",
cls: "copy-response-button",
});
copyButton.addEventListener("click", async () => {
// Generate creative title based on content
const title = this.generateNoteTitle(message.content);
const file = await this.app.vault.create(
`${title}.md`,
message.content
);
const leaf = this.app.workspace.getLeaf(false);
await leaf.openFile(file);
new Notice("Response copied to new note!");
});
// Directly render markdown using the correct API
await MarkdownRenderer.render(this.app, message.content, messageEl, "", this);
} else {
// For user messages, just show the visible part
const visibleContent = this.stripContextFromMessage(
message.content
);
messageEl.textContent = visibleContent;
}
this.messagesContainer.appendChild(messageEl);
this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
if (this.currentSession) {
this.currentSession.messages.push(message);
}
}
// Add new method for typing animation
private async typeMessage(text: string, container: HTMLElement) {
// First render the markdown but keep it hidden
await MarkdownRenderer.render(this.app, text, container, "", this);
const elements = Array.from(container.children);
container.empty();
for (const element of elements) {
if (element instanceof HTMLElement) {
if (element.tagName === "P") {
// For paragraphs, type each character
const text = element.textContent || "";
const p = container.createEl("p");
for (const char of text) {
p.textContent += char;
await new Promise((resolve) => setTimeout(resolve, 10)); // Adjust speed here
if (this.messagesContainer) {
this.messagesContainer.scrollTop =
this.messagesContainer.scrollHeight;
}
}
} else {
// For other elements (code blocks, lists, etc.), add them instantly
container.appendChild(element);
}
}
}
}
// Add method to strip context from messages
private stripContextFromMessage(message: string): string {
// Remove the context part from the message
const userQuestionMatch = message.match(/User question: (.*?)$/m);
if (userQuestionMatch) {
return userQuestionMatch[1].trim();
}
return message;
}
private addErrorMessage(message: string) {
const errorDiv = createEl("div", { cls: "gemini-message-error" });
const iconDiv = createEl("div", {
cls: "error-icon",
text: "⚠️",
});
const contentDiv = createEl("div", {
cls: "error-content",
text: message,
});
errorDiv.appendChild(iconDiv);
errorDiv.appendChild(contentDiv);
this.messagesContainer?.appendChild(errorDiv);
if (this.messagesContainer) {
this.messagesContainer.scrollTop =
this.messagesContainer.scrollHeight;
}
}
private addFloatingIcon() {
this.chatIcon = createEl("div", { cls: "gemini-chat-icon" });
const svg = createSvg("svg", {
attr: {
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": "2",
},
});
const path = createSvg("path", {
attr: {
d: "M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z",
},
});
svg.appendChild(path);
this.chatIcon.appendChild(svg);
this.chatIcon.addEventListener("click", () => {
this.toggleChatContainer();
});
document.body.appendChild(this.chatIcon);
}
private addChatContainer() {
this.chatContainer = document.createElement("div");
this.chatContainer.addClass("gemini-chat-container");
this.chatContainer.addClass("initially-hidden");
this.chatContainer.addClass("default-size");
// Create header
const header = this.createChatHeader();
this.chatContainer.appendChild(header);
// Create bot info
const botInfo = this.createBotInfo();
this.chatContainer.appendChild(botInfo);
// Create messages container
const messagesContainer = document.createElement("div");
messagesContainer.addClass("gemini-chat-messages");
this.chatContainer.appendChild(messagesContainer);
// Create suggested actions
const suggestedActions = this.createSuggestedActions();
this.chatContainer.appendChild(suggestedActions);
// Create input container
const inputContainer = this.createInputContainer();
this.chatContainer.appendChild(inputContainer);
document.body.appendChild(this.chatContainer);
// Add event listeners for the buttons
this.addChatEventListeners();
// Add resize handle
const resizeHandle = document.createElement("div");
resizeHandle.addClass("resize-handle");
this.chatContainer.appendChild(resizeHandle);
// Add resize functionality
this.addResizeFunctionality(resizeHandle);
}
private createChatHeader(): HTMLElement {
const header = document.createElement("div");
header.addClass("gemini-chat-header");
// Current file indicator
const currentFile = document.createElement("div");
currentFile.addClass("current-file");
header.appendChild(currentFile);
// Header controls
const controls = document.createElement("div");
controls.addClass("chat-header-controls");
// History button
const historyButton = document.createElement("button");
historyButton.addClass("history-button");
const historyIcon = this.createHistoryIcon();
historyButton.appendChild(historyIcon);
controls.appendChild(historyButton);
// More button
const moreButton = document.createElement("button");
moreButton.addClass("more-button");
const moreIcon = this.createMoreIcon();
moreButton.appendChild(moreIcon);
controls.appendChild(moreButton);
// Close button
const closeButton = document.createElement("button");
closeButton.addClass("close-button");
const closeIcon = this.createCloseIcon();
closeButton.appendChild(closeIcon);
controls.appendChild(closeButton);
header.appendChild(controls);
return header;
}
private createHistoryIcon(): SVGElement {
const svg = createSvg("svg", {
attr: {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": "2",
"stroke-linecap": "round",
"stroke-linejoin": "round",
},
});
const circle = createSvg("circle", {
attr: {
cx: "12",
cy: "12",
r: "10",
},
});
const polyline = createSvg("polyline", {
attr: {
points: "12 6 12 12 16 14",
},
});
svg.appendChild(circle);
svg.appendChild(polyline);
return svg;
}
private createMoreIcon(): SVGElement {
const svg = createSvg("svg", {
attr: {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": "2",
"stroke-linecap": "round",
"stroke-linejoin": "round",
},
});
const rect = createSvg("rect", {
attr: {
x: "3",
y: "3",
width: "18",
height: "18",
rx: "2",
ry: "2",
},
});
const line1 = createSvg("line", {
attr: {
x1: "3",
y1: "12",
x2: "21",
y2: "12",
},
});
const line2 = createSvg("line", {
attr: {
x1: "12",
y1: "3",
x2: "12",
y2: "21",
},
});
svg.appendChild(rect);
svg.appendChild(line1);
svg.appendChild(line2);
return svg;
}
private createCloseIcon(): SVGElement {
const svg = createSvg("svg", {
attr: {
xmlns: "http://www.w3.org/2000/svg",
width: "20",
height: "20",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": "2",
"stroke-linecap": "round",
"stroke-linejoin": "round",
},
});
const line1 = createSvg("line", {
attr: {
x1: "18",
y1: "6",
x2: "6",
y2: "18",
},
});
const line2 = createSvg("line", {
attr: {
x1: "6",
y1: "6",
x2: "18",
y2: "18",
},
});
svg.appendChild(line1);
svg.appendChild(line2);
return svg;
}
private createBotInfo(): HTMLElement {
const botInfo = document.createElement("div");
botInfo.addClass("bot-info");
// Bot avatar container
const avatarContainer = document.createElement("div");
avatarContainer.addClass("bot-avatar");
// Create the avatar SVG (simplified for security)
const avatarSvg = this.createBotAvatarSvg();
avatarContainer.appendChild(avatarSvg);
// Bot greeting
const greeting = document.createElement("div");
greeting.addClass("bot-greeting");
greeting.textContent = "Hello, How can I help you today?";
botInfo.appendChild(avatarContainer);
botInfo.appendChild(greeting);
return botInfo;
}
private createBotAvatarSvg(): SVGElement {
// Create simplified avatar SVG for security
const svg = createSvg("svg", {
attr: {
viewBox: "0 0 100 100",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
},
});
// Simple circle avatar
const circle = createSvg("circle", {
attr: {
cx: "50",
cy: "50",
r: "40",