-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
206 lines (205 loc) · 8.07 KB
/
script.js
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
const container = document.querySelector(".container");
const chatsContainer = document.querySelector(".chats-container");
const promptForm = document.querySelector(".prompt-form");
const promptInput = promptForm.querySelector(".prompt-input");
const fileInput = promptForm.querySelector("#file-input");
const fileUploadWrapper = promptForm.querySelector(".file-upload-wrapper");
const themeToggleBtn = document.querySelector("#theme-toggle-btn");
const searchParams = new URLSearchParams(window.location.search);
const API_KEY =
searchParams.get("key") || "AIzaSyDJQhISmYz7HcHTX4ZHlmGZbN7oh4UaYag"; // get from https://aistudio.google.com/app/apikey
const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
let controller, typingInterval;
const chatHistory = [];
const userData = { message: "", file: {} };
// Set initial theme from local storage
const isLightTheme = localStorage.getItem("themeColor") === "light_mode";
document.body.classList.toggle("light-theme", isLightTheme);
themeToggleBtn.textContent = isLightTheme ? "dark_mode" : "light_mode";
// Function to create message elements
const createMessageElement = (content, ...classes) => {
const div = document.createElement("div");
div.classList.add("message", ...classes);
div.innerHTML = content;
return div;
};
// Scroll to the bottom of the container
const scrollToBottom = () =>
container.scrollTo({ top: container.scrollHeight, behavior: "smooth" });
// Simulate typing effect for bot responses
const typingEffect = (text, textElement, botMsgDiv) => {
textElement.textContent = "";
const words = text.split(" ");
let wordIndex = 0;
// Set an interval to type each word
typingInterval = setInterval(() => {
if (wordIndex < words.length) {
textElement.textContent +=
(wordIndex === 0 ? "" : " ") + words[wordIndex++];
scrollToBottom();
} else {
clearInterval(typingInterval);
botMsgDiv.classList.remove("loading");
document.body.classList.remove("bot-responding");
}
}, 40); // 40 ms delay
};
// Make the API call and generate the 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 effect
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.textContent =
error.name === "AbortError"
? "Response generation stopped."
: error.message;
textElement.style.color = "#d62939";
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;
userData.message = userMessage;
promptInput.value = "";
document.body.classList.add("chats-active", "bot-responding");
fileUploadWrapper.classList.remove("file-attached", "img-attached", "active");
// Generate user message HTML with optional file attachment
const userMsgHTML = `
<p class="message-text"></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 = createMessageElement(userMsgHTML, "user-message");
userMsgDiv.querySelector(".message-text").textContent = userData.message;
chatsContainer.appendChild(userMsgDiv);
scrollToBottom();
setTimeout(() => {
// Generate bot message HTML and add in the chat container
const botMsgHTML = `<img class="avatar" src="https://cdn.freelogovectors.net/wp-content/uploads/2024/02/gemini_logo-chatbot-freelogovectors.net_-180x135.png" /> <p class="message-text">Just a sec...</p>`;
const botMsgDiv = createMessageElement(
botMsgHTML,
"bot-message",
"loading"
);
chatsContainer.appendChild(botMsgDiv);
scrollToBottom();
generateResponse(botMsgDiv);
}, 600); // 600 ms delay
};
// Handle file input change (file upload)
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 = "";
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,
};
};
});
// Cancel file upload
document.querySelector("#cancel-file-btn").addEventListener("click", () => {
userData.file = {};
fileUploadWrapper.classList.remove("file-attached", "img-attached", "active");
});
// Stop Bot Response
document.querySelector("#stop-response-btn").addEventListener("click", () => {
controller?.abort();
userData.file = {};
clearInterval(typingInterval);
chatsContainer
.querySelector(".bot-message.loading")
.classList.remove("loading");
document.body.classList.remove("bot-responding");
});
// Toggle dark/light theme
themeToggleBtn.addEventListener("click", () => {
const isLightTheme = document.body.classList.toggle("light-theme");
localStorage.setItem("themeColor", isLightTheme ? "light_mode" : "dark_mode");
themeToggleBtn.textContent = isLightTheme ? "dark_mode" : "light_mode";
});
// Delete all chats
document.querySelector("#delete-chats-btn").addEventListener("click", () => {
chatHistory.length = 0;
chatsContainer.innerHTML = "";
document.body.classList.remove("chats-active", "bot-responding");
});
// Handle suggestions click
document.querySelectorAll(".suggestions-item").forEach((suggestion) => {
suggestion.addEventListener("click", () => {
promptInput.value = suggestion.querySelector(".text").textContent;
promptForm.dispatchEvent(new Event("submit"));
});
});
// Show/hide controls for mobile on prompt input focus
document.addEventListener("click", ({ target }) => {
const wrapper = document.querySelector(".prompt-wrapper");
const shouldHide =
target.classList.contains("prompt-input") ||
(wrapper.classList.contains("hide-controls") &&
(target.id === "add-file-btn" || target.id === "stop-response-btn"));
wrapper.classList.toggle("hide-controls", shouldHide);
});
// Add event listeners for form submission and file input click
promptForm.addEventListener("submit", handleFormSubmit);
promptForm
.querySelector("#add-file-btn")
.addEventListener("click", () => fileInput.click());