dok/sockets/chat.js
2026-04-10 11:17:17 +01:00

89 lines
1.9 KiB
JavaScript

const socket = io();
window._socket = socket; // Globale Referenz für arena.js und andere Module
const username =
typeof window.playerName === "object"
? window.playerName.name
: window.playerName;
socket.emit("register", username);
const chatTitle = document.getElementById("chat-title");
let channel = "global";
const chatBox = document.getElementById("chat-messages");
let history = {
global: [],
guild: [],
private: [],
};
function updateChat() {
chatBox.value = history[channel].join("\n");
chatBox.scrollTop = chatBox.scrollHeight;
}
document.querySelectorAll(".chat-channels button").forEach((btn) => {
btn.onclick = () => {
document
.querySelectorAll(".chat-channels button")
.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
channel = btn.dataset.channel;
// Titel ändern
if (channel === "global") chatTitle.innerText = "Globalchat";
if (channel === "guild") chatTitle.innerText = "Gildenchat";
if (channel === "private") chatTitle.innerText = "Privatchat";
updateChat();
};
});
document.getElementById("chat-send").onclick = () => {
const text = document.getElementById("chat-text").value;
if (!text) return;
if (text.startsWith("/w ")) {
const parts = text.split(" ");
const target = parts[1];
const message = parts.slice(2).join(" ");
socket.emit("whisper", {
to: target,
message: message,
});
} else {
socket.emit("chatMessage", {
channel: channel,
message: text,
});
}
document.getElementById("chat-text").value = "";
};
socket.on("chatMessage", (data) => {
const line = `${data.user}: ${data.message}`;
history[data.channel].push(line);
if (history[data.channel].length > 50) history[data.channel].shift();
if (data.channel === channel) updateChat();
});
socket.on("systemMessage", (data) => {
const line = "[System] " + data.message;
history[channel].push(line);
updateChat();
});