completed basic Chat

This commit is contained in:
PxlLoewe
2025-03-22 01:29:14 -07:00
parent b7eb148ca6
commit 1c1d82cace
2 changed files with 95 additions and 38 deletions

View File

@@ -4,8 +4,16 @@ import { socket } from "(dispatch)/socket";
interface ChatStore {
ownId: null | string;
selectedChat: string | null;
chatOpen: boolean;
setChatOpen: (open: boolean) => void;
setSelectedChat: (chatId: string | null) => void;
setOwnId: (id: string) => void;
chats: Record<string, { name: string; messages: ChatMessage[] }>;
chats: Record<
string,
{ name: string; notification: boolean; messages: ChatMessage[] }
>;
setChatNotification: (userId: string, notification: boolean) => void;
sendMessage: (userId: string, message: string) => Promise<void>;
addChat: (userId: string, name: string) => void;
addMessage: (userId: string, message: ChatMessage) => void;
@@ -13,11 +21,14 @@ interface ChatStore {
export const useChatStore = create<ChatStore>((set, get) => ({
ownId: null,
chatOpen: false,
selectedChat: null,
setChatOpen: (open: boolean) => set({ chatOpen: open }),
setSelectedChat: (chatId: string | null) => set({ selectedChat: chatId }),
setOwnId: (id: string) => set({ ownId: id }),
chats: {},
sendMessage: (userId: string, message: string) => {
return new Promise((resolve, reject) => {
console.log("sendMessage", userId, message);
socket.emit(
"send-message",
{ userId, message },
@@ -35,22 +46,44 @@ export const useChatStore = create<ChatStore>((set, get) => ({
set((state) => ({
chats: {
...state.chats, // Bestehende Chats beibehalten
[userId]: { name, messages: [] }, // Neuen Chat hinzufügen
[userId]: { name, notification: false, messages: [] }, // Neuen Chat hinzufügen
},
}));
},
addMessage: (userId: string, message: ChatMessage) => {
console.log("addMessage", userId, message);
setChatNotification: (userId, notification) => {
const chat = get().chats[userId];
if (!chat) return;
console.log("setChatNotification", userId, notification);
set((state) => {
const user = state.chats[userId] || { name: userId, messages: [] };
return {
chats: {
...state.chats,
[userId]: {
...chat,
notification,
},
},
};
});
},
addMessage: (userId: string, message: ChatMessage) => {
set((state) => {
const user = state.chats[userId] || {
name: userId,
messages: [],
notification: false,
};
const isSender = message.senderId === state.ownId;
return {
selectedChat: state.selectedChat ? state.selectedChat : userId,
chats: {
...state.chats,
[userId]: {
...user,
name: isSender ? message.receiverName : message.senderName,
notification:
!isSender && (state.selectedChat !== userId || !state.chatOpen),
messages: [...user.messages, message], // Neuen Zustand erzeugen
},
},