72 lines
2.5 KiB
JavaScript
72 lines
2.5 KiB
JavaScript
async function sendMessage(e) {
|
|
e.preventDefault();
|
|
const input = document.getElementById('user-input');
|
|
const chatWindow = document.getElementById('chat-window');
|
|
const sendBtn = document.getElementById('send-btn');
|
|
const text = input.value.trim();
|
|
|
|
if (!text) return;
|
|
|
|
if (inputHistory[inputHistory.length - 1] !== text) {
|
|
inputHistory.push(text);
|
|
if (inputHistory.length > 50) inputHistory.shift();
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(inputHistory));
|
|
}
|
|
historyIndex = -1;
|
|
|
|
chatWindow.innerHTML += `
|
|
<div class="flex justify-end">
|
|
<div class="bg-indigo-600 text-white rounded-2xl px-4 py-2.5 max-w-2xl text-xs sm:text-sm shadow-sm">
|
|
${text}
|
|
</div>
|
|
</div>
|
|
`;
|
|
input.value = '';
|
|
input.style.height = 'auto';
|
|
chatWindow.scrollTop = chatWindow.scrollHeight;
|
|
|
|
sendBtn.disabled = true;
|
|
sendBtn.classList.add('opacity-50');
|
|
|
|
const endpoint = IS_GUEST ? '/api/v1/chat/guest' : '/api/v1/chat';
|
|
const headers = { 'Content-Type': 'application/json' };
|
|
if (!IS_GUEST) {
|
|
headers['Authorization'] = `Bearer ${API_TOKEN}`;
|
|
}
|
|
|
|
try {
|
|
const res = await fetch(endpoint, {
|
|
method: 'POST',
|
|
headers: headers,
|
|
body: JSON.stringify({ session_id: SESSION_ID, message: text })
|
|
});
|
|
|
|
if (res.status === 401 && !IS_GUEST) {
|
|
logout();
|
|
return;
|
|
}
|
|
|
|
const data = await res.json();
|
|
const assistantTitle = IS_GUEST ? "Локальная нейросеть (Гость)" : "ИИ-Ассистент SCUD Orion AI";
|
|
|
|
chatWindow.innerHTML += `
|
|
<div class="bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm max-w-2xl">
|
|
<p class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1"><i class="fa-solid fa-robot mr-1"></i> ${assistantTitle}</p>
|
|
<p class="text-slate-800 text-xs sm:text-sm whitespace-pre-wrap leading-relaxed">${data.reply}</p>
|
|
</div>
|
|
`;
|
|
chatWindow.scrollTop = chatWindow.scrollHeight;
|
|
if (!IS_GUEST) loadTasks();
|
|
|
|
} catch (err) {
|
|
chatWindow.innerHTML += `
|
|
<div class="bg-red-50 border border-red-200 rounded-2xl p-3.5 max-w-2xl text-red-700 text-xs sm:text-sm">
|
|
Ошибка связи с сервером.
|
|
</div>
|
|
`;
|
|
} finally {
|
|
sendBtn.disabled = false;
|
|
sendBtn.classList.remove('opacity-50');
|
|
}
|
|
}
|