projectId = "";
(function () {
const currentScript = document.currentScript;
if (!currentScript) {
console.error("No current script tag found.");
return;
}
const scriptUrl = currentScript.src;
const urlParams = new URLSearchParams(scriptUrl.split('?')[1]);
const projectId = urlParams.get("project_id");
if (!projectId) {
console.error("No ID found in script URL.");
return;
}
window.__CHATBOX_PROJECT_ID__ = projectId;
console.log("Loaded ID:", projectId);
// You can now use the ID in your logic
})();
window.addEventListener("load", async () => {
const projectId = window.__CHATBOX_PROJECT_ID__;
if (!projectId) {
console.error("No ID found in script URL.");
return;
}
const baseUrl = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
? 'http://127.0.0.1:8000/' // Local development
: 'https://chat.ia-ai.se/'; // Production server
const chatUrl= baseUrl + "chat"
try {
// Fetch the chatbox HTML content from the server
const response = await fetch(baseUrl + "chatbox?project_id=" + projectId, {
headers: {
'Accept': 'application/json, text/html'
}
});
if (!response.ok) {
console.error("Failed to load chatbox HTML:", await response.text());
return;
}
// Get the HTML content
const chatboxHtml = await response.text();
// Create a container for the chatbox HTML
const container = document.createElement("div");
container.innerHTML = chatboxHtml;
// Append the chatbox container to the body or any other desired container
document.body.appendChild(container);
// Wait until the chatbox is added to the DOM
setTimeout(() => {
// Select the input element inside the loaded chatbox
const chatbox = document.getElementById("chatbox");
const header = document.getElementById("chat-header");
const input = document.getElementById("chat-input");
const messages = document.getElementById("chat-messages");
if (input) {
// Log to verify if the input was found
console.log("Input element found:", input);
input.addEventListener("keydown", async (e) => {
if (e.key === "Enter" && input.value.trim() !== "") {
const msg = input.value;
messages.innerHTML += `
You: ` + `${msg}
`;
messages.scrollTop = messages.scrollHeight;
const session_id = getSessionId();
// disable input
chatInput = document.getElementById("chat-input");
old_value = chatInput.placeholder;
chatInput.disabled = true;
chatInput.value = "";
let animationInterval;
let baseText = "Writing";
let dots = "";
function animateDots() {
if (dots.length >= 8) {
dots = "";
} else {
dots += ".";
}
chatInput.placeholder = baseText + dots;
}
// Clear any existing interval just in case
clearInterval(animationInterval);
// First show immediately
animateDots();
// Random delay between 200ms and 500ms per update
function startInterval() {
const delay = 100 + Math.random() * 300;
animationInterval = setTimeout(() => {
animateDots();
startInterval();
}, delay);
}
startInterval();
try {
const res = await fetch(chatUrl, {
method: "POST",
headers: {
"Content-Type": "application/json", // Make sure this header is set
"Accept": "application/json", // This tells the server we expect JSON in response
},
body: JSON.stringify({
message: msg,
cookie: document.cookie,
session_id: session_id,
project_id: projectId,
}),
});
const data = await res.json();
console.log("Received data:", data);
clearTimeout(animationInterval);
animationInterval = null;
chatInput.disabled = false;
chatInput.placeholder = old_value;
if (!res.ok) {
console.error(`Error ${res.status}: ${data}`);
let botMsg = `Assistant: There is something wrong...
`;
messages.innerHTML += botMsg;
messages.scrollTop = messages.scrollHeight;
return;
}
// Prepare bot's response and URLs
let botMsg = `Assistant: ${data.response}
`;
// If URLs are provided, display them as clickable links
/*
if (data.urls && data.urls.length > 0) {
botMsg += ``;
data.urls.forEach(url => {
botMsg += `- ${url}
`;
});
botMsg += `
`;
}
*/
messages.innerHTML += botMsg;
messages.scrollTop = messages.scrollHeight;
} catch (error) {
if (!navigator.onLine) {
console.error("No internet connection.");
let botMsg = `Assistant: Ingen internetanslutning.
`;
messages.innerHTML += botMsg;
messages.scrollTop = messages.scrollHeight;
} else {
console.error("Fetch failed:", error);
let botMsg = `Assistant: Fick inget svar från servern.
`;
messages.innerHTML += botMsg;
messages.scrollTop = messages.scrollHeight;
// alert("Something went wrong.");
}
}
}
});
let offsetX = 0,
offsetY = 0,
isDragging = false;
header.addEventListener("mousedown", (e) => {
isDragging = true;
offsetX = e.clientX - chatbox.offsetLeft;
offsetY = e.clientY - chatbox.offsetTop;
});
document.addEventListener("mouseup", () => (isDragging = false));
document.addEventListener("mousemove", (e) => {
if (isDragging) {
chatbox.style.left = e.clientX - offsetX + "px";
chatbox.style.top = e.clientY - offsetY + "px";
chatbox.style.bottom = "auto";
chatbox.style.right = "auto";
}
});
} else {
console.error("Input element not found in chatbox.");
}
}, 100); // Small delay to ensure the HTML has been fully inserted
} catch (error) {
console.error("Error loading chatbox:", error);
}
});
function getSessionId() {
// Check if a session ID exists in localStorage
let sessionId = localStorage.getItem("sessionId");
if (!sessionId) {
// If no session ID exists, generate a new one (or use a UUID library to generate a unique ID)
sessionId = generateUniqueId(); // Use your preferred method to generate a unique ID
localStorage.setItem("sessionId", sessionId); // Store the session ID in localStorage
}
return sessionId;
}
// Function to generate a unique ID (you can use a library like uuid for a more robust ID)
function generateUniqueId() {
return "user-" + Math.random().toString(36).substr(2, 9);
}
console.log("chatbox");
window.addEventListener("load", async () => {});