feat(web): стабилизация UI, Gemini-скроллинг, роутеры контекста/снапшотов и актуализация роадмапа
This commit is contained in:
@@ -1,67 +1,586 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: static/js/chat/core.js
|
||||
* ROLE: Отправка сообщений в API с токеном и обработка ошибок.
|
||||
* FILE: modules/web_api/static/js/chat/core.js
|
||||
* ROLE: Ядро чата: полноэкранный Drag-and-Drop оверлей, авто-высота инпута (24px),
|
||||
* надежный расчет скролла вопроса к верху окна, крупный шрифт text-sm.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
async function sendMessage(userMessageText) {
|
||||
const chatInput = document.getElementById("chat-input");
|
||||
const message = userMessageText || (chatInput ? chatInput.value.trim() : "");
|
||||
if (!message) return;
|
||||
let currentAttachedFile = null;
|
||||
|
||||
if (chatInput && !userMessageText) {
|
||||
chatInput.value = "";
|
||||
const CHAT_INPUT_STORAGE_KEY = "scud_chat_input_history";
|
||||
let chatInputHistory = JSON.parse(localStorage.getItem(CHAT_INPUT_STORAGE_KEY) || "[]");
|
||||
let chatHistoryIndex = -1;
|
||||
let temporaryCurrentInput = "";
|
||||
|
||||
function saveCommandToHistory(commandText) {
|
||||
if (!commandText || !commandText.trim()) return;
|
||||
const cleanCmd = commandText.trim();
|
||||
if (cleanCmd.startsWith("action:save_draft_")) return;
|
||||
|
||||
chatInputHistory = chatInputHistory.filter(item => item !== cleanCmd);
|
||||
chatInputHistory.push(cleanCmd);
|
||||
if (chatInputHistory.length > 50) chatInputHistory.shift();
|
||||
localStorage.setItem(CHAT_INPUT_STORAGE_KEY, JSON.stringify(chatInputHistory));
|
||||
chatHistoryIndex = -1;
|
||||
}
|
||||
|
||||
// ⭐️ ЕДИНАЯ ФУНКЦИЯ СКРОЛЛА: плавное выравнивание вопроса к верхней границе
|
||||
function scrollToUserMessageTop() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const userBubbles = container.querySelectorAll(".user-chat-bubble");
|
||||
const targetEl = userBubbles[userBubbles.length - 1] || container.lastElementChild;
|
||||
if (!targetEl) return;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
setTimeout(() => {
|
||||
const containerTop = container.getBoundingClientRect().top;
|
||||
const targetTop = targetEl.getBoundingClientRect().top;
|
||||
|
||||
const targetScroll = container.scrollTop + (targetTop - containerTop) - 16;
|
||||
|
||||
container.scrollTo({
|
||||
top: Math.max(0, targetScroll),
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}, 50);
|
||||
});
|
||||
}
|
||||
|
||||
function updateInputHeightAndFade(textarea) {
|
||||
if (!textarea) return;
|
||||
|
||||
if (!textarea.value || textarea.value.trim() === '') {
|
||||
textarea.style.height = '24px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// Отображаем сообщение пользователя в чате
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("user", message);
|
||||
textarea.style.height = 'auto';
|
||||
const minHeight = 24;
|
||||
const maxHeight = 120;
|
||||
const currentScrollHeight = textarea.scrollHeight;
|
||||
|
||||
if (currentScrollHeight <= minHeight + 2) {
|
||||
textarea.style.height = minHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
} else if (currentScrollHeight > maxHeight) {
|
||||
textarea.style.height = maxHeight + 'px';
|
||||
textarea.style.overflowY = 'auto';
|
||||
textarea.style.maskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
textarea.style.webkitMaskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
} else {
|
||||
textarea.style.height = currentScrollHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function appendUserMessage(text, filename = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const msgId = 'user-msg-' + Date.now();
|
||||
let fileBadge = '';
|
||||
if (filename) {
|
||||
fileBadge = `
|
||||
<div class="inline-flex items-center gap-1.5 px-2.5 py-1 mb-2 bg-indigo-700/80 rounded-lg text-xs font-semibold text-white shadow-xs">
|
||||
<i class="fa-solid fa-paperclip text-xs"></i>
|
||||
<span class="truncate max-w-xs">${escapeHtml(filename)}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Подготовка заголовков с гарантированным токеном
|
||||
const token = (typeof AuthManager !== "undefined") ? AuthManager.getToken() : (localStorage.getItem("auth_token") || "dev_token_1");
|
||||
const userId = (typeof AuthManager !== "undefined") ? AuthManager.getUserId() : parseInt(localStorage.getItem("user_id") || "1", 10);
|
||||
const sessionId = localStorage.getItem("chat_session_id") || "web_session_main";
|
||||
const msgHtml = `
|
||||
<div id="${msgId}" class="user-chat-bubble flex gap-3 max-w-4xl mx-auto w-full justify-end pt-3 scroll-mt-4">
|
||||
<div class="flex-1 max-w-2xl bg-indigo-600 text-white rounded-2xl rounded-tr-none p-4 shadow-sm">
|
||||
${fileBadge}
|
||||
<div class="text-sm leading-relaxed whitespace-pre-wrap">${escapeHtml(text)}</div>
|
||||
</div>
|
||||
<div class="w-8 h-8 rounded-lg bg-slate-200 text-slate-600 flex items-center justify-center shrink-0 shadow-sm mt-0.5 font-bold text-sm">
|
||||
<i class="fa-solid fa-user"></i>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", msgHtml);
|
||||
}
|
||||
|
||||
function appendAssistantLoading() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return null;
|
||||
|
||||
const loadingId = 'loading-' + Date.now();
|
||||
const html = `
|
||||
<div id="${loadingId}" class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
||||
<div class="text-sm text-slate-500 flex items-center gap-2">
|
||||
<i class="fa-solid fa-spinner fa-spin text-indigo-600"></i>
|
||||
<span>ИИ обрабатывает запрос...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
return loadingId;
|
||||
}
|
||||
|
||||
function appendAssistantMessage(text, buttons = [], actionPayload = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
let payloadHtml = '';
|
||||
let isHtmlBody = false;
|
||||
|
||||
if (actionPayload) {
|
||||
if (actionPayload.type === 'SNAPSHOTS_CARD' && typeof renderSnapshotsCard === 'function') {
|
||||
payloadHtml = renderSnapshotsCard(actionPayload.data);
|
||||
} else if (actionPayload.type === 'TASK_INTERACTIVE_CARD' && typeof renderInteractiveTaskCard === 'function') {
|
||||
payloadHtml = renderInteractiveTaskCard(actionPayload.tasks);
|
||||
} else if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
|
||||
const dlUrl = actionPayload.download_url || '#';
|
||||
const fName = actionPayload.filename || 'ROADMAP.md';
|
||||
const count = actionPayload.tasks_count || '';
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-indigo-50/80 border border-indigo-200 rounded-xl flex items-center justify-between gap-3 shadow-sm">
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
<div class="w-9 h-9 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm">
|
||||
<i class="fa-solid fa-file-lines text-base"></i>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-bold text-slate-800 truncate">${escapeHtml(fName)}</div>
|
||||
<div class="text-xs text-slate-500">Задач выгружено: ${count} шт. · Markdown</div>
|
||||
</div>
|
||||
</div>
|
||||
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
|
||||
class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white rounded-lg text-xs font-bold shadow-sm transition flex items-center gap-1.5 shrink-0">
|
||||
<i class="fa-solid fa-download text-xs"></i>
|
||||
<span>Скачать файл</span>
|
||||
</a>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'SNAPSHOT_INSPECT_CARD') {
|
||||
const records = actionPayload.records || [];
|
||||
const inspectTableId = 'inspect-table-' + Date.now();
|
||||
const searchInputId = 'inspect-search-' + Date.now();
|
||||
|
||||
const rowsHtml = records.map((r, idx) => `
|
||||
<tr class="inspect-row border-b border-slate-100 text-xs ${r.is_present ? 'bg-white' : 'bg-slate-50/60'} hover:bg-indigo-50/40"
|
||||
data-fio="${escapeHtml(r.fio).toLowerCase()}" data-dept="${escapeHtml(r.department).toLowerCase()}">
|
||||
<td class="p-2.5 text-slate-400 text-center font-mono w-10">${idx + 1}</td>
|
||||
<td class="p-2.5 font-medium text-slate-800">${escapeHtml(r.fio)}</td>
|
||||
<td class="p-2.5 text-slate-500 text-center">${escapeHtml(r.department)}</td>
|
||||
<td class="p-2.5 text-center ${r.time_in !== 'Нет входа' ? 'font-bold text-emerald-700' : 'text-slate-400'}">${escapeHtml(r.time_in)}</td>
|
||||
<td class="p-2.5 text-center text-slate-500">${escapeHtml(r.first_activity)}</td>
|
||||
<td class="p-2.5 text-center ${r.time_out !== 'Нет выхода' ? 'font-bold text-slate-800' : 'text-slate-400'}">${escapeHtml(r.time_out)}</td>
|
||||
<td class="p-2.5 text-center font-mono text-slate-600">${escapeHtml(r.in_building)}</td>
|
||||
<td class="p-2.5 text-center font-bold">${r.is_present ? '<span class="text-emerald-600">✓ Да</span>' : '<span class="text-slate-400">Нет</span>'}</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
|
||||
payloadHtml = `
|
||||
<div class="mt-3 bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm flex flex-col">
|
||||
<div class="px-4 py-3 bg-slate-100/90 border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm font-bold text-slate-800">Срез #${escapeHtml(actionPayload.snapshot_id)}</span>
|
||||
<span class="text-xs text-slate-500">· Всего: ${records.length} чел. (Присутствуют: ${actionPayload.present_count || 0})</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="text" id="${searchInputId}" placeholder="Поиск в срезе (ФИО / отдел)..."
|
||||
oninput="window.filterInspectTable('${inspectTableId}', this.value)"
|
||||
class="text-xs px-3 py-1.5 bg-white border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 w-60" />
|
||||
<button onclick="window.sendChatAction('покажи срезы')" class="text-xs text-indigo-600 hover:underline font-semibold">Все срезы</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="max-h-96 overflow-y-auto">
|
||||
<table id="${inspectTableId}" class="w-full text-left border-collapse">
|
||||
<thead class="bg-slate-50 text-[11px] uppercase text-slate-500 sticky top-0 border-b border-slate-200 shadow-xs">
|
||||
<tr>
|
||||
<th class="p-2.5 text-center w-10">№</th>
|
||||
<th class="p-2.5">Сотрудник</th>
|
||||
<th class="p-2.5 text-center">Отдел</th>
|
||||
<th class="p-2.5 text-center">Вход</th>
|
||||
<th class="p-2.5 text-center">Активность</th>
|
||||
<th class="p-2.5 text-center">Выход</th>
|
||||
<th class="p-2.5 text-center">В здании</th>
|
||||
<th class="p-2.5 text-center">Статус</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${rowsHtml}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'PROMPT_EDITOR') {
|
||||
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
|
||||
const editorId = 'prompt-editor-' + Date.now();
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
|
||||
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
|
||||
<span><i class="fa-solid fa-pen-to-square text-indigo-600 mr-1"></i> Инлайн-редактор системного промпта:</span>
|
||||
<span class="text-[11px] text-slate-400 font-normal">Прямое редактирование текста</span>
|
||||
</div>
|
||||
<textarea id="${editorId}" rows="14"
|
||||
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
|
||||
<div class="flex items-center justify-end gap-2 pt-1">
|
||||
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
|
||||
<button type="button" onclick="window.submitPromptDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-eye text-xs"></i>
|
||||
<span>Показать превью изменений</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'RULES_EDITOR') {
|
||||
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
|
||||
const editorId = 'rules-editor-' + Date.now();
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
|
||||
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
|
||||
<span><i class="fa-solid fa-book-bookmark text-emerald-600 mr-1"></i> Редактор базы знаний и правил компании:</span>
|
||||
<span class="text-[11px] text-slate-400 font-normal">Прямое изменение правил кадрового арбитража</span>
|
||||
</div>
|
||||
<textarea id="${editorId}" rows="12"
|
||||
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
|
||||
<div class="flex items-center justify-end gap-2 pt-1">
|
||||
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
|
||||
<button type="button" onclick="window.submitRulesDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-eye text-xs"></i>
|
||||
<span>Показать превью изменений</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'PROMPT_PREVIEW') {
|
||||
isHtmlBody = true;
|
||||
}
|
||||
}
|
||||
|
||||
let buttonsHtml = '';
|
||||
if (!actionPayload || (actionPayload.type !== 'PROMPT_EDITOR' && actionPayload.type !== 'RULES_EDITOR')) {
|
||||
const allButtons = (buttons && buttons.length > 0) ? buttons : (actionPayload && actionPayload.buttons ? actionPayload.buttons : []);
|
||||
if (allButtons && Array.isArray(allButtons) && allButtons.length > 0) {
|
||||
buttonsHtml = `
|
||||
<div class="flex flex-wrap gap-2 mt-3.5 pt-2.5 border-t border-slate-100">
|
||||
${allButtons.map(b => `
|
||||
<button onclick="window.sendChatAction('${escapeHtml(b.value || b.action || b.title || '')}')"
|
||||
class="px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-lg text-xs font-semibold border border-indigo-200 transition">
|
||||
${escapeHtml(b.label || b.title || b.action)}
|
||||
</button>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const bodyContent = isHtmlBody ? text : escapeHtml(text);
|
||||
|
||||
const html = `
|
||||
<div class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm min-w-0">
|
||||
<div class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1.5">ИИ-ассистент SCUD Orion AI</div>
|
||||
<div class="text-sm text-slate-800 leading-relaxed whitespace-pre-wrap">${bodyContent}</div>
|
||||
${payloadHtml}
|
||||
${buttonsHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
}
|
||||
|
||||
window.filterInspectTable = function(tableId, query) {
|
||||
const table = document.getElementById(tableId);
|
||||
if (!table) return;
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
const rows = table.querySelectorAll('.inspect-row');
|
||||
rows.forEach(r => {
|
||||
const fio = r.getAttribute('data-fio') || '';
|
||||
const dept = r.getAttribute('data-dept') || '';
|
||||
if (!q || fio.includes(q) || dept.includes(q)) {
|
||||
r.classList.remove('hidden');
|
||||
} else {
|
||||
r.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
window.sendChatAction = function(actionText) {
|
||||
if (!actionText || !actionText.trim()) return;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) {
|
||||
input.value = actionText.trim();
|
||||
updateInputHeightAndFade(input);
|
||||
}
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.submitPromptDraftToDiff = function(editorId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
if (!textarea) return;
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) {
|
||||
alert("Текст системного промпта не может быть пустым");
|
||||
return;
|
||||
}
|
||||
|
||||
const command = `action:save_draft_prompt:::${newText}`;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) input.value = command;
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.submitRulesDraftToDiff = function(editorId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
if (!textarea) return;
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) {
|
||||
alert("Правила не могут быть пустыми");
|
||||
return;
|
||||
}
|
||||
|
||||
const command = `action:save_draft_rules:::${newText}`;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) input.value = command;
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.sendMessage = async function() {
|
||||
const input = document.getElementById("user-input");
|
||||
if (!input) return;
|
||||
|
||||
const messageText = input.value.trim();
|
||||
const fileToSend = currentAttachedFile;
|
||||
|
||||
if (!messageText && !fileToSend) return;
|
||||
|
||||
saveCommandToHistory(messageText);
|
||||
|
||||
input.value = "";
|
||||
input.style.height = '24px';
|
||||
input.style.overflowY = 'hidden';
|
||||
input.style.maskImage = 'none';
|
||||
input.style.webkitMaskImage = 'none';
|
||||
window.clearAttachedFile();
|
||||
|
||||
// 1. Отрисовка сообщения пользователя в ленте
|
||||
if (!messageText.startsWith("action:save_draft_prompt:::") && !messageText.startsWith("action:save_draft_rules:::")) {
|
||||
appendUserMessage(
|
||||
messageText || (fileToSend ? `Прикреплен файл: ${fileToSend.name}` : ''),
|
||||
fileToSend ? fileToSend.name : null
|
||||
);
|
||||
} else {
|
||||
appendUserMessage("Сформировать предпросмотр изменений");
|
||||
}
|
||||
|
||||
// 2. Вставка лоадера
|
||||
const loadingId = appendAssistantLoading();
|
||||
|
||||
// 3. Вызов точного скролла
|
||||
scrollToUserMessageTop();
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: message,
|
||||
session_id: sessionId,
|
||||
user_id: userId
|
||||
})
|
||||
let res;
|
||||
if (fileToSend) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", fileToSend);
|
||||
formData.append("message", messageText);
|
||||
formData.append("session_id", "web_session_main");
|
||||
|
||||
res = await fetch("/api/v1/chat/upload", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": AuthManager.getAuthHeaders()["Authorization"]
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (res.status === 404) {
|
||||
res = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: messageText || `Загружен файл: ${fileToSend.name}`,
|
||||
session_id: "web_session_main"
|
||||
})
|
||||
});
|
||||
}
|
||||
} else {
|
||||
res = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: messageText,
|
||||
session_id: "web_session_main"
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
const loaderEl = document.getElementById(loadingId);
|
||||
if (loaderEl) loaderEl.remove();
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const replyText = data.response || data.text || data.message || "Запрос выполнен.";
|
||||
const buttons = data.buttons || [];
|
||||
const actionPayload = data.action_payload || null;
|
||||
|
||||
appendAssistantMessage(replyText, buttons, actionPayload);
|
||||
|
||||
if (window.SidebarManager) {
|
||||
SidebarManager.renderContent();
|
||||
}
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Ошибка отправки сообщения:", err);
|
||||
const loaderEl = document.getElementById(loadingId);
|
||||
if (loaderEl) loaderEl.remove();
|
||||
appendAssistantMessage("⚠️ Ошибка соединения с сервером при отправке сообщения.");
|
||||
}
|
||||
};
|
||||
|
||||
window.clearAttachedFile = function() {
|
||||
currentAttachedFile = null;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
|
||||
if (preview) preview.classList.add("hidden");
|
||||
if (nameEl) nameEl.innerText = "";
|
||||
if (fileInput) fileInput.value = "";
|
||||
};
|
||||
|
||||
function handleFileSelected(file) {
|
||||
if (!file) return;
|
||||
currentAttachedFile = file;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
|
||||
if (preview && nameEl) {
|
||||
nameEl.innerText = file.name;
|
||||
preview.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const input = document.getElementById("user-input");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
const overlay = document.getElementById("global-drag-overlay");
|
||||
|
||||
if (input) {
|
||||
input.style.lineHeight = '24px';
|
||||
input.style.height = '24px';
|
||||
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
if (e.shiftKey) return;
|
||||
e.preventDefault();
|
||||
window.sendMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtBeginning = input.selectionStart === 0 && input.selectionEnd === 0;
|
||||
|
||||
if (isSingleLine || isAtBeginning) {
|
||||
if (chatInputHistory.length > 0) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex === -1) {
|
||||
temporaryCurrentInput = input.value;
|
||||
chatHistoryIndex = chatInputHistory.length - 1;
|
||||
} else if (chatHistoryIndex > 0) {
|
||||
chatHistoryIndex--;
|
||||
}
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
} else if (e.key === "ArrowDown") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtEnd = input.selectionStart === input.value.length;
|
||||
|
||||
if (isSingleLine || isAtEnd) {
|
||||
if (chatHistoryIndex !== -1) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex < chatInputHistory.length - 1) {
|
||||
chatHistoryIndex++;
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
} else {
|
||||
chatHistoryIndex = -1;
|
||||
input.value = temporaryCurrentInput;
|
||||
}
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (response.status === 403) {
|
||||
console.warn("[Chat] Получен 403 Forbidden. Сбрасываем сессию и повторяем...");
|
||||
localStorage.removeItem("auth_token");
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", "⚠️ Сессия была обновлена. Пожалуйста, отправьте сообщение повторно.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ошибка сервера (HTTP ${response.status})`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const reply = data.response || data.message || "Ответ получен без текста.";
|
||||
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", reply);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error("[Chat Error]:", err);
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", `⚠️ Не удалось связаться с сервером: ${err.message}`);
|
||||
}
|
||||
input.addEventListener("input", function() {
|
||||
updateInputHeightAndFade(this);
|
||||
chatHistoryIndex = -1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener("change", (e) => {
|
||||
if (e.target.files && e.target.files[0]) {
|
||||
handleFileSelected(e.target.files[0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let dragCounter = 0;
|
||||
|
||||
window.addEventListener('dragenter', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter++;
|
||||
if (overlay) {
|
||||
overlay.classList.remove('hidden');
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragleave', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter--;
|
||||
if (dragCounter <= 0) {
|
||||
dragCounter = 0;
|
||||
if (overlay) {
|
||||
overlay.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
}, false);
|
||||
|
||||
window.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter = 0;
|
||||
if (overlay) {
|
||||
overlay.classList.add('hidden');
|
||||
}
|
||||
|
||||
const dt = e.dataTransfer;
|
||||
if (dt && dt.files && dt.files[0]) {
|
||||
handleFileSelected(dt.files[0]);
|
||||
}
|
||||
}, false);
|
||||
});
|
||||
Reference in New Issue
Block a user