feat(web): 重构前端架构并完善认证系统

主要变更:
- 使用 shadcn/ui 重构 UI 组件库
- 实现 Zustand 状态管理(authStore、uiStore)
- 使用 axios 封装 HTTP 客户端,支持 token 自动刷新和加密
- 添加登录/注册表单,支持登录后跳转回原页面
- 实现 Dashboard 布局(Sidebar、Header、UserNav)
- 添加用户管理页面(DataTable、分页、编辑弹窗)
- 添加个人中心和系统设置页面
- 实现全局错误边界和 ErrorBoundary 组件
- 使用 Next.js 16 proxy.ts 替代 middleware.ts
- 修复 ThemeToggle 和 LoginForm 的水合错误

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
charilezhou
2026-01-16 21:08:55 +08:00
parent c958271027
commit c2d9aaedc9
93 changed files with 8941 additions and 758 deletions

View File

@@ -214,6 +214,22 @@ NEXT_PUBLIC_ENCRYPTION_KEY=<与后端相同的密钥>
生成密钥: `openssl rand -base64 32`
## Documentation
项目文档统一存放在 `docs/` 目录下:
```
docs/
├── web/ # 前端相关文档
│ └── DESIGN.md # Web 前端设计文档
├── api/ # 后端相关文档
└── shared/ # 共享模块文档
```
| 文档 | 说明 |
|------|------|
| `docs/web/DESIGN.md` | Web 前端整体设计(技术栈、目录结构、状态管理、实施计划) |
## Key Files
- `deploy/docker-compose.yml` - PostgreSQL + Redis 容器配置

21
apps/web/components.json Normal file
View File

@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@@ -10,20 +10,52 @@
"clean": "rm -rf .next .turbo node_modules"
},
"dependencies": {
"@hookform/resolvers": "^5.2.2",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-avatar": "^1.1.11",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-progress": "^1.1.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.2.8",
"@seclusion/shared": "workspace:*",
"@tanstack/react-query": "^5.90.18",
"@tanstack/react-table": "^8.21.3",
"axios": "^1.13.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"next": "^16.1.1",
"next-themes": "^0.4.6",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"react-dom": "^19.0.0",
"react-hook-form": "^7.71.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"zod": "^4.3.5",
"zustand": "^5.0.10"
},
"devDependencies": {
"@seclusion/eslint-config": "workspace:*",
"@seclusion/typescript-config": "workspace:*",
"@tailwindcss/postcss": "^4.1.18",
"@types/node": "^22.10.2",
"@types/react": "^19.0.2",
"@types/react-dom": "^19.0.2",
"autoprefixer": "^10.4.23",
"dotenv-cli": "^11.0.0",
"eslint": "^9.39.0",
"eslint-config-next": "^16.1.1",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.18",
"typescript": "^5.7.2"
}
}

View File

@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
'@tailwindcss/postcss': {},
},
};
export default config;

View File

@@ -0,0 +1,37 @@
import Link from 'next/link';
import { ThemeToggle } from '@/components/layout/ThemeToggle';
import { siteConfig } from '@/config/site';
export default function AuthLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="min-h-screen flex flex-col">
{/* 顶部导航 */}
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="container flex h-14 items-center justify-between">
<Link href="/" className="font-bold text-xl">
{siteConfig.name}
</Link>
<ThemeToggle />
</div>
</header>
{/* 主内容区 */}
<main className="flex-1 flex items-center justify-center p-4">
<div className="w-full max-w-md">{children}</div>
</main>
{/* 页脚 */}
<footer className="border-t py-4">
<div className="container text-center text-sm text-muted-foreground">
&copy; {new Date().getFullYear()} {siteConfig.name}. All rights
reserved.
</div>
</footer>
</div>
);
}

View File

@@ -0,0 +1,79 @@
import type { Metadata } from 'next';
import Link from 'next/link';
import { Suspense } from 'react';
import { LoginForm } from '@/components/forms/LoginForm';
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
export const metadata: Metadata = {
title: '登录',
};
// 登录表单加载占位符
function LoginFormSkeleton() {
return (
<div className="space-y-4">
<div className="space-y-2">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-10 w-full" />
</div>
<div className="space-y-2">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-10 w-full" />
</div>
<div className="space-y-2">
<Skeleton className="h-4 w-16" />
<div className="flex gap-2">
<Skeleton className="h-10 flex-1" />
<Skeleton className="h-10 w-24" />
</div>
</div>
<Skeleton className="h-10 w-full" />
</div>
);
}
export default function LoginPage() {
return (
<Card>
<CardHeader className="space-y-1">
<CardTitle className="text-2xl text-center"></CardTitle>
<CardDescription className="text-center">
</CardDescription>
</CardHeader>
<CardContent>
<Suspense fallback={<LoginFormSkeleton />}>
<LoginForm />
</Suspense>
</CardContent>
<CardFooter className="flex flex-col space-y-4">
<div className="text-sm text-muted-foreground text-center">
<Link
href="/forgot-password"
className="hover:text-primary underline underline-offset-4"
>
</Link>
</div>
<div className="text-sm text-muted-foreground text-center">
{' '}
<Link
href="/register"
className="hover:text-primary underline underline-offset-4"
>
</Link>
</div>
</CardFooter>
</Card>
);
}

View File

@@ -0,0 +1,43 @@
import type { Metadata } from 'next';
import Link from 'next/link';
import { RegisterForm } from '@/components/forms/RegisterForm';
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/components/ui/card';
export const metadata: Metadata = {
title: '注册',
};
export default function RegisterPage() {
return (
<Card>
<CardHeader className="space-y-1">
<CardTitle className="text-2xl text-center"></CardTitle>
<CardDescription className="text-center">
使
</CardDescription>
</CardHeader>
<CardContent>
<RegisterForm />
</CardContent>
<CardFooter>
<div className="text-sm text-muted-foreground text-center w-full">
{' '}
<Link
href="/login"
className="hover:text-primary underline underline-offset-4"
>
</Link>
</div>
</CardFooter>
</Card>
);
}

View File

@@ -0,0 +1,29 @@
import type { Metadata } from 'next';
import {
DashboardStats,
DashboardOverview,
RecentActivity,
} from '@/components/dashboard';
export const metadata: Metadata = {
title: '仪表盘',
};
export default function DashboardPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight"></h1>
<p className="text-muted-foreground"></p>
</div>
<DashboardStats />
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
<DashboardOverview />
<RecentActivity />
</div>
</div>
);
}

View File

@@ -0,0 +1,13 @@
'use client';
import { ErrorBoundary } from '@/components/shared/ErrorBoundary';
export default function DashboardError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return <ErrorBoundary error={error} reset={reset} />;
}

View File

@@ -0,0 +1,26 @@
'use client';
import { Header } from '@/components/layout/Header';
import { Sidebar, MobileSidebar } from '@/components/layout/Sidebar';
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="min-h-screen flex">
{/* <20><>面端侧边栏 */}
<Sidebar />
{/* 移动端侧边栏 */}
<MobileSidebar />
{/* 主内容区 */}
<div className="flex-1 flex flex-col">
<Header />
<main className="flex-1 p-4 md:p-6">{children}</main>
</div>
</div>
);
}

View File

@@ -0,0 +1,48 @@
import type { Metadata } from 'next';
import { PasswordForm } from '@/components/forms/PasswordForm';
import { ProfileForm } from '@/components/forms/ProfileForm';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
export const metadata: Metadata = {
title: '个人中心',
};
export default function ProfilePage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight"></h1>
<p className="text-muted-foreground"></p>
</div>
<div className="grid gap-6 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<ProfileForm />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<PasswordForm />
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -0,0 +1,23 @@
import type { Metadata } from 'next';
import { ThemeSettings, SidebarSettings } from '@/components/settings';
export const metadata: Metadata = {
title: '系统设置',
};
export default function SettingsPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight"></h1>
<p className="text-muted-foreground"></p>
</div>
<div className="grid gap-6 md:grid-cols-2">
<ThemeSettings />
<SidebarSettings />
</div>
</div>
);
}

View File

@@ -0,0 +1,37 @@
import type { Metadata } from 'next';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { UsersTable } from '@/components/users/UsersTable';
export const metadata: Metadata = {
title: '用户管理',
};
export default function UsersPage() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight"></h1>
<p className="text-muted-foreground"></p>
</div>
</div>
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<UsersTable />
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,13 @@
'use client';
import { ErrorBoundary } from '@/components/shared/ErrorBoundary';
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return <ErrorBoundary error={error} reset={reset} />;
}

View File

@@ -0,0 +1,57 @@
'use client';
import { AlertCircle, RefreshCw } from 'lucide-react';
import { useEffect } from 'react';
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error('全局错误:', error);
}, [error]);
return (
<html lang="zh-CN">
<body>
<div className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
<div className="w-full max-w-md rounded-lg border bg-white p-6 shadow-lg">
<div className="text-center">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
<AlertCircle className="h-6 w-6 text-red-600" />
</div>
<h1 className="mb-2 text-xl font-semibold text-gray-900">
</h1>
<p className="mb-4 text-sm text-gray-500">
</p>
{process.env.NODE_ENV === 'development' && (
<div className="mb-4 rounded-md bg-gray-100 p-3 text-left">
<p className="text-sm font-medium text-red-600">
{error.message}
</p>
{error.digest && (
<p className="mt-1 text-xs text-gray-500">
ID: {error.digest}
</p>
)}
</div>
)}
<button
onClick={reset}
className="inline-flex items-center rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-800"
>
<RefreshCw className="mr-2 h-4 w-4" />
</button>
</div>
</div>
</div>
</body>
</html>
);
}

View File

@@ -1,27 +1,87 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@import "tailwindcss";
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 255, 255, 255;
--background-end-rgb: 255, 255, 255;
@theme {
--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
--color-background: hsl(0 0% 100%);
--color-foreground: hsl(222.2 84% 4.9%);
--color-card: hsl(0 0% 100%);
--color-card-foreground: hsl(222.2 84% 4.9%);
--color-popover: hsl(0 0% 100%);
--color-popover-foreground: hsl(222.2 84% 4.9%);
--color-primary: hsl(222.2 47.4% 11.2%);
--color-primary-foreground: hsl(210 40% 98%);
--color-secondary: hsl(210 40% 96.1%);
--color-secondary-foreground: hsl(222.2 47.4% 11.2%);
--color-muted: hsl(210 40% 96.1%);
--color-muted-foreground: hsl(215.4 16.3% 46.9%);
--color-accent: hsl(210 40% 96.1%);
--color-accent-foreground: hsl(222.2 47.4% 11.2%);
--color-destructive: hsl(0 84.2% 60.2%);
--color-destructive-foreground: hsl(210 40% 98%);
--color-border: hsl(214.3 31.8% 91.4%);
--color-input: hsl(214.3 31.8% 91.4%);
--color-ring: hsl(222.2 84% 4.9%);
--color-chart-1: hsl(12 76% 61%);
--color-chart-2: hsl(173 58% 39%);
--color-chart-3: hsl(197 37% 24%);
--color-chart-4: hsl(43 74% 66%);
--color-chart-5: hsl(27 87% 67%);
--color-sidebar: hsl(0 0% 98%);
--color-sidebar-foreground: hsl(240 5.3% 26.1%);
--color-sidebar-primary: hsl(240 5.9% 10%);
--color-sidebar-primary-foreground: hsl(0 0% 98%);
--color-sidebar-accent: hsl(240 4.8% 95.9%);
--color-sidebar-accent-foreground: hsl(240 5.9% 10%);
--color-sidebar-border: hsl(220 13% 91%);
--color-sidebar-ring: hsl(217.2 91.2% 59.8%);
--radius-lg: 0.5rem;
--radius-md: calc(var(--radius-lg) - 2px);
--radius-sm: calc(var(--radius-lg) - 4px);
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
.dark {
--color-background: hsl(222.2 84% 4.9%);
--color-foreground: hsl(210 40% 98%);
--color-card: hsl(222.2 84% 4.9%);
--color-card-foreground: hsl(210 40% 98%);
--color-popover: hsl(222.2 84% 4.9%);
--color-popover-foreground: hsl(210 40% 98%);
--color-primary: hsl(210 40% 98%);
--color-primary-foreground: hsl(222.2 47.4% 11.2%);
--color-secondary: hsl(217.2 32.6% 17.5%);
--color-secondary-foreground: hsl(210 40% 98%);
--color-muted: hsl(217.2 32.6% 17.5%);
--color-muted-foreground: hsl(215 20.2% 65.1%);
--color-accent: hsl(217.2 32.6% 17.5%);
--color-accent-foreground: hsl(210 40% 98%);
--color-destructive: hsl(0 62.8% 30.6%);
--color-destructive-foreground: hsl(210 40% 98%);
--color-border: hsl(217.2 32.6% 17.5%);
--color-input: hsl(217.2 32.6% 17.5%);
--color-ring: hsl(212.7 26.8% 83.9%);
--color-chart-1: hsl(220 70% 50%);
--color-chart-2: hsl(160 60% 45%);
--color-chart-3: hsl(30 80% 55%);
--color-chart-4: hsl(280 65% 60%);
--color-chart-5: hsl(340 75% 55%);
--color-sidebar: hsl(240 5.9% 10%);
--color-sidebar-foreground: hsl(240 4.8% 95.9%);
--color-sidebar-primary: hsl(224.3 76.3% 48%);
--color-sidebar-primary-foreground: hsl(0 0% 100%);
--color-sidebar-accent: hsl(240 3.7% 15.9%);
--color-sidebar-accent-foreground: hsl(240 4.8% 95.9%);
--color-sidebar-border: hsl(240 3.7% 15.9%);
--color-sidebar-ring: hsl(217.2 91.2% 59.8%);
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}

View File

@@ -1,10 +1,15 @@
import type { Metadata } from 'next';
import { Providers } from './providers';
import './globals.css';
export const metadata: Metadata = {
title: 'Seclusion',
description: 'A monorepo template with Next.js and NestJS',
title: {
default: 'Seclusion',
template: '%s | Seclusion',
},
description: '基于 Next.js + NestJS 的 Monorepo 项目模板',
};
export default function RootLayout({
@@ -13,8 +18,10 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN">
<body>{children}</body>
<html lang="zh-CN" suppressHydrationWarning>
<body className="min-h-screen bg-background font-sans antialiased">
<Providers>{children}</Providers>
</body>
</html>
);
}

View File

@@ -1,37 +1,167 @@
import { formatDate } from '@seclusion/shared';
import { ArrowRight, Github, Layers, Lock, Zap } from 'lucide-react';
import Link from 'next/link';
import { ThemeToggle } from '@/components/layout/ThemeToggle';
import { Button } from '@/components/ui/button';
import { siteConfig } from '@/config/site';
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-center p-24">
<div className="text-center">
<h1 className="text-4xl font-bold mb-4">Seclusion</h1>
<p className="text-lg text-gray-600 mb-8">A monorepo template with Next.js + NestJS</p>
<div className="flex gap-4 justify-center flex-wrap">
<a
href="http://localhost:4000/health"
className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
>
API Health Check
</a>
<a
href="http://localhost:4000/api/docs"
target="_blank"
rel="noopener noreferrer"
className="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition"
>
API Docs
</a>
<a
href="/test/users"
className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition"
>
</a>
<div className="min-h-screen flex flex-col">
{/* 导航栏 */}
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="container flex h-14 items-center justify-between">
<Link href="/" className="font-bold text-xl">
{siteConfig.name}
</Link>
<div className="flex items-center gap-4">
<ThemeToggle />
<Button asChild variant="ghost" size="sm">
<Link href="/login"></Link>
</Button>
<Button asChild size="sm">
<Link href="/register"></Link>
</Button>
</div>
</div>
<p className="mt-8 text-sm text-gray-400">
Generated at: {formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')}
</p>
</div>
</main>
</header>
{/* Hero 区域 */}
<main className="flex-1">
<section className="container py-24 md:py-32">
<div className="mx-auto max-w-3xl text-center">
<h1 className="text-4xl font-bold tracking-tight sm:text-5xl md:text-6xl">
<span className="text-primary"> </span>
</h1>
<p className="mt-6 text-lg text-muted-foreground md:text-xl">
Next.js 16 + NestJS 10 Monorepo
</p>
<div className="mt-10 flex flex-wrap items-center justify-center gap-4">
<Button asChild size="lg">
<Link href="/dashboard">
使
<ArrowRight className="ml-2 h-4 w-4" />
</Link>
</Button>
<Button asChild variant="outline" size="lg">
<a
href="https://github.com"
target="_blank"
rel="noopener noreferrer"
>
<Github className="mr-2 h-4 w-4" />
GitHub
</a>
</Button>
</div>
</div>
</section>
{/* 特性介绍 */}
<section className="container py-16 md:py-24">
<div className="mx-auto max-w-5xl">
<h2 className="text-center text-3xl font-bold tracking-tight">
</h2>
<p className="mt-4 text-center text-muted-foreground">
</p>
<div className="mt-12 grid gap-8 md:grid-cols-3">
<div className="rounded-lg border bg-card p-6">
<div className="flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
<Layers className="h-6 w-6 text-primary" />
</div>
<h3 className="mt-4 text-lg font-semibold">Monorepo </h3>
<p className="mt-2 text-sm text-muted-foreground">
使 pnpm workspace + Turborepo
</p>
</div>
<div className="rounded-lg border bg-card p-6">
<div className="flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
<Lock className="h-6 w-6 text-primary" />
</div>
<h3 className="mt-4 text-lg font-semibold"></h3>
<p className="mt-2 text-sm text-muted-foreground">
AES-256-GCM JWT
</p>
</div>
<div className="rounded-lg border bg-card p-6">
<div className="flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
<Zap className="h-6 w-6 text-primary" />
</div>
<h3 className="mt-4 text-lg font-semibold"></h3>
<p className="mt-2 text-sm text-muted-foreground">
TypeScript ESLint + Prettier
</p>
</div>
</div>
</div>
</section>
{/* 快速链接 */}
<section className="container py-16 md:py-24">
<div className="mx-auto max-w-3xl">
<h2 className="text-center text-3xl font-bold tracking-tight">
访
</h2>
<div className="mt-8 grid gap-4 sm:grid-cols-3">
<a
href={`${siteConfig.apiUrl}/health`}
target="_blank"
rel="noopener noreferrer"
className="flex flex-col items-center rounded-lg border p-6 transition-colors hover:bg-accent"
>
<span className="text-2xl">🏥</span>
<span className="mt-2 font-medium"></span>
<span className="mt-1 text-xs text-muted-foreground">
API
</span>
</a>
<a
href={`${siteConfig.apiUrl}/api/docs`}
target="_blank"
rel="noopener noreferrer"
className="flex flex-col items-center rounded-lg border p-6 transition-colors hover:bg-accent"
>
<span className="text-2xl">📚</span>
<span className="mt-2 font-medium">API </span>
<span className="mt-1 text-xs text-muted-foreground">
Swagger
</span>
</a>
<Link
href="/test/users"
className="flex flex-col items-center rounded-lg border p-6 transition-colors hover:bg-accent"
>
<span className="text-2xl">🧪</span>
<span className="mt-2 font-medium"></span>
<span className="mt-1 text-xs text-muted-foreground">
</span>
</Link>
</div>
</div>
</section>
</main>
{/* 页脚 */}
<footer className="border-t py-8">
<div className="container text-center text-sm text-muted-foreground">
<p>&copy; {new Date().getFullYear()} {siteConfig.name}. All rights reserved.</p>
<p className="mt-2">
Built with Next.js, NestJS, and
</p>
</div>
</footer>
</div>
);
}

View File

@@ -0,0 +1,29 @@
'use client';
import { QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from 'next-themes';
import { Toaster } from '@/components/ui/sonner';
import { getQueryClient } from '@/lib/query-client';
interface ProvidersProps {
children: React.ReactNode;
}
export function Providers({ children }: ProvidersProps) {
const queryClient = getQueryClient();
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
<Toaster richColors position="top-right" />
</ThemeProvider>
</QueryClientProvider>
);
}

View File

@@ -1,606 +0,0 @@
'use client';
import { useState, useEffect, useCallback, useRef } from 'react';
import { Captcha } from '@/components/Captcha';
import { apiFetch } from '@/lib/api';
import { isEncryptionEnabled } from '@/lib/crypto';
import type {
AuthResponse,
AuthUser,
UserResponse,
PaginatedResponse,
MessageState,
RegisterFormState,
LoginFormState,
UpdateUserFormState,
RefreshTokenResponse,
} from '@/types';
import { CaptchaScene } from '@/types';
export default function UserManagementPage() {
// 认证状态
const [token, setToken] = useState<string>('');
const [refreshToken, setRefreshToken] = useState<string>('');
const [currentUser, setCurrentUser] = useState<AuthUser | null>(null);
// 用于存储 refreshToken 的 ref避免 useCallback 依赖问题
const refreshTokenRef = useRef(refreshToken);
refreshTokenRef.current = refreshToken;
// 用户列表
const [users, setUsers] = useState<UserResponse[]>([]);
const [deletedUsers, setDeletedUsers] = useState<UserResponse[]>([]);
// 表单状态
const [registerForm, setRegisterForm] = useState<RegisterFormState>({
email: '',
password: '',
name: '',
captchaId: '',
captchaCode: '',
});
const [loginForm, setLoginForm] = useState<LoginFormState>({
email: '',
password: '',
captchaId: '',
captchaCode: '',
});
const [updateForm, setUpdateForm] = useState<UpdateUserFormState>({ id: '', name: '' });
// 验证码刷新 key用于重置验证码组件
const [registerCaptchaKey, setRegisterCaptchaKey] = useState(0);
const [loginCaptchaKey, setLoginCaptchaKey] = useState(0);
// UI 状态
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<MessageState | null>(null);
const [activeTab, setActiveTab] = useState<'auth' | 'users' | 'deleted'>('auth');
// 显示消息
const showMessage = (type: 'success' | 'error', text: string) => {
setMessage({ type, text });
setTimeout(() => setMessage(null), 5000);
};
// 刷新 Token
const handleRefreshToken = useCallback(async (): Promise<boolean> => {
const currentRefreshToken = refreshTokenRef.current;
if (!currentRefreshToken) return false;
try {
const response = await apiFetch<RefreshTokenResponse>('/auth/refresh', {
method: 'POST',
body: JSON.stringify({ refreshToken: currentRefreshToken }),
});
setToken(response.accessToken);
setRefreshToken(response.refreshToken);
return true;
} catch {
// 刷新失败,清除认证状态
setToken('');
setRefreshToken('');
setCurrentUser(null);
return false;
}
}, []);
// 注册
const handleRegister = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
const response = await apiFetch<AuthResponse>('/auth/register', {
method: 'POST',
body: JSON.stringify(registerForm),
});
setToken(response.accessToken);
setRefreshToken(response.refreshToken);
setCurrentUser(response.user);
showMessage('success', '注册成功');
setRegisterForm({ email: '', password: '', name: '', captchaId: '', captchaCode: '' });
setRegisterCaptchaKey((k) => k + 1); // 刷新验证码
} catch (error) {
showMessage('error', error instanceof Error ? error.message : '注册失败');
setRegisterCaptchaKey((k) => k + 1); // 失败后刷新验证码
} finally {
setLoading(false);
}
};
// 登录
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
const response = await apiFetch<AuthResponse>('/auth/login', {
method: 'POST',
body: JSON.stringify(loginForm),
});
setToken(response.accessToken);
setRefreshToken(response.refreshToken);
setCurrentUser(response.user);
showMessage('success', '登录成功');
setLoginForm({ email: '', password: '', captchaId: '', captchaCode: '' });
setLoginCaptchaKey((k) => k + 1); // 刷新验证码
} catch (error) {
showMessage('error', error instanceof Error ? error.message : '登录失败');
setLoginCaptchaKey((k) => k + 1); // 失败后刷新验证码
} finally {
setLoading(false);
}
};
// 获取当前用户
const fetchCurrentUser = useCallback(async () => {
if (!token) return;
try {
const user = await apiFetch<AuthUser>('/auth/me', { token });
setCurrentUser(user);
} catch (error) {
showMessage('error', error instanceof Error ? error.message : '获取用户信息失败');
}
}, [token]);
// 获取用户列表
const fetchUsers = useCallback(async () => {
if (!token) return;
setLoading(true);
try {
const response = await apiFetch<PaginatedResponse<UserResponse>>('/users', { token });
setUsers(response.items);
} catch (error) {
showMessage('error', error instanceof Error ? error.message : '获取用户列表失败');
} finally {
setLoading(false);
}
}, [token]);
// 获取已删除用户列表
const fetchDeletedUsers = useCallback(async () => {
if (!token) return;
setLoading(true);
try {
const response = await apiFetch<PaginatedResponse<UserResponse>>('/users/deleted', {
token,
});
setDeletedUsers(response.items);
} catch (error) {
showMessage('error', error instanceof Error ? error.message : '获取已删除用户列表失败');
} finally {
setLoading(false);
}
}, [token]);
// 更新用户
const handleUpdateUser = async (e: React.FormEvent) => {
e.preventDefault();
if (!updateForm.id) return;
setLoading(true);
try {
await apiFetch(`/users/${updateForm.id}`, {
method: 'PATCH',
body: JSON.stringify({ name: updateForm.name }),
token,
});
showMessage('success', '更新成功');
setUpdateForm({ id: '', name: '' });
fetchUsers();
} catch (error) {
showMessage('error', error instanceof Error ? error.message : '更新失败');
} finally {
setLoading(false);
}
};
// 删除用户
const handleDeleteUser = async (id: string) => {
if (!confirm('确定要删除该用户吗?')) return;
setLoading(true);
try {
await apiFetch(`/users/${id}`, { method: 'DELETE', token });
showMessage('success', '删除成功');
fetchUsers();
fetchDeletedUsers();
} catch (error) {
showMessage('error', error instanceof Error ? error.message : '删除失败');
} finally {
setLoading(false);
}
};
// 恢复用户
const handleRestoreUser = async (id: string) => {
setLoading(true);
try {
await apiFetch(`/users/${id}/restore`, { method: 'PATCH', token });
showMessage('success', '恢复成功');
fetchUsers();
fetchDeletedUsers();
} catch (error) {
showMessage('error', error instanceof Error ? error.message : '恢复失败');
} finally {
setLoading(false);
}
};
// 登出
const handleLogout = () => {
setToken('');
setRefreshToken('');
setCurrentUser(null);
setUsers([]);
setDeletedUsers([]);
showMessage('success', '已登出');
};
// 登录后自动获取数据
useEffect(() => {
if (token) {
fetchCurrentUser();
fetchUsers();
fetchDeletedUsers();
}
}, [token, fetchCurrentUser, fetchUsers, fetchDeletedUsers]);
return (
<main className="min-h-screen bg-gray-50 p-8">
<div className="max-w-4xl mx-auto">
{/* 标题 */}
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900"></h1>
<p className="text-gray-600 mt-2">
:{' '}
{isEncryptionEnabled() ? (
<span className="text-green-600 font-medium"></span>
) : (
<span className="text-gray-400"></span>
)}
</p>
</div>
{/* 消息提示 */}
{message && (
<div
className={`mb-4 p-4 rounded-lg ${
message.type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
}`}
>
{message.text}
</div>
)}
{/* 当前用户信息 */}
{currentUser && (
<div className="mb-6 p-4 bg-blue-50 rounded-lg flex justify-between items-center">
<div>
<span className="text-blue-800">: </span>
<span className="font-medium">{currentUser.name || currentUser.email}</span>
<span className="text-gray-500 ml-2">({currentUser.email})</span>
</div>
<div className="flex gap-2">
<button
onClick={async () => {
const success = await handleRefreshToken();
if (success) {
showMessage('success', 'Token 刷新成功');
} else {
showMessage('error', 'Token 刷新失败,请重新登录');
}
}}
disabled={loading || !refreshToken}
className="px-4 py-2 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 disabled:opacity-50"
>
Token
</button>
<button
onClick={handleLogout}
className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
>
</button>
</div>
</div>
)}
{/* 标签页 */}
<div className="flex border-b mb-6">
{(['auth', 'users', 'deleted'] as const).map((tab) => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
className={`px-6 py-3 font-medium ${
activeTab === tab
? 'border-b-2 border-blue-600 text-blue-600'
: 'text-gray-500 hover:text-gray-700'
}`}
>
{tab === 'auth' ? '认证' : tab === 'users' ? '用户列表' : '已删除用户'}
</button>
))}
</div>
{/* 认证标签页 */}
{activeTab === 'auth' && (
<div className="grid md:grid-cols-2 gap-6">
{/* 注册表单 */}
<div className="bg-white p-6 rounded-lg shadow">
<h2 className="text-xl font-semibold mb-4"></h2>
<form onSubmit={handleRegister} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
type="email"
value={registerForm.email}
onChange={(e) => setRegisterForm({ ...registerForm, email: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
type="password"
value={registerForm.password}
onChange={(e) => setRegisterForm({ ...registerForm, password: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required
minLength={6}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
()
</label>
<input
type="text"
value={registerForm.name}
onChange={(e) => setRegisterForm({ ...registerForm, name: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
</div>
<Captcha
key={registerCaptchaKey}
scene={CaptchaScene.REGISTER}
value={registerForm.captchaCode}
onChange={(captchaId, captchaCode) =>
setRegisterForm({ ...registerForm, captchaId, captchaCode })
}
disabled={loading}
/>
<button
type="submit"
disabled={loading}
className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
>
{loading ? '处理中...' : '注册'}
</button>
</form>
</div>
{/* 登录表单 */}
<div className="bg-white p-6 rounded-lg shadow">
<h2 className="text-xl font-semibold mb-4"></h2>
<form onSubmit={handleLogin} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
type="email"
value={loginForm.email}
onChange={(e) => setLoginForm({ ...loginForm, email: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
type="password"
value={loginForm.password}
onChange={(e) => setLoginForm({ ...loginForm, password: e.target.value })}
className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required
/>
</div>
<Captcha
key={loginCaptchaKey}
scene={CaptchaScene.LOGIN}
value={loginForm.captchaCode}
onChange={(captchaId, captchaCode) =>
setLoginForm({ ...loginForm, captchaId, captchaCode })
}
disabled={loading}
/>
<button
type="submit"
disabled={loading}
className="w-full py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
>
{loading ? '处理中...' : '登录'}
</button>
</form>
</div>
</div>
)}
{/* 用户列表标签页 */}
{activeTab === 'users' && (
<div className="space-y-6">
{/* 更新用户表单 */}
<div className="bg-white p-6 rounded-lg shadow">
<h2 className="text-xl font-semibold mb-4"></h2>
<form onSubmit={handleUpdateUser} className="flex gap-4">
<select
value={updateForm.id}
onChange={(e) => {
const user = users.find((u) => u.id === e.target.value);
setUpdateForm({ id: e.target.value, name: user?.name || '' });
}}
className="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
>
<option value=""></option>
{users.map((user) => (
<option key={user.id} value={user.id}>
{user.name || user.email}
</option>
))}
</select>
<input
type="text"
value={updateForm.name}
onChange={(e) => setUpdateForm({ ...updateForm, name: e.target.value })}
placeholder="新姓名"
className="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
/>
<button
type="submit"
disabled={loading || !updateForm.id}
className="px-6 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 disabled:opacity-50"
>
</button>
</form>
</div>
{/* 用户列表 */}
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="px-6 py-4 border-b flex justify-between items-center">
<h2 className="text-xl font-semibold"></h2>
<button
onClick={fetchUsers}
disabled={loading || !token}
className="px-4 py-2 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50"
>
</button>
</div>
{!token ? (
<div className="p-6 text-center text-gray-500"></div>
) : users.length === 0 ? (
<div className="p-6 text-center text-gray-500"></div>
) : (
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
ID
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{users.map((user) => (
<tr key={user.id}>
<td className="px-6 py-4 text-sm text-gray-500 font-mono">
{user.id.slice(0, 8)}...
</td>
<td className="px-6 py-4 text-sm text-gray-900">{user.email}</td>
<td className="px-6 py-4 text-sm text-gray-900">{user.name || '-'}</td>
<td className="px-6 py-4 text-sm text-gray-500">
{new Date(user.createdAt).toLocaleString('zh-CN')}
</td>
<td className="px-6 py-4 text-sm">
<button
onClick={() => handleDeleteUser(user.id)}
disabled={loading}
className="text-red-600 hover:text-red-800 disabled:opacity-50"
>
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
)}
{/* 已删除用户标签页 */}
{activeTab === 'deleted' && (
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="px-6 py-4 border-b flex justify-between items-center">
<h2 className="text-xl font-semibold"></h2>
<button
onClick={fetchDeletedUsers}
disabled={loading || !token}
className="px-4 py-2 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 disabled:opacity-50"
>
</button>
</div>
{!token ? (
<div className="p-6 text-center text-gray-500"></div>
) : deletedUsers.length === 0 ? (
<div className="p-6 text-center text-gray-500"></div>
) : (
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
ID
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{deletedUsers.map((user) => (
<tr key={user.id} className="bg-gray-50">
<td className="px-6 py-4 text-sm text-gray-500 font-mono">
{user.id.slice(0, 8)}...
</td>
<td className="px-6 py-4 text-sm text-gray-500">{user.email}</td>
<td className="px-6 py-4 text-sm text-gray-500">{user.name || '-'}</td>
<td className="px-6 py-4 text-sm text-gray-500">
{user.deletedAt ? new Date(user.deletedAt).toLocaleString('zh-CN') : '-'}
</td>
<td className="px-6 py-4 text-sm">
<button
onClick={() => handleRestoreUser(user.id)}
disabled={loading}
className="text-green-600 hover:text-green-800 disabled:opacity-50"
>
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
)}
{/* 返回首页 */}
<div className="mt-8 text-center">
<a href="/" className="text-blue-600 hover:text-blue-800">
</a>
</div>
</div>
</main>
);
}

View File

@@ -0,0 +1,100 @@
'use client';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Skeleton } from '@/components/ui/skeleton';
import { useUsers, useDeletedUsers } from '@/hooks/useUsers';
interface ProgressItemProps {
label: string;
value: number;
total: number;
color?: string;
}
function ProgressItem({ label, value, total, color: _color = 'bg-primary' }: ProgressItemProps) {
const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
return (
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium">
{value} ({percentage}%)
</span>
</div>
<Progress value={percentage} className="h-2" />
</div>
);
}
export function DashboardOverview() {
const { data: usersData, isLoading: isLoadingUsers } = useUsers({ pageSize: 1 });
const { data: deletedUsersData, isLoading: isLoadingDeleted } = useDeletedUsers({ pageSize: 1 });
const isLoading = isLoadingUsers || isLoadingDeleted;
const activeUsers = usersData?.total ?? 0;
const deletedUsers = deletedUsersData?.total ?? 0;
const totalUsers = activeUsers + deletedUsers;
return (
<Card className="col-span-4">
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{isLoading ? (
<div className="space-y-6">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="space-y-2">
<div className="flex justify-between">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-4 w-16" />
</div>
<Skeleton className="h-2 w-full" />
</div>
))}
</div>
) : totalUsers === 0 ? (
<div className="flex items-center justify-center h-[200px] text-muted-foreground">
</div>
) : (
<>
<ProgressItem
label="活跃用户"
value={activeUsers}
total={totalUsers}
/>
<ProgressItem
label="已删除用户"
value={deletedUsers}
total={totalUsers}
/>
<div className="pt-4 border-t">
<div className="grid grid-cols-2 gap-4 text-center">
<div>
<p className="text-2xl font-bold text-primary">{activeUsers}</p>
<p className="text-xs text-muted-foreground"></p>
</div>
<div>
<p className="text-2xl font-bold text-muted-foreground">{deletedUsers}</p>
<p className="text-xs text-muted-foreground"></p>
</div>
</div>
</div>
</>
)}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,125 @@
'use client';
import { Users, UserCheck, UserPlus, Activity, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useUsers, useDeletedUsers } from '@/hooks/useUsers';
interface StatCardProps {
title: string;
value: string | number;
description?: string;
icon: React.ReactNode;
isLoading?: boolean;
}
function StatCard({
title,
value,
description,
icon,
isLoading,
}: StatCardProps) {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{title}</CardTitle>
<div className="text-muted-foreground">{icon}</div>
</CardHeader>
<CardContent>
{isLoading ? (
<>
<Skeleton className="h-8 w-20 mb-1" />
<Skeleton className="h-4 w-32" />
</>
) : (
<>
<div className="text-2xl font-bold">{value}</div>
{description && (
<p className="text-xs text-muted-foreground">{description}</p>
)}
</>
)}
</CardContent>
</Card>
);
}
export function DashboardStats() {
const {
data: usersData,
isLoading: isLoadingUsers,
refetch: refetchUsers,
} = useUsers({ pageSize: 1 });
const {
data: deletedUsersData,
isLoading: isLoadingDeleted,
refetch: refetchDeleted,
} = useDeletedUsers({ pageSize: 1 });
const isLoading = isLoadingUsers || isLoadingDeleted;
const handleRefresh = () => {
refetchUsers();
refetchDeleted();
};
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold"></h2>
<Button
variant="outline"
size="sm"
onClick={handleRefresh}
disabled={isLoading}
>
<RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
</Button>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<StatCard
title="总用户数"
value={usersData?.total ?? '-'}
description="系统中的活跃用户"
icon={<Users className="h-4 w-4" />}
isLoading={isLoadingUsers}
/>
<StatCard
title="活跃用户"
value={usersData?.total ?? '-'}
description="近 30 天有登录记录"
icon={<UserCheck className="h-4 w-4" />}
isLoading={isLoadingUsers}
/>
<StatCard
title="已删除用户"
value={deletedUsersData?.total ?? '-'}
description="已软删除的用户"
icon={<UserPlus className="h-4 w-4" />}
isLoading={isLoadingDeleted}
/>
<StatCard
title="系统状态"
value="正常"
description="所有服务运行正常"
icon={<Activity className="h-4 w-4" />}
isLoading={false}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,120 @@
'use client';
import { formatDate } from '@seclusion/shared';
import { Clock, User, LogIn, UserPlus, Trash2 } from 'lucide-react';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
interface Activity {
id: string;
type: 'login' | 'register' | 'delete' | 'update';
user: string;
timestamp: Date;
description: string;
}
// 模拟活动数据(实际项目中应从 API 获取)
const mockActivities: Activity[] = [
{
id: '1',
type: 'login',
user: 'admin@example.com',
timestamp: new Date(Date.now() - 5 * 60 * 1000),
description: '用户登录系统',
},
{
id: '2',
type: 'register',
user: 'newuser@example.com',
timestamp: new Date(Date.now() - 30 * 60 * 1000),
description: '新用户注册',
},
{
id: '3',
type: 'update',
user: 'user@example.com',
timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
description: '更新个人资料',
},
{
id: '4',
type: 'delete',
user: 'old@example.com',
timestamp: new Date(Date.now() - 5 * 60 * 60 * 1000),
description: '账户被删除',
},
];
const activityIcons = {
login: LogIn,
register: UserPlus,
delete: Trash2,
update: User,
};
const activityColors = {
login: 'text-blue-500',
register: 'text-green-500',
delete: 'text-red-500',
update: 'text-yellow-500',
};
export function RecentActivity() {
// 实际项目中应使用 useQuery 获取活动数据
const activities = mockActivities;
return (
<Card className="col-span-3">
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<ScrollArea className="h-[300px] pr-4">
{activities.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-muted-foreground">
<Clock className="h-8 w-8 mb-2" />
<p></p>
</div>
) : (
<div className="space-y-4">
{activities.map((activity) => {
const Icon = activityIcons[activity.type];
const colorClass = activityColors[activity.type];
return (
<div
key={activity.id}
className="flex items-start gap-3 pb-4 border-b last:border-0 last:pb-0"
>
<div className={`mt-0.5 ${colorClass}`}>
<Icon className="h-4 w-4" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{activity.user}
</p>
<p className="text-sm text-muted-foreground">
{activity.description}
</p>
</div>
<time className="text-xs text-muted-foreground whitespace-nowrap">
{formatDate(activity.timestamp, 'HH:mm')}
</time>
</div>
);
})}
</div>
)}
</ScrollArea>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,3 @@
export { DashboardStats } from './DashboardStats';
export { DashboardOverview } from './DashboardOverview';
export { RecentActivity } from './RecentActivity';

View File

@@ -0,0 +1,132 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { CaptchaScene } from '@seclusion/shared';
import { Loader2 } from 'lucide-react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { Captcha } from '@/components/shared/Captcha';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { loginSchema, type LoginFormValues } from '@/lib/validations';
import { authService } from '@/services/auth.service';
import { useAuthStore } from '@/stores';
export function LoginForm() {
const router = useRouter();
const searchParams = useSearchParams();
const redirectUri = searchParams.get('redirect') || '/dashboard';
const { setAuth } = useAuthStore();
const [isLoading, setIsLoading] = useState(false);
const form = useForm<LoginFormValues>({
resolver: zodResolver(loginSchema),
defaultValues: {
email: '',
password: '',
captchaId: '',
captchaCode: '',
},
});
const onSubmit = async (values: LoginFormValues) => {
setIsLoading(true);
try {
const response = await authService.login({
email: values.email,
password: values.password,
captchaId: values.captchaId,
captchaCode: values.captchaCode,
});
setAuth(
response.accessToken,
response.refreshToken,
response.user,
response.accessTokenExpiresIn,
response.refreshTokenExpiresIn
);
toast.success('登录成功');
router.push(redirectUri);
} catch (error) {
toast.error(error instanceof Error ? error.message : '登录失败');
// 刷新验证码
form.setValue('captchaCode', '');
} finally {
setIsLoading(false);
}
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
type="email"
placeholder="请输入邮箱"
autoComplete="email"
disabled={isLoading}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
type="password"
placeholder="请输入密码"
autoComplete="current-password"
disabled={isLoading}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Captcha
scene={CaptchaScene.LOGIN}
value={form.watch('captchaCode')}
onChange={(id, code) => {
form.setValue('captchaId', id);
form.setValue('captchaCode', code);
}}
disabled={isLoading}
/>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
</Button>
</form>
</Form>
);
}

View File

@@ -0,0 +1,133 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2 } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { http } from '@/lib/http';
const passwordSchema = z
.object({
currentPassword: z.string().min(1, '请输入当前密码'),
newPassword: z
.string()
.min(6, '新密码至少 6 位')
.max(32, '新密码最多 32 位'),
confirmPassword: z.string().min(1, '请确认新密码'),
})
.refine((data) => data.newPassword === data.confirmPassword, {
message: '两次密码输入不一致',
path: ['confirmPassword'],
});
type PasswordFormValues = z.infer<typeof passwordSchema>;
export function PasswordForm() {
const form = useForm<PasswordFormValues>({
resolver: zodResolver(passwordSchema),
defaultValues: {
currentPassword: '',
newPassword: '',
confirmPassword: '',
},
});
const onSubmit = async (values: PasswordFormValues) => {
try {
await http.post('/auth/change-password', {
currentPassword: values.currentPassword,
newPassword: values.newPassword,
});
toast.success('密码修改成功');
form.reset();
} catch (error) {
toast.error(error instanceof Error ? error.message : '密码修改失败');
}
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="currentPassword"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
type="password"
placeholder="请输入当前密码"
autoComplete="current-password"
disabled={form.formState.isSubmitting}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="newPassword"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
type="password"
placeholder="请输入新密码"
autoComplete="new-password"
disabled={form.formState.isSubmitting}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
type="password"
placeholder="请再次输入新密码"
autoComplete="new-password"
disabled={form.formState.isSubmitting}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
</Button>
</form>
</Form>
);
}

View File

@@ -0,0 +1,119 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2 } from 'lucide-react';
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { useUpdateUser } from '@/hooks/useUsers';
import { useAuthStore } from '@/stores';
const profileSchema = z.object({
name: z
.string()
.min(2, '用户名至少 2 位')
.max(20, '用户名最多 20 位'),
email: z.string().email('邮箱格式不正确'),
});
type ProfileFormValues = z.infer<typeof profileSchema>;
export function ProfileForm() {
const { user, setUser } = useAuthStore();
const updateUser = useUpdateUser();
const form = useForm<ProfileFormValues>({
resolver: zodResolver(profileSchema),
defaultValues: {
name: '',
email: '',
},
});
// 当用户数据加载后填充表单
useEffect(() => {
if (user) {
form.reset({
name: user.name || '',
email: user.email,
});
}
}, [user, form]);
const onSubmit = async (values: ProfileFormValues) => {
if (!user) return;
try {
const updatedUser = await updateUser.mutateAsync({
id: user.id,
data: { name: values.name },
});
// 更新本地用户状态
setUser({ ...user, name: updatedUser.name });
toast.success('个人信息已更新');
} catch (error) {
toast.error(error instanceof Error ? error.message : '更新失败');
}
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input {...field} disabled />
</FormControl>
<FormDescription></FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
placeholder="请输入用户名"
disabled={updateUser.isPending}
{...field}
/>
</FormControl>
<FormDescription></FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" disabled={updateUser.isPending}>
{updateUser.isPending && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
</Button>
</form>
</Form>
);
}

View File

@@ -0,0 +1,172 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { CaptchaScene } from '@seclusion/shared';
import { Loader2 } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { Captcha } from '@/components/shared/Captcha';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { registerSchema, type RegisterFormValues } from '@/lib/validations';
import { authService } from '@/services/auth.service';
import { useAuthStore } from '@/stores';
export function RegisterForm() {
const router = useRouter();
const { setAuth } = useAuthStore();
const [isLoading, setIsLoading] = useState(false);
const form = useForm<RegisterFormValues>({
resolver: zodResolver(registerSchema),
defaultValues: {
email: '',
password: '',
confirmPassword: '',
name: '',
captchaId: '',
captchaCode: '',
},
});
const onSubmit = async (values: RegisterFormValues) => {
setIsLoading(true);
try {
const response = await authService.register({
email: values.email,
password: values.password,
name: values.name,
captchaId: values.captchaId,
captchaCode: values.captchaCode,
});
setAuth(
response.accessToken,
response.refreshToken,
response.user,
response.accessTokenExpiresIn,
response.refreshTokenExpiresIn
);
toast.success('注册成功');
router.push('/dashboard');
} catch (error) {
toast.error(error instanceof Error ? error.message : '注册失败');
// 刷新验证码
form.setValue('captchaCode', '');
} finally {
setIsLoading(false);
}
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
placeholder="请输入用户名"
autoComplete="name"
disabled={isLoading}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
type="email"
placeholder="请输入邮箱"
autoComplete="email"
disabled={isLoading}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
type="password"
placeholder="请输入密码"
autoComplete="new-password"
disabled={isLoading}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input
type="password"
placeholder="请再次输入密码"
autoComplete="new-password"
disabled={isLoading}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Captcha
scene={CaptchaScene.REGISTER}
value={form.watch('captchaCode')}
onChange={(id, code) => {
form.setValue('captchaId', id);
form.setValue('captchaCode', code);
}}
disabled={isLoading}
/>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
</Button>
</form>
</Form>
);
}

View File

@@ -0,0 +1,4 @@
export { LoginForm } from './LoginForm';
export { RegisterForm } from './RegisterForm';
export { ProfileForm } from './ProfileForm';
export { PasswordForm } from './PasswordForm';

View File

@@ -0,0 +1,59 @@
'use client';
import { Menu } from 'lucide-react';
import Link from 'next/link';
import { ThemeToggle } from './ThemeToggle';
import { UserNav } from './UserNav';
import { Button } from '@/components/ui/button';
import { siteConfig } from '@/config/site';
import { cn } from '@/lib/utils';
import { useUIStore } from '@/stores';
interface HeaderProps {
showSidebarToggle?: boolean;
className?: string;
}
export function Header({ showSidebarToggle = true, className }: HeaderProps) {
const { toggleSidebar } = useUIStore();
return (
<header
className={cn(
'sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60',
className
)}
>
<div className="flex h-14 items-center px-4 md:px-6">
{/* 左侧Logo 和侧边栏切换 */}
<div className="flex items-center gap-2">
{showSidebarToggle && (
<Button
variant="ghost"
size="icon"
className="h-9 w-9 md:hidden"
onClick={toggleSidebar}
>
<Menu className="h-5 w-5" />
<span className="sr-only"></span>
</Button>
)}
<Link href="/" className="flex items-center space-x-2">
<span className="font-bold text-xl">{siteConfig.name}</span>
</Link>
</div>
{/* 中间:可扩展区域 */}
<div className="flex-1" />
{/* 右侧:主题切换和用户菜单 */}
<div className="flex items-center gap-2">
<ThemeToggle />
<UserNav />
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,134 @@
'use client';
import { ChevronLeft } from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';
import { sidebarNav } from '@/config/nav';
import { siteConfig } from '@/config/site';
import { cn } from '@/lib/utils';
import { useUIStore } from '@/stores';
interface SidebarContentProps {
collapsed?: boolean;
}
function SidebarContent({ collapsed = false }: SidebarContentProps) {
const pathname = usePathname();
return (
<ScrollArea className="flex-1 py-2">
<nav className="grid gap-1 px-2">
{sidebarNav.map((group, index) => (
<div key={index} className="pb-2">
{group.title && !collapsed && (
<h4 className="mb-1 px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
{group.title}
</h4>
)}
{group.items.map((item) => {
const isActive = pathname === item.href;
const Icon = item.icon;
return (
<Link
key={item.href}
href={item.href}
className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors',
'hover:bg-accent hover:text-accent-foreground',
isActive
? 'bg-accent text-accent-foreground font-medium'
: 'text-muted-foreground',
collapsed && 'justify-center px-2'
)}
title={collapsed ? item.title : undefined}
>
<Icon className="h-4 w-4 shrink-0" />
{!collapsed && <span>{item.title}</span>}
{!collapsed && item.badge && (
<span className="ml-auto rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground">
{item.badge}
</span>
)}
</Link>
);
})}
</div>
))}
</nav>
</ScrollArea>
);
}
export function Sidebar() {
const { sidebarCollapsed, setSidebarCollapsed } = useUIStore();
return (
<aside
className={cn(
'hidden md:flex flex-col border-r bg-background transition-all duration-300',
sidebarCollapsed ? 'w-16' : 'w-64'
)}
>
{/* Logo */}
<div
className={cn(
'flex h-14 items-center border-b px-4',
sidebarCollapsed ? 'justify-center' : 'justify-between'
)}
>
{!sidebarCollapsed && (
<Link href="/dashboard" className="font-bold text-lg">
{siteConfig.name}
</Link>
)}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
>
<ChevronLeft
className={cn(
'h-4 w-4 transition-transform',
sidebarCollapsed && 'rotate-180'
)}
/>
<span className="sr-only">
{sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'}
</span>
</Button>
</div>
{/* 导航内容 */}
<SidebarContent collapsed={sidebarCollapsed} />
</aside>
);
}
// 移动端侧边栏Sheet 抽屉)
export function MobileSidebar() {
const { sidebarOpen, setSidebarOpen } = useUIStore();
return (
<Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
<SheetContent side="left" className="w-64 p-0">
<SheetTitle className="sr-only"></SheetTitle>
<div className="flex h-14 items-center border-b px-4">
<Link
href="/dashboard"
className="font-bold text-lg"
onClick={() => setSidebarOpen(false)}
>
{siteConfig.name}
</Link>
</div>
<SidebarContent />
</SheetContent>
</Sheet>
);
}

View File

@@ -0,0 +1,62 @@
'use client';
import { Moon, Sun, Monitor } from 'lucide-react';
import { useTheme } from 'next-themes';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
export function ThemeToggle() {
const { setTheme, theme } = useTheme();
const [mounted, setMounted] = useState(false);
// 避免水合不匹配:只在客户端挂载后才渲染主题相关内容
useEffect(() => {
setMounted(true);
}, []);
// 服务器端渲染时显示占位符,避免 ID 不匹配
if (!mounted) {
return (
<Button variant="ghost" size="icon" className="h-9 w-9">
<Sun className="h-4 w-4" />
<span className="sr-only"></span>
</Button>
);
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-9 w-9">
<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only"></span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme('light')}>
<Sun className="mr-2 h-4 w-4" />
{theme === 'light' && <span className="ml-auto"></span>}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('dark')}>
<Moon className="mr-2 h-4 w-4" />
{theme === 'dark' && <span className="ml-auto"></span>}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('system')}>
<Monitor className="mr-2 h-4 w-4" />
{theme === 'system' && <span className="ml-auto"></span>}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,80 @@
'use client';
import { LogOut, User, Settings } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { performLogout } from '@/lib/auth';
import { useAuthStore } from '@/stores';
export function UserNav() {
const router = useRouter();
const { user } = useAuthStore();
const handleLogout = () => {
performLogout({ showToast: true });
};
if (!user) {
return (
<Button variant="ghost" size="sm" onClick={() => router.push('/login')}>
</Button>
);
}
// 获取用户名首字母作为头像
const initials = user.name
? user.name.slice(0, 2).toUpperCase()
: user.email.slice(0, 2).toUpperCase();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="relative h-9 w-9 rounded-full">
<Avatar className="h-9 w-9">
<AvatarFallback className="bg-primary text-primary-foreground">
{initials}
</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" align="end" forceMount>
<DropdownMenuLabel className="font-normal">
<div className="flex flex-col space-y-1">
<p className="text-sm font-medium leading-none">{user.name}</p>
<p className="text-xs leading-none text-muted-foreground">
{user.email}
</p>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem onClick={() => router.push('/profile')}>
<User className="mr-2 h-4 w-4" />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => router.push('/settings')}>
<Settings className="mr-2 h-4 w-4" />
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleLogout} className="text-destructive">
<LogOut className="mr-2 h-4 w-4" />
退
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,4 @@
export { Header } from './Header';
export { Sidebar, MobileSidebar } from './Sidebar';
export { ThemeToggle } from './ThemeToggle';
export { UserNav } from './UserNav';

View File

@@ -0,0 +1,50 @@
'use client';
import { PanelLeftClose, PanelLeft } from 'lucide-react';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useUIStore } from '@/stores/uiStore';
export function SidebarSettings() {
const sidebarCollapsed = useUIStore((state) => state.sidebarCollapsed);
const setSidebarCollapsed = useUIStore((state) => state.setSidebarCollapsed);
return (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{sidebarCollapsed ? (
<PanelLeftClose className="h-5 w-5 text-muted-foreground" />
) : (
<PanelLeft className="h-5 w-5 text-muted-foreground" />
)}
<div className="space-y-0.5">
<Label htmlFor="sidebar-collapsed"></Label>
<p className="text-sm text-muted-foreground">
</p>
</div>
</div>
<Switch
id="sidebar-collapsed"
checked={sidebarCollapsed}
onCheckedChange={setSidebarCollapsed}
/>
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,73 @@
'use client';
import { Moon, Sun, Monitor } from 'lucide-react';
import { useTheme } from 'next-themes';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
const themes = [
{
value: 'light',
label: '浅色',
icon: Sun,
},
{
value: 'dark',
label: '深色',
icon: Moon,
},
{
value: 'system',
label: '跟随系统',
icon: Monitor,
},
] as const;
export function ThemeSettings() {
const { theme, setTheme } = useTheme();
return (
<Card>
<CardHeader>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<Label></Label>
<div className="grid grid-cols-3 gap-4">
{themes.map((item) => {
const Icon = item.icon;
const isActive = theme === item.value;
return (
<button
key={item.value}
onClick={() => setTheme(item.value)}
className={cn(
'flex flex-col items-center gap-2 rounded-lg border-2 p-4 transition-colors',
'hover:bg-accent hover:text-accent-foreground',
isActive
? 'border-primary bg-accent'
: 'border-transparent'
)}
>
<Icon className="h-6 w-6" />
<span className="text-sm font-medium">{item.label}</span>
</button>
);
})}
</div>
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,2 @@
export { ThemeSettings } from './ThemeSettings';
export { SidebarSettings } from './SidebarSettings';

View File

@@ -1,27 +1,40 @@
'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import type { CaptchaResponse, CaptchaScene } from '@seclusion/shared';
import { RefreshCw } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { http } from '@/lib/http';
import { cn } from '@/lib/utils';
import { apiFetch } from '@/lib/api';
import type { CaptchaResponse } from '@/types';
import { CaptchaScene } from '@/types';
export interface CaptchaProps {
/** 验证码使用场景 */
scene: (typeof CaptchaScene)[keyof typeof CaptchaScene];
scene: CaptchaScene;
/** 验证码值变化时的回调 */
onChange: (captchaId: string, captchaCode: string) => void;
/** 验证码输入值 */
value: string;
/** 是否禁用 */
disabled?: boolean;
/** 自定义类名 */
className?: string;
}
/**
*
*
*/
export function Captcha({ scene, onChange, value, disabled = false }: CaptchaProps) {
export function Captcha({
scene,
onChange,
value,
disabled = false,
className,
}: CaptchaProps) {
const [captchaId, setCaptchaId] = useState<string>('');
const [captchaImage, setCaptchaImage] = useState<string>('');
const [loading, setLoading] = useState(false);
@@ -36,7 +49,10 @@ export function Captcha({ scene, onChange, value, disabled = false }: CaptchaPro
setLoading(true);
setError(null);
try {
const response = await apiFetch<CaptchaResponse>(`/captcha?scene=${scene}`);
const response = await http.get<CaptchaResponse>(
`/captcha?scene=${scene}`,
{ skipAuth: true }
);
setCaptchaId(response.captchaId);
setCaptchaImage(response.image);
// 清空之前的输入,通知父组件新的 captchaId
@@ -60,38 +76,59 @@ export function Captcha({ scene, onChange, value, disabled = false }: CaptchaPro
};
return (
<div className="space-y-2">
<label className="block text-sm font-medium text-gray-700"></label>
<div className={cn('space-y-2', className)}>
<Label></Label>
<div className="flex gap-2 items-center">
{/* 验证码输入框 */}
<input
<Input
type="text"
value={value}
onChange={handleInputChange}
placeholder="请输入验证码"
disabled={disabled || loading}
maxLength={6}
className="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50"
required
className="flex-1"
/>
{/* 验证码图片 */}
<div
className="h-10 min-w-[100px] flex items-center justify-center bg-gray-100 rounded cursor-pointer hover:opacity-80 transition-opacity"
className={cn(
'h-9 min-w-[100px] flex items-center justify-center rounded-md border bg-muted',
!loading && !disabled && 'cursor-pointer hover:opacity-80',
'transition-opacity'
)}
onClick={!loading && !disabled ? fetchCaptcha : undefined}
title="点击刷新验证码"
>
{loading ? (
<span className="text-xs text-gray-500">...</span>
<RefreshCw className="h-4 w-4 animate-spin text-muted-foreground" />
) : error ? (
<span className="text-xs text-red-500 px-2">{error}</span>
<span className="text-xs text-destructive px-2">{error}</span>
) : captchaImage ? (
<img src={captchaImage} alt="验证码" className="h-full object-contain" />
<img
src={captchaImage}
alt="验证码"
className="h-full object-contain"
/>
) : (
<span className="text-xs text-gray-500"></span>
<span className="text-xs text-muted-foreground"></span>
)}
</div>
{/* 刷新按钮 */}
<Button
type="button"
variant="ghost"
size="icon"
className="h-9 w-9 shrink-0"
onClick={fetchCaptcha}
disabled={loading || disabled}
>
<RefreshCw
className={cn('h-4 w-4', loading && 'animate-spin')}
/>
<span className="sr-only"></span>
</Button>
</div>
<p className="text-xs text-gray-500"></p>
<p className="text-xs text-muted-foreground"></p>
</div>
);
}

View File

@@ -0,0 +1,112 @@
'use client';
import {
flexRender,
getCoreRowModel,
useReactTable,
type ColumnDef,
} from '@tanstack/react-table';
import { Skeleton } from '@/components/ui/skeleton';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
isLoading?: boolean;
emptyMessage?: string;
}
export function DataTable<TData, TValue>({
columns,
data,
isLoading = false,
emptyMessage = '暂无数据',
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
if (isLoading) {
return (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
{columns.map((_, index) => (
<TableHead key={index}>
<Skeleton className="h-4 w-20" />
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{Array.from({ length: 5 }).map((_, rowIndex) => (
<TableRow key={rowIndex}>
{columns.map((_, cellIndex) => (
<TableCell key={cellIndex}>
<Skeleton className="h-4 w-full" />
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}
return (
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && 'selected'}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
{emptyMessage}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}

View File

@@ -0,0 +1,109 @@
'use client';
import {
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { PAGINATION } from '@/config/constants';
interface DataTablePaginationProps {
page: number;
pageSize: number;
total: number;
totalPages: number;
onPageChange: (page: number) => void;
onPageSizeChange: (pageSize: number) => void;
}
export function DataTablePagination({
page,
pageSize,
total,
totalPages,
onPageChange,
onPageSizeChange,
}: DataTablePaginationProps) {
const canGoPrevious = page > 1;
const canGoNext = page < totalPages;
return (
<div className="flex items-center justify-between px-2 py-4">
<div className="flex-1 text-sm text-muted-foreground">
{total}
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
<p className="text-sm font-medium"></p>
<Select
value={String(pageSize)}
onValueChange={(value) => onPageSizeChange(Number(value))}
>
<SelectTrigger className="h-8 w-[70px]">
<SelectValue placeholder={pageSize} />
</SelectTrigger>
<SelectContent side="top">
{PAGINATION.PAGE_SIZE_OPTIONS.map((size) => (
<SelectItem key={size} value={String(size)}>
{size}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-sm font-medium"></p>
</div>
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
{page} / {totalPages}
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => onPageChange(1)}
disabled={!canGoPrevious}
>
<span className="sr-only"></span>
<ChevronsLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => onPageChange(page - 1)}
disabled={!canGoPrevious}
>
<span className="sr-only"></span>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => onPageChange(page + 1)}
disabled={!canGoNext}
>
<span className="sr-only"></span>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => onPageChange(totalPages)}
disabled={!canGoNext}
>
<span className="sr-only"></span>
<ChevronsRight className="h-4 w-4" />
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,69 @@
'use client';
import { AlertCircle, RefreshCw, Home } from 'lucide-react';
import Link from 'next/link';
import { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/components/ui/card';
interface ErrorBoundaryProps {
error: Error & { digest?: string };
reset: () => void;
}
export function ErrorBoundary({ error, reset }: ErrorBoundaryProps) {
useEffect(() => {
// 可以在这里发送错误到日志服务
console.error('应用错误:', error);
}, [error]);
return (
<div className="flex min-h-[400px] items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10">
<AlertCircle className="h-6 w-6 text-destructive" />
</div>
<CardTitle></CardTitle>
<CardDescription>
</CardDescription>
</CardHeader>
<CardContent>
{process.env.NODE_ENV === 'development' && (
<div className="rounded-md bg-muted p-3">
<p className="text-sm font-medium text-destructive">
{error.message}
</p>
{error.digest && (
<p className="mt-1 text-xs text-muted-foreground">
ID: {error.digest}
</p>
)}
</div>
)}
</CardContent>
<CardFooter className="flex gap-2">
<Button variant="outline" className="flex-1" onClick={reset}>
<RefreshCw className="mr-2 h-4 w-4" />
</Button>
<Button asChild className="flex-1">
<Link href="/dashboard">
<Home className="mr-2 h-4 w-4" />
</Link>
</Button>
</CardFooter>
</Card>
</div>
);
}

View File

@@ -0,0 +1,4 @@
export { Captcha } from './Captcha';
export { DataTable } from './DataTable';
export { DataTablePagination } from './DataTablePagination';
export { ErrorBoundary } from './ErrorBoundary';

View File

@@ -0,0 +1,157 @@
"use client"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import * as React from "react"
import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
)
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
)
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

View File

@@ -0,0 +1,53 @@
"use client"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import * as React from "react"
import { cn } from "@/lib/utils"
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback }

View File

@@ -0,0 +1,46 @@
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,109 @@
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import * as React from "react"
import { cn } from "@/lib/utils"
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
className
)}
{...props}
/>
)
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-item"
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
)
}
function BreadcrumbLink({
asChild,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="breadcrumb-link"
className={cn("hover:text-foreground transition-colors", className)}
{...props}
/>
)
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
className={cn("text-foreground font-normal", className)}
{...props}
/>
)
}
function BreadcrumbSeparator({
children,
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:size-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
}
function BreadcrumbEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="size-4" />
<span className="sr-only">More</span>
</span>
)
}
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}

View File

@@ -0,0 +1,62 @@
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@@ -0,0 +1,32 @@
"use client"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "lucide-react"
import * as React from "react"
import { cn } from "@/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,143 @@
"use client"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import * as React from "react"
import { cn } from "@/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,257 @@
"use client"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import * as React from "react"
import { cn } from "@/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground 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-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground 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-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}

View File

@@ -0,0 +1,167 @@
"use client"
import type * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import * as React from "react"
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { Label } from "@/components/ui/label"
import { cn } from "@/lib/utils"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState } = useFormContext()
const formState = useFormState({ name: fieldContext.name })
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
)
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField()
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField()
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : props.children
if (!body) {
return null
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body}
</p>
)
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View File

@@ -0,0 +1,24 @@
"use client"
import * as LabelPrimitive from "@radix-ui/react-label"
import * as React from "react"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,127 @@
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react"
import * as React from "react"
import { buttonVariants, type Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
}
function PaginationContent({
className,
...props
}: React.ComponentProps<"ul">) {
return (
<ul
data-slot="pagination-content"
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
)
}
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
return <li data-slot="pagination-item" {...props} />
}
type PaginationLinkProps = {
isActive?: boolean
} & Pick<React.ComponentProps<typeof Button>, "size"> &
React.ComponentProps<"a">
function PaginationLink({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) {
return (
<a
aria-current={isActive ? "page" : undefined}
data-slot="pagination-link"
data-active={isActive}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className
)}
{...props}
/>
)
}
function PaginationPrevious({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
{...props}
>
<ChevronLeftIcon />
<span className="hidden sm:block">Previous</span>
</PaginationLink>
)
}
function PaginationNext({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
{...props}
>
<span className="hidden sm:block">Next</span>
<ChevronRightIcon />
</PaginationLink>
)
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontalIcon className="size-4" />
<span className="sr-only">More pages</span>
</span>
)
}
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
}

View File

@@ -0,0 +1,48 @@
"use client"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import * as React from "react"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground 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-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View File

@@ -0,0 +1,31 @@
"use client"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import * as React from "react"
import { cn } from "@/lib/utils"
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
)
}
export { Progress }

View File

@@ -0,0 +1,58 @@
"use client"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import * as React from "react"
import { cn } from "@/lib/utils"
function ScrollArea({
className,
children,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
<ScrollAreaPrimitive.ScrollAreaScrollbar
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb
data-slot="scroll-area-thumb"
className="bg-border relative flex-1 rounded-full"
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
)
}
export { ScrollArea, ScrollBar }

View File

@@ -0,0 +1,190 @@
"use client"
import * as SelectPrimitive from "@radix-ui/react-select"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import * as React from "react"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground 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-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span
data-slot="select-item-indicator"
className="absolute right-2 flex size-3.5 items-center justify-center"
>
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@@ -0,0 +1,28 @@
"use client"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import * as React from "react"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

View File

@@ -0,0 +1,139 @@
"use client"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import * as React from "react"
import { cn } from "@/lib/utils"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
)
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
)
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -0,0 +1,40 @@
"use client"
import {
CircleCheckIcon,
InfoIcon,
Loader2Icon,
OctagonXIcon,
TriangleAlertIcon,
} from "lucide-react"
import { useTheme } from "next-themes"
import { Toaster as Sonner, type ToasterProps } from "sonner"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
icons={{
success: <CircleCheckIcon className="size-4" />,
info: <InfoIcon className="size-4" />,
warning: <TriangleAlertIcon className="size-4" />,
error: <OctagonXIcon className="size-4" />,
loading: <Loader2Icon className="size-4 animate-spin" />,
}}
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
} as React.CSSProperties
}
{...props}
/>
)
}
export { Toaster }

View File

@@ -0,0 +1,31 @@
"use client"
import * as SwitchPrimitive from "@radix-ui/react-switch"
import * as React from "react"
import { cn } from "@/lib/utils"
function Switch({
className,
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitive.Root>
)
}
export { Switch }

View File

@@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -0,0 +1,66 @@
"use client"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import * as React from "react"
import { cn } from "@/lib/utils"
function Tabs({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function TabsList({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
className
)}
{...props}
/>
)
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent }

View File

@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

View File

@@ -0,0 +1,61 @@
"use client"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import * as React from "react"
import { cn } from "@/lib/utils"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
)
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@@ -0,0 +1,133 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import type { UserResponse } from '@seclusion/shared';
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { useUpdateUser } from '@/hooks/useUsers';
const editUserSchema = z.object({
name: z.string().max(50, '姓名最多 50 个字符').optional(),
});
type EditUserFormValues = z.infer<typeof editUserSchema>;
interface UserEditDialogProps {
user: UserResponse | null;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function UserEditDialog({
user,
open,
onOpenChange,
}: UserEditDialogProps) {
const updateUser = useUpdateUser();
const form = useForm<EditUserFormValues>({
resolver: zodResolver(editUserSchema),
defaultValues: {
name: '',
},
});
// 当用户变化时重置表单
useEffect(() => {
if (user) {
form.reset({
name: user.name || '',
});
}
}, [user, form]);
const onSubmit = async (values: EditUserFormValues) => {
if (!user) return;
try {
await updateUser.mutateAsync({
id: user.id,
data: { name: values.name || undefined },
});
toast.success('用户信息已更新');
onOpenChange(false);
} catch (error) {
toast.error(error instanceof Error ? error.message : '更新失败');
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
{user?.email}
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel></FormLabel>
<FormControl>
<Input placeholder="请输入姓名" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="text-sm text-muted-foreground space-y-1">
<p>
<span className="font-medium">:</span> {user?.email}
</p>
<p>
<span className="font-medium">ID:</span>{' '}
<span className="font-mono">{user?.id}</span>
</p>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
>
</Button>
<Button type="submit" disabled={updateUser.isPending}>
{updateUser.isPending ? '保存中...' : '保存'}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,308 @@
'use client';
import type { UserResponse } from '@seclusion/shared';
import { formatDate } from '@seclusion/shared';
import type { ColumnDef } from '@tanstack/react-table';
import { MoreHorizontal, Trash2, RotateCcw, Pencil } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { UserEditDialog } from './UserEditDialog';
import { DataTable } from '@/components/shared/DataTable';
import { DataTablePagination } from '@/components/shared/DataTablePagination';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { PAGINATION } from '@/config/constants';
import {
useUsers,
useDeletedUsers,
useDeleteUser,
useRestoreUser,
} from '@/hooks/useUsers';
interface UserActionsProps {
user: UserResponse;
isDeleted?: boolean;
onDelete: (id: string) => void;
onRestore: (id: string) => void;
onEdit: (user: UserResponse) => void;
}
function UserActions({
user,
isDeleted,
onDelete,
onRestore,
onEdit,
}: UserActionsProps) {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only"></span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel></DropdownMenuLabel>
<DropdownMenuSeparator />
{isDeleted ? (
<DropdownMenuItem onClick={() => onRestore(user.id)}>
<RotateCcw className="mr-2 h-4 w-4" />
</DropdownMenuItem>
) : (
<>
<DropdownMenuItem onClick={() => onEdit(user)}>
<Pencil className="mr-2 h-4 w-4" />
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => onDelete(user.id)}
className="text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}
export function UsersTable() {
const [page, setPage] = useState<number>(PAGINATION.DEFAULT_PAGE);
const [pageSize, setPageSize] = useState<number>(PAGINATION.DEFAULT_PAGE_SIZE);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [userToDelete, setUserToDelete] = useState<string | null>(null);
const [showDeleted, setShowDeleted] = useState(false);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [userToEdit, setUserToEdit] = useState<UserResponse | null>(null);
// 查询
const {
data: usersData,
isLoading: isLoadingUsers,
refetch: refetchUsers,
} = useUsers({ page, pageSize });
const {
data: deletedUsersData,
isLoading: isLoadingDeleted,
refetch: refetchDeleted,
} = useDeletedUsers({ page, pageSize });
// 变更
const deleteUser = useDeleteUser();
const restoreUser = useRestoreUser();
const handleDelete = (id: string) => {
setUserToDelete(id);
setDeleteDialogOpen(true);
};
const confirmDelete = async () => {
if (!userToDelete) return;
try {
await deleteUser.mutateAsync(userToDelete);
toast.success('用户已删除');
} catch (error) {
toast.error(error instanceof Error ? error.message : '删除失败');
} finally {
setDeleteDialogOpen(false);
setUserToDelete(null);
}
};
const handleRestore = async (id: string) => {
try {
await restoreUser.mutateAsync(id);
toast.success('用户已恢复');
} catch (error) {
toast.error(error instanceof Error ? error.message : '恢复失败');
}
};
const handleEdit = (user: UserResponse) => {
setUserToEdit(user);
setEditDialogOpen(true);
};
const columns: ColumnDef<UserResponse>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="font-mono text-xs text-muted-foreground">
{row.original.id.slice(0, 8)}...
</span>
),
},
{
accessorKey: 'email',
header: '邮箱',
},
{
accessorKey: 'name',
header: '姓名',
cell: ({ row }) => row.original.name || '-',
},
{
accessorKey: 'createdAt',
header: '创建时间',
cell: ({ row }) =>
formatDate(new Date(row.original.createdAt), 'YYYY-MM-DD HH:mm'),
},
...(showDeleted
? [
{
accessorKey: 'deletedAt',
header: '删除时间',
cell: ({ row }: { row: { original: UserResponse } }) =>
row.original.deletedAt
? formatDate(
new Date(row.original.deletedAt),
'YYYY-MM-DD HH:mm'
)
: '-',
} as ColumnDef<UserResponse>,
]
: []),
{
id: 'actions',
header: '操作',
cell: ({ row }) => (
<UserActions
user={row.original}
isDeleted={showDeleted}
onDelete={handleDelete}
onRestore={handleRestore}
onEdit={handleEdit}
/>
),
},
];
const data = showDeleted ? deletedUsersData : usersData;
const isLoading = showDeleted ? isLoadingDeleted : isLoadingUsers;
return (
<div className="space-y-4">
{/* 工具栏 */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Button
variant={!showDeleted ? 'default' : 'outline'}
size="sm"
onClick={() => {
setShowDeleted(false);
setPage(1);
}}
>
{usersData && (
<Badge variant="secondary" className="ml-2">
{usersData.total}
</Badge>
)}
</Button>
<Button
variant={showDeleted ? 'default' : 'outline'}
size="sm"
onClick={() => {
setShowDeleted(true);
setPage(1);
}}
>
{deletedUsersData && (
<Badge variant="secondary" className="ml-2">
{deletedUsersData.total}
</Badge>
)}
</Button>
</div>
<Button
variant="outline"
size="sm"
onClick={() => (showDeleted ? refetchDeleted() : refetchUsers())}
>
</Button>
</div>
{/* 数据表格 */}
<DataTable
columns={columns}
data={data?.items || []}
isLoading={isLoading}
emptyMessage={showDeleted ? '暂无已删除用户' : '暂无用户'}
/>
{/* 分页 */}
{data && data.total > 0 && (
<DataTablePagination
page={page}
pageSize={pageSize}
total={data.total}
totalPages={data.totalPages}
onPageChange={setPage}
onPageSizeChange={(size) => {
setPageSize(size);
setPage(1);
}}
/>
)}
{/* 删除确认弹窗 */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction
onClick={confirmDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* 编辑用户弹窗 */}
<UserEditDialog
user={userToEdit}
open={editDialogOpen}
onOpenChange={setEditDialogOpen}
/>
</div>
);
}

View File

@@ -0,0 +1,2 @@
export { UsersTable } from './UsersTable';
export { UserEditDialog } from './UserEditDialog';

View File

@@ -0,0 +1,25 @@
// API 相关常量
export const API_ENDPOINTS = {
AUTH: {
LOGIN: '/auth/login',
REGISTER: '/auth/register',
REFRESH: '/auth/refresh',
ME: '/auth/me',
LOGOUT: '/auth/logout',
},
USERS: '/users',
CAPTCHA: '/captcha',
} as const;
// 分页默认值
export const PAGINATION = {
DEFAULT_PAGE: 1,
DEFAULT_PAGE_SIZE: 10,
PAGE_SIZE_OPTIONS: [10, 20, 50, 100],
} as const;
// 本地存储 Key
export const STORAGE_KEYS = {
AUTH: 'auth-storage',
UI: 'ui-storage',
} as const;

View File

@@ -0,0 +1,61 @@
import {
LayoutDashboard,
Users,
Settings,
User,
type LucideIcon,
} from 'lucide-react';
export interface NavItem {
title: string;
href: string;
icon: LucideIcon;
disabled?: boolean;
external?: boolean;
badge?: string;
}
export interface NavGroup {
title?: string;
items: NavItem[];
}
export const mainNav: NavItem[] = [
{
title: '仪表盘',
href: '/dashboard',
icon: LayoutDashboard,
},
];
export const sidebarNav: NavGroup[] = [
{
items: [
{
title: '仪表盘',
href: '/dashboard',
icon: LayoutDashboard,
},
{
title: '用户管理',
href: '/users',
icon: Users,
},
],
},
{
title: '设置',
items: [
{
title: '个人中心',
href: '/profile',
icon: User,
},
{
title: '系统设置',
href: '/settings',
icon: Settings,
},
],
},
];

View File

@@ -0,0 +1,6 @@
export const siteConfig = {
name: 'Seclusion',
description: '基于 Next.js + NestJS 的 Monorepo 项目模板',
url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000',
apiUrl: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000',
};

View File

@@ -0,0 +1,9 @@
export {
useUsers,
useDeletedUsers,
useUser,
useUpdateUser,
useDeleteUser,
useRestoreUser,
userKeys,
} from './useUsers';

View File

@@ -0,0 +1,97 @@
import type { UpdateUserDto } from '@seclusion/shared';
import {
useMutation,
useQuery,
useQueryClient,
} from '@tanstack/react-query';
import { userService, type GetUsersParams } from '@/services/user.service';
import { useIsAuthenticated } from '@/stores';
// Query Keys
export const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
list: (params: GetUsersParams) => [...userKeys.lists(), params] as const,
deleted: () => [...userKeys.all, 'deleted'] as const,
deletedList: (params: GetUsersParams) =>
[...userKeys.deleted(), params] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: string) => [...userKeys.details(), id] as const,
};
// 获取用户列表
export function useUsers(params: GetUsersParams = {}) {
const isAuthenticated = useIsAuthenticated();
return useQuery({
queryKey: userKeys.list(params),
queryFn: () => userService.getUsers(params),
enabled: isAuthenticated,
});
}
// 获取已删除的用户列表
export function useDeletedUsers(params: GetUsersParams = {}) {
const isAuthenticated = useIsAuthenticated();
return useQuery({
queryKey: userKeys.deletedList(params),
queryFn: () => userService.getDeletedUsers(params),
enabled: isAuthenticated,
});
}
// 获取单个用户
export function useUser(id: string) {
const isAuthenticated = useIsAuthenticated();
return useQuery({
queryKey: userKeys.detail(id),
queryFn: () => userService.getUser(id),
enabled: isAuthenticated && !!id,
});
}
// 更新用户
export function useUpdateUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, data }: { id: string; data: UpdateUserDto }) =>
userService.updateUser(id, data),
onSuccess: (_, { id }) => {
// 使相关查询失效
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
queryClient.invalidateQueries({ queryKey: userKeys.detail(id) });
},
});
}
// 删除用户
export function useDeleteUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) => userService.deleteUser(id),
onSuccess: () => {
// 使用户列表和已删除列表都失效
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
queryClient.invalidateQueries({ queryKey: userKeys.deleted() });
},
});
}
// 恢复用户
export function useRestoreUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) => userService.restoreUser(id),
onSuccess: () => {
// 使用户列表和已删除列表都失效
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
queryClient.invalidateQueries({ queryKey: userKeys.deleted() });
},
});
}

View File

@@ -1,45 +0,0 @@
import { encryptRequest, decryptResponse, isEncryptionEnabled } from './crypto';
import type { FetchOptions } from '@/types';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';
export async function apiFetch<T>(endpoint: string, options: FetchOptions = {}): Promise<T> {
const { token, headers, body, skipEncryption, ...rest } = options;
// 处理请求体加密
let processedBody = body;
if (body && !skipEncryption && isEncryptionEnabled()) {
// 如果 body 是字符串,先解析为对象
const bodyData = typeof body === 'string' ? JSON.parse(body) : body;
const encryptedBody = await encryptRequest(bodyData);
processedBody = JSON.stringify(encryptedBody);
}
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
headers: {
'Content-Type': 'application/json',
...(token && { Authorization: `Bearer ${token}` }),
...headers,
},
body: processedBody,
...rest,
});
if (!response.ok) {
// 错误响应也可能被加密
const isEncrypted = response.headers.get('X-Encrypted') === 'true';
const errorData = await response.json().catch(() => ({}));
const error = isEncrypted
? await decryptResponse(errorData, true).catch(() => errorData)
: errorData;
throw new Error(error.message || `HTTP error! status: ${response.status}`);
}
// 检查响应是否被加密
const isEncrypted = response.headers.get('X-Encrypted') === 'true';
const data = await response.json();
// 解密响应
return decryptResponse<T>(data, isEncrypted);
}

70
apps/web/src/lib/auth.ts Normal file
View File

@@ -0,0 +1,70 @@
/**
* Auth 工具函数
* 提供登录/登出相关的便捷方法
*/
import { toast } from 'sonner';
import { useAuthStore } from '@/stores/authStore';
/**
* 执行登出操作
* @param options.redirect - 可选,登出后跳转的 URL默认跳转到登录页
* @param options.showToast - 可选,是否显示提示,默认不显示
* @param options.toastMessage - 可选,自定义提示信息
*/
export function performLogout(options?: {
redirect?: string;
showToast?: boolean;
toastMessage?: string;
}) {
const { redirect, showToast = false, toastMessage } = options || {};
// 清除认证状态
useAuthStore.getState().logout();
// 显示提示(如果需要)
if (showToast) {
toast.info(toastMessage || '已退出登录');
}
// 执行跳转
if (typeof window !== 'undefined') {
const targetUrl = redirect || '/login';
window.location.href = targetUrl;
}
}
/**
* 执行登出并返回登录页(带当前页面作为 redirect 参数)
* 用于 401 等场景,让用户登录后可以返回之前页面
*/
export function performLogoutWithRedirect(options?: {
showToast?: boolean;
toastMessage?: string;
}) {
const { showToast = true, toastMessage = '登录已过期,请重新登录' } = options || {};
// 获取当前路径作为 redirect 参数
const currentPath = typeof window !== 'undefined' ? window.location.pathname : '';
const redirectParam =
currentPath && currentPath !== '/login'
? `?redirect=${encodeURIComponent(currentPath)}`
: '';
performLogout({
redirect: `/login${redirectParam}`,
showToast,
toastMessage,
});
}
/**
* 获取登录页 URL带可选的 redirect 参数)
* @param redirectTo - 登录后要跳转的页面
*/
export function getLoginUrl(redirectTo?: string): string {
if (redirectTo && redirectTo !== '/login') {
return `/login?redirect=${encodeURIComponent(redirectTo)}`;
}
return '/login';
}

284
apps/web/src/lib/http.ts Normal file
View File

@@ -0,0 +1,284 @@
/**
* Axios HTTP 客户端封装
* 功能:
* - 自动附加 Authorization header
* - 请求体加密 / 响应体解密
* - Token 过期主动刷新(基于过期时间)
* - 请求队列(避免并发刷新 token
*/
import type { RefreshTokenResponse } from '@seclusion/shared';
import axios, {
type AxiosError,
type AxiosInstance,
type AxiosRequestConfig,
type InternalAxiosRequestConfig,
} from 'axios';
import { API_ENDPOINTS } from '@/config/constants';
import { performLogoutWithRedirect } from '@/lib/auth';
import { decryptResponse, encryptRequest, isEncryptionEnabled } from '@/lib/crypto';
import { useAuthStore } from '@/stores/authStore';
// API 基础 URL
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';
// 扩展 AxiosRequestConfig 以支持自定义选项
interface CustomRequestConfig extends AxiosRequestConfig {
// 跳过加密(用于文件上传等场景)
skipEncryption?: boolean;
// 跳过认证(用于登录、注册等公开接口)
skipAuth?: boolean;
}
// Token 刷新状态管理
let isRefreshing = false;
let failedQueue: Array<{
resolve: (token: string | null) => void;
reject: (error: Error) => void;
}> = [];
/**
* 处理等待队列中的请求
*/
function processQueue(error: Error | null, token: string | null = null) {
failedQueue.forEach((promise) => {
if (error) {
promise.reject(error);
} else {
promise.resolve(token);
}
});
failedQueue = [];
}
/**
* 刷新 Token
*/
async function refreshToken(): Promise<string | null> {
const store = useAuthStore.getState();
const { refreshToken: currentRefreshToken, setAuth, user, isRefreshTokenExpired } = store;
// 如果 refreshToken 已过期,直接登出并跳转
if (isRefreshTokenExpired()) {
performLogoutWithRedirect({ toastMessage: '登录已过期,请重新登录' });
return null;
}
if (!currentRefreshToken) {
performLogoutWithRedirect({ toastMessage: '登录已过期,请重新登录' });
return null;
}
try {
// 直接使用 axios 发送请求,避免循环调用拦截器
const response = await axios.post<RefreshTokenResponse>(
`${API_BASE_URL}${API_ENDPOINTS.AUTH.REFRESH}`,
{ refreshToken: currentRefreshToken },
{ headers: { 'Content-Type': 'application/json' } }
);
const {
accessToken,
refreshToken: newRefreshToken,
accessTokenExpiresIn,
refreshTokenExpiresIn,
} = response.data;
// 更新 store 中的 token
if (user) {
setAuth(accessToken, newRefreshToken, user, accessTokenExpiresIn, refreshTokenExpiresIn);
}
return accessToken;
} catch {
// 刷新失败,登出用户并跳转
performLogoutWithRedirect({ toastMessage: '登录已过期,请重新登录' });
return null;
}
}
/**
* 确保 token 有效(如果即将过期则刷新)
*/
async function ensureValidToken(): Promise<string | null> {
const store = useAuthStore.getState();
const { token, isTokenExpiringSoon, isRefreshTokenExpired } = store;
// 没有 token
if (!token) {
return null;
}
// token 没有即将过期,直接返回
if (!isTokenExpiringSoon()) {
return token;
}
// refreshToken 已过期,无法刷新,登出用户并跳转
if (isRefreshTokenExpired()) {
performLogoutWithRedirect({ toastMessage: '登录已过期,请重新登录' });
return null;
}
// token 即将过期,需要刷新
if (isRefreshing) {
// 正在刷新中,等待刷新完成
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject });
});
}
isRefreshing = true;
try {
const newToken = await refreshToken();
processQueue(null, newToken);
return newToken;
} catch (error) {
processQueue(error as Error, null);
return null;
} finally {
isRefreshing = false;
}
}
/**
* 创建 Axios 实例
*/
function createHttpClient(): AxiosInstance {
const instance = axios.create({
baseURL: API_BASE_URL,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器
instance.interceptors.request.use(
async (config: InternalAxiosRequestConfig & CustomRequestConfig) => {
// 添加 Authorization header
if (!config.skipAuth) {
// 确保 token 有效(如果即将过期则主动刷新)
const token = await ensureValidToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
}
// 加密请求体
if (config.data && !config.skipEncryption && isEncryptionEnabled()) {
try {
const encryptedData = await encryptRequest(config.data);
config.data = encryptedData;
} catch (error) {
console.error('请求加密失败:', error);
throw error;
}
}
return config;
},
(error) => Promise.reject(error)
);
// 响应拦截器
instance.interceptors.response.use(
async (response) => {
// 检查响应是否被加密
const isEncrypted = response.headers['x-encrypted'] === 'true';
if (isEncrypted && response.data) {
try {
response.data = await decryptResponse(response.data, true);
} catch (error) {
console.error('响应解密失败:', error);
throw error;
}
}
return response;
},
async (error: AxiosError) => {
// 处理 401 错误 - 登录已过期,提示用户并跳转登录页
if (error.response?.status === 401) {
performLogoutWithRedirect();
return Promise.reject(new Error('登录已过期'));
}
// 处理错误响应(可能被加密)
if (error.response?.data) {
const isEncrypted = error.response.headers['x-encrypted'] === 'true';
if (isEncrypted) {
try {
error.response.data = await decryptResponse(error.response.data, true);
} catch {
// 解密失败时保留原始错误
}
}
}
// 提取错误信息
const errorData = error.response?.data as { message?: string } | undefined;
const message = errorData?.message || error.message || '请求失败';
return Promise.reject(new Error(message));
}
);
return instance;
}
// 创建单例实例
const httpClient = createHttpClient();
/**
* HTTP 请求方法封装
*/
export const http = {
/**
* GET 请求
*/
get: async <T>(url: string, config?: CustomRequestConfig): Promise<T> => {
const response = await httpClient.get<T>(url, config);
return response.data;
},
/**
* POST 请求
*/
post: async <T>(url: string, data?: unknown, config?: CustomRequestConfig): Promise<T> => {
const response = await httpClient.post<T>(url, data, config);
return response.data;
},
/**
* PUT 请求
*/
put: async <T>(url: string, data?: unknown, config?: CustomRequestConfig): Promise<T> => {
const response = await httpClient.put<T>(url, data, config);
return response.data;
},
/**
* PATCH 请求
*/
patch: async <T>(url: string, data?: unknown, config?: CustomRequestConfig): Promise<T> => {
const response = await httpClient.patch<T>(url, data, config);
return response.data;
},
/**
* DELETE 请求
*/
delete: async <T>(url: string, config?: CustomRequestConfig): Promise<T> => {
const response = await httpClient.delete<T>(url, config);
return response.data;
},
};
// 导出 axios 实例(用于特殊场景)
export { httpClient };
// 导出自定义配置类型
export type { CustomRequestConfig };

View File

@@ -0,0 +1,37 @@
'use client';
import { QueryClient } from '@tanstack/react-query';
function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
// 数据被认为是陈旧的时间(默认 0立即变为 stale
staleTime: 60 * 1000, // 1 分钟
// 缓存数据保留时间(默认 5 分钟)
gcTime: 5 * 60 * 1000,
// 重试次数
retry: 1,
// 窗口重新聚焦时重新获取数据
refetchOnWindowFocus: false,
},
mutations: {
// 重试次数
retry: 0,
},
},
});
}
let browserQueryClient: QueryClient | undefined = undefined;
export function getQueryClient() {
if (typeof window === 'undefined') {
// Server: always make a new query client
return makeQueryClient();
} else {
// Browser: make a new query client if we don't already have one
if (!browserQueryClient) browserQueryClient = makeQueryClient();
return browserQueryClient;
}
}

View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

View File

@@ -0,0 +1,94 @@
import { z } from 'zod';
// ==================== 登录表单 ====================
export const loginSchema = z.object({
email: z
.string()
.min(1, '请输入邮箱')
.email('邮箱格式不正确'),
password: z
.string()
.min(1, '请输入密码')
.min(6, '密码至少 6 位'),
captchaId: z.string().min(1, '验证码 ID 不能为空'),
captchaCode: z
.string()
.min(1, '请输入验证码')
.length(4, '验证码为 4 位'),
});
export type LoginFormValues = z.infer<typeof loginSchema>;
// ==================== 注册表单 ====================
export const registerSchema = z.object({
email: z
.string()
.min(1, '请输入邮箱')
.email('邮箱格式不正确'),
password: z
.string()
.min(1, '请输入密码')
.min(6, '密码至少 6 位')
.max(32, '密码最多 32 位'),
confirmPassword: z.string().min(1, '请确认密码'),
name: z
.string()
.min(1, '请输入用户名')
.min(2, '用户名至少 2 位')
.max(20, '用户名最多 20 位'),
captchaId: z.string().min(1, '验证码 ID 不能为空'),
captchaCode: z
.string()
.min(1, '请输入验证码')
.length(4, '验证码为 4 位'),
}).refine((data) => data.password === data.confirmPassword, {
message: '两次密码输入不一致',
path: ['confirmPassword'],
});
export type RegisterFormValues = z.infer<typeof registerSchema>;
// ==================== 用户更新表单 ====================
export const updateUserSchema = z.object({
name: z
.string()
.min(2, '用户名至少 2 位')
.max(20, '用户名最多 20 位')
.optional(),
email: z
.string()
.email('邮箱格式不正确')
.optional(),
});
export type UpdateUserFormValues = z.infer<typeof updateUserSchema>;
// ==================== 忘记密码表单 ====================
export const forgotPasswordSchema = z.object({
email: z
.string()
.min(1, '请输入邮箱')
.email('邮箱格式不正确'),
captchaId: z.string().min(1, '验证码 ID 不能为空'),
captchaCode: z
.string()
.min(1, '请输入验证码')
.length(4, '验证码为 4 位'),
});
export type ForgotPasswordFormValues = z.infer<typeof forgotPasswordSchema>;
// ==================== 重置密码表单 ====================
export const resetPasswordSchema = z.object({
password: z
.string()
.min(1, '请输入新密码')
.min(6, '密码至少 6 位')
.max(32, '密码最多 32 位'),
confirmPassword: z.string().min(1, '请确认密码'),
}).refine((data) => data.password === data.confirmPassword, {
message: '两次密码输入不一致',
path: ['confirmPassword'],
});
export type ResetPasswordFormValues = z.infer<typeof resetPasswordSchema>;

65
apps/web/src/proxy.ts Normal file
View File

@@ -0,0 +1,65 @@
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
// 需要认证的路由
const protectedRoutes = ['/dashboard', '/users', '/settings', '/profile'];
// 认证页面(已登录用户应该跳转)
const authRoutes = ['/login', '/register', '/forgot-password'];
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// 从 cookie 获取 tokenZustand persist 存储在 localStorage但我们可以同步到 cookie
// 由于 proxy 运行在服务器端,无法访问 localStorage我们使用 cookie
const authStorage = request.cookies.get('auth-storage')?.value;
let isAuthenticated = false;
if (authStorage) {
try {
const parsed = JSON.parse(authStorage);
isAuthenticated = !!parsed.state?.token;
} catch {
isAuthenticated = false;
}
}
// 检查是否访问受保护路由
const isProtectedRoute = protectedRoutes.some(
(route) => pathname === route || pathname.startsWith(`${route}/`)
);
// 检查是否访问认证页面
const isAuthRoute = authRoutes.some(
(route) => pathname === route || pathname.startsWith(`${route}/`)
);
// 未登录访问受保护路由 -> 跳转登录
if (isProtectedRoute && !isAuthenticated) {
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('redirect', pathname);
return NextResponse.redirect(loginUrl);
}
// 已登录访问认证页面 -> 跳转仪表盘
if (isAuthRoute && isAuthenticated) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* 匹配所有路径除了:
* - api (API routes)
* - _next/static (静态文件)
* - _next/image (图片优化)
* - favicon.ico (favicon)
* - public 文件夹
*/
'/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)' ,
],
};

View File

@@ -0,0 +1,40 @@
import type {
AuthResponse,
AuthUser,
LoginDto,
RefreshTokenResponse,
RegisterDto,
} from '@seclusion/shared';
import { API_ENDPOINTS } from '@/config/constants';
import { http } from '@/lib/http';
export const authService = {
// 登录(公开接口,跳过认证)
login: (data: LoginDto): Promise<AuthResponse> => {
return http.post<AuthResponse>(API_ENDPOINTS.AUTH.LOGIN, data, {
skipAuth: true,
});
},
// 注册(公开接口,跳过认证)
register: (data: RegisterDto): Promise<AuthResponse> => {
return http.post<AuthResponse>(API_ENDPOINTS.AUTH.REGISTER, data, {
skipAuth: true,
});
},
// 刷新 Token公开接口跳过认证
refreshToken: (refreshToken: string): Promise<RefreshTokenResponse> => {
return http.post<RefreshTokenResponse>(
API_ENDPOINTS.AUTH.REFRESH,
{ refreshToken },
{ skipAuth: true }
);
},
// 获取当前用户信息
getMe: (): Promise<AuthUser> => {
return http.get<AuthUser>(API_ENDPOINTS.AUTH.ME);
},
};

View File

@@ -0,0 +1,2 @@
export { authService } from './auth.service';
export { userService, type GetUsersParams } from './user.service';

View File

@@ -0,0 +1,50 @@
import type {
PaginatedResponse,
UpdateUserDto,
UserResponse,
} from '@seclusion/shared';
import { API_ENDPOINTS } from '@/config/constants';
import { http } from '@/lib/http';
export interface GetUsersParams {
page?: number;
pageSize?: number;
search?: string;
}
export const userService = {
// 获取用户列表
getUsers: (params: GetUsersParams = {}): Promise<PaginatedResponse<UserResponse>> => {
return http.get<PaginatedResponse<UserResponse>>(API_ENDPOINTS.USERS, {
params,
});
},
// 获取已删除的用户列表
getDeletedUsers: (params: GetUsersParams = {}): Promise<PaginatedResponse<UserResponse>> => {
return http.get<PaginatedResponse<UserResponse>>(`${API_ENDPOINTS.USERS}/deleted`, {
params,
});
},
// 获取单个用户
getUser: (id: string): Promise<UserResponse> => {
return http.get<UserResponse>(`${API_ENDPOINTS.USERS}/${id}`);
},
// 更新用户
updateUser: (id: string, data: UpdateUserDto): Promise<UserResponse> => {
return http.patch<UserResponse>(`${API_ENDPOINTS.USERS}/${id}`, data);
},
// 删除用户(软删除)
deleteUser: (id: string): Promise<void> => {
return http.delete<void>(`${API_ENDPOINTS.USERS}/${id}`);
},
// 恢复用户
restoreUser: (id: string): Promise<UserResponse> => {
return http.patch<UserResponse>(`${API_ENDPOINTS.USERS}/${id}/restore`);
},
};

View File

@@ -0,0 +1,114 @@
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import type { AuthStore } from './types';
import { STORAGE_KEYS } from '@/config/constants';
const initialState = {
token: null,
refreshToken: null,
tokenExpiresAt: null,
refreshTokenExpiresAt: null,
user: null,
isHydrated: false,
};
// 同步 auth 状态到 cookie供 proxy 使用)
function syncToCookie(state: { token: string | null }) {
if (typeof document === 'undefined') return;
if (state.token) {
// 设置 cookie有效期 7 天
document.cookie = `${STORAGE_KEYS.AUTH}=${JSON.stringify({ state })}; path=/; max-age=${7 * 24 * 60 * 60}; SameSite=Lax`;
} else {
// 清除 cookie
document.cookie = `${STORAGE_KEYS.AUTH}=; path=/; max-age=0`;
}
}
export const useAuthStore = create<AuthStore>()(
persist(
(set, get) => ({
...initialState,
setAuth: (token, refreshToken, user, accessTokenExpiresIn, refreshTokenExpiresIn) => {
const now = Date.now();
set({
token,
refreshToken,
user,
// 将秒数转换为过期时间戳(毫秒)
tokenExpiresAt: now + accessTokenExpiresIn * 1000,
refreshTokenExpiresAt: now + refreshTokenExpiresIn * 1000,
});
syncToCookie({ token });
},
setUser: (user) => set({ user }),
logout: () => {
set({
token: null,
refreshToken: null,
tokenExpiresAt: null,
refreshTokenExpiresAt: null,
user: null,
});
syncToCookie({ token: null });
},
clearAuth: () => {
set({
token: null,
refreshToken: null,
tokenExpiresAt: null,
refreshTokenExpiresAt: null,
user: null,
});
syncToCookie({ token: null });
},
setHydrated: () => set({ isHydrated: true }),
// 检查 token 是否即将过期(默认提前 60 秒刷新)
isTokenExpiringSoon: (bufferSeconds = 60) => {
const { tokenExpiresAt } = get();
if (!tokenExpiresAt) return true;
return Date.now() >= tokenExpiresAt - bufferSeconds * 1000;
},
// 检查 refreshToken 是否过期
isRefreshTokenExpired: () => {
const { refreshTokenExpiresAt } = get();
if (!refreshTokenExpiresAt) return true;
return Date.now() >= refreshTokenExpiresAt;
},
}),
{
name: STORAGE_KEYS.AUTH,
storage: createJSONStorage(() => localStorage),
partialize: (state) => ({
token: state.token,
refreshToken: state.refreshToken,
tokenExpiresAt: state.tokenExpiresAt,
refreshTokenExpiresAt: state.refreshTokenExpiresAt,
user: state.user,
}),
onRehydrateStorage: () => (state) => {
state?.setHydrated();
// 恢复时同步到 cookie
if (state?.token) {
syncToCookie({ token: state.token });
}
},
}
)
);
// Selector hooks for better performance
export const useToken = () => useAuthStore((state) => state.token);
export const useUser = () => useAuthStore((state) => state.user);
export const useIsAuthenticated = () =>
useAuthStore((state) => !!state.token && !!state.user);
export const useIsHydrated = () => useAuthStore((state) => state.isHydrated);

View File

@@ -0,0 +1,3 @@
export { useAuthStore, useToken, useUser, useIsAuthenticated, useIsHydrated } from './authStore';
export { useUIStore, useTheme, useSidebarOpen, useSidebarCollapsed } from './uiStore';
export type { AuthState, AuthActions, AuthStore, UIState, UIActions, UIStore, Theme } from './types';

View File

@@ -0,0 +1,55 @@
import type { AuthUser } from '@seclusion/shared';
// Auth Store 状态类型
export interface AuthState {
token: string | null;
refreshToken: string | null;
/** token 过期时间戳(毫秒) */
tokenExpiresAt: number | null;
/** refreshToken 过期时间戳(毫秒) */
refreshTokenExpiresAt: number | null;
user: AuthUser | null;
isHydrated: boolean;
}
// Auth Store Actions 类型
export interface AuthActions {
setAuth: (
token: string,
refreshToken: string,
user: AuthUser,
accessTokenExpiresIn: number,
refreshTokenExpiresIn: number
) => void;
setUser: (user: AuthUser) => void;
logout: () => void;
clearAuth: () => void;
setHydrated: () => void;
/** 检查 token 是否即将过期(默认提前 60 秒) */
isTokenExpiringSoon: (bufferSeconds?: number) => boolean;
/** 检查 refreshToken 是否过期 */
isRefreshTokenExpired: () => boolean;
}
// Auth Store 完整类型
export type AuthStore = AuthState & AuthActions;
// UI Store 状态类型
export type Theme = 'light' | 'dark' | 'system';
export interface UIState {
theme: Theme;
sidebarOpen: boolean;
sidebarCollapsed: boolean;
}
// UI Store Actions 类型
export interface UIActions {
setTheme: (theme: Theme) => void;
toggleSidebar: () => void;
setSidebarOpen: (open: boolean) => void;
setSidebarCollapsed: (collapsed: boolean) => void;
}
// UI Store 完整类型
export type UIStore = UIState & UIActions;

View File

@@ -0,0 +1,40 @@
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import type { UIStore } from './types';
import { STORAGE_KEYS } from '@/config/constants';
export const useUIStore = create<UIStore>()(
persist(
(set) => ({
theme: 'system',
sidebarOpen: true,
sidebarCollapsed: false,
setTheme: (theme) => set({ theme }),
toggleSidebar: () =>
set((state) => ({ sidebarOpen: !state.sidebarOpen })),
setSidebarOpen: (open) => set({ sidebarOpen: open }),
setSidebarCollapsed: (collapsed) =>
set({ sidebarCollapsed: collapsed }),
}),
{
name: STORAGE_KEYS.UI,
storage: createJSONStorage(() => localStorage),
partialize: (state) => ({
theme: state.theme,
sidebarCollapsed: state.sidebarCollapsed,
}),
}
)
);
// Selector hooks
export const useTheme = () => useUIStore((state) => state.theme);
export const useSidebarOpen = () => useUIStore((state) => state.sidebarOpen);
export const useSidebarCollapsed = () =>
useUIStore((state) => state.sidebarCollapsed);

View File

@@ -26,16 +26,6 @@ export type {
// 重导出验证码场景常量
export { CaptchaScene } from '@seclusion/shared';
// ==================== API 相关类型 ====================
/** API 请求配置 */
export interface FetchOptions extends RequestInit {
/** JWT Token */
token?: string;
/** 跳过加密处理(用于特殊接口如文件上传) */
skipEncryption?: boolean;
}
// ==================== 加密相关类型 ====================
/** 加密配置 */

1043
docs/web/DESIGN.md Normal file

File diff suppressed because it is too large Load Diff

1802
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff