Added Global Message for Next Game - Bug Fixed on Double Displaying Ping Buddies

This commit is contained in:
NigeParis 2025-12-10 13:10:59 +01:00 committed by apetitco
parent 945419427a
commit 6643d495bd
5 changed files with 170 additions and 60 deletions

View file

@ -230,6 +230,33 @@ div-private {
right-12 right-12
} }
.popUpMessage {
@apply
bg-white
p-6 rounded-xl
shadow-xl
w-[800px]
h-[100px]
p-[10px]
border-1
border-black
}
.gamePopup {
@apply
fixed
inset-0
bg-black/50
flex
justify-center
items-center;
}
.hidden{ .hidden{
display: none; display: none;
} }

View file

@ -1,6 +1,7 @@
<div class="displaybox"> <div class="displaybox">
<div id="mainbox" class="mainboxDisplay"> <div id="mainbox" class="mainboxDisplay">
<button id="b-whoami" class="btn-style absolute top-4 left-6">Who am i</button> <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"> <h1 class="text-3xl font-bold text-gray-800">
ChatterBox<span id="t-username"></span> ChatterBox<span id="t-username"></span>
</h1><br> </h1><br>
@ -26,9 +27,6 @@
<p id="ping-title" class="ping-title">Ping Buddies</p> <p id="ping-title" class="ping-title">Ping Buddies</p>
<div id="ping-list" class="flex-1 overflow-y-auto"> <div id="ping-list" class="flex-1 overflow-y-auto">
<div id = "div-buddies"> <div id = "div-buddies">
<!-- <p>Alice</p>
<p>Bob</p>
<p>Charlie</p> -->Marks
</div> </div>
</div> </div>
<div id="profile-modal" class="profilPopup hidden"> <div id="profile-modal" class="profilPopup hidden">
@ -37,6 +35,12 @@
<button id="close-modal" class="btn-style absolute bottom-32 right-12">Close</button> <button id="close-modal" class="btn-style absolute bottom-32 right-12">Close</button>
</div> </div>
</div> </div>
<div id="game-modal" class="gamePopup hidden">
<div class="popUpMessage">
<p class="" id="modal-message"></p>
<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

@ -87,10 +87,12 @@ function addMessage(text: string) {
return ; return ;
}; };
function clearText() { function clear(senderSocket: Socket) {
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement; const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
if (!chatWindow) return; if (!chatWindow) return;
chatWindow.innerHTML = ""; chatWindow.innerHTML = "";
// senderSocket.emit('nextGame');
} }
function isLoggedIn() { function isLoggedIn() {
@ -106,11 +108,11 @@ function inviteToPlayPong(profil: ClientProfil, senderSocket: Socket) {
function actionBtnPopUpClear(profil: ClientProfil) { function actionBtnPopUpClear(profil: ClientProfil, senderSocket: Socket) {
setTimeout(() => { setTimeout(() => {
const clearTextBtn = document.querySelector("#popup-b-clear"); const clearTextBtn = document.querySelector("#popup-b-clear");
clearTextBtn?.addEventListener("click", () => { clearTextBtn?.addEventListener("click", () => {
clearText(); clear(senderSocket);
}); });
}, 0) }, 0)
}; };
@ -240,8 +242,9 @@ async function listBuddies(socket: Socket, buddies: HTMLDivElement, listBuddies:
}); });
buddiesElement.addEventListener("dblclick", () => { buddiesElement.addEventListener("dblclick", () => {
console.log("Open profile:", listBuddies); console.log("Open profile:", listBuddies);
getProfil(socket, listBuddies); getProfil(socket, listBuddies);
sendtextbox.value = "";
}); });
buddies.appendChild(buddiesElement); buddies.appendChild(buddiesElement);
@ -387,12 +390,32 @@ async function openProfilePopup(profil: ClientProfil) {
<div id="profile-about">About: '${profil.text}' </div> <div id="profile-about">About: '${profil.text}' </div>
</div> </div>
`; `;
const profilList = document.getElementById("profile-modal") ?? null; const profilList = document.getElementById("profile-modal") ?? null;
if (profilList) if (profilList)
profilList.classList.remove("hidden"); profilList.classList.remove("hidden");
// The popup now exists → attach the event // The popup now exists → attach the event
} }
async function openMessagePopup(message: string) {
const modalmessage = document.getElementById("modal-message") ?? null;
if(!message) return
const obj:any = JSON.parse(message);
if (modalmessage)
modalmessage.innerHTML = `
<div class="profile-info">
</br>
<div id="profile-about">Next Game Message: ${obj.link}</div>
</div>`;
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 { function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn {
@ -470,7 +493,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
socket.on('profilMessage', (profil: ClientProfil) => { socket.on('profilMessage', (profil: ClientProfil) => {
openProfilePopup(profil); openProfilePopup(profil);
actionBtnPopUpClear(profil); actionBtnPopUpClear(profil, socket);
actionBtnPopUpInvite(profil, socket); actionBtnPopUpInvite(profil, socket);
}); });
@ -489,37 +512,39 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
addMessage(message); addMessage(message);
}) })
type Providers = { //receives broadcast of the next GAME
name: string, socket.on('nextGame', (message) => {
display_name: string, openMessagePopup(message);
icon_url?: string, // addMessage(message);
color?: { default: string, hover: string }, })
};
let toggle = false let toggle = false
window.addEventListener("focus", () => { window.addEventListener("focus", async () => {
//nst bwhoami = document.getElementById('b-whoami') as HTMLButtonElement; //nst bwhoami = document.getElementById('b-whoami') as HTMLButtonElement;
if (window.location.pathname === '/app/chat') {
setTimeout(() => {
connected(socket); connected(socket);
console.log("%cWindow is focused on /chat:" + socket.id, color.green); }, 0);
if (window.location.pathname === '/app/chat') {
console.log('%cWindow is focused on /chat:' + socket.id, color.green);
if (socket.id) { if (socket.id) {
windowStateVisable(); await windowStateVisable();
} }
toggle = true; toggle = true;
} }
}); });
window.addEventListener("blur", () => { window.addEventListener("blur", () => {
console.log("%cWindow is not focused on /chat", color.red); console.log('%cWindow is not focused on /chat', color.red);
if (socket.id) if (socket.id)
windowStateHidden(); windowStateHidden();
toggle = false; toggle = false;
}); });
// setInterval(async () => { // setInterval(async () => {
// //connected(socket); // //connected(socket);
// },10000); // every 10 seco // },10000); // every 10 sec
socket.on('listBud', async (myBuddies: string) => { socket.on('listBud', async (myBuddies: string) => {
const buddies = document.getElementById('div-buddies') as HTMLDivElement; const buddies = document.getElementById('div-buddies') as HTMLDivElement;
console.log('List buddies connected ', myBuddies); console.log('List buddies connected ', myBuddies);
@ -552,6 +577,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
const buddies = document.getElementById('div-buddies') as HTMLDivElement; const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const bquit = document.getElementById('b-quit') as HTMLDivElement; const bquit = document.getElementById('b-quit') as HTMLDivElement;
const systemWindow = document.getElementById('system-box') as HTMLDivElement; const systemWindow = document.getElementById('system-box') as HTMLDivElement;
const bnextGame = document.getElementById('b-nextGame') as HTMLDivElement;
chatWindow.textContent = ''; chatWindow.textContent = '';
chatWindow.innerHTML = ''; chatWindow.innerHTML = '';
@ -578,6 +604,18 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
if (profilList) profilList.classList.add("hidden"); 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");
});
// Send button // Send button
sendButton?.addEventListener("click", () => { sendButton?.addEventListener("click", () => {
if (sendtextbox && sendtextbox.value.trim()) { if (sendtextbox && sendtextbox.value.trim()) {
@ -631,6 +669,14 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
if (chatWindow) { if (chatWindow) {
chatWindow.innerHTML = ''; chatWindow.innerHTML = '';
} }
clear(socket); //DEV testing broadcastGames
});
// Dev Game message button
bnextGame?.addEventListener("click", () => {
if (chatWindow) {
socket.emit('nextGame');
}
}); });
bquit?.addEventListener('click', () => { bquit?.addEventListener('click', () => {
@ -652,5 +698,4 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
} }
} }
}; };
addRoute('/chat', handleChat, { bypass_auth: true }); addRoute('/chat', handleChat, { bypass_auth: true });

View file

@ -142,3 +142,11 @@ export function typeResponse<K extends string, T extends TProperties>(
export function isNullish<T>(v: T | undefined | null): v is null | undefined { export function isNullish<T>(v: T | undefined | null): v is null | undefined {
return v === null || v === undefined; return v === null || v === undefined;
} }
/**
/* EXPERIMENTAL: how to send a starting game link to chat
**/
export async function sendGameLinkToChatService(link: string) :Promise<string> {
const payload = { link };
return JSON.stringify(payload);
}

View file

@ -7,6 +7,7 @@ import * as swagger from '@shared/swagger';
import * as utils from '@shared/utils'; import * as utils from '@shared/utils';
import { Server, Socket } from 'socket.io'; import { Server, Socket } from 'socket.io';
import type { User } from '@shared/database/mixin/user'; import type { User } from '@shared/database/mixin/user';
import { sendGameLinkToChatService } from '../../@shared/src/utils/index';
// colors for console.log // colors for console.log
export const color = { export const color = {
@ -46,7 +47,7 @@ export type ClientProfil = {
command: string, command: string,
destination: string, destination: string,
type: string, type: string,
user: string, user: string,
loginName: string, loginName: string,
userID: string, userID: string,
text: string, text: string,
@ -55,21 +56,28 @@ export type ClientProfil = {
SenderName: string, SenderName: string,
innerHtml?: string, innerHtml?: string,
}; };
/**
/* TODO find the description info for profil / or profil game link and return
**/
function createNextGame() {
return '<a href=\'https://localhost:8888/app/\' style=\'color: blue; text-decoration: underline; cursor: pointer;\'>The next Game is Starting click here to watch</a>';
};
// export type inviteGame = { function setAboutPlayer(about: string): string {
// command?: string, if (!about) {
// destination?: string, about = 'Player is good Shape - This is a default description';
// type?: string, }
// user?: string, return about;
// loginName?: string, };
// userID?: string,
// innerHtml?: string, function setGameLink(link: string): string {
// timestamp?: number, if (!link) {
// SenderWindowID?:string, link = '<a href=\'https://google.com\' style=\'color: blue; text-decoration: underline; cursor: pointer;\'>Click me</a>';
// SenderName: string }
// }; return link;
};
const clientChat = new Map<string, ClientInfo>(); const clientChat = new Map<string, ClientInfo>();
@ -118,6 +126,7 @@ declare module 'fastify' {
profilMessage: (data: ClientProfil) => void; profilMessage: (data: ClientProfil) => void;
inviteGame: (data: ClientProfil) => void; inviteGame: (data: ClientProfil) => void;
privMessageCopy: (msg: string) => void; privMessageCopy: (msg: string) => void;
nextGame: (msg: string) => void;
message: (msg: string) => void; message: (msg: string) => void;
listBud: (msg: string) => void; listBud: (msg: string) => void;
testend: (sock_id_client: string) => void; testend: (sock_id_client: string) => void;
@ -189,6 +198,28 @@ async function onReady(fastify: FastifyInstance) {
}); });
} }
async function broadcastNextGame(gameLink?: Promise<string>) {
const link = gameLink ? await gameLink : undefined;
const sockets = await fastify.io.fetchSockets();
// fastify.io.fetchSockets().then((sockets) => {
for (const socket of sockets) {
// Skip sender's own socket
const clientInfo = clientChat.get(socket.id);
if (!clientInfo?.user) {
console.log(color.yellow, `Skipping socket ${socket.id} (no user found)`);
continue;
}
// Emit structured JSON object
if (link) {
socket.emit('nextGame', link);
}
// Debug logs
// console.log(color.green, `'DEBUG LOG: Broadcast to:', ${data.command} message: ${data.text}`);
}
};
// function formatTimestamp(ms: number) { // function formatTimestamp(ms: number) {
// const d = new Date(ms); // const d = new Date(ms);
// return d.toLocaleString('fr-FR', { timeZone: 'Europe/Paris' }); // return d.toLocaleString('fr-FR', { timeZone: 'Europe/Paris' });
@ -198,21 +229,9 @@ async function onReady(fastify: FastifyInstance) {
return users.find(user => user.name === name) || null; return users.find(user => user.name === name) || null;
} }
///TODO find the description info for profil / or profil game link and return
function getAboutPlayer( ): string{
const description = 'Player is good Shape this needs to be replaced by a bd.function()';
return description;
}
function getGameLink(): string{
const link = `<a href="https://google.com" style="color: blue; text-decoration: underline; cursor: pointer;">Click me</a>`;
return link;
}
// this function returns html the profil pop up in CHAT of a user 'nickname unique' TODO .... // this function returns html the profil pop up in CHAT of a user 'nickname unique' TODO ....
async function getProfil(user: string, socket: Socket): Promise <ClientProfil> { async function getProfil(user: string, socket: Socket): Promise <ClientProfil> {
let clientProfil!: ClientProfil; let clientProfil!: ClientProfil;
const users: User[] = fastify.db.getAllUsers() ?? []; const users: User[] = fastify.db.getAllUsers() ?? [];
const allUsers: User | null = getUserByName(users, user); const allUsers: User | null = getUserByName(users, user);
@ -220,20 +239,20 @@ async function onReady(fastify: FastifyInstance) {
if (user === allUsers?.name) { if (user === allUsers?.name) {
console.log(color.yellow, `'login Name: '${allUsers.login}' user: '${user}'`); console.log(color.yellow, `'login Name: '${allUsers.login}' user: '${user}'`);
clientProfil = clientProfil =
{ {
command: 'getProfil', command: 'getProfil',
destination: 'profilMsg', destination: 'profilMsg',
type: 'chat' as const, type: 'chat' as const,
user: `${allUsers.name}`, user: `${allUsers.name}`,
loginName: `${allUsers?.login ?? 'Guest'}`, loginName: `${allUsers?.login ?? 'Guest'}`,
userID: `${allUsers?.id ?? ''}`, userID: `${allUsers?.id ?? ''}`,
text: getAboutPlayer(), text: setAboutPlayer(''),
timestamp: Date.now(), timestamp: Date.now(),
SenderWindowID: socket.id, SenderWindowID: socket.id,
SenderName: '', SenderName: '',
innerHtml: '', innerHtml: '',
}; };
} }
return clientProfil; return clientProfil;
}; };
@ -250,10 +269,10 @@ async function onReady(fastify: FastifyInstance) {
function sendInvite(innerHtml: string, data: ClientProfil) { function sendInvite(innerHtml: string, data: ClientProfil) {
fastify.io.fetchSockets().then((sockets) => { fastify.io.fetchSockets().then((sockets) => {
let targetSocket; let targetSocket;
for (const socket of sockets) { for (const socket of sockets) {
let clientInfo: string = clientChat.get(socket.id)?.user || ''; const clientInfo: string = clientChat.get(socket.id)?.user || '';
if (clientInfo === data.user) { if (clientInfo === data.user) {
console.log(color.yellow, 'FOUND:', data.user); console.log(color.yellow, 'FOUND:', data.user);
targetSocket = socket || ''; targetSocket = socket || '';
@ -261,7 +280,7 @@ async function onReady(fastify: FastifyInstance) {
} }
} }
data.innerHtml = innerHtml ?? ''; data.innerHtml = innerHtml ?? '';
if (targetSocket) { if (targetSocket) {
targetSocket.emit('inviteGame', data); targetSocket.emit('inviteGame', data);
} }
}); });
@ -333,6 +352,13 @@ async function onReady(fastify: FastifyInstance) {
console.log('testend received from client socket id:', sock_id_cl); console.log('testend received from client socket id:', sock_id_cl);
}); });
socket.on('nextGame', () => {
const link = createNextGame();
const game: Promise<string> = sendGameLinkToChatService(link);
broadcastNextGame(game);
});
socket.on('list', (object) => { socket.on('list', (object) => {
const userFromFrontend = object || null; const userFromFrontend = object || null;
@ -496,8 +522,8 @@ async function onReady(fastify: FastifyInstance) {
const clientName: string = clientChat.get(socket.id)?.user || ''; const clientName: string = clientChat.get(socket.id)?.user || '';
const profilInvite: ClientProfil = JSON.parse(data) || ''; const profilInvite: ClientProfil = JSON.parse(data) || '';
// const users: User[] = fastify.db.getAllUsers() ?? []; // const users: User[] = fastify.db.getAllUsers() ?? [];
const inviteHtml: string = `invites you to a game ` + getGameLink(); const inviteHtml: string = 'invites you to a game ' + setGameLink('');
if (clientName !== null) { if (clientName !== null) {
// const testuser: User | null = getUserByName(users, profilInvite.user ?? ''); // const testuser: User | null = getUserByName(users, profilInvite.user ?? '');
// console.log(color.yellow, 'user:', testuser?.name ?? 'Guest'); // console.log(color.yellow, 'user:', testuser?.name ?? 'Guest');