/
cppv
/
hackathon13
Обзор
Документация
Войти
/
cppv
/
hackathon13
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
static/js/script.js
139 строк
5 KB
cppv
hackathon13
25 май 2025, 11:54
25 май 2025, 11:54
8af8c2d
Код
Авторство
О чём код?
// тут скрипт для чата document.addEventListener('DOMContentLoaded', function() { const chatMessages = document.getElementById('chat-messages'); const userInput = document.getElementById('user-input'); const sendButton = document.getElementById('send-button'); const clearButton = document.getElementById('clear-button'); const chatContainer = document.getElementById('chat-container'); const buttonText = sendButton.querySelector('.button-text'); const loadingIndicator = sendButton.querySelector('.loading'); // добавляем сообщение в чат function addMessage(content, isUser = false) { const messageDiv = document.createElement('div'); messageDiv.className = isUser ? 'user-message' : 'assistant-message'; // форматим текст const formattedContent = formatMessage(content); messageDiv.innerHTML = formattedContent; // время сообщения const timeDiv = document.createElement('div'); timeDiv.className = 'message-time'; const now = new Date(); timeDiv.textContent = now.toLocaleTimeString(); messageDiv.appendChild(timeDiv); chatMessages.appendChild(messageDiv); // прокрутка вниз chatContainer.scrollTo({ top: chatContainer.scrollHeight, behavior: 'smooth' }); } // форматирование сообщений чтоб красиво было function formatMessage(content) { // код в тройных кавычках content = content.replace(/```([\s\S]*?)```/g, function(match, code) { return `<pre><code>${escapeHtml(code.trim())}</code></pre>`; }); // код в одинарных кавычках content = content.replace(/`([^`]+)`/g, '<code>$1</code>'); // жирный текст content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>'); // курсив content = content.replace(/\*(.*?)\*/g, '<em>$1</em>'); // переносы строк content = content.replace(/\n/g, '<br>'); return content; } // чтоб html теги не ломали верстку function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } // отправка вопроса на сервер async function sendQuestion() { const question = userInput.value.trim(); if (question === '') return; // показываем вопрос в чате addMessage(question, true); // чистим поле userInput.value = ''; // блокируем кнопки пока ждем ответ userInput.disabled = true; buttonText.style.display = 'none'; loadingIndicator.style.display = 'inline-block'; sendButton.disabled = true; try { // запрос на сервер const response = await fetch('/ask', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ question: question }), }); const data = await response.json(); // показываем ответ addMessage(data.response); } catch (error) { // если что-то пошло не так addMessage('Упс, что-то пошло не так. Попробуй еще раз!'); console.error('Error:', error); } finally { // включаем обратно кнопки userInput.disabled = false; buttonText.style.display = 'inline'; loadingIndicator.style.display = 'none'; sendButton.disabled = false; userInput.focus(); } } // кнопка отправить sendButton.addEventListener('click', sendQuestion); // энтер тоже отправляет userInput.addEventListener('keypress', function(event) { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); sendQuestion(); } }); // очистка чата clearButton.addEventListener('click', async function() { try { await fetch('/clear_history', { method: 'POST', }); chatMessages.innerHTML = ''; userInput.focus(); } catch (error) { console.error('Error clearing history:', error); } }); // фокус на поле ввода userInput.focus(); });