-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
196 lines (160 loc) · 7.39 KB
/
Copy pathscript.js
File metadata and controls
196 lines (160 loc) · 7.39 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
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 themeToggle = document.querySelector('#theme-toggle-btn');
const API_KEY = 'AIzaSyB8mgHxqmNwOHO7_EXPASweEDoi_XZpF50';
const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${API_KEY}`;
let typingInterval , controller;
const userData ={ message: "" , file: {}}
const chatHistory = [];
const createMsgElement = (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 scrollToBotttom = () => container.scrollTo( { top: container.scrollHeight ,behavior: "smooth"});
//simulate typing effect for the bot
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++];
scrollToBotttom();
}else{
botMsgDiv.classList.remove('loading');
document.body.classList.remove('bot-responding');
clearInterval(typingInterval);
}
},40)
};
//make api call and generate the boot's response
const generateResponse = async(botMsgDiv) => {
const textElement = botMsgDiv.querySelector('.message-text');
controller = new AbortController();
//add user message and file to the chat history
chatHistory.push({
role: "user",
parts:[{text: userData.message}, ...(userData.file.data ? [{ inline_data :(({ fileName, isImage,...rest}) =>rest)(userData.file) }] : [])]
});
try {
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 and display them 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}] });
console.log(chatHistory);
// console.log(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');
scrollToBotttom();
}finally{
userData.file = {};
}
}
// handling 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; //adding user message to userdata object
document.body.classList.add('bot-responding');
fileUploadWrapper.classList.remove('active' , 'img-attached','file-attached');
// generates user message html and in the chats container
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-outlined">description</span>${userData.file.fileName}</p>`) : ""}
`;
const userMsgDiv = createMsgElement(userMsgHTML, 'user-message');
userMsgDiv.querySelector('.message-text').textContent = userMessage;
chatsContainer.appendChild(userMsgDiv);
scrollToBotttom(); //scroll after each message added
setTimeout(() => {
// generate bot message html and add the chats after 600ms
const botMsgHTML = `<img src="chatbot-logo.svg" alt="" class="avatar">
<p class="message-text">
Just a sec...
</p>` ;
const botMsgDiv = createMsgElement(botMsgHTML , 'bot-message' , 'loading');
chatsContainer.appendChild(botMsgDiv);
generateResponse(botMsgDiv);
}, 600)
};
//handle file input change (file upload)
fileInput.addEventListener('change' , () => {
const file = fileInput.files[0];
if(!file) return;
console.log(file);
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('active' , 'img-attached','file-attached');
});
//stop ongoing bot responce
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');
});
//handle suggestion click
document.querySelectorAll('.suggestion-item').forEach(item => {
item.addEventListener('click', () => {
promptInput.value = item.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-responce-btn'));
wrapper.classList.toggle('hide-controls', shouldHide);
});
//toggeling theme color
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());