Files
scud_ai/modules/web_api/static/js/chat/messages.js
T

213 lines
9.0 KiB
JavaScript

/**
* ===============================================================================
* FILE: modules/web_api/static/js/chat/messages.js
* ROLE: Рендеринг сообщений на базе marked.js с поддержкой marked v4-v14+.
* ===============================================================================
*/
function safeEscapeCode(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function renderMarkdownGemini(rawText) {
if (!rawText || typeof rawText !== 'string') return '';
if (typeof marked === 'undefined') {
return safeEscapeCode(rawText).replace(/\n/g, '<br>');
}
const renderer = new marked.Renderer();
// Переопределяем ТОЛЬКО блоки кода (совместимо со всеми версиями marked)
renderer.code = function(arg1, arg2) {
// Поддержка и старых версий (code, lang), и новых (token)
let code = '';
let lang = 'code';
if (typeof arg1 === 'object' && arg1 !== null) {
code = arg1.text || '';
lang = arg1.lang || 'code';
} else {
code = arg1 || '';
lang = arg2 || 'code';
}
const language = (lang || 'code').trim();
const blockId = 'code-block-' + Math.random().toString(36).substr(2, 9);
return `
<div class="my-3 rounded-xl overflow-hidden border border-slate-700/80 bg-slate-900 shadow-md font-mono text-xs text-left">
<div class="flex items-center justify-between px-3.5 py-1.5 bg-slate-800 border-b border-slate-700/70 text-slate-300">
<span class="text-[11px] font-semibold tracking-wider text-slate-400 lowercase">${safeEscapeCode(language)}</span>
<button type="button" onclick="window.copyCodeBlock('${blockId}', this)"
class="flex items-center gap-1.5 px-2 py-1 text-[11px] text-slate-300 hover:text-white bg-slate-700/60 hover:bg-slate-700 rounded-md transition cursor-pointer">
<i class="fa-regular fa-copy text-xs"></i>
<span>Копировать</span>
</button>
</div>
<div class="p-3.5 overflow-x-auto text-emerald-300 leading-relaxed font-mono whitespace-pre"><code id="${blockId}">${safeEscapeCode(code)}</code></div>
</div>
`;
};
marked.setOptions({
renderer: renderer,
gfm: true,
breaks: true
});
return marked.parse(rawText);
}
window.copyCodeBlock = function(blockId, btnElement) {
const codeEl = document.getElementById(blockId);
if (!codeEl) return;
const textToCopy = codeEl.innerText;
function showSuccessFeedback() {
const originalHtml = btnElement.innerHTML;
btnElement.innerHTML = `<i class="fa-solid fa-check text-emerald-400 text-xs"></i><span class="text-emerald-400 font-bold">Скопировано!</span>`;
btnElement.classList.add('bg-slate-800');
setTimeout(() => {
btnElement.innerHTML = originalHtml;
btnElement.classList.remove('bg-slate-800');
}, 2000);
}
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(textToCopy)
.then(showSuccessFeedback)
.catch(() => fallbackCopy(textToCopy));
} else {
fallbackCopy(textToCopy);
}
function fallbackCopy(text) {
try {
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
if (successful) {
showSuccessFeedback();
} else {
console.warn("Fallback execCommand copy failed");
}
} catch (err) {
console.error("Не удалось скопировать код в буфер:", err);
}
}
};
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">${safeEscapeCode(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">${safeEscapeCode(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('${safeEscapeCode(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">
${safeEscapeCode(b.label || b.title || b.action)}
</button>
`).join('')}
</div>
`;
}
}
const bodyContent = isHtmlBody ? text : renderMarkdownGemini(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 chat-markdown-content">${bodyContent}</div>
${payloadHtml}
${buttonsHtml}
</div>
</div>
`;
container.insertAdjacentHTML("beforeend", html);
if (window.ensureScrollSpacerAtEnd) {
window.ensureScrollSpacerAtEnd();
}
};