feat: opsx-loki 全面升级 — 前端重构/用户与LDAP/部署向导/日志查询
基于 WEB-UI-Development-Guide 标准的整体升级,并更名 LokiDeploy → opsx-loki。 前端(Gin+React+shadcn/ui): - 按 02/07 章重构:页面域化拆分(无超 400 行文件)、PageContainer/ListQuery、 反馈分级(成功静默/失败 toast/危险确认)、401 单飞刷新+队列重放 - 暗色模式(next-themes)+ 语义 Token(--primary 品牌色/success/warning/info) - 部署向导(状态推导四步:环境→存储→Loki→采集,内嵌表单闭环) - 日志查询页:LogQL 标签构建器/拖拽直方图/日志上下文/Live Tail/查询历史 - 按用户+标签策略的查询授权(服务端强制合并策略) 后端(Go+Gin+JSON DB): - 简单用户管理(仅 admin,无 RBAC)+ TokenVersion 会话吊销 + 登录 IP 限流 - LDAP 接入:配置(AES 加密存储/hasPassword 脱敏)/测试连接/批量导入/登录 - 存储配置测试连接(SigV4 零依赖)+ 桶不存在自动创建 - Loki 三模式部署修复:SSH 密钥认证、3.x 配置模板、ruler 对象存储嵌套块、 凭证解密、孤儿 deploying 状态恢复、Grafana 部署(可选默认关)+面板导入 - DaemonSet 采集纯 YAML(去 helm 依赖)+ DNS 自愈回退 ClusterIP + 集群名标签 - 日志查询代理:cluster-svc 经 kube-apiserver proxy/url 直连 + cursor 翻页 - 统一 log 命名空间;部署就绪探活;Grafana 访问地址自动记录 修复:run.sh 增量编译检测、Sanitized 脱敏补全、LokiDeployment Update 白名单、 健康检查 CreatedAt 零值等 10+ 存量 bug。 数据兼容:DB 沿用旧 lokideploy.json(新名优先);localStorage 一次性迁移; HKDF 加密前缀保留(已加密凭证不受影响)。
This commit is contained in:
1 parent
327e282356
commit
f9c6c1d826
204 files changed
+14107
-9103
No files matched your search
@@ -1,42 +0,0 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
+32
-50
@@ -1,75 +1,58 @@
|
||||
import { lazy, Suspense, memo } from 'react'
|
||||
import { Routes, Route, Navigate } from 'react-router'
|
||||
import { lazy, Suspense, memo, useEffect } from 'react'
|
||||
import { Routes, Route, Navigate, useLocation } from 'react-router'
|
||||
import { Toaster } from '@/components/ui/sonner'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { isLoggedIn, getUser } from '@/lib/auth-storage'
|
||||
import { routes, findRouteMeta } from '@/router/routes'
|
||||
|
||||
// 路由守卫组件 - 独立定义,便于复用
|
||||
const Layout = lazy(() => import('@/components/Layout'))
|
||||
|
||||
// 路由守卫 - 未登录跳登录页并携带来源路径(登录成功后回跳,见 lib/redirect.ts)
|
||||
const RequireAuth = memo(function RequireAuth({ children }: { children: React.ReactNode }) {
|
||||
const token = localStorage.getItem('token')
|
||||
if (!token) {
|
||||
return <Navigate to="/login" replace />
|
||||
const location = useLocation()
|
||||
if (!isLoggedIn()) {
|
||||
const from = location.pathname + location.search
|
||||
return <Navigate to={`/login?redirect=${encodeURIComponent(from)}`} replace />
|
||||
}
|
||||
if (getUser()?.role !== 'admin' && location.pathname !== '/logs') return <Navigate to="/logs" replace />
|
||||
// 动态导入Layout以避免在登录页面加载它
|
||||
return <LazyLayout>{children}</LazyLayout>
|
||||
})
|
||||
|
||||
// 懒加载页面组件 - 实现代码分割
|
||||
const Login = lazy(() => import('@/pages/Login'))
|
||||
const Dashboard = lazy(() => import('@/pages/Dashboard'))
|
||||
const Clusters = lazy(() => import('@/pages/Clusters'))
|
||||
const Hosts = lazy(() => import('@/pages/Hosts'))
|
||||
const Storage = lazy(() => import('@/pages/Storage'))
|
||||
const Deployments = lazy(() => import('@/pages/Deployments'))
|
||||
const Collectors = lazy(() => import('@/pages/Collectors'))
|
||||
const Settings = lazy(() => import('@/pages/Settings'))
|
||||
const Layout = lazy(() => import('@/components/Layout'))
|
||||
|
||||
// 懒加载布局包装器
|
||||
// 懒加载布局包装器(Layout chunk 加载期间的整屏占位)
|
||||
function LazyLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<Suspense fallback={<PageLoadingFallback />}>
|
||||
<Suspense fallback={<AppLoadingFallback />}>
|
||||
<Layout>{children}</Layout>
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
// 页面加载中占位
|
||||
function PageLoadingFallback() {
|
||||
// 整屏加载占位
|
||||
function AppLoadingFallback() {
|
||||
return (
|
||||
<div className="h-screen w-screen flex items-center justify-center bg-slate-50 dark:bg-slate-950">
|
||||
<LoadingSpinner size="lg" text="页面加载中..." />
|
||||
<div className="h-screen w-screen flex items-center justify-center bg-muted dark:bg-slate-950">
|
||||
<div className="w-6 h-6 border-2 border-slate-300 border-t-primary rounded-full animate-spin" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 路由配置 - 集中管理路由定义
|
||||
interface RouteConfig {
|
||||
path: string
|
||||
element: React.ReactNode
|
||||
auth?: boolean
|
||||
// document.title 由路由 meta 单源驱动
|
||||
function useDocumentTitle() {
|
||||
const location = useLocation()
|
||||
useEffect(() => {
|
||||
const title = findRouteMeta(location.pathname)?.title
|
||||
document.title = title && location.pathname !== '/login' ? `${title} · opsx-loki` : 'opsx-loki'
|
||||
}, [location.pathname])
|
||||
}
|
||||
|
||||
const routes: RouteConfig[] = [
|
||||
{ path: '/login', element: <Login />, auth: false },
|
||||
{ path: '/', element: <Dashboard />, auth: true },
|
||||
{ path: '/clusters', element: <Clusters />, auth: true },
|
||||
{ path: '/hosts', element: <Hosts />, auth: true },
|
||||
{ path: '/storage', element: <Storage />, auth: true },
|
||||
{ path: '/deployments', element: <Deployments />, auth: true },
|
||||
{ path: '/collectors', element: <Collectors />, auth: true },
|
||||
{ path: '/settings', element: <Settings />, auth: true },
|
||||
]
|
||||
|
||||
/**
|
||||
* App 根组件
|
||||
*
|
||||
* 优化点:
|
||||
* 1. 所有页面使用 React.lazy 懒加载,实现代码分割
|
||||
* 2. 路由守卫独立为 memo 组件
|
||||
* 3. Suspense 统一处理加载状态
|
||||
* 4. 路由配置集中管理
|
||||
* - 路由配置集中在 router/routes.tsx(meta 驱动标题/菜单)
|
||||
* - 页面全部 React.lazy 懒加载实现代码分割
|
||||
* - 页面级 Suspense 在 Layout 的内容区,切换页面时布局不闪
|
||||
*/
|
||||
const App = memo(function App() {
|
||||
useDocumentTitle()
|
||||
return (
|
||||
<>
|
||||
<Routes>
|
||||
@@ -79,16 +62,15 @@ const App = memo(function App() {
|
||||
path={route.path}
|
||||
element={
|
||||
route.auth ? (
|
||||
<RequireAuth>{route.element}</RequireAuth>
|
||||
<RequireAuth>{<route.component />}</RequireAuth>
|
||||
) : (
|
||||
<Suspense fallback={<PageLoadingFallback />}>
|
||||
{route.element}
|
||||
<Suspense fallback={<AppLoadingFallback />}>
|
||||
<route.component />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
<Toaster />
|
||||
</>
|
||||
|
||||
@@ -11,19 +11,16 @@ export interface LoginResponse {
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
// silent:错误密码返回 401 时不触发全局清凭证/跳登录
|
||||
login: (username: string, password: string) =>
|
||||
http.post<LoginResponse>('/auth/login', { username, password }),
|
||||
|
||||
register: (username: string, password: string, nickname: string, role?: string) =>
|
||||
http.post<User>('/auth/register', {
|
||||
username,
|
||||
password,
|
||||
nickname,
|
||||
role: role || 'user',
|
||||
}),
|
||||
http.post<LoginResponse>('/auth/login', { username, password }, { silent: true }),
|
||||
|
||||
getCurrentUser: () => http.get<User>('/auth/user'),
|
||||
|
||||
changePassword: (oldPassword: string, newPassword: string) =>
|
||||
http.post<{ message: string }>('/auth/password', { oldPassword, newPassword }),
|
||||
|
||||
// 后端探活(登录页检测 API 服务是否可达);short timeout + silent
|
||||
health: () =>
|
||||
http.get<{ status: string }>('/health', { timeout: 3000, silent: true }),
|
||||
};
|
||||
@@ -1,19 +1,28 @@
|
||||
// 集群域 API
|
||||
import { http } from '../http';
|
||||
import { http, buildQuery, type ListParams, type RequestOptions } from '../http';
|
||||
import type { PageData, Cluster, ClusterInfo } from '@/types';
|
||||
|
||||
export interface ClusterCreateInput {
|
||||
name: string;
|
||||
description?: string;
|
||||
configType?: string;
|
||||
apiServer?: string;
|
||||
kubeconfig?: string;
|
||||
token?: string;
|
||||
context?: string;
|
||||
}
|
||||
|
||||
export type ClusterUpdateInput = Partial<ClusterCreateInput>;
|
||||
|
||||
export const clusterApi = {
|
||||
list: (page = 1, pageSize = 10) =>
|
||||
http.get<PageData<Cluster>>(`/clusters?page=${page}&pageSize=${pageSize}`),
|
||||
list: (params: ListParams = {}, options?: RequestOptions) =>
|
||||
http.get<PageData<Cluster>>(`/clusters${buildQuery(params)}`, options),
|
||||
|
||||
get: (id: number) => http.get<Cluster>(`/clusters/${id}`),
|
||||
|
||||
create: (data: {
|
||||
name: string; description?: string; configType?: string;
|
||||
apiServer?: string; kubeconfig?: string; token?: string; context?: string;
|
||||
}) => http.post<Cluster>('/clusters', data),
|
||||
create: (data: ClusterCreateInput) => http.post<Cluster>('/clusters', data),
|
||||
|
||||
update: (id: number, data: Record<string, unknown>) =>
|
||||
update: (id: number, data: ClusterUpdateInput) =>
|
||||
http.put<{ message: string }>(`/clusters/${id}`, data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/clusters/${id}`),
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// 采集器域 API
|
||||
import { http } from '../http';
|
||||
import { http, buildQuery, type ListParams, type RequestOptions } from '../http';
|
||||
import type { PageData, Collector, CreateCollectorRequest } from '@/types';
|
||||
|
||||
export const collectorApi = {
|
||||
list: (page = 1, pageSize = 100) =>
|
||||
http.get<PageData<Collector>>(`/collectors?page=${page}&pageSize=${pageSize}`),
|
||||
list: (params: ListParams = {}, options?: RequestOptions) =>
|
||||
http.get<PageData<Collector>>(`/collectors${buildQuery(params)}`, options),
|
||||
|
||||
get: (id: number) => http.get<Collector>(`/collectors/${id}`),
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Loki 部署域 API
|
||||
import { http } from '../http';
|
||||
import { http, buildQuery, type ListParams, type RequestOptions } from '../http';
|
||||
import type {
|
||||
PageData,
|
||||
LokiDeployment,
|
||||
@@ -8,15 +8,17 @@ import type {
|
||||
CreateDeploymentRequest,
|
||||
} from '@/types';
|
||||
|
||||
export type DeploymentUpdateInput = Partial<CreateDeploymentRequest>;
|
||||
|
||||
export const deploymentApi = {
|
||||
list: (page = 1, pageSize = 10) =>
|
||||
http.get<PageData<LokiDeployment>>(`/deployments?page=${page}&pageSize=${pageSize}`),
|
||||
list: (params: ListParams = {}, options?: RequestOptions) =>
|
||||
http.get<PageData<LokiDeployment>>(`/deployments${buildQuery(params)}`, options),
|
||||
|
||||
get: (id: number) => http.get<LokiDeployment>(`/deployments/${id}`),
|
||||
|
||||
create: (data: CreateDeploymentRequest) => http.post<LokiDeployment>('/deployments', data),
|
||||
|
||||
update: (id: number, data: Record<string, unknown>) =>
|
||||
update: (id: number, data: DeploymentUpdateInput) =>
|
||||
http.put<{ message: string }>(`/deployments/${id}`, data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/deployments/${id}`),
|
||||
@@ -27,10 +29,37 @@ export const deploymentApi = {
|
||||
|
||||
restart: (id: number) => http.post<{ message: string }>(`/deployments/${id}/restart`),
|
||||
|
||||
logs: (id: number, page = 1, pageSize = 50) =>
|
||||
logs: (id: number, params: ListParams = {}) =>
|
||||
http.get<PageData<DeploymentLog>>(
|
||||
`/deployments/${id}/logs?page=${page}&pageSize=${pageSize}`
|
||||
`/deployments/${id}/logs${buildQuery({ page: 1, pageSize: 50, ...params })}`
|
||||
),
|
||||
|
||||
stats: () => http.get<DashboardStats>('/deployments/stats'),
|
||||
|
||||
// 部署就绪探测(经自动注册数据源访问 Loki /ready)
|
||||
ready: (id: number) => http.get<{ ready: boolean; message: string }>(`/deployments/${id}/ready`),
|
||||
|
||||
// 支持的 Loki 版本列表(部署表单版本下拉数据源)
|
||||
versions: () => http.get<{ versions: string[] }>('/deployments/versions'),
|
||||
|
||||
// 向导预检:聚合存储/集群/主机/Loki/采集器状态(状态推导式向导数据源)
|
||||
preflight: () =>
|
||||
http.get<{
|
||||
hasStorage: boolean
|
||||
defaultStorage: string
|
||||
hasActiveCluster: boolean
|
||||
clusterNames: string[]
|
||||
hasActiveHost: boolean
|
||||
hostNames: string[]
|
||||
runningLoki: null | {
|
||||
id: number
|
||||
name: string
|
||||
mode: string
|
||||
endpoint: string
|
||||
namespace: string
|
||||
grafana: boolean
|
||||
}
|
||||
activeCollectors: number
|
||||
grafanaReady: boolean
|
||||
}>('/deployments/preflight'),
|
||||
};
|
||||
@@ -1,20 +1,32 @@
|
||||
// 主机域 API
|
||||
import { http } from '../http';
|
||||
import { http, buildQuery, type ListParams, type RequestOptions } from '../http';
|
||||
import type { PageData, Host, HostInfo } from '@/types';
|
||||
|
||||
export interface HostCreateInput {
|
||||
name: string;
|
||||
hostIP: string;
|
||||
port?: number;
|
||||
user: string;
|
||||
authType: 'password' | 'key';
|
||||
password?: string;
|
||||
privateKey?: string;
|
||||
keyPhrase?: string;
|
||||
os?: string;
|
||||
arch?: string;
|
||||
labels?: string;
|
||||
}
|
||||
|
||||
export type HostUpdateInput = Partial<HostCreateInput>;
|
||||
|
||||
export const hostApi = {
|
||||
list: (page = 1, pageSize = 10) =>
|
||||
http.get<PageData<Host>>(`/hosts?page=${page}&pageSize=${pageSize}`),
|
||||
list: (params: ListParams = {}, options?: RequestOptions) =>
|
||||
http.get<PageData<Host>>(`/hosts${buildQuery(params)}`, options),
|
||||
|
||||
get: (id: number) => http.get<Host>(`/hosts/${id}`),
|
||||
|
||||
create: (data: {
|
||||
name: string; hostIP: string; port?: number; user: string;
|
||||
authType: 'password' | 'key'; password?: string; privateKey?: string;
|
||||
keyPhrase?: string; os?: string; arch?: string; labels?: string;
|
||||
}) => http.post<Host>('/hosts', data),
|
||||
create: (data: HostCreateInput) => http.post<Host>('/hosts', data),
|
||||
|
||||
update: (id: number, data: Record<string, unknown>) =>
|
||||
update: (id: number, data: HostUpdateInput) =>
|
||||
http.put<{ message: string }>(`/hosts/${id}`, data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/hosts/${id}`),
|
||||
|
||||
+179
-103
@@ -1,51 +1,108 @@
|
||||
// HTTP 请求引擎 — 统一的 fetch 封装,提供 request<T> 与 http.get/post/put/delete 两种用法。
|
||||
// 参考 aiops 的 @/utils/request 模式:超时/取消、token 注入、401 自动登出、统一错误处理。
|
||||
// HTTP 请求引擎 — 统一 fetch 封装:超时/取消、token 注入、结构化错误、
|
||||
// 401 单飞刷新 + 队列重放(见开发标准 03 章)。组件一律通过 api 层调用,禁止直接 fetch。
|
||||
import type { ApiResponse } from '@/types';
|
||||
import {
|
||||
getAccessToken,
|
||||
getRefreshToken,
|
||||
saveTokenPair,
|
||||
clearAuth,
|
||||
} from '@/lib/auth-storage';
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_URL || '';
|
||||
const DEFAULT_TIMEOUT = 30000; // 30秒默认超时
|
||||
const DEFAULT_TIMEOUT = 30000; // 30 秒默认超时
|
||||
const REFRESH_TIMEOUT = 10000; // 刷新 token 接口独立超时
|
||||
|
||||
function getToken(): string | null {
|
||||
return localStorage.getItem('token');
|
||||
/** 结构化 API 错误:status 为 HTTP 状态码(网络/超时等非 HTTP 错误为 0),code 为后端业务码 */
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
readonly code?: number;
|
||||
|
||||
constructor(message: string, status = 0, code?: number) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions extends RequestInit {
|
||||
export interface RequestOptions extends RequestInit {
|
||||
timeout?: number;
|
||||
signal?: AbortSignal;
|
||||
/** 静默模式:401 失效不触发清凭证/跳登录的全局副作用,仅抛错(登录、轮询接口用) */
|
||||
silent?: boolean;
|
||||
/** 内部标记:刷新 token 后的重放请求,防止 401 无限循环 */
|
||||
retried?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 核心请求函数:带超时与取消支持,自动注入 Authorization,统一处理 401。
|
||||
*/
|
||||
export async function request<T>(
|
||||
url: string,
|
||||
options: RequestOptions = {}
|
||||
): Promise<T> {
|
||||
// —— 401 单飞刷新状态 ——
|
||||
// 并发 N 个 401 只触发一次刷新;刷新期间的请求进入队列,拿到新 token 后统一重放。
|
||||
let isRefreshing = false;
|
||||
let refreshQueue: Array<(token: string | null) => void> = [];
|
||||
|
||||
// 这些端点自身的 401 不触发登出跳转(错误密码、refresh 失效等场景)
|
||||
const AUTH_ENDPOINTS = ['/auth/login', '/auth/refresh'];
|
||||
|
||||
async function doRefresh(): Promise<string | null> {
|
||||
const refreshToken = getRefreshToken();
|
||||
if (!refreshToken) return null;
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), REFRESH_TIMEOUT);
|
||||
const response = await fetch(`${API_BASE}/api/v1/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timer);
|
||||
if (!response.ok) return null;
|
||||
const body = (await response.json()) as ApiResponse<{
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresAt: number;
|
||||
}>;
|
||||
if (body.code !== 0 || !body.data?.accessToken) return null;
|
||||
saveTokenPair(body.data);
|
||||
return body.data.accessToken;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let redirecting = false;
|
||||
|
||||
/** 清凭证并防抖跳转登录(并发失效只产生一次跳转,携带当前路径供回跳) */
|
||||
function redirectToLogin(): void {
|
||||
clearAuth();
|
||||
if (redirecting) return;
|
||||
redirecting = true;
|
||||
const current = window.location.pathname + window.location.search;
|
||||
const target =
|
||||
current.startsWith('/login')
|
||||
? '/login'
|
||||
: `/login?redirect=${encodeURIComponent(current)}`;
|
||||
window.location.href = target;
|
||||
}
|
||||
|
||||
/** 单次 HTTP 往返:组头、超时、取消、解包。401 以 ApiError(status=401) 抛出,由上层统一处理 */
|
||||
async function doRequest<T>(url: string, options: RequestOptions): Promise<T> {
|
||||
const { timeout = DEFAULT_TIMEOUT, signal, ...fetchOptions } = options;
|
||||
|
||||
const token = getToken();
|
||||
const token = getAccessToken();
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...((fetchOptions.headers as Record<string, string>) || {}),
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const fullUrl = `${API_BASE}/api/v1${url}`;
|
||||
|
||||
// 超时控制
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
// 外部 signal 联动
|
||||
const externalSignal = signal;
|
||||
const onExternalAbort = () => {
|
||||
controller.abort();
|
||||
};
|
||||
if (externalSignal) {
|
||||
externalSignal.addEventListener('abort', onExternalAbort);
|
||||
const onExternalAbort = () => controller.abort();
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', onExternalAbort);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -55,53 +112,109 @@ export async function request<T>(
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (response.status === 401) {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
window.location.href = '/login';
|
||||
throw new Error('Unauthorized');
|
||||
throw new ApiError('未授权或登录已过期', 401);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (!contentType || !contentType.includes('application/json')) {
|
||||
const text = await response.text();
|
||||
throw new Error(
|
||||
`Server returned non-JSON (${response.status}): ${text.substring(0, 200)}`
|
||||
throw new ApiError(
|
||||
`服务端返回了非 JSON 响应(${response.status}):${text.substring(0, 200)}`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ApiResponse<T>;
|
||||
if (data.code !== 0) {
|
||||
throw new Error(data.message || 'Request failed');
|
||||
const body: unknown = await response.json();
|
||||
// 多数接口走 {code, data, message} 包装;/health 等基础端点直接返回裸 JSON
|
||||
if (
|
||||
body !== null &&
|
||||
typeof body === 'object' &&
|
||||
'code' in body &&
|
||||
typeof (body as ApiResponse<T>).code === 'number'
|
||||
) {
|
||||
const data = body as ApiResponse<T>;
|
||||
if (data.code !== 0) {
|
||||
throw new ApiError(data.message || '请求失败', response.status, data.code);
|
||||
}
|
||||
return data.data;
|
||||
}
|
||||
return data.data;
|
||||
return body as T;
|
||||
} catch (err) {
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (err instanceof Error) {
|
||||
if (err.name === 'AbortError') {
|
||||
if (controller.signal.aborted && !externalSignal?.aborted) {
|
||||
throw new Error(`Request timeout after ${timeout}ms`);
|
||||
}
|
||||
throw new Error('Request was cancelled');
|
||||
}
|
||||
if (err instanceof TypeError && err.message.includes('fetch')) {
|
||||
throw new Error(
|
||||
'Cannot connect to backend server. Please ensure the API server is running.'
|
||||
);
|
||||
if (err instanceof ApiError) throw err;
|
||||
if (err instanceof Error && err.name === 'AbortError') {
|
||||
if (controller.signal.aborted && !signal?.aborted) {
|
||||
throw new ApiError(`请求超时(${timeout}ms)`);
|
||||
}
|
||||
throw new ApiError('请求已取消');
|
||||
}
|
||||
throw err;
|
||||
if (err instanceof TypeError) {
|
||||
throw new ApiError('无法连接到后端服务,请确认 API 服务已启动');
|
||||
}
|
||||
throw err instanceof Error ? new ApiError(err.message) : new ApiError(String(err));
|
||||
} finally {
|
||||
if (externalSignal) {
|
||||
externalSignal.removeEventListener('abort', onExternalAbort);
|
||||
clearTimeout(timeoutId);
|
||||
if (signal) {
|
||||
signal.removeEventListener('abort', onExternalAbort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 核心请求函数:在 doRequest 之上处理 401 —— 有 refreshToken 时单飞刷新并重放;
|
||||
* 刷新失败或无 refreshToken 时清凭证跳登录(silent 请求除外)。
|
||||
*/
|
||||
export async function request<T>(
|
||||
url: string,
|
||||
options: RequestOptions = {}
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await doRequest<T>(url, options);
|
||||
} catch (err) {
|
||||
if (!(err instanceof ApiError) || err.status !== 401) throw err;
|
||||
|
||||
// 静默请求 / 鉴权端点自身 / 已重放过:不再刷新、不再跳转,直接失败
|
||||
if (options.silent || options.retried || AUTH_ENDPOINTS.some((p) => url.startsWith(p))) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (!getRefreshToken()) {
|
||||
redirectToLogin();
|
||||
throw new ApiError('登录已过期,请重新登录', 401);
|
||||
}
|
||||
|
||||
// 已有刷新在进行中:挂入队列,等新 token 下发后重放本请求
|
||||
if (isRefreshing) {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
refreshQueue.push((token) => {
|
||||
if (!token) {
|
||||
reject(new ApiError('登录已过期,请重新登录', 401));
|
||||
return;
|
||||
}
|
||||
request<T>(url, { ...options, retried: true }).then(resolve, reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
isRefreshing = true;
|
||||
let newToken: string | null = null;
|
||||
try {
|
||||
newToken = await doRefresh();
|
||||
} finally {
|
||||
isRefreshing = false;
|
||||
const queue = refreshQueue;
|
||||
refreshQueue = [];
|
||||
queue.forEach((cb) => cb(newToken));
|
||||
}
|
||||
|
||||
if (!newToken) {
|
||||
redirectToLogin();
|
||||
throw new ApiError('登录已过期,请重新登录', 401);
|
||||
}
|
||||
return request<T>(url, { ...options, retried: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 语义化 HTTP 助手:自动处理 method 与 JSON 序列化,减少调用样板。
|
||||
* @example
|
||||
@@ -129,57 +242,20 @@ export const http = {
|
||||
request<T>(url, { ...options, method: 'DELETE' }),
|
||||
};
|
||||
|
||||
/**
|
||||
* 创建可取消的请求辅助函数
|
||||
*/
|
||||
export function createCancelableRequest() {
|
||||
const controller = new AbortController();
|
||||
|
||||
return {
|
||||
request: async <T>(url: string, options: Omit<RequestOptions, 'signal'> = {}) => {
|
||||
return request<T>(url, { ...options, signal: controller.signal });
|
||||
},
|
||||
cancel: () => controller.abort(),
|
||||
get signal() {
|
||||
return controller.signal;
|
||||
},
|
||||
};
|
||||
/** 列表查询参数(分页) */
|
||||
export interface ListParams {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 带自动重试的请求函数(不重试 401/取消/超时)
|
||||
*/
|
||||
export async function requestWithRetry<T>(
|
||||
url: string,
|
||||
options: RequestOptions = {},
|
||||
retries = 3,
|
||||
delay = 1000
|
||||
): Promise<T> {
|
||||
let lastError: Error | unknown;
|
||||
|
||||
for (let i = 0; i < retries; i++) {
|
||||
try {
|
||||
return await request<T>(url, options);
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
|
||||
if (err instanceof Error) {
|
||||
if (
|
||||
err.message === 'Unauthorized' ||
|
||||
err.message === 'Request was cancelled' ||
|
||||
err.message.startsWith('Request timeout')
|
||||
) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (i === retries - 1) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, delay * (i + 1)));
|
||||
/** 列表查询参数:统一编码拼接,避免模板字符串拼 query 无转义 */
|
||||
export function buildQuery(params: ListParams): string {
|
||||
const search = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value !== undefined && value !== '') {
|
||||
search.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
const qs = search.toString();
|
||||
return qs ? `?${qs}` : '';
|
||||
}
|
||||
@@ -7,3 +7,4 @@ export * from './host';
|
||||
export * from './storage';
|
||||
export * from './deployment';
|
||||
export * from './collector';
|
||||
export * from './user';
|
||||
@@ -0,0 +1,55 @@
|
||||
// LDAP 域 API — 配置(密码脱敏)/测试/用户预览/批量导入
|
||||
import { http } from '../http';
|
||||
|
||||
export interface LdapConfig {
|
||||
enabled: boolean
|
||||
host: string
|
||||
port: number
|
||||
useSSL: boolean
|
||||
bindDN: string
|
||||
bindPassword: string // 提交时传空 = 保留已存密码;响应恒为空
|
||||
baseDN: string
|
||||
userFilter: string
|
||||
usernameAttr: string
|
||||
nameAttr: string
|
||||
emailAttr: string
|
||||
// 仅响应
|
||||
hasPassword?: boolean
|
||||
configured?: boolean
|
||||
}
|
||||
|
||||
export interface LdapTestResult {
|
||||
success: boolean
|
||||
message: string
|
||||
userInfo?: { dn: string; username: string; displayName: string; email: string }
|
||||
}
|
||||
|
||||
export interface LdapUserPreview {
|
||||
dn: string
|
||||
username: string
|
||||
displayName: string
|
||||
email: string
|
||||
}
|
||||
|
||||
export interface LdapImportResult {
|
||||
successCount: number
|
||||
skippedCount: number
|
||||
updatedCount: number
|
||||
failedCount: number
|
||||
failedUsers: Array<{ username: string; error: string }>
|
||||
}
|
||||
|
||||
export const ldapApi = {
|
||||
getConfig: () => http.get<LdapConfig>('/settings/ldap'),
|
||||
|
||||
saveConfig: (data: LdapConfig) => http.put<LdapConfig>('/settings/ldap', data),
|
||||
|
||||
// 用表单参数测试(未保存也可测;密码空回退已存)
|
||||
test: (data: LdapConfig & { testUsername?: string; testPassword?: string }) =>
|
||||
http.post<LdapTestResult>('/settings/ldap/test', data),
|
||||
|
||||
listUsers: (ouDN?: string) => http.post<LdapUserPreview[]>('/settings/ldap/users', { ouDN: ouDN || '' }),
|
||||
|
||||
batchImport: (users: Array<{ dn: string; username: string; nickname: string; email: string }>) =>
|
||||
http.post<LdapImportResult>('/users/batch-import-ldap', { users }),
|
||||
}
|
||||
@@ -1,24 +1,55 @@
|
||||
// 存储域 API
|
||||
import { http } from '../http';
|
||||
import { http, buildQuery, type ListParams, type RequestOptions } from '../http';
|
||||
import type { PageData, StorageConfig } from '@/types';
|
||||
|
||||
export interface StorageCreateInput {
|
||||
name: string;
|
||||
storageType: 's3' | 'oss' | 'minio' | 'rustfs';
|
||||
endpoint?: string;
|
||||
bucket: string;
|
||||
region?: string;
|
||||
accessKey?: string;
|
||||
secretKey?: string;
|
||||
pathPrefix?: string;
|
||||
insecure?: boolean;
|
||||
isDefault?: boolean;
|
||||
}
|
||||
|
||||
export type StorageUpdateInput = Partial<StorageCreateInput>;
|
||||
|
||||
export const storageApi = {
|
||||
list: (page = 1, pageSize = 10) =>
|
||||
http.get<PageData<StorageConfig>>(`/storages?page=${page}&pageSize=${pageSize}`),
|
||||
list: (params: ListParams = {}, options?: RequestOptions) =>
|
||||
http.get<PageData<StorageConfig>>(`/storages${buildQuery(params)}`, options),
|
||||
|
||||
get: (id: number) => http.get<StorageConfig>(`/storages/${id}`),
|
||||
|
||||
create: (data: {
|
||||
name: string; storageType: 's3' | 'oss' | 'minio' | 'rustfs';
|
||||
endpoint?: string; bucket: string; region?: string;
|
||||
accessKey?: string; secretKey?: string; pathPrefix?: string;
|
||||
insecure?: boolean; isDefault?: boolean;
|
||||
}) => http.post<StorageConfig>('/storages', data),
|
||||
create: (data: StorageCreateInput) => http.post<StorageConfig>('/storages', data),
|
||||
|
||||
update: (id: number, data: Record<string, unknown>) =>
|
||||
update: (id: number, data: StorageUpdateInput) =>
|
||||
http.put<{ message: string }>(`/storages/${id}`, data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/storages/${id}`),
|
||||
|
||||
getDefault: () => http.get<StorageConfig>('/storages/default'),
|
||||
|
||||
// 测试连接(不落库):可达性/凭证/桶存在性,createIfMissing 时自动建桶
|
||||
test: (data: {
|
||||
storageType: StorageCreateInput['storageType'];
|
||||
endpoint?: string;
|
||||
bucket: string;
|
||||
region?: string;
|
||||
accessKey?: string;
|
||||
secretKey?: string;
|
||||
insecure?: boolean;
|
||||
createIfMissing?: boolean;
|
||||
}) =>
|
||||
http.post<StorageTestResult>('/storages/test', data),
|
||||
};
|
||||
|
||||
export interface StorageTestResult {
|
||||
reachable: boolean;
|
||||
authenticated: boolean;
|
||||
bucketExists: boolean;
|
||||
bucketCreated: boolean;
|
||||
message: string;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// 用户管理域 API(全部端点仅 admin 可用,后端 AdminAuth 兜底)
|
||||
import { http, buildQuery, type ListParams, type RequestOptions } from '../http';
|
||||
import type { PageData, User } from '@/types';
|
||||
|
||||
export interface UserCreateInput {
|
||||
username: string;
|
||||
password: string;
|
||||
nickname?: string;
|
||||
role?: 'admin' | 'user';
|
||||
}
|
||||
|
||||
export const userApi = {
|
||||
list: (params: ListParams = {}, options?: RequestOptions) =>
|
||||
http.get<PageData<User>>(`/users${buildQuery(params)}`, options),
|
||||
|
||||
create: (data: UserCreateInput) => http.post<User>('/users', data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/users/${id}`),
|
||||
|
||||
// 管理员重置密码(后端会吊销目标用户全部旧会话)
|
||||
resetPassword: (id: number, newPassword: string) =>
|
||||
http.post<{ message: string }>(`/users/${id}/reset-password`, { newPassword }),
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import { memo } from 'react'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
|
||||
interface ConfirmDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** 危险操作对象名进文案(如集群名),防误删 */
|
||||
name?: string
|
||||
title?: string
|
||||
description?: string
|
||||
confirmText?: string
|
||||
/** 确认中(提交 loading 态防双击) */
|
||||
loading?: boolean
|
||||
onConfirm: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 危险操作确认弹窗 — 替代原生 window.confirm()(阻塞主线程且样式与组件体系脱节)。
|
||||
* 默认为删除语义(红色确认钮);文案必须带操作对象名。
|
||||
*/
|
||||
export const ConfirmDialog = memo(function ConfirmDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
name,
|
||||
title = '确认删除',
|
||||
description,
|
||||
confirmText = '删除',
|
||||
loading = false,
|
||||
onConfirm,
|
||||
}: ConfirmDialogProps) {
|
||||
const desc =
|
||||
description ??
|
||||
(name
|
||||
? `确定要删除「${name}」吗?此操作不可恢复。`
|
||||
: '确定要执行该操作吗?此操作不可恢复。')
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{desc}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={loading}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
// 阻止默认关闭,等异步完成由调用方控制
|
||||
e.preventDefault()
|
||||
onConfirm()
|
||||
}}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{loading ? '处理中...' : confirmText}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
})
|
||||
|
||||
export default ConfirmDialog
|
||||
@@ -24,12 +24,12 @@ export const EmptyState = memo(function EmptyState({
|
||||
className,
|
||||
}: EmptyStateProps) {
|
||||
return (
|
||||
<Card className={cn('border-dashed border-slate-300 dark:border-slate-700', className)}>
|
||||
<Card className={cn('border-dashed border-border', className)}>
|
||||
<CardContent className="p-12 text-center">
|
||||
<Icon className="w-12 h-12 text-slate-300 mx-auto mb-4" />
|
||||
<p className="text-slate-500 font-medium">{title}</p>
|
||||
<Icon className="w-12 h-12 text-muted-foreground/60 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground font-medium">{title}</p>
|
||||
{description && (
|
||||
<p className="text-sm text-slate-400 mt-1">{description}</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">{description}</p>
|
||||
)}
|
||||
{action && <div className="mt-4">{action}</div>}
|
||||
</CardContent>
|
||||
|
||||
@@ -2,49 +2,69 @@ import { Component, type ReactNode } from 'react'
|
||||
|
||||
interface State {
|
||||
hasError: boolean
|
||||
error?: Error
|
||||
message?: string
|
||||
}
|
||||
|
||||
// 捕获子树渲染错误,避免整页白屏;显示错误信息便于排查
|
||||
// 动态 import / chunk 加载失败特征(发版后旧 hash chunk 404 是最常见场景)
|
||||
function isChunkLoadError(error: Error): boolean {
|
||||
const msg = error.message || ''
|
||||
return (
|
||||
msg.includes('Failed to fetch dynamically imported module') ||
|
||||
msg.includes('Importing a module script failed') ||
|
||||
msg.includes('Loading chunk') ||
|
||||
msg.includes('Loading CSS chunk')
|
||||
)
|
||||
}
|
||||
|
||||
const CHUNK_RELOADED_FLAG = 'opsxloki.chunk-reloaded'
|
||||
|
||||
/**
|
||||
* 全局错误边界
|
||||
* - chunk 加载失败自动刷新一次(每个会话最多一次,防循环),二次失败才显示错误卡片
|
||||
* - 不向用户暴露原始堆栈,仅显示错误消息摘要
|
||||
*/
|
||||
export default class ErrorBoundary extends Component<{ children: ReactNode }, State> {
|
||||
state: State = { hasError: false }
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { hasError: true, error }
|
||||
if (isChunkLoadError(error) && !sessionStorage.getItem(CHUNK_RELOADED_FLAG)) {
|
||||
sessionStorage.setItem(CHUNK_RELOADED_FLAG, '1')
|
||||
window.location.reload()
|
||||
}
|
||||
return { hasError: true, message: error.message }
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: { componentStack: string }) {
|
||||
// 错误上报收口:先 console,后续可接 Sentry 等远端上报
|
||||
console.error('页面渲染错误:', error, info)
|
||||
}
|
||||
|
||||
handleReset = () => {
|
||||
this.setState({ hasError: false, error: undefined })
|
||||
this.setState({ hasError: false, message: undefined })
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50 p-4">
|
||||
<div className="max-w-lg w-full bg-white rounded-2xl shadow-lg border border-red-200 p-6">
|
||||
<h2 className="text-lg font-semibold text-red-600 mb-2">页面渲染出错</h2>
|
||||
<p className="text-sm text-slate-600 mb-3">
|
||||
请把下方错误信息反馈给开发者,或尝试刷新页面:
|
||||
<div className="min-h-screen flex items-center justify-center bg-muted dark:bg-slate-950 p-4">
|
||||
<div className="max-w-lg w-full bg-card rounded-2xl shadow-lg border border-destructive/30 p-6">
|
||||
<h2 className="text-lg font-semibold text-destructive mb-2">页面渲染出错</h2>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
页面遇到异常,可尝试刷新;若持续出现请把下方信息反馈给开发者。
|
||||
</p>
|
||||
<pre className="text-xs bg-slate-900 text-red-300 p-3 rounded-lg overflow-auto max-h-60 font-mono whitespace-pre-wrap">
|
||||
{this.state.error?.message || '未知错误'}
|
||||
{'\n\n'}
|
||||
{this.state.error?.stack}
|
||||
<pre className="text-xs bg-muted font-mono text-destructive p-3 rounded-lg overflow-auto max-h-40 font-mono whitespace-pre-wrap">
|
||||
{this.state.message || '未知错误'}
|
||||
</pre>
|
||||
<div className="flex gap-2 mt-4">
|
||||
<button
|
||||
onClick={() => window.location.reload()}
|
||||
className="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm hover:bg-emerald-700"
|
||||
className="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90"
|
||||
>
|
||||
刷新页面
|
||||
</button>
|
||||
<button
|
||||
onClick={this.handleReset}
|
||||
className="px-4 py-2 bg-slate-100 text-slate-600 rounded-lg text-sm hover:bg-slate-200"
|
||||
className="px-4 py-2 bg-muted text-muted-foreground rounded-lg text-sm hover:bg-muted"
|
||||
>
|
||||
重置组件
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { memo } from 'react'
|
||||
import { AlertCircle, RotateCw } from 'lucide-react'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
interface ErrorStateProps {
|
||||
/** 错误消息(原因必带,用户要知情) */
|
||||
message?: string
|
||||
onRetry?: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误占位态 — 与空态(EmptyState)严格区分:加载失败必须可见且可重试,
|
||||
* 禁止把失败吞掉后渲染成「暂无数据」(数据组件三态之一,见开发标准 07 章)。
|
||||
*/
|
||||
export const ErrorState = memo(function ErrorState({
|
||||
message = '加载失败',
|
||||
onRetry,
|
||||
className,
|
||||
}: ErrorStateProps) {
|
||||
return (
|
||||
<Card className="border-destructive/30 border-dashed">
|
||||
<CardContent className={className ?? 'p-12 text-center'}>
|
||||
<AlertCircle className="w-12 h-12 text-destructive mx-auto mb-4" />
|
||||
<p className="text-muted-foreground font-medium">{message}</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">请检查网络或后端服务状态后重试</p>
|
||||
{onRetry && (
|
||||
<div className="mt-4">
|
||||
<Button variant="outline" size="sm" onClick={onRetry}>
|
||||
<RotateCw className="w-3.5 h-3.5 mr-1" />
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
export default ErrorState
|
||||
@@ -0,0 +1,27 @@
|
||||
import { memo } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface InfoRowProps {
|
||||
label: string
|
||||
value: string
|
||||
/** 追加到 value 上的类(如截断宽度) */
|
||||
valueClass?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 信息行 — 标签/值 两栏展示。
|
||||
* 原先在 Clusters/Hosts/Deployments/Collectors/Storage 五个页面各复制一份,
|
||||
* 第三次复用时晋升为全局组件(三次法则,见开发标准 02 章)。
|
||||
*/
|
||||
export const InfoRow = memo(function InfoRow({ label, value, valueClass }: InfoRowProps) {
|
||||
return (
|
||||
<div className="flex justify-between">
|
||||
<span>{label}</span>
|
||||
<span className={cn('font-medium text-foreground', valueClass)}>
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default InfoRow
|
||||
+186
-135
@@ -3,198 +3,249 @@ import {
|
||||
useState,
|
||||
useEffect,
|
||||
useCallback,
|
||||
useMemo,
|
||||
Suspense,
|
||||
} from 'react'
|
||||
import { Link, useLocation, useNavigate } from 'react-router'
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Server,
|
||||
Monitor,
|
||||
HardDrive,
|
||||
Rocket,
|
||||
RadioTower,
|
||||
Settings,
|
||||
LogOut,
|
||||
PanelLeftClose,
|
||||
PanelLeftOpen,
|
||||
Shield,
|
||||
ChevronRight,
|
||||
Activity,
|
||||
Menu,
|
||||
Sun,
|
||||
Moon,
|
||||
Monitor,
|
||||
} from 'lucide-react'
|
||||
import { useTheme } from 'next-themes'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useIsMobile } from '@/hooks/use-mobile'
|
||||
import { menuItems, findRouteMeta } from '@/router/routes'
|
||||
import { getUser, clearAuth } from '@/lib/auth-storage'
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
interface MenuItem {
|
||||
path: string
|
||||
icon: typeof LayoutDashboard
|
||||
label: string
|
||||
// 侧栏折叠状态持久化 key(命名空间见开发标准 08 章)
|
||||
const LAYOUT_COLLAPSED_KEY = 'opsxloki.layout.collapsed'
|
||||
|
||||
// 侧栏导航 — 桌面 aside 与移动端抽屉共用;菜单数据来自路由配置单源派生
|
||||
function SidebarNav({ collapsed, onNavigate }: { collapsed: boolean; onNavigate?: () => void }) {
|
||||
const location = useLocation()
|
||||
const isAdmin = getUser()?.role === 'admin'
|
||||
// adminOnly 项(用户管理)仅管理员可见;后端 AdminAuth 兜底
|
||||
const visibleItems = menuItems.filter((item) => !item.adminOnly || isAdmin)
|
||||
return (
|
||||
<nav className="flex-1 py-4 px-2 space-y-1 overflow-y-auto" aria-label="主导航">
|
||||
{visibleItems.map((item) => {
|
||||
const isActive = location.pathname === item.path
|
||||
return (
|
||||
<Link
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
onClick={onNavigate}
|
||||
aria-label={item.label}
|
||||
className={cn(
|
||||
'flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all',
|
||||
isActive
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'text-slate-400 hover:bg-slate-800 hover:text-white'
|
||||
)}
|
||||
title={!collapsed ? item.label : undefined}
|
||||
>
|
||||
{item.icon && <item.icon className="w-5 h-5 flex-shrink-0" />}
|
||||
{!collapsed && <span className="text-sm font-medium">{item.label}</span>}
|
||||
{!collapsed && isActive && (
|
||||
<ChevronRight className="w-4 h-4 ml-auto flex-shrink-0" />
|
||||
)}
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
const MENU_ITEMS: MenuItem[] = [
|
||||
{ path: '/', icon: LayoutDashboard, label: '仪表盘' },
|
||||
{ path: '/clusters', icon: Server, label: '集群管理' },
|
||||
{ path: '/hosts', icon: Monitor, label: '主机管理' },
|
||||
{ path: '/storage', icon: HardDrive, label: '存储配置' },
|
||||
{ path: '/deployments', icon: Rocket, label: '部署Loki' },
|
||||
{ path: '/collectors', icon: RadioTower, label: '部署客户端' },
|
||||
{ path: '/settings', icon: Settings, label: '系统设置' },
|
||||
]
|
||||
// 侧栏 Logo 区
|
||||
function SidebarLogo({ collapsed }: { collapsed: boolean }) {
|
||||
return (
|
||||
<div className="h-16 flex items-center px-4 border-b border-slate-700 flex-shrink-0">
|
||||
{collapsed ? (
|
||||
<div className="w-8 h-8 rounded-lg bg-primary flex items-center justify-center mx-auto">
|
||||
<Activity className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 rounded-lg bg-primary flex items-center justify-center">
|
||||
<Activity className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<span className="font-bold text-lg tracking-tight">opsx-loki</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 主题三态切换:浅色 → 深色 → 跟随系统(key: opsxloki.theme.mode)
|
||||
function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme()
|
||||
const next = theme === 'light' ? 'dark' : theme === 'dark' ? 'system' : 'light'
|
||||
const label = next === 'light' ? '切换为浅色' : next === 'dark' ? '切换为深色' : '切换为跟随系统'
|
||||
return (
|
||||
<button
|
||||
onClick={() => setTheme(next)}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800"
|
||||
>
|
||||
{theme === 'light' ? (
|
||||
<Sun className="w-4 h-4" />
|
||||
) : theme === 'dark' ? (
|
||||
<Moon className="w-4 h-4" />
|
||||
) : (
|
||||
<Monitor className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// 页面级加载骨架(挂在 main 内,切页时布局不闪)
|
||||
function PageSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6" aria-busy="true" aria-label="页面加载中">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-7 w-48" />
|
||||
<Skeleton className="h-4 w-72" />
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="h-40 rounded-xl" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Layout 组件(React.memo优化)
|
||||
*
|
||||
* 优化点:
|
||||
* 1. 使用 React.memo 避免不必要的重渲染
|
||||
* 2. menuItems 使用 useMemo 缓存
|
||||
* 3. handleLogout 使用 useCallback 缓存
|
||||
* 4. sidebar 状态使用 useIsMobile 自动适配移动端
|
||||
* 5. 导航链接使用 useMemo 缓存避免重复计算
|
||||
* Layout 组件 — 布局骨架,业务页只挂在内容区
|
||||
* - 菜单/顶栏标题来自路由 meta 单源(router/routes.tsx)
|
||||
* - 桌面端折叠状态持久化;移动端(<768px)侧栏为抽屉 + 遮罩
|
||||
* - 页面懒加载的 Suspense 边界在 main 内部
|
||||
*/
|
||||
const Layout = memo(function Layout({ children }: { children: React.ReactNode }) {
|
||||
const isMobile = useIsMobile()
|
||||
const [sidebarOpen, setSidebarOpen] = useState(!isMobile)
|
||||
const [user, setUser] = useState<{ username: string; role: string } | null>(null)
|
||||
const [collapsed, setCollapsed] = useState(() => localStorage.getItem(LAYOUT_COLLAPSED_KEY) === '1')
|
||||
const [mobileOpen, setMobileOpen] = useState(false)
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const user = getUser()
|
||||
|
||||
// 当移动端状态变化时,自动调整侧边栏
|
||||
useEffect(() => {
|
||||
setSidebarOpen(!isMobile)
|
||||
}, [isMobile])
|
||||
// 顶栏标题来自路由 meta
|
||||
const pageTitle = findRouteMeta(location.pathname)?.title || 'opsx-loki'
|
||||
|
||||
// 从localStorage加载用户信息
|
||||
// 折叠状态持久化(仅桌面端语义)
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem('user')
|
||||
if (stored) {
|
||||
try {
|
||||
setUser(JSON.parse(stored))
|
||||
} catch {
|
||||
// 解析失败静默处理
|
||||
}
|
||||
}
|
||||
localStorage.setItem(LAYOUT_COLLAPSED_KEY, collapsed ? '1' : '0')
|
||||
}, [collapsed])
|
||||
|
||||
const toggleSidebar = useCallback(() => {
|
||||
setCollapsed((prev) => !prev)
|
||||
}, [])
|
||||
|
||||
// 缓存当前页面标题
|
||||
const pageTitle = useMemo(
|
||||
() => MENU_ITEMS.find((item) => item.path === location.pathname)?.label || '仪表盘',
|
||||
[location.pathname]
|
||||
)
|
||||
|
||||
// 缓存登出处理函数
|
||||
const handleLogout = useCallback(() => {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('refreshToken')
|
||||
localStorage.removeItem('user')
|
||||
navigate('/login')
|
||||
clearAuth()
|
||||
navigate('/login', { replace: true })
|
||||
}, [navigate])
|
||||
|
||||
// 缓存侧边栏切换函数
|
||||
const toggleSidebar = useCallback(() => {
|
||||
setSidebarOpen((prev) => !prev)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen bg-slate-50 dark:bg-slate-950">
|
||||
{/* Sidebar */}
|
||||
<aside
|
||||
className={cn(
|
||||
'bg-slate-900 text-white transition-all duration-300 flex flex-col flex-shrink-0',
|
||||
sidebarOpen ? 'w-64' : 'w-16'
|
||||
)}
|
||||
>
|
||||
{/* Logo */}
|
||||
<div className="h-16 flex items-center px-4 border-b border-slate-700 flex-shrink-0">
|
||||
{sidebarOpen ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 rounded-lg bg-emerald-500 flex items-center justify-center">
|
||||
<Activity className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<span className="font-bold text-lg tracking-tight">LokiDeploy</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-8 h-8 rounded-lg bg-emerald-500 flex items-center justify-center mx-auto">
|
||||
<Activity className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div className="flex h-screen bg-background">
|
||||
{/* 桌面侧栏 */}
|
||||
{!isMobile && (
|
||||
<aside
|
||||
className={cn(
|
||||
'bg-slate-900 text-white transition-all duration-300 flex flex-col flex-shrink-0',
|
||||
collapsed ? 'w-16' : 'w-64'
|
||||
)}
|
||||
</div>
|
||||
>
|
||||
<SidebarLogo collapsed={collapsed} />
|
||||
<SidebarNav collapsed={collapsed} />
|
||||
<div className="p-2 border-t border-slate-700 flex-shrink-0">
|
||||
<button
|
||||
onClick={toggleSidebar}
|
||||
aria-label={collapsed ? '展开菜单' : '收起菜单'}
|
||||
title={collapsed ? '展开菜单' : '收起菜单'}
|
||||
className="flex items-center justify-center w-full py-2.5 rounded-lg text-slate-400 hover:bg-slate-800 hover:text-white transition-all"
|
||||
>
|
||||
{collapsed ? (
|
||||
<PanelLeftOpen className="w-5 h-5" />
|
||||
) : (
|
||||
<PanelLeftClose className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="flex-1 py-4 px-2 space-y-1 overflow-y-auto">
|
||||
{MENU_ITEMS.map((item) => {
|
||||
const isActive = location.pathname === item.path
|
||||
return (
|
||||
<Link
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
className={cn(
|
||||
'flex items-center gap-3 px-3 py-2.5 rounded-lg transition-all',
|
||||
isActive
|
||||
? 'bg-emerald-600 text-white'
|
||||
: 'text-slate-400 hover:bg-slate-800 hover:text-white'
|
||||
)}
|
||||
title={!sidebarOpen ? item.label : undefined}
|
||||
>
|
||||
<item.icon className="w-5 h-5 flex-shrink-0" />
|
||||
{sidebarOpen && (
|
||||
<span className="text-sm font-medium">{item.label}</span>
|
||||
)}
|
||||
{sidebarOpen && isActive && (
|
||||
<ChevronRight className="w-4 h-4 ml-auto flex-shrink-0" />
|
||||
)}
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* Bottom Actions */}
|
||||
<div className="p-2 border-t border-slate-700 flex-shrink-0">
|
||||
<button
|
||||
onClick={toggleSidebar}
|
||||
title={sidebarOpen ? '收起菜单' : '展开菜单'}
|
||||
className="flex items-center justify-center w-full py-2.5 rounded-lg text-slate-400 hover:bg-slate-800 hover:text-white transition-all"
|
||||
>
|
||||
{sidebarOpen ? (
|
||||
<PanelLeftClose className="w-5 h-5" />
|
||||
) : (
|
||||
<PanelLeftOpen className="w-5 h-5" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
{/* 移动端抽屉侧栏 */}
|
||||
{isMobile && (
|
||||
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
|
||||
<SheetContent side="left" className="bg-slate-900 text-white border-none p-0 w-72">
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle className="text-white">opsx-loki 导航</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="flex flex-col h-full">
|
||||
<SidebarLogo collapsed={false} />
|
||||
<SidebarNav collapsed={false} onNavigate={() => setMobileOpen(false)} />
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)}
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="flex-1 flex flex-col overflow-hidden min-w-0">
|
||||
{/* Top Bar */}
|
||||
<header className="h-16 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between px-6 flex-shrink-0">
|
||||
<h1 className="text-xl font-semibold text-slate-800 dark:text-white truncate">
|
||||
{pageTitle}
|
||||
</h1>
|
||||
<header className="h-16 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between px-4 md:px-6 flex-shrink-0 gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
{isMobile && (
|
||||
<button
|
||||
onClick={() => setMobileOpen(true)}
|
||||
aria-label="打开导航菜单"
|
||||
className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800"
|
||||
>
|
||||
<Menu className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
<h1 className="text-lg md:text-xl font-semibold text-slate-800 dark:text-white truncate">
|
||||
{pageTitle}
|
||||
</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 flex-shrink-0">
|
||||
<ThemeToggle />
|
||||
{user && (
|
||||
<div className="flex items-center gap-3 text-sm text-slate-600 dark:text-slate-300">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>{user.username}</span>
|
||||
<span className="px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 text-xs font-medium">
|
||||
<span className="px-2 py-0.5 rounded-full bg-success/10 text-success text-xs font-medium">
|
||||
{user.role === 'admin' ? '管理员' : user.role}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
title="退出登录"
|
||||
className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-slate-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/30 transition-all"
|
||||
aria-label="退出登录"
|
||||
className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-all"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
<span>退出</span>
|
||||
<span className="hidden md:inline">退出</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Page Content */}
|
||||
<main className="flex-1 overflow-auto p-6">
|
||||
{children}
|
||||
{/* Page Content — 页面级 Suspense 边界,懒加载时不闪布局 */}
|
||||
<main className="flex-1 overflow-auto p-4 md:p-6">
|
||||
<Suspense fallback={<PageSkeleton />}>{children}</Suspense>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -26,9 +26,9 @@ export const LoadingSpinner = memo(function LoadingSpinner({
|
||||
return (
|
||||
<div className={cn('flex flex-col items-center justify-center gap-3', className)}>
|
||||
<Activity
|
||||
className={cn('text-emerald-500 animate-spin', SIZE_MAP[size])}
|
||||
className={cn('text-primary animate-spin', SIZE_MAP[size])}
|
||||
/>
|
||||
{text && <p className="text-sm text-slate-500">{text}</p>}
|
||||
{text && <p className="text-sm text-muted-foreground">{text}</p>}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { memo } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { PageHeader } from '@/components/PageHeader'
|
||||
|
||||
interface PageContainerProps {
|
||||
/** 页头标题;缺省则不渲染页头(如仪表盘总览页) */
|
||||
title?: string
|
||||
description?: string
|
||||
/** 页头右侧操作区(主按钮等) */
|
||||
action?: React.ReactNode
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面容器 — 统一页面骨架(页头 + 内容区间距)。
|
||||
* 业务页一律以此为容器,不自行手写布局外壳(见开发标准 05 章)。
|
||||
*/
|
||||
export const PageContainer = memo(function PageContainer({
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
className,
|
||||
children,
|
||||
}: PageContainerProps) {
|
||||
return (
|
||||
<div className={cn('space-y-6', className)}>
|
||||
{title && <PageHeader title={title} description={description} action={action} />}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default PageContainer
|
||||
@@ -22,11 +22,11 @@ export const PageHeader = memo(function PageHeader({
|
||||
return (
|
||||
<div className={cn('flex items-center justify-between', className)}>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-slate-800 dark:text-white">
|
||||
<h2 className="text-lg font-semibold text-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
{description && (
|
||||
<p className="text-sm text-slate-500 mt-0.5">{description}</p>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
{action && <div className="flex-shrink-0">{action}</div>}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { memo, useMemo } from 'react'
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
PaginationEllipsis,
|
||||
} from '@/components/ui/pagination'
|
||||
|
||||
interface PaginationBarProps {
|
||||
page: number
|
||||
pageSize: number
|
||||
total: number
|
||||
onPageChange: (page: number) => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** 计算要展示的页码(当前页居中,最多 5 个,超界用省略号) */
|
||||
function pageNumbers(current: number, totalPages: number): Array<number | 'ellipsis-l' | 'ellipsis-r'> {
|
||||
if (totalPages <= 5) {
|
||||
return Array.from({ length: totalPages }, (_, i) => i + 1)
|
||||
}
|
||||
if (current <= 3) {
|
||||
return [1, 2, 3, 4, 'ellipsis-r', totalPages]
|
||||
}
|
||||
if (current >= totalPages - 2) {
|
||||
return [1, 'ellipsis-l', totalPages - 3, totalPages - 2, totalPages - 1, totalPages]
|
||||
}
|
||||
return [1, 'ellipsis-l', current - 1, current, current + 1, 'ellipsis-r', totalPages]
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页条 — 列表页统一分页 UI,消费后端 PageData.total。
|
||||
* (此前各页固定拉 100 条且丢弃 total,超量数据被静默截断。)
|
||||
*/
|
||||
export const PaginationBar = memo(function PaginationBar({
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
onPageChange,
|
||||
className,
|
||||
}: PaginationBarProps) {
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize))
|
||||
const pages = useMemo(() => pageNumbers(page, totalPages), [page, totalPages])
|
||||
|
||||
if (total <= pageSize) {
|
||||
return (
|
||||
<div className={className}>
|
||||
<p className="text-xs text-muted-foreground text-center">共 {total} 条</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<PaginationPrevious
|
||||
href="#"
|
||||
aria-disabled={page <= 1}
|
||||
className={page <= 1 ? 'pointer-events-none opacity-50' : ''}
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
if (page > 1) onPageChange(page - 1)
|
||||
}}
|
||||
/>
|
||||
</PaginationItem>
|
||||
{pages.map((p, idx) =>
|
||||
typeof p === 'number' ? (
|
||||
<PaginationItem key={p}>
|
||||
<PaginationLink
|
||||
href="#"
|
||||
isActive={p === page}
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
onPageChange(p)
|
||||
}}
|
||||
>
|
||||
{p}
|
||||
</PaginationLink>
|
||||
</PaginationItem>
|
||||
) : (
|
||||
<PaginationItem key={`${p}-${idx}`}>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
)
|
||||
)}
|
||||
<PaginationItem>
|
||||
<PaginationNext
|
||||
href="#"
|
||||
aria-disabled={page >= totalPages}
|
||||
className={page >= totalPages ? 'pointer-events-none opacity-50' : ''}
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
if (page < totalPages) onPageChange(page + 1)
|
||||
}}
|
||||
/>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
<p className="text-xs text-muted-foreground text-center mt-1">
|
||||
共 {total} 条 · 第 {page}/{totalPages} 页
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default PaginationBar
|
||||
@@ -0,0 +1,38 @@
|
||||
import { memo, useState } from 'react'
|
||||
import { Eye, EyeOff } from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
interface PasswordInputProps extends Omit<React.ComponentProps<typeof Input>, 'type'> {
|
||||
/** 明文切换按钮(密钥类字段默认开启) */
|
||||
toggleable?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码/密钥输入框 — 带明文切换。
|
||||
* 供 Hosts(SSH 密码/密钥口令)、Storage(secretKey)等敏感字段复用。
|
||||
*/
|
||||
export const PasswordInput = memo(function PasswordInput({
|
||||
toggleable = true,
|
||||
className,
|
||||
...props
|
||||
}: PasswordInputProps) {
|
||||
const [visible, setVisible] = useState(false)
|
||||
return (
|
||||
<div className="relative">
|
||||
<Input type={visible ? 'text' : 'password'} className={`${className ?? ''} pr-10`} {...props} />
|
||||
{toggleable && (
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
aria-label={visible ? '隐藏密码' : '显示密码'}
|
||||
onClick={() => setVisible((prev) => !prev)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-slate-600"
|
||||
>
|
||||
{visible ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default PasswordInput
|
||||
@@ -1,14 +1,8 @@
|
||||
import { memo, useMemo } from 'react'
|
||||
import {
|
||||
CheckCircle,
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
PauseCircle,
|
||||
Activity,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
import { Clock } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { statusLabel } from '@/lib/utils'
|
||||
import { STATUS_CONFIG } from './status-config'
|
||||
|
||||
export type StatusSize = 'sm' | 'md'
|
||||
|
||||
@@ -19,61 +13,11 @@ interface StatusBadgeProps {
|
||||
className?: string
|
||||
}
|
||||
|
||||
interface StatusConfig {
|
||||
icon: LucideIcon
|
||||
color: string
|
||||
bg: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const STATUS_CONFIG: Record<string, Omit<StatusConfig, 'label'>> = {
|
||||
running: {
|
||||
icon: CheckCircle,
|
||||
color: 'text-emerald-500',
|
||||
bg: 'bg-emerald-100 text-emerald-700',
|
||||
},
|
||||
active: {
|
||||
icon: CheckCircle,
|
||||
color: 'text-emerald-500',
|
||||
bg: 'bg-emerald-100 text-emerald-700',
|
||||
},
|
||||
failed: {
|
||||
icon: AlertTriangle,
|
||||
color: 'text-red-500',
|
||||
bg: 'bg-red-100 text-red-700',
|
||||
},
|
||||
error: {
|
||||
icon: AlertTriangle,
|
||||
color: 'text-red-500',
|
||||
bg: 'bg-red-100 text-red-700',
|
||||
},
|
||||
pending: {
|
||||
icon: Clock,
|
||||
color: 'text-amber-500',
|
||||
bg: 'bg-amber-100 text-amber-700',
|
||||
},
|
||||
stopped: {
|
||||
icon: PauseCircle,
|
||||
color: 'text-slate-400',
|
||||
bg: 'bg-slate-100 text-slate-600',
|
||||
},
|
||||
inactive: {
|
||||
icon: PauseCircle,
|
||||
color: 'text-slate-400',
|
||||
bg: 'bg-slate-100 text-slate-600',
|
||||
},
|
||||
deploying: {
|
||||
icon: Activity,
|
||||
color: 'text-blue-500',
|
||||
bg: 'bg-blue-100 text-blue-700',
|
||||
},
|
||||
}
|
||||
|
||||
function getStatusConfig(status: string): StatusConfig {
|
||||
function getStatusConfig(status: string): { icon: typeof Clock; color: string; bg: string; label: string } {
|
||||
const config = STATUS_CONFIG[status] || {
|
||||
icon: Clock,
|
||||
color: 'text-slate-400',
|
||||
bg: 'bg-slate-100 text-slate-600',
|
||||
color: 'text-muted-foreground',
|
||||
bg: 'bg-muted text-muted-foreground',
|
||||
}
|
||||
return {
|
||||
...config,
|
||||
@@ -144,9 +88,4 @@ export const StatusIcon = memo(function StatusIcon({
|
||||
)
|
||||
})
|
||||
|
||||
/** 独立状态颜色工具函数(用于需要className的场景) */
|
||||
export function getStatusColorClass(status: string): string {
|
||||
return STATUS_CONFIG[status]?.bg || 'bg-slate-100 text-slate-600'
|
||||
}
|
||||
|
||||
export default StatusBadge
|
||||
@@ -0,0 +1,14 @@
|
||||
// 全局组件出口(barrel)— 页面统一从这里 import 共享组件。
|
||||
// 页面私有组件放各自 pages/<domain>/components/,晋升三次后再进这里。
|
||||
export { default as PageContainer } from './PageContainer';
|
||||
export { default as PageHeader } from './PageHeader';
|
||||
export { default as InfoRow } from './InfoRow';
|
||||
export { default as ConfirmDialog } from './ConfirmDialog';
|
||||
export { default as ErrorState } from './ErrorState';
|
||||
export { default as EmptyState } from './EmptyState';
|
||||
export { default as LoadingSpinner, FullScreenLoader } from './LoadingSpinner';
|
||||
export { default as PaginationBar } from './PaginationBar';
|
||||
export { default as PasswordInput } from './PasswordInput';
|
||||
export { default as StatusBadge, StatusIcon } from './StatusBadge';
|
||||
export { getStatusColorClass } from './status-config';
|
||||
export { default as ErrorBoundary } from './ErrorBoundary';
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
CheckCircle,
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
PauseCircle,
|
||||
Activity,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
|
||||
export interface StatusConfig {
|
||||
icon: LucideIcon
|
||||
color: string
|
||||
bg: string
|
||||
label: string
|
||||
}
|
||||
|
||||
// 状态色全部走语义 Token(success/warning/destructive/info/muted),禁止硬编码调色板
|
||||
export const STATUS_CONFIG: Record<string, Omit<StatusConfig, 'label'>> = {
|
||||
running: {
|
||||
icon: CheckCircle,
|
||||
color: 'text-success',
|
||||
bg: 'bg-success/10 text-success',
|
||||
},
|
||||
active: {
|
||||
icon: CheckCircle,
|
||||
color: 'text-success',
|
||||
bg: 'bg-success/10 text-success',
|
||||
},
|
||||
failed: {
|
||||
icon: AlertTriangle,
|
||||
color: 'text-destructive',
|
||||
bg: 'bg-destructive/10 text-destructive',
|
||||
},
|
||||
error: {
|
||||
icon: AlertTriangle,
|
||||
color: 'text-destructive',
|
||||
bg: 'bg-destructive/10 text-destructive',
|
||||
},
|
||||
pending: {
|
||||
icon: Clock,
|
||||
color: 'text-warning',
|
||||
bg: 'bg-warning/10 text-warning',
|
||||
},
|
||||
stopped: {
|
||||
icon: PauseCircle,
|
||||
color: 'text-muted-foreground',
|
||||
bg: 'bg-muted text-muted-foreground',
|
||||
},
|
||||
inactive: {
|
||||
icon: PauseCircle,
|
||||
color: 'text-muted-foreground',
|
||||
bg: 'bg-muted text-muted-foreground',
|
||||
},
|
||||
deploying: {
|
||||
icon: Activity,
|
||||
color: 'text-info',
|
||||
bg: 'bg-info/10 text-info',
|
||||
},
|
||||
}
|
||||
|
||||
/** 状态颜色工具(用于需要 className 的场景,与 StatusBadge 同源) */
|
||||
export function getStatusColorClass(status: string): string {
|
||||
return STATUS_CONFIG[status]?.bg || 'bg-muted text-muted-foreground'
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import * as React from "react"
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Accordion({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
|
||||
}
|
||||
|
||||
function AccordionItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||
return (
|
||||
<AccordionPrimitive.Item
|
||||
data-slot="accordion-item"
|
||||
className={cn("border-b last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||
return (
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
data-slot="accordion-trigger"
|
||||
className={cn(
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||
return (
|
||||
<AccordionPrimitive.Content
|
||||
data-slot="accordion-content"
|
||||
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||
{...props}
|
||||
>
|
||||
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
)
|
||||
}
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||
@@ -1,66 +0,0 @@
|
||||
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 }
|
||||
@@ -1,11 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
|
||||
|
||||
function AspectRatio({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
|
||||
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
|
||||
}
|
||||
|
||||
export { AspectRatio }
|
||||
@@ -1,51 +0,0 @@
|
||||
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 }
|
||||
@@ -1,46 +0,0 @@
|
||||
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 }
|
||||
@@ -1,109 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
"use client"
|
||||
|
||||
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:--spacing(8)] [[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 gap-4 flex-col md:flex-row relative",
|
||||
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 }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute bg-popover inset-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-(--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 size-(--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 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] 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 }
|
||||
@@ -1,239 +0,0 @@
|
||||
import * as React from "react"
|
||||
import useEmblaCarousel, {
|
||||
type UseEmblaCarouselType,
|
||||
} from "embla-carousel-react"
|
||||
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
type CarouselApi = UseEmblaCarouselType[1]
|
||||
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||
type CarouselOptions = UseCarouselParameters[0]
|
||||
type CarouselPlugin = UseCarouselParameters[1]
|
||||
|
||||
type CarouselProps = {
|
||||
opts?: CarouselOptions
|
||||
plugins?: CarouselPlugin
|
||||
orientation?: "horizontal" | "vertical"
|
||||
setApi?: (api: CarouselApi) => void
|
||||
}
|
||||
|
||||
type CarouselContextProps = {
|
||||
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||
scrollPrev: () => void
|
||||
scrollNext: () => void
|
||||
canScrollPrev: boolean
|
||||
canScrollNext: boolean
|
||||
} & CarouselProps
|
||||
|
||||
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||
|
||||
function useCarousel() {
|
||||
const context = React.useContext(CarouselContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useCarousel must be used within a <Carousel />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function Carousel({
|
||||
orientation = "horizontal",
|
||||
opts,
|
||||
setApi,
|
||||
plugins,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & CarouselProps) {
|
||||
const [carouselRef, api] = useEmblaCarousel(
|
||||
{
|
||||
...opts,
|
||||
axis: orientation === "horizontal" ? "x" : "y",
|
||||
},
|
||||
plugins
|
||||
)
|
||||
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||
|
||||
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||
if (!api) return
|
||||
setCanScrollPrev(api.canScrollPrev())
|
||||
setCanScrollNext(api.canScrollNext())
|
||||
}, [])
|
||||
|
||||
const scrollPrev = React.useCallback(() => {
|
||||
api?.scrollPrev()
|
||||
}, [api])
|
||||
|
||||
const scrollNext = React.useCallback(() => {
|
||||
api?.scrollNext()
|
||||
}, [api])
|
||||
|
||||
const handleKeyDown = React.useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault()
|
||||
scrollPrev()
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault()
|
||||
scrollNext()
|
||||
}
|
||||
},
|
||||
[scrollPrev, scrollNext]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api || !setApi) return
|
||||
setApi(api)
|
||||
}, [api, setApi])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) return
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
|
||||
return () => {
|
||||
api?.off("select", onSelect)
|
||||
}
|
||||
}, [api, onSelect])
|
||||
|
||||
return (
|
||||
<CarouselContext.Provider
|
||||
value={{
|
||||
carouselRef,
|
||||
api: api,
|
||||
opts,
|
||||
orientation:
|
||||
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||
scrollPrev,
|
||||
scrollNext,
|
||||
canScrollPrev,
|
||||
canScrollNext,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onKeyDownCapture={handleKeyDown}
|
||||
className={cn("relative", className)}
|
||||
role="region"
|
||||
aria-roledescription="carousel"
|
||||
data-slot="carousel"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</CarouselContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { carouselRef, orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={carouselRef}
|
||||
className="overflow-hidden"
|
||||
data-slot="carousel-content"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex",
|
||||
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
data-slot="carousel-item"
|
||||
className={cn(
|
||||
"min-w-0 shrink-0 grow-0 basis-full",
|
||||
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselPrevious({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-previous"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -left-12 -translate-y-1/2"
|
||||
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollPrev}
|
||||
onClick={scrollPrev}
|
||||
{...props}
|
||||
>
|
||||
<ArrowLeft />
|
||||
<span className="sr-only">Previous slide</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselNext({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-next"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -right-12 -translate-y-1/2"
|
||||
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollNext}
|
||||
onClick={scrollNext}
|
||||
{...props}
|
||||
>
|
||||
<ArrowRight />
|
||||
<span className="sr-only">Next slide</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
type CarouselApi,
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselPrevious,
|
||||
CarouselNext,
|
||||
}
|
||||
@@ -1,357 +0,0 @@
|
||||
"use client"
|
||||
|
||||
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-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||
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-(--color-border) bg-(--color-bg)",
|
||||
{
|
||||
"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,
|
||||
} 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,
|
||||
}
|
||||
@@ -1,32 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
import { Check } 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}
|
||||
const Checkbox = React.forwardRef<
|
||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CheckboxPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"grid place-content-center peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
className={cn("grid place-content-center text-current")}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
<Check className="h-4 w-4" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
))
|
||||
Checkbox.displayName = CheckboxPrimitive.Root.displayName
|
||||
|
||||
export { Checkbox }
|
||||
@@ -1,31 +0,0 @@
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleTrigger
|
||||
data-slot="collapsible-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleContent
|
||||
data-slot="collapsible-content"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
@@ -1,182 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
function Command({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
return (
|
||||
<CommandPrimitive
|
||||
data-slot="command"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = "Command Palette",
|
||||
description = "Search for a command to run...",
|
||||
children,
|
||||
className,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogHeader className="sr-only">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent
|
||||
className={cn("overflow-hidden p-0", className)}
|
||||
showCloseButton={showCloseButton}
|
||||
>
|
||||
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="command-input-wrapper"
|
||||
className="flex h-9 items-center gap-2 border-b px-3"
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
data-slot="command-input"
|
||||
className={cn(
|
||||
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||
return (
|
||||
<CommandPrimitive.List
|
||||
data-slot="command-list"
|
||||
className={cn(
|
||||
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandEmpty({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||
return (
|
||||
<CommandPrimitive.Empty
|
||||
data-slot="command-empty"
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||
return (
|
||||
<CommandPrimitive.Group
|
||||
data-slot="command-group"
|
||||
className={cn(
|
||||
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
return (
|
||||
<CommandPrimitive.Separator
|
||||
data-slot="command-separator"
|
||||
className={cn("bg-border -mx-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
return (
|
||||
<CommandPrimitive.Item
|
||||
data-slot="command-item"
|
||||
className={cn(
|
||||
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="command-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-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 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-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 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Drawer as DrawerPrimitive } from "vaul"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Drawer({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
||||
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
|
||||
}
|
||||
|
||||
function DrawerTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
||||
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DrawerPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
||||
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
|
||||
}
|
||||
|
||||
function DrawerClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
||||
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
|
||||
}
|
||||
|
||||
function DrawerOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
||||
return (
|
||||
<DrawerPrimitive.Overlay
|
||||
data-slot="drawer-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
||||
return (
|
||||
<DrawerPortal data-slot="drawer-portal">
|
||||
<DrawerOverlay />
|
||||
<DrawerPrimitive.Content
|
||||
data-slot="drawer-content"
|
||||
className={cn(
|
||||
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
|
||||
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
||||
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
||||
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
||||
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-header"
|
||||
className={cn(
|
||||
"flex flex-col gap-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,
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
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 inset-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,
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function HoverCard({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
|
||||
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
|
||||
}
|
||||
|
||||
function HoverCardTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
|
||||
return (
|
||||
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function HoverCardContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
|
||||
return (
|
||||
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
|
||||
<HoverCardPrimitive.Content
|
||||
data-slot="hover-card-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</HoverCardPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { HoverCard, HoverCardTrigger, HoverCardContent }
|
||||
@@ -1,170 +0,0 @@
|
||||
"use client"
|
||||
|
||||
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,
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { OTPInput, OTPInputContext } from "input-otp"
|
||||
import { MinusIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function InputOTP({
|
||||
className,
|
||||
containerClassName,
|
||||
...props
|
||||
}: React.ComponentProps<typeof OTPInput> & {
|
||||
containerClassName?: string
|
||||
}) {
|
||||
return (
|
||||
<OTPInput
|
||||
data-slot="input-otp"
|
||||
containerClassName={cn(
|
||||
"flex items-center gap-2 has-disabled:opacity-50",
|
||||
containerClassName
|
||||
)}
|
||||
className={cn("disabled:cursor-not-allowed", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="input-otp-group"
|
||||
className={cn("flex items-center", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPSlot({
|
||||
index,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
index: number
|
||||
}) {
|
||||
const inputOTPContext = React.useContext(OTPInputContext)
|
||||
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="input-otp-slot"
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{char}
|
||||
{hasFakeCaret && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
|
||||
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div data-slot="input-otp-separator" role="separator" {...props}>
|
||||
<MinusIcon />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
|
||||
@@ -1,193 +0,0 @@
|
||||
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"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
|
||||
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
role="list"
|
||||
data-slot="item-group"
|
||||
className={cn("group/item-group flex flex-col", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="item-separator"
|
||||
orientation="horizontal"
|
||||
className={cn("my-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const itemVariants = cva(
|
||||
"group/item flex items-center border border-transparent text-sm rounded-md transition-colors [a]:hover:bg-accent/50 [a]:transition-colors duration-100 flex-wrap outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline: "border-border",
|
||||
muted: "bg-muted/50",
|
||||
},
|
||||
size: {
|
||||
default: "p-4 gap-4 ",
|
||||
sm: "py-3 px-4 gap-2.5",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Item({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> &
|
||||
VariantProps<typeof itemVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
return (
|
||||
<Comp
|
||||
data-slot="item"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(itemVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const itemMediaVariants = cva(
|
||||
"flex shrink-0 items-center justify-center gap-2 group-has-[[data-slot=item-description]]/item:self-start [&_svg]:pointer-events-none group-has-[[data-slot=item-description]]/item:translate-y-0.5",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
icon: "size-8 border rounded-sm bg-muted [&_svg:not([class*='size-'])]:size-4",
|
||||
image:
|
||||
"size-10 rounded-sm overflow-hidden [&_img]:size-full [&_img]:object-cover",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function ItemMedia({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-media"
|
||||
data-variant={variant}
|
||||
className={cn(itemMediaVariants({ variant, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-content"
|
||||
className={cn(
|
||||
"flex flex-1 flex-col gap-1 [&+[data-slot=item-content]]:flex-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-title"
|
||||
className={cn(
|
||||
"flex w-fit items-center gap-2 text-sm leading-snug font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<p
|
||||
data-slot="item-description"
|
||||
className={cn(
|
||||
"text-muted-foreground line-clamp-2 text-sm leading-normal font-normal text-balance",
|
||||
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-actions"
|
||||
className={cn("flex items-center gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-header"
|
||||
className={cn(
|
||||
"flex basis-full items-center justify-between gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="item-footer"
|
||||
className={cn(
|
||||
"flex basis-full items-center justify-between gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Item,
|
||||
ItemMedia,
|
||||
ItemContent,
|
||||
ItemActions,
|
||||
ItemGroup,
|
||||
ItemSeparator,
|
||||
ItemTitle,
|
||||
ItemDescription,
|
||||
ItemHeader,
|
||||
ItemFooter,
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="kbd"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none",
|
||||
"[&_svg:not([class*='size-'])]:size-3",
|
||||
"[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="kbd-group"
|
||||
className={cn("inline-flex items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Kbd, KbdGroup }
|
||||
@@ -1,274 +0,0 @@
|
||||
import * as React from "react"
|
||||
import * as MenubarPrimitive from "@radix-ui/react-menubar"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Menubar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
|
||||
return (
|
||||
<MenubarPrimitive.Root
|
||||
data-slot="menubar"
|
||||
className={cn(
|
||||
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
|
||||
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
|
||||
}
|
||||
|
||||
function MenubarGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
|
||||
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
|
||||
}
|
||||
|
||||
function MenubarPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
|
||||
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
|
||||
}
|
||||
|
||||
function MenubarRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
|
||||
return (
|
||||
<MenubarPrimitive.Trigger
|
||||
data-slot="menubar-trigger"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarContent({
|
||||
className,
|
||||
align = "start",
|
||||
alignOffset = -4,
|
||||
sideOffset = 8,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
|
||||
return (
|
||||
<MenubarPortal>
|
||||
<MenubarPrimitive.Content
|
||||
data-slot="menubar-content"
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</MenubarPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.Item
|
||||
data-slot="menubar-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<MenubarPrimitive.CheckboxItem
|
||||
data-slot="menubar-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<MenubarPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</MenubarPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenubarPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
|
||||
return (
|
||||
<MenubarPrimitive.RadioItem
|
||||
data-slot="menubar-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<MenubarPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</MenubarPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenubarPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.Label
|
||||
data-slot="menubar-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
|
||||
return (
|
||||
<MenubarPrimitive.Separator
|
||||
data-slot="menubar-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="menubar-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
|
||||
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
|
||||
}
|
||||
|
||||
function MenubarSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.SubTrigger
|
||||
data-slot="menubar-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto h-4 w-4" />
|
||||
</MenubarPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
|
||||
return (
|
||||
<MenubarPrimitive.SubContent
|
||||
data-slot="menubar-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Menubar,
|
||||
MenubarPortal,
|
||||
MenubarMenu,
|
||||
MenubarTrigger,
|
||||
MenubarContent,
|
||||
MenubarGroup,
|
||||
MenubarSeparator,
|
||||
MenubarLabel,
|
||||
MenubarItem,
|
||||
MenubarShortcut,
|
||||
MenubarCheckboxItem,
|
||||
MenubarRadioGroup,
|
||||
MenubarRadioItem,
|
||||
MenubarSub,
|
||||
MenubarSubTrigger,
|
||||
MenubarSubContent,
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
import * as React from "react"
|
||||
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function NavigationMenu({
|
||||
className,
|
||||
children,
|
||||
viewport = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
|
||||
viewport?: boolean
|
||||
}) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Root
|
||||
data-slot="navigation-menu"
|
||||
data-viewport={viewport}
|
||||
className={cn(
|
||||
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{viewport && <NavigationMenuViewport />}
|
||||
</NavigationMenuPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.List
|
||||
data-slot="navigation-menu-list"
|
||||
className={cn(
|
||||
"group flex flex-1 list-none items-center justify-center gap-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Item
|
||||
data-slot="navigation-menu-item"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const navigationMenuTriggerStyle = cva(
|
||||
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
)
|
||||
|
||||
function NavigationMenuTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Trigger
|
||||
data-slot="navigation-menu-trigger"
|
||||
className={cn(navigationMenuTriggerStyle(), "group", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}{" "}
|
||||
<ChevronDownIcon
|
||||
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</NavigationMenuPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Content
|
||||
data-slot="navigation-menu-content"
|
||||
className={cn(
|
||||
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
|
||||
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuViewport({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"absolute top-full left-0 isolate z-50 flex justify-center"
|
||||
)}
|
||||
>
|
||||
<NavigationMenuPrimitive.Viewport
|
||||
data-slot="navigation-menu-viewport"
|
||||
className={cn(
|
||||
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuLink({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Link
|
||||
data-slot="navigation-menu-link"
|
||||
className={cn(
|
||||
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuIndicator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Indicator
|
||||
data-slot="navigation-menu-indicator"
|
||||
className={cn(
|
||||
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
|
||||
</NavigationMenuPrimitive.Indicator>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
NavigationMenu,
|
||||
NavigationMenuList,
|
||||
NavigationMenuItem,
|
||||
NavigationMenuContent,
|
||||
NavigationMenuTrigger,
|
||||
NavigationMenuLink,
|
||||
NavigationMenuIndicator,
|
||||
NavigationMenuViewport,
|
||||
navigationMenuTriggerStyle,
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
@@ -1,29 +0,0 @@
|
||||
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 }
|
||||
@@ -1,45 +0,0 @@
|
||||
"use client"
|
||||
|
||||
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 }
|
||||
@@ -1,54 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { GripVerticalIcon } from "lucide-react"
|
||||
import * as ResizablePrimitive from "react-resizable-panels"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ResizablePanelGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.Group>) {
|
||||
return (
|
||||
<ResizablePrimitive.Group
|
||||
data-slot="resizable-panel-group"
|
||||
className={cn(
|
||||
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ResizablePanel({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
|
||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
|
||||
}
|
||||
|
||||
function ResizableHandle({
|
||||
withHandle,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.Separator> & {
|
||||
withHandle?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ResizablePrimitive.Separator
|
||||
data-slot="resizable-handle"
|
||||
className={cn(
|
||||
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{withHandle && (
|
||||
<div className="bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border">
|
||||
<GripVerticalIcon className="size-2.5" />
|
||||
</div>
|
||||
)}
|
||||
</ResizablePrimitive.Separator>
|
||||
)
|
||||
}
|
||||
|
||||
export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
|
||||
@@ -5,54 +5,44 @@ import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
const ScrollArea = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn("relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
))
|
||||
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
const ScrollBar = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
>(({ className, orientation = "vertical", ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
ref={ref}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none select-none transition-colors",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
))
|
||||
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
@@ -1,28 +0,0 @@
|
||||
"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 }
|
||||
@@ -1,726 +0,0 @@
|
||||
"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 has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer text-sidebar-foreground hidden md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-label"
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-action"
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-button"
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip) {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
asChild = false,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-action"
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
asChild = false,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-sub-button"
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SliderPrimitive from "@radix-ui/react-slider"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Slider({
|
||||
className,
|
||||
defaultValue,
|
||||
value,
|
||||
min = 0,
|
||||
max = 100,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
|
||||
const _values = React.useMemo(
|
||||
() =>
|
||||
Array.isArray(value)
|
||||
? value
|
||||
: Array.isArray(defaultValue)
|
||||
? defaultValue
|
||||
: [min, max],
|
||||
[value, defaultValue, min, max]
|
||||
)
|
||||
|
||||
return (
|
||||
<SliderPrimitive.Root
|
||||
data-slot="slider"
|
||||
defaultValue={defaultValue}
|
||||
value={value}
|
||||
min={min}
|
||||
max={max}
|
||||
className={cn(
|
||||
"relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track
|
||||
data-slot="slider-track"
|
||||
className={cn(
|
||||
"bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
|
||||
)}
|
||||
>
|
||||
<SliderPrimitive.Range
|
||||
data-slot="slider-range"
|
||||
className={cn(
|
||||
"bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
|
||||
)}
|
||||
/>
|
||||
</SliderPrimitive.Track>
|
||||
{Array.from({ length: _values.length }, (_, index) => (
|
||||
<SliderPrimitive.Thumb
|
||||
data-slot="slider-thumb"
|
||||
key={index}
|
||||
className="border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
|
||||
/>
|
||||
))}
|
||||
</SliderPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Slider }
|
||||
@@ -1,16 +0,0 @@
|
||||
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 }
|
||||
@@ -1,114 +0,0 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("text-muted-foreground mt-4 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
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 } as React.CSSProperties}
|
||||
className={cn(
|
||||
"group/toggle-group flex w-fit items-center gap-[--spacing(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 }
|
||||
@@ -1,45 +0,0 @@
|
||||
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 }
|
||||
@@ -1,61 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { PageData } from '@/types'
|
||||
import type { ListParams } from '@/api'
|
||||
|
||||
export type ListFetcher<T> = (params: ListParams, signal: AbortSignal) => Promise<PageData<T>>
|
||||
|
||||
interface UseListQueryOptions {
|
||||
/** 每页条数(默认 12,卡片网格 3 列 × 4 行) */
|
||||
pageSize?: number
|
||||
}
|
||||
|
||||
export interface ListQueryResult<T> {
|
||||
list: T[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
/** 加载中(首屏与翻页) */
|
||||
loading: boolean
|
||||
/** 加载失败消息(非 null 时渲染 ErrorState,与空态严格区分) */
|
||||
error: string | null
|
||||
setPage: (page: number) => void
|
||||
/** 重拉当前页(操作完成/错误重试后调用) */
|
||||
refresh: () => void
|
||||
/** 回到第 1 页重拉(新建成功后调用) */
|
||||
reload: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页列表数据 hook — 「AbortController 取消 + 版本号令牌」双重防护(见开发标准 03 章):
|
||||
* 快速翻页/连续刷新时旧响应被取消或按版本丢弃,杜绝错序覆盖;
|
||||
* StrictMode 双执行、组件卸载时在途请求一并取消。
|
||||
*
|
||||
* @example
|
||||
* const query = useListQuery<Cluster>(
|
||||
* (params, signal) => clusterApi.list(params, { signal })
|
||||
* )
|
||||
*/
|
||||
export function useListQuery<T>(
|
||||
fetcher: ListFetcher<T>,
|
||||
options: UseListQueryOptions = {}
|
||||
): ListQueryResult<T> {
|
||||
const { pageSize = 12 } = options
|
||||
|
||||
const [list, setList] = useState<T[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const versionRef = useRef(0)
|
||||
// fetcher 透传到 ref,调用方内联箭头函数不会触发重复请求
|
||||
const fetcherRef = useRef(fetcher)
|
||||
fetcherRef.current = fetcher
|
||||
|
||||
const fetchData = useCallback(
|
||||
async (targetPage: number) => {
|
||||
// ① 取消旧请求
|
||||
abortRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
abortRef.current = controller
|
||||
// ② 版本号令牌:过期响应直接丢弃
|
||||
const currentVersion = ++versionRef.current
|
||||
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetcherRef.current({ page: targetPage, pageSize }, controller.signal)
|
||||
if (currentVersion !== versionRef.current) return
|
||||
setList(res.list ?? [])
|
||||
setTotal(res.total ?? 0)
|
||||
} catch (err) {
|
||||
if (currentVersion !== versionRef.current) return
|
||||
setError(err instanceof Error ? err.message : '加载失败')
|
||||
} finally {
|
||||
if (currentVersion === versionRef.current) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
},
|
||||
[pageSize]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void fetchData(page)
|
||||
}, [page, fetchData])
|
||||
|
||||
// 卸载:取消在途请求并作废版本
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
// 写入而非读取:递增使在途响应按版本号判过期(exhaustive-deps 误报)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
versionRef.current++
|
||||
abortRef.current?.abort()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
void fetchData(page)
|
||||
}, [fetchData, page])
|
||||
|
||||
const reload = useCallback(() => {
|
||||
if (page === 1) {
|
||||
void fetchData(1)
|
||||
} else {
|
||||
setPage(1)
|
||||
}
|
||||
}, [fetchData, page])
|
||||
|
||||
return { list, total, page, pageSize, loading, error, setPage, refresh, reload }
|
||||
}
|
||||
+68
-50
@@ -2,66 +2,84 @@
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/*
|
||||
* 语义 Token 单源(开发标准 06 章):
|
||||
* - 品牌主色 = emerald(原散落各页的 bg-emerald-600 收敛为 --primary)
|
||||
* - 中性色 = slate 色阶;暗色卡片比页面底色亮一档(靠亮度差分层)
|
||||
* - 语义色 success/warning/info 对齐状态语义,StatusBadge 等统一引用
|
||||
*/
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 240 10% 3.9%;
|
||||
--background: 210 40% 98%;
|
||||
--foreground: 222 47% 11%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 240 10% 3.9%;
|
||||
--card-foreground: 222 47% 11%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 240 10% 3.9%;
|
||||
--primary: 240 5.9% 10%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 240 4.8% 95.9%;
|
||||
--secondary-foreground: 240 5.9% 10%;
|
||||
--muted: 240 4.8% 95.9%;
|
||||
--muted-foreground: 240 3.8% 46.1%;
|
||||
--accent: 240 4.8% 95.9%;
|
||||
--accent-foreground: 240 5.9% 10%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--popover-foreground: 222 47% 11%;
|
||||
--primary: 161 94% 30%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--secondary: 210 40% 96%;
|
||||
--secondary-foreground: 222 47% 11%;
|
||||
--muted: 210 40% 96%;
|
||||
--muted-foreground: 215 16% 47%;
|
||||
--accent: 210 40% 96%;
|
||||
--accent-foreground: 222 47% 11%;
|
||||
--destructive: 0 84% 60%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 240 5.9% 90%;
|
||||
--input: 240 5.9% 90%;
|
||||
--ring: 240 5.9% 10%;
|
||||
--success: 161 74% 30%;
|
||||
--success-foreground: 0 0% 100%;
|
||||
--warning: 32 95% 44%;
|
||||
--warning-foreground: 0 0% 100%;
|
||||
--info: 221 83% 53%;
|
||||
--info-foreground: 0 0% 100%;
|
||||
--border: 214 32% 91%;
|
||||
--input: 214 25% 84%;
|
||||
--ring: 161 94% 30%;
|
||||
--radius: 0.625rem;
|
||||
--sidebar-background: 0 0% 98%;
|
||||
--sidebar-foreground: 240 5.3% 26.1%;
|
||||
--sidebar-primary: 240 5.9% 10%;
|
||||
--sidebar-primary-foreground: 0 0% 98%;
|
||||
--sidebar-accent: 240 4.8% 95.9%;
|
||||
--sidebar-accent-foreground: 240 5.9% 10%;
|
||||
--sidebar-border: 220 13% 91%;
|
||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||
--sidebar-background: 222 47% 11%;
|
||||
--sidebar-foreground: 215 20% 65%;
|
||||
--sidebar-primary: 161 94% 30%;
|
||||
--sidebar-primary-foreground: 0 0% 100%;
|
||||
--sidebar-accent: 217 33% 17%;
|
||||
--sidebar-accent-foreground: 210 40% 98%;
|
||||
--sidebar-border: 217 33% 20%;
|
||||
--sidebar-ring: 161 94% 30%;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 240 10% 3.9%;
|
||||
--foreground: 0 0% 98%;
|
||||
--card: 240 10% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
--popover: 240 10% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 240 5.9% 10%;
|
||||
--secondary: 240 3.7% 15.9%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: 240 3.7% 15.9%;
|
||||
--muted-foreground: 240 5% 64.9%;
|
||||
--accent: 240 3.7% 15.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--background: 222 47% 5%;
|
||||
--foreground: 210 40% 98%;
|
||||
--card: 222 47% 11%;
|
||||
--card-foreground: 210 40% 98%;
|
||||
--popover: 222 47% 11%;
|
||||
--popover-foreground: 210 40% 98%;
|
||||
--primary: 160 84% 39%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--secondary: 217 33% 17%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
--muted: 217 33% 17%;
|
||||
--muted-foreground: 215 20% 65%;
|
||||
--accent: 217 33% 17%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
--destructive: 0 72% 51%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 240 3.7% 15.9%;
|
||||
--input: 240 3.7% 15.9%;
|
||||
--ring: 240 4.9% 83.9%;
|
||||
--sidebar-background: 240 5.9% 10%;
|
||||
--sidebar-foreground: 240 4.8% 95.9%;
|
||||
--sidebar-primary: 224.3 76.3% 48%;
|
||||
--success: 160 84% 45%;
|
||||
--success-foreground: 0 0% 100%;
|
||||
--warning: 38 92% 50%;
|
||||
--warning-foreground: 0 0% 100%;
|
||||
--info: 217 91% 60%;
|
||||
--info-foreground: 0 0% 100%;
|
||||
--border: 217 33% 20%;
|
||||
--input: 217 26% 28%;
|
||||
--ring: 160 84% 39%;
|
||||
--sidebar-background: 222 47% 8%;
|
||||
--sidebar-foreground: 215 20% 65%;
|
||||
--sidebar-primary: 160 84% 39%;
|
||||
--sidebar-primary-foreground: 0 0% 100%;
|
||||
--sidebar-accent: 240 3.7% 15.9%;
|
||||
--sidebar-accent-foreground: 240 4.8% 95.9%;
|
||||
--sidebar-border: 240 3.7% 15.9%;
|
||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||
--sidebar-accent: 217 33% 17%;
|
||||
--sidebar-accent-foreground: 210 40% 98%;
|
||||
--sidebar-border: 217 33% 20%;
|
||||
--sidebar-ring: 160 84% 39%;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,4 +90,4 @@
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// 凭证存储统一出口 — 全项目对 token / 用户信息的读写必须经过这里,
|
||||
// 禁止组件直接操作 localStorage(避免 key 散落与多处重复实现)。
|
||||
// key 采用命名空间 opsxloki.auth.*(双端一致性约定,见开发标准 08 章)。
|
||||
import type { User } from '@/types';
|
||||
|
||||
const TOKEN_KEY = 'opsxloki.auth.token';
|
||||
const REFRESH_TOKEN_KEY = 'opsxloki.auth.refresh-token';
|
||||
const USER_KEY = 'opsxloki.auth.user';
|
||||
|
||||
export interface TokenPair {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export function getAccessToken(): string | null {
|
||||
return localStorage.getItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function getRefreshToken(): string | null {
|
||||
return localStorage.getItem(REFRESH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function getUser(): User | null {
|
||||
const raw = localStorage.getItem(USER_KEY);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return JSON.parse(raw) as User;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveAuth(pair: TokenPair, user: User): void {
|
||||
localStorage.setItem(TOKEN_KEY, pair.accessToken);
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, pair.refreshToken);
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user));
|
||||
}
|
||||
|
||||
export function saveTokenPair(pair: TokenPair): void {
|
||||
localStorage.setItem(TOKEN_KEY, pair.accessToken);
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, pair.refreshToken);
|
||||
}
|
||||
|
||||
export function clearAuth(): void {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
|
||||
export function isLoggedIn(): boolean {
|
||||
return getAccessToken() !== null;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// redirect 回跳安全校验 — 仅允许同源相对路径,防开放重定向(开发标准 04 章)。
|
||||
export function getSafeRedirectUrl(redirect: string | null | undefined): string {
|
||||
if (!redirect) return '/';
|
||||
// 禁止协议绝对地址与协议相对地址(//evil.com、https://evil.com)
|
||||
if (/^https?:\/\//i.test(redirect) || redirect.startsWith('//')) return '/';
|
||||
return redirect.startsWith('/') ? redirect : `/${redirect}`;
|
||||
}
|
||||
|
||||
/** 从 location.search 中提取并校验 redirect 参数 */
|
||||
export function readRedirectParam(search: string): string {
|
||||
return getSafeRedirectUrl(new URLSearchParams(search).get('redirect'));
|
||||
}
|
||||
+34
-3
@@ -1,16 +1,47 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router'
|
||||
import { ThemeProvider } from 'next-themes'
|
||||
import './index.css'
|
||||
|
||||
// 一次性迁移旧 LokiDeploy 时代的 localStorage key → opsxloki.*(保留登录态/主题/折叠/查询历史)
|
||||
function migrateStorage() {
|
||||
const pairs: Array<[string, string]> = [
|
||||
['lokideploy.auth.token', 'opsxloki.auth.token'],
|
||||
['lokideploy.auth.refresh-token', 'opsxloki.auth.refresh-token'],
|
||||
['lokideploy.auth.user', 'opsxloki.auth.user'],
|
||||
['lokideploy.theme.mode', 'opsxloki.theme.mode'],
|
||||
['lokideploy.layout.collapsed', 'opsxloki.layout.collapsed'],
|
||||
['lokideploy_log_query_history', 'opsxloki_log_query_history'],
|
||||
]
|
||||
for (const [oldKey, newKey] of pairs) {
|
||||
const v = localStorage.getItem(oldKey)
|
||||
if (v !== null && localStorage.getItem(newKey) === null) {
|
||||
localStorage.setItem(newKey, v)
|
||||
localStorage.removeItem(oldKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
migrateStorage()
|
||||
import App from './App.tsx'
|
||||
import ErrorBoundary from '@/components/ErrorBoundary'
|
||||
|
||||
// 主题:class 策略(.dark),三态 light/dark/system,key 带命名空间;
|
||||
// next-themes 会在挂载前注入主题脚本,避免暗色首帧白闪
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<ErrorBoundary>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="system"
|
||||
storageKey="opsxloki.theme.mode"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</ThemeProvider>
|
||||
</ErrorBoundary>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -1,543 +0,0 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Server,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Trash2,
|
||||
Eye,
|
||||
Key,
|
||||
FileKey,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { clusterApi } from '@/api'
|
||||
import { StatusBadge } from '@/components/StatusBadge'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { PageHeader } from '@/components/PageHeader'
|
||||
import { toast } from 'sonner'
|
||||
import type { Cluster, ClusterInfo } from '@/types'
|
||||
|
||||
// 从 kubeconfig 文本自动提取 server 地址
|
||||
const parseApiServer = (kubeconfig: string): string => {
|
||||
const m = kubeconfig.match(/^\s*server:\s*(\S+)/m)
|
||||
return m ? m[1] : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Clusters 页面 - 优化版本
|
||||
*
|
||||
* 优化点:
|
||||
* 1. React.memo 包裹组件
|
||||
* 2. 所有操作函数使用 useCallback 缓存
|
||||
* 3. alert() 替换为 sonner toast
|
||||
* 4. setTimeout 使用 ref 管理,添加清理函数
|
||||
* 5. 使用 StatusBadge 公共组件
|
||||
* 6. 使用 PageHeader、EmptyState、LoadingSpinner 公共组件
|
||||
*/
|
||||
const Clusters = memo(function Clusters() {
|
||||
const [clusters, setClusters] = useState<Cluster[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [detailOpen, setDetailOpen] = useState(false)
|
||||
const [selectedCluster, setSelectedCluster] = useState<Cluster | null>(null)
|
||||
const [clusterInfo, setClusterInfo] = useState<ClusterInfo | null>(null)
|
||||
const [validating, setValidating] = useState<number | null>(null)
|
||||
|
||||
// Form state
|
||||
const [name, setName] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [configType, setConfigType] = useState<'kubeconfig' | 'token'>('kubeconfig')
|
||||
const [kubeconfig, setKubeconfig] = useState('')
|
||||
const [apiServer, setApiServer] = useState('')
|
||||
const [token, setToken] = useState('')
|
||||
const [context, setContext] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
// 定时器管理ref
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
timeoutsRef.current.forEach((id) => clearTimeout(id))
|
||||
}
|
||||
}, [])
|
||||
|
||||
const addTimeout = useCallback((cb: () => void, delay: number) => {
|
||||
const id = setTimeout(cb, delay)
|
||||
timeoutsRef.current.push(id)
|
||||
return id
|
||||
}, [])
|
||||
|
||||
const loadClusters = useCallback(async () => {
|
||||
try {
|
||||
const res = await clusterApi.list(1, 100)
|
||||
setClusters(res.list)
|
||||
} catch (err) {
|
||||
console.error('Failed to load clusters:', err)
|
||||
toast.error('加载集群数据失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadClusters()
|
||||
}, [loadClusters])
|
||||
|
||||
const resetForm = useCallback(() => {
|
||||
setName('')
|
||||
setDescription('')
|
||||
setConfigType('kubeconfig')
|
||||
setKubeconfig('')
|
||||
setApiServer('')
|
||||
setToken('')
|
||||
setContext('')
|
||||
}, [])
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
// 校验
|
||||
if (configType === 'kubeconfig' && !kubeconfig.trim()) {
|
||||
toast.error('请填写 kubeconfig 内容')
|
||||
return
|
||||
}
|
||||
if (configType === 'token' && (!apiServer.trim() || !token.trim())) {
|
||||
toast.error('Token 接入方式需要填写 API Server 和 Token')
|
||||
return
|
||||
}
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await clusterApi.create({
|
||||
name,
|
||||
description,
|
||||
configType,
|
||||
apiServer: configType === 'token' ? apiServer : undefined,
|
||||
kubeconfig: configType === 'kubeconfig' ? kubeconfig : undefined,
|
||||
token: configType === 'token' ? token : undefined,
|
||||
context,
|
||||
})
|
||||
setOpen(false)
|
||||
resetForm()
|
||||
loadClusters()
|
||||
toast.success('集群添加成功')
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '创建集群失败'
|
||||
toast.error(message)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
},
|
||||
[name, description, configType, kubeconfig, apiServer, token, context, resetForm, loadClusters]
|
||||
)
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (id: number) => {
|
||||
if (!confirm('确定删除此集群?')) return
|
||||
try {
|
||||
await clusterApi.remove(id)
|
||||
loadClusters()
|
||||
toast.success('集群已删除')
|
||||
} catch (err) {
|
||||
console.error('Failed to delete cluster:', err)
|
||||
toast.error('删除集群失败')
|
||||
}
|
||||
},
|
||||
[loadClusters]
|
||||
)
|
||||
|
||||
const handleValidate = useCallback(
|
||||
async (id: number) => {
|
||||
setValidating(id)
|
||||
try {
|
||||
await clusterApi.validate(id)
|
||||
addTimeout(loadClusters, 3000)
|
||||
toast.success('验证指令已发送')
|
||||
} catch (err) {
|
||||
console.error('Failed to validate cluster:', err)
|
||||
toast.error('验证失败')
|
||||
} finally {
|
||||
addTimeout(() => setValidating(null), 3000)
|
||||
}
|
||||
},
|
||||
[loadClusters, addTimeout]
|
||||
)
|
||||
|
||||
const viewClusterInfo = useCallback(async (cluster: Cluster) => {
|
||||
setSelectedCluster(cluster)
|
||||
setClusterInfo(null)
|
||||
setDetailOpen(true)
|
||||
try {
|
||||
const info = await clusterApi.getInfo(cluster.id)
|
||||
setClusterInfo(info)
|
||||
} catch (err) {
|
||||
console.error('Failed to get cluster info:', err)
|
||||
toast.error('加载集群详情失败')
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<PageHeader
|
||||
title="集群管理"
|
||||
description="管理用于 Loki 部署的 Kubernetes 集群"
|
||||
action={
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-emerald-600 hover:bg-emerald-700">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
添加集群
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>添加 Kubernetes 集群</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">集群名称 *</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="production-cluster"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">描述</Label>
|
||||
<Input
|
||||
id="description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="生产环境日志集群"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>接入方式</Label>
|
||||
<Tabs
|
||||
value={configType}
|
||||
onValueChange={(v) => setConfigType(v as 'kubeconfig' | 'token')}
|
||||
>
|
||||
<TabsList>
|
||||
<TabsTrigger value="kubeconfig">
|
||||
<FileKey className="w-3.5 h-3.5 mr-1" /> Kubeconfig
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="token">
|
||||
<Key className="w-3.5 h-3.5 mr-1" /> Token
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="kubeconfig" className="space-y-2 pt-2">
|
||||
<Label htmlFor="kubeconfig">Kubeconfig 内容 *</Label>
|
||||
<Textarea
|
||||
id="kubeconfig"
|
||||
value={kubeconfig}
|
||||
onChange={(e) => setKubeconfig(e.target.value)}
|
||||
placeholder="粘贴 kubeconfig YAML(自动识别 API Server)..."
|
||||
className="min-h-[200px] font-mono text-xs"
|
||||
/>
|
||||
{kubeconfig && parseApiServer(kubeconfig) && (
|
||||
<p className="text-xs text-emerald-600">
|
||||
已识别 API Server:{parseApiServer(kubeconfig)}
|
||||
</p>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="token" className="space-y-2 pt-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="apiServer">API Server *</Label>
|
||||
<Input
|
||||
id="apiServer"
|
||||
value={apiServer}
|
||||
onChange={(e) => setApiServer(e.target.value)}
|
||||
placeholder="https://10.0.0.1:6443"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="token">Token *</Label>
|
||||
<Textarea
|
||||
id="token"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
placeholder="粘贴 Service Account Token..."
|
||||
className="min-h-[120px] font-mono text-xs"
|
||||
/>
|
||||
<p className="text-xs text-slate-400">
|
||||
采用 insecure 模式,便于内网/自签证书集群接入
|
||||
</p>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{configType === 'kubeconfig' && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="context">上下文(可选)</Label>
|
||||
<Input
|
||||
id="context"
|
||||
value={context}
|
||||
onChange={(e) => setContext(e.target.value)}
|
||||
placeholder="留空则使用默认上下文"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-emerald-600 hover:bg-emerald-700"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '添加中...' : '添加集群'}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Clusters Grid */}
|
||||
{loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : clusters.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Server}
|
||||
title="暂无集群"
|
||||
description="添加第一个 Kubernetes 集群开始使用"
|
||||
/>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{clusters.map((cluster) => (
|
||||
<ClusterCard
|
||||
key={cluster.id}
|
||||
cluster={cluster}
|
||||
validating={validating}
|
||||
onViewInfo={viewClusterInfo}
|
||||
onValidate={handleValidate}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Cluster Detail Dialog */}
|
||||
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
|
||||
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Server className="w-5 h-5 text-blue-500" />
|
||||
{selectedCluster?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{clusterInfo ? (
|
||||
<ClusterDetail info={clusterInfo} />
|
||||
) : (
|
||||
<LoadingSpinner className="h-32" />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:集群卡片
|
||||
interface ClusterCardProps {
|
||||
cluster: Cluster
|
||||
validating: number | null
|
||||
onViewInfo: (c: Cluster) => void
|
||||
onValidate: (id: number) => void
|
||||
onDelete: (id: number) => void
|
||||
}
|
||||
|
||||
const ClusterCard = memo(function ClusterCard({
|
||||
cluster,
|
||||
validating,
|
||||
onViewInfo,
|
||||
onValidate,
|
||||
onDelete,
|
||||
}: ClusterCardProps) {
|
||||
return (
|
||||
<Card className="border-slate-200 dark:border-slate-800 hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Server className="w-5 h-5 text-blue-500 flex-shrink-0" />
|
||||
<h3 className="font-semibold text-slate-800 dark:text-white truncate">
|
||||
{cluster.name}
|
||||
</h3>
|
||||
</div>
|
||||
<StatusBadge status={cluster.status} />
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-slate-500 mb-3 line-clamp-2">
|
||||
{cluster.description || '无描述'}
|
||||
</p>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-slate-500 mb-4">
|
||||
<InfoRow
|
||||
label="接入方式"
|
||||
value={cluster.configType === 'token' ? 'Token' : 'Kubeconfig'}
|
||||
/>
|
||||
{cluster.apiServer && (
|
||||
<InfoRow
|
||||
label="API Server"
|
||||
value={cluster.apiServer}
|
||||
valueClass="truncate max-w-[150px]"
|
||||
/>
|
||||
)}
|
||||
<InfoRow label="版本" value={cluster.version || '未知'} />
|
||||
<InfoRow label="节点数" value={String(cluster.nodesCount || 0)} />
|
||||
<InfoRow
|
||||
label="最后连接"
|
||||
value={
|
||||
cluster.lastConnected
|
||||
? new Date(cluster.lastConnected).toLocaleString()
|
||||
: '从未'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-3 border-t border-slate-100 dark:border-slate-800">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onViewInfo(cluster)}
|
||||
>
|
||||
<Eye className="w-3 h-3 mr-1" />
|
||||
详情
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onValidate(cluster.id)}
|
||||
disabled={validating === cluster.id}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3 h-3 mr-1 ${validating === cluster.id ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
验证
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => onDelete(cluster.id)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:信息行
|
||||
const InfoRow = memo(function InfoRow({
|
||||
label,
|
||||
value,
|
||||
valueClass,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
valueClass?: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex justify-between">
|
||||
<span>{label}</span>
|
||||
<span className={`font-medium text-slate-700 dark:text-slate-300 ${valueClass || ''}`}>
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:集群详情
|
||||
const ClusterDetail = memo(function ClusterDetail({ info }: { info: ClusterInfo }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
|
||||
<p className="text-xs text-slate-500">版本</p>
|
||||
<p className="text-sm font-medium">{info.version || '未知'}</p>
|
||||
</div>
|
||||
<div className="p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
|
||||
<p className="text-xs text-slate-500">当前上下文</p>
|
||||
<p className="text-sm font-medium">{info.currentContext || '默认'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-2">节点({info.nodes.length})</h4>
|
||||
<div className="space-y-2">
|
||||
{info.nodes.map((node, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="p-3 border border-slate-200 dark:border-slate-700 rounded-lg"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium text-sm">{node.name}</span>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-full text-xs ${
|
||||
node.status === 'Ready'
|
||||
? 'bg-emerald-100 text-emerald-700'
|
||||
: 'bg-red-100 text-red-700'
|
||||
}`}
|
||||
>
|
||||
{node.status === 'Ready' ? '就绪' : '未就绪'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 mt-2 text-xs text-slate-500">
|
||||
<span>IP:{node.internalIP}</span>
|
||||
<span>系统:{node.os}/{node.arch}</span>
|
||||
<span>版本:{node.version}</span>
|
||||
</div>
|
||||
{node.roles.length > 0 && (
|
||||
<div className="flex gap-1 mt-2">
|
||||
{node.roles.map((role, ridx) => (
|
||||
<span
|
||||
key={ridx}
|
||||
className="px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded text-xs"
|
||||
>
|
||||
{role}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-2">命名空间</h4>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{info.namespaces.map((ns, idx) => (
|
||||
<span
|
||||
key={idx}
|
||||
className="px-2 py-0.5 bg-slate-100 dark:bg-slate-800 rounded text-xs"
|
||||
>
|
||||
{ns}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Clusters
|
||||
@@ -1,503 +0,0 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
RadioTower,
|
||||
Plus,
|
||||
Trash2,
|
||||
Upload,
|
||||
Download,
|
||||
Server,
|
||||
Monitor,
|
||||
Cloud,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { collectorApi, deploymentApi, clusterApi, hostApi } from '@/api'
|
||||
import { statusLabel } from '@/lib/utils'
|
||||
import { StatusBadge } from '@/components/StatusBadge'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { PageHeader } from '@/components/PageHeader'
|
||||
import { toast } from 'sonner'
|
||||
import type { Collector, LokiDeployment, Cluster, Host } from '@/types'
|
||||
|
||||
// 采集器类型元数据 - 常量提取
|
||||
const COLLECTOR_TYPE_META: Record<string, { label: string; icon: typeof Server; color: string }> = {
|
||||
'host-promtail': { label: '主机 Promtail', icon: Monitor, color: 'bg-purple-100 text-purple-700' },
|
||||
'k8s-daemonset': { label: 'K8s DaemonSet', icon: Cloud, color: 'bg-blue-100 text-blue-700' },
|
||||
'k8s-fluentbit-sidecar': { label: 'K8s Sidecar', icon: Server, color: 'bg-cyan-100 text-cyan-700' },
|
||||
}
|
||||
|
||||
const COLLECTOR_TYPES = [
|
||||
{ value: 'host-promtail' as const, label: '主机 Promtail(SSH)' },
|
||||
{ value: 'k8s-daemonset' as const, label: 'K8s Promtail DaemonSet' },
|
||||
{ value: 'k8s-fluentbit-sidecar' as const, label: 'K8s Fluent Bit Sidecar' },
|
||||
]
|
||||
|
||||
/**
|
||||
* Collectors 页面 - 优化版本
|
||||
*
|
||||
* 优化点:
|
||||
* 1. React.memo 包裹组件
|
||||
* 2. 所有操作函数使用 useCallback 缓存
|
||||
* 3. alert() 替换为 sonner toast
|
||||
* 4. setTimeout 使用 ref 管理,添加清理
|
||||
* 5. 使用公共组件替代重复代码
|
||||
* 6. 常量映射提取到组件外部
|
||||
*/
|
||||
const Collectors = memo(function Collectors() {
|
||||
const [collectors, setCollectors] = useState<Collector[]>([])
|
||||
const [deployments, setDeployments] = useState<LokiDeployment[]>([])
|
||||
const [clusters, setClusters] = useState<Cluster[]>([])
|
||||
const [hosts, setHosts] = useState<Host[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [busy, setBusy] = useState<number | null>(null)
|
||||
|
||||
// Form state
|
||||
const [name, setName] = useState('')
|
||||
const [collectorType, setCollectorType] = useState<'host-promtail' | 'k8s-daemonset' | 'k8s-fluentbit-sidecar'>('host-promtail')
|
||||
const [lokiID, setLokiID] = useState('')
|
||||
const [hostID, setHostID] = useState('')
|
||||
const [clusterID, setClusterID] = useState('')
|
||||
const [targetDeployment, setTargetDeployment] = useState('')
|
||||
const [namespace, setNamespace] = useState('')
|
||||
const [logPath, setLogPath] = useState('')
|
||||
const [labels, setLabels] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
timeoutsRef.current.forEach((id) => clearTimeout(id))
|
||||
}
|
||||
}, [])
|
||||
|
||||
const addTimeout = useCallback((cb: () => void, delay: number) => {
|
||||
const id = setTimeout(cb, delay)
|
||||
timeoutsRef.current.push(id)
|
||||
return id
|
||||
}, [])
|
||||
|
||||
const loadAll = useCallback(async () => {
|
||||
try {
|
||||
const [cRes, dRes, clRes, hRes] = await Promise.all([
|
||||
collectorApi.list(1, 100),
|
||||
deploymentApi.list(1, 100),
|
||||
clusterApi.list(1, 100),
|
||||
hostApi.list(1, 100),
|
||||
])
|
||||
setCollectors(cRes.list)
|
||||
setDeployments(dRes.list)
|
||||
setClusters(clRes.list)
|
||||
setHosts(hRes.list)
|
||||
} catch (err) {
|
||||
console.error('Failed to load collectors:', err)
|
||||
toast.error('加载采集器数据失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadAll()
|
||||
}, [loadAll])
|
||||
|
||||
const resetForm = useCallback(() => {
|
||||
setName('')
|
||||
setCollectorType('host-promtail')
|
||||
setLokiID('')
|
||||
setHostID('')
|
||||
setClusterID('')
|
||||
setTargetDeployment('')
|
||||
setNamespace('')
|
||||
setLogPath('')
|
||||
setLabels('')
|
||||
}, [])
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!lokiID) {
|
||||
toast.error('请选择关联的 Loki 部署')
|
||||
return
|
||||
}
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await collectorApi.create({
|
||||
name,
|
||||
type: collectorType,
|
||||
lokiDeploymentID: Number(lokiID),
|
||||
hostID: collectorType === 'host-promtail' && hostID ? Number(hostID) : undefined,
|
||||
clusterID: collectorType !== 'host-promtail' && clusterID ? Number(clusterID) : undefined,
|
||||
targetDeployment: collectorType === 'k8s-fluentbit-sidecar' ? targetDeployment : undefined,
|
||||
namespace: collectorType !== 'host-promtail' ? namespace : undefined,
|
||||
logPath,
|
||||
labels,
|
||||
})
|
||||
setOpen(false)
|
||||
resetForm()
|
||||
loadAll()
|
||||
toast.success('采集器创建成功')
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '创建采集器失败'
|
||||
toast.error(message)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
},
|
||||
[name, collectorType, lokiID, hostID, clusterID, targetDeployment, namespace, logPath, labels, resetForm, loadAll]
|
||||
)
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (id: number) => {
|
||||
if (!confirm('确定删除此采集器?(将自动卸载)')) return
|
||||
try {
|
||||
await collectorApi.remove(id)
|
||||
loadAll()
|
||||
toast.success('采集器已删除')
|
||||
} catch (err) {
|
||||
console.error('Failed to delete collector:', err)
|
||||
toast.error('删除采集器失败')
|
||||
}
|
||||
},
|
||||
[loadAll]
|
||||
)
|
||||
|
||||
const handleAction = useCallback(
|
||||
async (id: number, action: 'install' | 'uninstall') => {
|
||||
setBusy(id)
|
||||
try {
|
||||
await collectorApi[action](id)
|
||||
addTimeout(loadAll, 3000)
|
||||
toast.success(action === 'install' ? '部署指令已发送' : '卸载指令已发送')
|
||||
} catch (err) {
|
||||
console.error('Collector action failed:', err)
|
||||
toast.error(action === 'install' ? '部署失败' : '卸载失败')
|
||||
} finally {
|
||||
addTimeout(() => setBusy(null), 3000)
|
||||
}
|
||||
},
|
||||
[loadAll, addTimeout]
|
||||
)
|
||||
|
||||
const isHostType = collectorType === 'host-promtail'
|
||||
const isK8sType = collectorType !== 'host-promtail'
|
||||
const isSidecarType = collectorType === 'k8s-fluentbit-sidecar'
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="部署客户端"
|
||||
description="部署日志采集器,将日志推送到关联的 Loki"
|
||||
action={
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-emerald-600 hover:bg-emerald-700">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
新建采集器
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建日志采集器</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="c-name">名称 *</Label>
|
||||
<Input
|
||||
id="c-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="app-logs-collector"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>采集器类型</Label>
|
||||
<Select
|
||||
value={collectorType}
|
||||
onValueChange={(v) =>
|
||||
setCollectorType(v as 'host-promtail' | 'k8s-daemonset' | 'k8s-fluentbit-sidecar')
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{COLLECTOR_TYPES.map((t) => (
|
||||
<SelectItem key={t.value} value={t.value}>
|
||||
{t.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>关联 Loki 部署 *</Label>
|
||||
<Select value={lokiID} onValueChange={setLokiID}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择已部署的 Loki(推送目标)" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{deployments.map((d) => (
|
||||
<SelectItem key={d.id} value={String(d.id)}>
|
||||
{d.name}({statusLabel(d.status)})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{isHostType && (
|
||||
<div className="space-y-2">
|
||||
<Label>目标主机 *</Label>
|
||||
<Select value={hostID} onValueChange={setHostID}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择主机" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{hosts.map((h) => (
|
||||
<SelectItem key={h.id} value={String(h.id)}>
|
||||
{h.name}({h.hostIP})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isK8sType && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label>目标集群 *</Label>
|
||||
<Select value={clusterID} onValueChange={setClusterID}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择集群" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{clusters.map((c) => (
|
||||
<SelectItem key={c.id} value={String(c.id)}>
|
||||
{c.name}({statusLabel(c.status)})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="c-ns">命名空间</Label>
|
||||
<Input
|
||||
id="c-ns"
|
||||
value={namespace}
|
||||
onChange={(e) => setNamespace(e.target.value)}
|
||||
placeholder={collectorType === 'k8s-daemonset' ? 'logging' : 'default'}
|
||||
/>
|
||||
</div>
|
||||
{isSidecarType && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="c-deploy">目标 Deployment *</Label>
|
||||
<Input
|
||||
id="c-deploy"
|
||||
value={targetDeployment}
|
||||
onChange={(e) => setTargetDeployment(e.target.value)}
|
||||
placeholder="my-app"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="c-log">采集日志路径</Label>
|
||||
<Input
|
||||
id="c-log"
|
||||
value={logPath}
|
||||
onChange={(e) => setLogPath(e.target.value)}
|
||||
placeholder={isHostType ? '/var/log/*.log' : '/var/log/app/*.log'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-emerald-600 hover:bg-emerald-700"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '创建中...' : '创建并部署'}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Collectors List */}
|
||||
{loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : collectors.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={RadioTower}
|
||||
title="暂无采集器"
|
||||
description="新建一个日志采集器,关联已部署的 Loki"
|
||||
/>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{collectors.map((c) => (
|
||||
<CollectorCard
|
||||
key={c.id}
|
||||
collector={c}
|
||||
busy={busy}
|
||||
onInstall={(id) => handleAction(id, 'install')}
|
||||
onUninstall={(id) => handleAction(id, 'uninstall')}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:采集器卡片
|
||||
interface CollectorCardProps {
|
||||
collector: Collector
|
||||
busy: number | null
|
||||
onInstall: (id: number) => void
|
||||
onUninstall: (id: number) => void
|
||||
onDelete: (id: number) => void
|
||||
}
|
||||
|
||||
const CollectorCard = memo(function CollectorCard({
|
||||
collector,
|
||||
busy,
|
||||
onInstall,
|
||||
onUninstall,
|
||||
onDelete,
|
||||
}: CollectorCardProps) {
|
||||
const meta = COLLECTOR_TYPE_META[collector.type] || {
|
||||
label: collector.type,
|
||||
icon: RadioTower,
|
||||
color: 'bg-slate-100 text-slate-600',
|
||||
}
|
||||
const Icon = meta.icon
|
||||
const isBusy = busy === collector.id
|
||||
|
||||
return (
|
||||
<Card className="border-slate-200 dark:border-slate-800 hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Icon className="w-5 h-5 text-emerald-600 flex-shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<h3 className="font-semibold text-slate-800 dark:text-white truncate">
|
||||
{collector.name}
|
||||
</h3>
|
||||
<p className="text-xs text-slate-500">
|
||||
关联 Loki:{collector.lokiDeployment?.name || '未知'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<StatusBadge status={collector.status} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-slate-500 mb-3">
|
||||
<div className="flex justify-between">
|
||||
<span>类型</span>
|
||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${meta.color}`}>
|
||||
{meta.label}
|
||||
</span>
|
||||
</div>
|
||||
{collector.host && (
|
||||
<InfoRow label="主机" value={`${collector.host.name}(${collector.host.hostIP})`} />
|
||||
)}
|
||||
{collector.cluster && (
|
||||
<InfoRow label="集群" value={collector.cluster.name} />
|
||||
)}
|
||||
{collector.targetDeployment && (
|
||||
<InfoRow label="目标 Deployment" value={collector.targetDeployment} />
|
||||
)}
|
||||
{collector.namespace && <InfoRow label="命名空间" value={collector.namespace} />}
|
||||
{collector.logPath && (
|
||||
<InfoRow label="日志路径" value={collector.logPath} />
|
||||
)}
|
||||
{collector.statusMessage && (
|
||||
<div className="p-2 bg-slate-50 dark:bg-slate-800 rounded text-xs mt-1">
|
||||
{collector.statusMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-3 border-t border-slate-100 dark:border-slate-800">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onInstall(collector.id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
<Upload className="w-3 h-3 mr-1" />
|
||||
{isBusy ? '处理中...' : '部署'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onUninstall(collector.id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
<Download className="w-3 h-3 mr-1" />
|
||||
卸载
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => onDelete(collector.id)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:信息行
|
||||
const InfoRow = memo(function InfoRow({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex justify-between">
|
||||
<span>{label}</span>
|
||||
<span className="font-medium text-slate-700 dark:text-slate-300 truncate max-w-[200px]">
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Collectors
|
||||
@@ -1,404 +0,0 @@
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import {
|
||||
Rocket,
|
||||
Server,
|
||||
Monitor,
|
||||
Activity,
|
||||
TrendingUp,
|
||||
CheckCircle,
|
||||
} from 'lucide-react'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { deploymentApi, clusterApi, hostApi } from '@/api'
|
||||
import { statusLabel } from '@/lib/utils'
|
||||
import { StatusIcon, getStatusColorClass } from '@/components/StatusBadge'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import type { DashboardStats, LokiDeployment, Cluster, Host } from '@/types'
|
||||
|
||||
// 统计卡片数据常量
|
||||
const STATS_CONFIG = [
|
||||
{
|
||||
key: 'deployments' as const,
|
||||
label: '部署总数',
|
||||
icon: Rocket,
|
||||
iconColor: 'text-emerald-600',
|
||||
iconBg: 'bg-emerald-100 dark:bg-emerald-900/30',
|
||||
getValue: (s: DashboardStats | null) => s?.totalDeployments || 0,
|
||||
subLabel: (s: DashboardStats | null) => `${s?.running || 0} 个运行中`,
|
||||
subIcon: TrendingUp,
|
||||
subColor: 'text-emerald-500',
|
||||
subTextColor: 'text-emerald-600',
|
||||
},
|
||||
{
|
||||
key: 'clusters' as const,
|
||||
label: '集群',
|
||||
icon: Server,
|
||||
iconColor: 'text-blue-600',
|
||||
iconBg: 'bg-blue-100 dark:bg-blue-900/30',
|
||||
getValue: (s: DashboardStats | null) => s?.clusterCount || 0,
|
||||
subLabel: () => '已接入',
|
||||
subIcon: CheckCircle,
|
||||
subColor: 'text-emerald-500',
|
||||
subTextColor: 'text-slate-500',
|
||||
},
|
||||
{
|
||||
key: 'hosts' as const,
|
||||
label: '主机',
|
||||
icon: Monitor,
|
||||
iconColor: 'text-purple-600',
|
||||
iconBg: 'bg-purple-100 dark:bg-purple-900/30',
|
||||
getValue: (s: DashboardStats | null) => s?.hostCount || 0,
|
||||
subLabel: () => 'SSH 就绪',
|
||||
subIcon: CheckCircle,
|
||||
subColor: 'text-emerald-500',
|
||||
subTextColor: 'text-slate-500',
|
||||
},
|
||||
{
|
||||
key: 'status' as const,
|
||||
label: '状态',
|
||||
icon: Activity,
|
||||
iconColor: 'text-orange-600',
|
||||
iconBg: 'bg-orange-100 dark:bg-orange-900/30',
|
||||
getValue: () => 0, // 状态卡片使用特殊渲染
|
||||
isStatusCard: true,
|
||||
},
|
||||
]
|
||||
|
||||
const STATUS_ITEMS = [
|
||||
{ key: 'running', label: '运行中', colorClass: 'text-emerald-600' },
|
||||
{ key: 'failed', label: '失败', colorClass: 'text-red-600' },
|
||||
{ key: 'pending', label: '等待中', colorClass: 'text-amber-600' },
|
||||
] as const
|
||||
|
||||
const REFRESH_INTERVAL = 10000 // 10秒自动刷新
|
||||
|
||||
/**
|
||||
* Dashboard 页面 - 全面优化版本
|
||||
*
|
||||
* 优化点:
|
||||
* 1. 使用 React.memo 包裹组件,避免不必要的重渲染
|
||||
* 2. 状态函数使用 useMemo 缓存(替代原来的getStatusIcon/getStatusColor)
|
||||
* 3. 数据加载使用 useCallback 缓存引用
|
||||
* 4. 自动刷新定时器添加清理函数,防止内存泄漏
|
||||
* 5. 使用 StatusBadge/StatusIcon 公共组件替代重复的状态渲染逻辑
|
||||
* 6. 提取常量配置避免重复创建
|
||||
*/
|
||||
const Dashboard = memo(function Dashboard() {
|
||||
const [stats, setStats] = useState<DashboardStats | null>(null)
|
||||
const [deployments, setDeployments] = useState<LokiDeployment[]>([])
|
||||
const [clusters, setClusters] = useState<Cluster[]>([])
|
||||
const [hosts, setHosts] = useState<Host[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const navigate = useNavigate()
|
||||
|
||||
// 使用ref追踪组件是否已卸载,防止内存泄漏
|
||||
const isMountedRef = useRef(true)
|
||||
// 使用ref存储定时器ID以便清理
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
|
||||
// 数据加载函数 - useCallback缓存引用
|
||||
const loadDashboard = useCallback(async () => {
|
||||
// 如果组件已卸载,不执行状态更新
|
||||
if (!isMountedRef.current) return
|
||||
|
||||
try {
|
||||
const [statsRes, deployRes, clusterRes, hostRes] = await Promise.all([
|
||||
deploymentApi.stats(),
|
||||
deploymentApi.list(1, 5),
|
||||
clusterApi.list(1, 5),
|
||||
hostApi.list(1, 5),
|
||||
])
|
||||
|
||||
// 再次检查组件是否仍挂载
|
||||
if (isMountedRef.current) {
|
||||
setStats(statsRes)
|
||||
setDeployments(deployRes.list)
|
||||
setClusters(clusterRes.list)
|
||||
setHosts(hostRes.list)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load dashboard:', err)
|
||||
} finally {
|
||||
if (isMountedRef.current) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
// 初始化加载 + 自动刷新定时器
|
||||
useEffect(() => {
|
||||
isMountedRef.current = true
|
||||
|
||||
// 立即加载数据
|
||||
loadDashboard()
|
||||
|
||||
// 设置自动刷新定时器
|
||||
intervalRef.current = setInterval(loadDashboard, REFRESH_INTERVAL)
|
||||
|
||||
// 清理函数:组件卸载时清除定时器和标记
|
||||
return () => {
|
||||
isMountedRef.current = false
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current)
|
||||
intervalRef.current = null
|
||||
}
|
||||
}
|
||||
}, [loadDashboard])
|
||||
|
||||
// 缓存导航处理函数
|
||||
const navigateTo = useCallback(
|
||||
(path: string) => () => navigate(path),
|
||||
[navigate]
|
||||
)
|
||||
|
||||
// 渲染状态概览数值
|
||||
const statusSummary = useMemo(() => {
|
||||
if (!stats) return null
|
||||
return STATUS_ITEMS.map((item) => (
|
||||
<div key={item.key} className="text-center">
|
||||
<p className={`text-lg font-bold ${item.colorClass}`}>
|
||||
{(stats[item.key as keyof DashboardStats] as number) || 0}
|
||||
</p>
|
||||
<p className="text-[10px] text-slate-400">{item.label}</p>
|
||||
</div>
|
||||
))
|
||||
}, [stats])
|
||||
|
||||
if (loading) {
|
||||
return <LoadingSpinner className="h-64" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{STATS_CONFIG.slice(0, 3).map((config) => {
|
||||
const Icon = config.icon
|
||||
const SubIcon = config.subIcon
|
||||
return (
|
||||
<Card key={config.key} className="border-slate-200 dark:border-slate-800">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-slate-500">{config.label}</p>
|
||||
<p className="text-3xl font-bold text-slate-900 dark:text-white mt-1">
|
||||
{config.getValue(stats)}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
className={`w-12 h-12 rounded-xl ${config.iconBg} flex items-center justify-center`}
|
||||
>
|
||||
<Icon className={`w-6 h-6 ${config.iconColor}`} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-4">
|
||||
{SubIcon && <SubIcon className={`w-4 h-4 ${config.subColor}`} />}
|
||||
<span className={`text-xs ${config.subTextColor}`}>
|
||||
{config.subLabel?.(stats)}
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Status Overview Card */}
|
||||
<Card className="border-slate-200 dark:border-slate-800">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-slate-500">状态</p>
|
||||
<div className="flex gap-3 mt-1">{statusSummary}</div>
|
||||
</div>
|
||||
<div className="w-12 h-12 rounded-xl bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center">
|
||||
<Activity className="w-6 h-6 text-orange-600" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Recent Deployments & Quick Resources */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Recent Deployments */}
|
||||
<RecentDeploymentsCard
|
||||
deployments={deployments}
|
||||
onViewAll={navigateTo('/deployments')}
|
||||
/>
|
||||
|
||||
{/* Quick Resources */}
|
||||
<div className="space-y-4">
|
||||
<ResourceListCard
|
||||
title="集群"
|
||||
icon={<Server className="w-4 h-4 text-blue-500" />}
|
||||
items={clusters.slice(0, 3)}
|
||||
onManage={navigateTo('/clusters')}
|
||||
getItemIcon={() => <Server className="w-4 h-4 text-blue-500" />}
|
||||
getItemLabel={(c) => c.name}
|
||||
getItemStatus={(c) => c.status}
|
||||
/>
|
||||
<ResourceListCard
|
||||
title="主机"
|
||||
icon={<Monitor className="w-4 h-4 text-purple-500" />}
|
||||
items={hosts.slice(0, 3)}
|
||||
onManage={navigateTo('/hosts')}
|
||||
getItemIcon={() => <Monitor className="w-4 h-4 text-purple-500" />}
|
||||
getItemLabel={(h) => h.name}
|
||||
getItemStatus={(h) => h.status}
|
||||
getItemExtra={(h) => h.hostIP}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:最近部署卡片 - 独立memo优化
|
||||
const RecentDeploymentsCard = memo(function RecentDeploymentsCard({
|
||||
deployments,
|
||||
onViewAll,
|
||||
}: {
|
||||
deployments: LokiDeployment[]
|
||||
onViewAll: () => void
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
return (
|
||||
<Card className="border-slate-200 dark:border-slate-800">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">最近部署</CardTitle>
|
||||
<button
|
||||
onClick={onViewAll}
|
||||
className="text-xs text-emerald-600 hover:text-emerald-700 font-medium"
|
||||
>
|
||||
查看全部
|
||||
</button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{deployments.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Rocket}
|
||||
title="暂无部署"
|
||||
description="创建你的第一个 Loki 部署"
|
||||
/>
|
||||
) : (
|
||||
deployments.map((d) => (
|
||||
<div
|
||||
key={d.id}
|
||||
className="flex items-center justify-between p-3 rounded-lg bg-slate-50 dark:bg-slate-800/50 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors cursor-pointer"
|
||||
onClick={() => navigate('/deployments')}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<StatusIcon status={d.status} size="sm" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate">
|
||||
{d.name}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
{d.mode} · {d.namespace || 'loki'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-full text-xs font-medium flex-shrink-0 ${getStatusColorClass(
|
||||
d.status
|
||||
)}`}
|
||||
>
|
||||
{statusLabel(d.status)}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:资源列表卡片 - 独立memo优化
|
||||
// 用具体结构类型而非泛型:memo 包裹泛型组件会导致 TS 无法从 props 推断 T,
|
||||
// 退化为约束类型 {id:number},使 getItemLabel/Status 中访问 name/status 报错。
|
||||
interface ResourceItem {
|
||||
id: number
|
||||
name: string
|
||||
status: string
|
||||
hostIP?: string
|
||||
}
|
||||
|
||||
interface ResourceListCardProps {
|
||||
title: string
|
||||
icon: React.ReactNode
|
||||
items: ResourceItem[]
|
||||
onManage: () => void
|
||||
getItemIcon: (item: ResourceItem) => React.ReactNode
|
||||
getItemLabel: (item: ResourceItem) => string
|
||||
getItemStatus: (item: ResourceItem) => string
|
||||
getItemExtra?: (item: ResourceItem) => string | undefined
|
||||
}
|
||||
|
||||
const ResourceListCard = memo(function ResourceListCard({
|
||||
title,
|
||||
icon,
|
||||
items,
|
||||
onManage,
|
||||
getItemIcon,
|
||||
getItemLabel,
|
||||
getItemStatus,
|
||||
getItemExtra,
|
||||
}: ResourceListCardProps) {
|
||||
return (
|
||||
<Card className="border-slate-200 dark:border-slate-800">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
{icon}
|
||||
{title}
|
||||
</CardTitle>
|
||||
<button
|
||||
onClick={onManage}
|
||||
className="text-xs text-emerald-600 hover:text-emerald-700 font-medium"
|
||||
>
|
||||
管理
|
||||
</button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{items.length === 0 ? (
|
||||
<p className="text-sm text-slate-400 text-center py-4">暂无{title}</p>
|
||||
) : (
|
||||
items.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex items-center justify-between p-2 rounded-md hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{getItemIcon(item)}
|
||||
<span className="text-sm truncate">{getItemLabel(item)}</span>
|
||||
{getItemExtra?.(item) && (
|
||||
<span className="text-xs text-slate-400 flex-shrink-0">
|
||||
{getItemExtra(item)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-full text-xs flex-shrink-0 ${getStatusColorClass(
|
||||
getItemStatus(item)
|
||||
)}`}
|
||||
>
|
||||
{statusLabel(getItemStatus(item))}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
export default Dashboard
|
||||
@@ -1,743 +0,0 @@
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
Rocket,
|
||||
Plus,
|
||||
Play,
|
||||
Square,
|
||||
RotateCw,
|
||||
Trash2,
|
||||
Terminal,
|
||||
ExternalLink,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { deploymentApi, clusterApi, hostApi, storageApi } from '@/api'
|
||||
import { statusLabel } from '@/lib/utils'
|
||||
import { StatusBadge, StatusIcon } from '@/components/StatusBadge'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { PageHeader } from '@/components/PageHeader'
|
||||
import { toast } from 'sonner'
|
||||
import type { LokiDeployment, Cluster, Host, StorageConfig, DeploymentLog } from '@/types'
|
||||
|
||||
// 表单默认值常量 - 避免重复创建
|
||||
const FORM_DEFAULTS = {
|
||||
name: '',
|
||||
description: '',
|
||||
version: '3.0.0',
|
||||
mode: 'k8s-helm' as 'k8s-helm' | 'k8s-yaml' | 'host-binary',
|
||||
clusterID: '',
|
||||
hostID: '',
|
||||
namespace: 'loki',
|
||||
storageConfigID: '',
|
||||
authEnabled: false,
|
||||
retentionDays: 30,
|
||||
replicas: 1,
|
||||
resourcesCPU: '500m',
|
||||
resourcesMem: '512Mi',
|
||||
storageSize: '10Gi',
|
||||
}
|
||||
|
||||
/**
|
||||
* Deployments 页面 - 全面优化版本
|
||||
*
|
||||
* 优化点:
|
||||
* 1. React.memo 包裹整个组件
|
||||
* 2. 使用 useReducer 简化大量 useState(替代原始15+个 useState)
|
||||
* 3. 所有操作函数使用 useCallback 缓存
|
||||
* 4. 部署卡片列表使用 useMemo 优化渲染
|
||||
* 5. setTimeout 添加清理函数,修复内存泄漏
|
||||
* 6. alert() 替换为 sonner toast 错误提示
|
||||
* 7. 使用 StatusBadge 公共组件替代重复状态函数
|
||||
* 8. 定时器使用 ref 存储以便清理
|
||||
*/
|
||||
const Deployments = memo(function Deployments() {
|
||||
// === State ===
|
||||
const [deployments, setDeployments] = useState<LokiDeployment[]>([])
|
||||
const [clusters, setClusters] = useState<Cluster[]>([])
|
||||
const [hosts, setHosts] = useState<Host[]>([])
|
||||
const [storages, setStorages] = useState<StorageConfig[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [logsOpen, setLogsOpen] = useState(false)
|
||||
const [selectedDeployment, setSelectedDeployment] = useState<LokiDeployment | null>(null)
|
||||
const [logs, setLogs] = useState<DeploymentLog[]>([])
|
||||
const [deploying, setDeploying] = useState<number | null>(null)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
// 表单状态 - 合并为一个对象减少state数量
|
||||
const [form, setForm] = useState({ ...FORM_DEFAULTS })
|
||||
|
||||
// 使用ref存储所有定时器ID以便清理
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
|
||||
// 组件卸载时清理所有定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
timeoutsRef.current.forEach((id) => clearTimeout(id))
|
||||
timeoutsRef.current = []
|
||||
}
|
||||
}, [])
|
||||
|
||||
// 添加定时器的辅助函数
|
||||
const addTimeout = useCallback((cb: () => void, delay: number) => {
|
||||
const id = setTimeout(cb, delay)
|
||||
timeoutsRef.current.push(id)
|
||||
return id
|
||||
}, [])
|
||||
|
||||
// === 数据加载 ===
|
||||
const loadAll = useCallback(async () => {
|
||||
try {
|
||||
const [deployRes, clusterRes, hostRes, storageRes] = await Promise.all([
|
||||
deploymentApi.list(1, 100),
|
||||
clusterApi.list(1, 100),
|
||||
hostApi.list(1, 100),
|
||||
storageApi.list(1, 100),
|
||||
])
|
||||
setDeployments(deployRes.list)
|
||||
setClusters(clusterRes.list)
|
||||
setHosts(hostRes.list)
|
||||
setStorages(storageRes.list)
|
||||
} catch (err) {
|
||||
console.error('Failed to load deployments:', err)
|
||||
toast.error('加载部署数据失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadAll()
|
||||
}, [loadAll])
|
||||
|
||||
// === 表单处理 ===
|
||||
const resetForm = useCallback(() => {
|
||||
setForm({ ...FORM_DEFAULTS })
|
||||
}, [])
|
||||
|
||||
const handleFormChange = useCallback(
|
||||
<K extends keyof typeof FORM_DEFAULTS>(key: K, value: (typeof FORM_DEFAULTS)[K]) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }))
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const clusterIDNum = form.clusterID ? Number(form.clusterID) : undefined
|
||||
const hostIDNum = form.hostID ? Number(form.hostID) : undefined
|
||||
const storageIDNum = form.storageConfigID ? Number(form.storageConfigID) : 0
|
||||
|
||||
await deploymentApi.create({
|
||||
name: form.name,
|
||||
description: form.description,
|
||||
version: form.version,
|
||||
mode: form.mode,
|
||||
clusterID: clusterIDNum,
|
||||
hostID: hostIDNum,
|
||||
namespace: form.namespace,
|
||||
storageConfigID: storageIDNum,
|
||||
authEnabled: form.authEnabled,
|
||||
retentionDays: form.retentionDays,
|
||||
replicas: form.replicas,
|
||||
resourcesCPU: form.resourcesCPU,
|
||||
resourcesMem: form.resourcesMem,
|
||||
storageSize: form.storageSize,
|
||||
})
|
||||
setOpen(false)
|
||||
resetForm()
|
||||
loadAll()
|
||||
toast.success('部署创建成功')
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '创建部署失败'
|
||||
toast.error(message)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
},
|
||||
[form, resetForm, loadAll]
|
||||
)
|
||||
|
||||
// === 操作函数 - useCallback 缓存 ===
|
||||
const handleDeploy = useCallback(
|
||||
async (id: number) => {
|
||||
setDeploying(id)
|
||||
try {
|
||||
await deploymentApi.deploy(id)
|
||||
addTimeout(loadAll, 2000)
|
||||
} catch (err) {
|
||||
console.error('Failed to deploy:', err)
|
||||
toast.error('部署失败')
|
||||
} finally {
|
||||
addTimeout(() => setDeploying(null), 5000)
|
||||
}
|
||||
},
|
||||
[loadAll, addTimeout]
|
||||
)
|
||||
|
||||
const handleStop = useCallback(
|
||||
async (id: number) => {
|
||||
try {
|
||||
await deploymentApi.stop(id)
|
||||
loadAll()
|
||||
toast.success('服务已停止')
|
||||
} catch (err) {
|
||||
console.error('Failed to stop:', err)
|
||||
toast.error('停止失败')
|
||||
}
|
||||
},
|
||||
[loadAll]
|
||||
)
|
||||
|
||||
const handleRestart = useCallback(
|
||||
async (id: number) => {
|
||||
setDeploying(id)
|
||||
try {
|
||||
await deploymentApi.restart(id)
|
||||
addTimeout(loadAll, 3000)
|
||||
toast.success('重启指令已发送')
|
||||
} catch (err) {
|
||||
console.error('Failed to restart:', err)
|
||||
toast.error('重启失败')
|
||||
} finally {
|
||||
addTimeout(() => setDeploying(null), 5000)
|
||||
}
|
||||
},
|
||||
[loadAll, addTimeout]
|
||||
)
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (id: number) => {
|
||||
if (!confirm('确定删除此部署?')) return
|
||||
try {
|
||||
await deploymentApi.remove(id)
|
||||
loadAll()
|
||||
toast.success('部署已删除')
|
||||
} catch (err) {
|
||||
console.error('Failed to delete:', err)
|
||||
toast.error('删除失败')
|
||||
}
|
||||
},
|
||||
[loadAll]
|
||||
)
|
||||
|
||||
const viewLogs = useCallback(
|
||||
async (deployment: LokiDeployment) => {
|
||||
setSelectedDeployment(deployment)
|
||||
setLogsOpen(true)
|
||||
try {
|
||||
const res = await deploymentApi.logs(deployment.id, 1, 100)
|
||||
setLogs(res.list)
|
||||
} catch (err) {
|
||||
console.error('Failed to load logs:', err)
|
||||
toast.error('加载日志失败')
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// === 辅助函数 ===
|
||||
const getTargetLabel = useCallback((d: LokiDeployment) => {
|
||||
if (d.cluster) return `集群:${d.cluster.name}`
|
||||
if (d.host) return `主机:${d.host.name}`
|
||||
return '未知'
|
||||
}, [])
|
||||
|
||||
// === 渲染优化 ===
|
||||
const deploymentCards = useMemo(
|
||||
() =>
|
||||
deployments.map((d) => (
|
||||
<DeploymentCard
|
||||
key={d.id}
|
||||
deployment={d}
|
||||
deploying={deploying}
|
||||
onDeploy={handleDeploy}
|
||||
onStop={handleStop}
|
||||
onRestart={handleRestart}
|
||||
onDelete={handleDelete}
|
||||
onViewLogs={viewLogs}
|
||||
getTargetLabel={getTargetLabel}
|
||||
/>
|
||||
)),
|
||||
[deployments, deploying, handleDeploy, handleStop, handleRestart, handleDelete, viewLogs, getTargetLabel]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<PageHeader
|
||||
title="部署Loki"
|
||||
description="部署与管理 Grafana Loki 日志聚合服务"
|
||||
action={
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-emerald-600 hover:bg-emerald-700">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
新建部署
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>创建 Loki 部署</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DeploymentForm
|
||||
form={form}
|
||||
onChange={handleFormChange}
|
||||
onSubmit={handleSubmit}
|
||||
submitting={submitting}
|
||||
clusters={clusters}
|
||||
hosts={hosts}
|
||||
storages={storages}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Deployments Grid */}
|
||||
{loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : deployments.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Rocket}
|
||||
title="暂无部署"
|
||||
description="创建你的第一个 Loki 部署"
|
||||
/>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">{deploymentCards}</div>
|
||||
)}
|
||||
|
||||
{/* Logs Dialog */}
|
||||
<Dialog open={logsOpen} onOpenChange={setLogsOpen}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Terminal className="w-5 h-5 text-emerald-500" />
|
||||
部署日志 - {selectedDeployment?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<LogViewer logs={logs} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:部署卡片 - 独立memo优化
|
||||
interface DeploymentCardProps {
|
||||
deployment: LokiDeployment
|
||||
deploying: number | null
|
||||
onDeploy: (id: number) => void
|
||||
onStop: (id: number) => void
|
||||
onRestart: (id: number) => void
|
||||
onDelete: (id: number) => void
|
||||
onViewLogs: (d: LokiDeployment) => void
|
||||
getTargetLabel: (d: LokiDeployment) => string
|
||||
}
|
||||
|
||||
const DeploymentCard = memo(function DeploymentCard({
|
||||
deployment: d,
|
||||
deploying,
|
||||
onDeploy,
|
||||
onStop,
|
||||
onRestart,
|
||||
onDelete,
|
||||
onViewLogs,
|
||||
getTargetLabel,
|
||||
}: DeploymentCardProps) {
|
||||
const isDeploying = d.status === 'deploying'
|
||||
const isBusy = deploying === d.id
|
||||
const canDeploy = d.status === 'pending' || d.status === 'failed' || d.status === 'stopped'
|
||||
|
||||
return (
|
||||
<Card className="border-slate-200 dark:border-slate-800 hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<StatusIcon status={d.status} size="md" />
|
||||
<div className="min-w-0">
|
||||
<h3 className="font-semibold text-slate-800 dark:text-white truncate">
|
||||
{d.name}
|
||||
</h3>
|
||||
<p className="text-xs text-slate-500">{d.uuid}</p>
|
||||
</div>
|
||||
</div>
|
||||
<StatusBadge status={d.status} />
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-slate-500 mb-3">{d.description || '无描述'}</p>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-slate-500 mb-4">
|
||||
<InfoRow label="方式" value={d.mode} />
|
||||
<InfoRow label="版本" value={d.version} />
|
||||
<InfoRow label="目标" value={getTargetLabel(d)} />
|
||||
<InfoRow label="命名空间" value={d.namespace || 'loki'} />
|
||||
<InfoRow label="副本数" value={String(d.replicas)} />
|
||||
<InfoRow label="存储" value={d.storageConfig?.name || '本地'} />
|
||||
{d.endpoint && (
|
||||
<InfoRow label="访问地址" value={d.endpoint} valueClass="text-emerald-600 truncate max-w-[200px]" />
|
||||
)}
|
||||
{d.statusMessage && (
|
||||
<div className="p-2 bg-slate-50 dark:bg-slate-800 rounded text-xs">
|
||||
{d.statusMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 pt-3 border-t border-slate-100 dark:border-slate-800">
|
||||
{canDeploy ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs bg-emerald-50 text-emerald-700 hover:bg-emerald-100 border-emerald-200"
|
||||
onClick={() => onDeploy(d.id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
<Play className="w-3 h-3 mr-1" />
|
||||
{isBusy ? '部署中...' : '部署'}
|
||||
</Button>
|
||||
) : isDeploying ? (
|
||||
<Button variant="outline" size="sm" className="flex-1 text-xs" disabled>
|
||||
<RotateCw className="w-3 h-3 mr-1 animate-spin" />
|
||||
部署中...
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" size="sm" className="text-xs" onClick={() => onStop(d.id)}>
|
||||
<Square className="w-3 h-3 mr-1" />
|
||||
停止
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs"
|
||||
onClick={() => onRestart(d.id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
<RotateCw className={`w-3 h-3 mr-1 ${isBusy ? 'animate-spin' : ''}`} />
|
||||
重启
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button variant="outline" size="sm" className="text-xs" onClick={() => onViewLogs(d)}>
|
||||
<Terminal className="w-3 h-3 mr-1" />
|
||||
日志
|
||||
</Button>
|
||||
{d.endpoint && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs text-emerald-600 hover:text-emerald-700"
|
||||
onClick={() => window.open(d.endpoint, '_blank')}
|
||||
title="浏览器访问"
|
||||
>
|
||||
<ExternalLink className="w-3 h-3 mr-1" />
|
||||
访问
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => onDelete(d.id)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:信息行
|
||||
const InfoRow = memo(function InfoRow({
|
||||
label,
|
||||
value,
|
||||
valueClass,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
valueClass?: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex justify-between">
|
||||
<span>{label}</span>
|
||||
<span className={`font-medium text-slate-700 dark:text-slate-300 ${valueClass || ''}`}>
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:日志查看器
|
||||
const LogViewer = memo(function LogViewer({ logs }: { logs: DeploymentLog[] }) {
|
||||
return (
|
||||
<div className="bg-slate-900 text-green-400 font-mono text-xs p-4 rounded-lg h-96 overflow-auto">
|
||||
{logs.length === 0 ? (
|
||||
<p className="text-slate-500">暂无日志...</p>
|
||||
) : (
|
||||
logs.map((log) => (
|
||||
<div
|
||||
key={log.id}
|
||||
className={`mb-1 ${
|
||||
log.level === 'error'
|
||||
? 'text-red-400'
|
||||
: log.level === 'warn'
|
||||
? 'text-amber-400'
|
||||
: log.level === 'success'
|
||||
? 'text-emerald-400'
|
||||
: 'text-green-400'
|
||||
}`}
|
||||
>
|
||||
<span className="text-slate-500">
|
||||
[{new Date(log.createdAt).toLocaleTimeString()}]
|
||||
</span>{' '}
|
||||
<span className="font-bold uppercase">{log.level}</span> {log.message}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:部署表单
|
||||
interface DeploymentFormProps {
|
||||
form: typeof FORM_DEFAULTS
|
||||
onChange: <K extends keyof typeof FORM_DEFAULTS>(key: K, value: (typeof FORM_DEFAULTS)[K]) => void
|
||||
onSubmit: (e: React.FormEvent) => void
|
||||
submitting: boolean
|
||||
clusters: Cluster[]
|
||||
hosts: Host[]
|
||||
storages: StorageConfig[]
|
||||
}
|
||||
|
||||
const DeploymentForm = memo(function DeploymentForm({
|
||||
form,
|
||||
onChange,
|
||||
onSubmit,
|
||||
submitting,
|
||||
clusters,
|
||||
hosts,
|
||||
storages,
|
||||
}: DeploymentFormProps) {
|
||||
const isK8s = form.mode === 'k8s-helm' || form.mode === 'k8s-yaml'
|
||||
const isHost = form.mode === 'host-binary'
|
||||
|
||||
return (
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="d-name">部署名称 *</Label>
|
||||
<Input
|
||||
id="d-name"
|
||||
value={form.name}
|
||||
onChange={(e) => onChange('name', e.target.value)}
|
||||
placeholder="production-loki"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="d-desc">描述</Label>
|
||||
<Textarea
|
||||
id="d-desc"
|
||||
value={form.description}
|
||||
onChange={(e) => onChange('description', e.target.value)}
|
||||
placeholder="生产环境 Loki 日志服务"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>版本</Label>
|
||||
<Select value={form.version} onValueChange={(v) => onChange('version', v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="3.0.0">3.0.0</SelectItem>
|
||||
<SelectItem value="2.9.8">2.9.8</SelectItem>
|
||||
<SelectItem value="2.9.7">2.9.7</SelectItem>
|
||||
<SelectItem value="2.9.6">2.9.6</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>部署方式</Label>
|
||||
<Select
|
||||
value={form.mode}
|
||||
onValueChange={(v) =>
|
||||
onChange('mode', v as 'k8s-helm' | 'k8s-yaml' | 'host-binary')
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="k8s-helm">K8s Helm 部署</SelectItem>
|
||||
<SelectItem value="k8s-yaml">K8s YAML 部署</SelectItem>
|
||||
<SelectItem value="host-binary">主机二进制部署</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isK8s && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label>目标集群 *</Label>
|
||||
<Select value={form.clusterID} onValueChange={(v) => onChange('clusterID', v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="请选择集群" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{clusters.map((c) => (
|
||||
<SelectItem key={c.id} value={String(c.id)}>
|
||||
{c.name}({statusLabel(c.status)})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="d-ns">命名空间</Label>
|
||||
<Input
|
||||
id="d-ns"
|
||||
value={form.namespace}
|
||||
onChange={(e) => onChange('namespace', e.target.value)}
|
||||
placeholder="loki"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isHost && (
|
||||
<div className="space-y-2">
|
||||
<Label>目标主机 *</Label>
|
||||
<Select value={form.hostID} onValueChange={(v) => onChange('hostID', v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="请选择主机" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{hosts.map((h) => (
|
||||
<SelectItem key={h.id} value={String(h.id)}>
|
||||
{h.name}({h.hostIP})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>存储配置</Label>
|
||||
<Select value={form.storageConfigID} onValueChange={(v) => onChange('storageConfigID', v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="请选择存储(可选)" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0">本地存储(默认)</SelectItem>
|
||||
{storages.map((s) => (
|
||||
<SelectItem key={s.id} value={String(s.id)}>
|
||||
{s.name}({s.storageType})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="d-replicas">副本数</Label>
|
||||
<Input
|
||||
id="d-replicas"
|
||||
type="number"
|
||||
min={1}
|
||||
max={10}
|
||||
value={form.replicas}
|
||||
onChange={(e) => onChange('replicas', Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="d-retention">保留天数</Label>
|
||||
<Input
|
||||
id="d-retention"
|
||||
type="number"
|
||||
min={1}
|
||||
value={form.retentionDays}
|
||||
onChange={(e) => onChange('retentionDays', Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="d-size">存储容量</Label>
|
||||
<Input
|
||||
id="d-size"
|
||||
value={form.storageSize}
|
||||
onChange={(e) => onChange('storageSize', e.target.value)}
|
||||
placeholder="10Gi"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="d-cpu">CPU</Label>
|
||||
<Input
|
||||
id="d-cpu"
|
||||
value={form.resourcesCPU}
|
||||
onChange={(e) => onChange('resourcesCPU', e.target.value)}
|
||||
placeholder="500m"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="d-mem">内存</Label>
|
||||
<Input
|
||||
id="d-mem"
|
||||
value={form.resourcesMem}
|
||||
onChange={(e) => onChange('resourcesMem', e.target.value)}
|
||||
placeholder="512Mi"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="d-auth"
|
||||
checked={form.authEnabled}
|
||||
onCheckedChange={(v) => onChange('authEnabled', v)}
|
||||
/>
|
||||
<Label htmlFor="d-auth">启用多租户鉴权</Label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-emerald-600 hover:bg-emerald-700"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '创建中...' : '创建部署'}
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
})
|
||||
|
||||
export default Deployments
|
||||
@@ -1,633 +0,0 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Monitor,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Trash2,
|
||||
Eye,
|
||||
Terminal,
|
||||
Key,
|
||||
Lock,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { hostApi } from '@/api'
|
||||
import { StatusBadge } from '@/components/StatusBadge'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { PageHeader } from '@/components/PageHeader'
|
||||
import { toast } from 'sonner'
|
||||
import type { Host, HostInfo } from '@/types'
|
||||
|
||||
// 使用率颜色阈值 - 常量提取
|
||||
const usageColor = (v: number) =>
|
||||
v >= 90 ? 'bg-red-500' : v >= 70 ? 'bg-amber-500' : 'bg-emerald-500'
|
||||
|
||||
/**
|
||||
* Hosts 页面 - 优化版本
|
||||
*
|
||||
* 优化点:
|
||||
* 1. React.memo 包裹组件
|
||||
* 2. 所有操作函数使用 useCallback 缓存
|
||||
* 3. alert() 替换为 sonner toast
|
||||
* 4. setTimeout 使用 ref 管理
|
||||
* 5. 使用公共组件替代重复代码
|
||||
*/
|
||||
const Hosts = memo(function Hosts() {
|
||||
const [hosts, setHosts] = useState<Host[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [detailOpen, setDetailOpen] = useState(false)
|
||||
const [terminalOpen, setTerminalOpen] = useState(false)
|
||||
const [selectedHost, setSelectedHost] = useState<Host | null>(null)
|
||||
const [hostInfo, setHostInfo] = useState<HostInfo | null>(null)
|
||||
const [validating, setValidating] = useState<number | null>(null)
|
||||
|
||||
// Terminal state
|
||||
const [command, setCommand] = useState('')
|
||||
const [terminalOutput, setTerminalOutput] = useState('')
|
||||
const [executing, setExecuting] = useState(false)
|
||||
|
||||
// Form state
|
||||
const [name, setName] = useState('')
|
||||
const [hostIP, setHostIP] = useState('')
|
||||
const [port, setPort] = useState(22)
|
||||
const [user, setUser] = useState('root')
|
||||
const [authType, setAuthType] = useState<'password' | 'key'>('password')
|
||||
const [password, setPassword] = useState('')
|
||||
const [privateKey, setPrivateKey] = useState('')
|
||||
const [keyPhrase, setKeyPhrase] = useState('')
|
||||
const [labels, setLabels] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
timeoutsRef.current.forEach((id) => clearTimeout(id))
|
||||
}
|
||||
}, [])
|
||||
|
||||
const addTimeout = useCallback((cb: () => void, delay: number) => {
|
||||
const id = setTimeout(cb, delay)
|
||||
timeoutsRef.current.push(id)
|
||||
return id
|
||||
}, [])
|
||||
|
||||
const loadHosts = useCallback(async () => {
|
||||
try {
|
||||
const res = await hostApi.list(1, 100)
|
||||
setHosts(res.list)
|
||||
} catch (err) {
|
||||
console.error('Failed to load hosts:', err)
|
||||
toast.error('加载主机数据失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadHosts()
|
||||
}, [loadHosts])
|
||||
|
||||
const resetForm = useCallback(() => {
|
||||
setName('')
|
||||
setHostIP('')
|
||||
setPort(22)
|
||||
setUser('root')
|
||||
setAuthType('password')
|
||||
setPassword('')
|
||||
setPrivateKey('')
|
||||
setKeyPhrase('')
|
||||
setLabels('')
|
||||
}, [])
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await hostApi.create({
|
||||
name,
|
||||
hostIP,
|
||||
port,
|
||||
user,
|
||||
authType,
|
||||
password: authType === 'password' ? password : undefined,
|
||||
privateKey: authType === 'key' ? privateKey : undefined,
|
||||
keyPhrase: authType === 'key' ? keyPhrase : undefined,
|
||||
labels,
|
||||
})
|
||||
setOpen(false)
|
||||
resetForm()
|
||||
loadHosts()
|
||||
toast.success('主机添加成功')
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '添加主机失败'
|
||||
toast.error(message)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
},
|
||||
[name, hostIP, port, user, authType, password, privateKey, keyPhrase, labels, resetForm, loadHosts]
|
||||
)
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (id: number) => {
|
||||
if (!confirm('确定删除此主机?')) return
|
||||
try {
|
||||
await hostApi.remove(id)
|
||||
loadHosts()
|
||||
toast.success('主机已删除')
|
||||
} catch (err) {
|
||||
console.error('Failed to delete host:', err)
|
||||
toast.error('删除主机失败')
|
||||
}
|
||||
},
|
||||
[loadHosts]
|
||||
)
|
||||
|
||||
const handleValidate = useCallback(
|
||||
async (id: number) => {
|
||||
setValidating(id)
|
||||
try {
|
||||
await hostApi.validate(id)
|
||||
addTimeout(loadHosts, 3000)
|
||||
toast.success('验证指令已发送')
|
||||
} catch (err) {
|
||||
console.error('Failed to validate host:', err)
|
||||
toast.error('验证失败')
|
||||
} finally {
|
||||
addTimeout(() => setValidating(null), 3000)
|
||||
}
|
||||
},
|
||||
[loadHosts, addTimeout]
|
||||
)
|
||||
|
||||
const viewHostInfo = useCallback(
|
||||
async (host: Host) => {
|
||||
setSelectedHost(host)
|
||||
setHostInfo(null)
|
||||
setDetailOpen(true)
|
||||
try {
|
||||
const info = await hostApi.getInfo(host.id)
|
||||
setHostInfo(info)
|
||||
} catch (err) {
|
||||
console.error('Failed to get host info:', err)
|
||||
toast.error('加载主机详情失败')
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const openTerminal = useCallback((host: Host) => {
|
||||
setSelectedHost(host)
|
||||
setTerminalOpen(true)
|
||||
setTerminalOutput(`已连接到 ${host.name} (${host.hostIP})\n输入命令后按"执行"...\n`)
|
||||
setCommand('')
|
||||
}, [])
|
||||
|
||||
const executeCommand = useCallback(async () => {
|
||||
if (!selectedHost || !command.trim()) return
|
||||
setExecuting(true)
|
||||
setTerminalOutput((prev) => prev + `\n$ ${command}\n`)
|
||||
try {
|
||||
const res = await hostApi.execute(selectedHost.id, command)
|
||||
setTerminalOutput((prev) => prev + (res.stdout || '') + (res.stderr || '') + '\n')
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '命令执行失败'
|
||||
setTerminalOutput((prev) => prev + `错误:${message}\n`)
|
||||
} finally {
|
||||
setExecuting(false)
|
||||
setCommand('')
|
||||
}
|
||||
}, [selectedHost, command])
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="主机管理"
|
||||
description="管理用于二进制方式部署 Loki 的 SSH 主机"
|
||||
action={
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-emerald-600 hover:bg-emerald-700">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
添加主机
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>添加 SSH 主机</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="h-name">名称 *</Label>
|
||||
<Input
|
||||
id="h-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="loki-server-1"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="h-ip">主机 IP *</Label>
|
||||
<Input
|
||||
id="h-ip"
|
||||
value={hostIP}
|
||||
onChange={(e) => setHostIP(e.target.value)}
|
||||
placeholder="192.168.1.100"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="h-port">端口</Label>
|
||||
<Input
|
||||
id="h-port"
|
||||
type="number"
|
||||
value={port}
|
||||
onChange={(e) => setPort(Number(e.target.value))}
|
||||
placeholder="22"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="h-user">用户名 *</Label>
|
||||
<Input
|
||||
id="h-user"
|
||||
value={user}
|
||||
onChange={(e) => setUser(e.target.value)}
|
||||
placeholder="root"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>认证方式</Label>
|
||||
<div className="flex gap-4">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="authType"
|
||||
value="password"
|
||||
checked={authType === 'password'}
|
||||
onChange={() => setAuthType('password')}
|
||||
/>
|
||||
<Lock className="w-4 h-4" />
|
||||
<span className="text-sm">密码</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="authType"
|
||||
value="key"
|
||||
checked={authType === 'key'}
|
||||
onChange={() => setAuthType('key')}
|
||||
/>
|
||||
<Key className="w-4 h-4" />
|
||||
<span className="text-sm">SSH 密钥</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{authType === 'password' ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="h-password">密码 *</Label>
|
||||
<Input
|
||||
id="h-password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="SSH 登录密码"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="h-key">私钥 *</Label>
|
||||
<Textarea
|
||||
id="h-key"
|
||||
value={privateKey}
|
||||
onChange={(e) => setPrivateKey(e.target.value)}
|
||||
placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
|
||||
required
|
||||
className="min-h-[120px] font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="h-phrase">密钥口令(可选)</Label>
|
||||
<Input
|
||||
id="h-phrase"
|
||||
type="password"
|
||||
value={keyPhrase}
|
||||
onChange={(e) => setKeyPhrase(e.target.value)}
|
||||
placeholder="无口令则留空"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="h-labels">标签(JSON)</Label>
|
||||
<Input
|
||||
id="h-labels"
|
||||
value={labels}
|
||||
onChange={(e) => setLabels(e.target.value)}
|
||||
placeholder='["loki", "logging"]'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-emerald-600 hover:bg-emerald-700"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '添加中...' : '添加主机'}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Hosts Grid */}
|
||||
{loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : hosts.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Monitor}
|
||||
title="暂无主机"
|
||||
description="添加第一台 SSH 主机开始使用"
|
||||
/>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{hosts.map((host) => (
|
||||
<HostCard
|
||||
key={host.id}
|
||||
host={host}
|
||||
validating={validating}
|
||||
onViewInfo={viewHostInfo}
|
||||
onOpenTerminal={openTerminal}
|
||||
onValidate={handleValidate}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Host Detail Dialog */}
|
||||
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Monitor className="w-5 h-5 text-purple-500" />
|
||||
{selectedHost?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
{hostInfo ? (
|
||||
<HostDetail info={hostInfo} />
|
||||
) : (
|
||||
<LoadingSpinner className="h-32" />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Terminal Dialog */}
|
||||
<Dialog open={terminalOpen} onOpenChange={setTerminalOpen}>
|
||||
<DialogContent className="max-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Terminal className="w-5 h-5 text-emerald-500" />
|
||||
终端 - {selectedHost?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="bg-slate-900 text-green-400 font-mono text-xs p-4 rounded-lg h-80 overflow-auto whitespace-pre-wrap">
|
||||
{terminalOutput}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={command}
|
||||
onChange={(e) => setCommand(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && executeCommand()}
|
||||
placeholder="输入命令..."
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={executing}
|
||||
/>
|
||||
<Button
|
||||
onClick={executeCommand}
|
||||
disabled={executing || !command.trim()}
|
||||
className="bg-emerald-600 hover:bg-emerald-700"
|
||||
>
|
||||
{executing ? '执行中...' : '执行'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:主机卡片
|
||||
interface HostCardProps {
|
||||
host: Host
|
||||
validating: number | null
|
||||
onViewInfo: (h: Host) => void
|
||||
onOpenTerminal: (h: Host) => void
|
||||
onValidate: (id: number) => void
|
||||
onDelete: (id: number) => void
|
||||
}
|
||||
|
||||
const HostCard = memo(function HostCard({
|
||||
host,
|
||||
validating,
|
||||
onViewInfo,
|
||||
onOpenTerminal,
|
||||
onValidate,
|
||||
onDelete,
|
||||
}: HostCardProps) {
|
||||
return (
|
||||
<Card className="border-slate-200 dark:border-slate-800 hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Monitor className="w-5 h-5 text-purple-500 flex-shrink-0" />
|
||||
<h3 className="font-semibold text-slate-800 dark:text-white truncate">
|
||||
{host.name}
|
||||
</h3>
|
||||
</div>
|
||||
<StatusBadge status={host.status} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-slate-500 mb-4">
|
||||
<InfoRow label="IP 地址" value={`${host.hostIP}:${host.port}`} />
|
||||
<InfoRow label="用户名" value={host.user} />
|
||||
<InfoRow
|
||||
label="认证方式"
|
||||
value={host.authType === 'key' ? 'SSH 密钥' : '密码'}
|
||||
/>
|
||||
<InfoRow
|
||||
label="系统"
|
||||
value={`${host.os || '未知'} (${host.arch || '未知'})`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-3 border-t border-slate-100 dark:border-slate-800">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onViewInfo(host)}
|
||||
>
|
||||
<Eye className="w-3 h-3 mr-1" />
|
||||
详情
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onOpenTerminal(host)}
|
||||
>
|
||||
<Terminal className="w-3 h-3 mr-1" />
|
||||
终端
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs"
|
||||
onClick={() => onValidate(host.id)}
|
||||
disabled={validating === host.id}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3 h-3 ${validating === host.id ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => onDelete(host.id)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:信息行
|
||||
const InfoRow = memo(function InfoRow({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex justify-between">
|
||||
<span>{label}</span>
|
||||
<span className="font-medium text-slate-700 dark:text-slate-300">{value}</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:主机详情
|
||||
const HostDetail = memo(function HostDetail({ info }: { info: HostInfo }) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* 资源使用率 */}
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-3">资源使用率</h4>
|
||||
<div className="space-y-3">
|
||||
<UsageBar label="CPU" value={info.cpuUsage} />
|
||||
<UsageBar
|
||||
label="内存"
|
||||
value={info.memUsage}
|
||||
detail={`${info.memUsed} / ${info.memTotal}`}
|
||||
/>
|
||||
<UsageBar
|
||||
label="磁盘"
|
||||
value={info.diskUsage}
|
||||
detail={`${info.diskUsed} / ${info.diskTotal}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 基本信息 */}
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-3">基本信息</h4>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoCard label="主机名" value={info.hostname || '未知'} />
|
||||
<InfoCard label="系统" value={`${info.os || '未知'} ${info.version}`} />
|
||||
<InfoCard label="架构" value={info.arch || '未知'} />
|
||||
<InfoCard label="内核" value={info.kernel || '未知'} />
|
||||
<InfoCard label="CPU 核数" value={info.cpu || '未知'} />
|
||||
<InfoCard label="运行时长" value={info.uptime || '未知'} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 使用率进度条
|
||||
const UsageBar = memo(function UsageBar({
|
||||
label,
|
||||
value,
|
||||
detail,
|
||||
}: {
|
||||
label: string
|
||||
value: number
|
||||
detail?: string
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between text-xs mb-1">
|
||||
<span className="text-slate-500">{label}</span>
|
||||
<span className="font-medium">
|
||||
{value.toFixed(1)}% {detail && `(${detail})`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full ${usageColor(value)} rounded-full transition-all`}
|
||||
style={{ width: `${Math.min(value, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 信息卡片
|
||||
const InfoCard = memo(function InfoCard({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<div className="p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg">
|
||||
<p className="text-xs text-slate-500">{label}</p>
|
||||
<p className="text-sm font-medium truncate">{value}</p>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Hosts
|
||||
@@ -1,438 +0,0 @@
|
||||
import { memo, useCallback, useEffect, useState } from 'react'
|
||||
import {
|
||||
HardDrive,
|
||||
Plus,
|
||||
Trash2,
|
||||
Star,
|
||||
Cloud,
|
||||
Database,
|
||||
Package,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { storageApi } from '@/api'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { PageHeader } from '@/components/PageHeader'
|
||||
import { toast } from 'sonner'
|
||||
import type { StorageConfig } from '@/types'
|
||||
|
||||
// 存储类型图标映射 - 常量提取
|
||||
const STORAGE_TYPE_ICONS: Record<string, React.ReactNode> = {
|
||||
s3: <Cloud className="w-5 h-5 text-orange-500" />,
|
||||
oss: <Cloud className="w-5 h-5 text-red-500" />,
|
||||
minio: <Database className="w-5 h-5 text-blue-500" />,
|
||||
rustfs: <Package className="w-5 h-5 text-cyan-500" />,
|
||||
}
|
||||
|
||||
// 存储类型颜色
|
||||
const STORAGE_TYPE_COLORS: Record<string, string> = {
|
||||
s3: 'bg-orange-100 text-orange-700',
|
||||
oss: 'bg-red-100 text-red-700',
|
||||
minio: 'bg-blue-100 text-blue-700',
|
||||
rustfs: 'bg-cyan-100 text-cyan-700',
|
||||
}
|
||||
|
||||
const STORAGE_TYPES = ['s3', 'oss', 'minio', 'rustfs'] as const
|
||||
|
||||
/**
|
||||
* Storage 页面 - 优化版本
|
||||
*
|
||||
* 优化点:
|
||||
* 1. React.memo 包裹组件
|
||||
* 2. 所有操作函数使用 useCallback 缓存
|
||||
* 3. alert() 替换为 sonner toast
|
||||
* 4. 使用公共组件替代重复代码
|
||||
* 5. 常量图标和颜色映射提取
|
||||
*/
|
||||
const Storage = memo(function Storage() {
|
||||
const [storages, setStorages] = useState<StorageConfig[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
// Form state
|
||||
const [name, setName] = useState('')
|
||||
const [storageType, setStorageType] = useState<'s3' | 'oss' | 'minio' | 'rustfs'>('minio')
|
||||
const [endpoint, setEndpoint] = useState('')
|
||||
const [bucket, setBucket] = useState('')
|
||||
const [region, setRegion] = useState('')
|
||||
const [accessKey, setAccessKey] = useState('')
|
||||
const [secretKey, setSecretKey] = useState('')
|
||||
const [pathPrefix, setPathPrefix] = useState('loki')
|
||||
const [insecure, setInsecure] = useState(false)
|
||||
const [isDefault, setIsDefault] = useState(false)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const loadStorages = useCallback(async () => {
|
||||
try {
|
||||
const res = await storageApi.list(1, 100)
|
||||
setStorages(res.list)
|
||||
} catch (err) {
|
||||
console.error('Failed to load storages:', err)
|
||||
toast.error('加载存储配置失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadStorages()
|
||||
}, [loadStorages])
|
||||
|
||||
const resetForm = useCallback(() => {
|
||||
setName('')
|
||||
setStorageType('minio')
|
||||
setEndpoint('')
|
||||
setBucket('')
|
||||
setRegion('')
|
||||
setAccessKey('')
|
||||
setSecretKey('')
|
||||
setPathPrefix('loki')
|
||||
setInsecure(false)
|
||||
setIsDefault(false)
|
||||
}, [])
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await storageApi.create({
|
||||
name,
|
||||
storageType,
|
||||
endpoint,
|
||||
bucket,
|
||||
region,
|
||||
accessKey,
|
||||
secretKey,
|
||||
pathPrefix,
|
||||
insecure,
|
||||
isDefault,
|
||||
})
|
||||
setOpen(false)
|
||||
resetForm()
|
||||
loadStorages()
|
||||
toast.success('存储配置添加成功')
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '创建存储配置失败'
|
||||
toast.error(message)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
},
|
||||
[name, storageType, endpoint, bucket, region, accessKey, secretKey, pathPrefix, insecure, isDefault, resetForm, loadStorages]
|
||||
)
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (id: number) => {
|
||||
if (!confirm('确定删除此存储配置?')) return
|
||||
try {
|
||||
await storageApi.remove(id)
|
||||
loadStorages()
|
||||
toast.success('存储配置已删除')
|
||||
} catch (err) {
|
||||
console.error('Failed to delete storage:', err)
|
||||
toast.error('删除存储配置失败')
|
||||
}
|
||||
},
|
||||
[loadStorages]
|
||||
)
|
||||
|
||||
const handleSetDefault = useCallback(
|
||||
async (id: number) => {
|
||||
try {
|
||||
await storageApi.update(id, { isDefault: true })
|
||||
loadStorages()
|
||||
toast.success('已设为默认存储')
|
||||
} catch (err) {
|
||||
console.error('Failed to set default storage:', err)
|
||||
toast.error('设置默认存储失败')
|
||||
}
|
||||
},
|
||||
[loadStorages]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="存储配置"
|
||||
description="为 Loki 配置对象存储后端"
|
||||
action={
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-emerald-600 hover:bg-emerald-700">
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
添加存储
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>添加存储配置</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="s-name">名称 *</Label>
|
||||
<Input
|
||||
id="s-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="production-minio"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>存储类型</Label>
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{STORAGE_TYPES.map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
type="button"
|
||||
onClick={() => setStorageType(type)}
|
||||
className={`flex flex-col items-center gap-1 p-3 rounded-lg border transition-all ${
|
||||
storageType === type
|
||||
? 'border-emerald-500 bg-emerald-50 text-emerald-700'
|
||||
: 'border-slate-200 hover:border-slate-300 text-slate-600'
|
||||
}`}
|
||||
>
|
||||
{STORAGE_TYPE_ICONS[type]}
|
||||
<span className="text-xs font-medium uppercase">{type}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="s-endpoint">访问地址</Label>
|
||||
<Input
|
||||
id="s-endpoint"
|
||||
value={endpoint}
|
||||
onChange={(e) => setEndpoint(e.target.value)}
|
||||
placeholder={
|
||||
storageType === 's3'
|
||||
? 's3.amazonaws.com'
|
||||
: storageType === 'minio'
|
||||
? 'http://minio.example.com:9000'
|
||||
: ''
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="s-bucket">Bucket *</Label>
|
||||
<Input
|
||||
id="s-bucket"
|
||||
value={bucket}
|
||||
onChange={(e) => setBucket(e.target.value)}
|
||||
placeholder="loki-logs"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="s-region">区域</Label>
|
||||
<Input
|
||||
id="s-region"
|
||||
value={region}
|
||||
onChange={(e) => setRegion(e.target.value)}
|
||||
placeholder="us-east-1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="s-access">Access Key</Label>
|
||||
<Input
|
||||
id="s-access"
|
||||
value={accessKey}
|
||||
onChange={(e) => setAccessKey(e.target.value)}
|
||||
placeholder="minioadmin"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="s-secret">Secret Key</Label>
|
||||
<Input
|
||||
id="s-secret"
|
||||
type="password"
|
||||
value={secretKey}
|
||||
onChange={(e) => setSecretKey(e.target.value)}
|
||||
placeholder="minioadmin"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="s-prefix">路径前缀</Label>
|
||||
<Input
|
||||
id="s-prefix"
|
||||
value={pathPrefix}
|
||||
onChange={(e) => setPathPrefix(e.target.value)}
|
||||
placeholder="loki"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="s-insecure"
|
||||
checked={insecure}
|
||||
onCheckedChange={setInsecure}
|
||||
/>
|
||||
<Label htmlFor="s-insecure">不加密 (HTTP)</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="s-default"
|
||||
checked={isDefault}
|
||||
onCheckedChange={setIsDefault}
|
||||
/>
|
||||
<Label htmlFor="s-default">设为默认</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-emerald-600 hover:bg-emerald-700"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '添加中...' : '添加存储'}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Storage Grid */}
|
||||
{loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : storages.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={HardDrive}
|
||||
title="暂无存储配置"
|
||||
description="添加第一个 Loki 存储后端"
|
||||
/>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{storages.map((storage) => (
|
||||
<StorageCard
|
||||
key={storage.id}
|
||||
storage={storage}
|
||||
onSetDefault={handleSetDefault}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:存储卡片
|
||||
interface StorageCardProps {
|
||||
storage: StorageConfig
|
||||
onSetDefault: (id: number) => void
|
||||
onDelete: (id: number) => void
|
||||
}
|
||||
|
||||
const StorageCard = memo(function StorageCard({
|
||||
storage,
|
||||
onSetDefault,
|
||||
onDelete,
|
||||
}: StorageCardProps) {
|
||||
return (
|
||||
<Card
|
||||
className={`border-slate-200 dark:border-slate-800 hover:shadow-md transition-shadow ${
|
||||
storage.isDefault ? 'ring-1 ring-emerald-500' : ''
|
||||
}`}
|
||||
>
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{STORAGE_TYPE_ICONS[storage.storageType] || (
|
||||
<HardDrive className="w-5 h-5 text-slate-400" />
|
||||
)}
|
||||
<h3 className="font-semibold text-slate-800 dark:text-white truncate">
|
||||
{storage.name}
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
{storage.isDefault && (
|
||||
<span className="px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-700 text-xs font-medium flex items-center gap-0.5">
|
||||
<Star className="w-3 h-3" />
|
||||
默认
|
||||
</span>
|
||||
)}
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-full text-xs font-medium uppercase ${
|
||||
STORAGE_TYPE_COLORS[storage.storageType] || 'bg-slate-100 text-slate-600'
|
||||
}`}
|
||||
>
|
||||
{storage.storageType}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-slate-500 mb-4">
|
||||
<InfoRow label="访问地址" value={storage.endpoint || '默认'} />
|
||||
<InfoRow label="Bucket" value={storage.bucket} />
|
||||
<InfoRow label="区域" value={storage.region || '无'} />
|
||||
<InfoRow label="路径前缀" value={storage.pathPrefix || '无'} />
|
||||
<InfoRow label="不加密" value={storage.insecure ? '是' : '否'} />
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-3 border-t border-slate-100 dark:border-slate-800">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onSetDefault(storage.id)}
|
||||
disabled={storage.isDefault}
|
||||
>
|
||||
<Star className="w-3 h-3 mr-1" />
|
||||
{storage.isDefault ? '默认' : '设为默认'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => onDelete(storage.id)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
// 子组件:信息行
|
||||
const InfoRow = memo(function InfoRow({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex justify-between">
|
||||
<span>{label}</span>
|
||||
<span className="font-medium text-slate-700 dark:text-slate-300 truncate max-w-[150px]">
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Storage
|
||||
@@ -0,0 +1,101 @@
|
||||
import { memo } from 'react'
|
||||
import { Server, RefreshCw, Trash2, Eye } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { StatusBadge } from '@/components/StatusBadge'
|
||||
import { InfoRow } from '@/components/InfoRow'
|
||||
import type { Cluster } from '@/types'
|
||||
|
||||
interface ClusterCardProps {
|
||||
cluster: Cluster
|
||||
validating: number | null
|
||||
onViewInfo: (c: Cluster) => void
|
||||
onValidate: (id: number) => void
|
||||
onDelete: (c: Cluster) => void
|
||||
}
|
||||
|
||||
/** 集群卡片 — 列表项展示与操作入口 */
|
||||
export const ClusterCard = memo(function ClusterCard({
|
||||
cluster,
|
||||
validating,
|
||||
onViewInfo,
|
||||
onValidate,
|
||||
onDelete,
|
||||
}: ClusterCardProps) {
|
||||
return (
|
||||
<Card className="border-border hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Server className="w-5 h-5 text-info flex-shrink-0" />
|
||||
<h3 className="font-semibold text-foreground truncate">
|
||||
{cluster.name}
|
||||
</h3>
|
||||
</div>
|
||||
<StatusBadge status={cluster.status} />
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground mb-3 line-clamp-2">
|
||||
{cluster.description || '无描述'}
|
||||
</p>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-muted-foreground mb-4">
|
||||
<InfoRow
|
||||
label="接入方式"
|
||||
value={cluster.configType === 'token' ? 'Token' : 'Kubeconfig'}
|
||||
/>
|
||||
{cluster.apiServer && (
|
||||
<InfoRow
|
||||
label="API Server"
|
||||
value={cluster.apiServer}
|
||||
valueClass="truncate max-w-[150px]"
|
||||
/>
|
||||
)}
|
||||
<InfoRow label="版本" value={cluster.version || '未知'} />
|
||||
<InfoRow label="节点数" value={String(cluster.nodesCount || 0)} />
|
||||
<InfoRow
|
||||
label="最后连接"
|
||||
value={
|
||||
cluster.lastConnected
|
||||
? new Date(cluster.lastConnected).toLocaleString()
|
||||
: '从未'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-3 border-t border-border">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onViewInfo(cluster)}
|
||||
>
|
||||
<Eye className="w-3 h-3 mr-1" />
|
||||
详情
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onValidate(cluster.id)}
|
||||
disabled={validating === cluster.id}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3 h-3 mr-1 ${validating === cluster.id ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
验证
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label={`删除集群 ${cluster.name}`}
|
||||
className="text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => onDelete(cluster)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { Server } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { clusterApi } from '@/api'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import type { Cluster, ClusterInfo } from '@/types'
|
||||
|
||||
interface ClusterDetailDialogProps {
|
||||
cluster: Cluster | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** 集群详情弹窗 — 自负责拉取集群信息(打开即加载,卸载取消语义由加载态覆盖) */
|
||||
export const ClusterDetailDialog = memo(function ClusterDetailDialog({
|
||||
cluster,
|
||||
onClose,
|
||||
}: ClusterDetailDialogProps) {
|
||||
const [info, setInfo] = useState<ClusterInfo | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!cluster) return
|
||||
let cancelled = false
|
||||
clusterApi
|
||||
.getInfo(cluster.id)
|
||||
.then((data) => {
|
||||
if (!cancelled) setInfo(data)
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : '加载集群详情失败')
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [cluster])
|
||||
|
||||
return (
|
||||
<Dialog open={cluster !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Server className="w-5 h-5 text-info" />
|
||||
{cluster?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{error ? (
|
||||
<ErrorState message={error} />
|
||||
) : info ? (
|
||||
<ClusterDetail info={info} />
|
||||
) : (
|
||||
<LoadingSpinner className="h-32" />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
|
||||
/** 集群详情内容:版本/上下文/节点/命名空间 */
|
||||
const ClusterDetail = memo(function ClusterDetail({ info }: { info: ClusterInfo }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="p-3 bg-muted rounded-lg">
|
||||
<p className="text-xs text-muted-foreground">版本</p>
|
||||
<p className="text-sm font-medium">{info.version || '未知'}</p>
|
||||
</div>
|
||||
<div className="p-3 bg-muted rounded-lg">
|
||||
<p className="text-xs text-muted-foreground">当前上下文</p>
|
||||
<p className="text-sm font-medium">{info.currentContext || '默认'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-2">节点({info.nodes.length})</h4>
|
||||
<div className="space-y-2">
|
||||
{info.nodes.map((node) => (
|
||||
<div
|
||||
key={node.name}
|
||||
className="p-3 border border-border rounded-lg"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium text-sm">{node.name}</span>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-full text-xs ${
|
||||
node.status === 'Ready'
|
||||
? 'bg-success/10 text-primary'
|
||||
: 'bg-destructive/10 text-destructive'
|
||||
}`}
|
||||
>
|
||||
{node.status === 'Ready' ? '就绪' : '未就绪'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 mt-2 text-xs text-muted-foreground">
|
||||
<span>IP:{node.internalIP}</span>
|
||||
<span>系统:{node.os}/{node.arch}</span>
|
||||
<span>版本:{node.version}</span>
|
||||
</div>
|
||||
{node.roles.length > 0 && (
|
||||
<div className="flex gap-1 mt-2">
|
||||
{node.roles.map((role) => (
|
||||
<span
|
||||
key={role}
|
||||
className="px-1.5 py-0.5 bg-info/10 text-info rounded text-xs"
|
||||
>
|
||||
{role}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-2">命名空间</h4>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{info.namespaces.map((ns) => (
|
||||
<span
|
||||
key={ns}
|
||||
className="px-2 py-0.5 bg-muted rounded text-xs"
|
||||
>
|
||||
{ns}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,263 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { Key, FileKey } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { clusterApi } from '@/api'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
// 从 kubeconfig 文本自动提取 server 地址
|
||||
const parseApiServer = (kubeconfig: string): string => {
|
||||
const m = kubeconfig.match(/^\s*server:\s*(\S+)/m)
|
||||
return m ? m[1] : ''
|
||||
}
|
||||
|
||||
// 表单 schema:zod 为唯一校验源,消息中文且具体
|
||||
const clusterFormSchema = z
|
||||
.object({
|
||||
name: z.string().min(1, '请输入集群名称'),
|
||||
description: z.string().optional(),
|
||||
configType: z.enum(['kubeconfig', 'token']),
|
||||
kubeconfig: z.string().optional(),
|
||||
apiServer: z.string().optional(),
|
||||
token: z.string().optional(),
|
||||
context: z.string().optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.configType === 'kubeconfig' && !data.kubeconfig?.trim()) {
|
||||
ctx.addIssue({ code: 'custom', path: ['kubeconfig'], message: '请填写 kubeconfig 内容' })
|
||||
}
|
||||
if (data.configType === 'token') {
|
||||
if (!data.apiServer?.trim()) {
|
||||
ctx.addIssue({ code: 'custom', path: ['apiServer'], message: '请填写 API Server 地址' })
|
||||
}
|
||||
if (!data.token?.trim()) {
|
||||
ctx.addIssue({ code: 'custom', path: ['token'], message: '请填写 Token' })
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
type ClusterFormValues = z.infer<typeof clusterFormSchema>
|
||||
|
||||
const DEFAULT_VALUES: ClusterFormValues = {
|
||||
name: '',
|
||||
description: '',
|
||||
configType: 'kubeconfig',
|
||||
kubeconfig: '',
|
||||
apiServer: '',
|
||||
token: '',
|
||||
context: '',
|
||||
}
|
||||
|
||||
interface ClusterFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** 创建成功回调(父级刷新列表并关闭弹窗) */
|
||||
onCreated: () => void
|
||||
}
|
||||
|
||||
/** 添加集群弹窗 — react-hook-form + zod,自包含表单逻辑,页面只传开关与回调 */
|
||||
export const ClusterFormDialog = memo(function ClusterFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
}: ClusterFormDialogProps) {
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const form = useForm<ClusterFormValues>({
|
||||
resolver: zodResolver(clusterFormSchema),
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
})
|
||||
const configType = form.watch('configType')
|
||||
const kubeconfig = form.watch('kubeconfig')
|
||||
|
||||
// 打开时重置(编辑回填/关闭重置时机明确)
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset(DEFAULT_VALUES)
|
||||
}
|
||||
}, [open, form])
|
||||
|
||||
const onSubmit = form.handleSubmit(async (values) => {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await clusterApi.create({
|
||||
name: values.name,
|
||||
description: values.description,
|
||||
configType: values.configType,
|
||||
apiServer: values.configType === 'token' ? values.apiServer : undefined,
|
||||
kubeconfig: values.configType === 'kubeconfig' ? values.kubeconfig : undefined,
|
||||
token: values.configType === 'token' ? values.token : undefined,
|
||||
context: values.context,
|
||||
})
|
||||
onOpenChange(false)
|
||||
onCreated()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '创建集群失败')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>添加 Kubernetes 集群</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>集群名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="production-cluster" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>描述</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="生产环境日志集群" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormItem>
|
||||
<FormLabel>接入方式</FormLabel>
|
||||
<FormControl>
|
||||
<Tabs
|
||||
value={configType}
|
||||
onValueChange={(v) =>
|
||||
form.setValue('configType', v as ClusterFormValues['configType'])
|
||||
}
|
||||
>
|
||||
<TabsList>
|
||||
<TabsTrigger value="kubeconfig">
|
||||
<FileKey className="w-3.5 h-3.5 mr-1" /> Kubeconfig
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="token">
|
||||
<Key className="w-3.5 h-3.5 mr-1" /> Token
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="kubeconfig" className="space-y-2 pt-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="kubeconfig"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Kubeconfig 内容 *</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="粘贴 kubeconfig YAML(自动识别 API Server)..."
|
||||
className="min-h-[200px] font-mono text-xs"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{kubeconfig && parseApiServer(kubeconfig) && (
|
||||
<p className="text-xs text-primary">
|
||||
已识别 API Server:{parseApiServer(kubeconfig)}
|
||||
</p>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="token" className="space-y-2 pt-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="apiServer"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>API Server *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="https://10.0.0.1:6443" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="token"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Token *</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="粘贴 Service Account Token..."
|
||||
className="min-h-[120px] font-mono text-xs"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
采用 insecure 模式,便于内网/自签证书集群接入
|
||||
</p>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
|
||||
{configType === 'kubeconfig' && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="context"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>上下文(可选)</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="留空则使用默认上下文" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '添加中...' : '添加集群'}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,164 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Server, Plus } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { clusterApi, deploymentApi, collectorApi } from '@/api'
|
||||
import { PageContainer } from '@/components/PageContainer'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import { PaginationBar } from '@/components/PaginationBar'
|
||||
import { ConfirmDialog } from '@/components/ConfirmDialog'
|
||||
import { toast } from 'sonner'
|
||||
import { useListQuery } from '@/hooks/useListQuery'
|
||||
import type { Cluster } from '@/types'
|
||||
import { ClusterCard } from './components/ClusterCard'
|
||||
import { ClusterFormDialog } from './components/ClusterFormDialog'
|
||||
import { ClusterDetailDialog } from './components/ClusterDetailDialog'
|
||||
|
||||
/**
|
||||
* 集群管理页 — 只做编排:数据走 useListQuery(取消+版本号),
|
||||
* 卡片/表单/详情/删除确认均为域内子组件。成功操作静默(列表刷新即反馈)。
|
||||
*/
|
||||
const ClustersPage = memo(function ClustersPage() {
|
||||
const query = useListQuery<Cluster>((params, signal) =>
|
||||
clusterApi.list(params, { signal })
|
||||
)
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [detailCluster, setDetailCluster] = useState<Cluster | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<Cluster | null>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [validating, setValidating] = useState<number | null>(null)
|
||||
|
||||
// 验证后延时刷新列表的定时器(卸载清理)
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
useEffect(() => {
|
||||
const timers = timeoutsRef.current
|
||||
return () => {
|
||||
timers.forEach((id) => clearTimeout(id))
|
||||
}
|
||||
}, [])
|
||||
|
||||
// 删除保护:引用检查(部署/采集器仍指向该集群时警告)
|
||||
const [refCount, setRefCount] = useState<{ dep: number; col: number }>({ dep: 0, col: 0 })
|
||||
useEffect(() => {
|
||||
if (!deleteTarget) return
|
||||
Promise.all([
|
||||
deploymentApi.list({ page: 1, pageSize: 100 }),
|
||||
collectorApi.list({ page: 1, pageSize: 100 }),
|
||||
]).then(([d, c]) => {
|
||||
setRefCount({
|
||||
dep: d.list.filter((x) => x.clusterID === deleteTarget.id).length,
|
||||
col: c.list.filter((x) => x.clusterID === deleteTarget.id).length,
|
||||
})
|
||||
}).catch(() => setRefCount({ dep: 0, col: 0 }))
|
||||
}, [deleteTarget])
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
const id = deleteTarget?.id
|
||||
if (!id) return
|
||||
setDeleting(true)
|
||||
try {
|
||||
await clusterApi.remove(id)
|
||||
setDeleteTarget(null)
|
||||
query.refresh()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '删除集群失败')
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}, [deleteTarget, query])
|
||||
|
||||
const handleValidate = useCallback(
|
||||
async (id: number) => {
|
||||
setValidating(id)
|
||||
try {
|
||||
await clusterApi.validate(id)
|
||||
timeoutsRef.current.push(setTimeout(() => query.refresh(), 3000))
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '验证失败')
|
||||
} finally {
|
||||
timeoutsRef.current.push(setTimeout(() => setValidating(null), 3000))
|
||||
}
|
||||
},
|
||||
[query]
|
||||
)
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
title="集群管理"
|
||||
description="管理用于 Loki 部署的 Kubernetes 集群"
|
||||
action={
|
||||
<Button
|
||||
className="bg-primary hover:bg-primary/90"
|
||||
onClick={() => setFormOpen(true)}
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
添加集群
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{query.loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : query.error ? (
|
||||
<ErrorState message={query.error} onRetry={query.refresh} />
|
||||
) : query.list.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Server}
|
||||
title="暂无集群"
|
||||
description="添加第一个 Kubernetes 集群开始使用"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{query.list.map((cluster) => (
|
||||
<ClusterCard
|
||||
key={cluster.id}
|
||||
cluster={cluster}
|
||||
validating={validating}
|
||||
onViewInfo={setDetailCluster}
|
||||
onValidate={handleValidate}
|
||||
onDelete={setDeleteTarget}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<PaginationBar
|
||||
page={query.page}
|
||||
pageSize={query.pageSize}
|
||||
total={query.total}
|
||||
onPageChange={query.setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<ClusterFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
onCreated={query.reload}
|
||||
/>
|
||||
|
||||
<ClusterDetailDialog
|
||||
key={detailCluster?.id ?? 'none'}
|
||||
cluster={detailCluster}
|
||||
onClose={() => setDetailCluster(null)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteTarget(null)
|
||||
}}
|
||||
name={deleteTarget?.name}
|
||||
loading={deleting}
|
||||
description={
|
||||
refCount.dep + refCount.col > 0
|
||||
? `确定要删除「${deleteTarget?.name}」吗?警告:仍有 ${refCount.dep} 个部署、${refCount.col} 个采集策略引用该集群,删除后它们将无法工作。`
|
||||
: undefined
|
||||
}
|
||||
onConfirm={handleDelete}
|
||||
/>
|
||||
</PageContainer>
|
||||
)
|
||||
})
|
||||
|
||||
export default ClustersPage
|
||||
@@ -0,0 +1,144 @@
|
||||
import { memo } from 'react'
|
||||
import {
|
||||
RadioTower,
|
||||
Trash2,
|
||||
Upload,
|
||||
Download,
|
||||
Server,
|
||||
Monitor,
|
||||
Cloud,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { StatusBadge } from '@/components/StatusBadge'
|
||||
import { InfoRow } from '@/components/InfoRow'
|
||||
import type { Collector } from '@/types'
|
||||
|
||||
// 采集器类型元数据(图标 + 类型徽章配色)
|
||||
const COLLECTOR_TYPE_META: Record<string, { label: string; icon: LucideIcon; color: string }> = {
|
||||
'host-promtail': { label: '主机 Promtail', icon: Monitor, color: 'bg-purple-100 text-purple-700' },
|
||||
'k8s-daemonset': { label: 'K8s DaemonSet', icon: Cloud, color: 'bg-info/10 text-info' },
|
||||
'k8s-fluentbit-sidecar': { label: 'K8s Sidecar', icon: Server, color: 'bg-cyan-100 text-cyan-700' },
|
||||
}
|
||||
|
||||
const FALLBACK_META = { label: '', icon: RadioTower, color: 'bg-muted text-slate-600' }
|
||||
|
||||
interface CollectorCardProps {
|
||||
collector: Collector
|
||||
/** 部署/卸载进行中的采集器 ID(按钮 loading 态) */
|
||||
operating: number | null
|
||||
onInstall: (id: number) => void
|
||||
onUninstall: (id: number) => void
|
||||
onDelete: (c: Collector) => void
|
||||
}
|
||||
|
||||
/** 采集器卡片 — 列表项展示与操作入口(部署/卸载/删除) */
|
||||
export const CollectorCard = memo(function CollectorCard({
|
||||
collector,
|
||||
operating,
|
||||
onInstall,
|
||||
onUninstall,
|
||||
onDelete,
|
||||
}: CollectorCardProps) {
|
||||
const meta = COLLECTOR_TYPE_META[collector.type] ?? {
|
||||
...FALLBACK_META,
|
||||
label: collector.type,
|
||||
}
|
||||
const Icon = meta.icon
|
||||
const isBusy = operating === collector.id
|
||||
|
||||
return (
|
||||
<Card className="border-border hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Icon className="w-5 h-5 text-primary flex-shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<h3 className="font-semibold text-foreground truncate">
|
||||
{collector.name}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
关联 Loki:{collector.lokiDeployment?.name || '未知'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<StatusBadge status={collector.status} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-muted-foreground mb-3">
|
||||
<div className="flex justify-between">
|
||||
<span>类型</span>
|
||||
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${meta.color}`}>
|
||||
{meta.label}
|
||||
</span>
|
||||
</div>
|
||||
{collector.host && (
|
||||
<InfoRow
|
||||
label="主机"
|
||||
value={`${collector.host.name}(${collector.host.hostIP})`}
|
||||
valueClass="truncate max-w-[200px]"
|
||||
/>
|
||||
)}
|
||||
{collector.cluster && (
|
||||
<InfoRow
|
||||
label="集群"
|
||||
value={collector.cluster.name}
|
||||
valueClass="truncate max-w-[200px]"
|
||||
/>
|
||||
)}
|
||||
{collector.targetDeployment && (
|
||||
<InfoRow
|
||||
label="目标 Deployment"
|
||||
value={collector.targetDeployment}
|
||||
valueClass="truncate max-w-[200px]"
|
||||
/>
|
||||
)}
|
||||
{collector.namespace && (
|
||||
<InfoRow label="命名空间" value={collector.namespace} valueClass="truncate max-w-[200px]" />
|
||||
)}
|
||||
{collector.logPath && (
|
||||
<InfoRow label="日志路径" value={collector.logPath} valueClass="truncate max-w-[200px]" />
|
||||
)}
|
||||
{collector.statusMessage && (
|
||||
<div className="p-2 bg-muted rounded text-xs mt-1">
|
||||
{collector.statusMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-3 border-t border-border">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onInstall(collector.id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
<Upload className="w-3 h-3 mr-1" />
|
||||
{isBusy ? '处理中...' : '部署'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onUninstall(collector.id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
<Download className="w-3 h-3 mr-1" />
|
||||
卸载
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label={`删除采集器 ${collector.name}`}
|
||||
className="text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => onDelete(collector)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,369 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { collectorApi } from '@/api'
|
||||
import { statusLabel } from '@/lib/utils'
|
||||
import { toast } from 'sonner'
|
||||
import type { Cluster, Host, LokiDeployment } from '@/types'
|
||||
|
||||
type CollectorType = 'host-promtail' | 'k8s-daemonset' | 'k8s-fluentbit-sidecar'
|
||||
|
||||
const COLLECTOR_TYPES: Array<{ value: CollectorType; label: string }> = [
|
||||
{ value: 'host-promtail', label: '主机 Promtail(SSH)' },
|
||||
{ value: 'k8s-daemonset', label: 'K8s Promtail DaemonSet' },
|
||||
{ value: 'k8s-fluentbit-sidecar', label: 'K8s Fluent Bit Sidecar' },
|
||||
]
|
||||
|
||||
// 表单 schema:zod 为唯一校验源,消息中文且具体
|
||||
const collectorFormSchema = z
|
||||
.object({
|
||||
name: z.string().min(1, '请输入采集器名称'),
|
||||
type: z.enum(['host-promtail', 'k8s-daemonset', 'k8s-fluentbit-sidecar']),
|
||||
lokiDeploymentID: z.string().min(1, '请选择关联的 Loki 部署'),
|
||||
hostID: z.string(),
|
||||
clusterID: z.string(),
|
||||
targetDeployment: z.string(),
|
||||
namespace: z.string(),
|
||||
logPath: z.string(),
|
||||
/** 旧版表单即无录入入口,仅透传(默认空串) */
|
||||
labels: z.string(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.type === 'host-promtail' && !data.hostID) {
|
||||
ctx.addIssue({ code: 'custom', path: ['hostID'], message: '请选择目标主机' })
|
||||
}
|
||||
if (data.type !== 'host-promtail' && !data.clusterID) {
|
||||
ctx.addIssue({ code: 'custom', path: ['clusterID'], message: '请选择目标集群' })
|
||||
}
|
||||
if (
|
||||
data.type === 'k8s-fluentbit-sidecar' &&
|
||||
!data.targetDeployment.trim()
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['targetDeployment'],
|
||||
message: '请填写目标 Deployment 名称',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
type CollectorFormValues = z.infer<typeof collectorFormSchema>
|
||||
|
||||
const DEFAULT_VALUES: CollectorFormValues = {
|
||||
name: '',
|
||||
type: 'host-promtail',
|
||||
lokiDeploymentID: '',
|
||||
hostID: '',
|
||||
clusterID: '',
|
||||
targetDeployment: '',
|
||||
namespace: '',
|
||||
logPath: '',
|
||||
labels: '',
|
||||
}
|
||||
|
||||
interface CollectorFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** 创建成功回调(父级刷新列表并回到第 1 页) */
|
||||
onCreated: () => void
|
||||
deployments: LokiDeployment[]
|
||||
clusters: Cluster[]
|
||||
hosts: Host[]
|
||||
}
|
||||
|
||||
/** 新建采集器弹窗 — react-hook-form + zod;类型切换条件显示主机/集群选择与字段 */
|
||||
export const CollectorFormDialog = memo(function CollectorFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
deployments,
|
||||
clusters,
|
||||
hosts,
|
||||
}: CollectorFormDialogProps) {
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const form = useForm<CollectorFormValues>({
|
||||
resolver: zodResolver(collectorFormSchema),
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
})
|
||||
const collectorType = form.watch('type')
|
||||
|
||||
// 打开时重置(关闭重置时机明确)
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset(DEFAULT_VALUES)
|
||||
}
|
||||
}, [open, form])
|
||||
|
||||
const onSubmit = form.handleSubmit(async (values) => {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await collectorApi.create({
|
||||
name: values.name,
|
||||
type: values.type,
|
||||
lokiDeploymentID: Number(values.lokiDeploymentID),
|
||||
hostID:
|
||||
values.type === 'host-promtail' && values.hostID
|
||||
? Number(values.hostID)
|
||||
: undefined,
|
||||
clusterID:
|
||||
values.type !== 'host-promtail' && values.clusterID
|
||||
? Number(values.clusterID)
|
||||
: undefined,
|
||||
targetDeployment:
|
||||
values.type === 'k8s-fluentbit-sidecar' ? values.targetDeployment : undefined,
|
||||
namespace: values.type !== 'host-promtail' ? values.namespace : undefined,
|
||||
logPath: values.logPath,
|
||||
labels: values.labels,
|
||||
})
|
||||
onOpenChange(false)
|
||||
onCreated()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '创建采集器失败')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
})
|
||||
|
||||
const isHostType = collectorType === 'host-promtail'
|
||||
const isK8sType = collectorType !== 'host-promtail'
|
||||
const isSidecarType = collectorType === 'k8s-fluentbit-sidecar'
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>添加采集策略</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="app-logs-collector" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>采集器类型</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{COLLECTOR_TYPES.map((t) => (
|
||||
<SelectItem key={t.value} value={t.value}>
|
||||
{t.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="lokiDeploymentID"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>关联 Loki 部署 *</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择已部署的 Loki(推送目标)" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{deployments.map((d) => (
|
||||
<SelectItem key={d.id} value={String(d.id)}>
|
||||
{d.name}({statusLabel(d.status)})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{isHostType && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="hostID"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>目标主机 *</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择主机" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{hosts.map((h) => (
|
||||
<SelectItem key={h.id} value={String(h.id)}>
|
||||
{h.name}({h.hostIP})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isK8sType && (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="clusterID"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>目标集群 *</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择集群" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{clusters.map((c) => (
|
||||
<SelectItem key={c.id} value={String(c.id)}>
|
||||
{c.name}({statusLabel(c.status)})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="namespace"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>命名空间</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder={collectorType === 'k8s-daemonset' ? 'logging' : 'default'}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{isSidecarType && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="targetDeployment"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>目标 Deployment *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="my-app" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="logPath"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>采集日志路径</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder={isHostType ? '/var/log/*.log' : '/var/log/app/*.log'}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
{isHostType && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
支持 glob 通配(如 /var/log/*.log /var/log/syslog);多个路径用逗号分隔
|
||||
</p>
|
||||
)}
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="labels"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>自定义标签(JSON,可选)</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder='{"env": "prod", "team": "ops"}' {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
合法 JSON 时将附加到每条日志的标签,便于在 Loki/Grafana 中筛选;留空则不加
|
||||
</p>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '创建中...' : '创建并部署'}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,179 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { RadioTower, Plus } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { clusterApi, collectorApi, deploymentApi, hostApi } from '@/api'
|
||||
import { PageContainer } from '@/components/PageContainer'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import { PaginationBar } from '@/components/PaginationBar'
|
||||
import { ConfirmDialog } from '@/components/ConfirmDialog'
|
||||
import { toast } from 'sonner'
|
||||
import { useListQuery } from '@/hooks/useListQuery'
|
||||
import type { Cluster, Collector, Host, LokiDeployment } from '@/types'
|
||||
import { CollectorCard } from './components/CollectorCard'
|
||||
import { CollectorFormDialog } from './components/CollectorFormDialog'
|
||||
|
||||
/**
|
||||
* 日志采集页 — 采集策略编排:列表走 useListQuery(取消+版本号),
|
||||
* Loki 部署/集群/主机下拉数据为页面局部加载(与列表分页解耦)。
|
||||
* 部署(install)/卸载(uninstall)/删除保留;成功操作静默(列表刷新即反馈)。
|
||||
*/
|
||||
const CollectorsPage = memo(function CollectorsPage() {
|
||||
const query = useListQuery<Collector>((params, signal) =>
|
||||
collectorApi.list(params, { signal })
|
||||
)
|
||||
|
||||
// 表单下拉数据:一次性局部加载
|
||||
const [deployments, setDeployments] = useState<LokiDeployment[]>([])
|
||||
const [clusters, setClusters] = useState<Cluster[]>([])
|
||||
const [hosts, setHosts] = useState<Host[]>([])
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [deleteTarget, setDeleteTarget] = useState<Collector | null>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
/** 部署/卸载指令进行中的采集器 ID(按钮 loading + 防重复点击) */
|
||||
const [operating, setOperating] = useState<number | null>(null)
|
||||
|
||||
// 操作后延时刷新列表/清除按钮态的定时器(卸载清理)
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
timeoutsRef.current.forEach((id) => clearTimeout(id))
|
||||
timeoutsRef.current = []
|
||||
}
|
||||
}, [])
|
||||
|
||||
const addTimeout = useCallback((cb: () => void, delay: number) => {
|
||||
timeoutsRef.current.push(setTimeout(cb, delay))
|
||||
}, [])
|
||||
|
||||
// 下拉数据加载(失败仅提示,不阻塞列表)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
Promise.all([
|
||||
deploymentApi.list({ page: 1, pageSize: 100 }),
|
||||
clusterApi.list({ page: 1, pageSize: 100 }),
|
||||
hostApi.list({ page: 1, pageSize: 100 }),
|
||||
])
|
||||
.then(([deployRes, clusterRes, hostRes]) => {
|
||||
if (cancelled) return
|
||||
setDeployments(deployRes.list)
|
||||
setClusters(clusterRes.list)
|
||||
setHosts(hostRes.list)
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err instanceof Error ? err.message : '加载 Loki 部署/集群/主机数据失败')
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleAction = useCallback(
|
||||
async (id: number, action: 'install' | 'uninstall') => {
|
||||
setOperating(id)
|
||||
try {
|
||||
await collectorApi[action](id)
|
||||
addTimeout(query.refresh, 3000)
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : action === 'install' ? '部署采集器失败' : '卸载采集器失败'
|
||||
)
|
||||
} finally {
|
||||
addTimeout(() => setOperating(null), 3000)
|
||||
}
|
||||
},
|
||||
[query, addTimeout]
|
||||
)
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
const id = deleteTarget?.id
|
||||
if (!id) return
|
||||
setDeleting(true)
|
||||
try {
|
||||
await collectorApi.remove(id)
|
||||
setDeleteTarget(null)
|
||||
query.refresh()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '删除采集器失败')
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}, [deleteTarget, query])
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
title="日志采集"
|
||||
description="为主机与集群配置日志采集策略,日志将推送到关联的 Loki"
|
||||
action={
|
||||
<Button
|
||||
className="bg-primary hover:bg-primary/90"
|
||||
onClick={() => setFormOpen(true)}
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
添加采集策略
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{query.loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : query.error ? (
|
||||
<ErrorState message={query.error} onRetry={query.refresh} />
|
||||
) : query.list.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={RadioTower}
|
||||
title='暂无采集策略'
|
||||
description="新建一个日志采集器,关联已部署的 Loki"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{query.list.map((collector) => (
|
||||
<CollectorCard
|
||||
key={collector.id}
|
||||
collector={collector}
|
||||
operating={operating}
|
||||
onInstall={(id) => handleAction(id, 'install')}
|
||||
onUninstall={(id) => handleAction(id, 'uninstall')}
|
||||
onDelete={setDeleteTarget}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<PaginationBar
|
||||
page={query.page}
|
||||
pageSize={query.pageSize}
|
||||
total={query.total}
|
||||
onPageChange={query.setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<CollectorFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
onCreated={query.reload}
|
||||
deployments={deployments}
|
||||
clusters={clusters}
|
||||
hosts={hosts}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteTarget(null)
|
||||
}}
|
||||
name={deleteTarget?.name}
|
||||
description={
|
||||
deleteTarget
|
||||
? `确定要删除「${deleteTarget.name}」吗?删除时将自动卸载采集端,此操作不可恢复。`
|
||||
: undefined
|
||||
}
|
||||
loading={deleting}
|
||||
onConfirm={handleDelete}
|
||||
/>
|
||||
</PageContainer>
|
||||
)
|
||||
})
|
||||
|
||||
export default CollectorsPage
|
||||
@@ -0,0 +1,74 @@
|
||||
import { memo } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Rocket } from 'lucide-react'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { StatusIcon } from '@/components/StatusBadge'
|
||||
import { getStatusColorClass } from '@/components/status-config'
|
||||
import { statusLabel } from '@/lib/utils'
|
||||
import type { LokiDeployment } from '@/types'
|
||||
|
||||
/** 最近部署卡片 — 展示最近 5 条部署,点击跳转部署页 */
|
||||
export const RecentDeploymentsCard = memo(function RecentDeploymentsCard({
|
||||
deployments,
|
||||
onViewAll,
|
||||
}: {
|
||||
deployments: LokiDeployment[]
|
||||
onViewAll: () => void
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
return (
|
||||
<Card className="border-border">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">最近部署</CardTitle>
|
||||
<button
|
||||
onClick={onViewAll}
|
||||
className="text-xs text-primary hover:text-primary/80 font-medium"
|
||||
>
|
||||
查看全部
|
||||
</button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{deployments.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Rocket}
|
||||
title="暂无部署"
|
||||
description="创建你的第一个 Loki 部署"
|
||||
/>
|
||||
) : (
|
||||
deployments.map((d) => (
|
||||
<div
|
||||
key={d.id}
|
||||
className="flex items-center justify-between p-3 rounded-lg bg-muted/50 hover:bg-muted dark:hover:bg-slate-800 transition-colors cursor-pointer"
|
||||
onClick={() => navigate('/deployments')}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<StatusIcon status={d.status} size="sm" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium text-foreground truncate">
|
||||
{d.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{d.mode} · {d.namespace || 'loki'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-full text-xs font-medium flex-shrink-0 ${getStatusColorClass(
|
||||
d.status
|
||||
)}`}
|
||||
>
|
||||
{statusLabel(d.status)}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { memo } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { getStatusColorClass } from '@/components/status-config'
|
||||
import { statusLabel } from '@/lib/utils'
|
||||
|
||||
// 用具体结构类型而非泛型:memo 包裹泛型组件会导致 TS 无法从 props 推断 T
|
||||
interface ResourceItem {
|
||||
id: number
|
||||
name: string
|
||||
status: string
|
||||
hostIP?: string
|
||||
}
|
||||
|
||||
interface ResourceListCardProps {
|
||||
title: string
|
||||
icon: React.ReactNode
|
||||
items: ResourceItem[]
|
||||
onManage: () => void
|
||||
getItemIcon: (item: ResourceItem) => React.ReactNode
|
||||
getItemLabel: (item: ResourceItem) => string
|
||||
getItemStatus: (item: ResourceItem) => string
|
||||
getItemExtra?: (item: ResourceItem) => string | undefined
|
||||
}
|
||||
|
||||
/** 资源列表卡片 — 集群/主机快捷列表(仪表盘) */
|
||||
export const ResourceListCard = memo(function ResourceListCard({
|
||||
title,
|
||||
icon,
|
||||
items,
|
||||
onManage,
|
||||
getItemIcon,
|
||||
getItemLabel,
|
||||
getItemStatus,
|
||||
getItemExtra,
|
||||
}: ResourceListCardProps) {
|
||||
return (
|
||||
<Card className="border-border">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
{icon}
|
||||
{title}
|
||||
</CardTitle>
|
||||
<button
|
||||
onClick={onManage}
|
||||
className="text-xs text-primary hover:text-primary/80 font-medium"
|
||||
>
|
||||
管理
|
||||
</button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{items.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">暂无{title}</p>
|
||||
) : (
|
||||
items.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex items-center justify-between p-2 rounded-md hover:bg-muted dark:hover:bg-slate-800 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{getItemIcon(item)}
|
||||
<span className="text-sm truncate">{getItemLabel(item)}</span>
|
||||
{getItemExtra?.(item) && (
|
||||
<span className="text-xs text-muted-foreground flex-shrink-0">
|
||||
{getItemExtra(item)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded-full text-xs flex-shrink-0 ${getStatusColorClass(
|
||||
getItemStatus(item)
|
||||
)}`}
|
||||
>
|
||||
{statusLabel(getItemStatus(item))}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
import { memo } from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
|
||||
interface StatCardProps {
|
||||
label: string
|
||||
value: string | number
|
||||
icon: LucideIcon
|
||||
iconColor: string
|
||||
iconBg: string
|
||||
sub?: {
|
||||
icon: LucideIcon
|
||||
color: string
|
||||
textColor: string
|
||||
text: string
|
||||
}
|
||||
}
|
||||
|
||||
/** 指标卡 — 数字 + 图标 + 副指标(仪表盘通用件) */
|
||||
export const StatCard = memo(function StatCard({
|
||||
label,
|
||||
value,
|
||||
icon: Icon,
|
||||
iconColor,
|
||||
iconBg,
|
||||
sub,
|
||||
}: StatCardProps) {
|
||||
const SubIcon = sub?.icon
|
||||
return (
|
||||
<Card className="border-border">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">{label}</p>
|
||||
<p className="text-3xl font-bold text-foreground mt-1 tabular-nums">
|
||||
{value}
|
||||
</p>
|
||||
</div>
|
||||
<div className={`w-12 h-12 rounded-xl ${iconBg} flex items-center justify-center`}>
|
||||
<Icon className={`w-6 h-6 ${iconColor}`} />
|
||||
</div>
|
||||
</div>
|
||||
{sub && SubIcon && (
|
||||
<div className="flex items-center gap-2 mt-4">
|
||||
<SubIcon className={`w-4 h-4 ${sub.color}`} />
|
||||
<span className={`text-xs ${sub.textColor}`}>{sub.text}</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { clusterApi, deploymentApi, hostApi } from '@/api'
|
||||
import type { Cluster, DashboardStats, Host, LokiDeployment } from '@/types'
|
||||
|
||||
export interface DashboardData {
|
||||
stats: DashboardStats
|
||||
deployments: LokiDeployment[]
|
||||
clusters: Cluster[]
|
||||
hosts: Host[]
|
||||
}
|
||||
|
||||
const REFRESH_INTERVAL = 10000 // 10 秒自动刷新
|
||||
|
||||
/**
|
||||
* 仪表盘数据 hook — 轮询 + AbortController/版本号双重防护。
|
||||
* - 页面隐藏(document.hidden)时暂停轮询,重新可见立即刷新
|
||||
* - 首次加载失败暴露 error(由页面渲染 ErrorState,不再吞错)
|
||||
*/
|
||||
export function useDashboardStats(intervalMs: number = REFRESH_INTERVAL) {
|
||||
const [data, setData] = useState<DashboardData | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const versionRef = useRef(0)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
abortRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
abortRef.current = controller
|
||||
const version = ++versionRef.current
|
||||
|
||||
try {
|
||||
const [stats, deployRes, clusterRes, hostRes] = await Promise.all([
|
||||
deploymentApi.stats(),
|
||||
deploymentApi.list({ page: 1, pageSize: 5 }, { signal: controller.signal }),
|
||||
clusterApi.list({ page: 1, pageSize: 5 }, { signal: controller.signal }),
|
||||
hostApi.list({ page: 1, pageSize: 5 }, { signal: controller.signal }),
|
||||
])
|
||||
if (version !== versionRef.current) return
|
||||
setData({
|
||||
stats,
|
||||
deployments: deployRes.list,
|
||||
clusters: clusterRes.list,
|
||||
hosts: hostRes.list,
|
||||
})
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
if (version !== versionRef.current) return
|
||||
setError(err instanceof Error ? err.message : '加载仪表盘数据失败')
|
||||
} finally {
|
||||
if (version === versionRef.current) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
if (!document.hidden) void load()
|
||||
}, intervalMs)
|
||||
|
||||
// 重新可见时立即刷新一次
|
||||
const onVisibilityChange = () => {
|
||||
if (!document.hidden) void load()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
|
||||
return () => {
|
||||
clearInterval(intervalId)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
// 写入而非读取:递增使在途响应按版本号判过期(exhaustive-deps 误报)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
versionRef.current++
|
||||
abortRef.current?.abort()
|
||||
}
|
||||
}, [load, intervalMs])
|
||||
|
||||
return { data, loading, error, refresh: load }
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { memo, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Server, Monitor, Activity, TrendingUp, CheckCircle, Rocket, Wand2 } from 'lucide-react'
|
||||
import { Link } from 'react-router'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { PageContainer } from '@/components/PageContainer'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import { useDashboardStats } from './hooks/useDashboardStats'
|
||||
import { StatCard } from './components/StatCard'
|
||||
import { RecentDeploymentsCard } from './components/RecentDeploymentsCard'
|
||||
import { ResourceListCard } from './components/ResourceListCard'
|
||||
import type { DashboardStats } from '@/types'
|
||||
|
||||
const STATUS_ITEMS = [
|
||||
{ key: 'running', label: '运行中', colorClass: 'text-primary' },
|
||||
{ key: 'failed', label: '失败', colorClass: 'text-destructive' },
|
||||
{ key: 'pending', label: '等待中', colorClass: 'text-warning' },
|
||||
] as const
|
||||
|
||||
/**
|
||||
* 仪表盘 — 指标卡 + 最近部署 + 资源快捷列表。
|
||||
* 数据由 useDashboardStats 轮询(页面隐藏暂停);首次失败渲染错误态而非空数据。
|
||||
*/
|
||||
const DashboardPage = memo(function DashboardPage() {
|
||||
const { data, loading, error, refresh } = useDashboardStats()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const navigateTo = useCallback(
|
||||
(path: string) => () => navigate(path),
|
||||
[navigate]
|
||||
)
|
||||
|
||||
const stats = data?.stats ?? null
|
||||
|
||||
const statCards = useMemo(() => {
|
||||
if (!stats) return null
|
||||
const cards: Array<React.ReactNode> = [
|
||||
<StatCard
|
||||
key="deployments"
|
||||
label="部署总数"
|
||||
value={stats.totalDeployments}
|
||||
icon={Rocket}
|
||||
iconColor="text-primary"
|
||||
iconBg="bg-success/10"
|
||||
sub={{
|
||||
icon: TrendingUp,
|
||||
color: 'text-primary',
|
||||
textColor: 'text-primary',
|
||||
text: `${stats.running} 个运行中`,
|
||||
}}
|
||||
/>,
|
||||
<StatCard
|
||||
key="clusters"
|
||||
label="集群"
|
||||
value={stats.clusterCount}
|
||||
icon={Server}
|
||||
iconColor="text-info"
|
||||
iconBg="bg-info/10"
|
||||
sub={{
|
||||
icon: CheckCircle,
|
||||
color: 'text-primary',
|
||||
textColor: 'text-muted-foreground',
|
||||
text: '已接入',
|
||||
}}
|
||||
/>,
|
||||
<StatCard
|
||||
key="hosts"
|
||||
label="主机"
|
||||
value={stats.hostCount}
|
||||
icon={Monitor}
|
||||
iconColor="text-purple-600"
|
||||
iconBg="bg-purple-100 dark:bg-purple-900/30"
|
||||
sub={{
|
||||
icon: CheckCircle,
|
||||
color: 'text-primary',
|
||||
textColor: 'text-muted-foreground',
|
||||
text: 'SSH 就绪',
|
||||
}}
|
||||
/>,
|
||||
]
|
||||
return cards
|
||||
}, [stats])
|
||||
|
||||
if (loading) {
|
||||
return <LoadingSpinner className="h-64" />
|
||||
}
|
||||
|
||||
if (error && !data) {
|
||||
return <ErrorState message={error} onRetry={refresh} />
|
||||
}
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
{/* 快速开始引导:尚无任何部署时置顶(状态推导引导,opsx-sec 范式) */}
|
||||
{(data?.stats.totalDeployments ?? 0) === 0 && (
|
||||
<Card className="border-primary/30 bg-primary/5">
|
||||
<CardContent className="p-5 flex items-center justify-between flex-wrap gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
||||
<Wand2 className="w-5 h-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">三步开始收集日志</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
环境与目标 → 存储 → 部署 Loki 与 Grafana,最后添加采集策略
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button asChild className="bg-primary hover:bg-primary/90">
|
||||
<Link to="/wizard">
|
||||
进入部署向导
|
||||
<Wand2 className="w-4 h-4 ml-1" />
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{statCards}
|
||||
|
||||
{/* 状态概览卡 */}
|
||||
<Card className="border-border">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">状态</p>
|
||||
<div className="flex gap-3 mt-1">
|
||||
{STATUS_ITEMS.map((item) => (
|
||||
<div key={item.key} className="text-center">
|
||||
<p className={`text-lg font-bold tabular-nums ${item.colorClass}`}>
|
||||
{(stats?.[item.key as keyof DashboardStats] as number) || 0}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">{item.label}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-12 h-12 rounded-xl bg-warning/10 flex items-center justify-center">
|
||||
<Activity className="w-6 h-6 text-warning" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Recent Deployments & Quick Resources */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<RecentDeploymentsCard
|
||||
deployments={data?.deployments ?? []}
|
||||
onViewAll={navigateTo('/deployments')}
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
<ResourceListCard
|
||||
title="集群"
|
||||
icon={<Server className="w-4 h-4 text-info" />}
|
||||
items={(data?.clusters ?? []).slice(0, 3)}
|
||||
onManage={navigateTo('/clusters')}
|
||||
getItemIcon={() => <Server className="w-4 h-4 text-info" />}
|
||||
getItemLabel={(c) => c.name}
|
||||
getItemStatus={(c) => c.status}
|
||||
/>
|
||||
<ResourceListCard
|
||||
title="主机"
|
||||
icon={<Monitor className="w-4 h-4 text-purple-500" />}
|
||||
items={(data?.hosts ?? []).slice(0, 3)}
|
||||
onManage={navigateTo('/hosts')}
|
||||
getItemIcon={() => <Monitor className="w-4 h-4 text-purple-500" />}
|
||||
getItemLabel={(h) => h.name}
|
||||
getItemStatus={(h) => h.status}
|
||||
getItemExtra={(h) => h.hostIP}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</PageContainer>
|
||||
)
|
||||
})
|
||||
|
||||
export default DashboardPage
|
||||
@@ -0,0 +1,179 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { Play, Square, RotateCw, Trash2, Terminal, ExternalLink } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { StatusBadge, StatusIcon } from '@/components/StatusBadge'
|
||||
import { InfoRow } from '@/components/InfoRow'
|
||||
import { deploymentApi } from '@/api'
|
||||
import type { LokiDeployment } from '@/types'
|
||||
|
||||
/** 部署目标展示:优先集群,其次主机 */
|
||||
const getTargetLabel = (d: LokiDeployment) => {
|
||||
if (d.cluster) return `集群:${d.cluster.name}`
|
||||
if (d.host) return `主机:${d.host.name}`
|
||||
return '未知'
|
||||
}
|
||||
|
||||
interface DeploymentCardProps {
|
||||
deployment: LokiDeployment
|
||||
/** 部署/重启进行中的部署 ID(按钮 loading 态) */
|
||||
operating: number | null
|
||||
onDeploy: (id: number) => void
|
||||
onStop: (id: number) => void
|
||||
onRestart: (id: number) => void
|
||||
onDelete: (d: LokiDeployment) => void
|
||||
onViewLogs: (d: LokiDeployment) => void
|
||||
}
|
||||
|
||||
/** 部署卡片 — 列表项展示与操作入口(部署/停止/重启/日志/访问/删除) */
|
||||
export const DeploymentCard = memo(function DeploymentCard({
|
||||
deployment: d,
|
||||
operating,
|
||||
onDeploy,
|
||||
onStop,
|
||||
onRestart,
|
||||
onDelete,
|
||||
onViewLogs,
|
||||
}: DeploymentCardProps) {
|
||||
// Loki 就绪探测(运行中时经数据源代理 /ready)
|
||||
const [ready, setReady] = useState<boolean | null>(null)
|
||||
useEffect(() => {
|
||||
if (d.status !== 'running') return
|
||||
let cancelled = false
|
||||
deploymentApi
|
||||
.ready(d.id)
|
||||
.then((r) => {
|
||||
if (!cancelled) setReady(r.ready)
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setReady(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [d.id, d.status])
|
||||
|
||||
const isDeploying = d.status === 'deploying'
|
||||
const isBusy = operating === d.id
|
||||
const canDeploy = d.status === 'pending' || d.status === 'failed' || d.status === 'stopped'
|
||||
|
||||
return (
|
||||
<Card className="border-border hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<StatusIcon status={d.status} size="md" />
|
||||
<div className="min-w-0">
|
||||
<h3 className="font-semibold text-foreground truncate">
|
||||
{d.name}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground">{d.uuid}</p>
|
||||
</div>
|
||||
</div>
|
||||
<StatusBadge status={d.status} />
|
||||
{d.status === 'running' && ready !== null && (
|
||||
<span
|
||||
className={`w-2 h-2 rounded-full ${ready ? 'bg-success' : 'bg-destructive'}`}
|
||||
title={ready ? 'Loki 就绪' : 'Loki 未就绪'}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground mb-3">{d.description || '无描述'}</p>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-muted-foreground mb-4">
|
||||
<InfoRow label="方式" value={d.mode} />
|
||||
<InfoRow label="版本" value={d.version} />
|
||||
<InfoRow label="目标" value={getTargetLabel(d)} />
|
||||
<InfoRow label="命名空间" value={d.namespace || 'loki'} />
|
||||
<InfoRow label="副本数" value={String(d.replicas)} />
|
||||
<InfoRow label="存储" value={d.storageConfig?.name || '本地'} />
|
||||
{d.endpoint && (
|
||||
<InfoRow label="访问地址" value={d.endpoint} valueClass="text-primary truncate max-w-[200px]" />
|
||||
)}
|
||||
{d.grafanaEnabled && d.grafanaEndpoint && (
|
||||
<div className="flex justify-between items-center gap-2">
|
||||
<span>Grafana</span>
|
||||
<a
|
||||
href={d.grafanaEndpoint}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-medium text-primary hover:underline truncate max-w-[200px]"
|
||||
title={`${d.grafanaEndpoint}(admin/admin)`}
|
||||
>
|
||||
{d.grafanaEndpoint.replace(/^https?:\/\//, '')}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{d.statusMessage && (
|
||||
<div className="p-2 bg-muted rounded text-xs">
|
||||
{d.statusMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 pt-3 border-t border-border">
|
||||
{canDeploy ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs bg-success/10 text-primary hover:bg-success/20 border-success/30"
|
||||
onClick={() => onDeploy(d.id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
<Play className="w-3 h-3 mr-1" />
|
||||
{isBusy ? '部署中...' : '部署'}
|
||||
</Button>
|
||||
) : isDeploying ? (
|
||||
<Button variant="outline" size="sm" className="flex-1 text-xs" disabled>
|
||||
<RotateCw className="w-3 h-3 mr-1 animate-spin" />
|
||||
部署中...
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" size="sm" className="text-xs" onClick={() => onStop(d.id)}>
|
||||
<Square className="w-3 h-3 mr-1" />
|
||||
停止
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs"
|
||||
onClick={() => onRestart(d.id)}
|
||||
disabled={isBusy}
|
||||
>
|
||||
<RotateCw className={`w-3 h-3 mr-1 ${isBusy ? 'animate-spin' : ''}`} />
|
||||
重启
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button variant="outline" size="sm" className="text-xs" onClick={() => onViewLogs(d)}>
|
||||
<Terminal className="w-3 h-3 mr-1" />
|
||||
日志
|
||||
</Button>
|
||||
{d.endpoint && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-xs text-primary hover:text-primary/80"
|
||||
onClick={() => window.open(d.endpoint, '_blank', 'noopener,noreferrer')}
|
||||
title="浏览器访问"
|
||||
>
|
||||
<ExternalLink className="w-3 h-3 mr-1" />
|
||||
访问
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label={`删除部署 ${d.name}`}
|
||||
className="text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => onDelete(d)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,442 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { deploymentApi } from '@/api'
|
||||
import { statusLabel } from '@/lib/utils'
|
||||
import { toast } from 'sonner'
|
||||
import type { Cluster, Host, StorageConfig } from '@/types'
|
||||
import {
|
||||
FALLBACK_VERSIONS,
|
||||
isK8sMode,
|
||||
deploymentFormSchema,
|
||||
DEFAULT_VALUES,
|
||||
type DeploymentFormValues,
|
||||
} from '../form-schema'
|
||||
|
||||
interface DeploymentFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** 创建成功回调(父级刷新列表并回到第 1 页) */
|
||||
onCreated: () => void
|
||||
clusters: Cluster[]
|
||||
hosts: Host[]
|
||||
storages: StorageConfig[]
|
||||
}
|
||||
|
||||
/** 创建 Loki 部署弹窗 — react-hook-form + zod;部署方式切换条件显示集群/主机选择 */
|
||||
export const DeploymentFormDialog = memo(function DeploymentFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
clusters,
|
||||
hosts,
|
||||
storages,
|
||||
}: DeploymentFormDialogProps) {
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
// 版本列表来自后端 LokiVersionList,失败回退兜底
|
||||
const [versions, setVersions] = useState<string[]>(FALLBACK_VERSIONS)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
deploymentApi
|
||||
.versions()
|
||||
.then((res) => {
|
||||
if (!cancelled && res.versions?.length) setVersions(res.versions)
|
||||
})
|
||||
.catch(() => {
|
||||
// 静默:保留兜底列表
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const form = useForm<DeploymentFormValues>({
|
||||
resolver: zodResolver(deploymentFormSchema),
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
})
|
||||
const mode = form.watch('mode')
|
||||
const grafanaEnabled = form.watch('grafanaEnabled')
|
||||
|
||||
// 打开时重置(关闭重置时机明确)
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset(DEFAULT_VALUES)
|
||||
}
|
||||
}, [open, form])
|
||||
|
||||
const onSubmit = form.handleSubmit(async (values) => {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await deploymentApi.create({
|
||||
name: values.name,
|
||||
description: values.description,
|
||||
version: values.version,
|
||||
mode: values.mode,
|
||||
clusterID: values.clusterID ? Number(values.clusterID) : undefined,
|
||||
hostID: values.hostID ? Number(values.hostID) : undefined,
|
||||
namespace: values.namespace,
|
||||
storageConfigID: values.storageConfigID ? Number(values.storageConfigID) : 0,
|
||||
authEnabled: values.authEnabled,
|
||||
retentionDays: Number(values.retentionDays),
|
||||
replicas: Number(values.replicas),
|
||||
resourcesCPU: values.resourcesCPU,
|
||||
resourcesMem: values.resourcesMem,
|
||||
storageSize: values.storageSize,
|
||||
grafanaEnabled: values.grafanaEnabled,
|
||||
grafanaVersion: values.grafanaEnabled ? values.grafanaVersion || undefined : undefined,
|
||||
})
|
||||
onOpenChange(false)
|
||||
onCreated()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '创建部署失败')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
})
|
||||
|
||||
const showK8s = isK8sMode(mode)
|
||||
const showHost = mode === 'host-binary'
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>创建 Loki 部署</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>部署名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="production-loki" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>描述</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="生产环境 Loki 日志服务" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="version"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>版本</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{versions.map((v) => (
|
||||
<SelectItem key={v} value={v}>
|
||||
{v}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="mode"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>部署方式</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="k8s-helm">K8s Helm 部署</SelectItem>
|
||||
<SelectItem value="k8s-yaml">K8s YAML 部署</SelectItem>
|
||||
<SelectItem value="host-binary">主机二进制部署</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showK8s && (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="clusterID"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>目标集群 *</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="请选择集群" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{clusters.map((c) => (
|
||||
<SelectItem key={c.id} value={String(c.id)}>
|
||||
{c.name}({statusLabel(c.status)})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="namespace"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>命名空间 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="loki" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{showHost && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="hostID"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>目标主机 *</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="请选择主机" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{hosts.map((h) => (
|
||||
<SelectItem key={h.id} value={String(h.id)}>
|
||||
{h.name}({h.hostIP})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="storageConfigID"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>存储配置</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="请选择存储(可选)" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0">本地存储(默认)</SelectItem>
|
||||
{storages.map((s) => (
|
||||
<SelectItem key={s.id} value={String(s.id)}>
|
||||
{s.name}({s.storageType})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="replicas"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>副本数</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" min={1} max={10} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="retentionDays"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>保留天数</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" min={1} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="storageSize"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>存储容量</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="10Gi" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="resourcesCPU"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>CPU</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="500m" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="resourcesMem"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>内存</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="512Mi" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="authEnabled"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<FormLabel>启用多租户鉴权</FormLabel>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="grafanaEnabled"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
<FormLabel>同时部署 Grafana(可选 — 平台已内置日志查询,通常无需 Grafana)</FormLabel>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{grafanaEnabled && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="grafanaVersion"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Grafana 版本</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="11.3.0" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '创建中...' : '创建部署'}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Terminal } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { deploymentApi } from '@/api'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import type { DeploymentLog, LokiDeployment } from '@/types'
|
||||
|
||||
interface LogViewerDialogProps {
|
||||
deployment: LokiDeployment | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** 部署日志弹窗 — 自负责拉取日志(打开即加载,版本号丢弃过期响应,失败可重试) */
|
||||
export const LogViewerDialog = memo(function LogViewerDialog({
|
||||
deployment,
|
||||
onClose,
|
||||
}: LogViewerDialogProps) {
|
||||
const [logs, setLogs] = useState<DeploymentLog[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
// 版本号令牌:快速重开/切换部署时丢弃过期响应
|
||||
const versionRef = useRef(0)
|
||||
|
||||
const loadLogs = useCallback(async (id: number) => {
|
||||
const current = ++versionRef.current
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await deploymentApi.logs(id, { page: 1, pageSize: 100 })
|
||||
if (current !== versionRef.current) return
|
||||
setLogs(res.list ?? [])
|
||||
} catch (err) {
|
||||
if (current !== versionRef.current) return
|
||||
setError(err instanceof Error ? err.message : '加载部署日志失败')
|
||||
} finally {
|
||||
if (current === versionRef.current) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!deployment) return
|
||||
setLogs([])
|
||||
setError(null)
|
||||
void loadLogs(deployment.id)
|
||||
}, [deployment, loadLogs])
|
||||
|
||||
return (
|
||||
<Dialog open={deployment !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Terminal className="w-5 h-5 text-primary" />
|
||||
部署日志 - {deployment?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{error ? (
|
||||
<ErrorState
|
||||
message={error}
|
||||
onRetry={() => deployment && loadLogs(deployment.id)}
|
||||
/>
|
||||
) : loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : (
|
||||
<LogView logs={logs} />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
|
||||
/** 终端风格日志列表 */
|
||||
const LogView = memo(function LogView({ logs }: { logs: DeploymentLog[] }) {
|
||||
return (
|
||||
<div className="bg-card dark:bg-card text-green-400 font-mono text-xs p-4 rounded-lg h-96 overflow-auto">
|
||||
{logs.length === 0 ? (
|
||||
<p className="text-muted-foreground">暂无日志...</p>
|
||||
) : (
|
||||
logs.map((log) => (
|
||||
<div
|
||||
key={log.id}
|
||||
className={`mb-1 ${
|
||||
log.level === 'error'
|
||||
? 'text-destructive'
|
||||
: log.level === 'warn'
|
||||
? 'text-warning'
|
||||
: log.level === 'success'
|
||||
? 'text-success'
|
||||
: 'text-green-400'
|
||||
}`}
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
[{new Date(log.createdAt).toLocaleTimeString()}]
|
||||
</span>{' '}
|
||||
<span className="font-bold uppercase">{log.level}</span> {log.message}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
// 部署表单 schema 与常量 — zod 为唯一校验源,消息中文且具体
|
||||
// (纯数据/纯逻辑抽离,见开发标准 07 章页面内聚 utils 范式)
|
||||
// 版本下拉兜底值;实际列表运行时从 GET /deployments/versions 拉取
|
||||
export const FALLBACK_VERSIONS = ['3.0.0', '2.9.8', '2.9.7', '2.9.6']
|
||||
|
||||
export type DeploymentMode = 'k8s-helm' | 'k8s-yaml' | 'host-binary'
|
||||
|
||||
export const isK8sMode = (mode: DeploymentMode) =>
|
||||
mode === 'k8s-helm' || mode === 'k8s-yaml'
|
||||
|
||||
// 整数字段校验(输入框 type=number 产出字符串,提交前统一转换)
|
||||
const isPositiveInt = (v: string, min: number, max?: number) => {
|
||||
const n = Number(v)
|
||||
return Number.isInteger(n) && n >= min && (max === undefined || n <= max)
|
||||
}
|
||||
|
||||
export const deploymentFormSchema = z
|
||||
.object({
|
||||
name: z.string().min(1, '请输入部署名称'),
|
||||
description: z.string(),
|
||||
version: z.string().min(1, '请选择 Loki 版本'),
|
||||
mode: z.enum(['k8s-helm', 'k8s-yaml', 'host-binary']),
|
||||
clusterID: z.string(),
|
||||
hostID: z.string(),
|
||||
namespace: z.string(),
|
||||
grafanaEnabled: z.boolean(),
|
||||
grafanaVersion: z.string().optional(),
|
||||
storageConfigID: z.string(),
|
||||
authEnabled: z.boolean(),
|
||||
retentionDays: z
|
||||
.string()
|
||||
.refine((v) => isPositiveInt(v, 1), '保留天数需为不小于 1 的整数'),
|
||||
replicas: z
|
||||
.string()
|
||||
.refine((v) => isPositiveInt(v, 1, 10), '副本数需为 1-10 之间的整数'),
|
||||
resourcesCPU: z.string().min(1, '请填写 CPU 配额(如 500m)'),
|
||||
resourcesMem: z.string().min(1, '请填写内存配额(如 512Mi)'),
|
||||
storageSize: z.string().min(1, '请填写存储容量(如 10Gi)'),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (isK8sMode(data.mode) && !data.clusterID) {
|
||||
ctx.addIssue({ code: 'custom', path: ['clusterID'], message: '请选择目标集群' })
|
||||
}
|
||||
if (data.mode === 'host-binary' && !data.hostID) {
|
||||
ctx.addIssue({ code: 'custom', path: ['hostID'], message: '请选择目标主机' })
|
||||
}
|
||||
if (isK8sMode(data.mode) && !data.namespace.trim()) {
|
||||
ctx.addIssue({ code: 'custom', path: ['namespace'], message: '请填写命名空间' })
|
||||
}
|
||||
})
|
||||
|
||||
export type DeploymentFormValues = z.infer<typeof deploymentFormSchema>
|
||||
|
||||
export const DEFAULT_VALUES: DeploymentFormValues = {
|
||||
name: '',
|
||||
description: '',
|
||||
version: '3.0.0',
|
||||
mode: 'k8s-helm',
|
||||
clusterID: '',
|
||||
hostID: '',
|
||||
namespace: 'log',
|
||||
grafanaEnabled: false,
|
||||
grafanaVersion: '11.3.0',
|
||||
storageConfigID: '',
|
||||
authEnabled: false,
|
||||
retentionDays: '30',
|
||||
replicas: '1',
|
||||
resourcesCPU: '500m',
|
||||
resourcesMem: '512Mi',
|
||||
storageSize: '10Gi',
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Rocket, Plus } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { clusterApi, deploymentApi, hostApi, storageApi } from '@/api'
|
||||
import { PageContainer } from '@/components/PageContainer'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import { PaginationBar } from '@/components/PaginationBar'
|
||||
import { ConfirmDialog } from '@/components/ConfirmDialog'
|
||||
import { toast } from 'sonner'
|
||||
import { useListQuery } from '@/hooks/useListQuery'
|
||||
import type { Cluster, Host, LokiDeployment, StorageConfig } from '@/types'
|
||||
import { DeploymentCard } from './components/DeploymentCard'
|
||||
import { DeploymentFormDialog } from './components/DeploymentFormDialog'
|
||||
import { LogViewerDialog } from './components/LogViewerDialog'
|
||||
|
||||
/**
|
||||
* Loki 部署页 — 只做编排:部署列表走 useListQuery(取消+版本号),
|
||||
* 集群/主机/存储下拉数据为页面局部加载(与列表分页解耦);
|
||||
* 卡片/表单/日志查看均为域内子组件。成功操作静默(列表刷新即反馈)。
|
||||
*/
|
||||
const DeploymentsPage = memo(function DeploymentsPage() {
|
||||
const query = useListQuery<LokiDeployment>((params, signal) =>
|
||||
deploymentApi.list(params, { signal })
|
||||
)
|
||||
|
||||
// 表单下拉数据:一次性局部加载,创建部署不依赖其刷新
|
||||
const [clusters, setClusters] = useState<Cluster[]>([])
|
||||
const [hosts, setHosts] = useState<Host[]>([])
|
||||
const [storages, setStorages] = useState<StorageConfig[]>([])
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [logsDeployment, setLogsDeployment] = useState<LokiDeployment | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<LokiDeployment | null>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
/** 部署/重启进行中的部署 ID(按钮 loading + 防重复点击) */
|
||||
const [operating, setOperating] = useState<number | null>(null)
|
||||
|
||||
// 操作后延时刷新列表/清除按钮态的定时器(卸载清理)
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
timeoutsRef.current.forEach((id) => clearTimeout(id))
|
||||
timeoutsRef.current = []
|
||||
}
|
||||
}, [])
|
||||
|
||||
const addTimeout = useCallback((cb: () => void, delay: number) => {
|
||||
timeoutsRef.current.push(setTimeout(cb, delay))
|
||||
}, [])
|
||||
|
||||
// 下拉数据加载(失败仅提示,不阻塞列表)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
Promise.all([
|
||||
clusterApi.list({ page: 1, pageSize: 100 }),
|
||||
hostApi.list({ page: 1, pageSize: 100 }),
|
||||
storageApi.list({ page: 1, pageSize: 100 }),
|
||||
])
|
||||
.then(([clusterRes, hostRes, storageRes]) => {
|
||||
if (cancelled) return
|
||||
setClusters(clusterRes.list)
|
||||
setHosts(hostRes.list)
|
||||
setStorages(storageRes.list)
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err instanceof Error ? err.message : '加载集群/主机/存储数据失败')
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleDeploy = useCallback(
|
||||
async (id: number) => {
|
||||
setOperating(id)
|
||||
try {
|
||||
await deploymentApi.deploy(id)
|
||||
addTimeout(query.refresh, 2000)
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '部署失败')
|
||||
} finally {
|
||||
addTimeout(() => setOperating(null), 5000)
|
||||
}
|
||||
},
|
||||
[query, addTimeout]
|
||||
)
|
||||
|
||||
const handleStop = useCallback(
|
||||
async (id: number) => {
|
||||
try {
|
||||
await deploymentApi.stop(id)
|
||||
query.refresh()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '停止失败')
|
||||
}
|
||||
},
|
||||
[query]
|
||||
)
|
||||
|
||||
const handleRestart = useCallback(
|
||||
async (id: number) => {
|
||||
setOperating(id)
|
||||
try {
|
||||
await deploymentApi.restart(id)
|
||||
addTimeout(query.refresh, 3000)
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '重启失败')
|
||||
} finally {
|
||||
addTimeout(() => setOperating(null), 5000)
|
||||
}
|
||||
},
|
||||
[query, addTimeout]
|
||||
)
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
const id = deleteTarget?.id
|
||||
if (!id) return
|
||||
setDeleting(true)
|
||||
try {
|
||||
await deploymentApi.remove(id)
|
||||
setDeleteTarget(null)
|
||||
query.refresh()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '删除部署失败')
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}, [deleteTarget, query])
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
title="部署Loki"
|
||||
description="部署与管理 Grafana Loki 日志聚合服务"
|
||||
action={
|
||||
<Button
|
||||
className="bg-primary hover:bg-primary/90"
|
||||
onClick={() => setFormOpen(true)}
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
新建部署
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{query.loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : query.error ? (
|
||||
<ErrorState message={query.error} onRetry={query.refresh} />
|
||||
) : query.list.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Rocket}
|
||||
title="暂无部署"
|
||||
description="创建你的第一个 Loki 部署"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{query.list.map((deployment) => (
|
||||
<DeploymentCard
|
||||
key={deployment.id}
|
||||
deployment={deployment}
|
||||
operating={operating}
|
||||
onDeploy={handleDeploy}
|
||||
onStop={handleStop}
|
||||
onRestart={handleRestart}
|
||||
onDelete={setDeleteTarget}
|
||||
onViewLogs={setLogsDeployment}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<PaginationBar
|
||||
page={query.page}
|
||||
pageSize={query.pageSize}
|
||||
total={query.total}
|
||||
onPageChange={query.setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<DeploymentFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
onCreated={query.reload}
|
||||
clusters={clusters}
|
||||
hosts={hosts}
|
||||
storages={storages}
|
||||
/>
|
||||
|
||||
<LogViewerDialog
|
||||
deployment={logsDeployment}
|
||||
onClose={() => setLogsDeployment(null)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteTarget(null)
|
||||
}}
|
||||
name={deleteTarget?.name}
|
||||
loading={deleting}
|
||||
onConfirm={handleDelete}
|
||||
/>
|
||||
</PageContainer>
|
||||
)
|
||||
})
|
||||
|
||||
export default DeploymentsPage
|
||||
@@ -0,0 +1,97 @@
|
||||
import { memo } from 'react'
|
||||
import { Monitor, RefreshCw, Trash2, Eye, Terminal } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { StatusBadge } from '@/components/StatusBadge'
|
||||
import { InfoRow } from '@/components/InfoRow'
|
||||
import type { Host } from '@/types'
|
||||
|
||||
interface HostCardProps {
|
||||
host: Host
|
||||
validating: number | null
|
||||
onViewInfo: (h: Host) => void
|
||||
onOpenTerminal: (h: Host) => void
|
||||
onValidate: (id: number) => void
|
||||
onDelete: (h: Host) => void
|
||||
}
|
||||
|
||||
/** 主机卡片 — 列表项展示与操作入口(删除传整个对象,供确认弹窗展示名称) */
|
||||
export const HostCard = memo(function HostCard({
|
||||
host,
|
||||
validating,
|
||||
onViewInfo,
|
||||
onOpenTerminal,
|
||||
onValidate,
|
||||
onDelete,
|
||||
}: HostCardProps) {
|
||||
return (
|
||||
<Card className="border-border hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Monitor className="w-5 h-5 text-purple-500 flex-shrink-0" />
|
||||
<h3 className="font-semibold text-foreground truncate">
|
||||
{host.name}
|
||||
</h3>
|
||||
</div>
|
||||
<StatusBadge status={host.status} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 text-xs text-muted-foreground mb-4">
|
||||
<InfoRow label="IP 地址" value={`${host.hostIP}:${host.port}`} />
|
||||
<InfoRow label="用户名" value={host.user} />
|
||||
<InfoRow
|
||||
label="认证方式"
|
||||
value={host.authType === 'key' ? 'SSH 密钥' : '密码'}
|
||||
/>
|
||||
<InfoRow
|
||||
label="系统"
|
||||
value={`${host.os || '未知'} (${host.arch || '未知'})`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-3 border-t border-border">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onViewInfo(host)}
|
||||
>
|
||||
<Eye className="w-3 h-3 mr-1" />
|
||||
详情
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1 text-xs"
|
||||
onClick={() => onOpenTerminal(host)}
|
||||
>
|
||||
<Terminal className="w-3 h-3 mr-1" />
|
||||
终端
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label={`验证主机 ${host.name}`}
|
||||
className="text-xs"
|
||||
onClick={() => onValidate(host.id)}
|
||||
disabled={validating === host.id}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`w-3 h-3 ${validating === host.id ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label={`删除主机 ${host.name}`}
|
||||
className="text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => onDelete(host)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { Monitor } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { hostApi } from '@/api'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import type { Host, HostInfo } from '@/types'
|
||||
|
||||
// 使用率颜色阈值
|
||||
const usageColor = (v: number) =>
|
||||
v >= 90 ? 'bg-destructive' : v >= 70 ? 'bg-warning' : 'bg-success'
|
||||
|
||||
interface HostDetailDialogProps {
|
||||
host: Host | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** 主机详情弹窗 — 自负责拉取主机信息(打开即加载,失败渲染 ErrorState 可重开重试) */
|
||||
export const HostDetailDialog = memo(function HostDetailDialog({
|
||||
host,
|
||||
onClose,
|
||||
}: HostDetailDialogProps) {
|
||||
const [info, setInfo] = useState<HostInfo | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!host) return
|
||||
let cancelled = false
|
||||
hostApi
|
||||
.getInfo(host.id)
|
||||
.then((data) => {
|
||||
if (!cancelled) setInfo(data)
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!cancelled) setError(err instanceof Error ? err.message : '加载主机详情失败')
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [host])
|
||||
|
||||
return (
|
||||
<Dialog open={host !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Monitor className="w-5 h-5 text-purple-500" />
|
||||
{host?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{error ? (
|
||||
<ErrorState message={error} />
|
||||
) : info ? (
|
||||
<HostDetail info={info} />
|
||||
) : (
|
||||
<LoadingSpinner className="h-32" />
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
|
||||
/** 主机详情内容:资源使用率 + 基本信息 */
|
||||
const HostDetail = memo(function HostDetail({ info }: { info: HostInfo }) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* 资源使用率 */}
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-3">资源使用率</h4>
|
||||
<div className="space-y-3">
|
||||
<UsageBar label="CPU" value={info.cpuUsage} />
|
||||
<UsageBar
|
||||
label="内存"
|
||||
value={info.memUsage}
|
||||
detail={`${info.memUsed} / ${info.memTotal}`}
|
||||
/>
|
||||
<UsageBar
|
||||
label="磁盘"
|
||||
value={info.diskUsage}
|
||||
detail={`${info.diskUsed} / ${info.diskTotal}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 基本信息 */}
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold mb-3">基本信息</h4>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InfoCard label="主机名" value={info.hostname || '未知'} />
|
||||
<InfoCard label="系统" value={`${info.os || '未知'} ${info.version}`} />
|
||||
<InfoCard label="架构" value={info.arch || '未知'} />
|
||||
<InfoCard label="内核" value={info.kernel || '未知'} />
|
||||
<InfoCard label="CPU 核数" value={info.cpu || '未知'} />
|
||||
<InfoCard label="运行时长" value={info.uptime || '未知'} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 使用率进度条
|
||||
const UsageBar = memo(function UsageBar({
|
||||
label,
|
||||
value,
|
||||
detail,
|
||||
}: {
|
||||
label: string
|
||||
value: number
|
||||
detail?: string
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between text-xs mb-1">
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<span className="font-medium">
|
||||
{value.toFixed(1)}% {detail && `(${detail})`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full ${usageColor(value)} rounded-full transition-all`}
|
||||
style={{ width: `${Math.min(value, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// 信息卡片
|
||||
const InfoCard = memo(function InfoCard({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<div className="p-2.5 bg-muted rounded-lg">
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className="text-sm font-medium truncate">{value}</p>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,304 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { Key, Lock } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { hostApi } from '@/api'
|
||||
import { PasswordInput } from '@/components/PasswordInput'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
// 表单 schema:zod 为唯一校验源,消息中文且具体
|
||||
// (port 在表单内为字符串、提交时转数字,避免 z.coerce 输入/输出类型分叉导致 RHF 泛型不兼容)
|
||||
const hostFormSchema = z
|
||||
.object({
|
||||
name: z.string().min(1, '请输入主机名称'),
|
||||
hostIP: z.string().min(1, '请输入主机 IP'),
|
||||
port: z
|
||||
.string()
|
||||
.min(1, '请输入端口')
|
||||
.regex(/^\d+$/, '端口必须为数字')
|
||||
.refine((v) => Number(v) >= 1 && Number(v) <= 65535, '端口必须在 1-65535 之间'),
|
||||
user: z.string().min(1, '请输入用户名'),
|
||||
authType: z.enum(['password', 'key']),
|
||||
password: z.string().optional(),
|
||||
privateKey: z.string().optional(),
|
||||
keyPhrase: z.string().optional(),
|
||||
labels: z.string().optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (data.authType === 'password' && !data.password?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['password'],
|
||||
message: '请填写 SSH 登录密码',
|
||||
})
|
||||
}
|
||||
if (data.authType === 'key' && !data.privateKey?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['privateKey'],
|
||||
message: '请粘贴 SSH 私钥内容',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
type HostFormValues = z.infer<typeof hostFormSchema>
|
||||
|
||||
const DEFAULT_VALUES: HostFormValues = {
|
||||
name: '',
|
||||
hostIP: '',
|
||||
port: '22',
|
||||
user: 'root',
|
||||
authType: 'password',
|
||||
password: '',
|
||||
privateKey: '',
|
||||
keyPhrase: '',
|
||||
labels: '',
|
||||
}
|
||||
|
||||
interface HostFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** 创建成功回调(父级刷新列表并关闭弹窗) */
|
||||
onCreated: () => void
|
||||
}
|
||||
|
||||
/** 添加 SSH 主机弹窗 — react-hook-form + zod,自包含表单逻辑,页面只传开关与回调 */
|
||||
export const HostFormDialog = memo(function HostFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
}: HostFormDialogProps) {
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const form = useForm<HostFormValues>({
|
||||
resolver: zodResolver(hostFormSchema),
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
})
|
||||
const authType = form.watch('authType')
|
||||
|
||||
// 打开时重置(默认值),关闭/重开时机明确
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset(DEFAULT_VALUES)
|
||||
}
|
||||
}, [open, form])
|
||||
|
||||
const onSubmit = form.handleSubmit(async (values) => {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await hostApi.create({
|
||||
name: values.name,
|
||||
hostIP: values.hostIP,
|
||||
port: Number(values.port),
|
||||
user: values.user,
|
||||
authType: values.authType,
|
||||
password: values.authType === 'password' ? values.password : undefined,
|
||||
privateKey: values.authType === 'key' ? values.privateKey : undefined,
|
||||
keyPhrase: values.authType === 'key' ? values.keyPhrase : undefined,
|
||||
labels: values.labels,
|
||||
})
|
||||
onOpenChange(false)
|
||||
onCreated()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '添加主机失败')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>添加 SSH 主机</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="loki-server-1" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="hostIP"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>主机 IP *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="192.168.1.100" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="port"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>端口</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" placeholder="22" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="user"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>用户名 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="root" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="authType"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>认证方式</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex gap-4">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="authType"
|
||||
value="password"
|
||||
checked={field.value === 'password'}
|
||||
onChange={() => field.onChange('password')}
|
||||
/>
|
||||
<Lock className="w-4 h-4" />
|
||||
<span className="text-sm">密码</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="authType"
|
||||
value="key"
|
||||
checked={field.value === 'key'}
|
||||
onChange={() => field.onChange('key')}
|
||||
/>
|
||||
<Key className="w-4 h-4" />
|
||||
<span className="text-sm">SSH 密钥</span>
|
||||
</label>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{authType === 'password' ? (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>密码 *</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput placeholder="SSH 登录密码" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="privateKey"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>私钥 *</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
|
||||
className="min-h-[120px] font-mono text-xs"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="keyPhrase"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>密钥口令(可选)</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput placeholder="无口令则留空" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="labels"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>标签(JSON)</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder='["loki", "logging"]' {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full bg-primary hover:bg-primary/90"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? '添加中...' : '添加主机'}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { Terminal } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { hostApi } from '@/api'
|
||||
import type { Host } from '@/types'
|
||||
|
||||
interface TerminalDialogProps {
|
||||
host: Host | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** 命令执行终端弹窗 — 打开即初始化欢迎输出,命令执行与输出渲染自包含 */
|
||||
export const TerminalDialog = memo(function TerminalDialog({
|
||||
host,
|
||||
onClose,
|
||||
}: TerminalDialogProps) {
|
||||
const [command, setCommand] = useState('')
|
||||
const [output, setOutput] = useState('')
|
||||
const [executing, setExecuting] = useState(false)
|
||||
|
||||
// 切换主机/重新打开时重置终端
|
||||
useEffect(() => {
|
||||
if (host) {
|
||||
setCommand('')
|
||||
setOutput(`已连接到 ${host.name} (${host.hostIP})\n输入命令后按"执行"...\n`)
|
||||
}
|
||||
}, [host])
|
||||
|
||||
const executeCommand = async () => {
|
||||
if (!host || !command.trim() || executing) return
|
||||
setExecuting(true)
|
||||
setOutput((prev) => prev + `\n$ ${command}\n`)
|
||||
try {
|
||||
const res = await hostApi.execute(host.id, command)
|
||||
setOutput((prev) => prev + (res.stdout || '') + (res.stderr || '') + '\n')
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : '命令执行失败'
|
||||
setOutput((prev) => prev + `错误:${message}\n`)
|
||||
} finally {
|
||||
setExecuting(false)
|
||||
setCommand('')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={host !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Terminal className="w-5 h-5 text-primary" />
|
||||
终端 - {host?.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="bg-card dark:bg-card text-green-400 font-mono text-xs p-4 rounded-lg h-80 overflow-auto whitespace-pre-wrap">
|
||||
{output}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={command}
|
||||
onChange={(e) => setCommand(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && executeCommand()}
|
||||
placeholder="输入命令..."
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={executing}
|
||||
/>
|
||||
<Button
|
||||
onClick={executeCommand}
|
||||
disabled={executing || !command.trim()}
|
||||
className="bg-primary hover:bg-primary/90"
|
||||
>
|
||||
{executing ? '执行中...' : '执行'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,171 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Monitor, Plus } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { hostApi, deploymentApi, collectorApi } from '@/api'
|
||||
import { PageContainer } from '@/components/PageContainer'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import { PaginationBar } from '@/components/PaginationBar'
|
||||
import { ConfirmDialog } from '@/components/ConfirmDialog'
|
||||
import { toast } from 'sonner'
|
||||
import { useListQuery } from '@/hooks/useListQuery'
|
||||
import type { Host } from '@/types'
|
||||
import { HostCard } from './components/HostCard'
|
||||
import { HostFormDialog } from './components/HostFormDialog'
|
||||
import { HostDetailDialog } from './components/HostDetailDialog'
|
||||
import { TerminalDialog } from './components/TerminalDialog'
|
||||
|
||||
/**
|
||||
* 主机管理页 — 只做编排:数据走 useListQuery(取消+版本号),
|
||||
* 卡片/表单/详情/终端/删除确认均为域内子组件。成功操作静默(列表刷新即反馈)。
|
||||
*/
|
||||
const HostsPage = memo(function HostsPage() {
|
||||
const query = useListQuery<Host>((params, signal) =>
|
||||
hostApi.list(params, { signal })
|
||||
)
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [detailHost, setDetailHost] = useState<Host | null>(null)
|
||||
const [terminalHost, setTerminalHost] = useState<Host | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<Host | null>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [validating, setValidating] = useState<number | null>(null)
|
||||
|
||||
// 验证后延时刷新列表的定时器(卸载清理)
|
||||
const timeoutsRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
useEffect(() => {
|
||||
const timers = timeoutsRef.current
|
||||
return () => {
|
||||
timers.forEach((id) => clearTimeout(id))
|
||||
}
|
||||
}, [])
|
||||
|
||||
const [refCount, setRefCount] = useState<{ dep: number; col: number }>({ dep: 0, col: 0 })
|
||||
useEffect(() => {
|
||||
if (!deleteTarget) return
|
||||
Promise.all([
|
||||
deploymentApi.list({ page: 1, pageSize: 100 }),
|
||||
collectorApi.list({ page: 1, pageSize: 100 }),
|
||||
]).then(([d, c]) => {
|
||||
setRefCount({
|
||||
dep: d.list.filter((x) => x.hostID === deleteTarget.id).length,
|
||||
col: c.list.filter((x) => x.hostID === deleteTarget.id).length,
|
||||
})
|
||||
}).catch(() => setRefCount({ dep: 0, col: 0 }))
|
||||
}, [deleteTarget])
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
const id = deleteTarget?.id
|
||||
if (!id) return
|
||||
setDeleting(true)
|
||||
try {
|
||||
await hostApi.remove(id)
|
||||
setDeleteTarget(null)
|
||||
query.refresh()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '删除主机失败')
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}, [deleteTarget, query])
|
||||
|
||||
const handleValidate = useCallback(
|
||||
async (id: number) => {
|
||||
setValidating(id)
|
||||
try {
|
||||
await hostApi.validate(id)
|
||||
timeoutsRef.current.push(setTimeout(() => query.refresh(), 3000))
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '验证失败')
|
||||
} finally {
|
||||
timeoutsRef.current.push(setTimeout(() => setValidating(null), 3000))
|
||||
}
|
||||
},
|
||||
[query]
|
||||
)
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
title="主机管理"
|
||||
description="管理用于二进制方式部署 Loki 的 SSH 主机"
|
||||
action={
|
||||
<Button
|
||||
className="bg-primary hover:bg-primary/90"
|
||||
onClick={() => setFormOpen(true)}
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
添加主机
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{query.loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : query.error ? (
|
||||
<ErrorState message={query.error} onRetry={query.refresh} />
|
||||
) : query.list.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Monitor}
|
||||
title="暂无主机"
|
||||
description="添加第一台 SSH 主机开始使用"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{query.list.map((host) => (
|
||||
<HostCard
|
||||
key={host.id}
|
||||
host={host}
|
||||
validating={validating}
|
||||
onViewInfo={setDetailHost}
|
||||
onOpenTerminal={setTerminalHost}
|
||||
onValidate={handleValidate}
|
||||
onDelete={setDeleteTarget}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<PaginationBar
|
||||
page={query.page}
|
||||
pageSize={query.pageSize}
|
||||
total={query.total}
|
||||
onPageChange={query.setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<HostFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
onCreated={query.reload}
|
||||
/>
|
||||
|
||||
<HostDetailDialog
|
||||
key={detailHost?.id ?? 'none'}
|
||||
host={detailHost}
|
||||
onClose={() => setDetailHost(null)}
|
||||
/>
|
||||
|
||||
<TerminalDialog
|
||||
host={terminalHost}
|
||||
onClose={() => setTerminalHost(null)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteTarget(null)
|
||||
}}
|
||||
name={deleteTarget?.name}
|
||||
loading={deleting}
|
||||
description={
|
||||
refCount.dep + refCount.col > 0
|
||||
? `确定要删除「${deleteTarget?.name}」吗?警告:仍有 ${refCount.dep} 个部署、${refCount.col} 个采集策略引用该主机,删除后它们将无法工作。`
|
||||
: undefined
|
||||
}
|
||||
onConfirm={handleDelete}
|
||||
/>
|
||||
</PageContainer>
|
||||
)
|
||||
})
|
||||
|
||||
export default HostsPage
|
||||
@@ -1,38 +1,34 @@
|
||||
import { memo, useCallback, useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { useLocation, useNavigate } from 'react-router'
|
||||
import { Activity, Eye, EyeOff, Shield, ServerOff } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { authApi } from '@/api'
|
||||
import { toast } from 'sonner'
|
||||
import { authApi, ApiError } from '@/api'
|
||||
import { saveAuth, isLoggedIn, getUser } from '@/lib/auth-storage'
|
||||
import { readRedirectParam } from '@/lib/redirect'
|
||||
|
||||
/**
|
||||
* Login 页面 - 优化版本
|
||||
*
|
||||
* 优化点:
|
||||
* 1. React.memo 包裹组件
|
||||
* 2. 表单处理使用 useCallback 缓存
|
||||
* 3. 错误处理使用 sonner toast 替代 alert
|
||||
* 4. 清理 useEffect 中的未使用变量
|
||||
* Login 页面
|
||||
* - 登录接口 silent(错误密码 401 不触发全局跳转)
|
||||
* - 登录成功按 redirect 参数回跳来源页(同源校验)
|
||||
* - 后端探活走 api 层(authApi.health)
|
||||
*/
|
||||
const Login = memo(function Login() {
|
||||
const [username, setUsername] = useState('admin')
|
||||
const [password, setPassword] = useState('admin123')
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [backendStatus, setBackendStatus] = useState<'checking' | 'online' | 'offline'>('checking')
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
useEffect(() => {
|
||||
// Check if already logged in
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) {
|
||||
navigate('/')
|
||||
if (isLoggedIn()) {
|
||||
navigate(getUser()?.role === 'admin' ? '/' : '/logs', { replace: true })
|
||||
return
|
||||
}
|
||||
// Quick backend check
|
||||
checkBackend()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [navigate])
|
||||
@@ -40,16 +36,10 @@ const Login = memo(function Login() {
|
||||
// 后端状态检查 - useCallback缓存
|
||||
const checkBackend = useCallback(async () => {
|
||||
try {
|
||||
const controller = new AbortController()
|
||||
const timeoutId = setTimeout(() => controller.abort(), 3000)
|
||||
// 用公开的健康检查端点探活;避免打 /auth/login(生产环境被 nginx 限流 5r/m,
|
||||
// 反复刷新登录页会触发限流并锁死真正的登录请求)
|
||||
const res = await fetch('/api/v1/health', {
|
||||
method: 'GET',
|
||||
signal: controller.signal,
|
||||
})
|
||||
clearTimeout(timeoutId)
|
||||
setBackendStatus(res.ok ? 'online' : 'offline')
|
||||
await authApi.health()
|
||||
setBackendStatus('online')
|
||||
} catch {
|
||||
setBackendStatus('offline')
|
||||
}
|
||||
@@ -64,31 +54,27 @@ const Login = memo(function Login() {
|
||||
|
||||
try {
|
||||
const result = await authApi.login(username, password)
|
||||
localStorage.setItem('token', result.accessToken)
|
||||
localStorage.setItem('refreshToken', result.refreshToken)
|
||||
localStorage.setItem('user', JSON.stringify(result.user))
|
||||
toast.success('登录成功')
|
||||
navigate('/')
|
||||
saveAuth(result, result.user)
|
||||
navigate(result.user.role === 'admin' ? readRedirectParam(location.search) : '/logs', { replace: true })
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '登录失败'
|
||||
if (message.includes('Cannot connect')) {
|
||||
setError('无法连接后端服务,请确认后端已启动(端口 8080)。')
|
||||
setBackendStatus('offline')
|
||||
} else if (
|
||||
message.includes('invalid') ||
|
||||
message.includes('password') ||
|
||||
message.includes('密码') ||
|
||||
message.includes('Unauthorized')
|
||||
) {
|
||||
setError('用户名或密码错误')
|
||||
if (err instanceof ApiError) {
|
||||
if (err.status === 0) {
|
||||
// 网络/超时类错误
|
||||
setError('无法连接后端服务,请确认后端已启动(端口 8080)。')
|
||||
setBackendStatus('offline')
|
||||
} else if (err.status === 401) {
|
||||
setError('用户名或密码错误')
|
||||
} else {
|
||||
setError(err.message || '登录失败')
|
||||
}
|
||||
} else {
|
||||
setError(message)
|
||||
setError(err instanceof Error ? err.message : '登录失败')
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
},
|
||||
[username, password, navigate]
|
||||
[username, password, navigate, location.search]
|
||||
)
|
||||
|
||||
// 密码显示切换 - useCallback缓存
|
||||
@@ -97,27 +83,27 @@ const Login = memo(function Login() {
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 dark:bg-slate-950 flex items-center justify-center p-4">
|
||||
<div className="min-h-screen bg-background flex justify-center px-4 pt-[8vh] md:pt-[14vh] pb-8">
|
||||
<div className="w-full max-w-md">
|
||||
{/* Logo */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-emerald-500 mb-4">
|
||||
<Activity className="w-9 h-9 text-white" />
|
||||
<div className="text-center mb-6">
|
||||
<div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary mb-3">
|
||||
<Activity className="w-8 h-8 text-primary-foreground" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-slate-900 dark:text-white">LokiDeploy</h1>
|
||||
<p className="text-sm text-slate-500 mt-1">Kubernetes Loki 日志部署平台</p>
|
||||
<h1 className="text-2xl font-bold text-foreground">opsx-loki</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">Kubernetes Loki 日志部署平台</p>
|
||||
</div>
|
||||
|
||||
{/* Backend Status */}
|
||||
{backendStatus === 'offline' && (
|
||||
<div className="mb-4 p-4 rounded-xl bg-amber-50 border border-amber-200 flex items-start gap-3">
|
||||
<ServerOff className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
|
||||
<div className="mb-4 p-4 rounded-xl bg-warning/10 border border-warning/30 flex items-start gap-3">
|
||||
<ServerOff className="w-5 h-5 text-warning flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-amber-800">后端服务未启动</p>
|
||||
<p className="text-xs text-amber-700 mt-1">
|
||||
<p className="text-sm font-medium text-warning">后端服务未启动</p>
|
||||
<p className="text-xs text-warning mt-1">
|
||||
无法连接 API 服务,请先启动后端:
|
||||
</p>
|
||||
<code className="block mt-2 px-3 py-2 bg-amber-100 rounded text-xs font-mono text-amber-900">
|
||||
<code className="block mt-2 px-3 py-2 bg-warning/20 rounded text-xs font-mono text-warning">
|
||||
./run.sh
|
||||
</code>
|
||||
</div>
|
||||
@@ -125,14 +111,14 @@ const Login = memo(function Login() {
|
||||
)}
|
||||
|
||||
{/* Login Card */}
|
||||
<div className="bg-white dark:bg-slate-900 rounded-2xl shadow-lg border border-slate-200 dark:border-slate-800 p-8">
|
||||
<div className="bg-card rounded-2xl shadow-lg border border-border p-8">
|
||||
<div className="flex items-center gap-2 mb-6">
|
||||
<Shield className="w-5 h-5 text-emerald-500" />
|
||||
<h2 className="text-lg font-semibold text-slate-800 dark:text-white">登录</h2>
|
||||
<Shield className="w-5 h-5 text-primary" />
|
||||
<h2 className="text-lg font-semibold text-foreground">登录</h2>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
|
||||
<div className="mb-4 p-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
@@ -167,7 +153,7 @@ const Login = memo(function Login() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={togglePassword}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{showPassword ? (
|
||||
@@ -181,18 +167,12 @@ const Login = memo(function Login() {
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-10 bg-emerald-600 hover:bg-emerald-700 text-white"
|
||||
className="w-full h-10 bg-primary hover:bg-primary/90 text-primary-foreground"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? '登录中...' : '登录'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-6 pt-4 border-t border-slate-100 dark:border-slate-800">
|
||||
<p className="text-xs text-center text-slate-500">
|
||||
默认账号:admin / admin123
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,24 @@
|
||||
import { FileQuestion, Home } from 'lucide-react'
|
||||
import { Link } from 'react-router'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
/** 404 页面 — 通配路由的显式落点,不静默跳首页 */
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="min-h-screen bg-muted dark:bg-slate-950 flex items-center justify-center p-6">
|
||||
<div className="max-w-md w-full text-center">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-muted mb-6">
|
||||
<FileQuestion className="w-8 h-8 text-muted-foreground" />
|
||||
</div>
|
||||
<h1 className="text-5xl font-bold text-foreground mb-2">404</h1>
|
||||
<p className="text-muted-foreground mb-8">页面不存在或已被移除</p>
|
||||
<Button asChild className="bg-primary hover:bg-primary/90 text-primary-foreground">
|
||||
<Link to="/">
|
||||
<Home className="w-4 h-4 mr-2" />
|
||||
返回首页
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { memo, useCallback, useEffect, useState } from 'react'
|
||||
import { Building2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { PasswordInput } from '@/components/PasswordInput'
|
||||
import { ldapApi, type LdapConfig, type LdapTestResult } from '@/api/ldap'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const EMPTY: LdapConfig = {
|
||||
enabled: false,
|
||||
host: '',
|
||||
port: 389,
|
||||
useSSL: false,
|
||||
bindDN: '',
|
||||
bindPassword: '',
|
||||
baseDN: '',
|
||||
userFilter: '(objectClass=inetOrgPerson)',
|
||||
usernameAttr: 'uid',
|
||||
nameAttr: 'displayName',
|
||||
emailAttr: 'mail',
|
||||
}
|
||||
|
||||
/**
|
||||
* LDAP 配置卡片 — 启用开关 + 表单 + 表单参数直测(未保存也可测);
|
||||
* 密码已保存时占位提示,留空提交即保留旧值。启用且配置齐全后,
|
||||
* 用户管理页才会出现「从 LDAP 导入」。
|
||||
*/
|
||||
export const LdapSection = memo(function LdapSection() {
|
||||
const [cfg, setCfg] = useState<LdapConfig>(EMPTY)
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [testing, setTesting] = useState(false)
|
||||
const [testResult, setTestResult] = useState<LdapTestResult | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
ldapApi
|
||||
.getConfig()
|
||||
.then((c) => {
|
||||
setCfg({ ...EMPTY, ...c, bindPassword: '' })
|
||||
setLoaded(true)
|
||||
})
|
||||
.catch(() => toast.error('加载 LDAP 配置失败'))
|
||||
}, [])
|
||||
|
||||
const set = useCallback(<K extends keyof LdapConfig>(k: K, v: LdapConfig[K]) => {
|
||||
setCfg((prev) => ({ ...prev, [k]: v }))
|
||||
}, [])
|
||||
|
||||
const handleTest = async () => {
|
||||
if (!cfg.host || !cfg.bindDN || !cfg.baseDN) {
|
||||
toast.error('请先填写服务器地址 / Bind DN / Base DN')
|
||||
return
|
||||
}
|
||||
setTesting(true)
|
||||
setTestResult(null)
|
||||
try {
|
||||
const result = await ldapApi.test(cfg)
|
||||
setTestResult(result)
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '测试失败')
|
||||
} finally {
|
||||
setTesting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true)
|
||||
try {
|
||||
const saved = await ldapApi.saveConfig(cfg)
|
||||
setCfg({ ...EMPTY, ...saved, bindPassword: '' })
|
||||
toast.success('LDAP 配置已保存')
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '保存失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="border-border">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base flex items-center justify-between">
|
||||
<span className="flex items-center gap-2">
|
||||
<Building2 className="w-4 h-4" />
|
||||
LDAP 接入
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">启用后支持 LDAP 登录与批量导入</span>
|
||||
<Switch checked={cfg.enabled} onCheckedChange={(v) => set('enabled', v)} />
|
||||
</div>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{loaded && !cfg.enabled ? (
|
||||
<p className="text-sm text-muted-foreground py-2 text-center">
|
||||
LDAP 未启用 —— 打开开关填写目录服务信息(服务器 / Bind DN / Base DN),
|
||||
保存后用户管理页将出现「从 LDAP 导入」
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>服务器地址 *</Label>
|
||||
<Input
|
||||
placeholder="8.217.205.92"
|
||||
value={cfg.host}
|
||||
onChange={(e) => set('host', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="space-y-2 col-span-2">
|
||||
<Label>端口</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={cfg.port || 389}
|
||||
onChange={(e) => set('port', Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 flex flex-col">
|
||||
<Label>LDAPS</Label>
|
||||
<div className="pt-2">
|
||||
<Switch checked={cfg.useSSL} onCheckedChange={(v) => set('useSSL', v)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<Label>Bind DN *</Label>
|
||||
<Input
|
||||
placeholder="cn=admin,dc=example,dc=com"
|
||||
value={cfg.bindDN}
|
||||
onChange={(e) => set('bindDN', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Bind 密码 *</Label>
|
||||
<PasswordInput
|
||||
placeholder={cfg.hasPassword ? '已保存,输入新密码以修改' : '管理员密码'}
|
||||
value={cfg.bindPassword}
|
||||
onChange={(e) => set('bindPassword', e.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Base DN *</Label>
|
||||
<Input
|
||||
placeholder="dc=example,dc=com"
|
||||
value={cfg.baseDN}
|
||||
onChange={(e) => set('baseDN', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>用户过滤器</Label>
|
||||
<Input value={cfg.userFilter} onChange={(e) => set('userFilter', e.target.value)} />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="space-y-2">
|
||||
<Label>用户名</Label>
|
||||
<Input value={cfg.usernameAttr} onChange={(e) => set('usernameAttr', e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>姓名</Label>
|
||||
<Input value={cfg.nameAttr} onChange={(e) => set('nameAttr', e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>邮箱</Label>
|
||||
<Input value={cfg.emailAttr} onChange={(e) => set('emailAttr', e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{testResult && (
|
||||
<div
|
||||
role="status"
|
||||
className={`p-3 rounded-lg border text-sm ${
|
||||
testResult.success
|
||||
? 'bg-success/10 border-success/30 text-success'
|
||||
: 'bg-destructive/10 border-destructive/30 text-destructive'
|
||||
}`}
|
||||
>
|
||||
{testResult.message}
|
||||
{testResult.userInfo && (
|
||||
<span className="block text-xs mt-1 opacity-80">
|
||||
{testResult.userInfo.displayName} · {testResult.userInfo.email || '无邮箱'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={handleTest} disabled={testing || !cfg.enabled}>
|
||||
{testing ? '测试中...' : '测试连接'}
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={saving || !cfg.enabled}>
|
||||
{saving ? '保存中...' : '保存配置'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user