-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
145 lines (121 loc) · 4.35 KB
/
script.js
File metadata and controls
145 lines (121 loc) · 4.35 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
// DOM Elements
const chatMessages = document.getElementById("chat-messages");
const userInput = document.getElementById("user-input");
const sendButton = document.getElementById("send-button");
const modal = document.getElementById("limit-modal");
const resetButton = document.getElementById("reset-button");
// === Configuration Section ===
// TODO: Replace with your own Cloudflare Worker URL
const workerUrl = "https://ai.mochammadnopalattasya.workers.dev/";
// Max message exchanges before conversation resets (user + AI = 1 exchange)
const MAX_MESSAGES = 50;
// Conversation history will be stored here (for memory context)
const conversationHistory = [];
function scrollToBottom() {
chatMessages.scrollTop = chatMessages.scrollHeight;
}
function addMessage(message, sender) {
const msgEl = document.createElement("div");
msgEl.classList.add("message", `${sender}-message`);
const bubble = document.createElement("div");
bubble.classList.add("message-bubble");
if (sender === "ai") {
const rawHtml = marked.parse(message);
const sanitized = DOMPurify.sanitize(rawHtml);
bubble.innerHTML = sanitized;
enhanceCodeBlocks(bubble);
} else {
bubble.textContent = message;
}
msgEl.appendChild(bubble);
chatMessages.appendChild(msgEl);
scrollToBottom();
}
function addTypingIndicator() {
const typingEl = document.createElement("div");
typingEl.classList.add("message", "ai-message");
typingEl.id = "typing-indicator";
const bubble = document.createElement("div");
bubble.classList.add("message-bubble");
const dots = document.createElement("div");
dots.classList.add("typing-dots");
dots.innerHTML = "<span></span><span></span><span></span>";
bubble.appendChild(dots);
typingEl.appendChild(bubble);
chatMessages.appendChild(typingEl);
scrollToBottom();
}
function removeTypingIndicator() {
const typing = document.getElementById("typing-indicator");
if (typing) typing.remove();
}
function enhanceCodeBlocks(container) {
const blocks = container.querySelectorAll("pre code");
blocks.forEach(block => {
hljs.highlightElement(block);
const pre = block.closest("pre");
const copyBtn = document.createElement("button");
copyBtn.className = "copy-button";
copyBtn.textContent = "Copy";
copyBtn.onclick = () => {
navigator.clipboard.writeText(block.innerText);
copyBtn.textContent = "Copied!";
setTimeout(() => (copyBtn.textContent = "Copy"), 1500);
};
pre.appendChild(copyBtn);
});
}
function showLimitModal() {
modal.style.display = "flex";
}
function resetConversation() {
conversationHistory.length = 0;
chatMessages.innerHTML = "";
addMessage("Hello! I'm your AI assistant. Type something to start chatting...", "ai");
modal.style.display = "none";
}
async function sendMessageToAI(userMessage) {
conversationHistory.push({ role: "user", content: userMessage });
if (conversationHistory.length > MAX_MESSAGES * 2) {
showLimitModal();
return;
}
// === AI personality and context prompt ===
// You can customize the system prompt below to change how the AI behaves
const prompt = [
"You are AIAssistant, a smart and friendly AI developed using Google's Gemini API, customized by the developer.",
...conversationHistory.map(m => m.role === "user" ? `User: ${m.content}` : `AI: ${m.content}`),
"AI:"
].join("\n");
addTypingIndicator();
try {
const res = await fetch(workerUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt })
});
const data = await res.json();
const aiReply = data.reply || "Sorry, an error occurred.";
conversationHistory.push({ role: "assistant", content: aiReply });
removeTypingIndicator();
addMessage(aiReply, "ai");
} catch (e) {
console.error(e);
removeTypingIndicator();
addMessage("An error occurred while contacting the AI.", "ai");
}
}
function handleUserMessage() {
const text = userInput.value.trim();
if (!text) return;
addMessage(text, "user");
sendMessageToAI(text);
userInput.value = "";
}
sendButton.addEventListener("click", handleUserMessage);
userInput.addEventListener("keypress", e => {
if (e.key === "Enter") handleUserMessage();
});
resetButton.addEventListener("click", resetConversation);
// Start greeting
addMessage("Hello! I'm your AI assistant. Type something to start chatting...", "ai");