-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
416 lines (354 loc) · 11.4 KB
/
script.js
File metadata and controls
416 lines (354 loc) · 11.4 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
let userType = document.getElementById("promptTextarea");
let userChatContainer = document.querySelector(".chat-container");
let imageButton = document.getElementById("image_button");
let imageInput = document.querySelector("#image_button input");
let image = document.querySelector("#image_button img");
let submitBtn = document.getElementById("submit")
// API configuration - will be loaded from config.js
let API_KEY = "";
let Api_Url = "";
// Initialize API configuration
function initializeAPI() {
// Try to get from window.CONFIG (loaded from config.js)
if (window.CONFIG && window.CONFIG.API_KEY) {
API_KEY = window.CONFIG.API_KEY;
console.log("✅ API configuration loaded from local config");
} else {
// For production, try to fetch from Vercel API endpoint
fetchProductionConfig();
return;
}
Api_Url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
}
// Fetch API configuration from production endpoint
async function fetchProductionConfig() {
try {
const response = await fetch('/config.js');
if (response.ok) {
const configScript = await response.text();
eval(configScript); // Execute the config script
if (window.CONFIG && window.CONFIG.API_KEY) {
API_KEY = window.CONFIG.API_KEY;
Api_Url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
console.log("✅ API configuration loaded from production endpoint");
} else {
throw new Error("Invalid config from production endpoint");
}
} else {
throw new Error("Failed to fetch production config");
}
} catch (error) {
console.error("❌ Failed to load API configuration:", error);
showAPIErrorMessage();
}
}
// Show error message when API is not configured
function showAPIErrorMessage() {
const errorHtml = `<i class="fa-solid fa-exclamation-triangle"></i>
<div class="aiChatArea" style="background: rgba(255, 0, 0, 0.1); color: #ff6b6b;">
⚠️ API configuration error. Please check your environment variables in Vercel dashboard.
</div>`;
const errorBox = createUserBox(errorHtml, "ai-chatBox");
userChatContainer.appendChild(errorBox);
}
// Initialize floating icons animation
document.addEventListener('DOMContentLoaded', function() {
// Initialize API configuration first
initializeAPI();
// Then start animations
initFloatingIcons();
});
function initFloatingIcons() {
const icons = document.querySelectorAll('.floating-icon');
icons.forEach((icon, index) => {
// Set random initial position
const startX = Math.random() * window.innerWidth;
const startY = Math.random() * window.innerHeight;
gsap.set(icon, {
x: startX,
y: startY,
opacity: 0.7,
scale: Math.random() * 0.5 + 0.8
});
// Create continuous floating animation
createFloatingAnimation(icon, index);
});
}
function createFloatingAnimation(icon, index) {
const tl = gsap.timeline({ repeat: -1 });
// Generate random path points
const points = [];
for (let i = 0; i < 4; i++) {
points.push({
x: Math.random() * (window.innerWidth - 100),
y: Math.random() * (window.innerHeight - 100)
});
}
// Animate through the path points
points.forEach((point, i) => {
tl.to(icon, {
x: point.x,
y: point.y,
duration: Math.random() * 8 + 5, // 5-13 seconds per segment
ease: "sine.inOut",
rotation: Math.random() * 360,
scale: Math.random() * 0.8 + 0.8,
opacity: Math.random() * 0.4 + 0.5
});
});
// Add floating effect (up and down movement)
gsap.to(icon, {
y: "+=30",
duration: 3 + Math.random() * 2,
yoyo: true,
repeat: -1,
ease: "sine.inOut",
delay: Math.random() * 2
});
// Add rotation animation
gsap.to(icon, {
rotation: "+=360",
duration: 15 + Math.random() * 10,
repeat: -1,
ease: "none"
});
// Add scale breathing effect
gsap.to(icon, {
scale: "+=0.3",
duration: 4 + Math.random() * 3,
yoyo: true,
repeat: -1,
ease: "power2.inOut",
delay: Math.random() * 3
});
// Add opacity pulsing
gsap.to(icon, {
opacity: Math.random() * 0.5 + 0.4,
duration: 2 + Math.random() * 2,
yoyo: true,
repeat: -1,
ease: "power2.inOut",
delay: Math.random() * 4
});
}
// Regenerate animation on window resize
window.addEventListener('resize', () => {
gsap.killTweensOf('.floating-icon');
initFloatingIcons();
});
let user = {
message: null,
file: {
mime_type: null,
data: null,
},
};
async function generateResponse(aiChatBox) {
// Check if API is properly configured
if (!API_KEY || API_KEY === "YOUR_API_KEY_PLACEHOLDER") {
console.error("❌ API key not configured");
showAPIErrorMessage();
return;
}
let text = document.querySelector(".aiChatArea");
// Show loading state
let loadingHtml = `<i class="fa-solid fa-brain"></i>
<div class="aiChatArea loading">Thinking...</div>`;
let loadingBox = createUserBox(loadingHtml, "ai-chatBox");
userChatContainer.appendChild(loadingBox);
userChatContainer.scrollTo({
top: userChatContainer.scrollHeight,
behavior: "smooth",
});
let RequestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [
{
parts: [
{ text: user.message },
...(user.file.data ? [{ "inline_data": user.file }] : []
),
],
},
],
}),
};
try {
let response = await fetch(Api_Url, RequestOptions);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}: ${response.statusText}`);
}
let data = await response.json();
// Check if the response has the expected structure
if (!data.candidates || !data.candidates[0] || !data.candidates[0].content || !data.candidates[0].content.parts || !data.candidates[0].content.parts[0]) {
throw new Error('Invalid response structure from API');
}
let apiResponse = data.candidates[0].content.parts[0].text.trim();
console.log(apiResponse);
// Remove loading box
userChatContainer.removeChild(loadingBox);
let aiResponseHtml = `<i class="fa-solid fa-brain"></i>
<div class="aiChatArea">${apiResponse}</div>`;
let aiResponseBox = createUserBox(aiResponseHtml, "ai-chatBox");
// Append the new div to the chat container
userChatContainer.appendChild(aiResponseBox);
} catch (error) {
console.error('Error in generateResponse:', error);
// Remove loading box if it exists
if (loadingBox && userChatContainer.contains(loadingBox)) {
userChatContainer.removeChild(loadingBox);
}
// Show error message to user
let errorHtml = `<i class="fa-solid fa-triangle-exclamation"></i>
<div class="aiChatArea">Sorry, I encountered an error: ${error.message}. Please try again.</div>`;
let errorBox = createUserBox(errorHtml, "ai-chatBox");
userChatContainer.appendChild(errorBox);
} finally {
userChatContainer.scrollTo({
top: userChatContainer.scrollHeight,
behavior: "smooth",
});
image.src = `imageForAi.jpg`
image.classList.remove("chooseClass")
user.file = {}
}
}
function createUserBox(html, classes) {
let div = document.createElement("div");
div.innerHTML = html;
div.classList.add(classes);
return div;
}
// function generateResponse() {} // Removed duplicate function definition
function handleUserType(userEnter) {
// Prevent empty messages
if (!userEnter.trim() && !user.file.data) {
return;
}
user.message = userEnter;
let html = `<i class="fa-regular fa-user"></i>
<div class="userChatArea">
${user.message}
${user.file.data ? `<img src="data:${user.file.mime_type};base64,${user.file.data}" class="chooseimg" />` : ''}
</div>`;
userType.value = "";
let userChatBox = createUserBox(html, "user-chatBox");
userChatContainer.appendChild(userChatBox);
userChatContainer.scrollTo({
top: userChatContainer.scrollHeight,
behavior: "smooth",
});
// Add burst effect to floating icons on message send
burstIconsEffect();
// Disable input while processing
userType.disabled = true;
submitBtn.disabled = true;
setTimeout(() => {
generateResponse().finally(() => {
// Re-enable input after response
userType.disabled = false;
submitBtn.disabled = false;
userType.focus();
});
}, 600);
}
userType.addEventListener("keydown", (e) => {
if (e.key == "Enter") {
handleUserType(userType.value);
}
});
submitBtn.addEventListener("click", () => {
handleUserType(userType.value)
})
imageInput.addEventListener("change", () => {
const file = imageInput.files[0];
if (!file) return;
let reader = new FileReader();
reader.onload = (e) => {
console.log(e);
let base64String = e.target.result.split(",")[1];
user.file = {
mime_type: file.type,
data: base64String,
};
image.src = `data:${user.file.mime_type};base64,${user.file.data}`
image.classList.add("chooseClass")
};
reader.readAsDataURL(file);
});
imageButton.addEventListener("click", () => {
imageButton.querySelector("input").click();
});
// Add burst effect to floating icons
function burstIconsEffect() {
const icons = document.querySelectorAll('.floating-icon');
icons.forEach((icon, index) => {
// Temporary burst animation
gsap.to(icon, {
scale: "+=0.5",
opacity: "+=0.3",
rotation: "+=180",
duration: 0.8,
ease: "back.out(1.7)",
yoyo: true,
repeat: 1,
delay: index * 0.1
});
});
}
// Add mouse interaction effect
document.addEventListener('mousemove', (e) => {
const icons = document.querySelectorAll('.floating-icon');
icons.forEach((icon) => {
const rect = icon.getBoundingClientRect();
const iconCenterX = rect.left + rect.width / 2;
const iconCenterY = rect.top + rect.height / 2;
const distance = Math.sqrt(
Math.pow(e.clientX - iconCenterX, 2) +
Math.pow(e.clientY - iconCenterY, 2)
);
// If mouse is close to icon, make it more visible and larger
if (distance < 150) {
const intensity = (150 - distance) / 150;
gsap.to(icon, {
scale: 1 + intensity * 0.8,
opacity: 0.5 + intensity * 0.5,
duration: 0.3,
ease: "power2.out"
});
}
});
});
// Add click effect on chat container
document.querySelector('.chat-container').addEventListener('click', (e) => {
// Create temporary sparkle effect at click position
createSparkleEffect(e.clientX, e.clientY);
});
function createSparkleEffect(x, y) {
const icons = document.querySelectorAll('.floating-icon');
icons.forEach((icon, index) => {
const rect = icon.getBoundingClientRect();
const iconCenterX = rect.left + rect.width / 2;
const iconCenterY = rect.top + rect.height / 2;
const distance = Math.sqrt(
Math.pow(x - iconCenterX, 2) +
Math.pow(y - iconCenterY, 2)
);
// Create ripple effect based on distance
if (distance < 300) {
const delay = distance / 300 * 0.5; // Further icons animate later
gsap.to(icon, {
scale: "+=0.8",
opacity: "+=0.5",
rotation: "+=360",
duration: 1,
ease: "elastic.out(1, 0.5)",
delay: delay,
yoyo: true,
repeat: 1
});
}
});
}