feat: 管理后台增强——用户启停操作、shadcn日期区间/后缀标签组件

1. 用户管理页:新增启用状态列与启用/禁用操作按钮(对接 user/enable|disable)
2. 机构账号/记录查询页:时间区间改用官方 shadcn Range Picker 模式
   (Popover+Calendar mode=range 双月面板,新增 components/date-range-picker.tsx)
3. 上传配置页:文件类型限制改为标签式输入(新增 suffix-tag-input.tsx,
   Badge标签+回车添加+常用后缀快捷点选),替换自由文本框
4. 修复:.env 的 VITE_APP_TITLE 加引号,规避 Bun 1.3.10 env 解析
   对行尾多字节中文的截断(标题乱码"森睿智�")
5. 新增共享 hook hooks/use-user-status-actions.ts(从 org-account 迁出)
6. vite 代理保留 本地Docker(localhost:8080)/公司 两种目标,切换注释即可
This commit is contained in:
2026-09-15 12:16:14 +08:00
commit d92d7d6752
532 changed files with 177420 additions and 0 deletions

170
src/apis/file.ts Normal file
View File

@@ -0,0 +1,170 @@
import { http, HTTP_CONTENT_TYPE } from "@/lib/http";
const baseUrl = import.meta.env.VITE_API_URL;
export const RootType = {
// 1普通/2内穿外/3外传内/4我的分享
MY: "1",
INSIDE: "2",
OUTSIDE: "3",
SHARE: "4",
} as const;
export type RootType = (typeof RootType)[keyof typeof RootType];
export const FileStatus = {
// 1正常2失效11解析中12待审核13传输中14失败
VALID: "1",
INVALID: "2",
PARSING: "11",
AUDITING: "12",
TRANSFERING: "13",
FAILED: "14",
} as const;
export type FileStatus = (typeof FileStatus)[keyof typeof FileStatus];
export const FileType = {
// 1文件/2目录
FILE: "1",
DIRECTORY: "2",
} as const;
export type FileType = (typeof FileType)[keyof typeof FileType];
// 获取文件下载地址
export const getFileUrl = (code?: string, appendBaseUrl = true) => {
if (!code) {
return;
}
const url = `/file/download/${code}?time=` + Date.now();
if (appendBaseUrl && baseUrl != "/") {
return baseUrl + url;
}
return url;
};
// 下载
export const downloadFile = ({ url, code, ...rest }: any) => {
const newUrl = url ?? getFileUrl(code, false);
if (!newUrl) {
return;
}
return http.get(newUrl, { responseType: "blob", ...rest });
};
// 上传
export const uploadFile = (file: File) => {
const data = new FormData();
data.append("file", file);
const headers = { "content-type": HTTP_CONTENT_TYPE.MULTIPART_FORM_DATA };
return http.post("/file/upload", data, { headers });
};
// 创建分享
export const createShare = (data: any) => {
return http.post("/share_user_file/create", data);
};
// 查询
export const getFile = (params: any) => {
return http.get("/user_file/find", { params });
};
// 失效
export const invalidFile = (id: number) => {
return http.put(`/user_file/invalid/${id}`);
};
// 列表查询
export const getFileList = (params: any) => {
return http.get("/user_file/list", { params });
};
// 修改
export const modifyFile = (data: any) => {
return http.post("/user_file/modify", data);
};
// 分页查询
export const getFilePage = (params: any) => {
return http.get("/user_file/page", { params });
};
// 彻底删除文件
export const removeFile = (id: number) => {
return http.delete(`/user_file/remove/${id}`);
};
// 彻底删除文件
export const removeFileByIds = (ids: number[]) => {
return http.delete(`/user_file/remove_by_ids`, { data: ids });
};
// 创建
export const createFile = (data: any) => {
return http.post("/normal_user_file/create", data);
};
// 恢复
export const recoverFile = (id: number) => {
return http.put(`/normal_user_file/recover/${id}`);
};
// 转移
export const transferFile = (data: any) => {
return http.post(`/transfer_user_file/create`, data);
};
// 获取统计
export const getStatistics = () => {
return http.get(`/user_file/statistics/category`);
};
// 获取风险等级列表
export const getRiskLevel = (params?: any) => {
return http.get("/file_risk/min_audit_risk_level", { params });
};
// 保存风险等级数据
export const saveRiskLevel = (data: any) => {
return http.post("/file_risk/min_audit_risk_level", data);
};
// 获取风险规则列表
export const getRiskRule = (params?: any) => {
return http.get("/file_risk/rule", { params });
};
// 保存风险规则数据
export const saveRiskRule = (data?: any) => {
return http.post("/file_risk/rule", data);
};
// 分页查询
export const getFileRiskPage = (params?: any) => {
return http.get("/file_risk/page", { params });
};
// 分页查询
export const getFilePageSuper = (params: any) => {
return http.get("/user_file/page_super", { params });
};
// 按手机号分页查询文件记录(上传/发送/接收,平台管理员)
export const getFileRecordPageByPhone = (params: any) => {
return http.get("/user_file/record/page_by_phone", { params });
};
// 修改状态
export const modifyFileStatus = (data: any) => {
return http.put("/user_file/modify_status", data);
};
export const getShareFileList = ({ shareId, ...params }: any) => {
return http.get(`/share_user_file/${shareId}`, { params });
};
export const getDiffRiskRule = (fileCode: string) => {
return http.get(`/file_risk/dify_risk_rule`, { params: { fileCode } });
};

17
src/apis/org.ts Normal file
View File

@@ -0,0 +1,17 @@
import { http } from "@/lib/http";
export const getUserPage = (params: any) => {
return http.get("/user/page/platform_user", { params });
};
export const createOrg = (data: any) => {
return http.post("/uc/org/create", data);
};
export const modifyOrg = (data: any) => {
return http.put("/uc/org/modify", data);
};
export const getOrgPage = (params: any) => {
return http.get("/uc/org/page", { params });
};

24
src/apis/upload-config.ts Normal file
View File

@@ -0,0 +1,24 @@
import { http } from "@/lib/http";
// 查询当前机构的上传配置(所有登录用户)
export const getUploadConfig = () => {
return http.get("/upload_config/info");
};
// 保存机构的上传配置(机构管理员/平台超管,upsert)
export const modifyUploadConfig = (data: {
uploadEnabled: boolean;
allowAllType: boolean;
allowedSuffixes?: string[];
maxFileSize?: number;
}) => {
return http.post("/upload_config/modify", data);
};
// 上传预检:按文件名/大小校验当前机构配置,不通过时 success=false
export const checkUploadConfig = (params: {
fileName: string;
fileSize?: number;
}) => {
return http.get("/upload_config/check", { params });
};

68
src/apis/user.ts Normal file
View File

@@ -0,0 +1,68 @@
import { http, HTTP_CONTENT_TYPE } from "@/lib/http";
// 账号登录
export const login = (data = {}) => {
return http.post("/login", data, {
headers: {
"content-type": HTTP_CONTENT_TYPE.APPLICATION_FORM_URLENCODED,
},
});
};
// 登出
export const logout = () => {
return http.post("/logout");
};
// 获取用户信息
export const getUser = () => {
return http.get("/user/info");
};
export const createUser = (data: any) => {
return http.post("/user/create_org_user", data);
};
export const getUserOrg = () => {
return http.get("/uc/org/find");
};
export const cancelUser = (userId: number) => {
return http.post("/user/cancel", { userId });
};
export const modifyUserInfo = (data: any) => {
return http.post("/user/modify_org_user_info", data);
};
export const resetUserPwd = (data: any) => {
return http.post("/user/reset_org_user_pwd", data);
};
export const initUserPassword = (data: any) => {
return http.post("/unac/user/init_user_password", data);
};
export const modifyPassword = (data: any) => {
return http.post("/unac/user/modify_password", data);
};
// 启用用户(平台管理员,幂等)
export const enableUser = (userId: number) => {
return http.post("/user/enable", { userId });
};
// 禁用用户(平台管理员,幂等)
export const disableUser = (userId: number) => {
return http.post("/user/disable", { userId });
};
// 管理员直接注销用户(平台管理员,不走注销审批流程,幂等)
export const adminCancelUser = (userId: number) => {
return http.post("/user/admin_cancel", { userId });
};
// 分页查询机构账号(平台管理员,一行 = 一个机构下的一个账号)
export const getOrgAccountPage = (params: any) => {
return http.get("/user/page/org_account", { params });
};

BIN
src/assets/image/bg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

BIN
src/assets/image/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 378 KiB

View File

@@ -0,0 +1,41 @@
import { useState } from "react";
type Props = {
url?: string;
};
export function AudioPreview({ url }: Props) {
const [error, setError] = useState(false);
if (!url) {
return (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
音频地址无效
</div>
);
}
if (error) {
return (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
音频加载失败,请检查文件格式或网络连接
</div>
);
}
return (
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
<div className="w-full max-w-2xl px-8">
<audio
src={url}
controls
className="w-full"
onError={() => setError(true)}
preload="metadata"
>
您的浏览器不支持音频播放
</audio>
</div>
</div>
);
}

View File

@@ -0,0 +1,52 @@
import mammoth from "mammoth";
import axios from "axios";
import { useQuery } from "@tanstack/react-query";
type Props = {
url?: string;
};
export function DocxPreview({ url }: Props) {
const { data, isLoading, error, isError } = useQuery({
queryKey: ["documentFile", url],
queryFn: () =>
axios
.get(url!, { responseType: "arraybuffer" })
.then(async (response) => {
const result = await mammoth.convertToHtml({
arrayBuffer: response.data,
});
return result.value;
}),
enabled: !!url,
});
if (!url) {
return null;
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-full">
<div>加载中...</div>
</div>
);
}
if (isError) {
return (
<div className="flex items-center justify-center h-full text-red-500">
{error?.message || "加载失败"}
</div>
);
}
return (
<div className="h-full overflow-auto p-4">
<div
className="prose max-w-none"
dangerouslySetInnerHTML={{ __html: data as string }}
/>
</div>
);
}

View File

@@ -0,0 +1,109 @@
import { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import * as XLSX from "xlsx";
type Props = {
url?: string;
};
export function ExcelPreview({ url }: Props) {
const [sheets, setSheets] = useState<{ name: string; data: any[][] }[]>([]);
const [activeSheet, setActiveSheet] = useState(0);
const { data, isLoading, error, isError } = useQuery({
queryKey: ["excel", url],
queryFn: () => axios.get(url!, { responseType: "arraybuffer" }),
enabled: !!url,
});
useEffect(() => {
if (data?.data) {
try {
const workbook = XLSX.read(data.data, { type: "array" });
const sheetData = workbook.SheetNames.map((name) => {
const worksheet = workbook.Sheets[name];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
return { name, data: jsonData as any[][] };
});
setSheets(sheetData);
} catch (err) {
}
}
}, [data]);
if (!url) {
return (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
Excel 文件地址无效
</div>
);
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-full">
<div>加载中...</div>
</div>
);
}
if (isError) {
return (
<div className="flex items-center justify-center h-full text-red-500">
{error?.message || "加载失败"}
</div>
);
}
if (sheets.length === 0) {
return (
<div className="flex items-center justify-center h-full text-muted-foreground">
Excel 文件为空或格式不正确
</div>
);
}
const currentSheet = sheets[activeSheet];
return (
<div className="h-full flex flex-col">
{sheets.length > 1 && (
<div className="flex-none border-b bg-slate-50 dark:bg-slate-900 p-2 flex gap-2 overflow-x-auto">
{sheets.map((sheet, index) => (
<button
key={index}
onClick={() => setActiveSheet(index)}
className={`px-4 py-2 rounded text-sm whitespace-nowrap transition-colors ${
activeSheet === index
? "bg-primary text-primary-foreground"
: "bg-white dark:bg-slate-800 hover:bg-slate-100 dark:hover:bg-slate-700"
}`}
>
{sheet.name}
</button>
))}
</div>
)}
<div className="flex-auto overflow-auto">
<table className="w-full border-collapse text-sm">
<tbody>
{currentSheet.data.map((row, rowIndex) => (
<tr key={rowIndex} className="border-b">
{row.map((cell, cellIndex) => (
<td
key={cellIndex}
className="border-r px-3 py-2 whitespace-nowrap"
>
{cell !== null && cell !== undefined ? String(cell) : ""}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,46 @@
import { useState } from "react";
type Props = {
url?: string;
};
export function ImagePreview({ url }: Props) {
const [error, setError] = useState(false);
const [loading, setLoading] = useState(true);
if (!url) {
return (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
图片地址无效
</div>
);
}
if (error) {
return (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
图片加载失败,请检查文件格式或网络连接
</div>
);
}
return (
<div className="w-full h-full flex items-center justify-center bg-slate-50 dark:bg-slate-900 p-4">
{loading && (
<div className="absolute flex items-center justify-center">
<div className="text-muted-foreground">加载中...</div>
</div>
)}
<img
src={url}
alt="预览图片"
className="max-w-full max-h-full object-contain"
onLoad={() => setLoading(false)}
onError={() => {
setLoading(false);
setError(true);
}}
/>
</div>
);
}

View File

@@ -0,0 +1,56 @@
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeHighlight from "rehype-highlight";
import rehypeRaw from "rehype-raw";
import "highlight.js/styles/github.css";
type Props = {
url?: string;
};
export function MarkdownPreview({ url }: Props) {
const { data, isLoading, error, isError } = useQuery({
queryKey: ["markdown", url],
queryFn: () => axios.get(url!, { responseType: "text" }),
enabled: !!url,
});
if (!url) {
return (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
Markdown 文件地址无效
</div>
);
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-full">
<div>加载中...</div>
</div>
);
}
if (isError) {
return (
<div className="flex items-center justify-center h-full text-red-500">
{error?.message || "加载失败"}
</div>
);
}
return (
<div className="h-full overflow-auto p-8 bg-white dark:bg-slate-950">
<div className="max-w-4xl mx-auto prose prose-slate dark:prose-invert prose-headings:font-bold prose-a:text-blue-600 prose-code:text-pink-600 prose-pre:bg-slate-100 dark:prose-pre:bg-slate-900">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeHighlight, rehypeRaw]}
>
{data?.data || ""}
</ReactMarkdown>
</div>
</div>
);
}

View File

@@ -0,0 +1,137 @@
import { useEffect, useMemo, useState } from "react";
type Props = {
url?: string;
};
export function PDFPreview({ url }: Props) {
const [loaded, setLoaded] = useState(false);
const [blobUrl, setBlobUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [stage, setStage] = useState<"fetch" | "viewer">("fetch");
if (!url) {
return null;
}
const fileUrl = useMemo(() => {
try {
const u = new URL(url);
if (import.meta.env.DEV && u.pathname.startsWith("/anon/")) {
return `${u.pathname}${u.search}`;
}
return url;
} catch {
return url;
}
}, [url]);
useEffect(() => {
let revokedUrl: string | null = null;
const controller = new AbortController();
const timeoutMs = 20000;
setLoaded(false);
setError(null);
setStage("fetch");
setBlobUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
(async () => {
try {
const resp = (await Promise.race([
fetch(fileUrl, {
credentials: "include",
signal: controller.signal,
}),
new Promise((_, reject) =>
setTimeout(() => {
try {
controller.abort();
} catch {
// ignore
}
reject(new Error("PDF fetch timeout"));
}, timeoutMs)
),
])) as Response;
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}`);
}
const buf = await resp.arrayBuffer();
const head = new Uint8Array(buf.slice(0, 5));
const isPdf =
head.length === 5 &&
head[0] === 0x25 &&
head[1] === 0x50 &&
head[2] === 0x44 &&
head[3] === 0x46 &&
head[4] === 0x2d;
if (!isPdf) {
throw new Error("Response is not a PDF");
}
const blob = new Blob([buf], { type: "application/pdf" });
const nextUrl = URL.createObjectURL(blob);
revokedUrl = nextUrl;
setBlobUrl(nextUrl);
setStage("viewer");
} catch (e) {
if ((e as Error)?.name === "AbortError") return;
setError((e as Error)?.message || "Failed to load PDF");
}
})();
return () => {
controller.abort();
if (revokedUrl) URL.revokeObjectURL(revokedUrl);
};
}, [fileUrl]);
const viewerSrc = useMemo(() => {
if (!blobUrl) return null;
const base = import.meta.env.BASE_URL;
const viewerUrl = `${base}pdfjs/web/viewer.html?file=${encodeURIComponent(blobUrl)}`;
return viewerUrl;
}, [blobUrl]);
return (
<div className="flex flex-col h-full w-full">
<div className="flex-auto overflow-auto bg-gray-100">
<div className="p-4">
<div
className="relative h-[calc(100vh-220px)] min-h-[480px] w-full overflow-auto rounded-md border bg-white"
>
{!!error && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-sm text-red-600">
<div>{error}</div>
</div>
)}
{!error && !loaded && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-sm text-muted-foreground">
<div>
{stage === "fetch" ? "Loading..." : "Opening viewer..."}
</div>
</div>
)}
{viewerSrc && (
<iframe
title="PDF Viewer"
src={viewerSrc}
className="h-full w-full border-0"
onLoad={() => {
setLoaded(true);
}}
/>
)}
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,40 @@
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
type Props = {
url?: string;
};
export function TxtPreview({ url }: Props) {
const { data, isLoading, error, isError } = useQuery({
queryKey: ["file", url],
queryFn: () => axios.get(url!, { responseType: "text" }),
enabled: !!url,
});
if (!url) {
return null;
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-full">
<div>加载中...</div>
</div>
);
}
if (isError) {
return (
<div className="flex items-center justify-center h-full text-red-500">
{error?.message || "加载失败"}
</div>
);
}
return (
<div className="h-full overflow-auto p-4">
<pre className="whitespace-pre-wrap font-mono text-sm">{data?.data}</pre>
</div>
);
}

View File

@@ -0,0 +1,44 @@
import { useState } from "react";
type Props = {
url?: string;
};
export function VideoPreview({ url }: Props) {
const [error, setError] = useState(false);
const [loading, setLoading] = useState(true);
if (!url) {
return (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
视频地址无效
</div>
);
}
if (error) {
return (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
视频加载失败,请检查文件格式或网络连接
</div>
);
}
return (
<div className="w-full h-full bg-black flex items-center justify-center relative">
{loading && <div className="absolute text-white z-10">加载中...</div>}
<video
src={url}
controls
className="w-full h-full object-contain"
onLoadedData={() => setLoading(false)}
onError={() => {
setLoading(false);
setError(true);
}}
>
您的浏览器不支持视频播放
</video>
</div>
);
}

View File

@@ -0,0 +1,221 @@
import {
SidebarMenuButton,
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar";
import { AppSidebar } from "@/components/app-sidebar";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import {
ChevronDown,
ChevronLeft,
LogOut,
MonitorCog,
UserCog,
UserLock,
} from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Outlet, useRouter } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { logout } from "@/apis/user";
import { toast } from "sonner";
import { Spinner } from "@/components/ui/spinner";
import { useIsOrgAdmin, useIsPlatformOrg, useUserStore } from "@/stores/user";
import { useState } from "react";
import { Separator } from "@/components/ui/separator";
import { ModifyPasswordDialog } from "./modify-password-dialog";
type Props = {
menus: any[];
isAdmin?: boolean;
};
export function AppLayout({ menus, isAdmin }: Props) {
const router = useRouter();
const { user, org } = useUserStore();
const [open, setOpen] = useState(false);
const { mutateAsync, isPending } = useMutation({
mutationFn: logout,
onSuccess() {
useUserStore.setState({ token: null });
router.navigate({ to: "/login" });
},
});
const handleLogout = () => {
toast.promise(mutateAsync(), {
loading: "退出中...",
success: "退出成功",
});
};
const isOrgAdmin = useIsOrgAdmin();
const isPlatformOrg = useIsPlatformOrg();
const [openModifyPasswordDialog, setOpenModifyPasswordDialog] =
useState(false);
return (
<>
<SidebarProvider className="bg-transparent">
<AppSidebar menus={menus} isAdmin={isAdmin} />
<main className="w-full h-screen flex flex-col overflow-hidden">
<div className="flex-none p-2">
<div className="flex-none flex items-center space-x-3 h-[60px]">
<SidebarTrigger className="bg-white/20 size-8" />
<div className="flex-auto"></div>
{(isOrgAdmin || isPlatformOrg) && (
<div className="flex-none">
{isAdmin ? (
<Button
variant="ghost"
size="sm"
onClick={() => {
router.navigate({ to: "/" });
}}
>
<ChevronLeft />
返回智传
</Button>
) : (
<Button
variant="ghost"
size="sm"
className="bg-white/20"
onClick={() => {
router.navigate({ to: "/admin" });
}}
>
<MonitorCog />
管理后台
</Button>
)}
</div>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="flex items-center space-x-2 p-2 text-sm rounded-lg cursor-pointer">
<span>{org?.orgName}</span>
<ChevronDown size={12} />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent
side="bottom"
align="end"
className={"min-w-[260px]"}
>
<DropdownMenuLabel>
<div className="flex items-center space-x-2 text-left p-2 w-full">
<Avatar className="size-12">
<AvatarImage src={user?.avatarUrl} alt="头像" />
<AvatarFallback>
{user?.nickname?.slice(0, 1)}
</AvatarFallback>
</Avatar>
<div className="flex-auto">
<div className="text-base">{user?.nickname}</div>
<div className="text-xs mt-1 dark:text-white/60 text-black/60">
{user?.username}
</div>
</div>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<div className="p-1">
<DropdownMenuItem className="p-0">
<SidebarMenuButton
className="px-4 h-[40px] bg-transparent "
onClick={() => setOpen(true)}
>
<UserCog />
<span>个人信息</span>
</SidebarMenuButton>
</DropdownMenuItem>
<DropdownMenuItem className="p-0">
<SidebarMenuButton
className="px-4 h-[40px] bg-transparent"
onClick={() => setOpenModifyPasswordDialog(true)}
>
<UserLock />
<span>修改密码</span>
</SidebarMenuButton>
</DropdownMenuItem>
</div>
<DropdownMenuSeparator />
<div className="p-1">
<Button
variant="destructive"
size="lg"
className="w-full text-left"
onClick={handleLogout}
>
<div className="flex items-center space-x-2">
{isPending && <Spinner />}
退出登录
<LogOut size={16} />
</div>
</Button>
</div>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div className="flex-auto h-full overflow-y-auto p-2 pt-0">
<div className="rounded-xl bg-white/50 backdrop-blur-lg min-h-full">
<Outlet />
</div>
</div>
</main>
</SidebarProvider>
<ModifyPasswordDialog
open={openModifyPasswordDialog}
setOpen={setOpenModifyPasswordDialog}
/>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[380px]">
<DialogHeader>
<DialogTitle>个人信息</DialogTitle>
</DialogHeader>
<div className="space-y-2 text-sm">
<div className="flex items-center justify-between py-2">
<span className="w-[60px] text-black/60">头像</span>
<Avatar className="h-[40px] w-[40px]">
<AvatarImage src={user?.avatarUrl} alt="头像" />
<AvatarFallback>{user?.nickname?.slice(0, 1)}</AvatarFallback>
</Avatar>
</div>
<Separator />
<div className="flex items-center justify-between py-2">
<span className="w-[60px] text-black/60">昵称</span>
<span>{user?.nickname}</span>
</div>
<Separator />
<div className="flex items-center justify-between py-2">
<span className="w-[60px] text-black/60">账号</span>
<span>{user?.username}</span>
</div>
<Separator />
<div className="flex items-center justify-between py-2">
<span className="w-[60px] text-black/60">手机号</span>
<span>{user?.phone}</span>
</div>
</div>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -0,0 +1,77 @@
import {
Sidebar,
SidebarContent,
SidebarGroup,
SidebarGroupContent,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarHeader,
} from "@/components/ui/sidebar";
import logo from "@/assets/image/logo.png";
import { useLocation, useRouter } from "@tanstack/react-router";
import { useMemo } from "react";
import { Badge } from "@/components/ui/badge";
const title = import.meta.env.VITE_APP_TITLE;
const isInside = import.meta.env.VITE_IS_INSIDE === "true";
type Props = {
menus: any[];
isAdmin?: boolean;
};
export function AppSidebar({ menus, isAdmin }: Props) {
const router = useRouter();
const location = useLocation();
const currentPath = useMemo(
() => location.pathname.replace(import.meta.env.VITE_BASEPATH, ""),
[location.pathname],
);
return (
<Sidebar className="[&_.bg-sidebar]:bg-transparent border-none">
<SidebarHeader className="m-2 p-0">
<div className="flex items-center space-x-2 text-left w-full h-[60px]">
<img
src={logo}
alt=""
className="size-12 object-contain rounded-full bg-white overflow-hidden"
/>
<div className="text-primary text-2xl font-bold">
{isAdmin ? "管理后台" : title}
</div>
{isInside && (
<Badge className="bg-transparent text-primary border-primary">
内网
</Badge>
)}
</div>
</SidebarHeader>
<SidebarContent className="rounded-xl bg-white/50 backdrop-blur-lg m-2 mt-0">
<SidebarGroup>
<SidebarGroupContent>
<SidebarMenu>
{menus.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
asChild
isActive={currentPath === item.url}
onClick={() => {
router.navigate({ to: item.url });
}}
className="data-[active=true]:!bg-primary data-[active=true]:!text-white hover:bg-primary/10"
>
<div className="h-[40px] px-4 cursor-pointer">
{item.icon}
<span>{item.title}</span>
</div>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
</Sidebar>
);
}

View File

@@ -0,0 +1,102 @@
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { flexRender } from "@tanstack/react-table";
import type { Table as TanStackTable } from "@tanstack/react-table";
import type { UseQueryResult as TanStackQuery } from "@tanstack/react-query";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
type DataTableProps<TData> = {
table: TanStackTable<TData>;
query: TanStackQuery<TData>;
className?: string;
};
export function DataTable<TData>({
table,
query,
className,
}: DataTableProps<TData>) {
const { isFetching, isSuccess, isError, refetch } = query;
return (
<Table className={className}>
<TableHeader>
{table.getHeaderGroups().map((headerGroup: any) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header: any) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{isFetching && (
<TableRow>
<TableCell colSpan={table.getAllColumns().length}>
<div className="flex flex-col justify-center items-center p-4 gap-2">
<Spinner className="text-primary h-6 w-6" />
</div>
</TableCell>
</TableRow>
)}
{!isFetching && isError && (
<TableRow>
<TableCell colSpan={table.getAllColumns().length}>
<div className="flex flex-col justify-center items-center p-4 gap-2">
<span className="text-red-500 text-sm">加载数据失败</span>
<Button variant="outline" size="sm" onClick={() => refetch()}>
重新加载
</Button>
</div>
</TableCell>
</TableRow>
)}
{!isFetching && isSuccess && !table.getRowModel().rows?.length && (
<TableRow>
<TableCell colSpan={table.getAllColumns().length}>
<div className="flex flex-col justify-center items-center p-4 gap-2">
<span className="text-gray-500 text-sm">暂无数据</span>
</div>
</TableCell>
</TableRow>
)}
{!isFetching &&
isSuccess &&
!!table.getRowModel().rows?.length &&
table.getRowModel().rows.map((row: any) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell: any) => (
<TableCell
key={cell.id}
className={cell.column.columnDef.meta?.className}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
);
}

View File

@@ -0,0 +1,88 @@
import * as React from "react";
import { format, parse } from "date-fns";
import { zhCN } from "react-day-picker/locale";
import { CalendarIcon, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
interface DatePickerProps {
/** 日期字符串,格式 yyyy-MM-dd,空串表示未选择 */
value?: string;
onChange?: (value: string) => void;
placeholder?: string;
className?: string;
disabled?: boolean;
}
/**
* 日期选择器(shadcn Popover + Calendar)
* 受控组件,value/onChange 均为 yyyy-MM-dd 格式字符串
*/
export function DatePicker({
value,
onChange,
placeholder = "选择日期",
className,
disabled,
}: DatePickerProps) {
const [open, setOpen] = React.useState(false);
const selected = value
? parse(value, "yyyy-MM-dd", new Date())
: undefined;
const handleSelect = (date?: Date) => {
onChange?.(date ? format(date, "yyyy-MM-dd") : "");
setOpen(false);
};
return (
<div className={cn("flex items-center gap-1", className)}>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className={cn(
"w-[140px] justify-start px-3 font-normal",
!value && "text-muted-foreground",
)}
>
<CalendarIcon className="size-4" />
{value ? value : <span>{placeholder}</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
locale={zhCN}
selected={selected}
captionLayout="dropdown"
defaultMonth={selected}
onSelect={handleSelect}
/>
</PopoverContent>
</Popover>
{value ? (
<Button
type="button"
variant="ghost"
size="icon"
className="size-7 text-muted-foreground"
disabled={disabled}
title="清除"
onClick={() => onChange?.("")}
>
<X />
</Button>
) : null}
</div>
);
}

View File

@@ -0,0 +1,118 @@
import * as React from "react";
import { format, parse } from "date-fns";
import { zhCN } from "react-day-picker/locale";
import { type DateRange } from "react-day-picker";
import { CalendarIcon, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
export interface DateRangeValue {
/** 开始日期,yyyy-MM-dd */
from?: string;
/** 结束日期,yyyy-MM-dd */
to?: string;
}
interface DateRangePickerProps {
from?: string;
to?: string;
onChange?: (value: DateRangeValue) => void;
placeholder?: string;
className?: string;
disabled?: boolean;
}
const toDate = (text?: string) =>
text ? parse(text, "yyyy-MM-dd", new Date()) : undefined;
/**
* 日期区间选择器(shadcn Popover + Calendar range 模式,双月面板)
* 基于 https://ui.shadcn.com/docs/components/base/date-picker#range-picker
* from/to 为 yyyy-MM-dd 格式字符串
*/
export function DateRangePicker({
from,
to,
onChange,
placeholder = "选择时间区间",
className,
disabled,
}: DateRangePickerProps) {
const [open, setOpen] = React.useState(false);
const selected: DateRange | undefined =
from || to
? { from: toDate(from), to: toDate(to) }
: undefined;
const handleSelect = (range: DateRange | undefined) => {
onChange?.({
from: range?.from ? format(range.from, "yyyy-MM-dd") : undefined,
to: range?.to ? format(range.to, "yyyy-MM-dd") : undefined,
});
};
const hasValue = Boolean(from || to);
return (
<div className={cn("flex items-center gap-1", className)}>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className={cn(
"w-[260px] justify-start px-3 font-normal",
!hasValue && "text-muted-foreground",
)}
>
<CalendarIcon className="size-4" />
{from ? (
to ? (
<span>
{format(toDate(from)!, "yyyy-MM-dd")} ~{" "}
{format(toDate(to)!, "yyyy-MM-dd")}
</span>
) : (
<span>{from} ~</span>
)
) : (
<span>{placeholder}</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="range"
locale={zhCN}
captionLayout="dropdown"
defaultMonth={toDate(from)}
selected={selected}
onSelect={handleSelect}
numberOfMonths={2}
/>
</PopoverContent>
</Popover>
{hasValue ? (
<Button
type="button"
variant="ghost"
size="icon"
className="size-7 text-muted-foreground"
disabled={disabled}
title="清除"
onClick={() => onChange?.({ from: undefined, to: undefined })}
>
<X />
</Button>
) : null}
</div>
);
}

View File

@@ -0,0 +1,60 @@
import {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbSeparator,
BreadcrumbPage,
} from "@/components/ui/breadcrumb";
type DirectoryBreadcrumbProps = {
directorys: any[];
onChangeDirectorys: (record?: any) => void;
className?: string;
};
export function DirectoryBreadcrumb({
directorys,
onChangeDirectorys,
className,
}: DirectoryBreadcrumbProps) {
return (
<Breadcrumb className={className}>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink
onClick={() => onChangeDirectorys({ id: 0 })}
className="cursor-pointer"
>
根目录
</BreadcrumbLink>
</BreadcrumbItem>
{directorys.length > 0 && <BreadcrumbSeparator />}
{directorys.length > 0 &&
directorys.map((item: any, index: number) => (
<>
<BreadcrumbItem key={item.id}>
{index === directorys.length - 1 ? (
<BreadcrumbPage className="cursor-default">
{item.fileName}
</BreadcrumbPage>
) : (
<BreadcrumbLink
onClick={() => onChangeDirectorys(item)}
className="cursor-pointer"
>
{item.fileName.length > 6
? item.fileName.slice(0, 6) + "..."
: item.fileName}
</BreadcrumbLink>
)}
</BreadcrumbItem>
{index !== directorys.length - 1 && (
<BreadcrumbSeparator key={"separator" + item.id} />
)}
</>
))}
</BreadcrumbList>
</Breadcrumb>
);
}

View File

@@ -0,0 +1,30 @@
import { Button } from "@/components/ui/button";
import { MoveLeft, TriangleAlert } from "lucide-react";
import router from "@/router";
export default function ErrorBoundary() {
const handleBack = () => {
if (router.history.canGoBack()) {
router.history.back();
} else {
router.navigate({ to: "/" });
}
};
return (
<div className="min-h-screen p-4 box-border bg-gray-50 flex flex-col justify-center items-center">
<div className="p-4 flex flex-col justify-center items-center">
<TriangleAlert size={80} className="text-red-500" />
<div className="text-2xl mt-8">系统错误</div>
<div className="text-sm text-black/50 mt-2">
请您稍后再试,或者联系管理员
</div>
<div className="mt-4">
<Button className="!px-8 rounded-full" onClick={handleBack}>
<MoveLeft />
返回首页
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,74 @@
import {
Files,
FileQuestionMark,
FileImage,
FilePlay,
FileTypeIcon,
} from "lucide-react";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
export const categorys = [
{
key: "all",
name: "全部",
icon: <Files />,
},
{
key: "image",
name: "图片",
icon: <FileImage />,
},
{
key: "video",
name: "视频",
icon: <FilePlay />,
},
{
key: "document",
name: "文档",
icon: <FileTypeIcon />,
},
{
key: "other",
name: "其他",
icon: <FileQuestionMark />,
},
];
interface Props {
fileCategory: string;
setFileCategory: (value: string) => void;
reset: () => void;
}
export function FileCategoryFilter({
fileCategory,
setFileCategory,
reset,
}: Props) {
return (
<ToggleGroup
type="single"
variant="outline"
spacing={2}
size="sm"
value={fileCategory}
onValueChange={(value) => {
reset();
setFileCategory(value);
}}
>
{categorys.map((item) => (
<ToggleGroupItem
key={item.key}
value={item.key}
variant="outline"
className="px-3 rounded-full data-[state=on]:text-primary data-[state=on]:border-primary mr-2 last:mr-0"
>
{item.icon}
{item.name}
</ToggleGroupItem>
))}
</ToggleGroup>
);
}

View File

@@ -0,0 +1,116 @@
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { PDFPreview } from "./PDFPreview";
import { TxtPreview } from "./TxtPreview";
import { DocxPreview } from "./DocxPreview";
import { useMemo } from "react";
import { downloadFile, getFileUrl } from "@/apis/file";
import { VideoPreview } from "./VideoPreview";
import { AudioPreview } from "./AudioPreview";
import { ImagePreview } from "./ImagePreview";
import { ExcelPreview } from "./ExcelPreview";
import { MarkdownPreview } from "./MarkdownPreview";
import { Button } from "./ui/button";
import { Download } from "lucide-react";
type FilePreviewDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
data: any;
};
const getFileExtension = (filename?: string) => {
if (!filename) return "";
const parts = filename.split(".");
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : "";
};
export function FilePreviewDialog({
open,
setOpen,
data,
}: FilePreviewDialogProps) {
const url = useMemo(() => getFileUrl(data?.fileCode), [data]);
const fileExtension = useMemo(
() => getFileExtension(data?.fileName),
[data?.fileName],
);
const renderPreview = () => {
switch (fileExtension) {
case "pdf":
return <PDFPreview url={url} />;
case "txt":
return <TxtPreview url={url} />;
case "docx":
return <DocxPreview url={url} />;
case "mp4":
case "webm":
case "mov":
case "avi":
case "mkv":
case "flv":
case "wmv":
return <VideoPreview url={url} />;
case "mp3":
case "wav":
case "ogg":
case "m4a":
case "aac":
case "flac":
case "wma":
return <AudioPreview url={url} />;
case "jpg":
case "jpeg":
case "png":
case "gif":
case "bmp":
case "webp":
case "svg":
case "ico":
return <ImagePreview url={url} />;
case "xlsx":
case "xls":
case "csv":
return <ExcelPreview url={url} />;
case "md":
case "markdown":
return <MarkdownPreview url={url} />;
default:
return (
<div className="flex items-center justify-center h-full text-muted-foreground">
暂不支持预览该文件类型
</div>
);
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="!max-w-none !max-h-none h-screen w-screen flex flex-col p-0 m-0 rounded-none gap-0">
<DialogHeader className="flex-none p-4 border-b">
<DialogTitle>
<div className="flex items-center gap-4">
<span>
{data?.fileName?.slice(0, 20) +
(data?.fileName?.length > 20 ? "..." : "")}
</span>
<Button
variant="outline"
onClick={() => downloadFile({ code: data?.fileCode })}
>
<Download className="size-4" />
下载
</Button>
</div>
</DialogTitle>
</DialogHeader>
<div className="flex-auto overflow-hidden">{renderPreview()}</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,38 @@
import { useMemo } from "react";
import { Badge } from "@/components/ui/badge";
import clsx from "clsx";
export const statusOptions = {
1: {
text: "正常",
color: "bg-primary/10 text-primary",
},
2: {
text: "失效",
color: "bg-gray-500/10 text-gray-500",
},
11: {
text: "解析中",
color: "bg-emerald-500/10 text-emerald-500",
},
12: {
text: "待审核",
color: "bg-violet-500/10 text-violet-500",
},
13: {
text: "传输中",
color: "bg-amber-500/10 text-amber-500",
},
14: {
text: "失败",
color: "bg-red-500/10 text-red-500",
},
};
export function FileStatusBadge({ status }: { status: number | string }) {
const option = useMemo(
() => statusOptions[Number(status) as keyof typeof statusOptions],
[status],
);
return <Badge className={clsx(option?.color)}>{option?.text}</Badge>;
}

View File

@@ -0,0 +1,87 @@
import { useCallback } from "react";
import { ErrorCode, useDropzone } from "react-dropzone";
import { Upload } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
import { toast } from "sonner";
import { useMutation } from "@tanstack/react-query";
import { FileType, createFile } from "@/apis/file";
export const uploadFile = (file: any) =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.9) {
reject("上传失败");
} else {
resolve(file);
}
}, 4000);
});
export function FileUploader() {
const { mutateAsync, isPending } = useMutation({
mutationFn: (file: any) =>
uploadFile(file).then((res: any) =>
createFile({
fileCode: res.data?.fileCode,
fileName: res.data?.fileName,
fileType: FileType.FILE,
}),
),
onSuccess() {},
});
const onDropAccepted = useCallback((files: any) => {
files.forEach((file: any) => {
mutateAsync(file);
});
}, []);
const onDropRejected = useCallback((files: any) => {
const error = files[0].errors[0];
if (error.code === ErrorCode.FileTooLarge) {
toast.error("文件大小超过5MB");
return;
}
if (error.code === ErrorCode.TooManyFiles) {
toast.error("只能上传一个文件");
return;
}
toast.error("文件上传失败");
}, []);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDropAccepted,
onDropRejected,
maxFiles: 1,
minSize: 1 * 1024,
maxSize: 5 * 1024 * 1024,
disabled: isPending,
multiple: false,
});
return (
<div
className={`relative border border-dashed rounded-lg text-center cursor-pointer transition-colors hover:border-primary overflow-hidden
${
isDragActive
? "border-primary bg-primary/5"
: "border-muted-foreground/25"
}`}
>
{isPending && (
<div className="absolute left-0 right-0 top-0 bottom-0 flex items-center justify-center backdrop-blur-xs bg-white/10 z-50">
<Spinner className="h-12 w-12 text-primary" />
</div>
)}
<div {...getRootProps()} className="p-8 rounded-lg outline-none">
<input {...getInputProps()} />
<div className="p-4 rounded-full bg-gray-50 inline-flex justify-center items-center">
<Upload className="mx-auto h-6 w-6 text-muted-foreground" />
</div>
<p className="mt-2 text-lg">
{isDragActive ? "松开鼠标以选择文件" : "拖放文件到这里,或点击选择"}
</p>
<p className="mt-2 text-sm text-black/50">文件最大不能超过5MB</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,117 @@
import { useRouter } from "@tanstack/react-router";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import {
Form,
FormField,
FormItem,
FormLabel,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { initUserPassword } from "@/apis/user";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import logo from "@/assets/image/logo.png";
import { useUserStore } from "@/stores/user";
const formSchema = z.object({
rePassword: z.string().nonempty({
message: "确认密码不能为空",
}),
password: z.string().nonempty({
message: "密码不能为空",
}),
});
const title = import.meta.env.VITE_APP_TITLE;
export function InitPassword() {
const router = useRouter();
const user = useUserStore((state) => state.user);
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
password: "",
rePassword: "",
},
});
const { mutateAsync, isPending } = useMutation({
mutationFn: initUserPassword,
onSuccess() {
router.navigate({ to: "/", replace: true });
},
});
const onSubmit = (values: z.infer<typeof formSchema>) => {
toast.promise(mutateAsync({ ...values, username: user?.username }), {
loading: "提交中...",
success: "设置成功",
});
};
return (
<div className="flex items-center justify-center min-h-screen box-border">
<div>
<div className="flex justify-center items-center mb-4 gap-2">
<img
src={logo}
alt=""
className="size-12 object-contain rounded-full bg-white overflow-hidden"
/>
<div className="text-3xl">{title}</div>
</div>
<div className="w-[480px] p-10 bg-white rounded-xl">
<div className="text-center text-2xl">设置密码</div>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-8 mt-12"
>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>密码</FormLabel>
<FormControl>
<Input type="password" placeholder="密码" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="rePassword"
render={({ field }) => (
<FormItem>
<FormLabel>确认密码</FormLabel>
<FormControl>
<Input
type="password"
placeholder="确认密码"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={isPending}>
{isPending && <Spinner />}
提交
</Button>
</form>
</Form>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,9 @@
import { Spinner } from "./ui/spinner";
export default function Loading() {
return (
<div className="min-h-full h-full flex flex-col justify-center items-center p-4 gap-2">
<Spinner className="text-primary h-6 w-6" />
</div>
);
}

View File

@@ -0,0 +1,143 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
FormField,
FormItem,
FormControl,
FormMessage,
Form,
FormLabel,
} from "@/components/ui/form";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Spinner } from "@/components/ui/spinner";
import { Input } from "@/components/ui/input";
import { useEffect } from "react";
import { modifyPassword } from "@/apis/user";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
type ModifyPasswordDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
};
const formSchema = z.object({
oldPassword: z.string().nonempty({
message: "旧密码不能为空",
}),
newPassword: z.string().nonempty({
message: "新密码不能为空",
}),
reNewPassword: z.string().nonempty({
message: "确认密码不能为空",
}),
});
export function ModifyPasswordDialog({
open,
setOpen,
}: ModifyPasswordDialogProps) {
const {
mutateAsync: modifyPasswordMutateAsync,
isPending: modifyPasswordIsPending,
} = useMutation({
mutationFn: modifyPassword,
onSuccess() {
setOpen(false);
},
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
oldPassword: "",
newPassword: "",
reNewPassword: "",
},
});
useEffect(() => {
if (open) {
form.reset();
}
}, [open]);
const onSubmit = (values: z.infer<typeof formSchema>) => {
toast.promise(modifyPasswordMutateAsync(values), {
loading: "提交中...",
success: "修改成功",
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[400px]">
<DialogHeader>
<DialogTitle>修改密码</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="oldPassword"
render={({ field }) => (
<FormItem>
<FormLabel>旧密码</FormLabel>
<FormControl>
<Input {...field} type="password" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="newPassword"
render={({ field }) => (
<FormItem>
<FormLabel>新密码</FormLabel>
<FormControl>
<Input {...field} type="password" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="reNewPassword"
render={({ field }) => (
<FormItem>
<FormLabel>确认密码</FormLabel>
<FormControl>
<Input {...field} type="password" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">取消</Button>
</DialogClose>
<Button type="submit" disabled={modifyPasswordIsPending}>
{modifyPasswordIsPending && <Spinner />}确定
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,236 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner";
import { FileType, getFilePage } from "@/apis/file";
import { Folder, FolderInput, MoveRight } from "lucide-react";
import clsx from "clsx";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { DirectoryBreadcrumb } from "@/components/directory-breadcrumb";
import { DataTable } from "@/components/data-table";
import { Pagination } from "@/components/pagination";
import { useMoveFile } from "@/hooks/use-move-flie";
import { useEffect, useMemo, useState } from "react";
import { getCoreRowModel, useReactTable } from "@tanstack/react-table";
import { useQuery } from "@tanstack/react-query";
export function useColumns(handleChangeParentId: any) {
return [
{
accessorKey: "fileName",
header: "目录名",
size: 200,
cell: ({ row }: any) => (
<div
className={clsx(
"w-full flex items-center gap-1 break-all",
"cursor-pointer hover:underline hover:text-primary group",
)}
onClick={() => {
handleChangeParentId(row?.original);
}}
>
<Folder size={18} className="text-amber-500 group-hover:hidden" />
<FolderInput
size={18}
className="text-amber-500 group-hover:block hidden"
/>
<span>{row.getValue("fileName")}</span>
</div>
),
},
];
}
type MoveFileDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
data?: any;
refetch?: () => void;
params: any;
};
export function MoveFileDialog({
open,
setOpen,
data,
refetch,
params,
}: MoveFileDialogProps) {
// 选中行
const [rowSelection, setRowSelection] = useState({});
// 当前打开的目录层级
const [openDirectorys, setOpenDirectorys] = useState<any[]>([]);
// 文件目录ID
const [parentId, setParentId] = useState(0);
// 分页
const [pagination, setPagination] = useState({
pageIndex: 0,
pageSize: 10,
});
// 查询数据
const query = useQuery<any>({
queryKey: ["moveFiles", pagination, parentId, params],
queryFn: () =>
getFilePage({
...params,
parentId: parentId || 0,
pageSize: pagination.pageSize,
pageNo: pagination.pageIndex + 1,
fileType: FileType.DIRECTORY,
}).then((res) => res.data),
enabled: open,
});
// 切换上级ID
const handleChangeParentId = (record: any) => {
setParentId(record.id);
// 重置分页
table.setPageIndex(0);
// @ts-ignore
setOpenDirectorys((prev: any) => [...prev, record]);
// 重置选中数据
table.resetRowSelection();
};
// 过滤当前目录
const list = useMemo(
() =>
query?.data?.entityList?.filter((item: any) => item.id !== data?.id) ||
[],
[query, data],
);
// 表格
const columns = useColumns(handleChangeParentId);
const table = useReactTable({
data: list,
columns,
getCoreRowModel: getCoreRowModel(),
manualPagination: false,
rowCount: query?.data?.totalCount || 0,
pageCount: query?.data?.pageCount || 0,
onPaginationChange: setPagination,
autoResetPageIndex: false,
onRowSelectionChange: setRowSelection,
state: {
pagination,
rowSelection,
},
});
const changeOpenDirectorys = (record?: any) => {
setParentId(record?.id);
// 重置分页
table.setPageIndex(0);
// @ts-ignore
setOpenDirectorys((prev: any[]) => {
const index = prev.findIndex((item: any) => item.id === record?.id);
if (index > -1) {
return [...prev.slice(0, index + 1)];
}
return [];
});
// 重置选中数据
table.resetRowSelection();
};
// 重置
const reset = () => {
setParentId(0);
// 重置分页
table.setPageIndex(0);
// @ts-ignore
setOpenDirectorys([]);
// 重置选中数据
table.resetRowSelection();
};
const { move, moveIsPending } = useMoveFile({
onSuccess: () => {
refetch?.();
setOpen(false);
},
});
const handleSubmit = () => {
move({
...data,
parentId,
});
};
useEffect(() => {
if (open) {
reset();
}
}, [open]);
const currentDirectory = useMemo(
() => openDirectorys?.[openDirectorys?.length - 1],
[openDirectorys],
);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[680px]">
<DialogHeader>
<DialogTitle>
{data?.fileType === FileType.DIRECTORY ? "移动目录" : "移动文件"}
</DialogTitle>
</DialogHeader>
<div className="overflow-hidden space-y-2">
<DirectoryBreadcrumb
directorys={openDirectorys}
onChangeDirectorys={changeOpenDirectorys}
/>
<div className="max-h-[400px] overflow-y-auto relative border rounded-lg">
<DataTable table={table} query={query} />
<Pagination
table={table}
simple
className="p-2 justify-end sticky bottom-0 left-0 right-0 z-10 bg-white"
/>
</div>
</div>
<div className="flex items-center gap-2 text-sm overflow-hidden">
<span className="flex-1 overflow-hidden text-primary clamp-1 truncate p-2 rounded-lg bg-gray-100">
{data?.fileName}
</span>
<MoveRight size={16} className="flex-none" />
<span className="flex-1 overflow-hidden text-amber-500 clamp-1 truncate inline-flex items-center gap-1 p-2 rounded-lg bg-gray-100">
<Folder size={16} className="flex-none " />
{currentDirectory?.fileName || "根目录"}
</span>
</div>
<Alert className="!bg-amber-50 !border-amber-200">
<AlertTitle>
您确定要将{data?.fileType === FileType.DIRECTORY ? "目录" : "文件"}
移动到该目录下吗?
</AlertTitle>
<AlertDescription>
如果是目录,则目录下的所有文件和子目录都会被移动
</AlertDescription>
</Alert>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">取消</Button>
</DialogClose>
<Button type="submit" disabled={moveIsPending} onClick={handleSubmit}>
{moveIsPending && <Spinner />}确定
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,30 @@
import { Button } from "@/components/ui/button";
import { MoveLeft, Inbox } from "lucide-react";
import router from "@/router";
export default function NotFound() {
const handleBack = () => {
if (router.history.canGoBack()) {
router.history.back();
} else {
router.navigate({ to: "/" });
}
};
return (
<div className="min-h-screen p-4 box-border bg-gray-50 flex flex-col justify-center items-center">
<div className="p-4 flex flex-col justify-center items-center">
<Inbox size={80} className="text-gary-500" />
<div className="text-2xl mt-8">页面不存在</div>
<div className="text-sm text-black/50 mt-2">
请您稍后再试,或者联系管理员
</div>
<div className="mt-4">
<Button className="px-8! rounded-full" onClick={handleBack}>
<MoveLeft />
返回首页
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,46 @@
import { Button } from "@/components/ui/button";
import type { Table as TanStackTable } from "@tanstack/react-table";
import { debounce } from "@tanstack/react-pacer";
import clsx from "clsx";
type PaginationProps<TData> = {
table: TanStackTable<TData>;
className?: string;
simple?: boolean;
};
export function Pagination<TData>({
table,
className,
simple,
}: PaginationProps<TData>) {
return (
<div className={clsx("flex items-center gap-2", className)}>
{!simple && (
<div className="text-sm text-muted-foreground mr-4">
本页共{table.getRowModel().rows?.length || 0}条,总共
{table.getRowCount()}条
</div>
)}
<Button
size="sm"
variant="outline"
onClick={debounce(() => table.previousPage(), { wait: 500 })}
disabled={!table.getCanPreviousPage()}
>
上一页
</Button>
<Button size="sm" disabled variant="ghost">
{table.getState().pagination.pageIndex + 1} / {table.getPageCount()}
</Button>
<Button
size="sm"
variant="outline"
onClick={debounce(() => table.nextPage(), { wait: 500 })}
disabled={!table.getCanNextPage()}
>
下一页
</Button>
</div>
);
}

View File

@@ -0,0 +1,86 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner";
import { Folder, File } from "lucide-react";
import { useRemoveFile } from "@/hooks/use-remove-file";
import { FileStatus, FileType } from "@/apis/file";
type RemoveFileDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
data?: any;
refetch?: () => void;
};
export function RemoveFileDialog({
open,
setOpen,
data,
refetch,
}: RemoveFileDialogProps) {
const { remove, removeIsPending } = useRemoveFile({
onSuccess() {
refetch?.();
setOpen(false);
},
});
const onSubmit = () => {
remove({
id: data?.id,
oldStatus: data?.fileStatus,
newStatus: FileStatus.INVALID,
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[400px]">
<DialogHeader>
<DialogTitle>
您确定要删除该{data?.fileType === FileType.FILE ? "文件" : "目录"}?
</DialogTitle>
{data?.fileType === FileType.FILE ? (
<DialogDescription>
删除后文件将被放入到回收站中,可从回收站中恢复
</DialogDescription>
) : (
<DialogDescription>
目录下的文件也会一并被删除,删除的目录将会放入到回收站中,可从回收站中恢复
</DialogDescription>
)}
<div className="mt-1 flex items-center gap-1 text-sm p-2 rounded-md bg-gray-50">
{data?.fileType === FileType.FILE ? (
<File size={16} className="text-primary flex-none" />
) : (
<Folder size={16} className="text-amber-500 flex-none" />
)}
<span className="break-all">{data?.fileName}</span>
</div>
</DialogHeader>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">取消</Button>
</DialogClose>
<Button
type="submit"
variant="destructive"
disabled={removeIsPending}
onClick={onSubmit}
>
{removeIsPending && <Spinner />}确定
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,128 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
FormField,
FormItem,
FormControl,
FormMessage,
Form,
FormLabel,
} from "@/components/ui/form";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Spinner } from "@/components/ui/spinner";
import { Input } from "@/components/ui/input";
import { useEffect } from "react";
import { resetUserPwd } from "@/apis/user";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
type ResetUserPasswordDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
data: any;
};
const formSchema = z.object({
newPassword: z.string().nonempty({
message: "新密码不能为空",
}),
confirmPassword: z.string().nonempty({
message: "确认密码不能为空",
}),
});
export function ResetUserPasswordDialog({
open,
setOpen,
data,
}: ResetUserPasswordDialogProps) {
const {
mutateAsync: resetPasswordMutateAsync,
isPending: resetPasswordIsPending,
} = useMutation({
mutationFn: resetUserPwd,
onSuccess() {
setOpen(false);
},
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
newPassword: "",
confirmPassword: "",
},
});
useEffect(() => {
if (open) {
form.reset();
}
}, [open]);
const onSubmit = (values: z.infer<typeof formSchema>) => {
toast.promise(resetPasswordMutateAsync({ ...values, userId: data.id }), {
loading: "提交中...",
success: "修改成功",
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[400px]">
<DialogHeader>
<DialogTitle>重置密码</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="newPassword"
render={({ field }) => (
<FormItem>
<FormLabel>新密码</FormLabel>
<FormControl>
<Input {...field} type="password" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel>确认密码</FormLabel>
<FormControl>
<Input {...field} type="password" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">取消</Button>
</DialogClose>
<Button type="submit" disabled={resetPasswordIsPending}>
{resetPasswordIsPending && <Spinner />}确定
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,169 @@
import * as React from "react";
import { X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
/** 常用文件后缀,供快捷点选 */
const COMMON_SUFFIXES = [
"doc",
"docx",
"xls",
"xlsx",
"ppt",
"pptx",
"pdf",
"jpg",
"jpeg",
"png",
"gif",
"mp4",
"mp3",
"zip",
];
interface SuffixTagInputProps {
/** 已选后缀列表(小写,不含点) */
value: string[];
onChange?: (value: string[]) => void;
placeholder?: string;
className?: string;
disabled?: boolean;
}
/**
* 文件后缀标签输入(shadcn Badge + Input)
* 输入后回车或输入逗号/顿号/分号/空格即添加为标签,支持逐个删除与常用后缀快捷点选
*/
export function SuffixTagInput({
value,
onChange,
placeholder = "输入后缀后回车,如:docx",
className,
disabled,
}: SuffixTagInputProps) {
const [inputText, setInputText] = React.useState("");
const normalize = (text: string) =>
text.trim().replace(/^\.+/, "").toLowerCase();
const addSuffix = (raw: string) => {
const suffix = normalize(raw);
if (!suffix) {
return;
}
if (value.includes(suffix)) {
toastOnce(suffix);
return;
}
onChange?.([...value, suffix]);
};
const removeSuffix = (suffix: string) => {
onChange?.(value.filter((item) => item !== suffix));
};
const toggleCommon = (suffix: string) => {
if (value.includes(suffix)) {
removeSuffix(suffix);
} else {
addSuffix(suffix);
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
e.preventDefault();
addSuffix(inputText);
setInputText("");
return;
}
// 逗号/顿号/分号/空格 作为分隔提交
if (/[,,、;;\s]$/.test(e.key)) {
e.preventDefault();
addSuffix(inputText);
setInputText("");
return;
}
if (e.key === "Backspace" && inputText === "" && value.length > 0) {
removeSuffix(value[value.length - 1]);
}
};
return (
<div className="space-y-2">
<div
className={cn(
"flex min-h-9 w-full flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent px-3 py-1.5 text-sm",
"focus-within:ring-ring/50 focus-within:border-ring focus-within:ring-[3px]",
className,
)}
>
{value.map((suffix) => (
<Badge
key={suffix}
variant="secondary"
className="gap-1 font-normal"
>
{suffix}
{!disabled && (
<button
type="button"
title="删除"
className="rounded-full outline-none hover:text-red-500"
onClick={() => removeSuffix(suffix)}
>
<X className="size-3" />
</button>
)}
</Badge>
))}
<input
className="min-w-[120px] flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
value={inputText}
placeholder={value.length > 0 ? "" : placeholder}
disabled={disabled}
onChange={(e) => setInputText(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={() => {
// 失焦时提交未确认的输入
if (inputText.trim()) {
addSuffix(inputText);
setInputText("");
}
}}
/>
</div>
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-xs text-black/50">常用:</span>
{COMMON_SUFFIXES.map((suffix) => {
const selected = value.includes(suffix);
return (
<Badge
key={suffix}
variant={selected ? "default" : "outline"}
className={cn(
"cursor-pointer font-normal select-none",
disabled && "pointer-events-none opacity-50",
)}
onClick={() => toggleCommon(suffix)}
>
{suffix}
</Badge>
);
})}
</div>
</div>
);
}
// 重复添加时轻提示(同一后缀只提示一次)
let lastDuplicate = "";
let lastDuplicateAt = 0;
function toastOnce(suffix: string) {
const now = Date.now();
if (suffix !== lastDuplicate || now - lastDuplicateAt > 2000) {
import("sonner").then(({ toast }) => toast.info(`后缀 ${suffix} 已添加`));
}
lastDuplicate = suffix;
lastDuplicateAt = now;
}

View File

@@ -0,0 +1,73 @@
import { createContext, useContext, useEffect, useState } from "react";
type Theme = "dark" | "light" | "system";
type ThemeProviderProps = {
children: React.ReactNode;
defaultTheme?: Theme;
storageKey?: string;
};
type ThemeProviderState = {
theme: Theme;
setTheme: (theme: Theme) => void;
};
const initialState: ThemeProviderState = {
theme: "system",
setTheme: () => null,
};
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
export function ThemeProvider({
children,
defaultTheme = "system",
storageKey = "vite-ui-theme",
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
);
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove("light", "dark");
if (theme === "system") {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
.matches
? "dark"
: "light";
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme);
setTheme(theme);
},
};
return (
<ThemeProviderContext.Provider {...props} value={value}>
{children}
</ThemeProviderContext.Provider>
);
}
export const useTheme = () => {
const context = useContext(ThemeProviderContext);
if (context === undefined)
throw new Error("useTheme must be used within a ThemeProvider");
return context;
};

View File

@@ -0,0 +1,155 @@
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 left-0 right-0 top-0 bottom-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,51 @@
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-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,109 @@
import * 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,82 @@
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Separator } from "@/components/ui/separator";
const buttonGroupVariants = cva(
"flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
{
variants: {
orientation: {
horizontal:
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
vertical:
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
},
},
defaultVariants: {
orientation: "horizontal",
},
}
);
function ButtonGroup({
className,
orientation,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
return (
<div
role="group"
data-slot="button-group"
data-orientation={orientation}
className={cn(buttonGroupVariants({ orientation }), className)}
{...props}
/>
);
}
function ButtonGroupText({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "div";
return (
<Comp
className={cn(
"bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
);
}
function ButtonGroupSeparator({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="button-group-separator"
orientation={orientation}
className={cn(
"bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto",
className
)}
{...props}
/>
);
}
export {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
buttonGroupVariants,
};

View File

@@ -0,0 +1,62 @@
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 hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,218 @@
import * as React from "react"
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import {
DayPicker,
getDefaultClassNames,
type DayButton,
} from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-3 [--cell-size:2rem] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
String.raw`rtl:[&_.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:[&_.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"flex flex-col md:flex-row relative space-y-4 md:space-y-0 md:space-x-4",
defaultClassNames.months
),
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
nav: cn(
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"h-[var(--cell-size)] w-[var(--cell-size)] aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"h-[var(--cell-size)] w-[var(--cell-size)] aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_next
),
month_caption: cn(
"flex items-center justify-center h-[var(--cell-size)] w-full px-[var(--cell-size)]",
defaultClassNames.month_caption
),
dropdowns: cn(
"w-full flex items-center text-sm font-medium justify-center h-[var(--cell-size)] gap-1.5",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative border border-input shadow-sm focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px] rounded-md",
defaultClassNames.dropdown_root
),
dropdown: cn(
"absolute bg-popover left-0 right-0 top-0 bottom-0 opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
defaultClassNames.caption_label
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
defaultClassNames.weekday
),
week: cn("flex w-full mt-2", defaultClassNames.week),
week_number_header: cn(
"select-none w-[var(--cell-size)]",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] select-none text-muted-foreground",
defaultClassNames.week_number
),
day: cn(
"relative w-full h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
defaultClassNames.day
),
range_start: cn(
"rounded-l-md bg-accent",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex h-[var(--cell-size)] w-[var(--cell-size)] items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground dark:hover:text-accent-foreground flex aspect-square w-full min-w-[var(--cell-size)] flex-col gap-1 leading-none font-normal data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }

View File

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

357
src/components/ui/chart.tsx Normal file
View File

@@ -0,0 +1,357 @@
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import { cn } from "@/lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
}
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
function ChartContainer({
id,
className,
children,
config,
...props
}: React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
}) {
const uniqueId = React.useId()
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-sector]:outline-none [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-none",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
function ChartTooltipContent({
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
}) {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey || item?.dataKey || item?.name || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? config[label as keyof typeof config]?.label || label
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
className={cn(
"border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color || item.payload.fill || item.color
return (
<div
key={item.dataKey}
className={cn(
"[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
backgroundColor: "var(--color-bg)",
borderColor: "var(--color-border)",
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label || item.name}
</span>
</div>
{item.value && (
<span className="text-foreground font-mono font-medium tabular-nums">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
const ChartLegend = RechartsPrimitive.Legend
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean
nameKey?: string
}) {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload
.filter((item) => item.type !== "none")
.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className={cn(
"[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config
? config[configLabelKey]
: config[key as keyof typeof config]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}

View File

@@ -0,0 +1,30 @@
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="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,141 @@
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 left-0 right-0 top-0 bottom-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none 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,133 @@
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 left-0 right-0 top-0 bottom-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-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
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,254 @@
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-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] origin-[var(--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-none 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-none 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-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-[var(--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,
}

104
src/components/ui/empty.tsx Normal file
View File

@@ -0,0 +1,104 @@
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
function Empty({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty"
className={cn(
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12",
className
)}
{...props}
/>
)
}
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-header"
className={cn(
"flex max-w-sm flex-col items-center gap-2 text-center",
className
)}
{...props}
/>
)
}
const emptyMediaVariants = cva(
"flex shrink-0 items-center justify-center mb-2 [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-transparent",
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
},
},
defaultVariants: {
variant: "default",
},
}
)
function EmptyMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
return (
<div
data-slot="empty-icon"
data-variant={variant}
className={cn(emptyMediaVariants({ variant, className }))}
{...props}
/>
)
}
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-title"
className={cn("text-lg font-medium tracking-tight", className)}
{...props}
/>
)
}
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<div
data-slot="empty-description"
className={cn(
"text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-content"
className={cn(
"flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance",
className
)}
{...props}
/>
)
}
export {
Empty,
EmptyHeader,
EmptyTitle,
EmptyDescription,
EmptyContent,
EmptyMedia,
}

246
src/components/ui/field.tsx Normal file
View File

@@ -0,0 +1,246 @@
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
className
)}
{...props}
/>
)
}
const fieldVariants = cva(
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"[&>[data-slot=field-label]]:flex-auto",
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
responsive: [
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto",
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
}
)
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className
)}
{...props}
/>
)
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
className
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute left-0 right-0 top-0 bottom-0 top-1/2" />
{children && (
<span
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
if (!errors?.length) {
return null
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
]
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-destructive text-sm font-normal", className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
}

167
src/components/ui/form.tsx Normal file
View File

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

View File

@@ -0,0 +1,168 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-group"
role="group"
className={cn(
"group/input-group border-input dark:bg-input/30 relative flex w-full items-center rounded-md border shadow-xs transition-[color,box-shadow] outline-none",
"h-9 min-w-0 has-[>textarea]:h-auto",
// Variants based on alignment.
"has-[>[data-align=inline-start]]:[&>input]:pl-2",
"has-[>[data-align=inline-end]]:[&>input]:pr-2",
"has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>[data-align=block-start]]:[&>input]:pb-3",
"has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-end]]:[&>input]:pt-3",
// Focus state.
"has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot=input-group-control]:focus-visible]:ring-[3px]",
// Error state.
"has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[[data-slot][aria-invalid=true]]:border-destructive dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40",
className
)}
{...props}
/>
)
}
const inputGroupAddonVariants = cva(
"text-muted-foreground flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium select-none [&>svg:not([class*='size-'])]:size-4 [&>kbd]:rounded-[calc(var(--radius)-5px)] group-data-[disabled=true]/input-group:opacity-50",
{
variants: {
align: {
"inline-start":
"order-first pl-3 has-[>button]:ml-[-0.45rem] has-[>kbd]:ml-[-0.35rem]",
"inline-end":
"order-last pr-3 has-[>button]:mr-[-0.45rem] has-[>kbd]:mr-[-0.35rem]",
"block-start":
"order-first w-full justify-start px-3 pt-3 [.border-b]:pb-3 group-has-[>input]/input-group:pt-2.5",
"block-end":
"order-last w-full justify-start px-3 pb-3 [.border-t]:pt-3 group-has-[>input]/input-group:pb-2.5",
},
},
defaultVariants: {
align: "inline-start",
},
}
)
function InputGroupAddon({
className,
align = "inline-start",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
return (
<div
role="group"
data-slot="input-group-addon"
data-align={align}
className={cn(inputGroupAddonVariants({ align }), className)}
onClick={(e) => {
if ((e.target as HTMLElement).closest("button")) {
return
}
e.currentTarget.parentElement?.querySelector("input")?.focus()
}}
{...props}
/>
)
}
const inputGroupButtonVariants = cva(
"text-sm shadow-none flex gap-2 items-center",
{
variants: {
size: {
xs: "h-6 gap-1 px-2 rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-3.5 has-[>svg]:px-2",
sm: "h-8 px-2.5 gap-1.5 rounded-md has-[>svg]:px-2.5",
"icon-xs":
"size-6 rounded-[calc(var(--radius)-5px)] p-0 has-[>svg]:p-0",
"icon-sm": "size-8 p-0 has-[>svg]:p-0",
},
},
defaultVariants: {
size: "xs",
},
}
)
function InputGroupButton({
className,
type = "button",
variant = "ghost",
size = "xs",
...props
}: Omit<React.ComponentProps<typeof Button>, "size"> &
VariantProps<typeof inputGroupButtonVariants>) {
return (
<Button
type={type}
data-size={size}
variant={variant}
className={cn(inputGroupButtonVariants({ size }), className)}
{...props}
/>
)
}
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
className={cn(
"text-muted-foreground flex items-center gap-2 text-sm [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function InputGroupInput({
className,
...props
}: React.ComponentProps<"input">) {
return (
<Input
data-slot="input-group-control"
className={cn(
"flex-1 rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent",
className
)}
{...props}
/>
)
}
function InputGroupTextarea({
className,
...props
}: React.ComponentProps<"textarea">) {
return (
<Textarea
data-slot="input-group-control"
className={cn(
"flex-1 resize-none rounded-none border-0 bg-transparent py-3 shadow-none focus-visible:ring-0 dark:bg-transparent",
className
)}
{...props}
/>
)
}
export {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupText,
InputGroupInput,
InputGroupTextarea,
}

View File

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

View File

@@ -0,0 +1,22 @@
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,127 @@
import * as React from "react"
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { buttonVariants, type Button } 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,46 @@
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-[var(--radix-popover-content-transform-origin)] rounded-md border p-4 shadow-md outline-none",
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,29 @@
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,43 @@
import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function RadioGroup({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
className={cn("grid gap-3", className)}
{...props}
/>
)
}
function RadioGroupItem({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
return (
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"border-input text-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 dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator
data-slot="radio-group-indicator"
className="relative flex items-center justify-center"
>
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
}
export { RadioGroup, RadioGroupItem }

View File

@@ -0,0 +1,188 @@
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 = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-[var(--radix-select-content-available-height)] min-w-[8rem] origin-[var(--radix-select-content-transform-origin)] overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-none 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-child]:flex [&_span:last-child]:items-center [&_span:last-child]:space-x-2",
className
)}
{...props}
>
<span
data-slot="select-item-indicator"
className="absolute right-2 flex size-3.5 items-center justify-center"
>
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@@ -0,0 +1,28 @@
"use client"
import * as 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"
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 }

139
src/components/ui/sheet.tsx Normal file
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 left-0 right-0 top-0 bottom-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-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none 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 { cva, type VariantProps } 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 bg-sidebar flex min-h-screen 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-[var(--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-[var(--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-[var(--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)+1rem)]"
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)]"
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-screen w-[var(--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)+1rem+2px)]"
: "group-data-[collapsible=icon]:w-[var(--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("h-7 w-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-none 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-none 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 space-x-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none 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 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]:h-8 group-data-[collapsible=icon]:w-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-none 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-[var(--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,38 @@
import {
CircleCheckIcon,
InfoIcon,
Loader2Icon,
OctagonXIcon,
TriangleAlertIcon,
} from "lucide-react"
import { useTheme } from "next-themes"
import { Toaster as Sonner, type ToasterProps } from "sonner"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
icons={{
success: <CircleCheckIcon className="size-4" />,
info: <InfoIcon className="size-4" />,
warning: <TriangleAlertIcon className="size-4" />,
error: <OctagonXIcon className="size-4" />,
loading: <Loader2Icon className="size-4 animate-spin" />,
}}
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
} as React.CSSProperties
}
{...props}
/>
)
}
export { Toaster }

View File

@@ -0,0 +1,16 @@
import { Loader2Icon } from "lucide-react"
import { cn } from "@/lib/utils"
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
return (
<Loader2Icon
role="status"
aria-label="Loading"
className={cn("size-4 animate-spin", className)}
{...props}
/>
)
}
export { Spinner }

View File

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

114
src/components/ui/table.tsx Normal file
View File

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

View File

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

View File

@@ -0,0 +1,83 @@
"use client"
import * as React from "react"
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants> & {
spacing?: number
}
>({
size: "default",
variant: "default",
spacing: 0,
})
function ToggleGroup({
className,
variant,
size,
spacing = 0,
children,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
VariantProps<typeof toggleVariants> & {
spacing?: number
}) {
return (
<ToggleGroupPrimitive.Root
data-slot="toggle-group"
data-variant={variant}
data-size={size}
data-spacing={spacing}
style={{ "--gap": `${spacing}px` } as React.CSSProperties}
className={cn(
"group/toggle-group flex w-fit items-center gap-[var(--gap)] rounded-md data-[spacing=default]:data-[variant=outline]:shadow-xs",
className
)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size, spacing }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
)
}
function ToggleGroupItem({
className,
children,
variant,
size,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext)
return (
<ToggleGroupPrimitive.Item
data-slot="toggle-group-item"
data-variant={context.variant || variant}
data-size={context.size || size}
data-spacing={context.spacing}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
"w-auto min-w-0 shrink-0 px-3 focus:z-10 focus-visible:z-10",
"data-[spacing=0]:rounded-none data-[spacing=0]:shadow-none data-[spacing=0]:first:rounded-l-md data-[spacing=0]:last:rounded-r-md data-[spacing=0]:data-[variant=outline]:border-l-0 data-[spacing=0]:data-[variant=outline]:first:border-l",
className
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
)
}
export { ToggleGroup, ToggleGroupItem }

View File

@@ -0,0 +1,45 @@
import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-9 px-2 min-w-9",
sm: "h-8 px-1.5 min-w-8",
lg: "h-10 px-2.5 min-w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Toggle({
className,
variant,
size,
...props
}: React.ComponentProps<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive.Root
data-slot="toggle"
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Toggle, toggleVariants }

View File

@@ -0,0 +1,59 @@
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-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-[var(--radix-tooltip-content-transform-origin)] rounded-md px-3 py-1.5 text-xs",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@@ -0,0 +1,99 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { getFilePage } from "@/apis/file";
import { useReactTable } from "@tanstack/react-table";
import { getCoreRowModel } from "@tanstack/react-table";
type UseFetchFilesProps = {
useColumns: any;
queryKey: any[];
params: any;
};
export const useFetchFiles = ({
useColumns,
queryKey,
params,
}: UseFetchFilesProps) => {
// 当前打开的目录层级
const [openDirectorys, setOpenDirectorys] = useState([]);
// 文件目录ID
const [parentId, setParentId] = useState(0);
// 分页
const [pagination, setPagination] = useState({
pageIndex: 0,
pageSize: 10,
});
// 查询数据
const query = useQuery<any>({
queryKey: [...queryKey, pagination, parentId, params],
queryFn: () =>
getFilePage({
parentId: parentId || 0,
pageSize: pagination.pageSize,
pageNo: pagination.pageIndex + 1,
...params,
}).then((res) => res.data),
});
// 切换上级ID
const handleChangeParentId = (record: any) => {
setParentId(record.id);
// 重置分页
table.setPageIndex(0);
// @ts-ignore
setOpenDirectorys((prev: any) => [...prev, record]);
};
// 表格
const columns = useColumns(handleChangeParentId);
const table = useReactTable({
data: query?.data?.entityList || [],
columns,
getCoreRowModel: getCoreRowModel(),
manualPagination: false,
rowCount: query?.data?.totalCount || 0,
pageCount: query?.data?.pageCount || 0,
onPaginationChange: setPagination,
autoResetPageIndex: false,
state: {
pagination,
},
});
const changeOpenDirectorys = (record?: any) => {
setParentId(record?.id);
// 重置分页
table.setPageIndex(0);
// @ts-ignore
setOpenDirectorys((prev: any[]) => {
const index = prev.findIndex((item: any) => item.id === record?.id);
if (index > -1) {
return [...prev.slice(0, index + 1)];
}
return [];
});
};
// 重置
const reset = () => {
setParentId(0);
// 重置分页
table.setPageIndex(0);
// @ts-ignore
setOpenDirectorys([]);
};
return {
parentId,
setParentId,
handleChangeParentId,
openDirectorys,
changeOpenDirectorys,
pagination,
table,
query,
reset,
};
};

View File

@@ -0,0 +1,26 @@
const fileCategorys = [
{
value: "image",
name: "图片",
},
{
value: "video",
name: "视频",
},
{
value: "document",
name: "文档",
},
{
value: "other",
name: "其他",
},
{
value: "unknown",
name: "未知",
},
];
export const useFileCategoryName = (value: string) => {
return fileCategorys.find((item) => item.value === value)?.name || "未知";
};

19
src/hooks/use-mobile.ts Normal file
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,23 @@
import { useMutation } from "@tanstack/react-query";
import { modifyFile } from "@/apis/file";
import { toast } from "sonner";
export const useMoveFile = (mutationOptions?: any) => {
const { mutateAsync: moveMutateAsync, isPending: moveIsPending } =
useMutation({
mutationFn: modifyFile,
...(mutationOptions || {}),
});
const move = (values: any) => {
toast.promise(moveMutateAsync(values), {
loading: "移动中",
success: "移动成功",
});
};
return {
move,
moveIsPending,
};
};

View File

@@ -0,0 +1,23 @@
import { useMutation } from "@tanstack/react-query";
import { modifyFileStatus } from "@/apis/file";
import { toast } from "sonner";
export const useRemoveFile = (mutationOptions?: any) => {
const { mutateAsync: removeMutateAsync, isPending: removeIsPending } =
useMutation({
mutationFn: modifyFileStatus,
...(mutationOptions || {}),
});
const remove = (values: any) => {
toast.promise(removeMutateAsync(values), {
loading: "删除中",
success: "删除成功",
});
};
return {
remove,
removeIsPending,
};
};

View File

@@ -0,0 +1,37 @@
import { useQuery } from "@tanstack/react-query";
import { getUploadConfig } from "@/apis/upload-config";
export type UploadConfig = {
orgId: number;
uploadEnabled: boolean;
allowAllType: boolean;
allowedSuffixes: string[] | null;
maxFileSize: number | null;
configured: boolean;
};
// 当前机构的上传配置(未配置过的机构 = 默认策略:允许上传、允许全部类型、不限大小)
export const useUploadConfig = () => {
return useQuery<UploadConfig>({
queryKey: ["uploadConfig"],
queryFn: () => getUploadConfig().then((res: any) => res?.data),
});
};
// 允许的后缀 → 文件选择器 accept(带点);不限制时返回 undefined
export const toAccept = (config?: UploadConfig | null) => {
if (!config || config.allowAllType || !config.allowedSuffixes?.length) {
return undefined;
}
return config.allowedSuffixes
.map((suffix) => `.${String(suffix).replace(/^\.+/, "").toLowerCase()}`)
.join(",");
};
// 单文件大小上限(字节);不限制时返回 undefined
export const toMaxSize = (config?: UploadConfig | null) => {
if (config?.maxFileSize && config.maxFileSize > 0) {
return config.maxFileSize * 1024 * 1024;
}
return undefined;
};

View File

@@ -0,0 +1,41 @@
import { useMutation } from "@tanstack/react-query";
import { adminCancelUser, disableUser, enableUser } from "@/apis/user";
import { toast } from "sonner";
export const useUserStatusActions = (mutationOptions?: any) => {
const { mutateAsync: enableMutateAsync, isPending: enableIsPending } =
useMutation<any, Error, number>({
mutationFn: enableUser,
...(mutationOptions || {}),
});
const { mutateAsync: disableMutateAsync, isPending: disableIsPending } =
useMutation<any, Error, number>({
mutationFn: disableUser,
...(mutationOptions || {}),
});
const { mutateAsync: cancelMutateAsync, isPending: cancelIsPending } =
useMutation<any, Error, number>({
mutationFn: adminCancelUser,
...(mutationOptions || {}),
});
const wrap = (mutateAsync: (userId: number) => Promise<any>) => {
return (userId: number) => {
toast.promise(mutateAsync(userId), {
loading: "提交中...",
success: "操作成功",
});
};
};
return {
enable: wrap(enableMutateAsync),
disable: wrap(disableMutateAsync),
adminCancel: wrap(cancelMutateAsync),
enableIsPending,
disableIsPending,
cancelIsPending,
};
};

View File

@@ -0,0 +1,5 @@
export const HTTP_CONTENT_TYPE = {
MULTIPART_FORM_DATA: "multipart/form-data",
APPLICATION_FORM_URLENCODED: "application/x-www-form-urlencoded",
APPLICATION_JSON: "application/json",
} as const;

4
src/lib/http/csrf.ts Normal file
View File

@@ -0,0 +1,4 @@
export const getCsrfToken = (): string | null => {
const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/);
return match ? decodeURIComponent(match[1]) : null;
};

2
src/lib/http/index.ts Normal file
View File

@@ -0,0 +1,2 @@
export { default as http } from "./instance";
export * from "./constants";

22
src/lib/http/instance.ts Normal file
View File

@@ -0,0 +1,22 @@
import axios from "axios";
import { HTTP_CONTENT_TYPE } from "./constants";
import { setupInterceptors } from "./interceptors";
const http = axios.create({
timeout: 600_000,
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": HTTP_CONTENT_TYPE.APPLICATION_JSON,
},
baseURL: import.meta.env.VITE_API_URL,
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-XSRF-TOKEN",
});
// 设置实例的原型
// Object.setPrototypeOf(http, axios);
// 设置拦截器
setupInterceptors(http);
export default http;

View File

@@ -0,0 +1,110 @@
import { useUserStore } from "@/stores/user";
import type { AxiosInstance, InternalAxiosRequestConfig } from "axios";
import { toast } from "sonner";
import router from "@/router";
import { getCsrfToken } from "./csrf";
export const downloadFile = (res: any) => {
const [, filename] = res.headers?.["content-disposition"]?.split(";") || [];
const link = document.createElement("a");
link.download = decodeURIComponent(
filename?.replace("filename=", "").replace(/\"/g, "").trim() || "",
);
link.style.display = "none";
link.href = URL.createObjectURL(res.data);
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
};
export const setupInterceptors = (instance: AxiosInstance) => {
// 请求拦截
instance.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
console.info(
"%c request ------>%o",
"background:#4f46e5;color:#fff;",
config,
);
const csrfToken = getCsrfToken();
// @ts-ignore
config.headers = {
...config.headers,
// @ts-ignore
Authorization: `Bearer ${useUserStore.getState().token}`,
"X-XSRF-TOKEN": csrfToken || "",
};
return config;
},
(err: any) => {
console.error(
"%c request ------>%o",
"background:#dc2626;color:#fff;",
err,
);
return Promise.reject(err);
},
);
// 响应拦截
instance.interceptors.response.use(
(res: any) => {
console.info(
"%c response ------>%o",
"background:#059669;color:#fff;",
res,
);
if (res.status !== 200) {
toast.error(res?.data?.msg || "请求失败,请稍后再试");
return Promise.reject(res.data);
}
// 文件下载
if (!res.headers["content-type"]?.startsWith("application/json")) {
downloadFile(res);
return Promise.resolve();
}
const { code, msg, errorData } = res.data;
// 成功处理
if (["200"].includes(code) || res.headers.code === 200) {
return Promise.resolve(res.data);
}
// 未登录、登录超时、无权访问,重定向到登录页面
if (
["401", "402"].includes(code) &&
router.state.location.pathname !== "/login"
) {
toast.error(msg || "未登录/无权限");
useUserStore.setState({ token: null });
router.navigate({
to:
"/login?redirect=" +
encodeURIComponent(encodeURIComponent(router.state.location.href)),
replace: true,
});
return Promise.reject();
}
// token变更
if (code === "603") {
useUserStore.setState({ token: errorData.token });
return Promise.resolve();
}
// 失败统一弹窗处理
if (["555", "666", "999", "401", "402", "700"].includes(code)) {
toast.error(msg || "系统错误,请稍后再试");
}
return Promise.reject(res.data);
},
(err) => {
console.error(
"%c response ------>%o",
"background:#dc2626;color:#fff;",
err,
);
return Promise.reject(err);
},
);
return instance;
};

18
src/lib/utils.ts Normal file
View File

@@ -0,0 +1,18 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
// 将文件大小转换为人类可读的格式
export function formatFileSize(bytes: number): string {
if (bytes === undefined || bytes === null) return "-";
if (bytes === 0) return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
}

33
src/main.tsx Normal file
View File

@@ -0,0 +1,33 @@
import "@/polyfills/urlParse.js";
import "@/polyfills/promiseWithResolvers.js";
import React from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider } from "@tanstack/react-router";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@/components/ui/sonner";
import router from "@/router";
import "@/styles/globals.css";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
},
},
});
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<ThemeProvider defaultTheme="light" storageKey="react-flow-theme">
<RouterProvider router={router} />
<Toaster position="top-center" richColors theme="light" />
{import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
</ThemeProvider>
</QueryClientProvider>
</React.StrictMode>,
);

View File

@@ -0,0 +1,11 @@
// 严格检测:仅原生环境无该API时,才注入兼容实现
if (typeof Promise !== "function" || !Promise.withResolvers) {
Promise.withResolvers = function withResolvers() {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
}

29
src/polyfills/urlParse.js Normal file
View File

@@ -0,0 +1,29 @@
/* Polyfill for URL.parse / URL.canParse for older browsers (e.g. Chrome 86).
Must be imported before libraries like pdfjs-dist that may call URL.parse.
*/
(function applyUrlParsePolyfill() {
if (typeof URL === "undefined") return
if (typeof URL.parse !== "function") {
URL.parse = function (url, base) {
try {
return new URL(url, base)
} catch {
return null
}
}
}
if (typeof URL.canParse !== "function") {
URL.canParse = function (url, base) {
try {
// eslint-disable-next-line no-new
new URL(url, base)
return true
} catch {
return false
}
}
}
})()

433
src/routeTree.gen.ts Normal file
View File

@@ -0,0 +1,433 @@
/* eslint-disable */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// This file was automatically generated by TanStack Router.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as LoginRouteImport } from './routes/login'
import { Route as AdminRouteRouteImport } from './routes/admin/route'
import { Route as userRouteRouteImport } from './routes/(user)/route'
import { Route as ExtractIndexRouteImport } from './routes/extract/index'
import { Route as AdminIndexRouteImport } from './routes/admin/index'
import { Route as userIndexRouteImport } from './routes/(user)/index'
import { Route as ExtractListRouteImport } from './routes/extract/list'
import { Route as AdminUserIndexRouteImport } from './routes/admin/user/index'
import { Route as AdminUploadConfigIndexRouteImport } from './routes/admin/upload-config/index'
import { Route as AdminTenantIndexRouteImport } from './routes/admin/tenant/index'
import { Route as AdminOrgAccountIndexRouteImport } from './routes/admin/org-account/index'
import { Route as AdminFileRecordIndexRouteImport } from './routes/admin/file-record/index'
import { Route as AdminConsoleIndexRouteImport } from './routes/admin/console/index'
import { Route as userShareIndexRouteImport } from './routes/(user)/share/index'
import { Route as userRecycleIndexRouteImport } from './routes/(user)/recycle/index'
import { Route as userOutsideIndexRouteImport } from './routes/(user)/outside/index'
import { Route as userMyIndexRouteImport } from './routes/(user)/my/index'
import { Route as userInsideIndexRouteImport } from './routes/(user)/inside/index'
const LoginRoute = LoginRouteImport.update({
id: '/login',
path: '/login',
getParentRoute: () => rootRouteImport,
} as any)
const AdminRouteRoute = AdminRouteRouteImport.update({
id: '/admin',
path: '/admin',
getParentRoute: () => rootRouteImport,
} as any)
const userRouteRoute = userRouteRouteImport.update({
id: '/(user)',
getParentRoute: () => rootRouteImport,
} as any)
const ExtractIndexRoute = ExtractIndexRouteImport.update({
id: '/extract/',
path: '/extract/',
getParentRoute: () => rootRouteImport,
} as any)
const AdminIndexRoute = AdminIndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => AdminRouteRoute,
} as any)
const userIndexRoute = userIndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => userRouteRoute,
} as any)
const ExtractListRoute = ExtractListRouteImport.update({
id: '/extract/list',
path: '/extract/list',
getParentRoute: () => rootRouteImport,
} as any)
const AdminUserIndexRoute = AdminUserIndexRouteImport.update({
id: '/user/',
path: '/user/',
getParentRoute: () => AdminRouteRoute,
} as any)
const AdminUploadConfigIndexRoute = AdminUploadConfigIndexRouteImport.update({
id: '/upload-config/',
path: '/upload-config/',
getParentRoute: () => AdminRouteRoute,
} as any)
const AdminTenantIndexRoute = AdminTenantIndexRouteImport.update({
id: '/tenant/',
path: '/tenant/',
getParentRoute: () => AdminRouteRoute,
} as any)
const AdminOrgAccountIndexRoute = AdminOrgAccountIndexRouteImport.update({
id: '/org-account/',
path: '/org-account/',
getParentRoute: () => AdminRouteRoute,
} as any)
const AdminFileRecordIndexRoute = AdminFileRecordIndexRouteImport.update({
id: '/file-record/',
path: '/file-record/',
getParentRoute: () => AdminRouteRoute,
} as any)
const AdminConsoleIndexRoute = AdminConsoleIndexRouteImport.update({
id: '/console/',
path: '/console/',
getParentRoute: () => AdminRouteRoute,
} as any)
const userShareIndexRoute = userShareIndexRouteImport.update({
id: '/share/',
path: '/share/',
getParentRoute: () => userRouteRoute,
} as any)
const userRecycleIndexRoute = userRecycleIndexRouteImport.update({
id: '/recycle/',
path: '/recycle/',
getParentRoute: () => userRouteRoute,
} as any)
const userOutsideIndexRoute = userOutsideIndexRouteImport.update({
id: '/outside/',
path: '/outside/',
getParentRoute: () => userRouteRoute,
} as any)
const userMyIndexRoute = userMyIndexRouteImport.update({
id: '/my/',
path: '/my/',
getParentRoute: () => userRouteRoute,
} as any)
const userInsideIndexRoute = userInsideIndexRouteImport.update({
id: '/inside/',
path: '/inside/',
getParentRoute: () => userRouteRoute,
} as any)
export interface FileRoutesByFullPath {
'/admin': typeof AdminRouteRouteWithChildren
'/login': typeof LoginRoute
'/extract/list': typeof ExtractListRoute
'/': typeof userIndexRoute
'/admin/': typeof AdminIndexRoute
'/extract/': typeof ExtractIndexRoute
'/inside/': typeof userInsideIndexRoute
'/my/': typeof userMyIndexRoute
'/outside/': typeof userOutsideIndexRoute
'/recycle/': typeof userRecycleIndexRoute
'/share/': typeof userShareIndexRoute
'/admin/console/': typeof AdminConsoleIndexRoute
'/admin/file-record/': typeof AdminFileRecordIndexRoute
'/admin/org-account/': typeof AdminOrgAccountIndexRoute
'/admin/tenant/': typeof AdminTenantIndexRoute
'/admin/upload-config/': typeof AdminUploadConfigIndexRoute
'/admin/user/': typeof AdminUserIndexRoute
}
export interface FileRoutesByTo {
'/login': typeof LoginRoute
'/extract/list': typeof ExtractListRoute
'/': typeof userIndexRoute
'/admin': typeof AdminIndexRoute
'/extract': typeof ExtractIndexRoute
'/inside': typeof userInsideIndexRoute
'/my': typeof userMyIndexRoute
'/outside': typeof userOutsideIndexRoute
'/recycle': typeof userRecycleIndexRoute
'/share': typeof userShareIndexRoute
'/admin/console': typeof AdminConsoleIndexRoute
'/admin/file-record': typeof AdminFileRecordIndexRoute
'/admin/org-account': typeof AdminOrgAccountIndexRoute
'/admin/tenant': typeof AdminTenantIndexRoute
'/admin/upload-config': typeof AdminUploadConfigIndexRoute
'/admin/user': typeof AdminUserIndexRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/(user)': typeof userRouteRouteWithChildren
'/admin': typeof AdminRouteRouteWithChildren
'/login': typeof LoginRoute
'/extract/list': typeof ExtractListRoute
'/(user)/': typeof userIndexRoute
'/admin/': typeof AdminIndexRoute
'/extract/': typeof ExtractIndexRoute
'/(user)/inside/': typeof userInsideIndexRoute
'/(user)/my/': typeof userMyIndexRoute
'/(user)/outside/': typeof userOutsideIndexRoute
'/(user)/recycle/': typeof userRecycleIndexRoute
'/(user)/share/': typeof userShareIndexRoute
'/admin/console/': typeof AdminConsoleIndexRoute
'/admin/file-record/': typeof AdminFileRecordIndexRoute
'/admin/org-account/': typeof AdminOrgAccountIndexRoute
'/admin/tenant/': typeof AdminTenantIndexRoute
'/admin/upload-config/': typeof AdminUploadConfigIndexRoute
'/admin/user/': typeof AdminUserIndexRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/admin'
| '/login'
| '/extract/list'
| '/'
| '/admin/'
| '/extract/'
| '/inside/'
| '/my/'
| '/outside/'
| '/recycle/'
| '/share/'
| '/admin/console/'
| '/admin/file-record/'
| '/admin/org-account/'
| '/admin/tenant/'
| '/admin/upload-config/'
| '/admin/user/'
fileRoutesByTo: FileRoutesByTo
to:
| '/login'
| '/extract/list'
| '/'
| '/admin'
| '/extract'
| '/inside'
| '/my'
| '/outside'
| '/recycle'
| '/share'
| '/admin/console'
| '/admin/file-record'
| '/admin/org-account'
| '/admin/tenant'
| '/admin/upload-config'
| '/admin/user'
id:
| '__root__'
| '/(user)'
| '/admin'
| '/login'
| '/extract/list'
| '/(user)/'
| '/admin/'
| '/extract/'
| '/(user)/inside/'
| '/(user)/my/'
| '/(user)/outside/'
| '/(user)/recycle/'
| '/(user)/share/'
| '/admin/console/'
| '/admin/file-record/'
| '/admin/org-account/'
| '/admin/tenant/'
| '/admin/upload-config/'
| '/admin/user/'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
userRouteRoute: typeof userRouteRouteWithChildren
AdminRouteRoute: typeof AdminRouteRouteWithChildren
LoginRoute: typeof LoginRoute
ExtractListRoute: typeof ExtractListRoute
ExtractIndexRoute: typeof ExtractIndexRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/login': {
id: '/login'
path: '/login'
fullPath: '/login'
preLoaderRoute: typeof LoginRouteImport
parentRoute: typeof rootRouteImport
}
'/admin': {
id: '/admin'
path: '/admin'
fullPath: '/admin'
preLoaderRoute: typeof AdminRouteRouteImport
parentRoute: typeof rootRouteImport
}
'/(user)': {
id: '/(user)'
path: ''
fullPath: ''
preLoaderRoute: typeof userRouteRouteImport
parentRoute: typeof rootRouteImport
}
'/extract/': {
id: '/extract/'
path: '/extract'
fullPath: '/extract/'
preLoaderRoute: typeof ExtractIndexRouteImport
parentRoute: typeof rootRouteImport
}
'/admin/': {
id: '/admin/'
path: '/'
fullPath: '/admin/'
preLoaderRoute: typeof AdminIndexRouteImport
parentRoute: typeof AdminRouteRoute
}
'/(user)/': {
id: '/(user)/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof userIndexRouteImport
parentRoute: typeof userRouteRoute
}
'/extract/list': {
id: '/extract/list'
path: '/extract/list'
fullPath: '/extract/list'
preLoaderRoute: typeof ExtractListRouteImport
parentRoute: typeof rootRouteImport
}
'/admin/user/': {
id: '/admin/user/'
path: '/user'
fullPath: '/admin/user/'
preLoaderRoute: typeof AdminUserIndexRouteImport
parentRoute: typeof AdminRouteRoute
}
'/admin/upload-config/': {
id: '/admin/upload-config/'
path: '/upload-config'
fullPath: '/admin/upload-config/'
preLoaderRoute: typeof AdminUploadConfigIndexRouteImport
parentRoute: typeof AdminRouteRoute
}
'/admin/tenant/': {
id: '/admin/tenant/'
path: '/tenant'
fullPath: '/admin/tenant/'
preLoaderRoute: typeof AdminTenantIndexRouteImport
parentRoute: typeof AdminRouteRoute
}
'/admin/org-account/': {
id: '/admin/org-account/'
path: '/org-account'
fullPath: '/admin/org-account/'
preLoaderRoute: typeof AdminOrgAccountIndexRouteImport
parentRoute: typeof AdminRouteRoute
}
'/admin/file-record/': {
id: '/admin/file-record/'
path: '/file-record'
fullPath: '/admin/file-record/'
preLoaderRoute: typeof AdminFileRecordIndexRouteImport
parentRoute: typeof AdminRouteRoute
}
'/admin/console/': {
id: '/admin/console/'
path: '/console'
fullPath: '/admin/console/'
preLoaderRoute: typeof AdminConsoleIndexRouteImport
parentRoute: typeof AdminRouteRoute
}
'/(user)/share/': {
id: '/(user)/share/'
path: '/share'
fullPath: '/share/'
preLoaderRoute: typeof userShareIndexRouteImport
parentRoute: typeof userRouteRoute
}
'/(user)/recycle/': {
id: '/(user)/recycle/'
path: '/recycle'
fullPath: '/recycle/'
preLoaderRoute: typeof userRecycleIndexRouteImport
parentRoute: typeof userRouteRoute
}
'/(user)/outside/': {
id: '/(user)/outside/'
path: '/outside'
fullPath: '/outside/'
preLoaderRoute: typeof userOutsideIndexRouteImport
parentRoute: typeof userRouteRoute
}
'/(user)/my/': {
id: '/(user)/my/'
path: '/my'
fullPath: '/my/'
preLoaderRoute: typeof userMyIndexRouteImport
parentRoute: typeof userRouteRoute
}
'/(user)/inside/': {
id: '/(user)/inside/'
path: '/inside'
fullPath: '/inside/'
preLoaderRoute: typeof userInsideIndexRouteImport
parentRoute: typeof userRouteRoute
}
}
}
interface userRouteRouteChildren {
userIndexRoute: typeof userIndexRoute
userInsideIndexRoute: typeof userInsideIndexRoute
userMyIndexRoute: typeof userMyIndexRoute
userOutsideIndexRoute: typeof userOutsideIndexRoute
userRecycleIndexRoute: typeof userRecycleIndexRoute
userShareIndexRoute: typeof userShareIndexRoute
}
const userRouteRouteChildren: userRouteRouteChildren = {
userIndexRoute: userIndexRoute,
userInsideIndexRoute: userInsideIndexRoute,
userMyIndexRoute: userMyIndexRoute,
userOutsideIndexRoute: userOutsideIndexRoute,
userRecycleIndexRoute: userRecycleIndexRoute,
userShareIndexRoute: userShareIndexRoute,
}
const userRouteRouteWithChildren = userRouteRoute._addFileChildren(
userRouteRouteChildren,
)
interface AdminRouteRouteChildren {
AdminIndexRoute: typeof AdminIndexRoute
AdminConsoleIndexRoute: typeof AdminConsoleIndexRoute
AdminFileRecordIndexRoute: typeof AdminFileRecordIndexRoute
AdminOrgAccountIndexRoute: typeof AdminOrgAccountIndexRoute
AdminTenantIndexRoute: typeof AdminTenantIndexRoute
AdminUploadConfigIndexRoute: typeof AdminUploadConfigIndexRoute
AdminUserIndexRoute: typeof AdminUserIndexRoute
}
const AdminRouteRouteChildren: AdminRouteRouteChildren = {
AdminIndexRoute: AdminIndexRoute,
AdminConsoleIndexRoute: AdminConsoleIndexRoute,
AdminFileRecordIndexRoute: AdminFileRecordIndexRoute,
AdminOrgAccountIndexRoute: AdminOrgAccountIndexRoute,
AdminTenantIndexRoute: AdminTenantIndexRoute,
AdminUploadConfigIndexRoute: AdminUploadConfigIndexRoute,
AdminUserIndexRoute: AdminUserIndexRoute,
}
const AdminRouteRouteWithChildren = AdminRouteRoute._addFileChildren(
AdminRouteRouteChildren,
)
const rootRouteChildren: RootRouteChildren = {
userRouteRoute: userRouteRouteWithChildren,
AdminRouteRoute: AdminRouteRouteWithChildren,
LoginRoute: LoginRoute,
ExtractListRoute: ExtractListRoute,
ExtractIndexRoute: ExtractIndexRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()

16
src/router.ts Normal file
View File

@@ -0,0 +1,16 @@
import ErrorBoundary from "@/components/error-boundary";
import NotFound from "@/components/not-found";
import Loading from "@/components/loading";
import { createRouter, createHashHistory } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
const router = createRouter({
routeTree,
history: createHashHistory(),
basepath: import.meta.env.VITE_BASEPATH,
defaultNotFoundComponent: NotFound,
defaultErrorComponent: ErrorBoundary,
defaultPendingComponent: Loading,
});
export default router;

View File

@@ -0,0 +1,150 @@
import { Label, Pie, PieChart, Sector } from "recharts";
import { ChartContainer, ChartTooltip } from "@/components/ui/chart";
import { formatFileSize } from "@/lib/utils";
import { useMemo } from "react";
import type { PieSectorDataItem } from "recharts/types/polar/Pie";
// 总量
const total = 10 * 1024 * 1024 * 1024;
export const CustomTooltip = ({ active, payload }: any) => {
const isVisible = active && payload && payload.length;
const data = payload?.[0]?.payload;
return (
<div
className="p-4 bg-white/50 text-black backdrop-blur-lg rounded-md shadow z-10 border"
style={{
visibility: isVisible ? "visible" : "hidden",
borderColor: isVisible ? data?.fill : "transparent",
}}
>
{isVisible && (
<div className="flex items-center gap-2 min-w-[150px]">
<span
className="flex-none inline-block h-4 w-4 rounded-full bg-black"
style={{ backgroundColor: data.fill }}
/>
<span className="flex-none">{data.name}</span>
<span className="flex-auto text-right">{data.sizeString}</span>
</div>
)}
</div>
);
};
type Props = {
data: any[];
categorys: any[];
};
export function ChartPieDonutText({ data, categorys }: Props) {
// 已使用
const usedTotal = useMemo(() => {
if (!data?.length) {
return 0;
}
return data.reduce((count, current) => count + current.totalSize, 0);
}, [data]);
// 未使用
const unusedTotal = useMemo(() => total - usedTotal, [usedTotal]);
const chartData = useMemo(() => {
if (!data?.length) {
return [];
}
return [
...data,
{
totalSize: unusedTotal,
fileCategory: "unused",
key: "unused",
name: "未使用",
color: "hsl(var(--muted))",
sizeString: formatFileSize(unusedTotal),
proportion: Math.round((unusedTotal / total) * 100),
fill: `var(--color-unused)`,
},
];
}, [data, unusedTotal]);
const chartConfig = useMemo(() => {
if (!categorys?.length) {
return {};
}
return Object.fromEntries(
categorys.map((item) => [item.key, { ...item, label: item.name }])
);
}, [categorys]);
if (!data?.length) {
return null;
}
return (
<div className="w-full h-full">
<ChartContainer
config={chartConfig}
className="mx-auto aspect-square h-[240px]"
>
<PieChart>
<ChartTooltip cursor={false} content={CustomTooltip} />
<Pie
data={chartData}
dataKey="totalSize"
nameKey="fileCategory"
innerRadius={60}
strokeWidth={4}
activeIndex={0}
activeShape={({ outerRadius = 0, ...props }: PieSectorDataItem) => (
<Sector {...props} outerRadius={outerRadius + 10} />
)}
>
<Label
content={({ viewBox }) => {
if (viewBox && "cx" in viewBox && "cy" in viewBox) {
return (
<text
x={viewBox.cx}
y={viewBox.cy}
textAnchor="middle"
dominantBaseline="middle"
>
<tspan
x={viewBox.cx}
y={viewBox.cy}
className="fill-foreground text-2xl font-bold"
>
{formatFileSize(unusedTotal)}
</tspan>
<tspan
x={viewBox.cx}
y={(viewBox.cy || 0) + 24}
className="fill-muted-foreground"
>
可用容量
</tspan>
</text>
);
}
}}
/>
</Pie>
</PieChart>
</ChartContainer>
<div className="mt-5 flex items-center justify-center flex-col">
<div className="text-base text-black/60 flex items-center justify-between w-[240px] border-b border-b-solid border-b-black/10 py-4">
<span>总量:</span>
<span>{formatFileSize(total)}</span>
</div>
<div className="text-base text-black/60 flex items-center justify-between w-[240px] border-b border-b-solid border-b-black/10 py-4">
<span>已用:</span>
<span>{formatFileSize(usedTotal)}</span>
</div>
<div className="text-base text-black/60 flex items-center justify-between w-[240px] border-b border-b-solid border-b-black/10 py-4">
<span>可用:</span>
<span>{formatFileSize(unusedTotal)}</span>
</div>
</div>
</div>
);
}

139
src/routes/(user)/index.tsx Normal file
View File

@@ -0,0 +1,139 @@
import { Progress } from "@/components/ui/progress";
import { createFileRoute } from "@tanstack/react-router";
import {
File,
FileExclamationPoint,
FileType,
FilePlay,
FileImage,
FileChartPie,
} from "lucide-react";
import { ChartPieDonutText } from "./-components/ChartPieDonutText";
import { useQuery } from "@tanstack/react-query";
import { getStatistics } from "@/apis/file";
import { useMemo } from "react";
import { formatFileSize } from "@/lib/utils";
export const Route = createFileRoute("/(user)/")({
component: Index,
});
const categorys = [
{
key: "image",
name: "图片",
icon: <FileImage />,
color: "hsl(var(--chart-1))",
},
{
key: "video",
name: "视频",
icon: <FilePlay />,
color: "hsl(var(--chart-2))",
},
{
key: "document",
name: "文档",
icon: <FileType />,
color: "hsl(var(--chart-3))",
},
{
key: "other",
name: "其他",
icon: <File />,
color: "hsl(var(--chart-4))",
},
{
key: "unknown",
name: "未知",
icon: <FileExclamationPoint />,
color: "hsl(var(--chart-5))",
},
{
key: "unused",
name: "未使用",
icon: <FileChartPie />,
color: "hsl(var(--muted))",
},
];
const getCategory = (value: string) => {
return categorys.find((item) => item.key === value);
};
function Index() {
const { data } = useQuery<any[]>({
queryKey: ["getStatistics"],
queryFn: () =>
getStatistics().then((res: any) =>
res.data?.map((item: any) => ({
...item,
fileCategory: item.fileCategory ?? "unknown",
})),
),
});
const statisticsData = useMemo(() => {
if (!data?.length) {
return [];
}
const total = data.reduce((count, current) => count + current.totalSize, 0);
return data.map((item: any) => {
return {
...item,
...getCategory(item.fileCategory),
sizeString: formatFileSize(item.totalSize),
proportion: Math.round((item.totalSize / total) * 100),
fill: `var(--color-${item.fileCategory})`,
};
});
}, [data]);
return (
<div className="p-4 min-h-full">
<div>
<div className="text-lg">首页</div>
<div className="text-xs text-black/50">
欢迎回来!这里是您的个人控制台
</div>
</div>
<div className="mt-4 p-8 rounded-lg border border-solid border-black/10 bg-white">
{!!statisticsData?.length ? (
<div className="flex gap-2">
<div className="flex-auto">
<ChartPieDonutText categorys={categorys} data={statisticsData} />
</div>
<div className="flex-auto">
<div>文件类型分布</div>
<div className="mt-4">
{statisticsData?.map((item: any) => (
<div
key={item.fileCategory}
className="flex gap-4 items-center p-4 mb-2 last:mb-0 rounded-xl border border-solid border-black/10"
>
<div className="flex-none w-10 h-10 rounded-full bg-primary flex items-center justify-center text-white">
{item.icon}
</div>
<div className="flex-auto min-w-[100px]">
<div>{item.name}</div>
<div className="text-xs text-black/50">
{item.sizeString}({item.proportion}%)
</div>
</div>
<div className="flex-auto w-full">
<Progress value={item.proportion} />
</div>
</div>
))}
</div>
</div>
</div>
) : (
<div className="flex items-center justify-center py-10">
<div className="text-sm text-muted-foreground">暂无数据</div>
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,234 @@
import { createFileRoute } from "@tanstack/react-router";
import { File, Folder, FolderInput } from "lucide-react";
import { downloadFile, FileStatus, FileType, RootType } from "@/apis/file";
import { FileStatusBadge } from "@/components/file-status-badge";
import { formatFileSize } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { DirectoryBreadcrumb } from "@/components/directory-breadcrumb";
import { DataTable } from "@/components/data-table";
import { Pagination } from "@/components/pagination";
import { useFetchFiles } from "@/hooks/use-fetch-files";
import { useMemo, useState } from "react";
import { MoveFileDialog } from "@/components/move-file-dialog";
import { RemoveFileDialog } from "@/components/remove-file-dialog";
import { FilePreviewDialog } from "@/components/file-preview-dialog";
import { useFileCategoryName } from "@/hooks/use-file-category-name";
import { FileCategoryFilter } from "@/components/file-category-filter";
export const Route = createFileRoute("/(user)/inside/")({
component: RouteComponent,
});
export function useColumns({
handleChangeParentId,
handleMove,
handleRemove,
handleFilePreview,
}: any) {
return [
{
accessorKey: "fileName",
header: "文件名",
cell: ({ row }: any) => (
<div
className="flex items-center gap-1 break-all cursor-pointer hover:underline hover:text-primary group"
onClick={() => {
if (row?.original?.fileType === FileType.DIRECTORY) {
handleChangeParentId(row?.original);
} else {
handleFilePreview(row?.original);
}
}}
>
{row?.original?.fileType === FileType.FILE ? (
<>
<File size={18} className="text-primary" />
</>
) : (
<>
<Folder size={18} className="text-amber-500 group-hover:hidden" />
<FolderInput
size={18}
className="text-amber-500 group-hover:block hidden"
/>
</>
)}
<span>{row.getValue("fileName")}</span>
</div>
),
},
{
accessorKey: "createTime",
header: "创建日期",
cell: ({ row }: any) => <div>{row.getValue("createTime")}</div>,
},
{
accessorKey: "fileSize",
header: "文件大小",
cell: ({ row }: any) => (
<div>{formatFileSize(row.getValue("fileSize"))}</div>
),
},
{
accessorKey: "fileCategory",
header: "文件种类",
cell: ({ row }: any) => {
return (
<div>
{row.original.fileType === FileType.FILE
? useFileCategoryName(row.getValue("fileCategory"))
: "-"}
</div>
);
},
},
{
accessorKey: "fileStatus",
header: () => <div className="text-center">状态</div>,
cell: ({ row }: any) => (
<div className="text-center">
<FileStatusBadge status={row.original.fileStatus} />
</div>
),
},
{
id: "actions",
enableHiding: false,
header: "操作",
cell: ({ row }: any) => {
const record = row.original;
return (
<div className="space-x-2">
<Button
size="sm"
variant="destructive"
onClick={() => handleRemove(row.original)}
>
删除
</Button>
<Button
size="sm"
variant="outline"
onClick={() => handleMove(row.original)}
>
移动
</Button>
{record.fileType === FileType.FILE && (
<Button
variant="outline"
size="sm"
onClick={() => {
downloadFile({ code: record.fileCode });
}}
>
下载
</Button>
)}
</div>
);
},
},
];
}
const isInside = import.meta.env.VITE_IS_INSIDE === "true";
function RouteComponent() {
// 当前选中数据
const [currentEntity, setCurrentEntity] = useState(null);
// 移动文件
const [openMoveFileDialog, setOpenMoveFileDialog] = useState(false);
const handleMove = (record?: any) => {
setCurrentEntity(record);
setOpenMoveFileDialog(true);
};
// 删除文件
const [openRemoveFileDialog, setOpenRemoveFileDialog] = useState(false);
const handleRemove = (record?: any) => {
setCurrentEntity(record);
setOpenRemoveFileDialog(true);
};
// 文件预览
const [openFilePreviewDialog, setOpenFilePreviewDialog] = useState(false);
const handleFilePreview = (record?: any) => {
setCurrentEntity(record);
setOpenFilePreviewDialog(true);
};
const [fileCategory, setFileCategory] = useState("all");
const params = useMemo(() => {
return {
rootType: RootType.INSIDE,
fileStatusIn: [
FileStatus.VALID,
FileStatus.PARSING,
FileStatus.TRANSFERING,
FileStatus.FAILED,
].join(","),
fileCategory: fileCategory === "all" ? undefined : fileCategory,
};
}, [fileCategory]);
const { openDirectorys, changeOpenDirectorys, table, query, reset } =
useFetchFiles({
useColumns: (handleChangeParentId: any) =>
useColumns({
handleChangeParentId,
handleMove,
handleRemove,
handleFilePreview,
}),
queryKey: ["insideFiles"],
params,
});
return (
<>
<MoveFileDialog
open={openMoveFileDialog}
setOpen={setOpenMoveFileDialog}
data={currentEntity}
params={params}
refetch={query.refetch}
/>
<RemoveFileDialog
open={openRemoveFileDialog}
setOpen={setOpenRemoveFileDialog}
data={currentEntity}
refetch={query.refetch}
/>
<FilePreviewDialog
open={openFilePreviewDialog}
setOpen={setOpenFilePreviewDialog}
data={currentEntity}
/>
<div className="p-4 box-border min-h-full space-y-4">
<div>
<div className="text-lg">{isInside ? "我的发送" : "我的接收"}</div>
<div className="text-xs text-black/50">文件传输的状态</div>
</div>
<div className="flex items-center gap-2">
<FileCategoryFilter
fileCategory={fileCategory}
setFileCategory={setFileCategory}
reset={reset}
/>
</div>
<div className="p-4 rounded-lg border bg-white space-y-2">
<DirectoryBreadcrumb
directorys={openDirectorys}
onChangeDirectorys={changeOpenDirectorys}
/>
<div className="relative overflow-hidden">
<DataTable table={table} query={query} />
<Pagination
table={table}
className="justify-end p-2 sticky bottom-0 left-0 right-0 z-10 bg-white"
/>
</div>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,171 @@
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useCallback } from "react";
import { ErrorCode, useDropzone } from "react-dropzone";
import { Upload } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
import { toast } from "sonner";
import { useMutation } from "@tanstack/react-query";
import { FileType, createFile, uploadFile } from "@/apis/file";
import { checkUploadConfig } from "@/apis/upload-config";
import { toAccept, toMaxSize, useUploadConfig } from "@/hooks/use-upload-config";
type CreateFileDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
data?: any;
parentId?: number;
refetch?: () => void;
};
// 机构未限制类型时沿用的可选类型
const DEFAULT_ACCEPT =
".docx,.txt,.md,.mdx,.markdown,.pdf,.html,.xlsx,.csv,.pptx,.xml,.epub,.mp3,.m4a,.wav,.amr,.mpga,.mp4,.mov,.mpeg,.webm,.jpg,.jpeg,.png,.gif,.svg";
// 未配置机构大小上限时的默认限制(MB)
const DEFAULT_MAX_SIZE_MB = 50;
export function CreateFileDialog({
open,
setOpen,
parentId,
refetch,
}: CreateFileDialogProps) {
const { data: uploadConfig } = useUploadConfig();
// 机构关闭上传
const uploadDisabled = !!uploadConfig && uploadConfig.uploadEnabled === false;
// 机构限制类型时的可选后缀
const allowedSuffixes = uploadConfig?.allowAllType
? null
: uploadConfig?.allowedSuffixes || null;
const accept = toAccept(uploadConfig) ?? DEFAULT_ACCEPT;
const maxSizeMB =
uploadConfig?.maxFileSize && uploadConfig.maxFileSize > 0
? uploadConfig.maxFileSize
: DEFAULT_MAX_SIZE_MB;
const maxSize = toMaxSize(uploadConfig) ?? DEFAULT_MAX_SIZE_MB * 1024 * 1024;
const { mutateAsync, isPending } = useMutation({
mutationFn: (file: any) =>
uploadFile(file).then((res: any) =>
createFile({
fileCode: res.data?.fileCode,
fileName: res.data?.fileName,
fileType: FileType.FILE,
parentId,
}),
),
});
const onDropAccepted = useCallback((files: any) => {
Promise.allSettled(
files.map(async (file: any) => {
try {
// 上传预检:机构策略不通过时跳过该文件(原因由统一拦截器提示)
if (uploadConfig?.configured) {
await checkUploadConfig({
fileName: file.name,
fileSize: file.size,
});
}
} catch {
return null;
}
return mutateAsync(file);
}),
).then((results) => {
const uploaded = results.filter(
(item) => item.status === "fulfilled" && item.value,
).length;
if (uploaded > 0) {
toast.success("上传完成");
refetch?.();
setOpen(false);
}
});
}, []);
const onDropRejected = useCallback((files: any) => {
const error = files[0].errors[0];
if (error.code === ErrorCode.FileTooLarge) {
toast.error(`超过单个文件最大限制(单个最大${maxSizeMB}MB)`);
return;
}
if (error.code === ErrorCode.TooManyFiles) {
toast.error("超过最大文件数量限制(最大100个)");
return;
}
toast.error("文件上传失败");
}, []);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDropAccepted,
onDropRejected,
maxFiles: 100,
minSize: 1,
maxSize,
disabled: isPending || uploadDisabled,
multiple: true,
});
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[520px]">
<DialogHeader>
<DialogTitle>上传文件</DialogTitle>
</DialogHeader>
<div
className={`relative border border-dashed rounded-lg text-center transition-colors overflow-hidden
${
uploadDisabled
? "border-muted-foreground/25 opacity-60"
: "cursor-pointer hover:border-primary"
}
${
isDragActive
? "border-primary bg-primary/5"
: "border-muted-foreground/25"
}`}
>
{isPending && (
<div className="absolute left-0 right-0 top-0 bottom-0 flex items-center justify-center backdrop-blur-xs bg-white/80 z-50">
<Spinner className="h-12 w-12 text-primary" />
</div>
)}
<div {...getRootProps()} className="p-8 rounded-lg outline-none">
<input
{...getInputProps({
accept,
})}
/>
<div className="p-4 rounded-full bg-gray-50 inline-flex justify-center items-center">
<Upload className="mx-auto h-6 w-6 text-muted-foreground" />
</div>
<p className="mt-2 text-lg">
{uploadDisabled
? "当前机构已禁止上传文件"
: isDragActive
? "松开鼠标以选择文件"
: "拖放文件到这里,或点击选择"}
</p>
{uploadDisabled ? (
<p className="mt-2 text-sm text-black/50">
请联系机构管理员开启上传权限
</p>
) : (
<p className="mt-2 text-sm text-black/50">
{allowedSuffixes?.length
? `仅允许上传后缀为 ${allowedSuffixes.join("、")} 的文件,`
: ""}
文件最大不能超过{maxSizeMB}MB
</p>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,127 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
FormField,
FormItem,
FormControl,
FormMessage,
Form,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Spinner } from "@/components/ui/spinner";
import { useEffect } from "react";
import { useSaveFile } from "../-hooks/useSaveFile";
import { FileType } from "@/apis/file";
const formSchema = z.object({
fileName: z
.string()
.min(1, {
message: "目录至少1个字符",
})
.max(32, {
message: "目录最多32个字符",
})
.nonempty({
message: "目录不能为空",
}),
});
type EditFileDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
data?: any;
parentId?: number;
refetch?: () => void;
};
export function EditFileDialog({
open,
setOpen,
data,
parentId,
refetch,
}: EditFileDialogProps) {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
fileName: "",
},
});
const { save, saveIsPending } = useSaveFile({
onSuccess: () => {
refetch?.();
setOpen(false);
},
});
const onSubmit = (values: z.infer<typeof formSchema>) => {
save({
...(data || {}),
...values,
parentId,
});
};
useEffect(() => {
if (open) {
form.reset({ fileName: data?.fileName || "" });
}
}, [open, data]);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[400px]">
<DialogHeader>
<DialogTitle>
{data?.fileType === FileType.DIRECTORY && !data?.id
? "创建目录"
: "重命名"}
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="fileName"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
placeholder={
data?.fileType === FileType.DIRECTORY
? "请输入目录名"
: "请输入文件名"
}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">取消</Button>
</DialogClose>
<Button type="submit" disabled={saveIsPending}>
{saveIsPending && <Spinner />}确定
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,130 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
FormField,
FormItem,
FormControl,
FormMessage,
Form,
} from "@/components/ui/form";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Spinner } from "@/components/ui/spinner";
import { useEffect } from "react";
import { useShareFile } from "../-hooks/useShareFile";
import { Label } from "@/components/ui/label";
import { Folder, File } from "lucide-react";
import { FileType } from "@/apis/file";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
const formSchema = z.object({
validDays: z.number().or(z.string()),
});
type ShareDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
data?: any;
};
export function ShareDialog({ open, setOpen, data }: ShareDialogProps) {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
validDays: 1,
},
});
const { share, shareIsPending } = useShareFile({
onSuccess: () => {
setOpen(false);
},
});
const onSubmit = (values: z.infer<typeof formSchema>) => {
share({
userFileId: data.id,
validDays: values.validDays,
});
};
useEffect(() => {
if (open) {
form.reset();
}
}, [open, data]);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[400px]">
<DialogHeader>
<DialogTitle>分享文件</DialogTitle>
</DialogHeader>
<div className="mt-1 flex items-center gap-1 text-sm p-2 rounded-md bg-gray-50">
{data?.fileType === FileType.FILE ? (
<File size={16} className="text-primary flex-none" />
) : (
<Folder size={16} className="text-amber-500 flex-none" />
)}
<span className="break-all">{data?.fileName}</span>
</div>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="validDays"
render={({ field }) => (
<FormItem>
<Label>有效期</Label>
<FormControl>
<Select
onValueChange={field.onChange}
value={field.value.toString()}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="请选择有效期" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="1">1天</SelectItem>
<SelectItem value="3">3天</SelectItem>
<SelectItem value="5">5天</SelectItem>
<SelectItem value="7">7天</SelectItem>
<SelectItem value="15">15天</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">取消</Button>
</DialogClose>
<Button type="submit" disabled={shareIsPending}>
{shareIsPending && <Spinner />}确定
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,67 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner";
import { Folder, File } from "lucide-react";
import { useTransferFile } from "../-hooks/useTransferFile";
import { FileType } from "@/apis/file";
type TransferConfirmDialogProps = {
open: boolean;
setOpen: (open: boolean) => void;
data?: any;
};
const isInside = import.meta.env.VITE_IS_INSIDE === "true";
export function TransferConfirmDialog({
open,
setOpen,
data,
}: TransferConfirmDialogProps) {
const { transfer, transferIsPending } = useTransferFile({
onSuccess() {
setOpen(false);
},
});
const onSubmit = () => {
transfer({ userFileId: data?.id });
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-[400px]">
<DialogHeader>
<DialogTitle>
您确定要传输该{data?.fileType === FileType.FILE ? "文件" : "目录"}到
{isInside ? "外网" : "内网"}?
</DialogTitle>
<div className="mt-1 flex items-center gap-1 text-sm p-2 rounded-md bg-gray-50">
{data?.fileType === FileType.FILE ? (
<File size={16} className="text-primary flex-none" />
) : (
<Folder size={16} className="text-amber-500 flex-none" />
)}
<span className="break-all">{data?.fileName}</span>
</div>
</DialogHeader>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">取消</Button>
</DialogClose>
<Button type="submit" disabled={transferIsPending} onClick={onSubmit}>
{transferIsPending && <Spinner />}确定
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,28 @@
import { useMutation } from "@tanstack/react-query";
import { modifyFile, createFile } from "@/apis/file";
import { toast } from "sonner";
export const useSaveFile = (mutationOptions?: any) => {
const { mutateAsync: saveMutateAsync, isPending: saveIsPending } =
useMutation({
mutationFn: (values: any) => {
if (values.id) {
return modifyFile(values);
}
return createFile(values);
},
...(mutationOptions || {}),
});
const save = (values: any) => {
toast.promise(saveMutateAsync(values), {
loading: "提交中...",
success: "操作成功",
});
};
return {
save,
saveIsPending,
};
};

View File

@@ -0,0 +1,23 @@
import { useMutation } from "@tanstack/react-query";
import { createShare } from "@/apis/file";
import { toast } from "sonner";
export const useShareFile = (mutationOptions?: any) => {
const { mutateAsync: shareMutateAsync, isPending: shareIsPending } =
useMutation({
mutationFn: createShare,
...(mutationOptions || {}),
});
const share = (values: any) => {
toast.promise(shareMutateAsync(values), {
loading: "提交中...",
success: "操作成功",
});
};
return {
share,
shareIsPending,
};
};

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