added server component, provider, api for login request to backend and receive jjwt token, socket context , and auth connection
This commit is contained in:
parent
a049c054e8
commit
6fa6415bfa
25
components.json
Normal file
25
components.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "radix-nova",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"rtl": false,
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"menuColor": "default",
|
||||
"menuAccent": "subtle",
|
||||
"registries": {}
|
||||
}
|
||||
5208
package-lock.json
generated
5208
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -15,9 +15,13 @@
|
||||
"framer-motion": "^12.38.0",
|
||||
"lucide-react": "^1.8.0",
|
||||
"next": "16.2.4",
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"tailwind-merge": "^3.5.0"
|
||||
"shadcn": "^4.2.0",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
|
||||
@ -0,0 +1,460 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef, useMemo } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { useSocket, type ChatMessage, type RoomNotice } from "@/context/SocketContext";
|
||||
import { fetchConversations, createConversation } from "@/lib/api";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Send,
|
||||
Phone,
|
||||
Video,
|
||||
Plus,
|
||||
LogOut,
|
||||
Loader2,
|
||||
Hash,
|
||||
Wifi,
|
||||
WifiOff,
|
||||
Users,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Avatar,
|
||||
AvatarFallback,
|
||||
AvatarImage,
|
||||
} from "@/components/ui/avatar";
|
||||
import { useDebounce } from "@/hooks/useDebounce";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Types */
|
||||
/* ------------------------------------------------------------------ */
|
||||
interface Room {
|
||||
id: string;
|
||||
name: string;
|
||||
isGroup: boolean;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Backend rooms loaded dynamically */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* ChatPage */
|
||||
/* ------------------------------------------------------------------ */
|
||||
export default function ChatPage() {
|
||||
const router = useRouter();
|
||||
const { user, isLoading: authLoading, logout } = useAuth();
|
||||
const {
|
||||
isConnected,
|
||||
mySocketId,
|
||||
joinRoom,
|
||||
leaveRoom,
|
||||
sendMessage,
|
||||
messages,
|
||||
notices,
|
||||
currentRoom,
|
||||
setCurrentRoom,
|
||||
clearMessages,
|
||||
} = useSocket();
|
||||
|
||||
const [text, setText] = useState("");
|
||||
const [search, setSearch] = useState("");
|
||||
const [activeTab, setActiveTab] = useState<"rooms" | "create">("rooms");
|
||||
const [newRoomName, setNewRoomName] = useState("");
|
||||
const [rooms, setRooms] = useState<Room[]>([]);
|
||||
|
||||
const debouncedSearch = useDebounce(search, 300);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// ── Auth guard ────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
if (!authLoading && !user) {
|
||||
router.push("/login");
|
||||
}
|
||||
}, [authLoading, user, router]);
|
||||
|
||||
// ── Fetch rooms & Auto-join ─────────────────────────────────────
|
||||
useEffect(() => {
|
||||
if (!isConnected) return;
|
||||
|
||||
// Fetch conversations from API
|
||||
fetchConversations()
|
||||
.then((data) => {
|
||||
// Map backend returned data to Room format
|
||||
const loadedRooms = Array.isArray(data) ? data.map(c => ({
|
||||
id: c._id || c.id || "unknown",
|
||||
name: c.name || "Unnamed Group",
|
||||
isGroup: c.type === "group" || c.isGroup || true
|
||||
})) : [];
|
||||
|
||||
setRooms(loadedRooms);
|
||||
|
||||
// Auto-join first room
|
||||
if (!currentRoom && loadedRooms.length > 0) {
|
||||
const firstRoom = loadedRooms[0];
|
||||
setCurrentRoom(firstRoom.id);
|
||||
joinRoom(firstRoom.id);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.error("Failed to fetch conversations", err);
|
||||
});
|
||||
}, [isConnected, currentRoom, joinRoom, setCurrentRoom]);
|
||||
|
||||
// ── Scroll to bottom on new messages ──────────────────────────────
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [messages, notices]);
|
||||
|
||||
// ── Filtered rooms ────────────────────────────────────────────────
|
||||
const filteredRooms = useMemo(() => {
|
||||
if (!debouncedSearch.trim()) return rooms;
|
||||
return rooms.filter((r) =>
|
||||
r.name.toLowerCase().includes(debouncedSearch.toLowerCase())
|
||||
);
|
||||
}, [rooms, debouncedSearch]);
|
||||
|
||||
// ── Messages for current room ─────────────────────────────────────
|
||||
const roomMessages = useMemo(
|
||||
() => messages.filter((m) => m.roomId === currentRoom),
|
||||
[messages, currentRoom]
|
||||
);
|
||||
|
||||
const roomNotices = useMemo(
|
||||
() => notices.filter((n) => n.roomId === currentRoom),
|
||||
[notices, currentRoom]
|
||||
);
|
||||
|
||||
// ── Handlers ──────────────────────────────────────────────────────
|
||||
const handleSelectRoom = (room: Room) => {
|
||||
if (currentRoom === room.id) return;
|
||||
|
||||
// Leave old room
|
||||
if (currentRoom) {
|
||||
leaveRoom(currentRoom);
|
||||
}
|
||||
// Join new room
|
||||
setCurrentRoom(room.id);
|
||||
joinRoom(room.id);
|
||||
};
|
||||
|
||||
const handleSend = () => {
|
||||
if (!text.trim() || !currentRoom) return;
|
||||
sendMessage(currentRoom, text.trim());
|
||||
setText("");
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateRoom = async () => {
|
||||
const name = newRoomName.trim();
|
||||
if (!name) return;
|
||||
|
||||
try {
|
||||
// Actually create the room on the backend
|
||||
const created = await createConversation({ name, type: "group", participants: [user?.username || "unknown"] });
|
||||
const newRoom: Room = {
|
||||
id: created._id || created.id || name.toLowerCase().replace(/\s+/g, "-"),
|
||||
name: created.name || name,
|
||||
isGroup: true
|
||||
};
|
||||
|
||||
setRooms((prev) => {
|
||||
if (prev.find((r) => r.id === newRoom.id)) return prev;
|
||||
return [...prev, newRoom];
|
||||
});
|
||||
setNewRoomName("");
|
||||
setActiveTab("rooms");
|
||||
handleSelectRoom(newRoom);
|
||||
} catch (err) {
|
||||
console.error("Error creating room", err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
if (currentRoom) leaveRoom(currentRoom);
|
||||
clearMessages();
|
||||
logout();
|
||||
};
|
||||
|
||||
// ── Loading / Auth guard ──────────────────────────────────────────
|
||||
if (authLoading || !user) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedRoom = rooms.find((r) => r.id === currentRoom);
|
||||
|
||||
return (
|
||||
<div className="flex h-screen">
|
||||
{/* ================= LEFT SIDEBAR ================= */}
|
||||
<div className="w-1/3 border-r flex flex-col bg-background">
|
||||
{/* HEADER */}
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="text-xl font-semibold">Chats</h2>
|
||||
{/* Connection indicator */}
|
||||
{isConnected ? (
|
||||
<Wifi className="w-4 h-4 text-green-500" />
|
||||
) : (
|
||||
<WifiOff className="w-4 h-4 text-red-500" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="rounded-full"
|
||||
onClick={() => setActiveTab(activeTab === "create" ? "rooms" : "create")}
|
||||
title="Create room"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="rounded-full"
|
||||
onClick={handleLogout}
|
||||
title="Logout"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* USER INFO */}
|
||||
<div className="px-4 pb-2 text-sm text-muted-foreground">
|
||||
Logged in as <span className="font-medium text-foreground">{user.username}</span>
|
||||
</div>
|
||||
|
||||
{/* TABS */}
|
||||
<div className="flex gap-6 px-4 text-sm font-medium border-b pb-2">
|
||||
<button
|
||||
onClick={() => setActiveTab("rooms")}
|
||||
className={`pb-1 ${
|
||||
activeTab === "rooms"
|
||||
? "text-primary border-b-2 border-primary"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
Rooms
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab("create")}
|
||||
className={`pb-1 ${
|
||||
activeTab === "create"
|
||||
? "text-primary border-b-2 border-primary"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
Create
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* CREATE ROOM PANEL */}
|
||||
{activeTab === "create" && (
|
||||
<div className="p-4 space-y-3 border-b">
|
||||
<Input
|
||||
placeholder="Room name..."
|
||||
value={newRoomName}
|
||||
onChange={(e) => setNewRoomName(e.target.value)}
|
||||
className="rounded-full bg-muted"
|
||||
onKeyDown={(e) => e.key === "Enter" && handleCreateRoom()}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleCreateRoom}
|
||||
disabled={!newRoomName.trim()}
|
||||
className="w-full rounded-full"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Create Room
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* SEARCH */}
|
||||
<div className="p-4">
|
||||
<Input
|
||||
placeholder="Search rooms..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="rounded-full bg-muted"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ROOM LIST */}
|
||||
<div className="flex-1 overflow-y-auto px-2 space-y-1">
|
||||
{filteredRooms.length === 0 && (
|
||||
<p className="p-4 text-sm text-muted-foreground">
|
||||
No rooms found
|
||||
</p>
|
||||
)}
|
||||
|
||||
{filteredRooms.map((room) => {
|
||||
const isActive = currentRoom === room.id;
|
||||
const unreadCount = messages.filter(
|
||||
(m) => m.roomId === room.id && m.senderId !== mySocketId
|
||||
).length;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={room.id}
|
||||
onClick={() => handleSelectRoom(room)}
|
||||
className={`flex items-center gap-3 p-3 rounded-xl cursor-pointer transition
|
||||
${
|
||||
isActive
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "hover:bg-muted"
|
||||
}
|
||||
`}
|
||||
>
|
||||
<div
|
||||
className={`w-10 h-10 flex items-center justify-center rounded-full ${
|
||||
isActive ? "bg-white/20" : "bg-primary/10"
|
||||
}`}
|
||||
>
|
||||
{room.isGroup ? (
|
||||
<Users className={`w-5 h-5 ${isActive ? "text-white" : "text-primary"}`} />
|
||||
) : (
|
||||
<Hash className={`w-5 h-5 ${isActive ? "text-white" : "text-primary"}`} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<h3 className="font-semibold truncate">{room.name}</h3>
|
||||
<p className="text-xs opacity-70 truncate">
|
||||
#{room.id}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ================= RIGHT CHAT ================= */}
|
||||
<div className="w-2/3 flex flex-col">
|
||||
{/* HEADER */}
|
||||
<div className="p-4 border-b font-semibold flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 flex items-center justify-center rounded-full bg-primary/10">
|
||||
<Users className="w-5 h-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-lg">{selectedRoom?.name || "Select a room"}</span>
|
||||
{selectedRoom && (
|
||||
<p className="text-xs text-muted-foreground font-normal">
|
||||
#{selectedRoom.id} · {isConnected ? "Connected" : "Disconnected"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Call Buttons */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => console.log("Audio call")}
|
||||
>
|
||||
<Phone className="w-5 h-5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => console.log("Video call")}
|
||||
>
|
||||
<Video className="w-5 h-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* MESSAGES */}
|
||||
<div className="flex-1 p-4 space-y-2 overflow-y-auto">
|
||||
{!currentRoom && (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||
Select a room to start chatting
|
||||
</div>
|
||||
)}
|
||||
|
||||
{currentRoom && roomMessages.length === 0 && roomNotices.length === 0 && (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||
No messages yet. Say something!
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Interleave messages and notices by order */}
|
||||
{roomMessages.map((msg, idx) => {
|
||||
const isMe = msg.senderId === mySocketId;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`msg-${idx}`}
|
||||
className={`flex ${isMe ? "justify-end" : "justify-start"}`}
|
||||
>
|
||||
<div className="flex flex-col max-w-xs">
|
||||
{/* Show sender name for others */}
|
||||
{!isMe && (
|
||||
<span className="text-xs text-muted-foreground mb-1 ml-1">
|
||||
{msg.username}
|
||||
</span>
|
||||
)}
|
||||
<div
|
||||
className={`px-4 py-2 rounded-xl ${
|
||||
isMe
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted"
|
||||
}`}
|
||||
>
|
||||
{msg.text}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Room notices */}
|
||||
{roomNotices.map((notice, idx) => (
|
||||
<div key={`notice-${idx}`} className="flex justify-center">
|
||||
<span className="text-xs text-muted-foreground bg-muted/50 px-3 py-1 rounded-full">
|
||||
{notice.message}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
{/* INPUT */}
|
||||
<div className="p-4 border-t flex gap-2">
|
||||
<Input
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={
|
||||
currentRoom
|
||||
? `Message #${currentRoom}...`
|
||||
: "Select a room first..."
|
||||
}
|
||||
disabled={!currentRoom || !isConnected}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
disabled={!currentRoom || !isConnected || !text.trim()}
|
||||
>
|
||||
<Send className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,4 +1,8 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
/* @import "shadcn/tailwind.css"; */
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme {
|
||||
--color-border: var(--border);
|
||||
@ -39,50 +43,134 @@
|
||||
from {
|
||||
height: 0;
|
||||
}
|
||||
|
||||
to {
|
||||
height: var(--radix-accordion-content-height);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes accordion-up {
|
||||
from {
|
||||
height: var(--radix-accordion-content-height);
|
||||
}
|
||||
|
||||
to {
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: hsl(222.2 84% 4.9%);
|
||||
--foreground: hsl(210 40% 98%);
|
||||
--card: hsl(222.2 84% 4.9%);
|
||||
--card-foreground: hsl(210 40% 98%);
|
||||
--popover: hsl(222.2 84% 4.9%);
|
||||
--popover-foreground: hsl(210 40% 98%);
|
||||
--primary: hsl(217.2 91.2% 59.8%);
|
||||
--primary-foreground: hsl(222.2 47.4% 11.2%);
|
||||
--secondary: hsl(217.2 32.6% 17.5%);
|
||||
--secondary-foreground: hsl(210 40% 98%);
|
||||
--muted: hsl(217.2 32.6% 17.5%);
|
||||
--muted-foreground: hsl(215 20.2% 65.1%);
|
||||
--accent: hsl(217.2 32.6% 17.5%);
|
||||
--accent-foreground: hsl(210 40% 98%);
|
||||
--destructive: hsl(0 62.8% 30.6%);
|
||||
--destructive-foreground: hsl(210 40% 98%);
|
||||
--border: hsl(217.2 32.6% 17.5%);
|
||||
--input: hsl(217.2 32.6% 17.5%);
|
||||
--ring: hsl(224.3 76.3% 48%);
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
html, body {
|
||||
background-color: #ffffff !important;
|
||||
color: #0f172a !important;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
@apply bg-background text-foreground font-sans antialiased;
|
||||
}
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--font-heading: var(--font-sans);
|
||||
--font-sans: var(--font-sans);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-background: var(--background);
|
||||
--radius-sm: calc(var(--radius) * 0.6);
|
||||
--radius-md: calc(var(--radius) * 0.8);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.4);
|
||||
--radius-2xl: calc(var(--radius) * 1.8);
|
||||
--radius-3xl: calc(var(--radius) * 2.2);
|
||||
--radius-4xl: calc(var(--radius) * 2.6);
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #0f172a;
|
||||
--card: #3b82f6;
|
||||
--card-foreground: #ffffff;
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: #0f172a;
|
||||
--primary: #2563eb;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #f1f5f9;
|
||||
--secondary-foreground: #0f172a;
|
||||
--muted: #f1f5f9;
|
||||
--muted-foreground: #64748b;
|
||||
--accent: #f1f5f9;
|
||||
--accent-foreground: #0f172a;
|
||||
--destructive: #ef4444;
|
||||
--destructive-foreground: #ffffff;
|
||||
--border: #e2e8f0;
|
||||
--input: #e2e8f0;
|
||||
--ring: #3b82f6;
|
||||
--radius: 0.625rem;
|
||||
}
|
||||
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.1 0.05 260);
|
||||
--foreground: oklch(0.95 0.02 260);
|
||||
--card: oklch(0.15 0.08 260);
|
||||
--card-foreground: oklch(0.95 0.02 260);
|
||||
--popover: oklch(0.15 0.08 260);
|
||||
--popover-foreground: oklch(0.95 0.02 260);
|
||||
--primary: oklch(0.55 0.23 255);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.2 0.08 260);
|
||||
--secondary-foreground: oklch(0.95 0.02 260);
|
||||
--muted: oklch(0.2 0.08 260);
|
||||
--muted-foreground: oklch(0.7 0.05 260);
|
||||
--accent: oklch(0.2 0.08 260);
|
||||
--accent-foreground: oklch(0.95 0.02 260);
|
||||
--destructive: oklch(0.396 0.141 25.723);
|
||||
--destructive-foreground: oklch(0.95 0.02 260);
|
||||
--border: oklch(0.3 0.08 260);
|
||||
--input: oklch(0.3 0.08 260);
|
||||
--ring: oklch(0.55 0.23 255);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.89);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.15 0.08 260);
|
||||
--sidebar-foreground: oklch(0.95 0.02 260);
|
||||
--sidebar-primary: oklch(0.55 0.23 255);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.2 0.08 260);
|
||||
--sidebar-accent-foreground: oklch(0.95 0.02 260);
|
||||
--sidebar-border: oklch(0.3 0.08 260);
|
||||
--sidebar-ring: oklch(0.55 0.23 255);
|
||||
}
|
||||
@ -1,6 +1,10 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
import { Inter, Geist } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Providers } from "./providers";
|
||||
|
||||
const geist = Geist({ subsets: ["latin"], variable: "--font-sans" });
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] });
|
||||
|
||||
@ -15,9 +19,11 @@ export default function RootLayout({
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" className="dark">
|
||||
<body className={`${inter.className} min-h-screen bg-background antialiased`}>
|
||||
{children}
|
||||
<html lang="en" className={cn("font-sans", geist.variable)}>
|
||||
<body
|
||||
className={`${inter.className} min-h-screen bg-background antialiased`}
|
||||
>
|
||||
<Providers>{children}</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
@ -1,79 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { MessagesSquare, ArrowRight } from "lucide-react";
|
||||
import { MessagesSquare, ArrowRight, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export default function LoginPage() {
|
||||
const [name, setName] = useState("");
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
const { user, isLoading, login } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
const handleLogin = (e: React.FormEvent) => {
|
||||
const [name, setName] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
// If already authenticated, redirect to chat
|
||||
useEffect(() => {
|
||||
if (!isLoading && user) {
|
||||
router.push("/chat");
|
||||
}
|
||||
}, [isLoading, user, router]);
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) {
|
||||
localStorage.setItem("chat_app_user", JSON.stringify({ name }));
|
||||
setIsLoggedIn(true);
|
||||
if (!name.trim()) return;
|
||||
|
||||
setError("");
|
||||
setSubmitting(true);
|
||||
|
||||
try {
|
||||
await login(name.trim());
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Login failed. Is the backend running?");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoggedIn) {
|
||||
// Show nothing while checking auth state
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background px-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h1 className="text-3xl font-bold">Welcome, {name}!</h1>
|
||||
<p className="text-muted-foreground">
|
||||
You have successfully logged in.
|
||||
</p>
|
||||
<Button variant="outline" onClick={() => setIsLoggedIn(false)}>
|
||||
Logout
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background px-4">
|
||||
<div className="w-full max-w-md border border-border bg-card rounded-xl shadow-sm text-card-foreground">
|
||||
<div className="p-8 space-y-6">
|
||||
<header className="text-center space-y-2">
|
||||
<div className="inline-flex items-center justify-center w-12 h-12 rounded-lg bg-primary text-primary-foreground mb-2">
|
||||
<MessagesSquare className="w-6 h-6" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Login</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Enter your name to join the chat
|
||||
</p>
|
||||
</header>
|
||||
<div
|
||||
className="flex min-h-screen items-center justify-center px-4"
|
||||
style={{
|
||||
background:
|
||||
"linear-gradient(to bottom right, var(--primary), var(--background))",
|
||||
}}
|
||||
>
|
||||
<div className="w-full max-w-md rounded-3xl p-8 backdrop-blur-xl bg-white/20 border border-white/30 shadow-2xl">
|
||||
|
||||
<form onSubmit={handleLogin} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="name"
|
||||
className="text-sm font-medium leading-none"
|
||||
>
|
||||
Full Name
|
||||
</label>
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
className="bg-transparent"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full font-semibold">
|
||||
Login
|
||||
<ArrowRight className="ml-2 w-4 h-4" />
|
||||
</Button>
|
||||
</form>
|
||||
{/* Header */}
|
||||
<div className="text-center space-y-3 mb-6">
|
||||
<div className="mx-auto w-20 h-20 flex items-center justify-center rounded-full bg-white/30">
|
||||
<MessagesSquare className="w-10 h-10 text-blue" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-blue">
|
||||
User Login
|
||||
</h1>
|
||||
</div>
|
||||
<footer className="px-8 py-4 border-t border-border bg-muted/50 rounded-b-xl text-center text-xs text-muted-foreground">
|
||||
Sentiengeeks
|
||||
</footer>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="mb-4 p-3 rounded-xl bg-red-500/20 border border-red-400/30 text-red-700 text-sm text-center">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Form */}
|
||||
<form onSubmit={handleLogin} className="space-y-5">
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Enter your name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="rounded-full bg-white/80 border-none shadow-md placeholder:text-muted-foreground"
|
||||
required
|
||||
disabled={submitting}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={submitting || !name.trim()}
|
||||
className="w-full rounded-full bg-primary text-primary-foreground shadow-lg hover:opacity-90"
|
||||
>
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 w-4 h-4 animate-spin" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Continue
|
||||
<ArrowRight className="ml-2 w-4 h-4" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
17
src/app/providers.tsx
Normal file
17
src/app/providers.tsx
Normal file
@ -0,0 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { ReactNode } from "react";
|
||||
import { AuthProvider } from "@/context/AuthContext";
|
||||
import { SocketProvider } from "@/context/SocketContext";
|
||||
|
||||
/**
|
||||
* Client-side providers wrapper.
|
||||
* Wraps the entire app with Auth → Socket context layers.
|
||||
*/
|
||||
export function Providers({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<SocketProvider>{children}</SocketProvider>
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
112
src/components/ui/avatar.tsx
Normal file
112
src/components/ui/avatar.tsx
Normal file
@ -0,0 +1,112 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Avatar as AvatarPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
|
||||
size?: "default" | "sm" | "lg"
|
||||
}) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarImage({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn(
|
||||
"aspect-square size-full rounded-full object-cover",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="avatar-badge"
|
||||
className={cn(
|
||||
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
|
||||
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
|
||||
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
|
||||
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="avatar-group"
|
||||
className={cn(
|
||||
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarGroupCount({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="avatar-group-count"
|
||||
className={cn(
|
||||
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Avatar,
|
||||
AvatarImage,
|
||||
AvatarFallback,
|
||||
AvatarGroup,
|
||||
AvatarGroupCount,
|
||||
AvatarBadge,
|
||||
}
|
||||
117
src/context/AuthContext.tsx
Normal file
117
src/context/AuthContext.tsx
Normal file
@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
useCallback,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { loginWithName } from "@/lib/api";
|
||||
|
||||
// Represents logged-in user data stored in app
|
||||
interface AuthUser {
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
// Values available globally from AuthContext
|
||||
interface AuthContextValue {
|
||||
user: AuthUser | null;
|
||||
isLoading: boolean;
|
||||
login: (name: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
// Context
|
||||
|
||||
// Create authentication context
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
// Key used to store auth data in browser storage
|
||||
const STORAGE_KEY = "chat_app_auth";
|
||||
|
||||
// Provider
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
// Stores current logged-in user
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
|
||||
// Tracks whether auth state is still being loaded
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
// Runs once when app loads → restores user from localStorage
|
||||
useEffect(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
|
||||
if (stored) {
|
||||
const parsed: AuthUser = JSON.parse(stored);
|
||||
|
||||
// Only set user if data is valid
|
||||
if (parsed.token && parsed.username) {
|
||||
setUser(parsed);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// If corrupted data exists, remove it
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// LOGIN
|
||||
|
||||
// Logs user in using API and saves data locally
|
||||
const login = useCallback(
|
||||
async (name: string) => {
|
||||
const data = await loginWithName(name);
|
||||
|
||||
const authUser: AuthUser = {
|
||||
token: data.token,
|
||||
username: data.username,
|
||||
};
|
||||
|
||||
// Save user in localStorage for persistence
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(authUser));
|
||||
|
||||
// Update app state
|
||||
setUser(authUser);
|
||||
|
||||
// Redirect to chat page after login
|
||||
router.push("/chat");
|
||||
},
|
||||
[router],
|
||||
);
|
||||
|
||||
// LOGOUT
|
||||
|
||||
// Clears user session and redirects to login page
|
||||
const logout = useCallback(() => {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
setUser(null);
|
||||
router.push("/login");
|
||||
}, [router]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, isLoading, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// Custom hook to access auth state anywhere in app
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
|
||||
if (!ctx) {
|
||||
throw new Error("useAuth must be used inside <AuthProvider>");
|
||||
}
|
||||
|
||||
return ctx;
|
||||
}
|
||||
223
src/context/SocketContext.tsx
Normal file
223
src/context/SocketContext.tsx
Normal file
@ -0,0 +1,223 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
useRef,
|
||||
useCallback,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { io, Socket } from "socket.io-client";
|
||||
import { useAuth } from "./AuthContext";
|
||||
import { API_BASE_URL } from "@/lib/api";
|
||||
|
||||
// Shape of a chat message coming from the server
|
||||
export interface ChatMessage {
|
||||
_id?: string;
|
||||
roomId: string;
|
||||
senderId: string;
|
||||
username: string;
|
||||
text: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
// System messages related to a room (join/leave/info)
|
||||
export interface RoomNotice {
|
||||
roomId: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Everything that the socket context will provide to the app
|
||||
interface SocketContextValue {
|
||||
socket: Socket | null;
|
||||
isConnected: boolean;
|
||||
mySocketId: string | null;
|
||||
|
||||
// join / leave / send chat messages
|
||||
joinRoom: (roomId: string) => void;
|
||||
leaveRoom: (roomId: string) => void;
|
||||
sendMessage: (roomId: string, text: string) => void;
|
||||
|
||||
// chat state stored globally
|
||||
messages: ChatMessage[];
|
||||
notices: RoomNotice[];
|
||||
currentRoom: string | null;
|
||||
setCurrentRoom: (roomId: string | null) => void;
|
||||
clearMessages: () => void;
|
||||
}
|
||||
|
||||
//context
|
||||
// Create a global socket context
|
||||
const SocketContext = createContext<SocketContextValue | undefined>(undefined);
|
||||
|
||||
/* Provider */
|
||||
|
||||
export function SocketProvider({ children }: { children: ReactNode }) {
|
||||
const { user } = useAuth();
|
||||
|
||||
// Keep socket instance in a ref so it persists without rerenders
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
|
||||
// Connection status
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
|
||||
// Store current socket id assigned by server
|
||||
const [mySocketId, setMySocketId] = useState<string | null>(null);
|
||||
|
||||
// All chat messages received
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
|
||||
// System notices (join/leave/info messages)
|
||||
const [notices, setNotices] = useState<RoomNotice[]>([]);
|
||||
|
||||
// Currently active chat room
|
||||
const [currentRoom, setCurrentRoom] = useState<string | null>(null);
|
||||
|
||||
// Connect to socket when user logs in, disconnect when logged out
|
||||
useEffect(() => {
|
||||
if (!user?.token) {
|
||||
// If user logs out, close socket connection
|
||||
if (socketRef.current) {
|
||||
socketRef.current.disconnect();
|
||||
socketRef.current = null;
|
||||
setIsConnected(false);
|
||||
setMySocketId(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// If already connected, don't reconnect again
|
||||
if (socketRef.current?.connected) return;
|
||||
|
||||
// Create socket connection with auth token
|
||||
const socket = io(`${API_BASE_URL}/chat`, {
|
||||
auth: { token: `Bearer ${user.token}` },
|
||||
transports: ["websocket", "polling"],
|
||||
});
|
||||
|
||||
socketRef.current = socket;
|
||||
|
||||
/* ---------------- Server Events ---------------- */
|
||||
|
||||
// When connection is successfully established
|
||||
socket.on("connect", () => {
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
// When server confirms who you are
|
||||
socket.on(
|
||||
"connected",
|
||||
(data: { YourId: string; username: string; message: string }) => {
|
||||
setMySocketId(data.YourId);
|
||||
console.log("[Socket] Connected:", data.message);
|
||||
},
|
||||
);
|
||||
|
||||
// When socket disconnects
|
||||
socket.on("disconnect", () => {
|
||||
setIsConnected(false);
|
||||
setMySocketId(null);
|
||||
console.log("[Socket] Disconnected");
|
||||
});
|
||||
|
||||
// If authentication fails
|
||||
socket.on("authError", (data: { mesage?: string }) => {
|
||||
console.error("[Socket] Auth error:", data.mesage);
|
||||
socket.disconnect();
|
||||
});
|
||||
|
||||
// General server messages
|
||||
socket.on("serverNotice", (message: string) => {
|
||||
console.log("[Socket] Server notice:", message);
|
||||
});
|
||||
|
||||
//- Room Events
|
||||
|
||||
// When you join a room
|
||||
socket.on("roomJoined", (data: { roomId: string; message: string }) => {
|
||||
console.log("[Socket] Room joined:", data.message);
|
||||
});
|
||||
|
||||
// When you leave a room
|
||||
socket.on("roomLeft", (data: { roomId: string }) => {
|
||||
console.log("[Socket] Room left:", data.roomId);
|
||||
});
|
||||
|
||||
// System messages inside a room
|
||||
socket.on("roomNotice", (data: RoomNotice) => {
|
||||
setNotices((prev) => [...prev, data]);
|
||||
});
|
||||
|
||||
// New chat message received
|
||||
socket.on("roomMessage", (data: ChatMessage) => {
|
||||
setMessages((prev) => [...prev, data]);
|
||||
});
|
||||
|
||||
// Room-related errors
|
||||
socket.on("roomError", (data: { message: string }) => {
|
||||
console.error("[Socket] Room error:", data.message);
|
||||
});
|
||||
|
||||
// Cleanup socket when component unmounts or token changes
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
socketRef.current = null;
|
||||
setIsConnected(false);
|
||||
setMySocketId(null);
|
||||
};
|
||||
}, [user?.token]);
|
||||
|
||||
// Actions you can call from UI
|
||||
|
||||
// Join a chat room
|
||||
const joinRoom = useCallback((roomId: string) => {
|
||||
socketRef.current?.emit("joinRoom", { roomId });
|
||||
}, []);
|
||||
|
||||
// Leave a chat room
|
||||
const leaveRoom = useCallback((roomId: string) => {
|
||||
socketRef.current?.emit("leaveRoom", { roomId });
|
||||
}, []);
|
||||
|
||||
// Send a message to a room
|
||||
const sendMessage = useCallback((roomId: string, text: string) => {
|
||||
socketRef.current?.emit("roomMessage", { roomId, text });
|
||||
}, []);
|
||||
|
||||
// Clear all messages and notices (reset chat state)
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
setNotices([]);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SocketContext.Provider
|
||||
value={{
|
||||
socket: socketRef.current,
|
||||
isConnected,
|
||||
mySocketId,
|
||||
joinRoom,
|
||||
leaveRoom,
|
||||
sendMessage,
|
||||
messages,
|
||||
notices,
|
||||
currentRoom,
|
||||
setCurrentRoom,
|
||||
clearMessages,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</SocketContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// Hook to use socket context
|
||||
|
||||
// Custom hook to access socket anywhere in app
|
||||
export function useSocket() {
|
||||
const ctx = useContext(SocketContext);
|
||||
if (!ctx) throw new Error("useSocket must be used inside <SocketProvider>");
|
||||
return ctx;
|
||||
}
|
||||
15
src/hooks/useDebounce.ts
Normal file
15
src/hooks/useDebounce.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export function useDebounce<T>(value: T, delay: number = 300) {
|
||||
const [debouncedValue, setDebouncedValue] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedValue(value);
|
||||
}, delay);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [value, delay]);
|
||||
|
||||
return debouncedValue;
|
||||
}
|
||||
55
src/lib/api.ts
Normal file
55
src/lib/api.ts
Normal file
@ -0,0 +1,55 @@
|
||||
// Base URL for the NestJS backend API
|
||||
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL;
|
||||
|
||||
/**
|
||||
* POST /auth/token
|
||||
* Authenticates (or creates) a user by name and returns a JWT token.
|
||||
*/
|
||||
export async function loginWithName(name: string): Promise<{ token: string; username: string }> {
|
||||
const res = await fetch(`${API_BASE_URL}/auth/token`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({}));
|
||||
throw new Error(error.message || "Login failed");
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /users
|
||||
* Fetches all registered users.
|
||||
*/
|
||||
export async function fetchAllUsers(): Promise<any[]> {
|
||||
const res = await fetch(`${API_BASE_URL}/users`);
|
||||
if (!res.ok) throw new Error("Failed to fetch users");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /conversations
|
||||
* Fetches all conversations.
|
||||
*/
|
||||
export async function fetchConversations(): Promise<any[]> {
|
||||
const res = await fetch(`${API_BASE_URL}/conversations`);
|
||||
if (!res.ok) throw new Error("Failed to fetch conversations");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /conversations
|
||||
* Creates a new conversation.
|
||||
*/
|
||||
export async function createConversation(data: any): Promise<any> {
|
||||
const res = await fetch(`${API_BASE_URL}/conversations`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) throw new Error("Failed to create conversation");
|
||||
return res.json();
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user