Chat moved up to top level now in all services frontend

This commit is contained in:
NigeParis 2026-01-10 18:09:20 +01:00 committed by Nigel
parent 814c389e38
commit b4af6e08ca
32 changed files with 687 additions and 42 deletions

306
frontend/src/chat/chat.css Normal file
View file

@ -0,0 +1,306 @@
@import "tailwindcss";
@font-face {
font-family: "DejaVu Sans Mono";
src: url("/fonts/DejaVuSansMono.woff2") format("woff2");
}
@tailwind utilities;
.recessed {
@apply
inline-block
bg-gray-100
text-gray-800
p-2
rounded-md
shadow-inner
border
border-gray-300;
}
.btn-style {
@apply
w-25
h-8
border
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-px
active:shadow-[0_2px_0_0_black];
}
.send-btn-style {
@apply
w-12.5
h-12.5
border
border-gray-500
rounded-3xl
hover:bg-blue-200
bg-red-100
text-red-700
cursor-pointer
shadow-[0_2px_0_0_black]
transition-all
active:bg-gray-400
active:translate-y-px
active:shadow-[0_2px_0_0_black];;
}
.chatbox-style {
@apply
w-162.5
h-75 /* increase height if needed */
p-2
border
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-10
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 */
}
.modal-messages {
@apply
h-20
bg-white
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 */
}
.text-info {
@apply
text-blue-800
}
.chat-window-style {
@apply
w-100
h-12.5
p-6
border
border-black
shadow-sm
flex-1
rounded-3xl
focus:bg-blue-300
hover:bg-blue-200
bg-white
text-gray-800;
}
.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-212.5
p-6 rounded-xl
shadow-2xl
text-center z-50;
}
.mainboxDisplay button {
@apply
cursor-pointer
}
.title {
@apply
text-6xl
font-bold
text-gray-800
}
.ping-box {
@apply
w-37.5
ml-2 border
border-gray-500
bg-white
rounded-2xl
p-2
shadow-md
flex flex-col
gap-1
h-87.5;
}
.ping-title {
@apply
text-sm
font-semibold
text-blue-800;
}
div-buddies-list {
@apply
text-black
whitespace-pre-wrap
cursor-pointer
hover:text-blue-500
transition-colors
duration-150;
}
p {
@apply
text-black
}
div-test {
@apply
text-red-800
text-right;
}
div-notlog {
@apply
text-red-800
text-3xl
text-center;
}
div-private {
@apply
text-blue-800;
}
.popUpBox {
@apply
bg-white
rounded-xl
shadow-xl
w-200
h-87.5
p-6
border
border-black
}
.profilPopup {
@apply
fixed
inset-0
bg-black/50
flex
justify-center
items-center;
}
.popup-b-invite {
@apply
absolute
bottom-42
right-12
}
.popup-b-block {
@apply
absolute
bottom-52
right-12
}
.popUpMessage {
@apply
bg-white
rounded-xl
shadow-xl
w-200
h-33
p-6
border
border-black
}
.gamePopup {
@apply
fixed
inset-0
bg-black/50
flex
justify-center
items-center;
}
.chat-button {
@apply
z-100
text-3xl
fixed bottom-6
right-6
w-14
h-14
rounded-full
bg-gray-600
text-white
shadow-lg
flex items-center
justify-center
hover:bg-red-700
}
.hidden{
display: none;
}

View file

@ -0,0 +1,53 @@
<div class="chat-displaybox">
<div id="chat-mainbox" class="mainboxDisplay">
<h1 class="text-3xl font-bold text-gray-800">
Chatter Box<span id="chat-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>
<!-- Horizontal Message Box -->
<div id="chat-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" />
<div id="notify">🔕</div>
<div id="noGuest">💔</div>
<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>

420
frontend/src/chat/chat.ts Normal file
View file

@ -0,0 +1,420 @@
import "./chat.css";
import io, { Socket } from "socket.io-client";
import type { blockedUnBlocked } from "./types_front";
import type {
ClientMessage,
ClientProfil,
ClientProfilPartial,
} from "./types_front";
import type { User } from "@app/auth";
import {
addRoute,
setTitle,
type RouteHandlerParams,
type RouteHandlerReturn,
} from "@app/routing";
import authHtml from "./chat.html?raw";
import { getUser } from "@app/auth";
import { listBuddies } from "./chatHelperFunctions/listBuddies";
import { getProfil } from "./chatHelperFunctions/getProfil";
import { addMessage } from "./chatHelperFunctions/addMessage";
import { broadcastMsg } from "./chatHelperFunctions/broadcastMsg";
import { openProfilePopup } from "./chatHelperFunctions/openProfilePopup";
import { actionBtnPopUpBlock } from "./chatHelperFunctions/actionBtnPopUpBlock";
import { windowStateHidden } from "./chatHelperFunctions/windowStateHidden";
import { blockUser } from "./chatHelperFunctions/blockUser";
import { parseCmdMsg } from "./chatHelperFunctions/parseCmdMsg";
import { actionBtnPopUpInvite } from "./chatHelperFunctions/actionBtnPopUpInvite";
import { waitSocketConnected } from "./chatHelperFunctions/waitSocketConnected";
import { connected } from "./chatHelperFunctions/connected";
import { quitChat } from "./chatHelperFunctions/quitChat";
import { openMessagePopup } from "./chatHelperFunctions/openMessagePopup";
import { windowStateVisable } from "./chatHelperFunctions/windowStateVisable";
import { cmdList } from "./chatHelperFunctions/cmdList";
import { showInfo } from '../toast';
const MAX_SYSTEM_MESSAGES = 10;
let inviteMsgFlag: boolean = false;
export let noGuestFlag: boolean = true;
declare module "ft_state" {
interface State {
chatSock?: Socket;
}
}
export function getSocket(): Socket {
if (window.__state.chatSock === undefined)
window.__state.chatSock = io(window.location.host, {
path: "/api/chat/socket.io/",
}) as any as Socket;
return window.__state.chatSock;
}
const chatBox = document.getElementById("chatBox")!;
chatBox.classList.add('hidden');
chatBox.innerHTML = authHtml;
let socket = getSocket();
let blockMessage: boolean;
// Listen for the 'connect' event
socket.on("connect", async () => {
const systemWindow = document.getElementById("system-box") as HTMLDivElement;
const sendtextbox = document.getElementById(
"t-chat-window"
) as HTMLButtonElement;
const noGuest = document.getElementById("noGuest") ?? null;
await waitSocketConnected(socket);
const user = getUser()?.name;
const userID = getUser()?.id;
// Ensure we have a user AND socket is connected
if (!user || !socket.connected || !noGuest) return;
const message = {
command: "",
destination: "system-info",
type: "chat",
user,
token: document.cookie ?? "",
text: " has Just ARRIVED in the chat",
timestamp: Date.now(),
SenderWindowID: socket.id,
SenderID: userID,
};
socket.emit("message", JSON.stringify(message));
const guest = getUser()?.guest;
if (guest) {
noGuest.innerText = "";
} else {
noGuest.innerText = "❤️";
}
const userProfile: ClientProfil = {
command: "@noguest",
destination: "",
type: "chat",
timestamp: Date.now(),
guestmsg: true,
};
socket.emit("guestmsg", JSON.stringify(userProfile));
const messageElement = document.createElement("div");
messageElement.textContent = `${user}: is connected au server`;
systemWindow.appendChild(messageElement);
systemWindow.scrollTop = systemWindow.scrollHeight;
});
// Listen for messages from the server "MsgObjectServer"
socket.on("MsgObjectServer", (data: { message: ClientMessage }) => {
const systemWindow = document.getElementById("system-box") as HTMLDivElement;
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
if (socket) {
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;
}
if (chatWindow && data.message.destination === "inviteMsg") {
const messageElement = document.createElement("div-private");
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
messageElement.innerHTML = `🏓${data.message.SenderUserName}: ${data.message.innerHtml}`;
chatWindow.appendChild(messageElement);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
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;
}
});
socket.on("profilMessage", (profil: ClientProfil) => {
profil.SenderID = getUser()?.id ?? "";
profil.SenderName = getUser()?.name ?? "";
openProfilePopup(profil);
socket.emit("isBlockdBtn", profil);
socket.emit("check_Block_button", profil);
actionBtnPopUpInvite(profil, socket);
actionBtnPopUpBlock(profil, socket);
});
socket.on("blockUser", (blocked: ClientProfil) => {
let icon = "⛔";
if (inviteMsgFlag) {
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;
}
});
socket.on("blockBtn", (data: blockedUnBlocked) => {
const blockUserBtn = document.querySelector("#popup-b-block");
if (blockUserBtn) {
let message = "";
if (data.userState === "block") {
(message = "un-block"), (blockMessage = true);
} else {
(message = "block"), (blockMessage = false);
}
blockUserBtn.textContent = message;
}
});
socket.on("logout", () => {
quitChat(socket);
});
socket.on("privMessageCopy", (message: string) => {
addMessage(message);
});
//receives broadcast of the next GAME
socket.on("nextGame", (message: string) => {
openMessagePopup(message);
});
let toggle = false;
window.addEventListener("focus", async () => {
setTimeout(() => {
connected(socket);
}, 16);
if (window.location.pathname === "/app/chat") {
if (socket.id) {
await windowStateVisable();
}
toggle = true;
}
});
window.addEventListener("blur", () => {
if (socket.id) windowStateHidden();
toggle = false;
});
socket.on("listBud", async (myBuddies: string[]) => {
const buddies = document.getElementById("div-buddies") as HTMLDivElement;
listBuddies(socket, buddies, myBuddies);
});
socket.once("welcome", (data) => {
const buddies = document.getElementById("div-buddies") as HTMLDivElement;
buddies.textContent = "";
buddies.innerHTML = "";
connected(socket);
addMessage(`${data.msg} ` + getUser()?.name);
});
setTitle("Chat Page");
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 buddies = document.getElementById("div-buddies") as HTMLDivElement;
const bquit = document.getElementById("b-quit") as HTMLDivElement;
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", () => {
const notify = document.getElementById("notify") ?? null;
const noGuest = document.getElementById("noGuest") ?? null;
const userId = getUser()?.id;
const userAskingToBlock = getUser()?.name;
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 "@block":
if (msgCommand[1] === "") {
break;
}
if (!userAskingToBlock) return;
if (!userId) return;
const userToBlock: ClientProfil = {
command: msgCommand[0],
destination: "",
type: "chat",
user: msgCommand[1],
userID: userId,
timestamp: Date.now(),
SenderWindowID: socket.id,
SenderName: userAskingToBlock,
};
blockUser(userToBlock, socket);
break;
case "@notify":
if (notify === null) {
break;
}
if (inviteMsgFlag === false) {
notify.innerText = "🔔";
inviteMsgFlag = true;
} else {
notify.innerText = "🔕";
inviteMsgFlag = false;
}
break;
case "@guest":
if (!userId) {
return;
}
if (!userAskingToBlock) {
return;
}
if (noGuest === null) {
break;
}
const guest = getUser()?.guest;
if (noGuestFlag === false && noGuest.innerText === "💔") {
noGuest.innerText = "❤️​";
noGuestFlag = true;
} else {
noGuest.innerText = "💔";
noGuestFlag = false;
}
if (guest) {
noGuestFlag = true;
noGuest.innerText = "";
sendtextbox.value = "";
}
const userProfile: ClientProfilPartial = {
command: "@noguest",
destination: "",
type: "chat",
user: userAskingToBlock,
userID: userId,
timestamp: Date.now(),
SenderWindowID: "",
guestmsg: noGuestFlag,
};
socket.emit("guestmsg", JSON.stringify(userProfile));
break;
case "@profile":
if (msgCommand[1] === "") {
break;
}
getProfil(socket, msgCommand[1]);
break;
case "@cls":
chatWindow.innerHTML = "";
break;
case "@help":
cmdList();
break;
case "@quit":
quitChat(socket);
break;
default:
const user: User | null = getUser();
if (!user) return;
if (!user || !socket.connected) return;
const message: ClientProfilPartial = {
command: msgCommand[0],
destination: "",
type: "chat",
user: user.name,
userID: user.id,
token: document.cookie ?? "",
text: msgCommand[1],
timestamp: Date.now(),
SenderWindowID: socket.id ?? "",
SenderID: user.id,
};
socket.emit("privMessage", JSON.stringify(message));
break;
}
// Clear the input in all cases
sendtextbox.value = "";
}
}
});
// Clear Text button
clearText?.addEventListener("click", () => {
if (chatWindow) {
chatWindow.innerHTML = "";
}
});
bquit?.addEventListener("click", () => {
showInfo('Nigel close the chat overlay please')
});
// Enter key to send message
sendtextbox.addEventListener("keydown", (event) => {
if (!sendtextbox) return;
if (event.key === "Enter") {
event.preventDefault();
sendButton?.click();
}
});
const chatButton = document.querySelector('#chatButton');
chatButton!.addEventListener("click", () => {
const overlay = document.querySelector('#overlay')!;
if (chatBox.classList.contains('hidden')) {
chatBox.classList.toggle('hidden');
overlay.classList.add('opacity-60');
} else {
chatBox.classList.toggle('hidden');
overlay.classList.remove('opacity-60');
}
});

View file

@ -0,0 +1,13 @@
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

@ -0,0 +1,19 @@
import type { ClientProfil } from "../types_front";
import { Socket } from "socket.io-client";
import { inviteToPlayPong } from "./inviteToPlayPong";
/**
* function listens for a click on the U-Game button and activates a popup function
* inviteToPlayPong
* @param invite - Clients target profil
* @param senderSocket - socket from the sender
**/
export function actionBtnPopUpInvite(invite: ClientProfil, senderSocket: Socket) {
setTimeout(() => {
const InvitePongBtn = document.querySelector("#popup-b-invite");
InvitePongBtn?.addEventListener("click", () => {
inviteToPlayPong(invite, senderSocket);
});
}, 0)
};

View file

@ -0,0 +1,15 @@
/**
* 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;
return ;
};

View file

@ -0,0 +1,9 @@
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;
senderSocket.emit('blockUser', JSON.stringify(profil));
};

View file

@ -0,0 +1,36 @@
import { addMessage } from "./addMessage";
import { Socket } from 'socket.io-client';
import { getUser } from "@app/auth";
import type { ClientMessage } from "../types_front";
import { noGuestFlag } from "../chat";
/**
* function sends socket.emit to the backend to active and broadcast a message to all sockets
* echos the message with addMessage to the sender
* @param socket
* @param msgCommand
*/
export function broadcastMsg (socket: Socket, msgCommand: string[]): void {
let msgText = msgCommand[1] ?? "";
let dest = '';
addMessage(msgText);
const user = getUser();
if (user && socket?.connected) {
const message: ClientMessage = {
command: msgCommand[0],
destination: '',
type: "chat",
user: user.name,
token: document.cookie,
text: msgText,
timestamp: Date.now(),
SenderWindowID: socket.id ?? "",
SenderUserName: user.name,
SenderUserID: user.id,
userID: '',
frontendUserName: '',
frontendUser: '',
Sendertext: '',
};
socket.emit('message', JSON.stringify(message));
}
};

View file

@ -0,0 +1,12 @@
import { 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 = "";
}

View file

@ -0,0 +1,19 @@
import { addMessage } from "./addMessage";
import { getUser } from "@app/auth";
export function cmdList() {
addMessage('*');
addMessage('** ********** List of @cmds ********** **');
addMessage('\'@cls\' - clear chat screen conversations');
addMessage('\'@profile <name>\' - pulls ups user profile');
addMessage('\'@block <name>\' - blocks / unblock user');
const guestflag = getUser()?.guest;
if(!guestflag) {
addMessage('\'@guest\' - guest broadcast msgs on / off');
}
addMessage('\'@notify\' - toggles notifications on / off');
addMessage('\'@quit\' - disconnect user from the chat');
addMessage('** *********************************** **');
addMessage('*');
}

View file

@ -0,0 +1,32 @@
import { Socket } from "socket.io-client";
import { isLoggedIn } from "./isLoggedIn";
import { showError } from "@app/toast";
import { updateUser } from "@app/auth";
/**
* function displays who is logged in the chat in the ping-Bubbies window
* @param socket
*/
export async function connected(socket: Socket): Promise<void> {
setTimeout(async () => {
try {
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const loggedIn = isLoggedIn();
if (!loggedIn) throw('Not Logged in');
let oldUser = localStorage.getItem("oldName") ?? "";
if (loggedIn?.name === undefined) {return ;};
oldUser = loggedIn.name ?? "";
let user = await updateUser();
localStorage.setItem("oldName", oldUser);
buddies.textContent = "";
socket.emit('list', {
oldUser: oldUser,
user: user?.name,
});
} catch (e) {
showError('Failed to login: Unknown error');
}
}, 16);
};

View file

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

View file

@ -0,0 +1,7 @@
let count = 0;
export function incrementCounter(): number {
count += 1;
return count;
}

View file

@ -0,0 +1,18 @@
import { Socket } from 'socket.io-client';
import type { ClientProfil } from '../types_front';
import { getUser } from '@app/auth';
import { addMessage } from './addMessage';
/**
* function displays an invite message to sender
* it also sends a message to backend for a link and displays it in the target window
* @param profil of the target
* @param senderSocket
*/
export 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));
};

View file

@ -0,0 +1,9 @@
import { getUser } from "@app/auth";
import type { User } from '@app/auth'
/**
* function checks if logged in
* @returns either user | null
*/
export function isLoggedIn(): User | null {
return getUser() || null;
};

View file

@ -0,0 +1,44 @@
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 bud
* @returns
*/
export async function listBuddies(socket: Socket, buddies: HTMLDivElement, listBuddies: string[]) {
buddies.innerHTML = "";
for (const bud of listBuddies)
{
if (!buddies) return;
const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement;
const buddiesElement = document.createElement("div-buddies-list");
buddiesElement.textContent = bud + '\n';
const user = getUser()?.name ?? "";
buddies.appendChild(buddiesElement);
buddies.scrollTop = buddies.scrollHeight;
buddiesElement.style.cursor = "pointer";
buddiesElement.addEventListener("click", () => {
navigator.clipboard.writeText(bud);
if (bud !== user && user !== "") {
sendtextbox.value = `@${bud}: `;
sendtextbox.focus();
}
});
buddiesElement.addEventListener("dblclick", () => {
getProfil(socket, bud);
sendtextbox.value = "";
});
}
}

View file

@ -0,0 +1,10 @@
import { Socket } from "socket.io-client";
export function logout(socket: Socket) {
socket.emit("logout"); // notify server
socket.disconnect(); // actually close the socket
localStorage.clear();
if (window.__state.chatSock !== undefined)
window.__state.chatSock.close();
};

View file

@ -0,0 +1,26 @@
import { incrementCounter } from "./incrementCounter";
// let count = 0;
// function incrementCounter(): number {
// count += 1;
// return count;
// }
export async function openMessagePopup(message: any) {
const modalmessage = document.getElementById("modal-message") ?? null;
if(!message) return
const obj = message;
if (modalmessage) {
const messageElement = document.createElement("div");
messageElement.innerHTML = `
<div id="profile-about">Next Game Message ${incrementCounter()}: ${obj.nextGame}</div>
`;
modalmessage.appendChild(messageElement);
modalmessage.scrollTop = modalmessage.scrollHeight;
}
const gameMessage = document.getElementById("game-modal") ?? null;
if (gameMessage) {
gameMessage.classList.remove("hidden");
}
}

View file

@ -0,0 +1,22 @@
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" class="text-xl font-bold text-blue-500"> Profile of ${profil.user} </div>
<div-login-name id="loginName"> Login status: <span class="recessed">${profil.loginName ?? 'Guest'}</span> </div>
</br>
<div-login-name id="loginName"> Login ID: <span class="recessed">${profil.userID ?? ''}</span> </div>
</br>
<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" class="text-2xl">About: <span class="recessed text-amber-500">${profil.text}</span> </div>
</div>
`;
const profilList = document.getElementById("profile-modal") ?? null;
if (profilList)
profilList.classList.remove("hidden");
}

View file

@ -0,0 +1,47 @@
/**
* function takes the input line of the chat and checks the it's not a cmd
* ex: @command "arg" or @command noarg
* ex: command @help - displays commands availble
* @param msgText : string from input line
*
*/
export 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', '@help', '@cls'];
if (noArgCommands.includes(msgText)) {
command[0] = msgText;
command[1] = '';
return command;
}
const ArgCommands = ['@profile', '@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;
}

View file

@ -0,0 +1,29 @@
import { Socket } from "socket.io-client";
import { getSocket } from "../chat";
import { logout } from "./logout";
import { connected } from "./connected";
import { showError } from "@app/toast";
import { setTitle } from "@app/routing";
/**
* function to quit the chat - leaves the ping-Buddies list
* @param socket
*/
export 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('Chat Page');
connected(socket);
} else {
getSocket();
}
} catch (e) {
showError('Failed to Quit Chat: Unknown error');
}
};

View file

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

View file

@ -0,0 +1,14 @@
import { Socket } from "socket.io-client";
/**
* function waits for the socket to be connected and when connected calls socket.on "connect"
* @param socket
* @returns
*/
export function waitSocketConnected(socket: Socket): Promise<void> {
return new Promise(resolve => {
if (socket.connected) return resolve();
socket.on("connect", () => resolve());
});
};

View file

@ -0,0 +1,17 @@
import { updateUser } from "@app/auth";
export async function windowStateHidden() {
const socketId = window.__state.chatSock || 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,27 @@
import { setTitle } from "@app/routing";
import { updateUser } from "@app/auth";
/**
* function stores old name clears ping buddies list
* and emit a client entered to backend
* @returns
*/
export async function windowStateVisable() {
const buddies = document.getElementById('div-buddies') as HTMLDivElement;
const socketId = window.__state.chatSock || undefined;
let oldName = localStorage.getItem("oldName") || undefined;
if (socketId === undefined || oldName === undefined) {return;};
let user = await updateUser();
if(user === null) return;
socketId.emit('client_entered', {
userName: oldName,
user: user?.name,
});
buddies.innerHTML = '';
buddies.textContent = '';
setTitle('Chat Page');
return;
};

View file

@ -0,0 +1,64 @@
export type ClientMessage = {
command: string
destination: string;
type: string,
user: string;
userID: string,
token: string
frontendUserName: string,
frontendUser: string,
text: string;
SenderWindowID: string,
SenderUserName: string,
SenderUserID: string,
timestamp: number,
Sendertext: string,
innerHtml?: string,
};
export type ClientProfil = ClientProfilPartial & {
loginName?: string | '',
SenderName?: string | '',
Sendertext?: string | '',
innerHtml?: string | '',
};
export type ClientProfilPartial = {
command: string,
type: string,
destination: string,
user?: string | '',
userID?: string | '',
timestamp: number,
SenderWindowID?:string | '',
SenderID?: string | '',
text?: string | '',
token?: string | '',
guestmsg?: boolean,
}
export type blockedUnBlocked =
{
userState: string,
userTarget: string,
by: string,
};
export type obj =
{
command: string,
destination: string,
type: string,
user: string,
frontendUserName: string,
frontendUser: string,
token: string,
text: string,
timestamp: number,
SenderWindowID: string,
Sendertext: string,
};