From 676437a958f70feea8ab38dac9d177774165096f Mon Sep 17 00:00:00 2001 From: Aleksandr Pushkov Date: Tue, 27 Oct 2026 15:23:45 +0300 Subject: [PATCH] refactor(chat): decompose core.js into scroll.js, messages.js, input.js, and core.js --- modules/web_api/routers/chat.py | 14 - modules/web_api/static/index.html | 3 + modules/web_api/static/js/app.js | 3 +- modules/web_api/static/js/chat/core.js | 322 +-------------------- modules/web_api/static/js/chat/input.js | 207 +++++++++++++ modules/web_api/static/js/chat/messages.js | 106 +++++++ modules/web_api/static/js/chat/scroll.js | 47 +++ modules/web_api/static/js/chat/topics.js | 75 +---- 8 files changed, 385 insertions(+), 392 deletions(-) create mode 100644 modules/web_api/static/js/chat/input.js create mode 100644 modules/web_api/static/js/chat/messages.js create mode 100644 modules/web_api/static/js/chat/scroll.js diff --git a/modules/web_api/routers/chat.py b/modules/web_api/routers/chat.py index 477ecde..498b350 100644 --- a/modules/web_api/routers/chat.py +++ b/modules/web_api/routers/chat.py @@ -44,9 +44,6 @@ class ChatMessageRequest(BaseModel): session_id: Optional[str] = "session_main" -class UpdateSessionRequest(BaseModel): - title: str - class CreateSessionRequest(BaseModel): title: Optional[str] = None session_id: Optional[str] = None @@ -82,17 +79,6 @@ def create_chat_session_endpoint(payload: CreateSessionRequest, current_user=Dep return {"status": "success", "session": session} - -@router.patch("/sessions/{session_id}") -def update_chat_session_endpoint(session_id: str, payload: UpdateSessionRequest, current_user=Depends(get_current_user)): - """Ручное переименование названия диалога оператором.""" - new_title = payload.title.strip() - if not new_title: - raise HTTPException(status_code=400, detail="Название не может быть пустым") - db_update_session_title(session_id=session_id, new_title=new_title) - return {"status": "success", "session_id": session_id, "title": new_title} - - @router.delete("/sessions/{session_id}") def delete_chat_session_endpoint(session_id: str, current_user=Depends(get_current_user)): """Каскадное удаление темы и всех её сообщений.""" diff --git a/modules/web_api/static/index.html b/modules/web_api/static/index.html index a365126..2299a9b 100644 --- a/modules/web_api/static/index.html +++ b/modules/web_api/static/index.html @@ -248,6 +248,9 @@ + + + diff --git a/modules/web_api/static/js/app.js b/modules/web_api/static/js/app.js index 2569eae..d93c6ec 100644 --- a/modules/web_api/static/js/app.js +++ b/modules/web_api/static/js/app.js @@ -31,8 +31,7 @@ async function loadModals() { 'admin_modal.html', 'snapshot_inspector_modal.html', 'presence_modal.html', - 'confirm_modal.html', - 'rename_topic_modal.html' + 'confirm_modal.html' ]; const container = document.getElementById('modals-container'); diff --git a/modules/web_api/static/js/chat/core.js b/modules/web_api/static/js/chat/core.js index 345cfbf..2a8d97b 100644 --- a/modules/web_api/static/js/chat/core.js +++ b/modules/web_api/static/js/chat/core.js @@ -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 = ` -
- - ${escapeHtml(filename)} -
- `; - } - - const msgHtml = ` -
-
- ${fileBadge} -
${escapeHtml(text)}
-
-
- -
-
- `; - container.insertAdjacentHTML("beforeend", msgHtml); -} - -function appendAssistantLoading() { - const container = document.getElementById("chat-messages-container"); - if (!container) return null; - - const loadingId = 'loading-' + Date.now(); - const html = ` -
-
- -
-
-
- - ИИ обрабатывает запрос... -
-
-
- `; - 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 = ` -
- ${allButtons.map(b => ` - - `).join('')} -
- `; - } - } - - const bodyContent = isHtmlBody ? text : escapeHtml(text); - - const html = ` -
-
- -
-
-
ИИ-ассистент SCUD Orion AI
-
${bodyContent}
- ${payloadHtml} - ${buttonsHtml} -
-
- `; - 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); -}); diff --git a/modules/web_api/static/js/chat/input.js b/modules/web_api/static/js/chat/input.js new file mode 100644 index 0000000..5b4a13e --- /dev/null +++ b/modules/web_api/static/js/chat/input.js @@ -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; diff --git a/modules/web_api/static/js/chat/messages.js b/modules/web_api/static/js/chat/messages.js new file mode 100644 index 0000000..279197b --- /dev/null +++ b/modules/web_api/static/js/chat/messages.js @@ -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 = ` +
+ + ${escapeHtml(filename)} +
+ `; + } + + const msgHtml = ` +
+
+ ${fileBadge} +
${escapeHtml(text)}
+
+
+ +
+
+ `; + 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 = ` +
+
+ +
+
+
+ + ИИ обрабатывает запрос... +
+
+
+ `; + 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 = ` +
+ ${allButtons.map(b => ` + + `).join('')} +
+ `; + } + } + + const bodyContent = isHtmlBody ? text : escapeHtml(text); + + const html = ` +
+
+ +
+
+
ИИ-ассистент SCUD Orion AI
+
${bodyContent}
+ ${payloadHtml} + ${buttonsHtml} +
+
+ `; + container.insertAdjacentHTML("beforeend", html); + + if (window.ensureScrollSpacerAtEnd) { + window.ensureScrollSpacerAtEnd(); + } +}; diff --git a/modules/web_api/static/js/chat/scroll.js b/modules/web_api/static/js/chat/scroll.js new file mode 100644 index 0000000..15c6b8a --- /dev/null +++ b/modules/web_api/static/js/chat/scroll.js @@ -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); + } +}; diff --git a/modules/web_api/static/js/chat/topics.js b/modules/web_api/static/js/chat/topics.js index 8b3a5a9..8c00e46 100644 --- a/modules/web_api/static/js/chat/topics.js +++ b/modules/web_api/static/js/chat/topics.js @@ -119,20 +119,12 @@ window.TopicsManager = (function() { -
- - -
+ `; }).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 }; })();