feat: add admin role management with user authentication checks and update sidebar for admin access

This commit is contained in:
Julien Froidefond
2025-10-16 22:39:04 +02:00
parent 83f523c11a
commit 9899789fce
25 changed files with 1636 additions and 6 deletions

View File

@@ -0,0 +1,88 @@
"use client";
import { useState, useCallback } from "react";
import type { AdminUserData } from "@/lib/services/admin.service";
import { StatsCards } from "./StatsCards";
import { UsersTable } from "./UsersTable";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
interface AdminContentProps {
initialUsers: AdminUserData[];
initialStats: {
totalUsers: number;
totalAdmins: number;
usersWithKomga: number;
usersWithPreferences: number;
};
}
export function AdminContent({ initialUsers, initialStats }: AdminContentProps) {
const [users, setUsers] = useState(initialUsers);
const [stats, setStats] = useState(initialStats);
const [isRefreshing, setIsRefreshing] = useState(false);
const { toast } = useToast();
const refreshData = useCallback(async () => {
setIsRefreshing(true);
try {
const [usersResponse, statsResponse] = await Promise.all([
fetch("/api/admin/users"),
fetch("/api/admin/stats"),
]);
if (!usersResponse.ok || !statsResponse.ok) {
throw new Error("Erreur lors du rafraîchissement");
}
const [newUsers, newStats] = await Promise.all([
usersResponse.json(),
statsResponse.json(),
]);
setUsers(newUsers);
setStats(newStats);
toast({
title: "Données rafraîchies",
description: "Les données ont été mises à jour",
});
} catch {
toast({
variant: "destructive",
title: "Erreur",
description: "Impossible de rafraîchir les données",
});
} finally {
setIsRefreshing(false);
}
}, [toast]);
return (
<div className="container mx-auto px-4 py-8">
<div className="max-w-7xl mx-auto space-y-8">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">Administration</h1>
<p className="text-muted-foreground mt-2">
Gérez les utilisateurs de la plateforme
</p>
</div>
<Button onClick={refreshData} disabled={isRefreshing}>
<RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? "animate-spin" : ""}`} />
Rafraîchir
</Button>
</div>
<StatsCards stats={stats} />
<div>
<h2 className="text-2xl font-semibold mb-4">Utilisateurs</h2>
<UsersTable users={users} onUserUpdated={refreshData} />
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,92 @@
"use client";
import { useState } from "react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useToast } from "@/components/ui/use-toast";
import type { AdminUserData } from "@/lib/services/admin.service";
interface DeleteUserDialogProps {
user: AdminUserData;
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
}
export function DeleteUserDialog({
user,
open,
onOpenChange,
onSuccess,
}: DeleteUserDialogProps) {
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const handleDelete = async () => {
setIsLoading(true);
try {
const response = await fetch(`/api/admin/users/${user.id}`, {
method: "DELETE",
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la suppression");
}
toast({
title: "Succès",
description: "L'utilisateur a été supprimé",
});
onSuccess();
} catch (error) {
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
setIsLoading(false);
}
};
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Êtes-vous sûr?</AlertDialogTitle>
<AlertDialogDescription>
Vous allez supprimer l&apos;utilisateur <strong>{user.email}</strong>.
<br />
Cette action est irréversible et supprimera également :
<ul className="list-disc list-inside mt-2">
<li>Sa configuration Komga</li>
<li>Ses préférences</li>
<li>Ses favoris ({user._count?.favorites || 0})</li>
</ul>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isLoading}>Annuler</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={isLoading}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isLoading ? "Suppression..." : "Supprimer"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}

View File

@@ -0,0 +1,128 @@
"use client";
import { useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
import type { AdminUserData } from "@/lib/services/admin.service";
interface EditUserDialogProps {
user: AdminUserData;
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
}
const AVAILABLE_ROLES = [
{ value: "ROLE_USER", label: "User" },
{ value: "ROLE_ADMIN", label: "Admin" },
];
export function EditUserDialog({
user,
open,
onOpenChange,
onSuccess,
}: EditUserDialogProps) {
const [selectedRoles, setSelectedRoles] = useState<string[]>(user.roles);
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const handleRoleToggle = (role: string) => {
setSelectedRoles((prev) =>
prev.includes(role) ? prev.filter((r) => r !== role) : [...prev, role]
);
};
const handleSubmit = async () => {
if (selectedRoles.length === 0) {
toast({
variant: "destructive",
title: "Erreur",
description: "L'utilisateur doit avoir au moins un rôle",
});
return;
}
setIsLoading(true);
try {
const response = await fetch(`/api/admin/users/${user.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ roles: selectedRoles }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la mise à jour");
}
toast({
title: "Succès",
description: "Les rôles ont été mis à jour",
});
onSuccess();
} catch (error) {
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
} finally {
setIsLoading(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Modifier l&apos;utilisateur</DialogTitle>
<DialogDescription>
Gérer les rôles de <strong>{user.email}</strong>
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>Rôles</Label>
{AVAILABLE_ROLES.map((role) => (
<div key={role.value} className="flex items-center space-x-2">
<Checkbox
id={role.value}
checked={selectedRoles.includes(role.value)}
onCheckedChange={() => handleRoleToggle(role.value)}
disabled={isLoading}
/>
<Label htmlFor={role.value} className="font-normal cursor-pointer">
{role.label}
</Label>
</div>
))}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isLoading}>
Annuler
</Button>
<Button onClick={handleSubmit} disabled={isLoading}>
{isLoading ? "Enregistrement..." : "Enregistrer"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,170 @@
"use client";
import { useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
import { Lock } from "lucide-react";
import type { AdminUserData } from "@/lib/services/admin.service";
interface ResetPasswordDialogProps {
user: AdminUserData;
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
}
export function ResetPasswordDialog({
user,
open,
onOpenChange,
onSuccess,
}: ResetPasswordDialogProps) {
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const handleSubmit = async () => {
if (!newPassword || !confirmPassword) {
toast({
variant: "destructive",
title: "Erreur",
description: "Veuillez remplir tous les champs",
});
return;
}
if (newPassword !== confirmPassword) {
toast({
variant: "destructive",
title: "Erreur",
description: "Les mots de passe ne correspondent pas",
});
return;
}
if (newPassword.length < 8) {
toast({
variant: "destructive",
title: "Erreur",
description: "Le mot de passe doit contenir au moins 8 caractères",
});
return;
}
setIsLoading(true);
try {
const response = await fetch(`/api/admin/users/${user.id}/password`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ newPassword }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la réinitialisation");
}
toast({
title: "Succès",
description: "Le mot de passe a été réinitialisé",
});
setNewPassword("");
setConfirmPassword("");
onSuccess();
} catch (error) {
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
} finally {
setIsLoading(false);
}
};
const handleOpenChange = (open: boolean) => {
if (!open) {
setNewPassword("");
setConfirmPassword("");
}
onOpenChange(open);
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Réinitialiser le mot de passe</DialogTitle>
<DialogDescription>
Définir un nouveau mot de passe pour <strong>{user.email}</strong>
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="newPassword">Nouveau mot de passe</Label>
<div className="relative">
<Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
id="newPassword"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="pl-9"
placeholder="Minimum 8 caractères"
disabled={isLoading}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirmer le mot de passe</Label>
<div className="relative">
<Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="pl-9"
placeholder="Confirmer le nouveau mot de passe"
disabled={isLoading}
/>
</div>
</div>
<p className="text-sm text-muted-foreground">
Le mot de passe doit contenir au moins 8 caractères, une majuscule et un chiffre.
</p>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isLoading}
>
Annuler
</Button>
<Button onClick={handleSubmit} disabled={isLoading}>
{isLoading ? "Réinitialisation..." : "Réinitialiser"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,63 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Users, Shield, Settings, Bookmark } from "lucide-react";
interface StatsCardsProps {
stats: {
totalUsers: number;
totalAdmins: number;
usersWithKomga: number;
usersWithPreferences: number;
};
}
export function StatsCards({ stats }: StatsCardsProps) {
const cards = [
{
title: "Utilisateurs totaux",
value: stats.totalUsers,
icon: Users,
description: "Comptes enregistrés",
},
{
title: "Administrateurs",
value: stats.totalAdmins,
icon: Shield,
description: "Avec privilèges admin",
},
{
title: "Config Komga",
value: stats.usersWithKomga,
icon: Bookmark,
description: "Utilisateurs configurés",
},
{
title: "Préférences",
value: stats.usersWithPreferences,
icon: Settings,
description: "Préférences personnalisées",
},
];
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
{cards.map((card) => {
const Icon = card.icon;
return (
<Card key={card.title}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{card.title}</CardTitle>
<Icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{card.value}</div>
<p className="text-xs text-muted-foreground">{card.description}</p>
</CardContent>
</Card>
);
})}
</div>
);
}

View File

@@ -0,0 +1,170 @@
"use client";
import { useState } from "react";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Pencil, Trash2, Check, X, KeyRound } from "lucide-react";
import type { AdminUserData } from "@/lib/services/admin.service";
import { EditUserDialog } from "./EditUserDialog";
import { DeleteUserDialog } from "./DeleteUserDialog";
import { ResetPasswordDialog } from "./ResetPasswordDialog";
interface UsersTableProps {
users: AdminUserData[];
onUserUpdated: () => void;
}
export function UsersTable({ users, onUserUpdated }: UsersTableProps) {
const [editingUser, setEditingUser] = useState<AdminUserData | null>(null);
const [deletingUser, setDeletingUser] = useState<AdminUserData | null>(null);
const [resettingPasswordUser, setResettingPasswordUser] = useState<AdminUserData | null>(null);
return (
<>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Rôles</TableHead>
<TableHead>Config Komga</TableHead>
<TableHead>Préférences</TableHead>
<TableHead>Favoris</TableHead>
<TableHead>Créé le</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center text-muted-foreground">
Aucun utilisateur
</TableCell>
</TableRow>
) : (
users.map((user) => (
<TableRow key={user.id}>
<TableCell className="font-medium">{user.email}</TableCell>
<TableCell>
<div className="flex gap-1">
{user.roles.map((role) => (
<Badge
key={role}
variant={role === "ROLE_ADMIN" ? "default" : "secondary"}
>
{role.replace("ROLE_", "")}
</Badge>
))}
</div>
</TableCell>
<TableCell>
{user.hasKomgaConfig ? (
<div className="flex items-center gap-2">
<Check className="h-4 w-4 text-green-500" />
<span className="text-xs text-green-600 dark:text-green-400">Configuré</span>
</div>
) : (
<div className="flex items-center gap-2">
<X className="h-4 w-4 text-red-500" />
<span className="text-xs text-red-600 dark:text-red-400">Non configuré</span>
</div>
)}
</TableCell>
<TableCell>
{user.hasPreferences ? (
<div className="flex items-center gap-2">
<Check className="h-4 w-4 text-green-500" />
<span className="text-xs text-green-600 dark:text-green-400">Oui</span>
</div>
) : (
<div className="flex items-center gap-2">
<X className="h-4 w-4 text-red-500" />
<span className="text-xs text-red-600 dark:text-red-400">Non</span>
</div>
)}
</TableCell>
<TableCell>{user._count?.favorites || 0}</TableCell>
<TableCell>
{new Date(user.createdAt).toLocaleDateString("fr-FR")}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => setEditingUser(user)}
title="Modifier les rôles"
>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setResettingPasswordUser(user)}
title="Réinitialiser le mot de passe"
>
<KeyRound className="h-4 w-4 text-blue-500" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setDeletingUser(user)}
title="Supprimer l'utilisateur"
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{editingUser && (
<EditUserDialog
user={editingUser}
open={!!editingUser}
onOpenChange={(open) => !open && setEditingUser(null)}
onSuccess={() => {
setEditingUser(null);
onUserUpdated();
}}
/>
)}
{resettingPasswordUser && (
<ResetPasswordDialog
user={resettingPasswordUser}
open={!!resettingPasswordUser}
onOpenChange={(open) => !open && setResettingPasswordUser(null)}
onSuccess={() => {
setResettingPasswordUser(null);
}}
/>
)}
{deletingUser && (
<DeleteUserDialog
user={deletingUser}
open={!!deletingUser}
onOpenChange={(open) => !open && setDeletingUser(null)}
onSuccess={() => {
setDeletingUser(null);
onUserUpdated();
}}
/>
)}
</>
);
}

View File

@@ -20,9 +20,10 @@ interface ClientLayoutProps {
children: React.ReactNode;
initialLibraries: KomgaLibrary[];
initialFavorites: KomgaSeries[];
userIsAdmin?: boolean;
}
export default function ClientLayout({ children, initialLibraries = [], initialFavorites = [] }: ClientLayoutProps) {
export default function ClientLayout({ children, initialLibraries = [], initialFavorites = [], userIsAdmin = false }: ClientLayoutProps) {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const pathname = usePathname();
@@ -77,7 +78,8 @@ export default function ClientLayout({ children, initialLibraries = [], initialF
isOpen={isSidebarOpen}
onClose={handleCloseSidebar}
initialLibraries={initialLibraries}
initialFavorites={initialFavorites}
initialFavorites={initialFavorites}
userIsAdmin={userIsAdmin}
/>
)}
<main className={`${!isPublicRoute ? "container pt-safe" : ""}`}>{children}</main>

View File

@@ -1,6 +1,6 @@
"use client";
import { Home, Library, Settings, LogOut, RefreshCw, Star, Download, User } from "lucide-react";
import { Home, Library, Settings, LogOut, RefreshCw, Star, Download, User, Shield } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { signOut } from "next-auth/react";
@@ -18,9 +18,10 @@ interface SidebarProps {
onClose: () => void;
initialLibraries: KomgaLibrary[];
initialFavorites: KomgaSeries[];
userIsAdmin?: boolean;
}
export function Sidebar({ isOpen, onClose, initialLibraries, initialFavorites }: SidebarProps) {
export function Sidebar({ isOpen, onClose, initialLibraries, initialFavorites, userIsAdmin = false }: SidebarProps) {
const { t } = useTranslate();
const pathname = usePathname();
const router = useRouter();
@@ -294,6 +295,18 @@ export function Sidebar({ isOpen, onClose, initialLibraries, initialFavorites }:
<Settings className="mr-2 h-4 w-4" />
{t("sidebar.settings.preferences")}
</button>
{userIsAdmin && (
<button
onClick={() => handleLinkClick("/admin")}
className={cn(
"w-full flex items-center rounded-lg px-3 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground",
pathname === "/admin" ? "bg-accent" : "transparent"
)}
>
<Shield className="mr-2 h-4 w-4" />
{t("sidebar.admin")}
</button>
)}
</div>
</div>
</div>

View File

@@ -0,0 +1,117 @@
"use client";
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
AlertDialogHeader.displayName = "AlertDialogHeader";
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
{...props}
/>
);
AlertDialogFooter.displayName = "AlertDialogFooter";
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

View File

@@ -0,0 +1,29 @@
"use client";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };

View File

@@ -0,0 +1,104 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};

View File

@@ -0,0 +1,96 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
);
Table.displayName = "Table";
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
));
TableHeader.displayName = "TableHeader";
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
));
TableBody.displayName = "TableBody";
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}
{...props}
/>
));
TableFooter.displayName = "TableFooter";
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
)
);
TableRow.displayName = "TableRow";
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
));
TableHead.displayName = "TableHead";
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
));
TableCell.displayName = "TableCell";
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />
));
TableCaption.displayName = "TableCaption";
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };