fixes
This commit is contained in:
51
script.js
51
script.js
@@ -1,28 +1,17 @@
|
||||
const chatwin = document.getElementById("chatwin");
|
||||
const anchor = document.getElementById("anchor");
|
||||
|
||||
// Массив ключевых слов для выделения (без учета регистра)
|
||||
const specialKeywords = ['sergshemet', 'sergeyshemet', 'sshemet', 'сергей', 'серёга', 'админ'];
|
||||
|
||||
// Функция для проверки содержит ли сообщение ключевые слова
|
||||
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 {
|
||||
@@ -30,62 +19,39 @@ function createNewLine(json) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Создаем блок имени
|
||||
const nameBlock = document.createElement("div");
|
||||
nameBlock.className = "nameline " + element["type"];
|
||||
|
||||
// Для донатов добавляем сумму
|
||||
if (element["type"] == "donate") {
|
||||
nameBlock.innerHTML = element["sendr"] + '<br><p style="color: red">' + element['amount'] + "</p>";
|
||||
} 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;
|
||||
@@ -98,8 +64,6 @@ function removeOldMessages(maxMessages = 200) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Запрос новых сообщений с сервера
|
||||
function requestNewLines() {
|
||||
fetch("http://localhost:8008/")
|
||||
.then(response => {
|
||||
@@ -113,33 +77,22 @@ function requestNewLines() {
|
||||
})
|
||||
.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 = '<div class="nameline hello">Ошибка</div><div class="msgline">Не удалось подключиться к серверу чата</div>';
|
||||
errorDiv.innerHTML = '<div class="nameline hello">Maya</div><div class="msgline">Тацуя, демоны отключили сервер чата!</div>';
|
||||
chatwin.insertBefore(errorDiv, anchor);
|
||||
scrollToBottom();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Инициализация чата
|
||||
function initChat() {
|
||||
// Прокручиваем сразу вниз при загрузке
|
||||
scrollToBottom();
|
||||
|
||||
// Запрашиваем сообщения сразу при загрузке
|
||||
requestNewLines();
|
||||
|
||||
// Запускаем периодический опрос
|
||||
setInterval(requestNewLines, 1000);
|
||||
}
|
||||
|
||||
// Запускаем чат когда DOM загружен
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', initChat);
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user