feat: 优化项目目录结构

This commit is contained in:
2025-12-12 17:25:26 +08:00
parent ae627d0496
commit b89f83291e
235 changed files with 0 additions and 0 deletions

41
apps/frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

36
apps/frontend/README.md Normal file
View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@@ -0,0 +1,80 @@
'use client';
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { BlogApi } from "@/lib/api";
import { BlogComment } from "@/lib/types/blogComment";
import { Send, Undo2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
interface BlogCommentToolProps {
blogId: string;
onInsertComment: (b: BlogComment) => void;
replayTarget: BlogComment | null;
handleClearReplayTarget: () => void;
}
export function BlogCommentTool({ blogId, onInsertComment, replayTarget, handleClearReplayTarget }: BlogCommentToolProps) {
const [comment, setComment] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (replayTarget && textareaRef.current) {
textareaRef.current.focus();
textareaRef.current.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'start'
})
}
}, [replayTarget]);
const submit = async () => {
if (comment.trim().length === 0) return;
try {
const res = await BlogApi.createComment(blogId, comment, replayTarget ? replayTarget.id : undefined);
if (res) {
toast.success('发布成功');
setComment('');
onInsertComment(res);
handleClearReplayTarget();
}
} catch (error) {
if ((error as { statusCode: number }).statusCode === 429) {
return toast.error('操作太频繁了,稍后再试吧')
}
toast.error(`${(error as Error).message || '发布失败'}`)
}
}
const getPlaceHolderText = () => {
if (!replayTarget) return '评论';
let replayComment = replayTarget.content.trim();
if (replayComment.length > 8) {
replayComment = replayComment.slice(0, 8) + '...';
}
const replayUser = replayTarget.user ? replayTarget.user.nickname : '匿名';
return `回复 ${replayUser}${replayComment}`;
}
return (
<div className="my-3 flex items-end gap-2">
<Textarea
ref={textareaRef}
placeholder={getPlaceHolderText()}
onChange={v => setComment(v.target.value)}
value={comment} />
<Button variant='outline' size='icon' onClick={() => submit()} disabled={comment.trim().length === 0}>
<Send />
</Button>
{replayTarget && <Button variant='outline' size='icon' onClick={() => handleClearReplayTarget()}>
<Undo2 />
</Button>}
</div>
)
}

View File

@@ -0,0 +1,81 @@
import useSWR from "swr";
import { BlogCommentTool } from "./BlogCommentTool";
import { BlogApi } from "@/lib/api";
import { BlogComment } from "@/lib/types/blogComment";
import { useState } from "react";
import { useUserMe } from "@/hooks/user/use-user-me";
export function BlogComments({ blogId }: { blogId: string }) {
const { data, mutate } = useSWR(
`/api/blog/${blogId}/comments`,
() => BlogApi.getComments(blogId),
)
const { user } = useUserMe();
const insertComment = async (newOne: BlogComment) => {
await mutate(
(comments) => {
if (!comments) return [newOne];
return [newOne, ...comments]
},
{ revalidate: false }
)
}
const [replayTarget, setReplayTarget] = useState<BlogComment | null>(null);
return (
data && <div className="" >
<h1 className="px-2 border-l-4 border-zinc-300"> {data.length}</h1>
<BlogCommentTool
blogId={blogId}
onInsertComment={insertComment}
replayTarget={replayTarget}
handleClearReplayTarget={() => setReplayTarget(null)}
/>
<div className="text-sm text-zinc-600">
{
user ? (<span>{user.nickname}</span>) : (<span></span>)
}
</div>
<div className="flex flex-col">
{
data.filter(d => !d.parentId)
.map((d) => (
<div key={d.id} className="border-b border-zinc-300 py-2 last:border-none">
<h1 className="text-zinc-500">{d.user ? d.user.nickname : '匿名'}</h1>
<div className="whitespace-pre-wrap break-all">{d.content}</div>
<div className="text-xs text-zinc-500 flex gap-2">
<p>{new Date(d.createdAt).toLocaleString()}</p>
<p>{d.address}</p>
<p className="text-zinc-900 cursor-pointer" onClick={() => setReplayTarget(d)}></p>
</div>
{
data.filter(c => c.parentId === d.id).length > 0 && (
<div className="flex flex-col ml-5 my-1">
{
data.filter(c => c.parentId === d.id).map(c => (
<div key={c.id} className="border-b border-zinc-300 py-1 last:border-none">
<h1 className="text-zinc-500">{c.user ? c.user.nickname : '匿名'}</h1>
<div className="whitespace-pre-wrap break-all">{c.content}</div>
<div className="text-xs text-zinc-500 flex gap-2">
<p>{new Date().toLocaleString()}</p>
<p>{c.address}</p>
</div>
</div>
))
}
</div>
)
}
</div>
))
}
</div >
</div>
)
}

View File

@@ -0,0 +1,95 @@
'use client';
import { BlogApi } from "@/lib/api";
import { base62 } from "@/lib/utils";
import { useParams, useSearchParams } from "next/navigation";
import useSWR from "swr";
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import 'highlight.js/styles/github.css'
import { PhotoProvider, PhotoView } from 'react-photo-view';
import 'react-photo-view/dist/react-photo-view.css';
import rehypeRaw from 'rehype-raw'
import { Skeleton } from "@/components/ui/skeleton";
import { BlogComments } from "./components/BlogComments";
import Image from "next/image";
export default function Blog() {
const params = useParams();
const searchParams = useSearchParams();
const hex = Array.from(base62.decode(params.id as string)).map(b => b.toString(16).padStart(2, '0')).join('');
const id = [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32)
].join('-');
const password = searchParams.get('p');
const { data, error, isLoading } = useSWR(
`/api/blog/${id}`,
() => BlogApi.get(id, {
password: password || undefined,
}),
)
return (
<div className="w-full overflow-x-hidden">
<div className="max-w-200 mx-auto px-5 overflow-x-hidden mb-10">
{error && <div className="my-20 text-center text-zinc-600">{error.message}</div>}
{isLoading && (
<div className="flex flex-col gap-2 mt-10">
<Skeleton className="w-full h-10" />
<Skeleton className="w-full h-20" />
<Skeleton className="w-full h-10" />
<Skeleton className="w-full h-20" />
<Skeleton className="w-full h-30" />
</div>
)}
{data && (
<>
<h1 className="text-center text-3xl font-bold mt-10">{data.title}</h1>
<p className="text-sm text-zinc-500 text-center my-5">{new Date(data.createdAt).toLocaleString()}</p>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw, rehypeHighlight]}
components={{
h1: ({ ...props }) => <h1 className="text-3xl font-bold py-2" {...props} />,
h2: ({ ...props }) => <h2 className="text-2xl font-bold py-1" {...props} />,
h3: ({ ...props }) => <h3 className="text-xl font-bold py-0.5" {...props} />,
h4: ({ ...props }) => <h4 className="text-lg font-bold" {...props} />,
h5: ({ ...props }) => <h5 className="text-md font-bold" {...props} />,
p: ({ ...props }) => <p className="py-1 text-zinc-700" {...props} />,
img: ({ src }) => (
<PhotoProvider className="w-full">
<PhotoView src={src as string}>
<div style={{ width: '100%' }}>
<Image src={src as string} width={0} height={0} style={{ width: '100%', height: 'auto' }} unoptimized alt="加载失败" />
</div>
</PhotoView>
</PhotoProvider>
),
th: ({ ...props }) => <th className="text-ellipsis text-nowrap border border-zinc-300 p-2" {...props} />,
td: ({ ...props }) => <td className="border border-zinc-300 p-1" {...props} />,
table: ({ ...props }) => <div className="overflow-x-auto"><table {...props} /></div>,
pre: ({ ...props }) => <pre className="rounded-sm overflow-hidden shadow" {...props} />,
blockquote: ({ ...props }) => <blockquote className="pl-3 border-l-5" {...props} />,
a: ({ ...props }) => <a className="hover:underline" {...props} />,
}}
>{data.content}</ReactMarkdown>
</>
)}
{data && (
<>
<div className="border my-5"></div>
<BlogComments blogId={data.id} />
</>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,63 @@
"use client"
import { Skeleton } from "@/components/ui/skeleton";
import { BlogApi } from "@/lib/api";
import { useCallback } from "react"
import useSWR from "swr";
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert";
import { AlertCircle } from "lucide-react";
import { base62 } from "@/lib/utils";
export default function Blog() {
const formatNumber = useCallback((num: number) => {
if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
} else if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
}
return num.toString();
}, []);
const { data: blogs, error, isLoading } = useSWR(
'/api/blogs',
() => BlogApi.list(),
)
return (
<div className="max-w-120 w-auto mx-auto my-10 flex flex-col gap-8">
{
isLoading && (
<div className="w-full">
<Skeleton className="w-full h-5" />
<Skeleton className="w-full h-10 mt-1" />
<Skeleton className="w-full h-5 mt-5" />
</div>
)
}
{
error && (
<Alert variant="destructive" className="w-full">
<AlertCircle className="h-4 w-4" />
<AlertTitle></AlertTitle>
<AlertDescription>
{error.message}
</AlertDescription>
</Alert>
)
}
{
blogs && blogs.map((blog) => (
<div className="w-full px-5 cursor-default" key={blog.id}>
<a className="text-2xl font-medium cursor-pointer hover:underline" target="_blank" href={`/blog/${base62.encode(Buffer.from(blog.id.replace(/-/g, ''), 'hex'))}`}>{blog.title}</a>
<p className="text-sm font-medium text-zinc-400">{blog.description}</p>
<p className="text-sm font-medium text-zinc-400 mt-3">{new Date(blog.createdAt).toLocaleString()} · {formatNumber(blog.viewCount)} 访</p>
</div>
))
}
</div>
)
}

View File

@@ -0,0 +1,18 @@
import Header from "../../components/Header";
import Footer from "../../components/Footer";
export default function LayoutWithHeaderFooter({
children,
}: {
children: React.ReactNode;
}) {
return (
<>
<Header />
<main className="flex-1 flex flex-col bg-zinc-50">
{children}
</main>
<Footer />
</>
)
}

View File

@@ -0,0 +1,25 @@
'use client';
import favicon from '../favicon.ico';
import Image from 'next/image';
export default function Home() {
return (
<div className="w-full flex-1 flex flex-col items-center justify-center">
<Image
src={favicon.src}
alt="TONE's avatar"
width={180}
height={180}
className="rounded-full duration-400 size-35 md:size-45 select-none"
priority
quality={100}
/>
<h1 className='text-4xl md:text-5xl font-bold mt-5 md:mt-8 gradient-title duration-400 select-none'>(TONE)</h1>
<h2 className='text-lg sm:text-xl md:text-2xl mt-3 font-medium text-zinc-400 duration-400 select-none'></h2>
<div className='flex sm:flex-row flex-col gap-2 sm:gap-10 mt-5 md:mt-8 duration-400'>
<a href='https://space.bilibili.com/474156211' target='_black' className='bg-[#488fe9] hover:bg-[#3972ba] text-center text-white w-45 sm:w-32 px-6 py-2 text-lg rounded-full cursor-pointer'></a>
<a href='https://github.com/tonecn' className='bg-[#da843f] hover:bg-[#c87d3e] text-center text-white w-45 sm:w-32 px-6 py-2 text-lg rounded-full cursor-pointer'>GitHub</a>
</div>
</div>
);
}

View File

@@ -0,0 +1,47 @@
import { ResourceBadge } from "@/components/resource";
import { Card, CardContent } from "@/components/ui/card";
import { Resource } from "@/lib/types/resource";
import Image from "next/image";
import React from "react";
interface ResourceCardProps extends React.HTMLProps<HTMLAnchorElement> {
r: Resource;
}
export function ResourceCard({ r, ...props }: ResourceCardProps) {
const [imageError, setImageError] = React.useState(false);
return (
<a href={r.link} target="_blank" {...props}>
<Card className="w-full md:w-92 lg:w-100 md:rounded-xl rounded-none duration-300">
<CardContent>
<div className="flex gap-6">
<div>
{!imageError && <Image
src={r.imageUrl}
alt="资源图片"
width={90}
height={90}
className="rounded-md shadow"
priority
quality={80}
onError={() => setImageError(true)}
/>}
</div>
<div className="flex-1 overflow-x-hidden">
<div className="font-bold text-2xl">{r.title}</div>
<div className="font-medium text-sm text-zinc-400 mt-1">{r.description}</div>
<div className="flex gap-2 flex-wrap mt-4">
{
r.tags.map((tag) => (
<ResourceBadge key={tag.name} tag={tag} />
))
}
</div>
</div>
</div>
</CardContent>
</Card>
</a>
)
}

View File

@@ -0,0 +1,56 @@
"use client";
import useSWR from "swr";
import { ResourceCard } from "./components/ResourceCard";
import { ResourceApi } from "@/lib/api";
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert"
import { AlertCircle } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
export default function Resources() {
const { data, isLoading, error } = useSWR(
'/api/resource',
() => ResourceApi.list(),
);
return (
<div className="flex-1 flex flex-col items-center">
<h1 className="mt-6 md:mt-20 text-2xl md:text-5xl font-medium text-zinc-800 text-center duration-300"></h1>
<p className="mt-4 md:mt-8 mx-3 text-zinc-400 text-sm text-center duration-300">
<a className="text-zinc-600">使</a>
使</p>
{
error && (
<div className="mt-10 mx-5">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle></AlertTitle>
<AlertDescription>
{error.message}
</AlertDescription>
</Alert>
</div>
)
}
<div className="mt-6 sm:mt-10 md:mt-15 w-full flex flex-col md:w-auto md:mx-auto md:grid grid-cols-2 2xl:gap-x-35 lg:gap-x-20 gap-x-10 lg:gap-y-10 gap-y-5 sm:mb-10 duration-300">
{isLoading && (
[...Array(3).map((_, i) => (
<Skeleton key={i} className="h-35 w-full md:w-92 lg:w-100 md:rounded-xl rounded-none duration-300" />
))]
)}
{data && data.map((resource) => (
<ResourceCard
key={resource.id}
r={resource}
/>
))}
</div>
</div>
)
}

View File

@@ -0,0 +1,6 @@
import { Metadata } from "next";
export const metadata: Metadata = {
title: "特恩的日志",
description: "一名啥都会一点点的程序员",
};

View File

@@ -0,0 +1,71 @@
'use client';
import { AppSidebar } from "@/components/app-sidebar"
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbList,
BreadcrumbPage,
} from "@/components/ui/breadcrumb"
import {
SidebarInset,
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar"
import { useUserMe } from "@/hooks/user/use-user-me";
import { UserApi } from "@/lib/api";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
export default function ConsoleMenuLayout({
children,
}: {
children: React.ReactNode
}) {
const router = useRouter();
const { user, isLoading, error } = useUserMe({
onError: (e) => {
if (e.statusCode === 401) {
toast.info('登录凭证已失效,请重新登录');
router.replace('/console/login');
}
}
});
if (!isLoading && !error && !user) {
router.replace('/console/login');
localStorage.removeItem('token');
localStorage.removeItem(UserApi.USER_ME_CACHE_KEY);
toast.error('账户状态异常,请重新登录');
}
return (
<SidebarProvider>
<AppSidebar user={user} isUserLoading={isLoading} />
<SidebarInset>
<header className="flex h-16 shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12">
<div className="flex items-center gap-2 px-4">
<SidebarTrigger className="-ml-1" />
<div className="w-[1px] h-4 mr-2 bg-zinc-300"></div>
<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbPage>
{new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long'
}).format(new Date())}
</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
</div>
</header>
<div className="flex flex-1 flex-col gap-4 p-4 pt-0">
{children}
</div>
</SidebarInset>
</SidebarProvider>
)
}

View File

@@ -0,0 +1,7 @@
export default function MailInbox() {
return (
<div>
...
</div>
)
}

View File

@@ -0,0 +1,7 @@
export default function MailManage() {
return (
<div>
...
</div>
)
}

View File

@@ -0,0 +1,7 @@
export default function MailSend() {
return (
<div>
...
</div>
)
}

View File

@@ -0,0 +1,7 @@
export default function MailSent() {
return (
<div>
...
</div>
)
}

View File

@@ -0,0 +1,7 @@
export default function Page() {
return (
<div>
page
</div>
)
}

View File

@@ -0,0 +1,210 @@
'use client';
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Check, CloudUpload, File, Files, X } from "lucide-react";
import React, { useRef, useState } from "react";
import { Progress } from '@/components/ui/progress';
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { OssStore } from "@/lib/oss/OssStore";
import OSS, { Checkpoint } from "ali-oss";
interface UploadManagerProps {
children: React.ReactNode;
ossStore?: OssStore;
handleRefreshFileList?: () => void;
}
interface UploadFileItem {
id: string;
file: File;
status: 'ready' | 'uploading' | 'finish' | 'failed';
progress: number;// 0 ~ 100
}
export function UploadManager({ children, ossStore, handleRefreshFileList }: UploadManagerProps) {
const [filesList, setFileList] = useState<UploadFileItem[]>([]);
const handleFileSelect = (fileList: FileList) => {
setFileList(currentFileList => {
const newFiles: UploadFileItem[] = [];
for (const file of fileList) {
const repeatFile = currentFileList.find(f =>
f.file.name === file.name &&
f.file.size === file.size &&
f.file.lastModified === file.lastModified
);
if (!repeatFile) {
newFiles.push({
id: `${Math.random()}${Date.now()}`,
file: file,
progress: 0,
status: 'ready',
})
}
}
return [...currentFileList, ...newFiles];
})
}
const handleFileDelete = (fileItemId: string) => {
if (isUploading) return toast.warning('上传过程暂时无法删除');
setFileList(currentFileList => currentFileList.filter(i => i.id !== fileItemId))
}
const inputFileRef = useRef<HTMLInputElement>(null);
const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) return;
handleFileSelect(e.target.files);
}
const [fileDroping, setFileDroping] = useState(false);
const handleFileOnDropOver = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
setFileDroping(true);
}
const handleFileOnDrop = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
setFileDroping(false);
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
handleFileSelect(e.dataTransfer.files);
}
}
const [isUploading, setIsUploading] = useState(false);
/** 开始上传文件 */
const handleUpload = async () => {
if (!ossStore) return;
let store: OSS;
try { store = ossStore.getStore(); } catch { return toast.error(`初始化失败`) };
const needUploadFiles = filesList.filter(f => f.status !== 'finish');
if (needUploadFiles.length === 0) return toast.info('请选择需要上传的文件');
let failCount = 0;
setIsUploading(true);
for (const fileItem of needUploadFiles) {
fileItem.status = 'uploading';
await startUploadFile(store, fileItem, ossStore.getWorkDir()).catch(() => { fileItem.status = 'failed'; failCount++; });
fileItem.status = 'finish';
}
setIsUploading(false);
if (failCount > 0) {
toast.warning(`上传完成,本次共有${failCount}个文件上传失败`);
} else {
toast.success(`上传完成,共上传了${needUploadFiles.length}个文件`)
}
// 清空上传成功的文件
setFileList(current => current.filter(f => f.status !== 'finish'));
handleRefreshFileList?.();
}
// 上传单个文件
const startUploadFile = async (store: OSS, fileItem: UploadFileItem, workDir?: string) => {
let checkpoint: Checkpoint | undefined;
await store.multipartUpload(`${workDir ? `${workDir}/` : ''}${fileItem.file.name}`, fileItem.file, {
checkpoint: checkpoint,
progress: (p, cpt) => {
setFileList(currentFileList => {
return currentFileList.map(f => {
if (f.id == fileItem.id) {
f.progress = p * 100;
}
return f;
})
});
checkpoint = cpt;
}
})
}
return (
<Dialog>
<DialogTrigger asChild>
{children}
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div>
<div
onDrop={handleFileOnDrop}
onDragOver={handleFileOnDropOver}
onClick={() => inputFileRef.current?.click()}
className="flex items-center justify-center border shadow rounded select-none cursor-pointer relative">
<div className={cn('flex flex-col items-center py-6 text-zinc-500 text-sm text-center', fileDroping && 'invisible')}>
<div className="flex items-center gap-3">
<CloudUpload className="size-10 text-zinc-400" />
<span> </span>
</div>
<div className="w-full px-5 mt-3 text-xs">
<p>5GB的文件</p>
</div>
</div>
<div className={cn('absolute flex items-center text-zinc-600 gap-1 invisible', fileDroping && 'visible')}>
<Files className="size-6 text-zinc-500" />
<span className="text-sm"></span>
</div>
</div>
<input
type="file"
multiple
ref={inputFileRef}
className="hidden"
onChange={handleFileInputChange} />
</div>
<div>
{
filesList.map(f => (
<div
key={f.id}
className="group hover:bg-zinc-100 duration-300 rounded px-1 py-1">
<div className="flex justify-between items-center">
<div className="flex items-center gap-1">
<File className="size-4 text-zinc-500" />
{/* 存在一个bug文本省略无法自动适配容器宽度 */}
<div className="text-sm text-zinc-800 overflow-hidden text-nowrap text-ellipsis max-w-60">
{f.file.name}
</div>
</div>
<div>
{f.status === 'finish' && <Check className="size-4 text-green-600 group-hover:hidden" />}
<X
onClick={() => handleFileDelete(f.id)}
className="size-4 text-zinc-500 cursor-pointer hover:text-zinc-600 hidden group-hover:block" />
</div>
</div>
<div className="h-0 w-full relative">
{f.status === 'uploading' && <Progress value={f.progress} className="h-1" />}
</div>
</div>
))
}
</div>
<DialogFooter>
<Button
type="button"
className="cursor-pointer"
onClick={handleUpload}
disabled={isUploading}></Button>
</DialogFooter>
</DialogContent>
</Dialog >
)
}

View File

@@ -0,0 +1,164 @@
'use client';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Delete, Download, RefreshCcw, Upload } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { UploadManager } from './components/UploadManager';
import { OssObjectItem, OssObjectList, OssStore } from '@/lib/oss/OssStore';
import { useOssStore } from '@/hooks/admin/web/blog/use-oss-store';
import OSS from 'ali-oss';
const formatSizeNumber = (n: number) => {
const unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
for (const [i] of unit.entries()) {
if (n < 1024 ** (i + 1)) {
if (i <= 0) {
return `${(n)}${unit[i]}`;
} else {
return `${(n / 1024 ** i).toFixed(2)}${unit[i]}`;
}
}
}
}
const ossStore = new OssStore();
export default function Page() {
const [objectList, setObjectList] = useState<OssObjectList>(null)
ossStore.setSetObjectList(setObjectList);
const storeMeta = useOssStore();
useEffect(() => {
const data = storeMeta.stsTokenData;
if (!data) return;
const store = new OSS({
region: 'oss-cn-chengdu',
bucket: 'tone-personal',
accessKeyId: data.AccessKeyId,
accessKeySecret: data.AccessKeySecret,
stsToken: data.SecurityToken,
refreshSTSToken: async () => {
await storeMeta.refresh();
if (!storeMeta.stsTokenData) throw new Error();
const { AccessKeyId, AccessKeySecret, SecurityToken } = storeMeta.stsTokenData;
return {
accessKeyId: AccessKeyId,
accessKeySecret: AccessKeySecret,
stsToken: SecurityToken,
};
},
})
ossStore.setStore(store);
ossStore.setWorkDir(`tone-page/${data.userId}`)
ossStore.loadObjectList();
// eslint-disable-next-line react-hooks/exhaustive-deps -- storeMeta引用会导致无限循环依赖stsTokenData即可
}, [storeMeta.stsTokenData]);
const handleRefreshFileList = async () => ossStore.loadObjectList().catch(e => toast.error(e.message));
const handleCheckboxChange = ossStore.handleObjectCheckedStateChanged.bind(ossStore);
const checkedFileIds = useMemo(() => {
return (objectList || []).filter(i => i.isChecked).map(i => i.id);
}, [objectList])
const handleDeleteObject = async (objectItem: OssObjectItem) => {
await ossStore.deleteObject(objectItem)
.then(() => ossStore.loadObjectList())
.catch(e => toast.error(`${e.message}`))
}
const handleDeleteCheckedFiles = async () => {
if (!objectList) return;
const checkedObjects = objectList.filter(o => o.isChecked);
const res = await ossStore.deleteCheckedObjects(checkedObjects);
if (res.failed > 0) {
toast.warning(`删除完成,共有${res.failed}个文件删除失败`)
} else {
toast.success(`${res.all}个文件删除完成`)
}
handleRefreshFileList();
}
const handleDownloadObject = async (objectItem: OssObjectItem) => {
ossStore.downloadObject(objectItem).catch(e => toast.error(`${e.message}`));
}
return (
<div>
<div className='mt-1 flex gap-2'>
<UploadManager
ossStore={ossStore}
handleRefreshFileList={handleRefreshFileList}
>
<Button variant='default' className='cursor-pointer'><Upload /></Button>
</UploadManager>
<Button
variant='destructive'
className='cursor-pointer'
disabled={(checkedFileIds.length) <= 0}
onClick={() => handleDeleteCheckedFiles()}
><Delete /></Button>
<div className='flex items-center'>
<Button variant='secondary' size='icon' className='cursor-pointer' onClick={() => handleRefreshFileList()}><RefreshCcw /></Button>
{objectList && <div className='text-sm ml-2'> {objectList.length} 100</div>}
</div>
</div>
<Table>
<TableCaption>
{objectList === null && <div>...</div>}
{/* {error && <div>{`${error}`}</div>} */}
{objectList && objectList.length === 0 && <div></div>}
</TableCaption>
<TableHeader>
<TableRow>
<TableHead className='w-10'></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{
objectList && objectList.map(d => (
<TableRow key={d.name} >
<TableCell>
<Checkbox checked={d.isChecked} onCheckedChange={v => handleCheckboxChange(d.id, Boolean(v))} />
</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger className='whitespace-normal break-all cursor-pointer text-left'>
{d.name}
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onClick={() => handleDownloadObject(d)}><Download /></DropdownMenuItem>
{/* <DropdownMenuItem><Edit />编辑</DropdownMenuItem> */}
<DropdownMenuItem onClick={() => handleDeleteObject(d)}><Delete /></DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
<TableCell>{formatSizeNumber(d.size)}</TableCell>
<TableCell className='whitespace-normal break-words'>{d.lastModified.toLocaleString()}</TableCell>
</TableRow>
))
}
</TableBody>
</Table>
</div >
)
}

View File

@@ -0,0 +1,89 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from "@/components/ui/drawer"
import { useState } from "react";
import { AdminApi } from "@/lib/api";
import { toast } from "sonner";
import { ApiError } from "next/dist/server/api-utils";
interface CreateUserEditorProps {
children: React.ReactNode;
onRefresh: () => void;
}
export function CreateUserEditor({ children, onRefresh }: CreateUserEditorProps) {
const [open, setOpen] = useState(false);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
try {
await AdminApi.user.create({
username: formData.get("username")?.toString() || null,
nickname: formData.get("nickname")?.toString() || null,
email: formData.get("email")?.toString() || null,
phone: formData.get("phone")?.toString() || null,
password: formData.get("password")?.toString() || null,
});
setOpen(false);
toast.success('创建成功')
onRefresh();
} catch (error) {
toast.error((error as ApiError).message || '创建失败')
}
}
return (
<>
<div onClick={() => setOpen(true)} className="cursor-pointer">
{children}
</div>
<Drawer open={open} onClose={() => setOpen(false)}>
<DrawerContent>
<DrawerHeader className="text-left">
<DrawerTitle></DrawerTitle>
<DrawerDescription></DrawerDescription>
</DrawerHeader>
<form className="grid items-start gap-4 px-4" onSubmit={handleSubmit}>
<div className="grid gap-2">
<Label htmlFor="username"></Label>
<Input id="username" name="username" />
</div>
<div className="grid gap-2">
<Label htmlFor="nickname"></Label>
<Input id="nickname" name="nickname" />
</div>
<div className="grid gap-2">
<Label htmlFor="email"></Label>
<Input id="email" name="email" />
</div>
<div className="grid gap-2">
<Label htmlFor="phone"></Label>
<Input id="phone" name="phone" />
</div>
<div className="grid gap-2">
<Label htmlFor="password"></Label>
<Input id="password" name="password" />
</div>
<Button type="submit"></Button>
</form>
<DrawerFooter className="pt-2">
<DrawerClose asChild>
<Button variant="outline"></Button>
</DrawerClose>
</DrawerFooter>
</DrawerContent>
</Drawer>
</>
)
}

View File

@@ -0,0 +1,234 @@
'use client';
import * as React from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from "@/components/ui/drawer"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useUser } from "@/hooks/admin/user/use-user";
import { User } from "@/lib/types/user";
import { Skeleton } from "@/components/ui/skeleton";
import { AdminApi } from "@/lib/api";
import { toast } from "sonner";
import {
Alert,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert"
import { AlertCircle } from "lucide-react";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
export function UserInfoEditor({
onClose,
onUserUpdate,
onUserSoftDelete,
userId,
}: {
onClose: () => void,
onUserUpdate: (user: User) => void,
onUserSoftDelete: (userId: string) => void,
userId: string
}) {
const { user, isLoading, error } = useUser(userId);
// const [saveLoading, setSaveLoading] = React.useState(false);
const handleSave = async (user: {
username: string;
nickname: string;
email: string | null;
phone: string | null;
}) => {
try {
// setSaveLoading(true);
const res = await AdminApi.user.update(userId, user);
if (res) {
toast.success("保存成功");
onUserUpdate(res);
onClose();
} else {
throw new Error();
}
} catch (error) {
toast.error((error as Error).message || "保存失败");
} finally {
// setSaveLoading(false);
}
}
// const [removeLoading, setRemoveLoading] = React.useState(false);
const handleRemove = async (userId: string) => {
try {
// setRemoveLoading(true);
await AdminApi.user.remove(userId, true);
toast.success("注销成功");
onUserSoftDelete(userId);
onClose();
} catch (error) {
toast.error((error as Error).message || "注销失败");
} finally {
// setRemoveLoading(false);
}
}
const [passwordDialogOpen, setPasswordDialogOpen] = React.useState(false);
// const [setPasswordLoading, setSetPasswordLoading] = React.useState(false);
const handleSetPassword = async (userId: string, password: string) => {
try {
// setSetPasswordLoading(true);
await AdminApi.user.setPassword(userId, password);
toast.success("密码修改成功");
setPasswordDialogOpen(false);
} catch (error) {
toast.error((error as Error).message || "密码修改失败");
} finally {
// setSetPasswordLoading(false);
}
}
return (
<Drawer open={!!userId} onClose={onClose} >
<DrawerContent>
<DrawerHeader className="text-left">
<DrawerTitle></DrawerTitle>
<DrawerDescription></DrawerDescription>
</DrawerHeader>
{user && <ProfileForm className="px-4"
user={user}
onSetPassword={handleSetPassword}
onRemove={handleRemove}
passwordDialogOpen={passwordDialogOpen}
setPasswordDialogOpen={setPasswordDialogOpen}
onSubmit={(e) => {
e.preventDefault()
const formData = new FormData(e.currentTarget);
handleSave({
username: formData.get("username")?.toString() as unknown as string,
nickname: formData.get("nickname")?.toString() as unknown as string,
email: formData.get("email")?.toString() || null,
phone: formData.get("phone")?.toString() || null,
})
}} />}
{isLoading &&
[...Array(5)].map((_, i) => (
<Skeleton className="h-20 mx-4 my-1" key={i} />
))
}
{
error && (
<Alert variant="destructive" className="mx-4">
<AlertCircle className="h-6 w-6" />
<AlertTitle>!</AlertTitle>
<AlertDescription>{error.message}</AlertDescription>
</Alert>
)
}
<DrawerFooter className="pt-2">
<DrawerClose asChild>
<Button variant="outline"></Button>
</DrawerClose>
</DrawerFooter>
</DrawerContent>
</Drawer>
)
}
function ProfileForm({ className, user, onSetPassword, onRemove, passwordDialogOpen, setPasswordDialogOpen, ...props }:
React.ComponentProps<"form"> & {
user: User;
onSetPassword: (userId: string, password: string) => Promise<void>;
onRemove: (userId: string) => Promise<void>;
passwordDialogOpen: boolean;
setPasswordDialogOpen: (s: boolean) => void;
}) {
const [newPassword, setNewPassword] = React.useState<string>("");
return (
<form className={cn("grid items-start gap-4", className)} {...props}>
<div className="grid gap-2">
<Label htmlFor="userId">UserId</Label>
<Input id="userId" name="userId" defaultValue={user.userId} disabled />
</div>
<div className="grid gap-2">
<Label htmlFor="username"></Label>
<Input id="username" name="username" defaultValue={user.username} />
</div>
<div className="grid gap-2">
<Label htmlFor="nickname"></Label>
<Input id="nickname" name="nickname" defaultValue={user.nickname} />
</div>
<div className="grid gap-2">
<Label htmlFor="email"></Label>
<Input id="email" name="email" defaultValue={user.email} />
</div>
<div className="grid gap-2">
<Label htmlFor="phone"></Label>
<Input id="phone" name="phone" defaultValue={user.phone} />
</div>
<div className="w-full flex gap-5">
<Dialog open={passwordDialogOpen} onOpenChange={setPasswordDialogOpen}>
<DialogTrigger asChild>
<Button type="button" variant="secondary" className="flex-1" onClick={() => setNewPassword('')}></Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]" >
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
6-32
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="password" className="text-right">
</Label>
<Input
id="password"
name="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="col-span-3"
/>
</div>
</div>
<DialogFooter>
<Button type="button" onClick={() => onSetPassword(user.userId, newPassword)}></Button>
</DialogFooter>
</DialogContent>
</Dialog>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button type="button" variant="destructive" className="flex-1"></Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>?</AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={() => onRemove(user.userId)}></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
<Button type="submit"></Button>
</form>
)
}

View File

@@ -0,0 +1,156 @@
'use client';
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { TooltipContent, TooltipProvider, TooltipTrigger, Tooltip } from "@/components/ui/tooltip";
import { useUserList } from "@/hooks/admin/user/use-user-list";
import { useState } from "react";
import { UserInfoEditor } from "./components/user-info-editor";
import { User } from "@/lib/types/user";
import { CreateUserEditor } from "./components/create-user-editor";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { AdminApi } from "@/lib/api";
import { toast } from "sonner";
import { ApiError } from "next/dist/server/api-utils";
export default function Page() {
const { users, isLoading, error, mutate, refresh } = useUserList();
const [editorUserId, setEditorUserId] = useState("");
const handleUserUpdateLocal = async (newUser: User) => {
await mutate(
(data) => {
if (!data) return data;
return {
...data,
items: data.items.map((user) =>
user.userId === newUser.userId ? newUser : user
),
};
},
{
revalidate: false,
}
)
}
const handleUserDeleteLocal = async (userId: string, soft: boolean) => {
await mutate(
(data) => {
if (!data) return data;
return soft ? {
...data,
items: data.items.map(u => u.userId === userId ? { ...u, deletedAt: new Date().toLocaleString() } : u)
} : {
...data,
items: data.items.filter((user) => user.userId !== userId),
};
},
{
revalidate: false,
}
)
}
const [deletedUserId, setDeletedUserId] = useState('');
const handleUserDelete = async (userId: string) => {
try {
await AdminApi.user.remove(userId, false);
toast.success('删除成功');
handleUserDeleteLocal(userId, false);
setDeletedUserId('');
} catch (error) {
toast.error((error as ApiError).message || '删除失败');
}
}
return (
<>
<div>
<CreateUserEditor onRefresh={() => refresh()}>
<Button ></Button>
</CreateUserEditor>
</div>
<Table>
{error && <TableCaption>{error.message}</TableCaption>}
<TableHeader>
<TableRow>
<TableHead className="w-[100px]">userId</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{
users.map((user) => (
<TableRow key={user.userId}>
<TableCell className="font-medium">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="max-w-[100px] overflow-hidden text-ellipsis">{user.userId}</div>
</TooltipTrigger>
<TooltipContent>
<p>{user.userId}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</TableCell>
<TableCell>{user.username}</TableCell>
<TableCell>{user.nickname}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>{user.phone}</TableCell>
<TableCell>
{user.deletedAt
? <Button className="cursor-pointer" variant='destructive' size='sm'
onClick={() => setDeletedUserId(user.userId)}></Button>
: <Button className="cursor-pointer" variant='outline' size='sm'
onClick={() => setEditorUserId(user.userId)}></Button>
}
</TableCell>
</TableRow>
))
}
{isLoading && (
<TableRow>
{
Array.from({ length: 6 }).map((_, index) => (
<TableCell key={index}>
<Skeleton className="h-10 w-full" />
</TableCell>
))
}
</TableRow>
)}
</TableBody>
</Table >
<UserInfoEditor
onClose={() => setEditorUserId('')}
userId={editorUserId}
onUserUpdate={handleUserUpdateLocal}
onUserSoftDelete={userId => handleUserDeleteLocal(userId, true)}
/>
<AlertDialog open={!!deletedUserId} onOpenChange={o => !o && setDeletedUserId('')}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>?</AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={() => handleUserDelete(deletedUserId)}></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}

View File

@@ -0,0 +1,5 @@
export default function Page() {
return (
<div>role</div>
)
}

View File

@@ -0,0 +1,8 @@
export default function Page() {
return (
<div className="text-sm text-zinc-600">
<div>线</div>
<li></li>
</div>
)
}

View File

@@ -0,0 +1,10 @@
export default function Page() {
return (
<div className="text-sm text-zinc-600">
<div>线</div>
<li></li>
<li></li>
<li></li>
</div>
)
}

View File

@@ -0,0 +1,146 @@
'use client'
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { AdminApi } from "@/lib/api";
import { BlogPermission } from "@/lib/types/Blog.Permission.enum";
import { useState } from "react";
import { toast } from "sonner";
import { BlogPermissionCheckBoxs } from "./BlogPermissionCheckBoxs";
interface AddBlogProps {
children: React.ReactNode;
onRefresh: () => void;
}
export default function AddBlog({ children, onRefresh }: AddBlogProps) {
const [open, setOpen] = useState(false);
const [blog, setBlog] = useState({
title: "",
description: "",
contentUrl: "",
permissions: [] as BlogPermission[],
password: "",
});
const handleSubmit = async () => {
try {
const res = await AdminApi.web.blog.create({
...blog,
});
if (res) {
setOpen(false);
onRefresh();
toast.success("添加成功");
setBlog({
title: '',
description: '',
contentUrl: '',
permissions: [],
password: '',
})
} else {
throw new Error();
}
} catch (error) {
toast.error((error as Error).message || "添加失败");
}
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children}
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="title" className="text-right">
</Label>
<Input
id="title"
className="col-span-3"
value={blog.title}
onChange={(e) => setBlog({ ...blog, title: e.target.value })}
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="description" className="text-right">
</Label>
<Input
id="description"
className="col-span-3"
value={blog.description}
onChange={(e) => setBlog({ ...blog, description: e.target.value })}
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="contentUrl" className="text-right">
URL
</Label>
<Input
id="contentUrl"
className="col-span-3"
value={blog.contentUrl}
onChange={(e) => setBlog({ ...blog, contentUrl: e.target.value })}
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label className="text-right">
</Label>
<div className="col-span-3">
{
<BlogPermissionCheckBoxs
permissions={blog.permissions}
onCheckedChange={(p, n) => setBlog({
...blog,
permissions: n ?
[...blog.permissions, p] :
[...blog.permissions].filter(p => p !== p),
})}
/>
}
</div>
</div>
{
blog.permissions.includes(BlogPermission.ByPassword) &&
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="password" className="text-right">
</Label>
<Input
id="password"
className="col-span-3"
value={blog.password}
onChange={(e) => setBlog({ ...blog, password: e.target.value })}
/>
</div>
}
</div>
<DialogFooter>
<Button type="button" variant='secondary' onClick={() => setOpen(false)}></Button>
<Button type="button" onClick={handleSubmit}></Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,167 @@
"use client"
import React, { useState } from "react"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"
import { AdminApi } from "@/lib/api"
import useSWR from "swr"
import { ApiError } from "next/dist/server/api-utils"
import { BlogPermissionCheckBoxs } from "./BlogPermissionCheckBoxs"
import { BlogPermission } from "@/lib/types/Blog.Permission.enum"
import { SetPasswordDialog } from "./SetPasswordDialog"
interface BlogEditProps {
id: string;
children?: React.ReactNode;
onRefresh: () => void;
}
export default function BlogEdit({ id, children, onRefresh }: BlogEditProps) {
const [open, setOpen] = useState(false)
const { data: blog, mutate } = useSWR(
open ? `/api/admin/web/blog/${id}` : null,
() => AdminApi.web.blog.get(id),
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
dedupingInterval: 5000,
}
)
const handleSubmit = async () => {
if (!blog) return;
try {
await AdminApi.web.blog.update(id, {
title: blog.title,
description: blog.description,
contentUrl: blog.contentUrl,
permissions: blog.permissions,
});
toast.success("更新成功")
setOpen(false);
onRefresh();
} catch (error) {
toast.error((error as ApiError).message || "更新失败")
}
}
const handleDelete = async () => {
try {
await AdminApi.web.blog.remove(id);
toast.success("删除成功")
setOpen(false);
onRefresh();
} catch (error) {
toast.error((error as ApiError).message || "删除失败")
}
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children}
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
{
blog && (
<>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="title" className="text-right">
</Label>
<Input
id="title"
className="col-span-3"
value={blog.title}
onChange={(e) => mutate({ ...blog, title: e.target.value }, false)}
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="description" className="text-right">
</Label>
<Input
id="description"
className="col-span-3"
value={blog.description}
onChange={(e) => mutate({ ...blog, description: e.target.value }, false)}
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="contentUrl" className="text-right">
URL
</Label>
<Input
id="contentUrl"
className="col-span-3"
value={blog.contentUrl}
onChange={(e) => mutate({ ...blog, contentUrl: e.target.value }, false)}
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="permissions" className="text-right">
</Label>
<div className="col-span-3">
<BlogPermissionCheckBoxs
permissions={blog.permissions}
onCheckedChange={(permission, newState) => {
mutate({
...blog,
permissions: newState ?
[...blog.permissions, permission] :
blog.permissions.filter(p => p !== permission)
}, false)
}}
/>
</div>
</div>
{
blog.permissions.includes(BlogPermission.ByPassword) &&
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="permissions" className="text-right">
</Label>
<SetPasswordDialog id={id}>
<Button variant='outline'></Button>
</SetPasswordDialog>
</div>
}
</div>
<DialogFooter>
<div className="w-full flex justify-between">
<div>
<Button variant='destructive' onClick={handleDelete}></Button>
</div>
<div>
<Button type="button" variant='secondary' onClick={() => setOpen(false)}></Button>
<Button type="button" onClick={handleSubmit} className="ml-5"></Button>
</div>
</div>
</DialogFooter>
</>
)
}
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,45 @@
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { BlogPermission } from "@/lib/types/Blog.Permission.enum";
const blogPermissions = [
{
permission: BlogPermission.Public,
localText: '公开可读',
},
{
permission: BlogPermission.ByPassword,
localText: '受密码保护',
},
{
permission: BlogPermission.List,
localText: '显示在列表中',
},
{
permission: BlogPermission.AllowComments,
localText: '允许评论',
}
] as const;
interface BlogPermissionCheckBoxsProps {
permissions: BlogPermission[];
onCheckedChange: (permission: BlogPermission, newState: boolean) => void;
}
export function BlogPermissionCheckBoxs({ permissions, onCheckedChange }: BlogPermissionCheckBoxsProps) {
return (
<div className="flex gap-3 gap-x-8 flex-wrap">
{
blogPermissions.map((v, i) => (
<div key={`blog-permission-option-${i}`} className="flex gap-2">
<Checkbox
id={`blog-permission-option-checkbox-${i}`}
checked={permissions.includes(v.permission)}
onCheckedChange={newChecked => onCheckedChange(v.permission, !!newChecked)} />
<Label htmlFor={`blog-permission-option-checkbox-${i}`} className="whitespace-nowrap">{v.localText}</Label>
</div>
))
}
</div>
)
}

View File

@@ -0,0 +1,66 @@
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { Blog } from "@/lib/types/blog"
import BlogEdit from "./BlogEdit"
import { Button } from "@/components/ui/button"
interface BlogTableProps {
blogs: Blog[],
error?: string,
onRefresh: () => void,
}
export default function BlogTable({ blogs, error, onRefresh }: BlogTableProps) {
return (
<Table className="w-full overflow-x-auto">
{
error && (
<TableCaption>{error}</TableCaption>
)
}
<TableHeader>
<TableRow>
<TableHead className="w-[100px]">Id</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead>URL</TableHead>
<TableHead className="text-right"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{blogs.map((blog) => (
<TableRow key={blog.id}>
<TableCell className="font-medium">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="max-w-[100px] overflow-hidden text-ellipsis">{blog.id}</div>
</TooltipTrigger>
<TooltipContent>
<p>{blog.id}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</TableCell>
<TableCell className="whitespace-normal break-all">{blog.title}</TableCell>
<TableCell className="whitespace-normal break-all">{blog.description}</TableCell>
<TableCell className="whitespace-normal break-all">{blog.contentUrl}</TableCell>
<TableCell className="text-right">
<BlogEdit id={blog.id} onRefresh={() => onRefresh()}>
<Button variant={'outline'} size={'sm'}></Button>
</BlogEdit>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)
}

View File

@@ -0,0 +1,99 @@
'use client';
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { AdminApi } from "@/lib/api";
import { base62 } from "@/lib/utils";
import React, { useEffect, useState } from "react";
import { toast } from "sonner";
interface SetPasswordDialogProps {
id: string;
children: React.ReactNode;
}
export function SetPasswordDialog({ id, children }: SetPasswordDialogProps) {
const [open, setOpen] = useState(false);
const [password, setPassword] = useState('');
const handleSubmit = async () => {
if (!password) {
return toast.error('请输入密码');
}
await AdminApi.web.blog.setPassword(id, password).then(() => {
toast.success('修改成功');
setOpen(false);
}).catch(e => {
toast.error(`${e.message || e || '请求失败'}`)
});
}
useEffect(() => {
if (open) {
setPassword('');
}
}, [open])
const handleCopyShareURL = () => {
if (!password) {
return toast.warning('请先填写新密码');
}
const url = `${window.location.origin}/blog/${base62.encode(Buffer.from(id.replace(/-/g, ''), 'hex'))}?p=${password}`;
navigator.clipboard.writeText(url);
toast.success('分享链接复制成功,请点击保存按钮以提交新密码');
}
return (
<Dialog open={open} onOpenChange={v => setOpen(v)}>
<form>
<DialogTrigger asChild>
{children}
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
访URL需要填写完新密码后再点击
</DialogDescription>
</DialogHeader>
<div className="grid gap-4">
<div className="grid gap-3">
<Label htmlFor="new-password"></Label>
<Input
id="new-password"
name="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
</div>
</div>
<DialogFooter>
<div className="w-full flex justify-between">
<div>
<Button variant='secondary' onClick={handleCopyShareURL}>URl</Button>
</div>
<div className="flex gap-5">
<DialogClose asChild>
<Button variant="outline"></Button>
</DialogClose>
<Button type="submit" onClick={handleSubmit}></Button>
</div>
</div>
</DialogFooter>
</DialogContent>
</form>
</Dialog>
)
}

View File

@@ -0,0 +1,21 @@
"use client"
import { useBlogList } from "@/hooks/admin/web/blog/use-blog-list"
import BlogTable from "./components/BlogTable"
import AddBlog from "./components/AddBlog";
import { Button } from "@/components/ui/button";
export default function Page() {
const { blogs, refresh } = useBlogList();
return (
<>
<div>
<AddBlog onRefresh={refresh}>
<Button></Button>
</AddBlog>
</div>
<BlogTable blogs={blogs || []} onRefresh={refresh} />
</>
)
}

View File

@@ -0,0 +1,161 @@
"use client"
import React, { useState } from "react"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { AdminApi } from "@/lib/api"
import { toast } from "sonner"
import { ApiError } from "next/dist/server/api-utils"
import { ResourceBadge } from "@/components/resource"
import AddResourceTag from "./AddResourceTag"
import { Textarea } from "@/components/ui/textarea"
import { Plus } from "lucide-react"
interface AddResourceProps {
children: React.ReactNode;
refresh: () => void;
}
export default function AddResource({ children, refresh }: AddResourceProps) {
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState({
title: "",
description: "",
imageUrl: "",
link: "",
tags: [] as { type: string, name: string }[],
});
const handleSubmit = async () => {
try {
setLoading(true);
await AdminApi.web.resource.create({
...formData,
});
toast.success("添加成功");
setOpen(false);
refresh();
} catch (error) {
toast.error((error as ApiError).message || "添加失败");
}
}
const handleOpenChange = (open: boolean) => {
setOpen(open);
if (open) {
setFormData({
title: "",
description: "",
imageUrl: "",
link: "",
tags: [] as { type: string, name: string }[],
});
}
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
{children}
</DialogTrigger>
<DialogContent className="w-300">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-title" className="text-right">
</Label>
<Input
id="admin-web-resource-add-title"
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
className="col-span-3"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-description" className="text-right">
</Label>
<Textarea
id="admin-web-resource-add-description"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
className="col-span-3 max-h-15"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-imageUrl" className="text-right">
URL
</Label>
<Input
id="admin-web-resource-add-imageUrl"
value={formData.imageUrl}
onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value })}
className="col-span-3"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-link" className="text-right">
</Label>
<Input
id="admin-web-resource-add-link"
value={formData.link}
onChange={(e) => setFormData({ ...formData, link: e.target.value })}
className="col-span-3"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-tags" className="text-right">
</Label>
<div className="flex items-center gap-2">
{
formData.tags.map((tag, index) => (
<ResourceBadge tag={tag} key={index} editMode={true} onClose={name => setFormData({ ...formData, tags: formData.tags.filter(tag => tag.name !== name) })} />
))
}
<AddResourceTag onTagAdd={(tag) => {
if (!tag.name) return;
if (formData.tags.find(t => t.name === tag.name)) {
toast.error("标签已存在");
return;
}
setFormData({
...formData,
tags: [...formData.tags, tag],
})
}}>
<Button size='sm' variant='outline'>
<Plus />
</Button>
</AddResourceTag>
</div>
</div>
</div>
<DialogFooter>
<Button type="submit" onClick={handleSubmit} disabled={loading}></Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,79 @@
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { useState } from "react";
interface AddResourceTagProps {
children: React.ReactNode;
onTagAdd: (tag: { name: string; type: string }) => void;
}
export default function AddResourceTag({ onTagAdd, children }: AddResourceTagProps) {
const [open, setOpen] = useState(false);
const [tag, setTag] = useState({ name: '', type: 'default' });
function handleSetOpen(open: boolean) {
setOpen(open);
if (open) {
setTag({ name: '', type: 'default' });
}
}
return (
<Popover open={open} onOpenChange={handleSetOpen}>
<PopoverTrigger asChild>
{children}
</PopoverTrigger>
<PopoverContent className="w-80">
<div className="grid gap-4">
<div className="space-y-2">
<h4 className="font-medium leading-none"></h4>
</div>
<div className="grid gap-2">
<div className="grid grid-cols-3 items-center gap-4">
<Label htmlFor="add-tag-name"></Label>
<Input
id="add-tag-name"
className="col-span-2 h-8"
value={tag.name}
onChange={(e) => setTag({ ...tag, name: e.target.value })}
/>
</div>
<div className="grid grid-cols-3 items-center gap-4">
<Label htmlFor="add-tag-type"></Label>
<Select onValueChange={v => setTag({ ...tag, type: v })} defaultValue="default">
<SelectTrigger className="w-[185px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default"></SelectItem>
<SelectItem value="os">OS</SelectItem>
</SelectContent>
</Select>
</div>
<Button onClick={() => {
onTagAdd({
...tag,
});
setOpen(false);
}}></Button>
</div>
</div>
</PopoverContent>
</Popover>
)
}

View File

@@ -0,0 +1,209 @@
"use client"
import React, { useState } from "react"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"
import { ResourceBadge } from "@/components/resource"
import AddResourceTag from "./AddResourceTag"
import { Textarea } from "@/components/ui/textarea"
import { Plus } from "lucide-react"
import { Resource } from "@/lib/types/resource"
import { AdminApi } from "@/lib/api"
import useSWR from "swr"
import { ApiError } from "next/dist/server/api-utils"
import { Skeleton } from "@/components/ui/skeleton"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
interface ResourceEditProps {
children: React.ReactNode
id: string;
onRefresh: () => void;
}
export default function ResourceEdit({ children, id, onRefresh }: ResourceEditProps) {
const [open, setOpen] = useState(false);
const { data: resource, isLoading, mutate } = useSWR<Resource>(
open ? [`/api/admin/web/resource/${id}`] : null,
() => AdminApi.web.resource.get(id),
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
dedupingInterval: 5000,
}
)
const handleSubmit = async () => {
if (!resource) return;
try {
await AdminApi.web.resource.update(id, {
title: resource.title,
description: resource.description,
imageUrl: resource.imageUrl,
link: resource.link,
tags: resource.tags,
});
toast.success("资源更新成功");
onRefresh();
setOpen(false);
} catch (error) {
toast.error((error as ApiError).message || "资源更新失败");
}
}
const handleRemove = async (id: string) => {
try {
await AdminApi.web.resource.remove(id);
toast.success("资源删除成功");
onRefresh();
setOpen(false);
} catch (error) {
toast.error((error as ApiError).message || "资源删除失败");
}
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children}
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
{
isLoading && (
[...Array(5)].map((_, index) => (
<Skeleton className="w-full h-14 rounded" key={index} />
))
)
}
{resource && (
<>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-title" className="text-right">
</Label>
<Input
id="admin-web-resource-add-title"
value={resource.title}
onChange={(e) => mutate({ ...resource, title: e.target.value }, false)}
className="col-span-3"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-description" className="text-right">
</Label>
<Textarea
id="admin-web-resource-add-description"
value={resource.description}
onChange={(e) => mutate({ ...resource, description: e.target.value }, false)}
className="col-span-3 max-h-15"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-imageUrl" className="text-right">
URL
</Label>
<Input
id="admin-web-resource-add-imageUrl"
value={resource.imageUrl}
onChange={(e) => mutate({ ...resource, imageUrl: e.target.value }, false)}
className="col-span-3"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-link" className="text-right">
</Label>
<Input
id="admin-web-resource-add-link"
value={resource.link}
onChange={(e) => mutate({ ...resource, link: e.target.value }, false)}
className="col-span-3"
/>
</div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="admin-web-resource-add-tags" className="text-right">
</Label>
<div className="col-span-3 w-full flex flex-wrap items-center gap-2 gap-y-1">
{
resource.tags.map((tag, index) => (
<ResourceBadge tag={tag} key={index} editMode={true} onClose={name => mutate({ ...resource, tags: resource.tags.filter(tag => tag.name !== name) }, false)} />
))
}
<AddResourceTag onTagAdd={(tag) => {
if (!tag.name) return;
if (resource.tags.find(t => t.name === tag.name)) {
toast.error("标签已存在");
return;
}
mutate({
...resource,
tags: [...resource.tags, tag],
}, false)
}}>
<Button size='sm' variant='outline'>
<Plus />
</Button>
</AddResourceTag>
</div>
</div>
</div>
<DialogFooter>
<div className="w-full flex justify-between">
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant={'destructive'}></Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>?</AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={() => handleRemove(id)}></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<div >
<Button variant={'secondary'} onClick={() => setOpen(false)}></Button>
<Button type="button" onClick={handleSubmit} className="ml-3"></Button>
</div>
</div>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,83 @@
"use client"
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Resource } from "@/lib/types/resource";
import { ResourceBadge } from "@/components/resource";
import { Button } from "@/components/ui/button";
import ResourceEdit from "./ResourceEdit";
interface ResourceTableProps {
resources: Resource[];
errorMessage?: string;
onRefresh: () => void;
}
export default function ResourceTable({ resources, errorMessage, onRefresh }: ResourceTableProps) {
return (
<>
<Table>
{errorMessage && <TableCaption>{errorMessage}</TableCaption>}
<TableHeader>
<TableRow>
<TableHead className="w-[100px]">Id</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead>URL</TableHead>
<TableHead></TableHead>
<TableHead></TableHead>
<TableHead className="text-right w-10"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{resources.length > 0 ? resources.map((resource) => (
<TableRow key={resource.id}>
<TableCell className="font-medium">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="max-w-[100px] overflow-hidden text-ellipsis">{resource.id}</div>
</TooltipTrigger>
<TooltipContent>
<p>{resource.id}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</TableCell>
<TableCell className="whitespace-normal break-all">{resource.title}</TableCell>
<TableCell className="whitespace-normal break-all">{resource.description}</TableCell>
<TableCell className="whitespace-normal break-all">{resource.imageUrl}</TableCell>
<TableCell className="whitespace-normal break-all">{resource.link}</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1">
{resource.tags.map((tag, index) => (
<ResourceBadge tag={tag} key={index} />
))}
</div>
</TableCell>
<TableCell className="text-right">
<ResourceEdit id={resource.id} onRefresh={() => onRefresh()}>
<Button variant={'outline'} size={'sm'}></Button>
</ResourceEdit>
</TableCell>
</TableRow>
)) : (
<TableRow>
<TableCell colSpan={7} className="text-center">
<div className="my-5 text-zinc-500"></div>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</>
)
}

View File

@@ -0,0 +1,24 @@
"use client";
import { useResourceList } from "@/hooks/admin/web/resource/use-resource-list"
import ResourceTable from "./components/ResourceTable"
import { Button } from "@/components/ui/button";
import AddResource from "./components/AddResource";
export default function Page() {
const { resources, refresh } = useResourceList();
return (
<>
<div>
<AddResource refresh={refresh}>
<Button></Button>
</AddResource>
</div>
<ResourceTable
resources={resources || []}
onRefresh={refresh}
/>
</>
)
}

View File

@@ -0,0 +1,67 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
import { useState, useCallback } from "react";
import { toast } from "sonner";
import LoginHeader from "./LoginHeader";
import { SendCodeFormData } from "./types";
import { Label } from "@/components/ui/label";
export default function EmailLoginMode({ onSendCode }: { onSendCode: (data: SendCodeFormData) => Promise<boolean> }) {
const [email, setEmail] = useState("");
const handleSendCode = useCallback(() => {
if (!email.trim().match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
toast.error('请输入正确的邮箱地址');
return;
}
onSendCode({
type: 'email',
email,
})
}, [email, onSendCode]);
return (
<>
<LoginHeader />
<div className="grid gap-3">
<Label htmlFor="email"></Label>
<Input
id="email-login-mode-email"
name="email"
type="text"
placeholder="电子邮箱"
value={email}
onChange={(e) => setEmail(e.target.value)}
required />
</div>
<div className="grid gap-3">
<div className="flex items-center h-4">
<Label htmlFor="code"></Label>
</div>
<div className="flex gap-5">
<InputOTP
id="email-login-mode-code"
name="code"
maxLength={6}
pattern={REGEXP_ONLY_DIGITS_AND_CHARS}
required
>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
<Button type="button" variant="secondary" onClick={handleSendCode}></Button>
</div>
</div>
<Button type="submit" className="w-full">
</Button>
</>
)
}

View File

@@ -0,0 +1,12 @@
export default function LoginHeader() {
return (
<>
<div className="flex flex-col items-center text-center">
<h1 className="text-2xl font-bold"></h1>
<p className="text-muted-foreground text-balance">
</p>
</div>
</>
)
}

View File

@@ -0,0 +1,41 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import LoginHeader from "./LoginHeader";
import { Label } from "@/components/ui/label"
export default function PasswordLoginMode({ forgetPassword }: { forgetPassword: () => void }) {
return (
<>
<LoginHeader />
<div className="grid gap-3">
<Label htmlFor="email">//</Label>
<Input
id="password-login-mode-account"
name="account"
type="text"
placeholder="电子邮箱/手机号/账号"
required
/>
</div>
<div className="grid gap-3">
<div className="flex items-center h-4">
<Label htmlFor="password"></Label>
<a
onClick={forgetPassword}
className="ml-auto text-sm underline-offset-2 hover:underline cursor-pointer"
>
</a>
</div>
<Input
id="password-login-mode-password"
name="password"
type="password"
required />
</div>
<Button type="submit" className="w-full">
</Button>
</>
)
}

View File

@@ -0,0 +1,67 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
import { useState, useCallback } from "react";
import { toast } from "sonner";
import LoginHeader from "./LoginHeader";
import { SendCodeFormData } from "./types";
import { Label } from "@/components/ui/label"
export default function PhoneLoginMode({ onSendCode }: { onSendCode: (data: SendCodeFormData) => Promise<boolean> }) {
const [phone, setPhone] = useState("");
const handleSendCode = useCallback(() => {
if (phone.trim().length !== 11) {
toast.error('请输入正确的手机号');
return;
}
onSendCode({
type: 'phone',
phone,
})
}, [phone, onSendCode]);
return (
<>
<LoginHeader />
<div className="grid gap-3">
<Label htmlFor="phone"></Label>
<Input
id="phone-login-mode-phone"
name="phone"
type="text"
placeholder="+86 手机号"
value={phone}
onChange={(e) => setPhone(e.target.value)}
required />
</div>
<div className="grid gap-3">
<div className="flex items-center h-4">
<Label htmlFor="code"></Label>
</div>
<div className="flex gap-5">
<InputOTP
id="phone-login-mode-code"
name="code"
maxLength={6}
pattern={REGEXP_ONLY_DIGITS_AND_CHARS}
required
>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
<Button type="button" variant="secondary" onClick={handleSendCode} disabled></Button>
</div>
</div>
<Button type="submit" className="w-full" disabled>
</Button>
</>
)
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

View File

@@ -0,0 +1,16 @@
export type SubmitMode = 'password' | 'phone' | 'email';
export type LoginFormData = {
type: SubmitMode;
account?: string;
password?: string;
phone?: string;
email?: string;
code?: string;
}
export type SendCodeMode = 'phone' | 'email';
export type SendCodeFormData = {
type: SendCodeMode;
phone?: string;
email?: string;
}

View File

@@ -0,0 +1,149 @@
'use client';
import { authApi, verificationApi } from "@/lib/api";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { KeyRound, Phone, Mail } from "lucide-react";
import EmailLoginMode from "./components/EmailLoginMode";
import PasswordLoginMode from "./components/PasswordLoginMode";
import PhoneLoginMode from "./components/PhoneLoginMode";
import { LoginFormData, SendCodeFormData, SubmitMode } from "./components/types";
import { useCallback, useState } from "react";
import LoginBG from './components/login-bg.jpg';
import Image from "next/image";
import { ApiError } from "@/lib/api/fetcher";
export default function Login() {
const router = useRouter();
const [loginMode, setLoginMode] = useState<SubmitMode>('password');
const handleForgetPassword = useCallback(() => {
toast.warning('开发中,敬请期待!暂时可通过发送邮件至网站管理员进行密码重置。');
}, []);
const handleSendCode = async (data: SendCodeFormData) => {
try {
const res = await verificationApi.send({
type: 'login',
targetType: data.type,
phone: data.phone,
email: data.email,
})
if (res) {
toast.success('验证码已发送,请注意查收');
return true;
} else {
throw new Error();
}
} catch (error) {
toast.error((error as ApiError).message || '验证码发送失败,请稍后再试');
return false;
}
}
const handleSubmit = async (data: LoginFormData) => {
try {
const res = await authApi.login({
...data,
});
if (res.token) {
toast.success('登录成功');
localStorage.setItem('token', res.token);
router.replace('/console');
return true;
} else {
throw new Error();
}
} catch (error) {
toast.error((error as ApiError).message || '登录失败,请稍后再试');
return false;
}
}
return (
<>
<Header />
<div className="flex flex-1 flex-col items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm md:max-w-3xl">
<div className={cn("flex flex-col gap-6")}>
<Card className="overflow-hidden p-0">
<CardContent className="grid p-0 md:grid-cols-2">
<form className="p-6 md:p-8" onSubmit={(e) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
handleSubmit({
type: loginMode,
account: formData.get('account')?.toString(),
password: formData.get('password')?.toString(),
phone: formData.get('phone')?.toString(),
email: formData.get('email')?.toString(),
code: formData.get('code')?.toString(),
})
}}>
<div className="flex flex-col gap-6">
{loginMode === 'password' ? <PasswordLoginMode forgetPassword={handleForgetPassword} /> : null}
{loginMode === 'phone' ? <PhoneLoginMode onSendCode={handleSendCode} /> : null}
{loginMode === 'email' ? <EmailLoginMode onSendCode={handleSendCode} /> : null}
<div className="after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t">
<span className="bg-card text-muted-foreground relative z-10 px-2">
使
</span>
</div>
<div className="grid grid-cols-3 gap-4">
<Button variant={loginMode === 'password' ? 'default' : 'outline'} type="button" className="w-full" onClick={() => setLoginMode('password')}>
<KeyRound />
</Button>
<Button variant={loginMode === 'phone' ? 'default' : 'outline'} type="button" className="w-full" onClick={() => setLoginMode('phone')}>
<Phone />
</Button>
<Button variant={loginMode === 'email' ? 'default' : 'outline'} type="button" className="w-full" onClick={() => setLoginMode('email')}>
<Mail />
</Button>
</div>
<div className="text-center text-sm">
{" "}
<a className="underline underline-offset-4 cursor-pointer" onClick={() => setLoginMode('phone')}>
</a>
</div>
</div>
</form>
<div className="bg-muted relative hidden md:block">
<Image
src={LoginBG.src}
alt="Image"
width={500}
height={500}
className="absolute inset-0 h-full w-full object-cover dark:brightness-[0.2] dark:grayscale"
priority
quality={100}
/>
</div>
</CardContent>
</Card>
<div className="text-muted-foreground *:[a]:hover:text-primary text-center text-xs text-balance *:[a]:underline *:[a]:underline-offset-4">
{" "}
<a href="#" className="underline underline-offset-4">
</a>{" "}
{" "}
<a href="#" className="underline underline-offset-4">
</a>
</div>
</div >
</div>
</div>
<Footer />
</>
)
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

View File

@@ -0,0 +1,147 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
@keyframes gradient-text {
0% {
background-position: 0% center;
}
100% {
background-position: -200% center;
}
}
.gradient-title {
background: linear-gradient(30deg,
#2657e8 0%,
#ef0c7e 25%,
#3527f5 50%,
#ec1111 75%,
#2657e8 100%);
background-size: 400% 200%;
color: transparent;
background-clip: text;
-webkit-background-clip: text;
animation: gradient-text 20s linear infinite;
}

View File

@@ -0,0 +1,44 @@
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "../components/theme-provider";
import { metadata } from "./config/metadata";
import { Toaster } from "sonner";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export { metadata };
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased min-h-screen flex flex-col`}
suppressHydrationWarning
>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<main className="flex-1 flex flex-col bg-zinc-50">
{children}
<Toaster />
</main>
</ThemeProvider>
</body>
</html>
);
}

View File

@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "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

@@ -0,0 +1,47 @@
"use client";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
async function handleCopy(text: string) {
try {
await navigator.clipboard.writeText(text);
toast.success("复制成功");
} catch (error) {
if (error instanceof Error) {
toast.error(`复制失败 ${error.message}`);
}
}
}
export default function Footer() {
return (
<footer className="border-t border-zinc-300 h-3 relative">
<div className="bg-zinc-50 h-20 flex sm:justify-between justify-center items-center sm:px-20 flex-col sm:flex-row">
<div className="flex flex-col items-center sm:block">
<a href="https://beian.miit.gov.cn/" className="text-sm text-zinc-500 hover:border-zinc-500 border-b border-transparent">ICP备2023009516号-1</a>
<div className="text-sm text-zinc-500 cursor-default">© 2025 TONE Page. All rights reserved.</div>
</div>
<div>
<Popover>
<PopoverTrigger>
<div className="cursor-pointer text-zinc-600 hover:border-zinc-600 border-b border-transparent"></div>
</PopoverTrigger>
<PopoverContent className="w-60 mr-5">
<div className="flex items-center">
<div className="text-sm text-nowrap">:</div>
<Button variant="link" className="cursor-pointer select-text" onClick={() => handleCopy('tone@ctbu.net.cn')}>tone@ctbu.net.cn</Button>
</div>
</PopoverContent>
</Popover>
</div>
</div>
</footer>
)
}

View File

@@ -0,0 +1,109 @@
'use client';
import { cn } from "@/lib/utils";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@/components/ui/drawer"
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
export default function Header() {
const router = useRouter();
const pathname = usePathname();
const [showMenu, setShowMenu] = useState(false);
const menuItems = [
{ name: '特恩(TONE)', path: '/' },
{ name: '资源', path: '/resource' },
{ name: '博客', path: '/blog' },
{ name: '控制台', path: '/console' },
];
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>, path: string) => {
e.preventDefault();
if (path === '/console') {
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
router.push(token ? '/console' : '/console/login');
} else {
router.push(path);
}
setShowMenu(false);
}
return (
<header className="sticky top-0 z-50 backdrop-blur-sm bg-white/40 shadow">
<div className="flex items-center justify-between px-10 md:h-18 md:px-20 h-14 duration-300">
<Link
href="/"
className={cn(
"cursor-pointer font-medium text-zinc-500 hover:text-zinc-800 border-b-4 border-transparent duration-200",
pathname === "/" && "text-zinc-800"
)}
>
{pathname === "/"
? <div className="text-2xl"> 🍭</div>
: <div className="md:text-lg">(TONE)</div>}
</Link>
<Drawer direction="right" open={showMenu} onOpenChange={(state) => !state && setShowMenu(false)}>
<DrawerTrigger>
<div className="sm:hidden cursor-pointer text-zinc-600" onClick={() => setShowMenu(true)}>
</div>
</DrawerTrigger>
<DrawerContent>
<DrawerHeader>
<DrawerTitle className="flex justify-between">
<span></span>
<X className="cursor-pointer" onClick={() => setShowMenu(false)} />
</DrawerTitle>
<DrawerDescription></DrawerDescription>
</DrawerHeader>
<div className="w-full flex flex-col px-4 gap-2">
{menuItems.slice(1).map((item) => (
<Link
key={item.name}
href={item.path}
onClick={e => handleClick(e, item.path)}
>
<Button className="w-full" size='lg'
variant={pathname.startsWith(item.path) ? 'default' : 'outline'}
>{item.name}</Button>
</Link>
))}
</div>
</DrawerContent>
</Drawer>
<div className={cn(
"sm:flex items-center gap-12 hidden",
)}>
{menuItems.slice(1).map((item) => (
<Link
key={item.name}
href={item.path}
className={cn(
"cursor-pointer md:text-lg font-medium text-zinc-500 hover:text-zinc-800 border-b-4 border-transparent duration-200",
pathname.startsWith(item.path) && "text-zinc-800 border-b-pink-500"
)}
onClick={e => handleClick(e, item.path)}
>
{item.name}
</Link>
))}
</div>
</div>
</header >
)
}

View File

@@ -0,0 +1,153 @@
"use client"
import * as React from "react"
import {
CloudUpload,
Inbox,
LucideIcon,
Mail,
Server,
SquareTerminal,
Undo2,
UsersRound,
} from "lucide-react"
import { NavMain } from "@/components/nav-main"
import { NavUser } from "@/components/nav-user"
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
} from "@/components/ui/sidebar"
import Link from "next/link"
import { User } from "@/lib/types/user"
import { Role } from "@/lib/types/role"
export function AppSidebar({ user, isUserLoading, ...props }: React.ComponentProps<typeof Sidebar> & { user: User | undefined, isUserLoading: boolean }) {
const data = {
user: {
name: "shadcn",
email: "m@example.com",
avatar: "/avatars/shadcn.jpg",
},
navMain: null as null | {
title: string
url: string
icon?: LucideIcon
isActive?: boolean
isHidden?: boolean
items?: {
title: string
url: string
isHidden?: boolean
}[]
}[],
}
if (!isUserLoading) {
data.navMain = [
{
title: "网站管理",
url: "/console/web",
icon: SquareTerminal,
isHidden: !user?.roles.includes(Role.Admin),
items: [
{
title: "资源",
url: "/console/web/resource",
},
{
title: "博客",
url: "/console/web/blog",
},
],
},
{
title: "用户管理",
url: "/console/user/list",
icon: UsersRound,
isHidden: !user?.roles.includes(Role.Admin),
},
{
title: "邮件系统",
url: "/console/mail",
icon: Mail,
items: [
{
title: "收件箱",
url: "/console/mail/inbox",
},
{
title: "已发送",
url: "/console/mail/sent",
},
{
title: "发送邮件",
url: "/console/mail/send",
},
{
title: "邮件管理",
url: "/console/mail/manage",
isHidden: !user?.roles.includes(Role.Admin),
},
],
},
{
title: "文件存储",
url: "/console/storage",
icon: CloudUpload,
},
{
title: "虚拟云空间",
url: "/console/vspace",
icon: Inbox,
},
{
title: "虚拟主机",
url: "/console/vserver",
icon: Server,
},
{
title: "前往首页",
url: "/",
icon: Undo2,
},
]
}
return (
<Sidebar collapsible="icon" {...props}>
<SidebarHeader>
<SidebarMenu>
<SidebarMenuItem>
<Link href="/console">
<SidebarMenuButton size="lg" asChild>
<div className="cursor-pointer">
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
<SquareTerminal className="size-5" />
</div>
<div className="flex flex-col gap-0.5 leading-none">
<span className="font-semibold"> - </span>
<span className="">v1.0.0</span>
</div>
</div>
</SidebarMenuButton>
</Link>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<NavMain items={data.navMain} />
</SidebarContent>
<SidebarFooter>
<NavUser user={user} isUserLoading={isUserLoading} />
</SidebarFooter>
<SidebarRail />
</Sidebar>
)
}

View File

@@ -0,0 +1,95 @@
"use client"
import { ChevronRight, type LucideIcon } from "lucide-react"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
} from "@/components/ui/sidebar"
import Link from "next/link"
import { Skeleton } from "./ui/skeleton"
export function NavMain({
items,
}: {
items: null | {
title: string
url: string
icon?: LucideIcon
isActive?: boolean
isHidden?: boolean
items?: {
title: string
url: string
isHidden?: boolean
}[]
}[]
}) {
return (
<SidebarGroup>
<SidebarGroupLabel></SidebarGroupLabel>
<SidebarMenu>
{
!items && Array(5).fill(null).map((_, i) => (
<Skeleton key={i} className="w-full h-7 mt-1" />
))
}
{items && items.filter(i => !i.isHidden).map((item) => (
(item.items && item.items.length > 0)
? (
<Collapsible
key={item.title}
asChild
defaultOpen={item.isActive}
className="group/collapsible"
>
<SidebarMenuItem>
<CollapsibleTrigger asChild>
<SidebarMenuButton tooltip={item.title}>
{item.icon && <item.icon />}
<span>{item.title}</span>
<ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
</SidebarMenuButton>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub>
{item.items.filter(i => !i.isHidden).map((subItem) => (
<SidebarMenuSubItem key={subItem.title}>
<SidebarMenuSubButton asChild>
<Link href={subItem.url}>
<span>{subItem.title}</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
))}
</SidebarMenuSub>
</CollapsibleContent>
</SidebarMenuItem>
</Collapsible>
) : (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton tooltip={item.title} asChild>
<Link href={item.url}>
{item.icon && <item.icon />}
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
)
))}
</SidebarMenu>
</SidebarGroup>
)
}

View File

@@ -0,0 +1,144 @@
"use client"
import {
ChevronsUpDown,
KeyRound,
LogOut,
UserRoundCog,
} from "lucide-react"
import {
Avatar,
AvatarFallback,
AvatarImage,
} from "@/components/ui/avatar"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar"
import { authApi, UserApi } from "@/lib/api"
import { Skeleton } from "./ui/skeleton"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import SetPassword from "./nav-user/SetPassword"
import { useState } from "react"
import { User } from "@/lib/types/user"
import UserProfile from "./nav-user/UserProfile"
export function NavUser({ user, isUserLoading }: { user: User | undefined, isUserLoading: boolean }) {
const { isMobile } = useSidebar();
const router = useRouter();
async function logout() {
try {
await authApi.logout();
localStorage.removeItem('token');
localStorage.removeItem(UserApi.USER_ME_CACHE_KEY)
toast.success('登出成功');
router.replace('/console/login');
} catch {
toast.error('登出失败,请稍后再试');
}
}
const [userProfileOpen, setUserProfileOpen] = useState(false);
const [passwordOpen, setPasswordOpen] = useState(false);
return (
<>
<SidebarMenu>
<SidebarMenuItem>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton
size="lg"
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
>
{
user && <>
<Avatar className="h-8 w-8 rounded-lg">
<AvatarImage src={user.avatar} />
<AvatarFallback className="rounded-lg">U</AvatarFallback>
</Avatar>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">{user.nickname}</span>
<span className="truncate text-xs">{user.username}</span>
</div>
</>
}
{
isUserLoading && <div className="w-full flex items-center gap-2">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="flex-1 flex flex-col gap-1">
<Skeleton className="w-full h-4" />
<Skeleton className="w-full h-4" />
</div>
</div>
}
<ChevronsUpDown className="ml-auto size-4" />
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
side={isMobile ? "bottom" : "right"}
align="end"
sideOffset={4}
>
<DropdownMenuLabel className="p-0 font-normal">
{
user &&
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
<Avatar className="h-8 w-8 rounded-lg">
<AvatarImage src={user.avatar} />
<AvatarFallback className="rounded-lg">U</AvatarFallback>
</Avatar>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">{user.nickname}</span>
<span className="truncate text-xs">{user.username}</span>
</div>
</div>
}
{
isUserLoading && <div className="flex items-center gap-2">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="flex-1 flex flex-col gap-1">
<Skeleton className="w-full h-4" />
<Skeleton className="w-full h-4" />
</div>
</div>
}
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setTimeout(() => setUserProfileOpen(true), 0)}>
<UserRoundCog />
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTimeout(() => setPasswordOpen(true), 0)}>
<KeyRound />
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={logout}>
<LogOut />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
</SidebarMenu >
<UserProfile open={userProfileOpen} onOpenChange={setUserProfileOpen} />
<SetPassword open={passwordOpen} onOpenChange={setPasswordOpen} />
</>
)
}

View File

@@ -0,0 +1,74 @@
'use client';
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { FC } from "react";
import { DialogProps } from "@radix-ui/react-dialog";
import { toast } from "sonner";
import { UserApi } from "@/lib/api";
import { ApiError } from "next/dist/server/api-utils";
export default function SetPassword({ onOpenChange, ...props }: React.ComponentProps<FC<DialogProps>>) {
async function handleSetPassword(password: string) {
if (! /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*()_+\-=\[\]{};:'",.<>/?]{6,32}$/.test(password)) {
toast.error('新密码不符合规范,请重新输入');
return;
}
try {
await UserApi.updatePassword(password);
toast.success('新密码设置成功');
onOpenChange?.(false);
} catch (error) {
toast.error((error as ApiError).message || '新密码设置失败');
}
}
return (
<Dialog onOpenChange={onOpenChange} {...props}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
6-32
</DialogDescription>
</DialogHeader>
<form onSubmit={e => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const password = formData.get('password') as string;
handleSetPassword(password);
}}>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="password" className="text-right">
</Label>
<Input
id="password"
name="password"
defaultValue=""
className="col-span-3"
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant='secondary' onClick={() => onOpenChange?.(false)}></Button>
<Button type="submit"></Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog >
)
}

View File

@@ -0,0 +1,34 @@
import { DialogProps } from "@radix-ui/react-dialog";
import React, { FC } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "../ui/button";
export default function UserProfile({ onOpenChange, ...props }: React.ComponentProps<FC<DialogProps>>) {
return (
<Dialog onOpenChange={onOpenChange} {...props}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
6-32
</DialogDescription>
</DialogHeader>
<div>
...
</div>
<DialogFooter>
<Button type="button" variant='secondary' onClick={() => onOpenChange?.(false)}></Button>
</DialogFooter>
</DialogContent>
</Dialog >
)
}

View File

@@ -0,0 +1,34 @@
import { X } from "lucide-react";
interface ResourceBadgeProps extends React.HTMLProps<HTMLDivElement> {
tag: { name: string; type: string | 'os' };
editMode?: boolean;
onClose?: (name: string) => void;
}
export function ResourceBadge({ tag, editMode, onClose, ...props }: ResourceBadgeProps) {
return (
<div
id={tag.name}
className="text-[10px] text-zinc-500 font-medium py-[1px] px-1.5 rounded-full flex items-center gap-1"
style={{
backgroundColor: (() => {
switch (tag.type) {
case 'os':
return '#dbedfd';
default:
return '#e4e4e7';
}
})()
}}
{...props}
>
<span className="text-nowrap">{tag.name}</span>
{
editMode && (
<span onClick={() => onClose?.(tag.name)}><X className="w-3 h-3 text-zinc-800 cursor-pointer" /></span>
)
}
</div>
)
}

View File

@@ -0,0 +1,11 @@
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

View File

@@ -0,0 +1,157 @@
"use client"
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
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,66 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

View File

@@ -0,0 +1,53 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
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 * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md 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 * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-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,59 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
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 shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs 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 shadow-xs 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",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
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-1.5 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 React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "lucide-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="flex items-center justify-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,33 @@
"use client"
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
function Collapsible({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return (
<CollapsiblePrimitive.CollapsibleTrigger
data-slot="collapsible-trigger"
{...props}
/>
)
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return (
<CollapsiblePrimitive.CollapsibleContent
data-slot="collapsible-content"
{...props}
/>
)
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent }

View File

@@ -0,0 +1,135 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-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,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
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 sm:max-w-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.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,132 @@
"use client"
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { cn } from "@/lib/utils"
function Drawer({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
}
function DrawerTrigger({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
}
function DrawerPortal({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
}
function DrawerClose({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
}
function DrawerOverlay({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
return (
<DrawerPrimitive.Overlay
data-slot="drawer-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 DrawerContent({
className,
children,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
return (
<DrawerPortal data-slot="drawer-portal">
<DrawerOverlay />
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
className
)}
{...props}
>
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
)
}
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function DrawerTitle({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
)
}
function DrawerDescription({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}

View File

@@ -0,0 +1,257 @@
"use client"
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-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 flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
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,44 @@
"use client"
import * as React from "react"
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
import { cn } from "@/lib/utils"
function HoverCard({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
}
function HoverCardTrigger({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
return (
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
)
}
function HoverCardContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
return (
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
<HoverCardPrimitive.Content
data-slot="hover-card-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-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</HoverCardPrimitive.Portal>
)
}
export { HoverCard, HoverCardTrigger, HoverCardContent }

View File

@@ -0,0 +1,77 @@
"use client"
import * as React from "react"
import { OTPInput, OTPInputContext } from "input-otp"
import { MinusIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn(
"flex items-center gap-2 has-disabled:opacity-50",
containerClassName
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
)
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-otp-group"
className={cn("flex items-center", className)}
{...props}
/>
)
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & {
index: number
}) {
const inputOTPContext = React.useContext(OTPInputContext)
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
)
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
)
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }

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 flex 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 React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
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,276 @@
"use client"
import * as React from "react"
import * as MenubarPrimitive from "@radix-ui/react-menubar"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Menubar({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
return (
<MenubarPrimitive.Root
data-slot="menubar"
className={cn(
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
className
)}
{...props}
/>
)
}
function MenubarMenu({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
}
function MenubarGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
}
function MenubarPortal({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
}
function MenubarRadioGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
return (
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
)
}
function MenubarTrigger({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
return (
<MenubarPrimitive.Trigger
data-slot="menubar-trigger"
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
className
)}
{...props}
/>
)
}
function MenubarContent({
className,
align = "start",
alignOffset = -4,
sideOffset = 8,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
return (
<MenubarPortal>
<MenubarPrimitive.Content
data-slot="menubar-content"
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in 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-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</MenubarPortal>
)
}
function MenubarItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<MenubarPrimitive.Item
data-slot="menubar-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 MenubarCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
return (
<MenubarPrimitive.CheckboxItem
data-slot="menubar-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs 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">
<MenubarPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
)
}
function MenubarRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
return (
<MenubarPrimitive.RadioItem
data-slot="menubar-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs 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">
<MenubarPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
)
}
function MenubarLabel({
className,
inset,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
inset?: boolean
}) {
return (
<MenubarPrimitive.Label
data-slot="menubar-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function MenubarSeparator({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
return (
<MenubarPrimitive.Separator
data-slot="menubar-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function MenubarShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="menubar-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function MenubarSub({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
}
function MenubarSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<MenubarPrimitive.SubTrigger
data-slot="menubar-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 flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
)
}
function MenubarSubContent({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
return (
<MenubarPrimitive.SubContent
data-slot="menubar-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-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
export {
Menubar,
MenubarPortal,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarGroup,
MenubarSeparator,
MenubarLabel,
MenubarItem,
MenubarShortcut,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarSub,
MenubarSubTrigger,
MenubarSubContent,
}

View File

@@ -0,0 +1,168 @@
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDownIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function NavigationMenu({
className,
children,
viewport = true,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
viewport?: boolean
}) {
return (
<NavigationMenuPrimitive.Root
data-slot="navigation-menu"
data-viewport={viewport}
className={cn(
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
className
)}
{...props}
>
{children}
{viewport && <NavigationMenuViewport />}
</NavigationMenuPrimitive.Root>
)
}
function NavigationMenuList({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
return (
<NavigationMenuPrimitive.List
data-slot="navigation-menu-list"
className={cn(
"group flex flex-1 list-none items-center justify-center gap-1",
className
)}
{...props}
/>
)
}
function NavigationMenuItem({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
return (
<NavigationMenuPrimitive.Item
data-slot="navigation-menu-item"
className={cn("relative", className)}
{...props}
/>
)
}
const navigationMenuTriggerStyle = cva(
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
)
function NavigationMenuTrigger({
className,
children,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
return (
<NavigationMenuPrimitive.Trigger
data-slot="navigation-menu-trigger"
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDownIcon
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
)
}
function NavigationMenuContent({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
return (
<NavigationMenuPrimitive.Content
data-slot="navigation-menu-content"
className={cn(
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
className
)}
{...props}
/>
)
}
function NavigationMenuViewport({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
return (
<div
className={cn(
"absolute top-full left-0 isolate z-50 flex justify-center"
)}
>
<NavigationMenuPrimitive.Viewport
data-slot="navigation-menu-viewport"
className={cn(
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
className
)}
{...props}
/>
</div>
)
}
function NavigationMenuLink({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
return (
<NavigationMenuPrimitive.Link
data-slot="navigation-menu-link"
className={cn(
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function NavigationMenuIndicator({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
return (
<NavigationMenuPrimitive.Indicator
data-slot="navigation-menu-indicator"
className={cn(
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
className
)}
{...props}
>
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
</NavigationMenuPrimitive.Indicator>
)
}
export {
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
navigationMenuTriggerStyle,
}

View File

@@ -0,0 +1,127 @@
import * as React from "react"
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
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 React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
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 React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
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,185 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-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 = "popper",
...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}
{...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 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 React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator-root"
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 React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-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,726 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { VariantProps, cva } from "class-variance-authority"
import { PanelLeftIcon } from "lucide-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContextProps = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}) {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
_setOpen(openState)
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
},
[setOpenProp, open]
)
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
}
}
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className
)}
{...props}
>
{children}
</div>
)
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
)
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar()
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
)
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className
)}
{...props}
/>
)
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
)
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
)
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
)
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
)
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
)
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
)
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
)
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button"
const { isMobile, state } = useSidebar()
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
if (!tooltip) {
return button
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
}
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
)
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
)
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
)
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}

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,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,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 React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
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-primary text-primary-foreground 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-primary fill-primary 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,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;

View File

@@ -0,0 +1,33 @@
"use client"
import { list, UserListParams, UserListResponse } from '@/lib/api/admin/user'
import { useCallback } from 'react'
import { toast } from 'sonner'
import useSWR from 'swr'
export function useUserList(params?: UserListParams) {
const { data, error, isLoading, mutate } = useSWR<UserListResponse>(
['/api/admin/user', params],
() => list(params),
{
onError: (e) => {
toast.error(`${e.message || e}`)
}
}
)
const refresh = useCallback(() => {
return mutate()
}, [mutate])
return {
users: data?.items ?? [],
total: data?.total ?? 0,
page: data?.page ?? 1,
pageSize: data?.pageSize ?? 20,
isLoading,
error,
mutate,
refresh,
}
}

View File

@@ -0,0 +1,26 @@
import { AdminApi } from "@/lib/api";
import { User } from "@/lib/types/user";
import { toast } from "sonner";
import useSWR from "swr";
export function useUser(userId: string) {
const { data, error, isLoading, mutate } = useSWR<User>(
['/api/admin/user', userId],
() => AdminApi.user.get(userId),
{
revalidateOnReconnect: false,
revalidateIfStale: false,
dedupingInterval: 0,
onError: (e) => {
toast.error(`${e.message || e}`)
}
}
)
return {
user: data,
isLoading,
error,
mutate,
}
}

View File

@@ -0,0 +1,30 @@
"use client"
import { AdminApi } from "@/lib/api";
import { useCallback } from "react";
import { toast } from "sonner";
import useSWR from "swr";
export function useBlogList() {
const { data, error, isLoading, mutate } = useSWR(
['/admin/web/blog'],
() => AdminApi.web.blog.list(),
{
onError: (e) => {
toast.error(`${e.message || e}`)
}
}
)
const refresh = useCallback(() => {
return mutate()
}, [mutate])
return {
blogs: data,
error,
isLoading,
mutate,
refresh,
}
}

View File

@@ -0,0 +1,22 @@
import { useOssSts } from "@/hooks/oss/use-oss-sts";
import { StsToken } from "@/lib/api/oss";
import { useEffect } from "react";
export function useOssStore(options: { onStsTokenDataChanged?: (data: StsToken | undefined) => void; } = {}) {
const { stsTokenData, isLoading, error, mutate } = useOssSts();
useEffect(() => {
options.onStsTokenDataChanged?.(stsTokenData);
}, [stsTokenData]);
const refresh = async () => {
await mutate();
}
return {
stsTokenData,
isLoading,
error,
refresh,
}
}

View File

@@ -0,0 +1,30 @@
"use client"
import { AdminApi } from "@/lib/api";
import { useCallback } from "react";
import { toast } from "sonner";
import useSWR from "swr";
export function useResourceList() {
const { data, error, isLoading, mutate } = useSWR(
['/admin/web/resource'],
() => AdminApi.web.resource.list(),
{
onError: (e) => {
toast.error(`${e.message || e}`)
}
}
)
const refresh = useCallback(() => {
return mutate()
}, [mutate])
return {
resources: data,
error,
isLoading,
mutate,
refresh,
}
}

View File

@@ -0,0 +1,25 @@
import { OssApi } from "@/lib/api";
import { toast } from "sonner";
import useSWR from "swr";
export function useOssSts() {
const { data: stsTokenData, isLoading, error, mutate } = useSWR(
'/api/oss/sts',
() => OssApi.getStsToken(),
{
shouldRetryOnError: false,
// refreshInterval: 59 * 60 * 1000,
revalidateOnFocus: false,
onError: (e) => {
toast.error(`${e.message || e}`)
}
}
);
return {
stsTokenData,
isLoading,
error,
mutate,
}
}

View File

@@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

View File

@@ -0,0 +1,41 @@
import { UserApi } from "@/lib/api";
import useSWR from "swr";
export function useUserMe({ onError }: { onError?: (e: any) => void } = {}) {
const isClientSide = typeof window !== 'undefined';
const { data: user, isLoading, error } = useSWR(
'/api/user/me',
async () => {
if (isClientSide && !localStorage.getItem('token')) {
throw Object.assign(new Error('未登录'), { statusCode: -1 });
}
return await UserApi.me();
},
{
onError: (error) => {
if (error.statusCode === 401) {
if (isClientSide) {
localStorage.removeItem('token');
}
}
onError?.(error);
},
revalidateIfStale: false,
revalidateOnFocus: false,
shouldRetryOnError: (err) => {
if ([-1, 401].includes(err.statusCode)) {
return false;
}
return true;
},
}
);
return {
user,
isLoading,
error
}
}

View File

@@ -0,0 +1,2 @@
export * as user from './user/index';
export * as web from './web/index';

View File

@@ -0,0 +1,20 @@
import { User } from "@/lib/types/user";
import fetcher from "../../fetcher";
interface createUserParams {
username: string | null;
nickname: string | null;
email: string | null;
phone: string | null;
password: string | null;
}
export async function create(data: createUserParams) {
return fetcher<User>("/api/admin/user", {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
});
}

View File

@@ -0,0 +1,6 @@
import { User } from "@/lib/types/user";
import fetcher from "../../fetcher";
export function get(userId: string) {
return fetcher<User>(`/api/admin/user/${userId}`);
}

View File

@@ -0,0 +1,6 @@
export * from './list';
export * from './get';
export * from './create';
export * from './update';
export * from './set-password';
export * from './remove';

View File

@@ -0,0 +1,22 @@
import { User } from "@/lib/types/user"
import fetcher from "../../fetcher"
export interface UserListParams {
page?: number
pageSize?: number
}
export interface UserListResponse {
items: User[],
total: number
page: number
pageSize: number
}
export function list(params?: UserListParams): Promise<UserListResponse> {
const searchParams = new URLSearchParams()
if (params?.page) searchParams.set('page', params.page.toString())
if (params?.pageSize) searchParams.set('pageSize', params.pageSize.toString())
return fetcher<UserListResponse>('/api/admin/user')
}

View File

@@ -0,0 +1,7 @@
import fetcher from "../../fetcher";
export async function remove(userId: string, soft: boolean) {
return fetcher(`/api/admin/user/${userId}?soft=${soft}`, {
method: 'DELETE',
})
}

Some files were not shown because too many files have changed in this diff Show More