feat(channel): add channel creation with API, modal UI, and context state update
This commit is contained in:
parent
4e6bf60577
commit
21a49ff1d9
4 changed files with 320 additions and 54 deletions
73
app/api/channels/route.ts
Normal file
73
app/api/channels/route.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
/**
|
||||||
|
* @file app/api/channels/route.ts
|
||||||
|
* @description API route handler for creating new channels within a server.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/db";
|
||||||
|
import { channels, members } from "@/db/schema";
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the POST request to create a new channel within a specific server.
|
||||||
|
*
|
||||||
|
* @async
|
||||||
|
* @function POST
|
||||||
|
* @param {Request} req - The incoming HTTP request containing JSON payload with `name` and `serverId`.
|
||||||
|
* @returns {Promise<NextResponse>} The created channel object with status 201, or an error response (401, 400, 403, 500).
|
||||||
|
*/
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
try {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { name, serverId } = await req.json();
|
||||||
|
|
||||||
|
if (!name?.trim() || !serverId) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Name and server ID are required" },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the user is a member of the server
|
||||||
|
const [member] = await db
|
||||||
|
.select()
|
||||||
|
.from(members)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(members.userId, session.user.id),
|
||||||
|
eq(members.serverId, serverId),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!member) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Access denied to this server" },
|
||||||
|
{ status: 403 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the channel in the database
|
||||||
|
const [newChannel] = await db
|
||||||
|
.insert(channels)
|
||||||
|
.values({
|
||||||
|
name: name.trim().toLowerCase().replace(/\s+/g, "-"),
|
||||||
|
serverId,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
return NextResponse.json(newChannel, { status: 201 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("API Channel POST error:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Internal server error" },
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
160
components/modals/CreateChannelModal.tsx
Normal file
160
components/modals/CreateChannelModal.tsx
Normal file
|
|
@ -0,0 +1,160 @@
|
||||||
|
/**
|
||||||
|
* @file components/modals/CreateChannelModal.tsx
|
||||||
|
* @description Modal dialog component for creating a new text channel within a server.
|
||||||
|
*/
|
||||||
|
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { X, Loader2 } from "lucide-react";
|
||||||
|
import { useActiveServer } from "@/lib/context/ServerContext";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Properties for the CreateChannelModal component.
|
||||||
|
*
|
||||||
|
* @interface CreateChannelModalProps
|
||||||
|
* @property {boolean} isOpen - Determines whether the modal is visible.
|
||||||
|
* @property {() => void} onClose - Callback function executed to close the modal.
|
||||||
|
* @property {string} serverId - The unique identifier of the target server where the channel is created.
|
||||||
|
*/
|
||||||
|
interface CreateChannelModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
serverId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders a modal dialog allowing users to input a name and create a new server channel.
|
||||||
|
*
|
||||||
|
* @param {CreateChannelModalProps} props - The component props.
|
||||||
|
* @param {boolean} props.isOpen - Determines whether the modal is visible.
|
||||||
|
* @param {() => void} props.onClose - Callback function executed to close the modal.
|
||||||
|
* @param {string} props.serverId - The unique identifier of the target server where the channel is created.
|
||||||
|
* @returns {JSX.Element | null} The rendered modal component or null if closed.
|
||||||
|
*/
|
||||||
|
export function CreateChannelModal({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
serverId,
|
||||||
|
}: CreateChannelModalProps) {
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
const { addChannel } = useActiveServer();
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles form submission to create a new channel via the API.
|
||||||
|
*
|
||||||
|
* @async
|
||||||
|
* @function handleSubmit
|
||||||
|
* @param {React.FormEvent} e - The form submission event.
|
||||||
|
* @returns {Promise<void>} Resolves when the channel creation request completes.
|
||||||
|
*/
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!name.trim() || isLoading) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const response = await fetch("/api/channels", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name, serverId }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to create channel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const newChannel = await response.json();
|
||||||
|
|
||||||
|
addChannel(newChannel);
|
||||||
|
|
||||||
|
setName("");
|
||||||
|
onClose();
|
||||||
|
|
||||||
|
router.push(`/servers/${serverId}/channels/${newChannel.id}`);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
setError(err instanceof Error ? err.message : "Something went wrong.");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
onClick={onClose}
|
||||||
|
className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
className="bg-surface border border-surface/50 rounded-2xl w-full max-w-md p-6 shadow-2xl relative animate-in fade-in zoom-in-95 duration-150"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="absolute top-4 right-4 text-muted hover:text-white transition-colors cursor-pointer"
|
||||||
|
>
|
||||||
|
<X className="w-5 h-5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<h2 className="text-xl font-bold text-white mb-1">Create Channel</h2>
|
||||||
|
<p className="text-sm text-muted mb-6">
|
||||||
|
Create a new text channel for messaging in this server.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-semibold text-muted uppercase tracking-wider mb-2">
|
||||||
|
Channel Name
|
||||||
|
</label>
|
||||||
|
<div className="relative flex items-center">
|
||||||
|
<span className="absolute left-3.5 text-muted text-sm font-semibold">
|
||||||
|
#
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
placeholder="new-channel"
|
||||||
|
disabled={isLoading}
|
||||||
|
autoFocus
|
||||||
|
className="w-full bg-background border border-surface/80 rounded-xl pl-8 pr-3.5 py-2.5 text-sm text-white placeholder:text-muted focus:outline-none focus:ring-2 focus:ring-accent transition-all disabled:opacity-50"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <p className="text-xs text-red-400 mt-2">{error}</p>}
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-3 pt-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="px-4 py-2 text-sm font-medium text-muted hover:text-white transition-colors cursor-pointer"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isLoading || !name.trim()}
|
||||||
|
className="px-5 py-2 bg-accent text-white font-medium text-sm rounded-xl hover:bg-accent/90 transition-all disabled:opacity-50 flex items-center gap-2 cursor-pointer"
|
||||||
|
>
|
||||||
|
{isLoading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||||
|
Create
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -1,31 +1,36 @@
|
||||||
/**
|
/**
|
||||||
* @file components/sidebar/ChannelSidebar.tsx
|
* @file components/sidebar/ChannelSidebar.tsx
|
||||||
* @description Sidebar component listing channels for the active server, or rendering direct messages when no server is active.
|
* @description Sidebar component displaying server channels, navigation toggles, and modal triggers.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useParams } from "next/navigation";
|
import { useParams } from "next/navigation";
|
||||||
import { useActiveServer } from "@/lib/context/ServerContext";
|
import { useActiveServer } from "@/lib/context/ServerContext";
|
||||||
import { DirectMessageSidebar } from "@/components/sidebar/DirectMessageSidebar";
|
import { DirectMessageSidebar } from "@/components/sidebar/DirectMessageSidebar";
|
||||||
import { useSidebarStore } from "@/lib/stores/useSidebarStore";
|
import { useSidebarStore } from "@/lib/stores/useSidebarStore";
|
||||||
import { PanelLeftClose } from "lucide-react";
|
import { CreateChannelModal } from "@/components/modals/CreateChannelModal";
|
||||||
|
import { PanelLeftClose, Plus } from "lucide-react";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders the channel sidebar for the active server or defaults to the direct message view.
|
* Renders the channel sidebar for active servers, allowing users to navigate channels or create new ones.
|
||||||
* Handles responsive sidebar toggling and highlights active channels based on URL parameters.
|
|
||||||
*
|
*
|
||||||
* @returns {JSX.Element} The rendered channel sidebar or direct message sidebar component.
|
* @returns {JSX.Element} The rendered channel sidebar container.
|
||||||
*/
|
*/
|
||||||
export function ChannelSidebar() {
|
export function ChannelSidebar() {
|
||||||
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
const params = useParams();
|
const params = useParams();
|
||||||
const currentChannelId = params?.channelId as string;
|
const currentChannelId = params?.channelId as string;
|
||||||
const { activeServer } = useActiveServer();
|
const { activeServer } = useActiveServer();
|
||||||
const { closeNav, toggleNav } = useSidebarStore();
|
const { closeNav, toggleNav } = useSidebarStore();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Closes the mobile navigation drawer when a channel link is selected on viewports smaller than 768px.
|
* Handles channel selection clicks, closing the mobile navigation sidebar on smaller viewports.
|
||||||
|
*
|
||||||
|
* @function handleChannelClick
|
||||||
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
const handleChannelClick = () => {
|
const handleChannelClick = () => {
|
||||||
if (!window.matchMedia("(min-width: 768px)").matches) {
|
if (!window.matchMedia("(min-width: 768px)").matches) {
|
||||||
|
|
@ -38,51 +43,67 @@ export function ChannelSidebar() {
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex-1 w-full md:w-72 bg-surface/50 border-r border-background flex flex-col h-full shrink-0">
|
<>
|
||||||
{/* Server Header */}
|
<div className="flex-1 w-full md:w-72 bg-surface/50 border-r border-background flex flex-col h-full shrink-0">
|
||||||
<div className="h-14 border-b border-background flex items-center justify-between px-4 font-bold text-white shadow-sm">
|
{/* Server Header */}
|
||||||
<span className="truncate">{activeServer.name}</span>
|
<div className="h-14 border-b border-background flex items-center justify-between px-4 font-bold text-white shadow-sm">
|
||||||
<button
|
<span className="truncate">{activeServer.name}</span>
|
||||||
type="button"
|
<button
|
||||||
onClick={toggleNav}
|
type="button"
|
||||||
title="Collapse the sidebar"
|
onClick={toggleNav}
|
||||||
className="p-1.5 rounded-md text-muted hover:text-white hover:bg-surface transition-colors cursor-pointer"
|
title="Collapse the sidebar"
|
||||||
>
|
className="p-1.5 rounded-md text-muted hover:text-white hover:bg-surface transition-colors cursor-pointer"
|
||||||
<PanelLeftClose className="w-5 h-5" />
|
>
|
||||||
</button>
|
<PanelLeftClose className="w-5 h-5" />
|
||||||
</div>
|
</button>
|
||||||
|
|
||||||
{/* Channel List */}
|
|
||||||
<div className="flex-1 overflow-y-auto p-3 space-y-1">
|
|
||||||
<div className="flex items-center justify-between text-xs font-semibold text-muted px-2 py-1 uppercase tracking-wider">
|
|
||||||
<span>Text Channels</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-0.5">
|
{/* Channel List */}
|
||||||
{activeServer.channels.map((channel) => {
|
<div className="flex-1 overflow-y-auto p-3 space-y-1">
|
||||||
const isActive = currentChannelId === channel.id;
|
<div className="flex items-center justify-between text-xs font-semibold text-muted px-2 py-1 uppercase tracking-wider">
|
||||||
|
<span>Text Channels</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsModalOpen(true)}
|
||||||
|
className="p-1 rounded text-muted hover:text-white hover:bg-surface transition-colors cursor-pointer"
|
||||||
|
aria-label="Create channel"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
return (
|
<div className="space-y-0.5">
|
||||||
<Link
|
{activeServer.channels.map((channel) => {
|
||||||
key={channel.id}
|
const isActive = currentChannelId === channel.id;
|
||||||
href={`/servers/${activeServer.id}/channels/${channel.id}`}
|
|
||||||
onClick={handleChannelClick}
|
return (
|
||||||
prefetch={false}
|
<Link
|
||||||
className={`flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-all group ${
|
key={channel.id}
|
||||||
isActive
|
href={`/servers/${activeServer.id}/channels/${channel.id}`}
|
||||||
? "bg-accent/50 text-white font-medium"
|
onClick={handleChannelClick}
|
||||||
: "text-muted hover:bg-surface hover:text-white"
|
prefetch={false}
|
||||||
}`}
|
className={`flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-all group ${
|
||||||
>
|
isActive
|
||||||
<span className="text-muted group-hover:text-white text-base">
|
? "bg-accent/50 text-white font-medium"
|
||||||
#
|
: "text-muted hover:bg-surface hover:text-white"
|
||||||
</span>
|
}`}
|
||||||
<span className="truncate">{channel.name}</span>
|
>
|
||||||
</Link>
|
<span className="text-muted group-hover:text-white text-base">
|
||||||
);
|
#
|
||||||
})}
|
</span>
|
||||||
|
<span className="truncate">{channel.name}</span>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
<CreateChannelModal
|
||||||
|
isOpen={isModalOpen}
|
||||||
|
onClose={() => setIsModalOpen(false)}
|
||||||
|
serverId={activeServer.id}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,7 @@ export interface ServerMember {
|
||||||
interface ServerContextType {
|
interface ServerContextType {
|
||||||
activeServer: ServerWithChannels | null;
|
activeServer: ServerWithChannels | null;
|
||||||
setActiveServer: (server: ServerWithChannels | null) => void;
|
setActiveServer: (server: ServerWithChannels | null) => void;
|
||||||
|
addChannel: (channel: Channel) => void;
|
||||||
members: ServerMember[];
|
members: ServerMember[];
|
||||||
setMembers: (members: ServerMember[]) => void;
|
setMembers: (members: ServerMember[]) => void;
|
||||||
}
|
}
|
||||||
|
|
@ -46,6 +47,7 @@ interface ServerContextType {
|
||||||
const ServerContext = createContext<ServerContextType>({
|
const ServerContext = createContext<ServerContextType>({
|
||||||
activeServer: null,
|
activeServer: null,
|
||||||
setActiveServer: () => {},
|
setActiveServer: () => {},
|
||||||
|
addChannel: () => {},
|
||||||
members: [],
|
members: [],
|
||||||
setMembers: () => {},
|
setMembers: () => {},
|
||||||
});
|
});
|
||||||
|
|
@ -63,21 +65,31 @@ export function ServerProvider({ children }: { children: React.ReactNode }) {
|
||||||
);
|
);
|
||||||
const [members, setMembers] = useState<ServerMember[]>([]);
|
const [members, setMembers] = useState<ServerMember[]>([]);
|
||||||
|
|
||||||
|
const addChannel = (channel: Channel) => {
|
||||||
|
setActiveServer((prev) => {
|
||||||
|
if (!prev || prev.id !== channel.serverId) return prev;
|
||||||
|
return {
|
||||||
|
...prev,
|
||||||
|
channels: [...prev.channels, channel],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ServerContext.Provider
|
<ServerContext.Provider
|
||||||
value={{ activeServer, setActiveServer, members, setMembers }}
|
value={{
|
||||||
|
activeServer,
|
||||||
|
setActiveServer,
|
||||||
|
addChannel,
|
||||||
|
members,
|
||||||
|
setMembers,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</ServerContext.Provider>
|
</ServerContext.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom hook to access the current ServerContext state.
|
|
||||||
*
|
|
||||||
* @throws {Error} Throws an error if used outside of a `ServerProvider`.
|
|
||||||
* @returns {ServerContextType} The server context value containing active server state and member management functions.
|
|
||||||
*/
|
|
||||||
export function useActiveServer() {
|
export function useActiveServer() {
|
||||||
const context = useContext(ServerContext);
|
const context = useContext(ServerContext);
|
||||||
if (!context) {
|
if (!context) {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue