fixed chat zustand bug
This commit is contained in:
@@ -1,81 +1,196 @@
|
||||
"use client";
|
||||
import { ChatBubbleIcon, PaperPlaneIcon } from "@radix-ui/react-icons";
|
||||
import { useChatStore } from "_store/chatStore";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { Fragment, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
Dispatcher,
|
||||
getDispatcher,
|
||||
} from "(dispatch)/_components/navbar/_components/action";
|
||||
import { cn } from "helpers/cn";
|
||||
import { socket } from "(dispatch)/socket";
|
||||
import { ChatMessage } from "@repo/db";
|
||||
|
||||
export const Chat = () => {
|
||||
const { sendMessage, addChat, chats, addMessage, setOwnId } = useChatStore();
|
||||
const [sending, setSending] = useState(false);
|
||||
const session = useSession();
|
||||
const [dropdownOpen, setDropdownOpen] = useState(false);
|
||||
const [addTabValue, setAddTabValue] = useState<string>("");
|
||||
const [selectedTab, setSelectedTab] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<string>("");
|
||||
const [dispatcher, setDispatcher] = useState<Dispatcher[] | null>(null);
|
||||
const timeout = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!session.data?.user.id) return;
|
||||
setOwnId(session.data.user.id);
|
||||
}, [session]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchDispatcher = async () => {
|
||||
const data = await getDispatcher();
|
||||
setDispatcher(data);
|
||||
setAddTabValue(data[0]?.userId || "");
|
||||
};
|
||||
|
||||
timeout.current = setInterval(() => {
|
||||
fetchDispatcher();
|
||||
}, 10000);
|
||||
fetchDispatcher();
|
||||
|
||||
return () => {
|
||||
if (timeout.current) {
|
||||
clearInterval(timeout.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="dropdown">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
<div
|
||||
className={cn(
|
||||
"dropdown dropdown-center",
|
||||
dropdownOpen && "dropdown-open",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
className="btn btn-soft btn-sm btn-primary"
|
||||
onClick={() => {
|
||||
console.log("clicked");
|
||||
setDropdownOpen((prev) => !prev);
|
||||
}}
|
||||
>
|
||||
<ChatBubbleIcon className="w-4 h-4" />
|
||||
</div>
|
||||
<div
|
||||
tabIndex={0}
|
||||
className="dropdown-content card bg-base-200 w-150 shadow-md z-[1100]"
|
||||
>
|
||||
<div className="card-body">
|
||||
<div className="join">
|
||||
<select defaultValue="Small" className="select select-sm w-full">
|
||||
<option disabled={true}>Wähle einen Chatpartner...</option>
|
||||
<option><LST_01> Nicolas Kratsos #VAR0002</option>
|
||||
<option><CHX31> Vorname Nachname #VAR1010</option>
|
||||
<option><CHX100> Vorname Nachname #VAR1010</option>
|
||||
</select>
|
||||
<button className="btn btn-sm btn-soft btn-primary join-item">
|
||||
<span className="text-xl">+</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="tabs tabs-lift">
|
||||
<input
|
||||
type="radio"
|
||||
name="my_tabs_3"
|
||||
className="tab"
|
||||
aria-label="<LST_01>"
|
||||
/>
|
||||
<div className="tab-content bg-base-100 border-base-300 p-6">
|
||||
<div className="chat chat-start">
|
||||
<div className="chat-header">
|
||||
<LST_01> Nicolas Kratsos #VAR0002
|
||||
</div>
|
||||
<div className="chat-bubble">LST v2 ist schon nice</div>
|
||||
</div>
|
||||
<div className="chat chat-end">
|
||||
<div className="chat-bubble">Hast recht.</div>
|
||||
</div>
|
||||
</button>
|
||||
{dropdownOpen && (
|
||||
<div
|
||||
tabIndex={0}
|
||||
className="dropdown-content card bg-base-200 w-150 shadow-md z-[1100]"
|
||||
>
|
||||
<div className="card-body">
|
||||
<div className="join">
|
||||
<select
|
||||
className="select select-sm w-full"
|
||||
value={addTabValue}
|
||||
onChange={(e) => setAddTabValue(e.target.value)}
|
||||
>
|
||||
<option key={"default"} disabled={true}>
|
||||
Wähle einen Chatpartner...
|
||||
</option>
|
||||
{dispatcher?.map((user) => (
|
||||
<option key={user.userId} value={user.userId}>
|
||||
{user.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
className="btn btn-sm btn-soft btn-primary join-item"
|
||||
onClick={() => {
|
||||
const user = dispatcher?.find(
|
||||
(user) => user.userId === addTabValue,
|
||||
);
|
||||
if (!user) return;
|
||||
addChat(addTabValue, user.name);
|
||||
// setSelectedTab(addTabValue);
|
||||
}}
|
||||
>
|
||||
<span className="text-xl">+</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<input
|
||||
type="radio"
|
||||
name="my_tabs_3"
|
||||
className="tab"
|
||||
aria-label="<CHX31>"
|
||||
defaultChecked
|
||||
/>
|
||||
<div className="tab-content bg-base-100 border-base-300 p-6">
|
||||
<div className="chat chat-start">
|
||||
<div className="chat-header">
|
||||
<LST_01> Nicolas Kratsos #VAR0002
|
||||
</div>
|
||||
<div className="chat-bubble">get rekt lmao</div>
|
||||
</div>
|
||||
<div className="chat chat-end">
|
||||
<div className="chat-bubble">no u.</div>
|
||||
</div>
|
||||
<div className="tabs tabs-lift">
|
||||
{Object.keys(chats).map((userId) => {
|
||||
const chat = chats[userId];
|
||||
if (!chat) return null;
|
||||
return (
|
||||
<Fragment key={userId}>
|
||||
<input
|
||||
type="radio"
|
||||
name="my_tabs_3"
|
||||
className="tab"
|
||||
aria-label={`<${chat.name}>`}
|
||||
checked={selectedTab === userId}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
// Handle tab change
|
||||
setSelectedTab(userId);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="tab-content bg-base-100 border-base-300 p-6">
|
||||
{chat.messages.map((chatMessage) => {
|
||||
const isSender =
|
||||
chatMessage.senderId === session.data?.user.id;
|
||||
return (
|
||||
<div
|
||||
key={chatMessage.id}
|
||||
className={`chat ${isSender ? "chat-end" : "chat-start"}`}
|
||||
>
|
||||
<p className="chat-footer opacity-50">
|
||||
{new Date(
|
||||
chatMessage.timestamp,
|
||||
).toLocaleTimeString()}
|
||||
</p>
|
||||
<div className="chat-bubble">
|
||||
{chatMessage.text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{!chat.messages.length && (
|
||||
<p className="text-xs opacity-50">
|
||||
Noch keine Nachrichten
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="join">
|
||||
<div className="w-full">
|
||||
<label className="input validator join-item w-full">
|
||||
<input type="text" required className="w-full" />
|
||||
</label>
|
||||
<div className="join">
|
||||
<div className="w-full">
|
||||
<label className="input join-item w-full">
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
className="w-full"
|
||||
onChange={(e) => {
|
||||
setMessage(e.target.value);
|
||||
}}
|
||||
value={message}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<button
|
||||
className="btn btn-soft join-item"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setSending(true);
|
||||
if (message.length < 1) return;
|
||||
if (!selectedTab) return;
|
||||
sendMessage(selectedTab, message)
|
||||
.then(() => {
|
||||
setMessage("");
|
||||
setSending(false);
|
||||
})
|
||||
.catch(() => {
|
||||
setSending(false);
|
||||
});
|
||||
return false;
|
||||
}}
|
||||
disabled={sending}
|
||||
role="button"
|
||||
onSubmit={(e) => false}
|
||||
>
|
||||
{sending ? (
|
||||
<span className="loading loading-spinner loading-sm"></span>
|
||||
) : (
|
||||
<PaperPlaneIcon />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
<button className="btn btn-soft join-item">
|
||||
<PaperPlaneIcon />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"use server";
|
||||
|
||||
export interface Dispatcher {
|
||||
userId: string;
|
||||
lastSeen: string;
|
||||
loginTime: string;
|
||||
logoffTime: string;
|
||||
selectedZone: string;
|
||||
name: string;
|
||||
socketId: string;
|
||||
}
|
||||
|
||||
export const getDispatcher = async () => {
|
||||
const res = await fetch(`
|
||||
${process.env.NEXT_PUBLIC_DISPATCH_SERVER_URL}/dispatcher`);
|
||||
const data = await res.json();
|
||||
return data as Dispatcher[];
|
||||
};
|
||||
70
apps/dispatch/app/_store/chatStore.ts
Normal file
70
apps/dispatch/app/_store/chatStore.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { create } from "zustand";
|
||||
import { ChatMessage } from "@repo/db";
|
||||
import { socket } from "(dispatch)/socket";
|
||||
|
||||
interface ChatStore {
|
||||
ownId: null | string;
|
||||
setOwnId: (id: string) => void;
|
||||
chats: Record<string, { name: string; messages: ChatMessage[] }>;
|
||||
sendMessage: (userId: string, message: string) => Promise<void>;
|
||||
addChat: (userId: string, name: string) => void;
|
||||
addMessage: (userId: string, message: ChatMessage) => void;
|
||||
}
|
||||
|
||||
export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
ownId: null,
|
||||
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 },
|
||||
({ error }: { error?: string }) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
},
|
||||
addChat: (userId, name) => {
|
||||
set((state) => ({
|
||||
chats: {
|
||||
...state.chats, // Bestehende Chats beibehalten
|
||||
[userId]: { name, messages: [] }, // Neuen Chat hinzufügen
|
||||
},
|
||||
}));
|
||||
},
|
||||
addMessage: (userId: string, message: ChatMessage) => {
|
||||
console.log("addMessage", userId, message);
|
||||
set((state) => {
|
||||
const user = state.chats[userId] || { name: userId, messages: [] };
|
||||
const isSender = message.senderId === state.ownId;
|
||||
|
||||
return {
|
||||
chats: {
|
||||
...state.chats,
|
||||
[userId]: {
|
||||
...user,
|
||||
name: isSender ? message.receiverName : message.senderName,
|
||||
messages: [...user.messages, message], // Neuen Zustand erzeugen
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
}));
|
||||
|
||||
socket.on(
|
||||
"chat-message",
|
||||
({ userId, message }: { userId: string; message: ChatMessage }) => {
|
||||
const store = useChatStore.getState();
|
||||
console.log("chat-message", userId, message);
|
||||
// Update the chat store with the new message
|
||||
store.addMessage(userId, message);
|
||||
},
|
||||
);
|
||||
0
apps/dispatch/app/api/dispatcher/route.ts
Normal file
0
apps/dispatch/app/api/dispatcher/route.ts
Normal file
@@ -10,7 +10,6 @@ if (!process.env.LIVEKIT_API_SECRET)
|
||||
export const GET = async () => {
|
||||
const session = await getServerSession();
|
||||
|
||||
console.log(session?.user.permissions);
|
||||
if (!session)
|
||||
return Response.json({ message: "Unauthorized" }, { status: 401 });
|
||||
const user = await prisma.user.findUnique({
|
||||
@@ -18,7 +17,6 @@ export const GET = async () => {
|
||||
id: session.user.id,
|
||||
},
|
||||
});
|
||||
console.log(user);
|
||||
|
||||
if (!user || !user.permissions.includes("AUDIO"))
|
||||
return Response.json({ message: "Missing permissions" }, { status: 401 });
|
||||
|
||||
@@ -14,8 +14,10 @@
|
||||
"@livekit/components-react": "^2.8.1",
|
||||
"@livekit/components-styles": "^1.1.4",
|
||||
"@radix-ui/react-icons": "^1.3.2",
|
||||
"@repo/db": "*",
|
||||
"@repo/ui": "*",
|
||||
"@tailwindcss/postcss": "^4.0.14",
|
||||
"@tanstack/react-query": "^5.69.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"livekit-client": "^2.9.7",
|
||||
"livekit-server-sdk": "^2.10.2",
|
||||
|
||||
Reference in New Issue
Block a user