-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
2237 lines (1918 loc) · 71.8 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
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
document.addEventListener("DOMContentLoaded", () => {
const checkbox = document.getElementById("checkbox");
const body = document.body;
document.addEventListener("paste", (e) => {
const activeTab = document.querySelector(".tab-content.active");
if (!activeTab) return;
const toolInputMap = {
// Image tools
"compression-jpg": { id: "image-to-compress-jpg", type: "image" },
"compression-png": { id: "image-to-compress-png", type: "image" },
comparison: { id: "image-files", type: "image" },
resize: { id: "image-to-resize", type: "image" },
crop: { id: "image-to-crop", type: "image" },
flip: { id: "image-to-flip", type: "image" },
rotate: { id: "image-to-rotate", type: "image" },
colouradjust: { id: "image-to-adjust", type: "image" },
colorcurves: { id: "image-for-curves", type: "image" },
metadata: { id: "image-for-metadata", type: "image" },
// PDF tools
"merge-pdf": { id: "pdf-files", type: "pdf" },
"split-pdf": { id: "pdf-to-split", type: "pdf" },
"pdf-to-word": { id: "pdf-file-to-word", type: "pdf" },
"pdf-to-text": { id: "pdf-file-to-text", type: "pdf" },
};
const toolConfig = toolInputMap[activeTab.id];
if (!toolConfig) return;
const items = e.clipboardData.items;
for (const item of items) {
const itemType = item.type.toLowerCase();
// Handle images
if (toolConfig.type === "image" && itemType.startsWith("image/")) {
handlePastedFile(
item.getAsFile(),
toolConfig.id,
"image pasted from clipboard",
);
break;
}
// Handle PDFs
if (toolConfig.type === "pdf" && itemType === "application/pdf") {
handlePastedFile(
item.getAsFile(),
toolConfig.id,
"PDF pasted from clipboard",
);
break;
}
}
});
function handlePastedFile(file, inputId, labelText) {
const input = document.getElementById(inputId);
if (!input) return;
// Create a FileList-like object
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
input.files = dataTransfer.files;
// Trigger the change event
input.dispatchEvent(new Event("change"));
// Update the file input label
const label = input
.closest(".file-input-wrapper")
?.querySelector(".file-input-label");
if (label) {
label.textContent = labelText;
}
}
// Load saved theme preference
function initializeTheme() {
try {
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
body.classList.toggle("light-theme", savedTheme === "light");
checkbox.checked = savedTheme === "light";
}
} catch (error) {
console.error("error loading theme:", error);
}
}
function initializeCarouselCreator() {
const carouselForm = document.getElementById("carousel-form");
const carouselImages = document.getElementById("carousel-images");
const carouselPreview = document.getElementById("carousel-preview");
const createCarouselBtn = document.getElementById("create-carousel");
const carouselResult = document.getElementById("carousel-result");
const qualitySlider = document.getElementById("carousel-quality");
const qualityValue = document.getElementById("quality-value");
const aspectRatioSelect = document.getElementById("carousel-ratio");
let originalImage = null;
qualitySlider.addEventListener("input", () => {
qualityValue.textContent = `${qualitySlider.value}%`;
});
carouselImages.addEventListener("change", (event) => {
const file = event.target.files[0];
if (!file || !file.type.startsWith("image/")) {
alert("please select an image file");
return;
}
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
originalImage = img;
showPreview();
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
function showPreview() {
const previewCanvas = document.createElement("canvas");
const ctx = previewCanvas.getContext("2d");
// Set preview canvas size
previewCanvas.width = originalImage.width;
previewCanvas.height = originalImage.height;
// Draw original image
ctx.drawImage(originalImage, 0, 0);
// Calculate number of segments based on image width and selected ratio
const ratio = aspectRatioSelect.value;
const segmentWidth = getRatioWidth(ratio, originalImage.height);
const numberOfSegments = Math.ceil(originalImage.width / segmentWidth);
// Draw grid lines
ctx.strokeStyle = "rgba(255, 255, 255, 0.8)";
ctx.lineWidth = 2;
for (let i = 1; i < numberOfSegments; i++) {
const x = i * segmentWidth;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, originalImage.height);
ctx.stroke();
}
carouselPreview.innerHTML = "";
carouselPreview.appendChild(previewCanvas);
}
createCarouselBtn.addEventListener("click", async () => {
if (!originalImage) {
alert("please select an image first");
return;
}
const quality = parseInt(qualitySlider.value) / 100;
const ratio = aspectRatioSelect.value;
const segmentWidth = getRatioWidth(ratio, originalImage.height);
const numberOfSegments = Math.ceil(originalImage.width / segmentWidth);
carouselResult.innerHTML = "<p>Creating carousel segments...</p>";
try {
const segments = [];
for (let i = 0; i < numberOfSegments; i++) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Set dimensions based on selected ratio
const [width, height] = getCarouselDimensions();
canvas.width = width;
canvas.height = height;
// Fill with white background
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, width, height);
// Draw segment of original image
ctx.drawImage(
originalImage,
i * segmentWidth, // source x
0, // source y
segmentWidth, // source width
originalImage.height, // source height
0, // dest x
0, // dest y
width, // dest width
height, // dest height
);
segments.push(canvas.toDataURL("image/jpeg", quality));
}
// Display results
carouselResult.innerHTML = "<h3>Carousel Segments</h3>";
segments.forEach((dataUrl, index) => {
const wrapper = document.createElement("div");
wrapper.className = "segment-wrapper";
const img = document.createElement("img");
img.src = dataUrl;
img.className = "segment-preview";
const downloadBtn = document.createElement("a");
downloadBtn.href = dataUrl;
downloadBtn.download = `carousel-${index + 1}.jpg`;
downloadBtn.className = "button";
downloadBtn.textContent = `Download Segment ${index + 1}`;
wrapper.appendChild(img);
wrapper.appendChild(downloadBtn);
carouselResult.appendChild(wrapper);
});
} catch (error) {
console.error("Error creating segments:", error);
carouselResult.innerHTML = `
<p class="error">Error creating carousel segments: ${error.message}</p>
`;
}
});
function getRatioWidth(ratio, height) {
switch (ratio) {
case "1:1":
return height;
case "4:5":
return (height * 4) / 5;
case "16:9":
return (height * 16) / 9;
default:
return height;
}
}
function getCarouselDimensions() {
const ratio = aspectRatioSelect.value;
switch (ratio) {
case "1:1":
return [1080, 1080];
case "4:5":
return [1080, 1350];
case "16:9":
return [1080, 607];
default:
return [1080, 1080];
}
}
function processImage(src, targetWidth, targetHeight, quality) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
try {
const canvas = document.createElement("canvas");
canvas.width = targetWidth;
canvas.height = targetHeight;
const ctx = canvas.getContext("2d");
// Calculate dimensions to maintain aspect ratio
const scale = Math.max(
targetWidth / img.width,
targetHeight / img.height,
);
const scaledWidth = img.width * scale;
const scaledHeight = img.height * scale;
const x = (targetWidth - scaledWidth) / 2;
const y = (targetHeight - scaledHeight) / 2;
// Fill background with white
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, targetWidth, targetHeight);
// Draw image
ctx.drawImage(img, x, y, scaledWidth, scaledHeight);
resolve(canvas.toDataURL("image/jpeg", quality));
} catch (error) {
reject(error);
}
};
img.onerror = () => {
reject(new Error("Failed to load image"));
};
img.src = src;
});
}
}
// Handle theme toggle
function handleThemeToggle() {
try {
body.classList.toggle("light-theme");
localStorage.setItem(
"theme",
body.classList.contains("light-theme") ? "light" : "dark",
);
} catch (error) {
console.error("Error saving theme:", error);
}
}
// Add event listener to checkbox
if (checkbox) {
checkbox.addEventListener("change", handleThemeToggle);
initializeTheme(); // Initialize theme when page loads
} else {
console.error("Theme toggle checkbox not found!");
}
/* ================== Tab Navigation ================== */
const tabLinks = document.querySelectorAll(".tab-link");
const tabContents = document.querySelectorAll(".tab-content");
tabLinks.forEach((link) => {
link.addEventListener("click", (event) => {
const tabName = event.currentTarget.getAttribute("data-tab");
openTab(event, tabName);
});
});
console.log("Script version:", "0.1.0");
console.log("Last updated:", new Date().toISOString());
function isLocalStorageAvailable() {
try {
const test = "__storage_test__";
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch (e) {
return false;
}
}
// Initialize storage with a fallback for incognito mode
let storageType = isLocalStorageAvailable()
? localStorage
: {
_data: {},
setItem(id, val) {
this._data[id] = val;
},
getItem(id) {
return this._data[id] || null;
},
removeItem(id) {
delete this._data[id];
},
};
function setupDragAndDrop() {
const fileInputs = document.querySelectorAll(".file-input");
fileInputs.forEach((fileInput) => {
const wrapper = fileInput.closest(".file-input-wrapper");
wrapper.addEventListener("dragover", (e) => {
e.preventDefault();
e.stopPropagation();
wrapper.classList.add("dragover");
});
wrapper.addEventListener("dragleave", (e) => {
e.preventDefault();
e.stopPropagation();
wrapper.classList.remove("dragover");
});
wrapper.addEventListener("drop", (e) => {
e.preventDefault();
e.stopPropagation();
wrapper.classList.remove("dragover");
if (e.dataTransfer.files.length) {
fileInput.files = e.dataTransfer.files;
updateFileInputLabel(fileInput);
// Trigger change event to update preview if needed
const changeEvent = new Event("change");
fileInput.dispatchEvent(changeEvent);
}
});
});
}
const fileInput = document.getElementById("image-files");
const fileLabel = document.getElementById("file-label");
fileInput.addEventListener("change", (event) => {
const files = event.target.files;
if (files.length > 0) {
fileLabel.textContent =
files.length > 1 ? `${files.length} files selected` : files[0].name;
} else {
fileLabel.textContent = "no files chosen";
}
});
setupDragAndDrop();
// Update all file input change listeners to use updateFileInputLabel
document.querySelectorAll(".file-input").forEach((fileInput) => {
fileInput.addEventListener("change", () => {
updateFileInputLabel(fileInput);
});
});
function openTab(evt, tabName) {
tabContents.forEach((content) => {
content.classList.remove("active");
});
tabLinks.forEach((link) => {
link.classList.remove("active");
});
document.getElementById(tabName).classList.add("active");
evt.currentTarget.classList.add("active");
}
// Automatically open the first tab
if (tabLinks.length > 0) {
tabLinks[0].click();
}
// Setup custom file inputs
function setupCustomFileInputs() {
const fileInputs = document.querySelectorAll(".file-input");
fileInputs.forEach((fileInput) => {
const wrapper = fileInput.closest(".file-input-wrapper");
const button = wrapper.querySelector(".file-input-button");
const label = wrapper.querySelector(".file-input-label");
button.addEventListener("click", () => {
fileInput.click();
});
fileInput.addEventListener("change", () => {
if (fileInput.files.length > 0) {
if (fileInput.multiple) {
label.textContent = `${fileInput.files.length} file(s) selected`;
} else {
label.textContent = fileInput.files[0].name;
}
} else {
label.textContent = "No file chosen";
}
});
// Drag and Drop
wrapper.addEventListener("dragover", (e) => {
e.preventDefault();
e.stopPropagation();
wrapper.classList.add("dragover");
});
wrapper.addEventListener("dragleave", (e) => {
e.preventDefault();
e.stopPropagation();
wrapper.classList.remove("dragover");
});
wrapper.addEventListener("drop", (e) => {
e.preventDefault();
e.stopPropagation();
wrapper.classList.remove("dragover");
if (e.dataTransfer.files.length) {
fileInput.files = e.dataTransfer.files;
label.textContent = e.dataTransfer.files[0].name;
const changeEvent = new Event("change");
fileInput.dispatchEvent(changeEvent);
}
});
});
}
setupCustomFileInputs();
function debugStorage(action, key, value) {
console.log(`Storage ${action}:`, { key, value });
console.log("Current localStorage state:", localStorage);
}
let conversationHistory = [];
// GROQ API key elements
const groqApiKeyInput = document.getElementById("groq-api-key");
const saveGroqApiKeyBtn = document.getElementById("save-api-key");
const clearGroqApiKeyBtn = document.getElementById("clear-api-key");
const groqApiKeyStatus = document.getElementById("api-key-status");
const groqChatInterface = document.getElementById("chat-interface");
const groqChatForm = document.getElementById("chat-form");
const groqChatInput = document.getElementById("chat-input");
const groqChatMessages = document.getElementById("chat-messages");
// General API key and settings elements
const generalApiKeyInput = document.getElementById("general-api-key");
const generalEndpointInput = document.getElementById("general-endpoint");
const generalModelInput = document.getElementById("general-model");
const saveGeneralApiKeyBtn = document.getElementById("save-general-api-key");
const clearGeneralApiKeyBtn = document.getElementById(
"clear-general-api-key",
);
const generalApiKeyStatus = document.getElementById("general-api-key-status");
const generalChatInterface = document.getElementById(
"general-chat-interface",
);
const generalChatForm = document.getElementById("general-chat-form");
const generalChatInput = document.getElementById("general-chat-input");
const generalChatMessages = document.getElementById("general-chat-messages");
// Initialize API keys and settings immediately
function initializeApiKeys() {
const savedGroqApiKey = storageType.getItem("groq_api_key");
if (savedGroqApiKey) {
GROQ_API_KEY = savedGroqApiKey;
groqApiKeyInput.value = GROQ_API_KEY;
groqChatInterface.style.display = "block";
groqApiKeyStatus.textContent = "using saved API key";
groqApiKeyStatus.className = "status-success";
console.log("loaded saved GROQ API key");
loadConversationHistory("groq");
} else {
groqChatInterface.style.display = "none";
groqApiKeyStatus.textContent = "please enter a GROQ API key";
groqApiKeyStatus.className = "status-error";
}
const savedGeneralApiKey = storageType.getItem("general_api_key");
const savedGeneralEndpoint = storageType.getItem("general_endpoint");
const savedGeneralModel = storageType.getItem("general_model");
if (savedGeneralApiKey && savedGeneralEndpoint && savedGeneralModel) {
GENERAL_API_KEY = savedGeneralApiKey;
GENERAL_ENDPOINT = savedGeneralEndpoint;
GENERAL_MODEL = savedGeneralModel;
generalApiKeyInput.value = GENERAL_API_KEY;
generalEndpointInput.value = GENERAL_ENDPOINT;
generalModelInput.value = GENERAL_MODEL;
generalChatInterface.style.display = "block";
generalApiKeyStatus.textContent = "using saved settings";
generalApiKeyStatus.className = "status-success";
console.log("loaded saved general API settings");
loadConversationHistory("general");
} else {
generalChatInterface.style.display = "none";
generalApiKeyStatus.textContent = "please enter your API settings";
generalApiKeyStatus.className = "status-error";
}
}
// Save GROQ API key
function saveGroqApiKey() {
const apiKey = groqApiKeyInput.value.trim();
if (!apiKey) {
groqApiKeyStatus.textContent = "please enter a GROQ API key";
groqApiKeyStatus.className = "status-error";
groqChatInterface.style.display = "none";
return;
}
if (!apiKey.startsWith("gsk_")) {
groqApiKeyStatus.textContent =
"invalid API key format. should start with 'gsk_'";
groqApiKeyStatus.className = "status-error";
groqChatInterface.style.display = "none";
return;
}
try {
// Save the API key
storageType.setItem("groq_api_key", apiKey);
GROQ_API_KEY = apiKey;
// Update UI
groqApiKeyStatus.textContent = "API key saved successfully!";
groqApiKeyStatus.className = "status-success";
groqChatInterface.style.display = "block";
console.log("GROQ API key saved successfully");
} catch (error) {
console.error("error saving GROQ API key:", error);
groqApiKeyStatus.textContent =
"error saving GROQ API key. please try again.";
groqApiKeyStatus.className = "status-error";
}
}
// Clear GROQ API key
function clearGroqApiKey() {
try {
storageType.removeItem("groq_api_key");
GROQ_API_KEY = "";
groqApiKeyInput.value = "";
groqChatInterface.style.display = "none";
groqApiKeyStatus.textContent = "API key cleared";
groqApiKeyStatus.className = "status-success";
console.log("GROQ API key cleared");
} catch (error) {
console.error("Error clearing GROQ API key:", error);
groqApiKeyStatus.textContent =
"error clearing GROQ API key. please try again.";
groqApiKeyStatus.className = "status-error";
}
}
// Save general API settings
function saveGeneralApiSettings() {
const apiKey = generalApiKeyInput.value.trim();
const endpoint = generalEndpointInput.value.trim();
const model = generalModelInput.value.trim();
if (!apiKey || !endpoint || !model) {
generalApiKeyStatus.textContent = "please enter all required fields";
generalApiKeyStatus.className = "status-error";
generalChatInterface.style.display = "none";
return;
}
try {
// Save the API key, endpoint, and model
storageType.setItem("general_api_key", apiKey);
storageType.setItem("general_endpoint", endpoint);
storageType.setItem("general_model", model);
GENERAL_API_KEY = apiKey;
GENERAL_ENDPOINT = endpoint;
GENERAL_MODEL = model;
// Update UI
generalApiKeyStatus.textContent = "API settings saved successfully!";
generalApiKeyStatus.className = "status-success";
generalChatInterface.style.display = "block";
console.log("General API settings saved successfully");
} catch (error) {
console.error("error saving general API settings:", error);
generalApiKeyStatus.textContent =
"error saving API settings. please try again.";
generalApiKeyStatus.className = "status-error";
}
}
// Clear general API settings
function clearGeneralApiSettings() {
try {
storageType.removeItem("general_api_key");
storageType.removeItem("general_endpoint");
storageType.removeItem("general_model");
GENERAL_API_KEY = "";
GENERAL_ENDPOINT = "";
GENERAL_MODEL = "";
generalApiKeyInput.value = "";
generalEndpointInput.value = "";
generalModelInput.value = "";
generalChatInterface.style.display = "none";
generalApiKeyStatus.textContent = "API settings cleared";
generalApiKeyStatus.className = "status-success";
console.log("General API settings cleared");
} catch (error) {
console.error("Error clearing general API settings:", error);
generalApiKeyStatus.textContent =
"error clearing API settings. please try again.";
generalApiKeyStatus.className = "status-error";
}
}
// Initialize the API keys and settings on page load
initializeApiKeys();
initializeCarouselCreator();
// Add event listeners
saveGroqApiKeyBtn.addEventListener("click", saveGroqApiKey);
clearGroqApiKeyBtn.addEventListener("click", clearGroqApiKey);
saveGeneralApiKeyBtn.addEventListener("click", saveGeneralApiSettings);
clearGeneralApiKeyBtn.addEventListener("click", clearGeneralApiSettings);
// Message sending functions
async function sendMessageToGroq(message) {
if (!GROQ_API_KEY) {
throw new Error("please enter your GROQ API key first");
}
return sendMessage(message, "groq");
}
async function sendMessageToGeneral(message) {
if (!GENERAL_API_KEY || !GENERAL_ENDPOINT || !GENERAL_MODEL) {
throw new Error("please enter all general API settings first");
}
return sendMessage(message, "general");
}
async function sendMessage(message, type) {
const apiKey = type === "groq" ? GROQ_API_KEY : GENERAL_API_KEY;
const endpoint =
type === "groq"
? "https://api.groq.com/openai/v1/chat/completions"
: GENERAL_ENDPOINT;
const model =
type === "groq" ? "llama-3.2-90b-text-preview" : GENERAL_MODEL;
const historyKey =
type === "groq" ? "groq_chat_history" : "general_chat_history";
try {
// Add user's message to conversation history
conversationHistory.push({
role: "user",
content: message,
});
const response = await fetch(endpoint, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
messages: conversationHistory,
temperature: 0.7,
max_tokens: 2048,
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(
errorData.error?.message || "failed to get response from API",
);
}
const data = await response.json();
const assistantMessage = data.choices[0].message.content;
// Add assistant's response to conversation history
conversationHistory.push({
role: "assistant",
content: assistantMessage,
});
saveConversationHistory(historyKey);
return assistantMessage;
} catch (error) {
console.error("error:", error);
if (error.message.includes("authentication")) {
if (type === "groq") {
GROQ_API_KEY = "";
storageType.removeItem("groq_api_key");
showApiKeyError(
"invalid GROQ API key. please enter a valid key.",
groqApiKeyStatus,
);
} else {
GENERAL_API_KEY = "";
storageType.removeItem("general_api_key");
GENERAL_ENDPOINT = "";
storageType.removeItem("general_endpoint");
GENERAL_MODEL = "";
storageType.removeItem("general_model");
showApiKeyError(
"invalid general API settings. please enter valid settings.",
generalApiKeyStatus,
);
}
}
return `error: ${error.message}`;
}
}
function saveConversationHistory(key) {
try {
storageType.setItem(key, JSON.stringify(conversationHistory));
} catch (error) {
console.error("error saving chat history:", error);
}
}
function loadConversationHistory(type) {
try {
const historyKey =
type === "groq" ? "groq_chat_history" : "general_chat_history";
const savedHistory = storageType.getItem(historyKey);
if (savedHistory) {
conversationHistory = JSON.parse(savedHistory);
conversationHistory.forEach((msg) => {
addMessage(msg.content, msg.role === "user", type);
});
}
} catch (error) {
console.error("error loading chat history:", error);
conversationHistory = [];
}
}
function addMessage(message, isUser = false, type = "groq") {
const target = type === "groq" ? groqChatMessages : generalChatMessages;
const messageDiv = document.createElement("div");
messageDiv.classList.add("message");
messageDiv.classList.add(isUser ? "user-message" : "bot-message");
messageDiv.textContent = message;
target.appendChild(messageDiv);
target.scrollTop = target.scrollHeight;
}
if (groqChatForm) {
groqChatForm.addEventListener("submit", async (e) => {
e.preventDefault();
const message = groqChatInput.value.trim();
if (!message) return;
if (!GROQ_API_KEY) {
showApiKeyError(
"please enter your GROQ API key first",
groqApiKeyStatus,
);
return;
}
// Add user message to chat
addMessage(message, true, "groq");
groqChatInput.value = "";
// Show typing indicator
const loadingDiv = createTypingIndicator();
groqChatMessages.appendChild(loadingDiv);
groqChatMessages.scrollTop = groqChatMessages.scrollHeight;
try {
// Get response from GROQ
const response = await sendMessageToGroq(message);
// Remove typing indicator and add bot response
groqChatMessages.removeChild(loadingDiv);
addMessage(response, false, "groq");
// Save conversation history after each message
saveConversationHistory("groq_chat_history");
} catch (error) {
// Remove typing indicator and show error
groqChatMessages.removeChild(loadingDiv);
addMessage(`error: ${error.message}`, false, "groq");
}
});
}
if (generalChatForm) {
generalChatForm.addEventListener("submit", async (e) => {
e.preventDefault();
const message = generalChatInput.value.trim();
if (!message) return;
if (!GENERAL_API_KEY || !GENERAL_ENDPOINT || !GENERAL_MODEL) {
showApiKeyError(
"please enter all general API settings first",
generalApiKeyStatus,
);
return;
}
// Add user message to chat
addMessage(message, true, "general");
generalChatInput.value = "";
// Show typing indicator
const loadingDiv = createTypingIndicator();
generalChatMessages.appendChild(loadingDiv);
generalChatMessages.scrollTop = generalChatMessages.scrollHeight;
try {
// Get response from general API
const response = await sendMessageToGeneral(message);
// Remove typing indicator and add bot response
generalChatMessages.removeChild(loadingDiv);
addMessage(response, false, "general");
// Save conversation history after each message
saveConversationHistory("general_chat_history");
} catch (error) {
// Remove typing indicator and show error
generalChatMessages.removeChild(loadingDiv);
addMessage(`error: ${error.message}`, false, "general");
}
});
}
// Helper function to create typing indicator
function createTypingIndicator() {
const loadingDiv = document.createElement("div");
loadingDiv.classList.add("typing-container");
loadingDiv.innerHTML = `
<div class="typing-indicator">
<span></span>
<span></span>
<span></span>
</div>
`;
return loadingDiv;
}
// Helper function to display errors related to API keys
function showApiKeyError(message, statusElement) {
statusElement.textContent = message;
statusElement.className = "status-error";
if (statusElement === groqApiKeyStatus) {
groqChatInterface.style.display = "none";
} else {
generalChatInterface.style.display = "none";
}
}
// PDF Merge functionality
const mergePdfForm = document.getElementById("merge-pdf-form");
const mergePdfBtn = document.getElementById("merge-pdf-btn");
const mergePdfResult = document.getElementById("merge-pdf-result");
mergePdfBtn.addEventListener("click", async (e) => {
e.preventDefault();
const pdfFiles = document.getElementById("pdf-files").files;
if (pdfFiles.length < 2) {
alert("please select at least two PDF files to merge.");
return;
}
const mergedPdf = await PDFLib.PDFDocument.create();
for (const pdfFile of pdfFiles) {
const pdfBytes = await readFileAsArrayBuffer(pdfFile);
const pdf = await PDFLib.PDFDocument.load(pdfBytes);
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
copiedPages.forEach((page) => mergedPdf.addPage(page));
}
const pdfBytes = await mergedPdf.save();
const blob = new Blob([pdfBytes], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
mergePdfResult.innerHTML = `
<p>PDFs merged successfully!</p>
<a href="${url}" download="merged.pdf" class="button">download merged PDF</a>
`;
});
// PDF Split functionality
const splitPdfForm = document.getElementById("split-pdf-form");
const splitPdfBtn = document.getElementById("split-pdf-btn");
const splitPdfResult = document.getElementById("split-pdf-result");
const splitMethod = document.getElementById("split-method");
const pageRangeInput = document.getElementById("page-range-input");
const mergeSplitPdfsDiv = document.getElementById("merge-split-pdfs");
const mergeSplitPdfsBtn = document.getElementById("merge-split-pdfs-btn");
let splitPdfUrls = []; // Array to store split PDF URLs
splitMethod.addEventListener("change", () => {
pageRangeInput.style.display =
splitMethod.value === "range" ? "block" : "none";
});
splitPdfBtn.addEventListener("click", async (e) => {
e.preventDefault();
const pdfFileInput = document.getElementById("pdf-to-split");
const pdfFile = pdfFileInput.files[0];
if (!pdfFile) {
alert("please select a PDF file to split.");
return;
}
const pdfBytes = await readFileAsArrayBuffer(pdfFile);
const pdf = await PDFLib.PDFDocument.load(pdfBytes);
const pageCount = pdf.getPageCount();
let pagesToExtract = [];
if (splitMethod.value === "all") {
pagesToExtract = Array.from({ length: pageCount }, (_, i) => [i]);
} else {
const pageRange = document.getElementById("page-range").value;
pagesToExtract = parsePageRange(pageRange, pageCount);
}
splitPdfResult.innerHTML = "<p>PDF split successfully!</p>";
splitPdfUrls = []; // Clear previous split URLs
for (const range of pagesToExtract) {