const chatwin = document.getElementById("chatwin");
const anchor = document.getElementById("anchor");
// Массив ключевых слов для выделения (без учета регистра)
const specialKeywords = ['sergshemet', 'sergeyshemet', 'sshemet', 'сергей', 'серёга', 'админ'];
// Функция для проверки содержит ли сообщение ключевые слова
function containsSpecialKeywords(text) {
const lowerText = text.toLowerCase();
return specialKeywords.some(keyword => lowerText.includes(keyword.toLowerCase()));
}
// Создание новой строки чата из JSON данных
function createNewLine(json) {
// Сортируем сообщения по дате (самые старые первыми)
json.sort((a, b) => new Date(a.date) - new Date(b.date));
json.forEach(element => {
// Проверяем, существует ли уже элемент с таким ID
let existingMsg = document.getElementById(element["id"]);
if (existingMsg) {
// Обновляем текст существующего сообщения
existingMsg.innerHTML = element["msg"];
// Проверяем на ключевые слова для подсветки
if (containsSpecialKeywords(element["msg"])) {
existingMsg.classList.add("highlight-message");
} else {
existingMsg.classList.remove("highlight-message");
}
return;
}
// Создаем блок имени
const nameBlock = document.createElement("div");
nameBlock.className = "nameline " + element["type"];
// Для донатов добавляем сумму
if (element["type"] == "donate") {
nameBlock.innerHTML = element["sendr"] + '
' + element['amount'] + "
"; } else { nameBlock.innerHTML = element["sendr"]; } // Создаем блок сообщения const msgBlock = document.createElement("div"); msgBlock.className = "msgline"; msgBlock.innerHTML = element["msg"]; msgBlock.id = element["id"]; // Добавляем подсветку если есть ключевые слова if (containsSpecialKeywords(element["msg"])) { msgBlock.classList.add("highlight-message"); } // Стиль для донатов if (element["type"] == "donate") { msgBlock.style.backgroundColor = "#0000FF20"; } // Создаем строку чата const row = document.createElement("div"); row.className = "chatRow"; row.setAttribute("name", element["id"]); row.appendChild(nameBlock); row.appendChild(msgBlock); // ВСЕГДА вставляем новое сообщение перед якорем (внизу) chatwin.insertBefore(row, anchor); // Прокручиваем сразу к новому сообщению scrollToBottom(); }); // Ограничиваем количество сообщений (200) removeOldMessages(200); } // Функция прокрутки в самый низ function scrollToBottom() { // Используем setTimeout чтобы прокрутка происходила после добавления DOM элемента setTimeout(() => { window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }); }, 10); } // Удаление старых сообщений function removeOldMessages(maxMessages = 200) { const messageRows = document.getElementsByClassName("chatRow"); const rowsToRemove = messageRows.length - maxMessages; if (rowsToRemove > 0) { for (let i = 0; i < rowsToRemove; i++) { if (messageRows[0]) { messageRows[0].remove(); } } } } // Запрос новых сообщений с сервера function requestNewLines() { fetch("http://localhost:8008/") .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { createNewLine(data); }) .catch(error => { console.error('Error fetching chat messages:', error); // Показываем сообщение об ошибке только если его нет const errorRow = document.getElementById("error-message"); if (!errorRow) { const errorDiv = document.createElement("div"); errorDiv.id = "error-message"; errorDiv.className = "chatRow error"; errorDiv.innerHTML = '