/** =============================================================================== FILE: modules/web_api/static/js/chat.js ROLE: Клиентский интерфейс диалога, Drag-and-Drop вложений, генерация динамических кнопок подтверждений и рендеринг Generative UI интерактивного виджета задач. AI-CONTEXT-ANCHORS: - ANCHOR[FILE_UPLOAD_UTILS]: Выбор, превью и очистка прикрепленных файлов. - ANCHOR[INTERACTIVE_BUTTONS_CORE]: Деактивация и быстрая отправка нажатых кнопок. - ANCHOR[INTERACTIVE_TASK_WIDGET_JS]: Рендерер и REST-обработчики виджета задач. - ANCHOR[CHAT_SEND_PIPELINE]: Главный метод sendMessage и вставка сообщений в DOM. - ANCHOR[DRAG_DROP_HANDLERS]: Обработка перетаскивания файлов в окно чата. =============================================================================== */ // --- [SECTION 1: FILE UPLOAD HELPERS] --- # ANCHOR[FILE_UPLOAD_UTILS] function updateInputHeight(el) { if (!el) return; el.style.height = "24px"; const newHeight = Math.min(el.scrollHeight, 120); el.style.height = newHeight + "px"; } let selectedFile = null; function handleFileSelect(e) { const file = e.target.files[0]; if (!file) return; if (file.size > 15 * 1024 * 1024) { alert("Файл слишком большой. Максимальный размер: 15 МБ"); e.target.value = ""; return; } selectedFile = file; const fileNameEl = document.getElementById("file-name-display"); const fileSizeEl = document.getElementById("file-size-display"); const previewContainer = document.getElementById("file-preview-container"); if (fileNameEl) fileNameEl.innerText = file.name; if (fileSizeEl) fileSizeEl.innerText = `(${(file.size / 1024).toFixed(1)} KB)`; if (previewContainer) previewContainer.classList.remove("hidden"); } function clearAttachedFile() { selectedFile = null; const fileInput = document.getElementById("file-input"); const previewContainer = document.getElementById("file-preview-container"); if (fileInput) fileInput.value = ""; if (previewContainer) previewContainer.classList.add("hidden"); } // --- [SECTION 2: ACTION BUTTONS CORE] --- # ANCHOR[INTERACTIVE_BUTTONS_CORE] function disableAllActionButtons() { const allBtnContainers = document.querySelectorAll(".action-buttons-container"); allBtnContainers.forEach(container => { container.querySelectorAll("button").forEach(btn => { btn.disabled = true; btn.classList.add("opacity-40", "cursor-not-allowed"); }); }); } function handleActionButtonClick(text) { disableAllActionButtons(); const input = document.getElementById("user-input"); if (input) { input.value = text; sendMessage(); } } // --- [SECTION 3: INTERACTIVE TASK WIDGET] --- # ANCHOR[INTERACTIVE_TASK_WIDGET_JS] let activeWidgetTasksMap = new Map(); function renderTaskItemsHtml(tasks, filterStatus) { const filtered = tasks.filter(t => { if (filterStatus === "ALL") return true; return t.status === filterStatus; }); if (filtered.length === 0) { const label = filterStatus === 'BACKLOG' ? 'В планах' : filterStatus === 'IN_PROGRESS' ? 'В работе' : filterStatus === 'COMPLETED' ? 'Завершенные' : 'Все'; return `
Нет задач со статусом «${label}»
`; } return filtered.map(t => { const isDone = t.status === "COMPLETED"; const isProgress = t.status === "IN_PROGRESS"; const checkedAttr = isDone ? "checked" : ""; const textClass = isDone ? "line-through text-slate-400" : "text-slate-800 font-medium"; let statusPill = `В планах`; if (isDone) { statusPill = `Завершено`; } else if (isProgress) { statusPill = `В работе`; } let prioPill = ""; if (t.priority === "HIGH") { prioPill = `HIGH`; } return `
${t.task_id} ${prioPill} ${statusPill}
${escapeHtml(t.title)}
`; }).join(""); } function renderInteractiveTaskCard(tasks) { if (!tasks || !Array.isArray(tasks)) return ""; const widgetId = "task_widget_" + Date.now(); activeWidgetTasksMap.set(widgetId, { tasks: tasks, filter: "ALL" }); const itemsHtml = renderTaskItemsHtml(tasks, "ALL"); return `
${itemsHtml}
`; } function filterTaskWidget(widgetId, status, btnEl) { const state = activeWidgetTasksMap.get(widgetId); if (!state) return; state.filter = status; const widgetEl = document.getElementById(widgetId); if (!widgetEl) return; widgetEl.querySelectorAll(".widget-tab-btn").forEach(b => { b.className = "widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700"; }); btnEl.className = "widget-tab-btn px-2.5 py-1 rounded-lg bg-indigo-50 text-indigo-600 font-bold border border-indigo-200"; const container = widgetEl.querySelector(".widget-items-container"); if (container) { container.innerHTML = renderTaskItemsHtml(state.tasks, status); } } async function toggleTaskStatusInline(taskId, isChecked) { const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token"); const newStatus = isChecked ? "COMPLETED" : "BACKLOG"; try { const res = await fetch(`/api/v1/tasks/${taskId}`, { method: "PATCH", headers: { "Content-Type": "application/json", "Authorization": "Bearer " + token }, body: JSON.stringify({ status: newStatus }) }); if (res.ok) { // Обновляем статус задачи во всех локальных виджетах for (let [wId, state] of activeWidgetTasksMap.entries()) { const targetTask = state.tasks.find(t => t.task_id === taskId); if (targetTask) { targetTask.status = newStatus; const widgetEl = document.getElementById(wId); const container = widgetEl?.querySelector(".widget-items-container"); if (container) { container.innerHTML = renderTaskItemsHtml(state.tasks, state.filter); } } } if (typeof loadTasks === "function") loadTasks(); } } catch (err) { console.error("[Task Patch Error]", err); } } async function deleteTaskInline(taskId) { if (!confirm(`Удалить задачу ${taskId}?`)) return; const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token"); try { const res = await fetch(`/api/v1/tasks/${taskId}`, { method: "DELETE", headers: { "Authorization": "Bearer " + token } }); if (res.ok) { for (let [wId, state] of activeWidgetTasksMap.entries()) { state.tasks = state.tasks.filter(t => t.task_id !== taskId); const widgetEl = document.getElementById(wId); const container = widgetEl?.querySelector(".widget-items-container"); if (container) { container.innerHTML = renderTaskItemsHtml(state.tasks, state.filter); } } if (typeof loadTasks === "function") loadTasks(); } } catch (err) { console.error("[Task Delete Error]", err); } } async function addTaskInline(widgetId, inputEl) { if (!inputEl) return; const title = inputEl.value.trim(); if (!title) return; const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token"); try { const res = await fetch("/api/v1/tasks", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer " + token }, body: JSON.stringify({ title: title, priority: "MEDIUM", module: "general" }) }); if (res.ok) { inputEl.value = ""; // Мгновенная выгрузка свежего списка без обращения к LLM const tasksRes = await fetch("/api/v1/tasks", { headers: { "Authorization": "Bearer " + token } }); const updatedTasks = await tasksRes.json(); const state = activeWidgetTasksMap.get(widgetId); if (state) { state.tasks = updatedTasks; const widgetEl = document.getElementById(widgetId); const container = widgetEl?.querySelector(".widget-items-container"); if (container) { container.innerHTML = renderTaskItemsHtml(updatedTasks, state.filter); } } if (typeof loadTasks === "function") loadTasks(); } } catch (err) { console.error("[Task Add Error]", err); } } // --- [SECTION 4: CHAT SEND PIPELINE] --- # ANCHOR[CHAT_SEND_PIPELINE] async function sendMessage(e) { if (e && e.preventDefault) e.preventDefault(); const input = document.getElementById("user-input"); const chatWindow = document.getElementById("chat-window"); const sendBtn = document.getElementById("send-btn"); if (!input || !chatWindow) return; const text = input.value.trim(); if (!text && !selectedFile) return; disableAllActionButtons(); let userDisplayHtml = escapeHtml(text); if (selectedFile) { userDisplayHtml = `
${escapeHtml(selectedFile.name)}
` + userDisplayHtml; } const userMsgHtml = `
${userDisplayHtml}
`; chatWindow.insertAdjacentHTML("beforeend", userMsgHtml); input.value = ""; updateInputHeight(input); chatWindow.scrollTop = chatWindow.scrollHeight; if (sendBtn) { sendBtn.disabled = true; sendBtn.classList.add("opacity-50"); } const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token"); const isGuest = typeof IS_GUEST !== 'undefined' ? IS_GUEST : (localStorage.getItem("scud_is_guest") === "true"); const endpoint = isGuest ? "/api/v1/chat/guest" : "/api/v1/chat"; const formData = new FormData(); formData.append("session_id", "web_session_main"); formData.append("message", text || "Проанализируй прикрепленный файл"); if (selectedFile instanceof File) { formData.append("file", selectedFile, selectedFile.name); } const headers = {}; if (!isGuest && token) { headers["Authorization"] = "Bearer " + token; } try { const res = await fetch(endpoint, { method: "POST", headers: headers, body: formData }); if (res.status === 401 && !isGuest) { if (typeof logout === 'function') logout(); return; } const data = await res.json(); const assistantTitle = isGuest ? "Локальная нейросеть (Гость)" : "ИИ-Ассистент SCUD Orion AI"; const replyText = data.reply || "Пустой ответ от нейросети"; let actionButtonsHtml = ""; const actionData = data.action_type || data.action; if (actionData && actionData.buttons && actionData.buttons.length > 0) { const buttonsMarkup = actionData.buttons.map(btn => { let btnClasses = "bg-slate-100 hover:bg-slate-200 active:bg-slate-300 text-slate-700 border border-slate-300"; let iconMarkup = ''; const labelLower = (btn.label || "").toLowerCase(); const isPrimary = btn.style === "primary" || labelLower.includes("подтверд") || labelLower.startsWith("да"); const isDanger = btn.style === "danger" || labelLower.includes("отмен") || labelLower.startsWith("нет") || labelLower.includes("законч") || labelLower.includes("заверш"); if (isPrimary) { btnClasses = "bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white shadow-sm"; iconMarkup = ''; } else if (isDanger) { btnClasses = "bg-rose-50 hover:bg-rose-100 active:bg-rose-200 text-rose-700 border border-rose-300"; iconMarkup = ''; } return ` `; }).join(""); actionButtonsHtml = `
${buttonsMarkup}
`; } let interactiveWidgetHtml = ""; if (actionData && actionData.type === "TASK_INTERACTIVE_CARD" && Array.isArray(actionData.tasks)) { interactiveWidgetHtml = renderInteractiveTaskCard(actionData.tasks); } const botMsgHtml = `

${assistantTitle}

${escapeHtml(replyText)}

${interactiveWidgetHtml} ${actionButtonsHtml}
`; chatWindow.insertAdjacentHTML("beforeend", botMsgHtml); chatWindow.scrollTop = chatWindow.scrollHeight; clearAttachedFile(); if (!isGuest && typeof loadTasks === 'function') { loadTasks(); } } catch (err) { console.error("[Chat Error]", err); const errorHtml = `
Ошибка связи с сервером.
`; chatWindow.insertAdjacentHTML("beforeend", errorHtml); chatWindow.scrollTop = chatWindow.scrollHeight; } finally { if (sendBtn) { sendBtn.disabled = false; sendBtn.classList.remove("opacity-50"); } } } function escapeHtml(text) { if (!text) return ""; return text .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } // --- [SECTION 5: DRAG & DROP AND KEYBOARD LISTENERS] --- # ANCHOR[DRAG_DROP_HANDLERS] document.addEventListener("DOMContentLoaded", () => { const input = document.getElementById("user-input"); const dropZone = document.getElementById("chat-window")?.parentElement; const dropOverlay = document.getElementById("drop-overlay"); if (input) { let historyIndex = -1; let localHistory = JSON.parse(localStorage.getItem("scud_chat_input_history") || "[]"); input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); const text = input.value.trim(); if (text) { if (localHistory.length === 0 || localHistory[0] !== text) { localHistory.unshift(text); if (localHistory.length > 50) localHistory.pop(); localStorage.setItem("scud_chat_input_history", JSON.stringify(localHistory)); } historyIndex = -1; } sendMessage(e); updateInputHeight(input); return; } if (e.key === "ArrowUp") { const textBeforeCursor = input.value.substring(0, input.selectionStart); const isFirstLine = !textBeforeCursor.includes("\n"); if (isFirstLine && input.selectionStart === 0 && localHistory.length > 0) { if (historyIndex < localHistory.length - 1) { e.preventDefault(); if (historyIndex === -1) { input.dataset.draft = input.value; } historyIndex++; input.value = localHistory[historyIndex]; updateInputHeight(input); input.setSelectionRange(input.value.length, input.value.length); } } } if (e.key === "ArrowDown") { const textAfterCursor = input.value.substring(input.selectionEnd); const isLastLine = !textAfterCursor.includes("\n"); if (isLastLine && input.selectionEnd === input.value.length && historyIndex >= 0) { e.preventDefault(); if (historyIndex > 0) { historyIndex--; input.value = localHistory[historyIndex]; } else { historyIndex = -1; input.value = input.dataset.draft || ""; } updateInputHeight(input); input.setSelectionRange(input.value.length, input.value.length); } } }); } if (dropZone && dropOverlay) { ["dragenter", "dragover", "dragleave", "drop"].forEach(eventName => { dropZone.addEventListener(eventName, (e) => { e.preventDefault(); e.stopPropagation(); }, false); }); ["dragenter", "dragover"].forEach(eventName => { dropZone.addEventListener(eventName, () => { dropOverlay.classList.remove("hidden"); dropOverlay.classList.add("flex"); }, false); }); ["dragleave", "drop"].forEach(eventName => { dropZone.addEventListener(eventName, (e) => { if (eventName === "drop" || e.target === dropZone || !dropZone.contains(e.relatedTarget)) { dropOverlay.classList.add("hidden"); dropOverlay.classList.remove("flex"); } }, false); }); dropZone.addEventListener("drop", (e) => { const dt = e.dataTransfer; const files = dt.files; if (files && files.length > 0) { const file = files[0]; handleFileSelect({ target: { files: [file] } }); const fileInput = document.getElementById("file-input"); if (fileInput) { const dataTransfer = new DataTransfer(); dataTransfer.items.add(file); fileInput.files = dataTransfer.files; } } }, false); } });