Sure! Below is an example of a page.tsx file for a dashboard that manages Discord bot hosting and Minecraft server hosting using PufferPanel’s API. This example uses Next.js with TypeScript and ShadCN UI components. The dashboard includes sections to list and manage Discord Bots and Minecraft Servers.
Before diving into the code, make sure you have the following set up in your project:
-
Next.js with TypeScript: If you haven't set it up yet, you can create a new Next.js project with TypeScript using:
npx create-next-app@latest --typescript
-
ShadCN UI: Install ShadCN UI components and dependencies:
npm install shadcn-ui
Ensure that you have Tailwind CSS configured as ShadCN UI relies on it.
-
PufferPanel API Integration: This example assumes you have API endpoints set up to interact with PufferPanel for managing servers and bots. You might need to create API routes in Next.js (/pages/api/...) to handle requests securely.
Here’s the dashboard/page.tsx file:
// app/dashboard/page.tsx
import React, { useEffect, useState } from 'react';
import {
Button,
Table,
TableHeader,
TableRow,
TableCell,
TableBody,
TableHead,
Loader,
Modal,
Input,
} from 'shadcn-ui';
import axios from 'axios';
import { useRouter } from 'next/router';
// Define TypeScript interfaces
interface DiscordBot {
id: string;
name: string;
status: 'running' | 'stopped';
createdAt: string;
}
interface MinecraftServer {
id: string;
name: string;
ip: string;
status: 'running' | 'stopped';
createdAt: string;
}
const DashboardPage: React.FC = () => {
const [discordBots, setDiscordBots] = useState<DiscordBot[]>([]);
const [minecraftServers, setMinecraftServers] = useState<MinecraftServer[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
const [newBotName, setNewBotName] = useState<string>('');
const router = useRouter();
useEffect(() => {
// Fetch data from your API routes
const fetchData = async () => {
try {
setLoading(true);
const [botsRes, serversRes] = await Promise.all([
axios.get('/api/discord-bots'),
axios.get('/api/minecraft-servers'),
]);
setDiscordBots(botsRes.data);
setMinecraftServers(serversRes.data);
} catch (error) {
console.error('Error fetching data:', error);
// Handle error (e.g., redirect to login if unauthorized)
} finally {
setLoading(false);
}
};
fetchData();
}, []);
const handleStartBot = async (botId: string) => {
try {
await axios.post(`/api/discord-bots/${botId}/start`);
setDiscordBots((prev) =>
prev.map((bot) =>
bot.id === botId ? { ...bot, status: 'running' } : bot
)
);
} catch (error) {
console.error('Error starting bot:', error);
}
};
const handleStopBot = async (botId: string) => {
try {
await axios.post(`/api/discord-bots/${botId}/stop`);
setDiscordBots((prev) =>
prev.map((bot) =>
bot.id === botId ? { ...bot, status: 'stopped' } : bot
)
);
} catch (error) {
console.error('Error stopping bot:', error);
}
};
const handleStartServer = async (serverId: string) => {
try {
await axios.post(`/api/minecraft-servers/${serverId}/start`);
setMinecraftServers((prev) =>
prev.map((server) =>
server.id === serverId ? { ...server, status: 'running' } : server
)
);
} catch (error) {
console.error('Error starting server:', error);
}
};
const handleStopServer = async (serverId: string) => {
try {
await axios.post(`/api/minecraft-servers/${serverId}/stop`);
setMinecraftServers((prev) =>
prev.map((server) =>
server.id === serverId ? { ...server, status: 'stopped' } : server
)
);
} catch (error) {
console.error('Error stopping server:', error);
}
};
const handleCreateBot = async () => {
try {
const res = await axios.post('/api/discord-bots', { name: newBotName });
setDiscordBots((prev) => [...prev, res.data]);
setNewBotName('');
setIsModalOpen(false);
} catch (error) {
console.error('Error creating bot:', error);
}
};
if (loading) {
return (
<div className="flex justify-center items-center h-screen">
<Loader size="lg" />
</div>
);
}
return (
<div className="p-6 bg-gray-100 min-h-screen">
<header className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold">Dashboard</h1>
<Button onClick={() => router.push('/logout')}>Logout</Button>
</header>
{/* Discord Bots Section */}
<section className="mb-12">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-semibold">Discord Bots</h2>
<Button onClick={() => setIsModalOpen(true)}>Add New Bot</Button>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Status</TableHead>
<TableHead>Created At</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{discordBots.map((bot) => (
<TableRow key={bot.id}>
<TableCell>{bot.id}</TableCell>
<TableCell>{bot.name}</TableCell>
<TableCell>
{bot.status === 'running' ? (
<span className="text-green-500">Running</span>
) : (
<span className="text-red-500">Stopped</span>
)}
</TableCell>
<TableCell>{new Date(bot.createdAt).toLocaleString()}</TableCell>
<TableCell>
{bot.status === 'running' ? (
<Button
variant="warning"
size="sm"
onClick={() => handleStopBot(bot.id)}
>
Stop
</Button>
) : (
<Button
variant="success"
size="sm"
onClick={() => handleStartBot(bot.id)}
>
Start
</Button>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</section>
{/* Minecraft Servers Section */}
<section>
<h2 className="text-xl font-semibold mb-4">Minecraft Servers</h2>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>IP Address</TableHead>
<TableHead>Status</TableHead>
<TableHead>Created At</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{minecraftServers.map((server) => (
<TableRow key={server.id}>
<TableCell>{server.id}</TableCell>
<TableCell>{server.name}</TableCell>
<TableCell>{server.ip}</TableCell>
<TableCell>
{server.status === 'running' ? (
<span className="text-green-500">Running</span>
) : (
<span className="text-red-500">Stopped</span>
)}
</TableCell>
<TableCell>{new Date(server.createdAt).toLocaleString()}</TableCell>
<TableCell>
{server.status === 'running' ? (
<Button
variant="warning"
size="sm"
onClick={() => handleStopServer(server.id)}
>
Stop
</Button>
) : (
<Button
variant="success"
size="sm"
onClick={() => handleStartServer(server.id)}
>
Start
</Button>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</section>
{/* Add New Bot Modal */}
<Modal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
title="Add New Discord Bot"
>
<div className="space-y-4">
<Input
label="Bot Name"
value={newBotName}
onChange={(e) => setNewBotName(e.target.value)}
placeholder="Enter bot name"
/>
<div className="flex justify-end space-x-2">
<Button variant="secondary" onClick={() => setIsModalOpen(false)}>
Cancel
</Button>
<Button variant="primary" onClick={handleCreateBot}>
Create
</Button>
</div>
</div>
</Modal>
</div>
);
};
export default DashboardPage;
Explanation of the Code
-
Imports and Interfaces:
- Import necessary components from
shadcn-ui, axios for HTTP requests, and useRouter from Next.js for navigation.
- Define TypeScript interfaces
DiscordBot and MinecraftServer to type the data structures.
-
State Management:
discordBots and minecraftServers to store the lists fetched from the API.
loading to handle the loading state.
isModalOpen and newBotName to manage the modal state for creating a new Discord bot.
-
Data Fetching (useEffect):
- Fetch Discord bots and Minecraft servers data from respective API routes when the component mounts.
- Handle errors appropriately.
-
Action Handlers:
handleStartBot, handleStopBot, handleStartServer, handleStopServer: These functions send POST requests to start or stop bots and servers and update the state based on the response.
handleCreateBot: Sends a POST request to create a new Discord bot and updates the discordBots state.
-
Loading State:
- While data is being fetched, a loading spinner is displayed.
-
Rendering the Dashboard:
- Header: Displays the dashboard title and a Logout button.
- Discord Bots Section:
- Displays a table of Discord bots with options to start/stop each bot.
- An "Add New Bot" button opens a modal to create a new bot.
- Minecraft Servers Section:
- Displays a table of Minecraft servers with options to start/stop each server.
- Add New Bot Modal:
- A modal that contains a form to input the new bot’s name and create it.
Setting Up API Routes
For the above dashboard to work, you need to set up corresponding API routes in your Next.js project. Here's an example structure for the API routes:
-
Discord Bots APIs:
GET /api/discord-bots - Fetch the list of Discord bots.
POST /api/discord-bots - Create a new Discord bot.
POST /api/discord-bots/[id]/start - Start a specific Discord bot.
POST /api/discord-bots/[id]/stop - Stop a specific Discord bot.
-
Minecraft Servers APIs:
GET /api/minecraft-servers - Fetch the list of Minecraft servers.
POST /api/minecraft-servers/[id]/start - Start a specific Minecraft server.
POST /api/minecraft-servers/[id]/stop - Stop a specific Minecraft server.
Note: Implement these API routes with necessary authentication and PufferPanel client integration to manage your servers and bots.
Styling with Tailwind CSS
ShadCN UI relies on Tailwind CSS for styling. Ensure that Tailwind CSS is properly configured in your project. Here’s a basic setup:
-
Install Tailwind CSS:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
-
Configure tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
'./app/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [],
};
-
Add Tailwind Directives to globals.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
Additional Recommendations
-
Authentication: Ensure that the dashboard is protected and only accessible to authorized users. You can use NextAuth or another authentication library.
-
Error Handling: Enhance error handling to provide user feedback using toast notifications or inline messages.
-
Optimizations: Implement features like pagination, search, and sorting for the tables if you have many bots or servers.
-
Permissions: Handle different user roles and permissions if applicable.
-
Security: Secure your API routes, especially those that perform start/stop actions.
This example provides a foundational structure for your dashboard. You can expand upon it by adding more features, refining the UI, and integrating it fully with the PufferPanel API.