feat(servers): add server deletion modal, API endpoint, and delete button to header
This commit is contained in:
parent
b1acb6cf51
commit
cc8677ae37
7 changed files with 347 additions and 30 deletions
|
|
@ -1,6 +1,6 @@
|
|||
/**
|
||||
* @file app/servers/[serverId]/channels/[channelId]/page.tsx
|
||||
* @description Page component for viewing a specific channel and its messages.
|
||||
* @description Dynamic page component for displaying a specific channel within a server, including its messages and chat input.
|
||||
*/
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
|
|
@ -9,33 +9,39 @@ import { ChatInput } from "@/components/chat/ChatInput";
|
|||
import { ChatMessages } from "@/components/chat/ChatMessages";
|
||||
import { getChannelById } from "@/lib/services/channel.service";
|
||||
import { getChannelMessages } from "@/lib/services/message.service";
|
||||
import { getServerById } from "@/lib/services/server.service";
|
||||
|
||||
/**
|
||||
* Server component that fetches and renders a channel's details and message feed based on route parameters.
|
||||
* Renders the channel view by fetching server, channel, and message details in parallel based on route parameters.
|
||||
*
|
||||
* @param {Object} props - The component props.
|
||||
* @param {Promise<{ channelId: string }>} props.params - Async route parameters containing the channel ID.
|
||||
* @returns {Promise<JSX.Element>} The rendered channel page view or triggers a 404 notFound error.
|
||||
* @param {Promise<{ serverId: string; channelId: string }>} props.params - A promise resolving to the route parameters containing serverId and channelId.
|
||||
* @returns {Promise<JSX.Element>} The rendered channel page interface.
|
||||
*/
|
||||
export default async function ChannelPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ channelId: string }>;
|
||||
params: Promise<{ serverId: string; channelId: string }>;
|
||||
}) {
|
||||
const { channelId } = await params;
|
||||
const { serverId, channelId } = await params;
|
||||
|
||||
// Parallel loading of channel data and messages
|
||||
const [channel, channelMessages] = await Promise.all([
|
||||
// Parallel loading of server, channel, and messages
|
||||
const [server, channel, channelMessages] = await Promise.all([
|
||||
getServerById(serverId),
|
||||
getChannelById(channelId),
|
||||
getChannelMessages(channelId),
|
||||
]);
|
||||
|
||||
if (!channel) redirect("/");
|
||||
if (!channel || !server) redirect("/");
|
||||
|
||||
return (
|
||||
<div className="flex p-4 flex-col h-full bg-background">
|
||||
{/* Header */}
|
||||
<AppHeader title={channel.name} showMembersButton />
|
||||
<AppHeader
|
||||
title={channel.name}
|
||||
showMembersButton
|
||||
server={{ id: server.id, name: server.name }}
|
||||
/>
|
||||
|
||||
{/* Messages Feed */}
|
||||
<ChatMessages channelName={channel.name} messages={channelMessages} />
|
||||
|
|
|
|||
52
app/api/servers/[serverId]/route.ts
Normal file
52
app/api/servers/[serverId]/route.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
/**
|
||||
* @file app/api/servers/[serverId]/route.ts
|
||||
* @description API route handler for deleting a server.
|
||||
*/
|
||||
|
||||
import { auth } from "@/auth";
|
||||
import { db } from "@/db";
|
||||
import { servers } from "@/db/schema";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
* Handles DELETE requests to remove a server if the requesting user is the owner.
|
||||
*
|
||||
* @param {Request} req - The incoming HTTP request.
|
||||
* @param {Object} context - Route parameters context.
|
||||
* @param {Promise<{ serverId: string }>} context.params - Async route parameters containing the `serverId`.
|
||||
* @returns {Promise<NextResponse>} A JSON response with the deleted server data on success, or an appropriate error response.
|
||||
*/
|
||||
export async function DELETE(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ serverId: string }> },
|
||||
) {
|
||||
try {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return new NextResponse("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const { serverId } = await params;
|
||||
|
||||
// Delete the server only if the current user is the OWNER
|
||||
const [deletedServer] = await db
|
||||
.delete(servers)
|
||||
.where(
|
||||
and(eq(servers.id, serverId), eq(servers.ownerId, session.user.id)),
|
||||
)
|
||||
.returning();
|
||||
|
||||
if (!deletedServer) {
|
||||
return new NextResponse("Server not found or forbidden", { status: 404 });
|
||||
}
|
||||
|
||||
revalidatePath("/", "layout");
|
||||
return NextResponse.json(deletedServer);
|
||||
} catch (error) {
|
||||
console.error("[SERVER_DELETE]", error);
|
||||
return new NextResponse("Internal Error", { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@
|
|||
|
||||
import { useSidebarStore } from "@/lib/stores/useSidebarStore";
|
||||
import { PanelLeftOpen, PanelLeftClose, Users, Hash } from "lucide-react";
|
||||
import { ServerSettingsMenu } from "./ServerSettingsMenu";
|
||||
|
||||
/**
|
||||
* Properties for the AppHeader component.
|
||||
|
|
@ -14,27 +15,34 @@ import { PanelLeftOpen, PanelLeftClose, Users, Hash } from "lucide-react";
|
|||
* @interface AppHeaderProps
|
||||
* @property {string} [title] - Optional channel or page title to display in the header.
|
||||
* @property {boolean} [showMembersButton=false] - Flag indicating whether to display the member list toggle button.
|
||||
* @property {{ id: string; name: string }} [server] - Optional server details to enable server settings & delete functionality.
|
||||
*/
|
||||
interface AppHeaderProps {
|
||||
title?: string;
|
||||
showMembersButton?: boolean;
|
||||
server?: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the application header bar with navigation controls, dynamic page titles, and member list toggle capability.
|
||||
* Renders the application header bar with navigation controls, dynamic page titles, server settings, and member list toggle capability.
|
||||
*
|
||||
* @param {AppHeaderProps} props - The component props.
|
||||
* @param {string} [props.title] - Optional channel or page title to display.
|
||||
* @param {boolean} [props.showMembersButton=false] - Whether to show the button toggling the right sidebar/member panel.
|
||||
* @param {{ id: string; name: string }} [props.server] - Optional server object containing id and name for settings menu.
|
||||
* @returns {JSX.Element} The header component visual structure.
|
||||
*/
|
||||
export function AppHeader({
|
||||
title,
|
||||
showMembersButton = false,
|
||||
server,
|
||||
}: AppHeaderProps) {
|
||||
const { isNavOpen, toggleNav, toggleMembers } = useSidebarStore();
|
||||
|
||||
const hasContent = !isNavOpen || !!title || showMembersButton;
|
||||
const hasContent = !isNavOpen || !!title || showMembersButton || !!server;
|
||||
|
||||
return (
|
||||
<div
|
||||
|
|
@ -68,17 +76,25 @@ export function AppHeader({
|
|||
)}
|
||||
</div>
|
||||
|
||||
{/* Button for the member bar */}
|
||||
{showMembersButton && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleMembers}
|
||||
title="Mitgliederliste umschalten"
|
||||
className="p-1.5 rounded-md text-muted hover:text-white hover:bg-surface transition-colors cursor-pointer"
|
||||
>
|
||||
<Users className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
{/* Right Action Buttons */}
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Server Settings Menu (contains the Delete Server action) */}
|
||||
{server && (
|
||||
<ServerSettingsMenu serverId={server.id} serverName={server.name} />
|
||||
)}
|
||||
|
||||
{/* Button for the member bar */}
|
||||
{showMembersButton && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleMembers}
|
||||
title="Toggle Member List"
|
||||
className="p-1.5 rounded-md text-muted hover:text-white hover:bg-surface transition-colors cursor-pointer"
|
||||
>
|
||||
<Users className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
94
components/layout/ServerSettingsMenu.tsx
Normal file
94
components/layout/ServerSettingsMenu.tsx
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
/**
|
||||
* @file components/layout/ServerSettingsMenu.tsx
|
||||
* @description Header menu button providing server-level action options like deleting a server.
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { Settings, Trash2 } from "lucide-react";
|
||||
import { DeleteServerModal } from "@/components/modals/DeleteServerModal";
|
||||
|
||||
/**
|
||||
* Props for the ServerSettingsMenu component.
|
||||
*
|
||||
* @interface ServerSettingsMenuProps
|
||||
* @property {string} serverId - The unique identifier of the server.
|
||||
* @property {string} serverName - The name of the server used for display and verification during deletion.
|
||||
*/
|
||||
interface ServerSettingsMenuProps {
|
||||
serverId: string;
|
||||
serverName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a dropdown menu button for server settings, including an option to open the server deletion modal.
|
||||
*
|
||||
* @param {ServerSettingsMenuProps} props - The component props.
|
||||
* @param {string} props.serverId - The unique identifier of the server.
|
||||
* @param {string} props.serverName - The display name of the server.
|
||||
* @returns {JSX.Element} The rendered server settings dropdown menu and modal component.
|
||||
*/
|
||||
export function ServerSettingsMenu({
|
||||
serverId,
|
||||
serverName,
|
||||
}: ServerSettingsMenuProps) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Close dropdown when clicking outside
|
||||
useEffect(() => {
|
||||
/**
|
||||
* Handles mouse click events outside of the menu container to close the dropdown.
|
||||
*
|
||||
* @param {MouseEvent} event - The mouse click event object.
|
||||
*/
|
||||
function handleClickOutside(event: MouseEvent) {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="relative" ref={menuRef}>
|
||||
{/* Icon Button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen((prev) => !prev)}
|
||||
title="Server Settings"
|
||||
className="p-1.5 rounded-md text-muted hover:text-white hover:bg-surface transition-colors cursor-pointer"
|
||||
>
|
||||
<Settings className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
{/* Dropdown Menu */}
|
||||
{isOpen && (
|
||||
<div className="absolute right-0 mt-2 w-48 bg-surface border border-surface/50 rounded-xl shadow-xl p-1.5 z-50 animate-in fade-in zoom-in-95 duration-100">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsOpen(false);
|
||||
setIsDeleteModalOpen(true);
|
||||
}}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 text-xs font-medium text-rose-500 hover:bg-rose-500/10 rounded-lg transition-colors cursor-pointer"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
Delete Server
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Delete Modal */}
|
||||
<DeleteServerModal
|
||||
isOpen={isDeleteModalOpen}
|
||||
serverId={serverId}
|
||||
serverName={serverName}
|
||||
onClose={() => setIsDeleteModalOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -6,7 +6,6 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { X, Loader2 } from "lucide-react";
|
||||
import {
|
||||
SERVER_COLOR_CLASSES,
|
||||
|
|
@ -32,7 +31,6 @@ interface CreateServerModalProps {
|
|||
* @returns {JSX.Element | null} The rendered modal component or null when hidden.
|
||||
*/
|
||||
export function CreateServerModal({ isOpen, onClose }: CreateServerModalProps) {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState("");
|
||||
const [color, setColor] = useState("bg-indigo-500");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
|
@ -83,15 +81,15 @@ export function CreateServerModal({ isOpen, onClose }: CreateServerModalProps) {
|
|||
};
|
||||
|
||||
return (
|
||||
/* Outer Backdrop: Schließt das Modal bei Klick */
|
||||
/* Outer Backdrop */
|
||||
<div
|
||||
onClick={onClose}
|
||||
className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4 cursor-pointer"
|
||||
className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4"
|
||||
>
|
||||
{/* Inner Modal Content: Verhindert Event-Bubbling, damit Klicks hier drinnen das Modal NICHT schließen */}
|
||||
{/* Inner Modal Content */}
|
||||
<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 cursor-default"
|
||||
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"
|
||||
|
|
|
|||
128
components/modals/DeleteServerModal.tsx
Normal file
128
components/modals/DeleteServerModal.tsx
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
/**
|
||||
* @file components/modals/DeleteServerModal.tsx
|
||||
* @description Confirmation modal for permanently deleting a server.
|
||||
*/
|
||||
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { X, Loader2, AlertTriangle } from "lucide-react";
|
||||
|
||||
/**
|
||||
* Properties for the DeleteServerModal component.
|
||||
*
|
||||
* @interface DeleteServerModalProps
|
||||
* @property {boolean} isOpen - Indicates whether the modal dialog is currently visible.
|
||||
* @property {() => void} onClose - Callback function to handle closing the modal dialog.
|
||||
* @property {string} serverId - The unique identifier of the server to be deleted.
|
||||
* @property {string} serverName - The name of the server displayed in the confirmation message.
|
||||
*/
|
||||
interface DeleteServerModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
serverId: string;
|
||||
serverName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a confirmation modal allowing users to permanently delete a server.
|
||||
*
|
||||
* @param {DeleteServerModalProps} props - Component properties.
|
||||
* @returns {JSX.Element | null} The modal component or null if not open.
|
||||
*/
|
||||
export function DeleteServerModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
serverId,
|
||||
serverName,
|
||||
}: DeleteServerModalProps) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
/**
|
||||
* Sends a DELETE request to remove the server and redirects to the home route upon success.
|
||||
*/
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await fetch(`/api/servers/${serverId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to delete server.");
|
||||
}
|
||||
|
||||
onClose();
|
||||
|
||||
window.location.href = "/";
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : "Something went wrong.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
/* Outer Backdrop */
|
||||
<div
|
||||
onClick={onClose}
|
||||
className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4"
|
||||
>
|
||||
{/* Inner Modal Content */}
|
||||
<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>
|
||||
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<div className="p-2 bg-rose-500/10 text-rose-500 rounded-xl">
|
||||
<AlertTriangle className="w-6 h-6" />
|
||||
</div>
|
||||
<h2 className="text-xl font-bold text-white">Delete Server</h2>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted mb-6">
|
||||
Are you sure you want to delete{" "}
|
||||
<span className="font-semibold text-white">{serverName}</span>? This
|
||||
action cannot be undone and will permanently remove all channels and
|
||||
messages.
|
||||
</p>
|
||||
|
||||
{error && <p className="text-xs text-rose-400 mb-4">{error}</p>}
|
||||
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
<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="button"
|
||||
onClick={handleDelete}
|
||||
disabled={isLoading}
|
||||
className="px-5 py-2 bg-rose-600 text-white font-medium text-sm rounded-xl hover:bg-rose-700 transition-all disabled:opacity-50 flex items-center gap-2 cursor-pointer"
|
||||
>
|
||||
{isLoading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
Delete Server
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@
|
|||
*/
|
||||
|
||||
import { db } from "@/db";
|
||||
import { members, servers } from "@/db/schema";
|
||||
import { members, servers, channels } from "@/db/schema";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
|
||||
|
|
@ -82,3 +82,26 @@ export async function getUserServers(userId: string) {
|
|||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a single server by its ID without checking membership.
|
||||
*
|
||||
* @param {string} serverId - The unique identifier of the server to retrieve.
|
||||
* @returns {Promise<Object | null>} The server record or null if not found/invalid ID.
|
||||
*/
|
||||
export async function getServerById(serverId: string) {
|
||||
if (!uuidSchema.safeParse(serverId).success) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const server = await db.query.servers.findFirst({
|
||||
where: eq(servers.id, serverId),
|
||||
});
|
||||
|
||||
return server ?? null;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching server by ID ${serverId}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue