-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
186 lines (154 loc) · 7.22 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
// querySelector css seçicisine uyan ilk öğeyi seçer(class,id,element). eşleşen öğe yoksa null döner.
const messageInput = document.querySelector(".message-input");
const chatBody = document.querySelector(".chat-body");
const sendMessageButton = document.querySelector("#send-message");
const fileInput = document.querySelector("#file-input");
const fileUploadWrapper = document.querySelector(".file-upload-wrapper");
const fileCancelButton = document.querySelector("#file-cancel");
const chatBotToggler = document.querySelector("#chatbot-toggler");
const closeChatbot = document.querySelector("#close-chatbot")
const API_KEY = "AIzaSyCNXQOOBRGPFf3RSYBn1_DZUBjv9_KE1lo";
const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${API_KEY}` ;
const userData = {
message: null,
file: {
data:null,
mime_type:null
}
}
const chatHistory =[];
const initialInputHeight = messageInput.scrollHeight;
// mesaj elemanı oluşturmak için
const createMessageElement = (content, ...classes) => {
const div = document.createElement("div");// yeni bir div oluşturuyor
div.classList.add("message", ...classes);//dive 2 tane sınıf ekliyor(user-message)
div.innerHTML = content;// divin içine html içeriği olarak mesaj yerleştiriliyor
return div;
}
const generateBotResponse = async(incomingMessageDiv) =>{
const messageElement = incomingMessageDiv.querySelector(".message-text");
chatHistory.push({
role:"user",
parts: [
{ text: userData.message },
...(userData.file?.data ? [{ inline_data: userData.file }] : [])
]
});
const requestOptions = {
method:"POST",
headers:{"Content-Type": "application/json"},
body: JSON.stringify({
contents: chatHistory
})
}
try {
const response = await fetch(API_URL, requestOptions);
const data = await response.json();
if(!response.ok) throw new Error(data.error.message);
const apiResponseText = data.candidates[0].content.parts[0].text.replace(/\*\*\((.*?)\)\*\*\*/g, "$1").trim();
messageElement.innerText = apiResponseText;
chatHistory.push({
role:"model",
parts: [{text:apiResponseText}]});
} catch (error) {
console.log(error);
messageElement.innerText = error.message;
messageElement.style.color = "#ff0000";
}finally{
userData.file = {};
incomingMessageDiv.classList.remove("thinking");
chatBody.scrollTo({
top: chatBody.scrollHeight,
behavior: "smooth"
});
}
}
const handleOutgoinMessage = (e) => {
e.preventDefault();
userData.message = messageInput.value.trim();
messageInput.value = "";
fileUploadWrapper.classList.remove("file-uploaded");
messageInput.dispatchEvent(new Event ("input"));
const messageContent = `<div class="message-text">${userData.message}</div> ${userData.file.data ? `<img class="attachment" src="data:${userData.file.mime_type};base64,${userData.file.data}"/>` : ''}`;
const outgoinMessageDiv = createMessageElement(messageContent, "user-message");
outgoinMessageDiv.querySelector(".message-text").textContent = userData.message;
chatBody.appendChild(outgoinMessageDiv);//appendChild üst öğenin altına yeni bir öğe eklemek için kullanılır.
chatBody.scrollTo({
top: chatBody.scrollHeight,
behavior: "smooth"
});
setTimeout(() =>{
const messageContent = `<svg class="bot-avatar" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 1024 1024">
<path d="M738.3 287.6H285.7c-59 0-106.8 47.8-106.8 106.8v303.1c0 59 47.8 106.8 106.8 106.8h81.5v111.1c0 .7.8 1.1 1.4.7l166.9-110.6 41.8-.8h117.4l43.6-.4c59 0 106.8-47.8 106.8-106.8V394.5c0-59-47.8-106.9-106.8-106.9zM351.7 448.2c0-29.5 23.9-53.5 53.5-53.5s53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5-53.5-23.9-53.5-53.5zm157.9 267.1c-67.8 0-123.8-47.5-132.3-109h264.6c-8.6 61.5-64.5 109-132.3 109zm110-213.7c-29.5 0-53.5-23.9-53.5-53.5s23.9-53.5 53.5-53.5 53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5zM867.2 644.5V453.1h26.5c19.4 0 35.1 15.7 35.1 35.1v121.1c0 19.4-15.7 35.1-35.1 35.1h-26.5zM95.2 609.4V488.2c0-19.4 15.7-35.1 35.1-35.1h26.5v191.3h-26.5c-19.4 0-35.1-15.7-35.1-35.1zM561.5 149.6c0 23.4-15.6 43.3-36.9 49.7v44.9h-30v-44.9c-21.4-6.5-36.9-26.3-36.9-49.7 0-28.6 23.3-51.9 51.9-51.9s51.9 23.3 51.9 51.9z"></path>
</svg>
</div>
<div class="message-text">
<div class="thinking-indicator">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div></div>`;
const incomingMessageDiv = createMessageElement(messageContent, "bot-message","thinking");
chatBody.appendChild(incomingMessageDiv);
chatBody.scrollTo({
top: chatBody.scrollHeight,
behavior: "smooth"
});
generateBotResponse(incomingMessageDiv);
},600);
}
messageInput.addEventListener("keydown", (e) => {
const userMessage = e.target.value.trim();
if (e.key === "Enter" && userMessage && !e.shiftKey && window.innerWidth > 768) {
handleOutgoinMessage(e);
e.target.value = "";
}
});
messageInput.addEventListener("input", () =>{
messageInput.style.height = `${initialInputHeight}px`;
messageInput.style.height = `${messageInput.scrollHeight}px`;
document.querySelector(".chat-form").style.borderRadius= messageInput.scrollHeight>
initialInputHeight ? "15px":"32px";
})
fileInput.addEventListener("change", () => {
const file = fileInput.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
fileUploadWrapper.querySelector("img").src= e.target.result;
fileUploadWrapper.classList.add("file-uploaded");
const base64String = e.target.result.split(",")[1];
userData.file = {
data: base64String,
mime_type: file.type
};
fileInput.value = "";
};
reader.readAsDataURL(file);
});
fileCancelButton.addEventListener("click", () => {
userData.file = {};
fileUploadWrapper.classList.remove("file-uploaded");
})
const picker = new EmojiMart.Picker({
theme:"light",
skinTonePosition:"none",
previewPosition: "none",
onEmojiSelect:(emoji) =>{
const{selectionStart: start, selectionEnd: end} = messageInput;
messageInput.setRangeText(emoji.native,start,end, "end");
messageInput.focus();
},
onClickOutside:(e) =>{
if(e.target.id === "emoji-picker"){
document.body.classList.toggle("show-emoji-picker");
}else{
document.body.classList.remove("show-emoji-picker");
}
}
});
document.querySelector(".chat-form").appendChild(picker);
sendMessageButton.addEventListener("click", (e) => handleOutgoinMessage(e));
document.querySelector("#file-upload").addEventListener("click",() => fileInput.click());
chatBotToggler.addEventListener("click", () =>document.body.classList.toggle("show-chatbot"));
closeChatbot.addEventListener("click",() => document.body.classList.remove("show-chatbot"));