empty the pong to minimum set up

This commit is contained in:
NigeParis 2025-12-13 08:57:38 +01:00 committed by Maix0
parent 7c20066b63
commit 5354c01bad
15 changed files with 156 additions and 687 deletions

View file

@ -1,13 +0,0 @@
import { Socket } from 'socket.io-client';
import type { ClientProfil } from './types_front';
import { blockUser } from './blockUser';
export function actionBtnPopUpBlock(block: ClientProfil, senderSocket: Socket) {
setTimeout(() => {
const blockUserBtn = document.querySelector("#popup-b-block");
blockUserBtn?.addEventListener("click", () => {
block.text = '';
blockUser(block, senderSocket);
});
}, 0)
};

View file

@ -1,13 +0,0 @@
import { clearChatWindow } from './clearChatWindow';
import { Socket } from 'socket.io-client';
import type { ClientProfil } from './types_front';
export function actionBtnPopUpClear(profil: ClientProfil, senderSocket: Socket) {
setTimeout(() => {
const clearTextBtn = document.querySelector("#popup-b-clear");
clearTextBtn?.addEventListener("click", () => {
clearChatWindow(senderSocket);
});
}, 0)
};

View file

@ -1,18 +0,0 @@
import { color } from './pong';
/**
* function adds a message to the frontend chatWindow
* @param text
* @returns
*/
export function addMessage(text: string) {
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
if (!chatWindow) return;
const messageElement = document.createElement("div-test");
messageElement.textContent = text;
chatWindow.appendChild(messageElement);
chatWindow.scrollTop = chatWindow.scrollHeight;
console.log(`%c DEBUG LOG: Added new message:%c ${text}`, color.red, color.reset);
return ;
};

View file

@ -0,0 +1,19 @@
import { color } from './pong';
/**
* function adds a message to the frontend pongMessage
* ATTENTION send inner HTML ******
* @param text
* @returns
*/
export function addPongMessage(text: string) {
const pongMessage = document.getElementById("system-box") as HTMLDivElement;
if (!pongMessage) return;
const messageElement = document.createElement("div-test");
messageElement.innerHTML = text;
pongMessage.appendChild(messageElement);
pongMessage.scrollTop = pongMessage.scrollHeight;
console.log(`%c DEBUG LOG: Added PONG new message:%c ${text}`, color.red, color.reset);
return ;
};

View file

@ -1,11 +0,0 @@
import { Socket } from 'socket.io-client';
import type { ClientProfil } from './types_front';
import { getUser } from "@app/auth";
export function blockUser(profil: ClientProfil, senderSocket: Socket) {
profil.SenderName = getUser()?.name ?? '';
if (profil.SenderName === profil.user) return;
// addMessage(`${profil.Sendertext}: ${profil.user}⛔`)
senderSocket.emit('blockUser', JSON.stringify(profil));
};

View file

@ -1,4 +1,4 @@
import { addMessage } from "./addMessage";
import { addPongMessage } from "./addPongMessage";
import { Socket } from 'socket.io-client';
import { getUser } from "@app/auth";
@ -10,7 +10,7 @@ import { getUser } from "@app/auth";
*/
export function broadcastMsg (socket: Socket, msgCommand: string[]): void {
let msgText = msgCommand[1] ?? "";
addMessage(msgText);
addPongMessage(msgText);
const user = getUser();
if (user && socket?.connected) {
const message = {

View file

@ -1,13 +0,0 @@
import io, { Socket } from 'socket.io-client';
/**
* function clears all messages in the chat window
* @param senderSocket
* @returns
*/
export function clearChatWindow(senderSocket: Socket) {
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
if (!chatWindow) return;
chatWindow.innerHTML = "";
// senderSocket.emit('nextGame');
}

View file

@ -1,24 +0,0 @@
import { Socket } from 'socket.io-client';
/**
* getProfil of a user
* @param socket
* @param user
* @returns
*/
export function getProfil(socket: Socket, user: string) {
if (!socket.connected) return;
const profil = {
command: '@profil',
destination: 'profilMessage',
type: "chat",
user: user,
token: document.cookie ?? "",
text: user,
timestamp: Date.now(),
SenderWindowID: socket.id,
};
// addMessage(JSON.stringify(profil));
socket.emit('profilMessage', JSON.stringify(profil));
}

View file

@ -1,45 +0,0 @@
import { getUser } from "@app/auth";
import { Socket } from 'socket.io-client';
import { getProfil } from './getProfil';
/**
* function adds a user to the ping Buddies window\
* it also acts as click or double click\
* activates two possible actions:\
* click => private Mag\
* dbl click => get Profil of the name\
* collected in the clipBoard
* @param socket
* @param buddies
* @param listBuddies
* @returns
*/
export async function listBuddies(socket: Socket, buddies: HTMLDivElement, listBuddies: string) {
if (!buddies) return;
const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement;
const buddiesElement = document.createElement("div-buddies-list");
buddiesElement.textContent = listBuddies + '\n';
const user = getUser()?.name ?? "";
buddies.appendChild(buddiesElement);
buddies.scrollTop = buddies.scrollHeight;
console.log(`Added buddies: ${listBuddies}`);
buddiesElement.style.cursor = "pointer";
buddiesElement.addEventListener("click", () => {
navigator.clipboard.writeText(listBuddies);
if (listBuddies !== user && user !== "") {
sendtextbox.value = `@${listBuddies}: `;
console.log("Copied to clipboard:", listBuddies);
sendtextbox.focus();
}
});
buddiesElement.addEventListener("dblclick", () => {
console.log("Open profile:", listBuddies);
getProfil(socket, listBuddies);
sendtextbox.value = "";
});
}

View file

@ -1,24 +0,0 @@
import type { ClientProfil } from './types_front';
export async function openProfilePopup(profil: ClientProfil) {
const modalname = document.getElementById("modal-name") ?? null;
if (modalname)
modalname.innerHTML =
`
<div class="profile-info">
<div-profil-name id="profilName"> Profil of ${profil.user} </div>
<div-login-name id="loginName"> Login Name: '${profil.loginName ?? 'Guest'}' </div>
</br>
<div-login-name id="loginName"> Login ID: '${profil.userID ?? ''}' </div>
</br>
<button id="popup-b-clear" class="btn-style popup-b-clear">Clear Text</button>
<button id="popup-b-invite" class="btn-style popup-b-invite">U Game ?</button>
<button id="popup-b-block" class="btn-style popup-b-block">Block User</button>
<div id="profile-about">About: '${profil.text}' </div>
</div>
`;
const profilList = document.getElementById("profile-modal") ?? null;
if (profilList)
profilList.classList.remove("hidden");
// The popup now exists → attach the event
}

View file

@ -1,51 +1,17 @@
<div class="displaybox">
<div id="mainbox" class="mainboxDisplay">
<button id="b-whoami" class="btn-style absolute top-4 left-6">Who am i</button>
<button id="b-nextGame" class="btn-style absolute top-4 left-34">nextGame</button>
<h1 class="text-3xl font-bold text-gray-800">
ChatterBox<span id="t-username"></span>
Pong Box<span id="t-username"></span>
</h1><br>
<button id="b-clear" class="btn-style absolute top-4 right-6">Clear Text</button>
<button id="b-quit" class="btn-style absolute top-14 right-6">Quit Chat</button>
<button id="b-help" class="btn-style absolute top-14 left-6">Connected</button>
<!-- Horizontal Message Box -->
<div id="system-box" class="system-info">System: connecting ... </div>
<div class="flex justify-center mt-2">
<!-- Center wrapper for chat + vertical box -->
<!-- Groupe Chat + vertical box container -->
<div id = "g-boxes" class="flex gap-2">
<!-- Text Chat box panel + send -->
<div id="g-textBoxes" class="flex flex-col">
<div id="t-chatbox" class="chatbox-style"></div>
<div id="t-input-send" class="flex gap-1 mt-2">
<input id="t-chat-window" placeholder="Type your message..." class="chat-window-style" />
<button id="b-send" class="send-btn-style">Send</button>
</div>
</div>
<!-- Vertical Ping Buddies box panel-->
<div id="ping-box" class="ping-box">
<p id="ping-title" class="ping-title">Ping Buddies</p>
<div id="ping-list" class="flex-1 overflow-y-auto">
<div id = "div-buddies">
</div>
</div>
<div id="profile-modal" class="profilPopup hidden">
<div class="popUpBox">
<p class="" id="modal-name"></p>
<button id="close-modal" class="btn-style absolute bottom-32 right-12">Close</button>
</div>
</div>
<div id="game-modal" class="gamePopup hidden">
<div class="popUpMessage">
<div id="game-info">
<p class="modal-messages " id="modal-message"></p>
</div>
<button id="close-modal-message" class="btn-style absolute bottom-67 right-12">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View file

@ -4,16 +4,9 @@ import authHtml from './pong.html?raw';
import client from '@app/api'
import { getUser, updateUser } from "@app/auth";
import io, { Socket } from 'socket.io-client';
import { listBuddies } from './listBuddies';
import { getProfil } from './getProfil';
import { addMessage } from './addMessage';
import { broadcastMsg } from './broadcastMsg';
import { addPongMessage } from './addPongMessage';
import { isLoggedIn } from './isLoggedIn';
import type { ClientMessage, ClientProfil } from './types_front';
import { openProfilePopup } from './openProfilePopup';
import { actionBtnPopUpClear } from './actionBtnPopUpClear';
import { actionBtnPopUpBlock } from './actionBtnPopUpBlock';
import { windowStateHidden } from './windowStateHidden';
export const color = {
red: 'color: red;',
@ -48,128 +41,6 @@ export function getSocket(): Socket {
return __socket;
};
function inviteToPlayPong(profil: ClientProfil, senderSocket: Socket) {
profil.SenderName = getUser()?.name ?? '';
if (profil.SenderName === profil.user) return;
addMessage(`You invited to play: ${profil.user}🏓`)
senderSocket.emit('inviteGame', JSON.stringify(profil));
};
function actionBtnPopUpInvite(invite: ClientProfil, senderSocket: Socket) {
setTimeout(() => {
const InvitePongBtn = document.querySelector("#popup-b-invite");
InvitePongBtn?.addEventListener("click", () => {
inviteToPlayPong(invite, senderSocket);
});
}, 0)
};
// async function windowStateHidden() {
// const socketId = __socket || undefined;
// // let oldName = localStorage.getItem("oldName") ?? undefined;
// let oldName: string;
// if (socketId === undefined) return;
// let userName = await updateUser();
// oldName = userName?.name ?? "";
// if (oldName === "") return;
// localStorage.setItem('oldName', oldName);
// socketId.emit('client_left', {
// user: userName?.name,
// why: 'tab window hidden - socket not dead',
// });
// return;
// };
async function windowStateVisable() {
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const socketId = __socket || undefined;
let oldName = localStorage.getItem("oldName") || undefined;
console.log("%c WINDOW VISIBLE - oldName :'" + oldName + "'", color.green);
if (socketId === undefined || oldName === undefined) {console.log("%SOCKET ID", color.red); return;}
let user = await updateUser();
if(user === null) return;
console.log("%cUserName :'" + user?.name + "'", color.green);
socketId.emit('client_entered', {
userName: oldName,
user: user?.name,
});
buddies.innerHTML = '';
buddies.textContent = '';
//connected(socketId);
setTitle('Chat Page');
return;
};
function parseCmdMsg(msgText: string): string[] | undefined {
if (!msgText?.trim()) return;
msgText = msgText.trim();
const command: string[] = ['', ''];
if (!msgText.startsWith('@')) {
command[0] = '@msg';
command[1] = msgText;
return command;
}
const noArgCommands = ['@quit', '@who', '@cls'];
if (noArgCommands.includes(msgText)) {
command[0] = msgText;
command[1] = '';
return command;
}
const ArgCommands = ['@profil', '@block'];
const userName = msgText.indexOf(" ");
const cmd2 = msgText.slice(0, userName).trim() ?? "";
const user = msgText.slice(userName + 1).trim();
if (ArgCommands.includes(cmd2)) {
command[0] = cmd2;
command[1] = user;
return command;
}
const colonIndex = msgText.indexOf(":");
if (colonIndex === -1) {
command[0] = msgText;
command[1] = '';
return command;
}
const cmd = msgText.slice(0, colonIndex).trim();
const rest = msgText.slice(colonIndex + 1).trim();
command[0] = cmd;
command[1] = rest;
return command;
}
// async function listBuddies(socket: Socket, buddies: HTMLDivElement, listBuddies: string) {
// if (!buddies) return;
// const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement;
// const buddiesElement = document.createElement("div-buddies-list");
// buddiesElement.textContent = listBuddies + '\n';
// const user = getUser()?.name ?? "";
// buddies.appendChild(buddiesElement);
// buddies.scrollTop = buddies.scrollHeight;
// console.log(`Added buddies: ${listBuddies}`);
// buddiesElement.style.cursor = "pointer";
// buddiesElement.addEventListener("click", () => {
// navigator.clipboard.writeText(listBuddies);
// if (listBuddies !== user && user !== "") {
// sendtextbox.value = `@${listBuddies}: `;
// console.log("Copied to clipboard:", listBuddies);
// sendtextbox.focus();
// }
// });
// buddiesElement.addEventListener("dblclick", () => {
// console.log("Open profile:", listBuddies);
// getProfil(socket, listBuddies);
// sendtextbox.value = "";
// });
// }
function waitSocketConnected(socket: Socket): Promise<void> {
return new Promise(resolve => {
@ -178,69 +49,6 @@ function waitSocketConnected(socket: Socket): Promise<void> {
});
};
function quitChat (socket: Socket) {
try {
const systemWindow = document.getElementById('system-box') as HTMLDivElement;
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
if (socket) {
logout(socket);
setTitle('Pong Page');
systemWindow.innerHTML = "";
chatWindow.textContent = "";
connected(socket);
} else {
getSocket();
}
} catch (e) {
console.error("Quit Chat error:", e);
showError('Failed to Quit Chat: Unknown error');
}
};
// const bconnected = document.getElementById('b-help') as HTMLButtonElement;
// if (bconnected) {
// bconnected.click();
// }
function logout(socket: Socket) {
socket.emit("logout"); // notify server
socket.disconnect(); // actually close the socket
localStorage.clear();
if (__socket !== undefined)
__socket.close();
// window.location.href = "/login";
};
async function connected(socket: Socket): Promise<void> {
try {
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const loggedIn = isLoggedIn();
if (!loggedIn) throw('Not Logged in');
console.log('%cloggedIn:',color.blue, loggedIn?.name);
let oldUser = localStorage.getItem("oldName") ?? "";
console.log('%coldUser:',color.yellow, oldUser);
if (loggedIn?.name === undefined) {console.log('');return ;}
setTimeout(() => {
oldUser = loggedIn.name ?? "";
}, 0);
// const res = await client.guestLogin();
let user = await updateUser();
console.log('%cUser?name:',color.yellow, user?.name);
localStorage.setItem("oldName", oldUser);
buddies.textContent = "";
socket.emit('list', {
oldUser: oldUser,
user: user?.name,
});
} catch (e) {
console.error("Login error:", e);
showError('Failed to login: Unknown error');
}
};
async function whoami(socket: Socket) {
try {
@ -272,79 +80,24 @@ async function whoami(socket: Socket) {
}
};
// async function openProfilePopup(profil: ClientProfil) {
// const modalname = document.getElementById("modal-name") ?? null;
// if (modalname)
// modalname.innerHTML = `
// <div class="profile-info">
// <div-profil-name id="profilName"> Profil of ${profil.user} </div>
// <div-login-name id="loginName"> Login Name: '${profil.loginName ?? 'Guest'}' </div>
// </br>
// <div-login-name id="loginName"> Login ID: '${profil.userID ?? ''}' </div>
// </br>
// <button id="popup-b-clear" class="btn-style popup-b-clear">Clear Text</button>
// <button id="popup-b-invite" class="btn-style popup-b-invite">U Game ?</button>
// <button id="popup-b-block" class="btn-style popup-b-block">Block User</button>
// <div id="profile-about">About: '${profil.text}' </div>
// </div>
// `;
// const profilList = document.getElementById("profile-modal") ?? null;
// if (profilList)
// profilList.classList.remove("hidden");
// // The popup now exists → attach the event
// }
let count = 0;
function incrementCounter(): number {
count += 1;
return count;
}
async function openMessagePopup(message: string) {
const modalmessage = document.getElementById("modal-message") ?? null;
if(!message) return
const obj:any = JSON.parse(message);
if (modalmessage) {
const messageElement = document.createElement("div");
messageElement.innerHTML = `
<div class="profile-info">
<div id="profile-about">Next Game Message ${incrementCounter()}: ${obj.link}</div>
</div>`;
modalmessage.appendChild(messageElement);
modalmessage.scrollTop = modalmessage.scrollHeight;
}
const gameMessage = document.getElementById("game-modal") ?? null;
if (gameMessage)
gameMessage.classList.remove("hidden");
// The popup now exists → attach the event
}
function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn {
let socket = getSocket();
// Listen for the 'connect' event
socket.on("connect", async () => {
/**
* on connection plays this part
*/
socket.on("connect", async () => {
const systemWindow = document.getElementById('system-box') as HTMLDivElement;
await waitSocketConnected(socket);
console.log("I AM Connected to the server:", socket.id);
const user = getUser()?.name;
// Ensure we have a user AND socket is connected
if (!user || !socket.connected) return;
const message = {
command: "",
destination: 'system-info',
type: "chat",
user,
user: getUser()?.name,
token: document.cookie ?? "",
text: " has Just ARRIVED in the chat",
timestamp: Date.now(),
@ -352,260 +105,63 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
};
socket.emit('message', JSON.stringify(message));
const messageElement = document.createElement("div");
messageElement.textContent = `${user}: is connected au server`;
messageElement.textContent = `${message.user}: is connected au server`;
systemWindow.appendChild(messageElement);
systemWindow.scrollTop = systemWindow.scrollHeight;
});
// Listen for messages from the server "MsgObjectServer"
/**
* sockets different listeners
* transport different data formats
*/
socket.on("MsgObjectServer", (data: { message: ClientMessage}) => {
// Display the message in the chat window
const systemWindow = document.getElementById('system-box') as HTMLDivElement;
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
const bconnected = document.getElementById('b-help') as HTMLButtonElement;
if (bconnected) {
connected(socket);
}
if (chatWindow && data.message.destination === "") {
const messageElement = document.createElement("div");
messageElement.textContent = `${data.message.user}: ${data.message.text}`;
chatWindow.appendChild(messageElement);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
if (chatWindow && data.message.destination === "privateMsg") {
const messageElement = document.createElement("div-private");
messageElement.textContent = `🔒${data.message.user}: ${data.message.text}`;
chatWindow.appendChild(messageElement);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
const MAX_SYSTEM_MESSAGES = 10;
if (systemWindow && data.message.destination === "system-info") {
const messageElement = document.createElement("div");
messageElement.textContent = `${data.message.user}: ${data.message.text}`;
systemWindow.appendChild(messageElement);
// keep only last 10
while (systemWindow.children.length > MAX_SYSTEM_MESSAGES) {
systemWindow.removeChild(systemWindow.firstChild!);
}
systemWindow.scrollTop = systemWindow.scrollHeight;
}
console.log("Getuser():", getUser());
console.log('%csocket.on MsgObjectServer', color.yellow );
addPongMessage(`</br>${data.message.text}`);
});
socket.on('profilMessage', (profil: ClientProfil) => {
openProfilePopup(profil);
actionBtnPopUpClear(profil, socket);
actionBtnPopUpInvite(profil, socket);
actionBtnPopUpBlock(profil, socket);
console.log('%csocket.on profilMessage', color.yellow );
});
socket.on('inviteGame', (invite: ClientProfil) => {
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
const messageElement = document.createElement("div");
messageElement.innerHTML =`🏓${invite.SenderName}: ${invite.innerHtml}`;
chatWindow.appendChild(messageElement);
chatWindow.scrollTop = chatWindow.scrollHeight;
console.log('%csocket.on inviteGame', color.yellow );
});
socket.on('blockUser', (blocked: ClientProfil) => {
let icon = '⛔';
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
const messageElement = document.createElement("div");
if (`${blocked.text}` === '\'I have un-blocked you\'' ) { icon = '💚'};
messageElement.innerText =`${icon}${blocked.SenderName}: ${blocked.text}`;
chatWindow.appendChild(messageElement);
chatWindow.scrollTop = chatWindow.scrollHeight;
console.log('%csocket.on blockUser', color.yellow );
});
socket.on('logout', () => {
quitChat(socket);
console.log('%csocket.on logout', color.yellow );
});
socket.on('privMessageCopy', (message) => {
addMessage(message);
console.log('%csocket.on privMessageCopy', color.yellow );
})
//receives broadcast of the next GAME
socket.on('nextGame', (message: string) => {
openMessagePopup(message);
// addMessage(message);
console.log('%csocket.on nextGame', color.yellow );
})
let toggle = false
window.addEventListener("focus", async () => {
//nst bwhoami = document.getElementById('b-whoami') as HTMLButtonElement;
setTimeout(() => {
connected(socket);
}, 0);
if (window.location.pathname === '/app/chat') {
console.log('%cWindow is focused on /chat:' + socket.id, color.green);
if (socket.id) {
await windowStateVisable();
}
toggle = true;
}
});
window.addEventListener("blur", () => {
console.log('%cWindow is not focused on /chat', color.red);
if (socket.id)
windowStateHidden();
toggle = false;
});
// setInterval(async () => {
// //connected(socket);
// },10000); // every 10 sec
socket.on('listBud', async (myBuddies: string) => {
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
console.log('%cList buddies connected ',color.yellow, myBuddies);
listBuddies(socket, buddies, myBuddies);
console.log('%csocket.on listBud', color.yellow );
addPongMessage('socket.once \'listBud\' called')
});
socket.once('welcome', (data) => {
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const chatWindow = document.getElementById('t-chatbox') as HTMLDivElement;
chatWindow.innerHTML = '';
buddies.textContent = '';
buddies.innerHTML = '';
connected(socket);
addMessage (`${data.msg} ` + getUser()?.name);
console.log('%cWelcome PONG PAGE', color.yellow );
addPongMessage('socket.once \'Welcome\' called')
});
setTitle('Chat Page');
// Listen for the 'connect' event
setTitle('Pong Page');
return {
html: authHtml, postInsert: async (app) => {
const sendButton = document.getElementById('b-send') as HTMLButtonElement;
const chatWindow = document.getElementById('t-chatbox') as HTMLDivElement;
const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement;
const clearText = document.getElementById('b-clear') as HTMLButtonElement;
const bwhoami = document.getElementById('b-whoami') as HTMLButtonElement;
const bconnected = document.getElementById('b-help') as HTMLButtonElement;
const username = document.getElementById('username') as HTMLDivElement;
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const bquit = document.getElementById('b-quit') as HTMLDivElement;
const systemWindow = document.getElementById('system-box') as HTMLDivElement;
const bnextGame = document.getElementById('b-nextGame') as HTMLDivElement;
chatWindow.textContent = '';
chatWindow.innerHTML = '';
buddies.textContent = '';
buddies.innerHTML = '';
const buttonPro = document.getElementById("close-modal") ?? null;
if (buttonPro)
buttonPro.addEventListener("click", () => {
const profilList = document.getElementById("profile-modal") ?? null;
if (profilList) profilList.classList.add("hidden");
});
const buttonMessage = document.getElementById("close-modal-message") ?? null;
if (buttonMessage)
buttonMessage.addEventListener("click", () => {
const gameMessage = document.getElementById("game-modal") ?? null;
if (gameMessage) gameMessage.classList.add("hidden");
const modalmessage = document.getElementById("modal-message") ?? null;
if (modalmessage) {modalmessage.innerHTML = "";}
});
// Send button
sendButton?.addEventListener("click", () => {
if (sendtextbox && sendtextbox.value.trim()) {
let msgText: string = sendtextbox.value.trim();
const msgCommand = parseCmdMsg(msgText) ?? "";
connected(socket);
if (msgCommand !== "") {
switch (msgCommand[0]) {
case '@msg':
broadcastMsg(socket, msgCommand);
break;
case '@who':
whoami(socket);
break;
case '@profil':
getProfil(socket, msgCommand[1]);
break;
case '@cls':
chatWindow.innerHTML = '';
break;
case '@quit':
quitChat(socket);
break;
default:
const user = getUser()?.name;
// Ensure we have a user AND socket is connected
if (!user || !socket.connected) return;
const message = {
command: msgCommand[0],
destination: '',
type: "chat",
user: user,
token: document.cookie ?? "",
text: msgCommand[1],
timestamp: Date.now(),
SenderWindowID: socket.id,
};
//socket.emit('MsgObjectServer', message);
socket.emit('privMessage', JSON.stringify(message));
// addMessage(JSON.stringify(message));
break;
}
// Clear the input in all cases
sendtextbox.value = "";
}
}
});
// Clear Text button
clearText?.addEventListener("click", () => {
if (chatWindow) {
chatWindow.innerHTML = '';
}
//clearChatWindow(socket); //DEV testing broadcastGames
});
// Dev Game message button
bnextGame?.addEventListener("click", () => {
if (chatWindow) {
socket.emit('nextGame');
}
});
bquit?.addEventListener('click', () => {
quitChat(socket);
});
// Enter key to send message
sendtextbox!.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
sendButton?.click();
}
});
// Whoami button to display user name addMessage(msgCommand[0]);
bwhoami?.addEventListener('click', async () => {
whoami(socket);
});

View file

@ -1,18 +0,0 @@
import { __socket } from './pong';
import { updateUser } from "@app/auth";
export async function windowStateHidden() {
const socketId = __socket || undefined;
// let oldName = localStorage.getItem("oldName") ?? undefined;
let oldName: string;
if (socketId === undefined) return;
let userName = await updateUser();
oldName = userName?.name ?? "";
if (oldName === "") return;
localStorage.setItem('oldName', oldName);
socketId.emit('client_left', {
user: userName?.name,
why: 'tab window hidden - socket not dead',
});
return;
};

View file

@ -0,0 +1,2 @@
import './pong.css';

105
frontend/src/pong/pong.css Normal file
View file

@ -0,0 +1,105 @@
@import "tailwindcss";
@font-face {
font-family: "Nimbus Mono L";
src: url("/fonts/NimbusMonoL.woff2") format("woff2");
}
@tailwind utilities;
.btn-style {
@apply
w-[100px]
h-[32px]
border-1
border-gray-500
rounded-3xl
bg-gray-500
text-white
cursor-pointer
shadow-[0_2px_0_0_black]
transition-all
hover:bg-blue-200
active:bg-gray-400
active:translate-y-[1px]
active:shadow-[0_2px_0_0_black];
}
.chatbox-style {
@apply
w-[650px]
h-[300px] /* increase height if needed */
p-[8px]
border-1
border-black
shadow-2xl
text-left
text-gray-700
bg-white
rounded-3xl
overflow-y-auto
whitespace-pre-line
flex
flex-col
mx-auto;
}
.system-info {
@apply
h-[40px]
bg-gray-200
text-gray-700
p-3
rounded-3xl
mb-2 border
border-gray-200
text-center
shadow
overflow-y-auto
justify-end /* 👈 forces text to bottom */
relative; /* needed for overlay */
}
.displaybox {
@apply
fixed
inset-0
flex
items-center
justify-center
bg-[#43536b];
}
.mainboxDisplay {
@apply
fixed
top-1/2
left-1/2
-translate-x-1/2
-translate-y-1/2
bg-gray-200 w-[850px]
p-6 rounded-xl
shadow-2xl
text-center z-50;
}
.mainboxDisplay button {
@apply
cursor-pointer
}
.title {
@apply
text-6xl
font-bold
text-gray-800
}
p {
@apply
text-black
}