-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
210 lines (158 loc) · 7.04 KB
/
script.js
File metadata and controls
210 lines (158 loc) · 7.04 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
const chatsContainer = document.querySelector(".chats-container");
const promptForm = document.querySelector(".prompt-form");
const promptInput = promptForm.querySelector("input"); // fixed
const fileinput = promptForm.querySelector("#file-input");
const fileUploadWrapper = promptForm.querySelector(".file-upload-wrapper");
const themeToggle = document.querySelector("#theme-toggle-btn");
//api setup
const API_KEY = "AIzaSyAsalRw9Ofd2x9jp_zh0UF6roBt9i6M42c";
const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${API_KEY}`;
let typingInterval, controller;
const chatHistory = [];
const userData ={message: "", file:{}};
// Scroll to the bottom of the container
const scrollToBottom = () => {
const container = document.querySelector(".container");
container.scrollTop = container.scrollHeight;
}
// Function to create message element
const createMsgElement = (content, ...classes) => {
const div = document.createElement("div");
div.classList.add("message", ...classes);
div.innerHTML = content; // fixed
return div;
};
//stimulate typing effect for bot response
const typingEffect = (responseText, textElement, botMsgDiv) => {
textElement.textContent = "";
const words = responseText.split("");
let wordIndex = 0;
typingInterval = setInterval(() => {
if (wordIndex < words.length) {
textElement.textContent += words[wordIndex++];
scrollToBottom();
} else {
clearInterval(typingInterval);
botMsgDiv.classList.remove("loading");
document.body.classList.remove("bot-responding");
}
}, 40);
};
//Make the api call and generate to bot's response
const generateResponse = async (botMsgDiv) =>{
const textElement = botMsgDiv.querySelector(".message-text");
controller = new AbortController();
//Add user message and file data to the chat history
chatHistory.push({
role: "user",
parts: [{ text: userData.message }, ...(userData.file.data ? [{ inline_data: (({ fileName, isImage, ...rest }) => rest)
(userData.file) }] : [])]
});
try{
// Send the chat history to the Api to get a response
const response = await fetch(API_URL,{
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({ contents: chatHistory}),
signal: controller.signal
});
const data =await response.json();
if(!response.ok) throw new Error(data.error.message);
// Process the response text and display with typing effectl
const responseText = data.candidates[0].content.parts[0].text.replace(/\*\*([^*]+)\*\*/g, "$1").trim();
typingEffect(responseText, textElement ,botMsgDiv);
chatHistory.push({role: "model",parts: [{ text: responseText }]});
}catch(error){
textElement.style.color="#d62939"
textElement.textContent = error.name === "AbortError" ? "Response generation stopped." : error.message;
botMsgDiv.classList.remove("loading");
document.body.classList.remove("bot-responding");
scrollToBottom();
} finally{
userData.file={};
}
};
// Handle the form submission
const handleFormSubmit = (e) => {
e.preventDefault();
const userMessage = promptInput.value.trim();
if (!userMessage || document.body.classList.contains("bot-responding")) return;
promptInput.value="";
userData.message= userMessage;
document.body.classList.add("bot-responding","chats-active");
fileUploadWrapper.classList.remove("active", "img-attached", "file-attached");
// Generate user message HTML and add in chats container
const userMsgHTML = `
<p class="message-text">${userMessage}</p>
${
userData.file.data
? (userData.file.isImage
? `<img src="data:${userData.file.mime_type};base64,${userData.file.data}" class="img-attachment" />`
: `<p class="file-attachment"><span class="material-symbols-rounded">description</span>${userData.file.fileName}</p>`
)
: ""
}
`;
const userMsgDiv = createMsgElement(userMsgHTML, "user-message");
userMsgDiv.querySelector(".message-text").textContent=userMessage;
chatsContainer.appendChild(userMsgDiv);
scrollToBottom();
setTimeout(() => {
// Generate bot message HTML and add in chats container after 100ms
const botMsgHTML = `<img src="gemini.svg" class="avatar"><p class="message-text">Just a sec...</p>`;
const botMsgDiv = createMsgElement(botMsgHTML, "bot-message","loading");
chatsContainer.appendChild(botMsgDiv);
scrollToBottom();
generateResponse(botMsgDiv);
}, 100);
};
// Hndle file input chnage
fileinput.addEventListener("change",() =>{
const file= fileinput.files[0];
if(!file) return;
const isImage= file.type.startsWith("image/");
const reader= new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) =>{
fileinput.value="";
//Gemini always recieves the base 64 string of the file
const base64String = e.target.result.split(",")[1];
fileUploadWrapper.querySelector(".file-preview").src=e.target.result;
fileUploadWrapper.classList.add("active",isImage ? "img-attached": "file-attached");
// store file data in userData obj
userData.file={ fileName: file.name, data: base64String, mime_type: file.type, isImage }
}
});
// stop ongoing bot response
document.querySelector("#stop-response-btn").addEventListener("click", () =>{
userData.file={};
controller?.abort();
clearInterval(typingInterval);
chatsContainer.querySelector(".bot-message.loading").classList.remove("loading");
document.body.classList.remove("bot-responding");
});
// delete all chats
document.querySelector("#delete-chats-btn").addEventListener("click", () =>{
chatHistory.length = 0;
chatsContainer.innerHTML="";
document.body.classList.remove("bot-responding","chats-active");
});
//Handle suggestions click
document.querySelectorAll(".suggestions-item").forEach( item =>{
item.addEventListener("click",() => {
promptInput.value = item.querySelector(".text").textContent;
promptForm.dispatchEvent(new Event("submit"));
});
});
// Toggle dark/light theme
themeToggle.addEventListener("click", ()=>{
const isLightTheme= document.body.classList.toggle("light-theme");
localStorage.setItem("themeColor", isLightTheme ? "light_mode": "dark_mode");
themeToggle.textContent = isLightTheme ? "dark_mode" : "light_mode";
});
//set initial theme from local storage
const isLightTheme= localStorage.getItem("themeColor") === "light_mode";
document.body.classList.toggle("light-theme",isLightTheme);
themeToggle.textContent = isLightTheme ? "dark_mode" : "light_mode";
promptForm.addEventListener("submit", handleFormSubmit);
promptForm.querySelector("#add-file-btn").addEventListener("click", () => fileinput.click());