refactor(chat): decompose core.js into scroll.js, messages.js, input.js, and core.js
This commit is contained in:
@@ -1,183 +1,16 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/chat/core.js
|
||||
* ROLE: Ядро чата: сессии (TopicsManager), отправка сообщений,
|
||||
* индикатор загрузки, Drag-and-Drop и автоскролл.
|
||||
* ROLE: Сетевой диспетчер чата: отправка сообщений и файлов на бэкенд FastAPI.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
let currentAttachedFile = null;
|
||||
|
||||
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];
|
||||
if (!targetEl) return;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const targetScroll = targetEl.offsetTop - container.offsetTop - 12;
|
||||
container.scrollTo({
|
||||
top: Math.max(0, targetScroll),
|
||||
behavior: 'smooth'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function updateInputHeightAndFade(textarea) {
|
||||
if (!textarea) return;
|
||||
|
||||
if (!textarea.value || textarea.value.trim() === '') {
|
||||
textarea.style.height = '32px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
textarea.style.height = 'auto';
|
||||
const minHeight = 32;
|
||||
const maxHeight = 140;
|
||||
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 msgHtml = `
|
||||
<div id="${msgId}" class="user-chat-bubble relative 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;
|
||||
|
||||
const payloadHtml = window.ChatCardsRenderer
|
||||
? window.ChatCardsRenderer.renderActionPayload(actionPayload)
|
||||
: '';
|
||||
|
||||
const isHtmlBody = actionPayload && actionPayload.type === 'PROMPT_PREVIEW';
|
||||
|
||||
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.sendChatAction = function(actionText) {
|
||||
if (!actionText || !actionText.trim()) return;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) {
|
||||
input.value = actionText.trim();
|
||||
updateInputHeightAndFade(input);
|
||||
window.ChatInput.updateInputHeightAndFade(input);
|
||||
}
|
||||
window.sendMessage();
|
||||
};
|
||||
@@ -187,34 +20,30 @@ window.sendMessage = async function() {
|
||||
if (!input) return;
|
||||
|
||||
const messageText = input.value.trim();
|
||||
const fileToSend = currentAttachedFile;
|
||||
const fileToSend = window.ChatInput.getAttachedFile();
|
||||
|
||||
if (!messageText && !fileToSend) return;
|
||||
|
||||
saveCommandToHistory(messageText);
|
||||
|
||||
input.value = "";
|
||||
input.style.height = '32px';
|
||||
input.style.overflowY = 'hidden';
|
||||
input.style.maskImage = 'none';
|
||||
input.style.webkitMaskImage = 'none';
|
||||
window.clearAttachedFile();
|
||||
window.ChatInput.saveCommandToHistory(messageText);
|
||||
window.ChatInput.resetInput(input);
|
||||
|
||||
const activeSessionId = (window.TopicsManager && typeof window.TopicsManager.getActiveSessionId === "function")
|
||||
? window.TopicsManager.getActiveSessionId()
|
||||
: "session_main";
|
||||
|
||||
if (!messageText.startsWith("action:save_draft_prompt:::") && !messageText.startsWith("action:save_draft_rules:::")) {
|
||||
appendUserMessage(
|
||||
window.appendUserMessage(
|
||||
messageText || (fileToSend ? `Прикреплен файл: ${fileToSend.name}` : ''),
|
||||
fileToSend ? fileToSend.name : null
|
||||
);
|
||||
} else {
|
||||
appendUserMessage("Сформировать предпросмотр изменений");
|
||||
window.appendUserMessage("Сформировать предпросмотр изменений");
|
||||
}
|
||||
|
||||
const loadingId = appendAssistantLoading();
|
||||
scrollToUserMessageTop();
|
||||
const loadingId = window.appendAssistantLoading();
|
||||
if (window.scrollToUserMessageTop) {
|
||||
window.scrollToUserMessageTop();
|
||||
}
|
||||
|
||||
try {
|
||||
let res;
|
||||
@@ -260,7 +89,7 @@ window.sendMessage = async function() {
|
||||
const buttons = data.buttons || [];
|
||||
const actionPayload = data.action_payload || null;
|
||||
|
||||
appendAssistantMessage(replyText, buttons, actionPayload);
|
||||
window.appendAssistantMessage(replyText, buttons, actionPayload);
|
||||
|
||||
if (window.SidebarManager) {
|
||||
SidebarManager.renderContent();
|
||||
@@ -268,141 +97,18 @@ window.sendMessage = async function() {
|
||||
|
||||
if (window.TopicsManager && typeof window.TopicsManager.loadTopics === "function") {
|
||||
window.TopicsManager.loadTopics();
|
||||
// ⭐️ Повторный запрос через 2.5 сек, когда фоновая LLM завершит суммаризацию заголовка:
|
||||
setTimeout(() => {
|
||||
window.TopicsManager.loadTopics();
|
||||
}, 2500);
|
||||
}
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
||||
window.appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Ошибка отправки сообщения:", err);
|
||||
const loaderEl = document.getElementById(loadingId);
|
||||
if (loaderEl) loaderEl.remove();
|
||||
appendAssistantMessage("⚠️ Ошибка соединения с сервером при отправке сообщения.");
|
||||
window.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 = '32px';
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/chat/input.js
|
||||
* ROLE: Управление полем ввода (textarea), автовысота, история команд и Drag-and-Drop.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
window.ChatInput = (function() {
|
||||
let currentAttachedFile = null;
|
||||
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 updateInputHeightAndFade(textarea) {
|
||||
if (!textarea) return;
|
||||
|
||||
if (!textarea.value || textarea.value.trim() === '') {
|
||||
textarea.style.height = '32px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
textarea.style.height = 'auto';
|
||||
const minHeight = 32;
|
||||
const maxHeight = 140;
|
||||
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 clearAttachedFile() {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
function getAttachedFile() {
|
||||
return currentAttachedFile;
|
||||
}
|
||||
|
||||
function resetInput(input) {
|
||||
if (!input) return;
|
||||
input.value = "";
|
||||
input.style.height = '32px';
|
||||
input.style.overflowY = 'hidden';
|
||||
input.style.maskImage = 'none';
|
||||
input.style.webkitMaskImage = 'none';
|
||||
clearAttachedFile();
|
||||
}
|
||||
|
||||
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 = '32px';
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
return {
|
||||
saveCommandToHistory,
|
||||
updateInputHeightAndFade,
|
||||
clearAttachedFile,
|
||||
getAttachedFile,
|
||||
resetInput
|
||||
};
|
||||
})();
|
||||
|
||||
// Для совместимости с вызовами из HTML
|
||||
window.clearAttachedFile = window.ChatInput.clearAttachedFile;
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/chat/messages.js
|
||||
* ROLE: Рендеринг пузырей сообщений пользователя, ассистента и индикатора загрузки.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
window.appendUserMessage = function(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 msgHtml = `
|
||||
<div id="${msgId}" class="user-chat-bubble relative 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);
|
||||
};
|
||||
|
||||
window.appendAssistantLoading = function() {
|
||||
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;
|
||||
};
|
||||
|
||||
window.appendAssistantMessage = function(text, buttons = [], actionPayload = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const payloadHtml = window.ChatCardsRenderer
|
||||
? window.ChatCardsRenderer.renderActionPayload(actionPayload)
|
||||
: '';
|
||||
|
||||
const isHtmlBody = actionPayload && actionPayload.type === 'PROMPT_PREVIEW';
|
||||
|
||||
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);
|
||||
|
||||
if (window.ensureScrollSpacerAtEnd) {
|
||||
window.ensureScrollSpacerAtEnd();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/chat/scroll.js
|
||||
* ROLE: Изолированный движок скролла чата (Gemini-style scroll to top).
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
window.scrollToUserMessageTop = function() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
// Обеспечиваем невидимый эластичный спейсер в конце ленты
|
||||
let spacer = document.getElementById("chat-scroll-spacer");
|
||||
if (!spacer) {
|
||||
spacer = document.createElement("div");
|
||||
spacer.id = "chat-scroll-spacer";
|
||||
spacer.style.height = "calc(100vh - 220px)";
|
||||
spacer.style.flexShrink = "0";
|
||||
spacer.style.pointerEvents = "none";
|
||||
container.appendChild(spacer);
|
||||
} else {
|
||||
container.appendChild(spacer);
|
||||
}
|
||||
|
||||
const userBubbles = container.querySelectorAll(".user-chat-bubble");
|
||||
const targetEl = userBubbles[userBubbles.length - 1];
|
||||
if (!targetEl) return;
|
||||
|
||||
setTimeout(() => {
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const targetRect = targetEl.getBoundingClientRect();
|
||||
const targetScrollTop = container.scrollTop + (targetRect.top - containerRect.top) - 16;
|
||||
|
||||
container.scrollTo({
|
||||
top: Math.max(0, targetScrollTop),
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}, 40);
|
||||
};
|
||||
|
||||
window.ensureScrollSpacerAtEnd = function() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
const spacer = document.getElementById("chat-scroll-spacer");
|
||||
if (container && spacer) {
|
||||
container.appendChild(spacer);
|
||||
}
|
||||
};
|
||||
@@ -119,20 +119,12 @@ window.TopicsManager = (function() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition shrink-0 mt-0.5">
|
||||
<button type="button"
|
||||
onclick="event.stopPropagation(); window.TopicsManager.openRenameModal('${session.id}', '${escapeHtml(title)}')"
|
||||
class="p-1 text-slate-400 hover:text-indigo-600 rounded transition"
|
||||
title="Переименовать тему">
|
||||
<i class="fa-solid fa-pencil text-xs"></i>
|
||||
</button>
|
||||
<button type="button"
|
||||
onclick="event.stopPropagation(); window.TopicsManager.askDeleteTopic('${session.id}', '${escapeHtml(title)}')"
|
||||
class="p-1 text-slate-400 hover:text-rose-600 rounded transition"
|
||||
title="Удалить чат">
|
||||
<i class="fa-solid fa-trash-can text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
<button type="button"
|
||||
onclick="event.stopPropagation(); window.TopicsManager.askDeleteTopic('${session.id}', '${escapeHtml(title)}')"
|
||||
class="opacity-0 group-hover:opacity-100 p-1 text-slate-400 hover:text-rose-600 rounded transition shrink-0"
|
||||
title="Удалить чат">
|
||||
<i class="fa-solid fa-trash-can text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
@@ -283,65 +275,12 @@ window.TopicsManager = (function() {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
function openRenameModal(sessionId, currentTitle) {
|
||||
const modal = document.getElementById("rename-topic-modal");
|
||||
const idInput = document.getElementById("rename-topic-session-id");
|
||||
const titleInput = document.getElementById("rename-topic-input");
|
||||
|
||||
if (idInput) idInput.value = sessionId;
|
||||
if (titleInput) {
|
||||
titleInput.value = currentTitle;
|
||||
setTimeout(() => {
|
||||
titleInput.focus();
|
||||
titleInput.select();
|
||||
}, 50);
|
||||
}
|
||||
if (modal) modal.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function closeRenameModal() {
|
||||
const modal = document.getElementById("rename-topic-modal");
|
||||
if (modal) modal.classList.add("hidden");
|
||||
}
|
||||
|
||||
async function submitRenameModal(event) {
|
||||
if (event) event.preventDefault();
|
||||
const sessionId = document.getElementById("rename-topic-session-id")?.value;
|
||||
const newTitle = document.getElementById("rename-topic-input")?.value.trim();
|
||||
|
||||
if (!sessionId || !newTitle) return;
|
||||
closeRenameModal();
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/chat/sessions/' + encodeURIComponent(sessionId), {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
...AuthManager.getAuthHeaders(),
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ title: newTitle })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
await loadTopics();
|
||||
} else {
|
||||
console.error("Ошибка сохранения названия темы");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Ошибка сети при переименовании темы:", e);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
init,
|
||||
loadTopics,
|
||||
getActiveSessionId,
|
||||
switchTopic,
|
||||
createNewTopic,
|
||||
askDeleteTopic,
|
||||
openRenameModal,
|
||||
closeRenameModal,
|
||||
submitRenameModal
|
||||
askDeleteTopic
|
||||
};
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user