[优化] 格式化

This commit is contained in:
ryan
2026-05-30 13:15:20 +08:00
parent 28b1305906
commit 9ec3d5b42d
110 changed files with 29155 additions and 7642 deletions
+11 -11
View File
@@ -29,12 +29,12 @@ pnpm build
## 构建说明
* 构建采用 Next.js 静态导出模式。
* `pnpm build` 会先生成 `out/`,随后自动复制为 Go Server 兼容的 `build/` 目录。
* 默认 API Base URL 为 `/api`,如需覆盖可在构建时设置 `NEXT_PUBLIC_API_BASE_URL`。
* 构建版本号可通过 `NEXT_PUBLIC_APP_VERSION` 注入,例如 `NEXT_PUBLIC_APP_VERSION=v0.4.0 pnpm build`。
* `pnpm dev` 会以开发模式启动 `http://127.0.0.1:3001`,并通过同源代理把 `/api/*` 的 HTTP 与 WebSocket 请求统一转发到 `NEXT_DEV_BACKEND_URL`,默认是 `http://127.0.0.1:3000`。
* `pnpm start` 用于启动已构建产物,对应 Next 生产模式。
- 构建采用 Next.js 静态导出模式。
- `pnpm build` 会先生成 `out/`,随后自动复制为 Go Server 兼容的 `build/` 目录。
- 默认 API Base URL 为 `/api`,如需覆盖可在构建时设置 `NEXT_PUBLIC_API_BASE_URL`。
- 构建版本号可通过 `NEXT_PUBLIC_APP_VERSION` 注入,例如 `NEXT_PUBLIC_APP_VERSION=v0.4.0 pnpm build`。
- `pnpm dev` 会以开发模式启动 `http://127.0.0.1:3001`,并通过同源代理把 `/api/*` 的 HTTP 与 WebSocket 请求统一转发到 `NEXT_DEV_BACKEND_URL`,默认是 `http://127.0.0.1:3000`。
- `pnpm start` 用于启动已构建产物,对应 Next 生产模式。
## 开源协议
@@ -42,8 +42,8 @@ pnpm build
## 目录约定
* `app/`:路由与布局
* `features/`:业务模块
* `components/`:复用组件
* `lib/`:请求、环境变量、工具与常量
* `tests/`:测试代码
- `app/`:路由与布局
- `features/`:业务模块
- `components/`:复用组件
- `lib/`:请求、环境变量、工具与常量
- `tests/`:测试代码
@@ -2,7 +2,7 @@ import { DashboardOverview } from '@/features/dashboard/components/dashboard-ove
export default function DashboardPage() {
return (
<div className='space-y-6'>
<div className="space-y-6">
<DashboardOverview />
</div>
);
+8 -3
View File
@@ -1,8 +1,8 @@
@import '../styles/tokens.css';
@import 'tailwindcss';
@import '@heroui/styles';
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import 'tw-animate-css';
@import 'shadcn/tailwind.css';
@custom-variant dark (&:is(.dark *));
@@ -27,7 +27,12 @@ body {
background: var(--body-background);
color: var(--foreground-primary);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
Inter,
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
sans-serif;
transition:
background 0.2s ease,
+9 -5
View File
@@ -6,10 +6,10 @@ import { AppProviders } from '@/components/providers/app-providers';
import { getThemeInitScript } from '@/lib/theme/theme';
import './globals.css';
import { Geist } from "next/font/google";
import { cn } from "@/lib/utils";
import { Geist } from 'next/font/google';
import { cn } from '@/lib/utils';
const geist = Geist({subsets:['latin'],variable:'--font-sans'});
const geist = Geist({ subsets: ['latin'], variable: '--font-sans' });
export const metadata: Metadata = {
title: {
@@ -26,9 +26,13 @@ interface RootLayoutProps {
export default function RootLayout({ children }: RootLayoutProps) {
return (
<html lang='zh-CN' suppressHydrationWarning className={cn("font-sans", geist.variable)}>
<html
lang="zh-CN"
suppressHydrationWarning
className={cn('font-sans', geist.variable)}
>
<body>
<Script id='theme-init' strategy='beforeInteractive'>
<Script id="theme-init" strategy="beforeInteractive">
{getThemeInitScript()}
</Script>
<AppProviders>{children}</AppProviders>
+10 -4
View File
@@ -4,11 +4,17 @@ import { AppCard } from '@/components/ui/app-card';
export default function NotFound() {
return (
<main className='flex min-h-screen items-center justify-center px-4'>
<AppCard title='页面不存在' description='当前请求的页面尚未接入新版管理端路由。'>
<div className='space-y-4 text-sm leading-6 text-[var(--foreground-secondary)]'>
<main className="flex min-h-screen items-center justify-center px-4">
<AppCard
title="页面不存在"
description="当前请求的页面尚未接入新版管理端路由。"
>
<div className="space-y-4 text-sm leading-6 text-[var(--foreground-secondary)]">
<p>请返回总览页,或继续通过侧边导航访问已初始化的模块入口。</p>
<Link href='/' className='inline-flex rounded-full bg-[var(--brand-primary)] px-4 py-2 font-medium text-[var(--foreground-inverse)] transition hover:opacity-90'>
<Link
href="/"
className="inline-flex rounded-full bg-[var(--brand-primary)] px-4 py-2 font-medium text-[var(--foreground-inverse)] transition hover:opacity-90"
>
返回总览
</Link>
</div>
@@ -31,101 +31,102 @@ function getChartValue(params: unknown) {
}
export function RankChart({
items,
color,
valueFormatter = defaultFormatter,
emptyMessage = '暂无分布数据',
}: RankChartProps) {
items,
color,
valueFormatter = defaultFormatter,
emptyMessage = '暂无分布数据',
}: RankChartProps) {
const option = useMemo<EChartsOption>(
() => ({
animationDuration: 400,
grid: {
left: 16,
right: 24,
top: 12,
bottom: 12,
containLabel: true,
() => ({
animationDuration: 400,
grid: {
left: 16,
right: 24,
top: 12,
bottom: 12,
containLabel: true,
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
backgroundColor: 'rgba(15, 23, 42, 0.92)',
borderWidth: 0,
textStyle: {
color: '#e2e8f0',
fontSize: 12,
},
formatter: (params: unknown) => {
const item = Array.isArray(params) ? params[0] : params;
const data = item as { name?: string; value?: number };
return `${data.name ?? ''}<br/>${valueFormatter(data.value ?? 0)}`;
},
},
xAxis: {
type: 'value',
axisLabel: {
color: '#94a3b8',
},
splitLine: {
lineStyle: {
color: 'rgba(148, 163, 184, 0.16)',
type: 'dashed',
},
backgroundColor: 'rgba(15, 23, 42, 0.92)',
borderWidth: 0,
textStyle: {
},
},
yAxis: {
type: 'category',
data: items.map((item) => item.label),
axisTick: { show: false },
axisLine: { show: false },
axisLabel: {
color: '#cbd5e1',
width: 120,
overflow: 'truncate',
},
},
series: [
{
type: 'bar',
data: items.map((item) => item.value),
barWidth: 12,
showBackground: true,
backgroundStyle: {
color: 'rgba(148, 163, 184, 0.12)',
borderRadius: 999,
},
itemStyle: {
color,
borderRadius: 999,
},
label: {
show: true,
position: 'right',
color: '#e2e8f0',
fontSize: 12,
},
formatter: (params: unknown) => {
const item = Array.isArray(params) ? params[0] : params;
const data = item as { name?: string; value?: number };
return `${data.name ?? ''}<br/>${valueFormatter(data.value ?? 0)}`;
formatter: (params: unknown) =>
valueFormatter(getChartValue(params)),
},
},
xAxis: {
type: 'value',
axisLabel: {
color: '#94a3b8',
},
splitLine: {
lineStyle: {
color: 'rgba(148, 163, 184, 0.16)',
type: 'dashed',
},
},
},
yAxis: {
type: 'category',
data: items.map((item) => item.label),
axisTick: { show: false },
axisLine: { show: false },
axisLabel: {
color: '#cbd5e1',
width: 120,
overflow: 'truncate',
},
},
series: [
{
type: 'bar',
data: items.map((item) => item.value),
barWidth: 12,
showBackground: true,
backgroundStyle: {
color: 'rgba(148, 163, 184, 0.12)',
borderRadius: 999,
},
itemStyle: {
color,
borderRadius: 999,
},
label: {
show: true,
position: 'right',
color: '#e2e8f0',
formatter: (params: unknown) => valueFormatter(getChartValue(params)),
},
},
],
}),
[color, items, valueFormatter],
],
}),
[color, items, valueFormatter],
);
if (items.length === 0) {
return (
<div className="flex h-[220px] items-center justify-center rounded-3xl border border-dashed border-[var(--border-default)] bg-[var(--surface-muted)] text-sm text-[var(--foreground-secondary)]">
{emptyMessage}
</div>
<div className="flex h-[220px] items-center justify-center rounded-3xl border border-dashed border-[var(--border-default)] bg-[var(--surface-muted)] text-sm text-[var(--foreground-secondary)]">
{emptyMessage}
</div>
);
}
return (
<ReactECharts
option={option}
notMerge
lazyUpdate
style={{ height: Math.max(220, items.length * 44), width: '100%' }}
/>
<ReactECharts
option={option}
notMerge
lazyUpdate
style={{ height: Math.max(220, items.length * 44), width: '100%' }}
/>
);
}
@@ -32,15 +32,15 @@ type TooltipParam = {
const defaultFormatter = (value: number) => formatCompactNumber(value);
export function TrendChart({
labels,
series,
height = 220,
yAxisValueFormatter,
}: TrendChartProps) {
labels,
series,
height = 220,
yAxisValueFormatter,
}: TrendChartProps) {
const option = useMemo<EChartsOption>(() => {
const axisFormatter = yAxisValueFormatter ?? defaultFormatter;
const maxValue = calculateNiceAxisMax(
series.flatMap((item) => item.values),
series.flatMap((item) => item.values),
);
return {
@@ -70,17 +70,17 @@ export function TrendChart({
const header = items[0]?.axisValueLabel ?? '';
const rows = items.map((item) => {
const matchedSeries = series.find(
(seriesItem) => seriesItem.label === item.seriesName,
(seriesItem) => seriesItem.label === item.seriesName,
);
const formatter =
matchedSeries?.valueFormatter ??
yAxisValueFormatter ??
defaultFormatter;
matchedSeries?.valueFormatter ??
yAxisValueFormatter ??
defaultFormatter;
const rawValue = Array.isArray(item.value)
? item.value[1]
: item.value;
? item.value[1]
: item.value;
const numericValue =
typeof rawValue === 'number' ? rawValue : Number(rawValue ?? 0);
typeof rawValue === 'number' ? rawValue : Number(rawValue ?? 0);
return [
'<span style="display:inline-flex;align-items:center;gap:8px;">',
@@ -145,11 +145,11 @@ export function TrendChart({
color: item.color,
},
areaStyle:
item.variant === 'area'
? {
color: item.fillColor ?? `${item.color}33`,
}
: undefined,
item.variant === 'area'
? {
color: item.fillColor ?? `${item.color}33`,
}
: undefined,
emphasis: {
focus: 'series',
scale: true,
@@ -161,48 +161,48 @@ export function TrendChart({
if (labels.length === 0 || series.length === 0) {
return (
<div className="flex h-[220px] items-center justify-center rounded-3xl border border-dashed border-[var(--border-default)] bg-[var(--surface-muted)] text-sm text-[var(--foreground-secondary)]">
暂无趋势数据
</div>
<div className="flex h-[220px] items-center justify-center rounded-3xl border border-dashed border-[var(--border-default)] bg-[var(--surface-muted)] text-sm text-[var(--foreground-secondary)]">
暂无趋势数据
</div>
);
}
return (
<div className="space-y-4">
<div className="flex flex-wrap gap-3">
{series.map((item) => {
const latestValue = item.values[item.values.length - 1] ?? 0;
const formatter = item.valueFormatter ?? defaultFormatter;
return (
<div
key={item.label}
className="min-w-[140px] rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3"
>
<div className="flex items-center gap-2">
<div className="space-y-4">
<div className="flex flex-wrap gap-3">
{series.map((item) => {
const latestValue = item.values[item.values.length - 1] ?? 0;
const formatter = item.valueFormatter ?? defaultFormatter;
return (
<div
key={item.label}
className="min-w-[140px] rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3"
>
<div className="flex items-center gap-2">
<span
className="h-2.5 w-2.5 rounded-full"
style={{ backgroundColor: item.color }}
className="h-2.5 w-2.5 rounded-full"
style={{ backgroundColor: item.color }}
/>
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
{item.label}
</p>
</div>
<p className="mt-2 text-lg font-semibold text-[var(--foreground-primary)]">
{formatter(latestValue)}
</p>
</div>
);
})}
</div>
<div className="overflow-hidden rounded-[28px] border border-[var(--border-default)] bg-[linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))] px-4 py-4">
<ReactECharts
option={option}
notMerge
lazyUpdate
style={{ height, width: '100%' }}
/>
</div>
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
{item.label}
</p>
</div>
<p className="mt-2 text-lg font-semibold text-[var(--foreground-primary)]">
{formatter(latestValue)}
</p>
</div>
);
})}
</div>
<div className="overflow-hidden rounded-[28px] border border-[var(--border-default)] bg-[linear-gradient(180deg,rgba(255,255,255,0.03),rgba(255,255,255,0))] px-4 py-4">
<ReactECharts
option={option}
notMerge
lazyUpdate
style={{ height, width: '100%' }}
/>
</div>
</div>
);
}
@@ -1,17 +1,19 @@
interface EmptyStateProps {
title: string;
description?: string;
title: string;
description?: string;
}
export function EmptyState({title, description}: EmptyStateProps) {
return (
<div
className='rounded-2xl border border-dashed border-[var(--border-default)] bg-[var(--surface-muted)] px-5 py-6 text-sm'>
<p className='text-base font-semibold text-[var(--foreground-primary)]'>{title}</p>
{description ?
<p className='mt-2 leading-6 text-[var(--foreground-secondary)]'>{description}</p> : null
}
</div>
);
export function EmptyState({ title, description }: EmptyStateProps) {
return (
<div className="rounded-2xl border border-dashed border-[var(--border-default)] bg-[var(--surface-muted)] px-5 py-6 text-sm">
<p className="text-base font-semibold text-[var(--foreground-primary)]">
{title}
</p>
{description ? (
<p className="mt-2 leading-6 text-[var(--foreground-secondary)]">
{description}
</p>
) : null}
</div>
);
}
@@ -5,9 +5,13 @@ interface ErrorStateProps {
export function ErrorState({ title, description }: ErrorStateProps) {
return (
<div className='rounded-2xl border border-[var(--status-danger-border)] bg-[var(--status-danger-soft)] px-5 py-6 text-sm'>
<p className='text-base font-semibold text-[var(--status-danger-foreground)]'>{title}</p>
<p className='mt-2 leading-6 text-[var(--status-danger-foreground)]/80'>{description}</p>
<div className="rounded-2xl border border-[var(--status-danger-border)] bg-[var(--status-danger-soft)] px-5 py-6 text-sm">
<p className="text-base font-semibold text-[var(--status-danger-foreground)]">
{title}
</p>
<p className="mt-2 leading-6 text-[var(--status-danger-foreground)]/80">
{description}
</p>
</div>
);
}
@@ -16,12 +16,12 @@ export function FeaturePlaceholder({
<AppCard
title={title}
description={description}
action={<StatusBadge label='阶段 1 骨架完成' variant='success' />}
action={<StatusBadge label="阶段 1 骨架完成" variant="success" />}
>
<ul className='space-y-3 text-sm leading-6 text-[var(--foreground-secondary)]'>
<ul className="space-y-3 text-sm leading-6 text-[var(--foreground-secondary)]">
{milestones.map((item) => (
<li key={item} className='flex gap-3'>
<span className='mt-2 h-2 w-2 shrink-0 rounded-full bg-[var(--brand-primary)]' />
<li key={item} className="flex gap-3">
<span className="mt-2 h-2 w-2 shrink-0 rounded-full bg-[var(--brand-primary)]" />
<span>{item}</span>
</li>
))}
@@ -7,9 +7,9 @@ interface LoadingStateProps {
export function LoadingState({ className }: LoadingStateProps) {
return (
<div className={cn('space-y-3', className)}>
<div className='h-4 w-32 animate-pulse rounded bg-[var(--control-background-hover)]' />
<div className='h-24 animate-pulse rounded-2xl bg-[var(--surface-muted)]' />
<div className='h-24 animate-pulse rounded-2xl bg-[var(--surface-muted)]' />
<div className="h-4 w-32 animate-pulse rounded bg-[var(--control-background-hover)]" />
<div className="h-24 animate-pulse rounded-2xl bg-[var(--surface-muted)]" />
<div className="h-24 animate-pulse rounded-2xl bg-[var(--surface-muted)]" />
</div>
);
}
@@ -22,7 +22,8 @@ declare global {
}
const TURNSTILE_SCRIPT_ID = 'cloudflare-turnstile-script';
const TURNSTILE_SCRIPT_SRC = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
const TURNSTILE_SCRIPT_SRC =
'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
interface TurnstileWidgetProps {
siteKey: string;
@@ -63,7 +64,9 @@ export function TurnstileWidget({
});
};
const existingScript = document.getElementById(TURNSTILE_SCRIPT_ID) as HTMLScriptElement | null;
const existingScript = document.getElementById(
TURNSTILE_SCRIPT_ID,
) as HTMLScriptElement | null;
if (window.turnstile) {
mountWidget();
@@ -81,7 +84,9 @@ export function TurnstileWidget({
return () => {
cancelled = true;
const script = document.getElementById(TURNSTILE_SCRIPT_ID) as HTMLScriptElement | null;
const script = document.getElementById(
TURNSTILE_SCRIPT_ID,
) as HTMLScriptElement | null;
if (script) {
script.removeEventListener('load', mountWidget);
}
@@ -92,5 +97,5 @@ export function TurnstileWidget({
};
}, [onError, onExpire, onVerify, siteKey]);
return <div id={elementId} ref={containerRef} className='min-h-16' />;
return <div id={elementId} ref={containerRef} className="min-h-16" />;
}
@@ -9,11 +9,11 @@ interface DashboardShellProps {
export function DashboardShell({ children }: DashboardShellProps) {
return (
<div className='flex min-h-screen bg-transparent text-[var(--foreground-primary)]'>
<div className="flex min-h-screen bg-transparent text-[var(--foreground-primary)]">
<DashboardSidebar />
<div className='flex min-w-0 flex-1 flex-col'>
<div className="flex min-w-0 flex-1 flex-col">
<DashboardTopbar />
<main className='flex-1 px-4 py-6 md:px-8 md:py-8'>{children}</main>
<main className="flex-1 px-4 py-6 md:px-8 md:py-8">{children}</main>
</div>
</div>
);
@@ -1,26 +1,30 @@
import type {ReactNode} from 'react';
import type { ReactNode } from 'react';
interface PageHeaderProps {
title: string;
description?: string;
action?: ReactNode;
title: string;
description?: string;
action?: ReactNode;
}
export function PageHeader({title, description, action}: PageHeaderProps) {
return (
<div className='flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between'>
<div className='space-y-3'>
<p className='text-sm font-medium uppercase tracking-[0.24em] text-[var(--brand-primary)]'>OpenFlare</p>
<div className='space-y-2'>
<h1 className='text-3xl font-semibold tracking-tight text-[var(--foreground-primary)]'>{title}</h1>
{description ? (
<p className='max-w-3xl text-sm leading-7 text-[var(--foreground-secondary)]'>
{description}
</p>
) : null}
</div>
</div>
{action ? <div className='flex flex-wrap gap-3'>{action}</div> : null}
export function PageHeader({ title, description, action }: PageHeaderProps) {
return (
<div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
<div className="space-y-3">
<p className="text-sm font-medium tracking-[0.24em] text-[var(--brand-primary)] uppercase">
OpenFlare
</p>
<div className="space-y-2">
<h1 className="text-3xl font-semibold tracking-tight text-[var(--foreground-primary)]">
{title}
</h1>
{description ? (
<p className="max-w-3xl text-sm leading-7 text-[var(--foreground-secondary)]">
{description}
</p>
) : null}
</div>
);
</div>
{action ? <div className="flex flex-wrap gap-3">{action}</div> : null}
</div>
);
}
@@ -9,27 +9,35 @@ interface PublicShellProps {
export function PublicShell({ children }: PublicShellProps) {
return (
<div className='flex min-h-screen items-center justify-center px-4 py-12'>
<div className='w-full max-w-3xl rounded-[var(--radius-xl)] border border-[var(--border-default)] bg-[var(--surface-panel)]/85 p-8 shadow-[var(--shadow-soft)] backdrop-blur'>
<div className='mb-8 flex flex-col gap-4 border-b border-[var(--border-default)] pb-6 md:flex-row md:items-end md:justify-between'>
<div className="flex min-h-screen items-center justify-center px-4 py-12">
<div className="w-full max-w-3xl rounded-[var(--radius-xl)] border border-[var(--border-default)] bg-[var(--surface-panel)]/85 p-8 shadow-[var(--shadow-soft)] backdrop-blur">
<div className="mb-8 flex flex-col gap-4 border-b border-[var(--border-default)] pb-6 md:flex-row md:items-end md:justify-between">
<div>
<p className='text-3xl font-medium text-[var(--brand-primary)]'>OpenFlare</p>
<p className="text-3xl font-medium text-[var(--brand-primary)]">
OpenFlare
</p>
</div>
<div className='flex flex-col items-start gap-3 text-sm text-[var(--foreground-secondary)] md:items-end'>
<span className='rounded-full border border-[var(--border-default)] px-3 py-1.5'>
<div className="flex flex-col items-start gap-3 text-sm text-[var(--foreground-secondary)] md:items-end">
<span className="rounded-full border border-[var(--border-default)] px-3 py-1.5">
{publicEnv.appVersion}
</span>
</div>
</div>
<div className='space-y-6'>{children}</div>
<div className="space-y-6">{children}</div>
<div className='mt-8 border-t border-[var(--border-default)] pt-6 text-sm text-[var(--foreground-secondary)]'>
<div className='flex flex-wrap gap-4'>
<Link href='/' className='text-[var(--brand-primary)] transition hover:opacity-80'>
<div className="mt-8 border-t border-[var(--border-default)] pt-6 text-sm text-[var(--foreground-secondary)]">
<div className="flex flex-wrap gap-4">
<Link
href="/"
className="text-[var(--brand-primary)] transition hover:opacity-80"
>
返回
</Link>
<Link href='/about' className='text-[var(--brand-primary)] transition hover:opacity-80'>
<Link
href="/about"
className="text-[var(--brand-primary)] transition hover:opacity-80"
>
关于
</Link>
</div>
@@ -10,7 +10,10 @@ import {
useState,
} from 'react';
import { logout as logoutRequest, getCurrentUser } from '@/features/auth/api/auth';
import {
logout as logoutRequest,
getCurrentUser,
} from '@/features/auth/api/auth';
import type { AuthUser } from '@/types/auth';
interface AuthContextValue {
@@ -93,7 +93,9 @@ export function ThemeProvider({ children }: ThemeProviderProps) {
[resolvedTheme, setThemeMode, themeMode],
);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
return (
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
);
}
export function useTheme() {
@@ -25,17 +25,23 @@ export function AppCard({
{...props}
>
{(title || description || action) && (
<header className='flex flex-col gap-3 border-b border-[var(--border-default)] px-6 py-5 md:flex-row md:items-start md:justify-between'>
<div className='space-y-1'>
{title ? <h2 className='text-lg font-semibold text-[var(--foreground-primary)]'>{title}</h2> : null}
<header className="flex flex-col gap-3 border-b border-[var(--border-default)] px-6 py-5 md:flex-row md:items-start md:justify-between">
<div className="space-y-1">
{title ? (
<h2 className="text-lg font-semibold text-[var(--foreground-primary)]">
{title}
</h2>
) : null}
{description ? (
<p className='text-sm leading-6 text-[var(--foreground-secondary)]'>{description}</p>
<p className="text-sm leading-6 text-[var(--foreground-secondary)]">
{description}
</p>
) : null}
</div>
{action ? <div className='shrink-0'>{action}</div> : null}
{action ? <div className="shrink-0">{action}</div> : null}
</header>
)}
<div className='px-6 py-5'>{children}</div>
<div className="px-6 py-5">{children}</div>
</section>
);
}
@@ -55,32 +55,52 @@ export function AppModal({
}
return (
<div className='fixed inset-0 z-50 flex items-center justify-center bg-slate-950/55 px-4 py-6' role='dialog' aria-modal='true' aria-label={title}>
<button type='button' className='absolute inset-0 cursor-default' onClick={onClose} aria-label='关闭弹窗' />
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/55 px-4 py-6"
role="dialog"
aria-modal="true"
aria-label={title}
>
<button
type="button"
className="absolute inset-0 cursor-default"
onClick={onClose}
aria-label="关闭弹窗"
/>
<div
className={cn(
'relative flex max-h-[calc(100vh-3rem)] w-full flex-col overflow-hidden rounded-[28px] border border-[var(--border-default)] bg-[var(--surface-panel)] shadow-2xl',
sizeClassNameMap[size],
)}
>
<div className='flex items-start justify-between gap-4 border-b border-[var(--border-default)] px-6 py-5'>
<div className='space-y-2'>
<h2 className='text-xl font-semibold text-[var(--foreground-primary)]'>{title}</h2>
<div className="flex items-start justify-between gap-4 border-b border-[var(--border-default)] px-6 py-5">
<div className="space-y-2">
<h2 className="text-xl font-semibold text-[var(--foreground-primary)]">
{title}
</h2>
{description ? (
<p className='max-w-2xl text-sm leading-6 text-[var(--foreground-secondary)]'>{description}</p>
<p className="max-w-2xl text-sm leading-6 text-[var(--foreground-secondary)]">
{description}
</p>
) : null}
</div>
<button
type='button'
type="button"
onClick={onClose}
className='inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-[var(--border-default)] bg-[var(--control-background)] text-lg text-[var(--foreground-primary)] transition hover:bg-[var(--control-background-hover)]'
aria-label='关闭弹窗'
className="inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-[var(--border-default)] bg-[var(--control-background)] text-lg text-[var(--foreground-primary)] transition hover:bg-[var(--control-background-hover)]"
aria-label="关闭弹窗"
>
×
</button>
</div>
<div className='min-h-0 flex-1 overflow-y-auto px-6 py-6'>{children}</div>
{footer ? <div className='border-t border-[var(--border-default)] px-6 py-5'>{footer}</div> : null}
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-6">
{children}
</div>
{footer ? (
<div className="border-t border-[var(--border-default)] px-6 py-5">
{footer}
</div>
) : null}
</div>
</div>
);
+29 -5
View File
@@ -261,7 +261,9 @@ function useDrawerMetaContext() {
const context = useContext(DrawerMetaContext);
if (!context) {
throw new Error('Drawer title and description must be used within DrawerContent.');
throw new Error(
'Drawer title and description must be used within DrawerContent.',
);
}
return context;
@@ -271,14 +273,30 @@ export function DrawerHeader({
className,
...props
}: HTMLAttributes<HTMLDivElement>) {
return <div className={cn('border-b border-[var(--border-default)] px-6 py-5', className)} {...props} />;
return (
<div
className={cn(
'border-b border-[var(--border-default)] px-6 py-5',
className,
)}
{...props}
/>
);
}
export function DrawerFooter({
className,
...props
}: HTMLAttributes<HTMLDivElement>) {
return <div className={cn('border-t border-[var(--border-default)] px-6 py-4', className)} {...props} />;
return (
<div
className={cn(
'border-t border-[var(--border-default)] px-6 py-4',
className,
)}
{...props}
/>
);
}
export function DrawerTitle({
@@ -290,7 +308,10 @@ export function DrawerTitle({
return (
<h2
id={titleId}
className={cn('text-xl font-semibold text-[var(--foreground-primary)]', className)}
className={cn(
'text-xl font-semibold text-[var(--foreground-primary)]',
className,
)}
{...props}
/>
);
@@ -305,7 +326,10 @@ export function DrawerDescription({
return (
<p
id={descriptionId}
className={cn('mt-2 text-sm leading-6 text-[var(--foreground-secondary)]', className)}
className={cn(
'mt-2 text-sm leading-6 text-[var(--foreground-secondary)]',
className,
)}
{...props}
/>
);
+1 -1
View File
@@ -8,7 +8,7 @@ const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
<input
type={type}
className={cn(
'flex h-10 w-full rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2 text-sm text-[var(--foreground-primary)] shadow-none outline-none transition placeholder:text-[var(--foreground-muted)] focus-visible:border-[var(--border-strong)] focus-visible:ring-2 focus-visible:ring-[var(--accent-soft)] disabled:cursor-not-allowed disabled:opacity-50',
'flex h-10 w-full rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2 text-sm text-[var(--foreground-primary)] shadow-none transition outline-none placeholder:text-[var(--foreground-muted)] focus-visible:border-[var(--border-strong)] focus-visible:ring-2 focus-visible:ring-[var(--accent-soft)] disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
ref={ref}
+12 -13
View File
@@ -2,19 +2,18 @@ import * as React from 'react';
import { cn } from '@/lib/utils/cn';
const Label = React.forwardRef<
HTMLLabelElement,
React.ComponentProps<'label'>
>(({ className, ...props }, ref) => (
<label
ref={ref}
className={cn(
'text-sm font-medium leading-none text-[var(--foreground-primary)] peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
className,
)}
{...props}
/>
));
const Label = React.forwardRef<HTMLLabelElement, React.ComponentProps<'label'>>(
({ className, ...props }, ref) => (
<label
ref={ref}
className={cn(
'text-sm leading-none font-medium text-[var(--foreground-primary)] peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
className,
)}
{...props}
/>
),
);
Label.displayName = 'Label';
@@ -1,13 +1,13 @@
"use client"
'use client';
import * as React from "react"
import { Separator as SeparatorPrimitive } from "radix-ui"
import * as React from 'react';
import { Separator as SeparatorPrimitive } from 'radix-ui';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Separator({
className,
orientation = "horizontal",
orientation = 'horizontal',
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
@@ -17,12 +17,12 @@ function Separator({
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
className
'bg-border shrink-0 data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch',
className,
)}
{...props}
/>
)
);
}
export { Separator }
export { Separator };
@@ -21,7 +21,8 @@ const Switch = React.forwardRef<HTMLButtonElement, SwitchProps>(
},
ref,
) => {
const [internalChecked, setInternalChecked] = React.useState(defaultChecked);
const [internalChecked, setInternalChecked] =
React.useState(defaultChecked);
const isControlled = checked !== undefined;
const isChecked = isControlled ? checked : internalChecked;
@@ -9,7 +9,7 @@ const Textarea = React.forwardRef<
return (
<textarea
className={cn(
'flex min-h-28 w-full rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2 text-sm text-[var(--foreground-primary)] shadow-none outline-none transition placeholder:text-[var(--foreground-muted)] focus-visible:border-[var(--border-strong)] focus-visible:ring-2 focus-visible:ring-[var(--accent-soft)] disabled:cursor-not-allowed disabled:opacity-50',
'flex min-h-28 w-full rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2 text-sm text-[var(--foreground-primary)] shadow-none transition outline-none placeholder:text-[var(--foreground-muted)] focus-visible:border-[var(--border-strong)] focus-visible:ring-2 focus-visible:ring-[var(--accent-soft)] disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
ref={ref}
@@ -11,55 +11,61 @@ interface ThemeToggleProps {
export function ThemeToggle({ className }: ThemeToggleProps) {
const { themeMode, resolvedTheme, setThemeMode } = useTheme();
const currentIndex = themeModes.indexOf(themeMode);
const nextTheme = themeModes[(currentIndex + 1) % themeModes.length] as ThemeMode;
const nextTheme = themeModes[
(currentIndex + 1) % themeModes.length
] as ThemeMode;
const icon =
themeMode === 'light' ? (
<svg
className='h-5 w-5'
viewBox='0 0 24 24'
fill='none'
stroke='currentColor'
strokeWidth='1.8'
strokeLinecap='round'
strokeLinejoin='round'
className="h-5 w-5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx='12' cy='12' r='4' />
<path d='M12 2.5v2.2M12 19.3v2.2M21.5 12h-2.2M4.7 12H2.5M18.7 5.3l-1.6 1.6M6.9 17.1l-1.6 1.6M18.7 18.7l-1.6-1.6M6.9 6.9 5.3 5.3' />
<circle cx="12" cy="12" r="4" />
<path d="M12 2.5v2.2M12 19.3v2.2M21.5 12h-2.2M4.7 12H2.5M18.7 5.3l-1.6 1.6M6.9 17.1l-1.6 1.6M18.7 18.7l-1.6-1.6M6.9 6.9 5.3 5.3" />
</svg>
) : themeMode === 'dark' ? (
<svg
className='h-5 w-5'
viewBox='0 0 24 24'
fill='none'
stroke='currentColor'
strokeWidth='1.8'
strokeLinecap='round'
strokeLinejoin='round'
className="h-5 w-5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d='M20 15.2A7.8 7.8 0 1 1 8.8 4 6.4 6.4 0 0 0 20 15.2Z' />
<path d="M20 15.2A7.8 7.8 0 1 1 8.8 4 6.4 6.4 0 0 0 20 15.2Z" />
</svg>
) : (
<svg
className='h-5 w-5'
viewBox='0 0 24 24'
fill='none'
stroke='currentColor'
strokeWidth='1.8'
strokeLinecap='round'
strokeLinejoin='round'
className="h-5 w-5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
>
<rect x='3.5' y='4' width='17' height='12' rx='2.5' />
<path d='M8 20h8M12 16v4' />
<rect x="3.5" y="4" width="17" height="12" rx="2.5" />
<path d="M8 20h8M12 16v4" />
</svg>
);
const label =
themeMode === 'light' ? '浅色模式' : themeMode === 'dark' ? '深色模式' : '跟随系统';
themeMode === 'light'
? '浅色模式'
: themeMode === 'dark'
? '深色模式'
: '跟随系统';
return (
<button
type='button'
type="button"
onClick={() => setThemeMode(nextTheme)}
className={cn(
'inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-[var(--border-default)] bg-[var(--control-background)] text-[var(--foreground-primary)] transition hover:bg-[var(--control-background-hover)]',
@@ -33,45 +33,68 @@ export function AboutPage() {
}
if (aboutQuery.isError) {
return <ErrorState title='关于页加载失败' description={getErrorMessage(aboutQuery.error)} />;
return (
<ErrorState
title="关于页加载失败"
description={getErrorMessage(aboutQuery.error)}
/>
);
}
if (statusQuery.isError) {
return <ErrorState title='系统状态加载失败' description={getErrorMessage(statusQuery.error)} />;
return (
<ErrorState
title="系统状态加载失败"
description={getErrorMessage(statusQuery.error)}
/>
);
}
const aboutContent = aboutQuery.data?.trim() ?? '';
const status = statusQuery.data;
if (!status) {
return <EmptyState title='暂无系统信息' description='未能获取 OpenFlare 的公开状态信息。' />;
return (
<EmptyState
title="暂无系统信息"
description="未能获取 OpenFlare 的公开状态信息。"
/>
);
}
return (
<div className='space-y-6'>
<div className="space-y-6">
<AppCard
title='关于 OpenFlare'
description='公开展示当前系统简介、版本信息与项目入口。'
action={<StatusBadge label={status.version || 'dev'} variant='info' />}
title="关于 OpenFlare"
description="公开展示当前系统简介、版本信息与项目入口。"
action={<StatusBadge label={status.version || 'dev'} variant="info" />}
>
<div className='grid gap-4 md:grid-cols-3'>
<div className='rounded-2xl border border-[var(--border-default)] bg-[var(--surface-muted)] px-4 py-4'>
<p className='text-xs uppercase tracking-[0.2em] text-[var(--foreground-muted)]'>系统名称</p>
<p className='mt-2 text-sm font-medium text-[var(--foreground-primary)]'>{status.system_name || 'OpenFlare'}</p>
<div className="grid gap-4 md:grid-cols-3">
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-muted)] px-4 py-4">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
系统名称
</p>
<p className="mt-2 text-sm font-medium text-[var(--foreground-primary)]">
{status.system_name || 'OpenFlare'}
</p>
</div>
<div className='rounded-2xl border border-[var(--border-default)] bg-[var(--surface-muted)] px-4 py-4'>
<p className='text-xs uppercase tracking-[0.2em] text-[var(--foreground-muted)]'>Server 启动时间</p>
<p className='mt-2 text-sm font-medium text-[var(--foreground-primary)]'>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-muted)] px-4 py-4">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
Server 启动时间
</p>
<p className="mt-2 text-sm font-medium text-[var(--foreground-primary)]">
{formatDateTime(new Date(status.start_time * 1000))}
</p>
</div>
<div className='rounded-2xl border border-[var(--border-default)] bg-[var(--surface-muted)] px-4 py-4'>
<p className='text-xs uppercase tracking-[0.2em] text-[var(--foreground-muted)]'>项目仓库</p>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-muted)] px-4 py-4">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
项目仓库
</p>
<a
href='https://github.com/Rain-kl/OpenFlare'
target='_blank'
rel='noreferrer'
className='mt-2 block text-sm font-medium text-[var(--brand-primary)] transition hover:opacity-80'
href="https://github.com/Rain-kl/OpenFlare"
target="_blank"
rel="noreferrer"
className="mt-2 block text-sm font-medium text-[var(--brand-primary)] transition hover:opacity-80"
>
github.com/Rain-kl/OpenFlare
</a>
@@ -80,21 +103,29 @@ export function AboutPage() {
</AppCard>
{aboutContent ? (
<AppCard title='项目介绍' description='以下内容由系统设置中的“关于内容”维护。'>
<AppCard
title="项目介绍"
description="以下内容由系统设置中的“关于内容”维护。"
>
<div
className='prose prose-sm max-w-none text-[var(--foreground-primary)] [&_a]:text-[var(--brand-primary)]'
dangerouslySetInnerHTML={{ __html: marked.parse(aboutContent) as string }}
className="prose prose-sm max-w-none text-[var(--foreground-primary)] [&_a]:text-[var(--brand-primary)]"
dangerouslySetInnerHTML={{
__html: marked.parse(aboutContent) as string,
}}
/>
</AppCard>
) : (
<EmptyState
title='尚未配置关于内容'
description='可在设置页的“其他设置”标签中编写 Markdown / HTML 内容,这里会自动同步展示。'
title="尚未配置关于内容"
description="可在设置页的“其他设置”标签中编写 Markdown / HTML 内容,这里会自动同步展示。"
/>
)}
<div className='flex flex-wrap gap-3 text-sm'>
<Link href='/login' className='text-[var(--brand-primary)] transition hover:opacity-80'>
<div className="flex flex-wrap gap-3 text-sm">
<Link
href="/login"
className="text-[var(--brand-primary)] transition hover:opacity-80"
>
前往登录
</Link>
</div>
@@ -29,11 +29,8 @@ import {
} from '@/features/shared/components/resource-primitives';
import { formatDateTime, formatRelativeTime } from '@/lib/utils/date';
const applyLogsQueryKey = (
nodeId: string,
pageNo: number,
pageSize: number,
) => ['apply-logs', nodeId, pageNo, pageSize] as const;
const applyLogsQueryKey = (nodeId: string, pageNo: number, pageSize: number) =>
['apply-logs', nodeId, pageNo, pageSize] as const;
const pageSizeOptions = [20, 50, 100];
const emptyApplyLogRows: ApplyLogItem[] = [];
@@ -64,7 +61,12 @@ function truncateHash(value: string) {
return value.length > 12 ? `${value.slice(0, 12)}...` : value;
}
function buildSummary(rows: ApplyLogItem[], total: number, current: number, totalPage: number) {
function buildSummary(
rows: ApplyLogItem[],
total: number,
current: number,
totalPage: number,
) {
const nodeIds = new Set(rows.map((item) => item.node_id));
return [
{ label: '总记录数', value: total },
@@ -209,14 +211,17 @@ export function ApplyLogsPage() {
<InlineMessage tone={feedback.tone} message={feedback.message} />
) : null}
<AppCard title="日志摘要" description="后端按分页返回应用日志,页面仅展示当前页数据和总量信息。">
<AppCard
title="日志摘要"
description="后端按分页返回应用日志,页面仅展示当前页数据和总量信息。"
>
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
{summary.map((item) => (
<div
key={item.label}
className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4"
>
<p className="text-xs tracking-[0.2em] uppercase text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
{item.label}
</p>
<p className="mt-2 text-lg font-semibold text-[var(--foreground-primary)]">
@@ -348,13 +353,16 @@ export function ApplyLogsPage() {
<div className="flex flex-col gap-3 border-t border-[var(--border-default)] pt-4 md:flex-row md:items-center md:justify-between">
<p className="text-sm text-[var(--foreground-secondary)]">
第 {current} / {Math.max(totalPage, 1)} 页,共 {total} 条记录。
第 {current} / {Math.max(totalPage, 1)} 页,共 {total}{' '}
条记录。
</p>
<div className="flex flex-wrap gap-2">
<SecondaryButton
type="button"
disabled={current <= 1}
onClick={() => setPageNo((previous) => Math.max(1, previous - 1))}
onClick={() =>
setPageNo((previous) => Math.max(1, previous - 1))
}
>
上一页
</SecondaryButton>
@@ -363,7 +371,9 @@ export function ApplyLogsPage() {
disabled={totalPage === 0 || current >= totalPage}
onClick={() =>
setPageNo((previous) =>
totalPage > 0 ? Math.min(totalPage, previous + 1) : previous,
totalPage > 0
? Math.min(totalPage, previous + 1)
: previous,
)
}
>
@@ -387,14 +397,30 @@ export function ApplyLogsPage() {
<div className="space-y-4">
<div className="flex flex-wrap gap-2">
<StatusBadge {...getResultMeta(selectedLog.result)} />
<StatusBadge label={`Node:${selectedLog.node_id}`} variant="info" />
<StatusBadge label={`版本:${selectedLog.version}`} variant="warning" />
<StatusBadge
label={`Node:${selectedLog.node_id}`}
variant="info"
/>
<StatusBadge
label={`版本:${selectedLog.version}`}
variant="warning"
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<MetricCard label="创建时间" value={formatDateTime(selectedLog.created_at)} />
<MetricCard label="相对时间" value={formatRelativeTime(selectedLog.created_at)} />
<MetricCard label="目标 Checksum" value={selectedLog.checksum || '—'} breakAll />
<MetricCard
label="创建时间"
value={formatDateTime(selectedLog.created_at)}
/>
<MetricCard
label="相对时间"
value={formatRelativeTime(selectedLog.created_at)}
/>
<MetricCard
label="目标 Checksum"
value={selectedLog.checksum || '—'}
breakAll
/>
<MetricCard
label="支持文件数"
value={String(selectedLog.support_file_count)}
@@ -412,10 +438,10 @@ export function ApplyLogsPage() {
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs tracking-[0.2em] uppercase text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
消息
</p>
<pre className="mt-3 whitespace-pre-wrap break-words text-sm leading-6 text-[var(--foreground-primary)]">
<pre className="mt-3 text-sm leading-6 break-words whitespace-pre-wrap text-[var(--foreground-primary)]">
{selectedLog.message || '—'}
</pre>
</div>
@@ -430,7 +456,10 @@ export function ApplyLogsPage() {
onClose={() => setCleanupModalOpen(false)}
footer={
<div className="flex flex-wrap justify-end gap-2">
<SecondaryButton type="button" onClick={() => setCleanupModalOpen(false)}>
<SecondaryButton
type="button"
onClick={() => setCleanupModalOpen(false)}
>
取消
</SecondaryButton>
<PrimaryButton
@@ -505,7 +534,7 @@ function MetricCard({
}) {
return (
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs tracking-[0.2em] uppercase text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
{label}
</p>
<p
@@ -1,4 +1,8 @@
import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode } from 'react';
import type {
ButtonHTMLAttributes,
InputHTMLAttributes,
ReactNode,
} from 'react';
import { cn } from '@/lib/utils/cn';
@@ -12,10 +16,16 @@ export function AuthFormField({
children: ReactNode;
}) {
return (
<label className='block space-y-2'>
<span className='text-sm font-medium text-[var(--foreground-primary)]'>{label}</span>
<label className="block space-y-2">
<span className="text-sm font-medium text-[var(--foreground-primary)]">
{label}
</span>
{children}
{hint ? <span className='block text-xs text-[var(--foreground-secondary)]'>{hint}</span> : null}
{hint ? (
<span className="block text-xs text-[var(--foreground-secondary)]">
{hint}
</span>
) : null}
</label>
);
}
@@ -25,7 +35,7 @@ export function AuthInput(props: InputHTMLAttributes<HTMLInputElement>) {
<input
{...props}
className={cn(
'w-full rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3 text-sm text-[var(--foreground-primary)] outline-none transition placeholder:text-[var(--foreground-muted)] focus:border-[var(--border-strong)] focus:ring-2 focus:ring-[var(--accent-soft)]',
'w-full rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3 text-sm text-[var(--foreground-primary)] transition outline-none placeholder:text-[var(--foreground-muted)] focus:border-[var(--border-strong)] focus:ring-2 focus:ring-[var(--accent-soft)]',
props.className,
)}
/>
@@ -18,15 +18,18 @@ export function DashboardAuthGuard({ children }: DashboardAuthGuardProps) {
useEffect(() => {
if (!isLoading && !isAuthenticated) {
const redirect = pathname && pathname !== '/' ? `?redirect=${encodeURIComponent(pathname)}` : '';
const redirect =
pathname && pathname !== '/'
? `?redirect=${encodeURIComponent(pathname)}`
: '';
router.replace(`/login${redirect}`);
}
}, [isAuthenticated, isLoading, pathname, router]);
if (isLoading || !isAuthenticated) {
return (
<main className='flex min-h-screen items-center justify-center px-4 py-8'>
<LoadingState className='w-full max-w-md' />
<main className="flex min-h-screen items-center justify-center px-4 py-8">
<LoadingState className="w-full max-w-md" />
</main>
);
}
@@ -16,7 +16,10 @@ export function GitHubOAuthCallback() {
const { setUser } = useAuth();
const handledCodeRef = useRef<string | null>(null);
const [prompt, setPrompt] = useState('正在处理 GitHub 授权结果...');
const [message, setMessage] = useState<{ tone: 'danger' | 'success'; text: string } | null>(null);
const [message, setMessage] = useState<{
tone: 'danger' | 'success';
text: string;
} | null>(null);
const code = searchParams?.get('code')?.trim() ?? '';
const mutation = useMutation({
@@ -28,14 +31,20 @@ export function GitHubOAuthCallback() {
},
onError: (error: Error) => {
setPrompt('授权处理失败');
setMessage({ tone: 'danger', text: error.message || 'GitHub 授权失败,请稍后重试。' });
setMessage({
tone: 'danger',
text: error.message || 'GitHub 授权失败,请稍后重试。',
});
},
});
useEffect(() => {
if (!code) {
setPrompt('缺少授权 code');
setMessage({ tone: 'danger', text: '未收到 GitHub 授权参数,请返回登录页重试。' });
setMessage({
tone: 'danger',
text: '未收到 GitHub 授权参数,请返回登录页重试。',
});
return;
}
@@ -48,10 +57,12 @@ export function GitHubOAuthCallback() {
}, [code, mutation]);
return (
<AppCard title='GitHub OAuth 回调' description={prompt}>
<div className='space-y-4'>
<AppCard title="GitHub OAuth 回调" description={prompt}>
<div className="space-y-4">
{mutation.isPending ? <LoadingState /> : null}
{message ? <InlineMessage tone={message.tone} message={message.text} /> : null}
{message ? (
<InlineMessage tone={message.tone} message={message.text} />
) : null}
</div>
</AppCard>
);
@@ -19,45 +19,66 @@ export function PasswordResetConfirmForm() {
const searchParams = useSearchParams();
const email = searchParams?.get('email') || '';
const token = searchParams?.get('token') || '';
const [message, setMessage] = useState<{ tone: 'success' | 'danger'; text: string } | null>(null);
const [message, setMessage] = useState<{
tone: 'success' | 'danger';
text: string;
} | null>(null);
const mutation = useMutation({
mutationFn: () => resetPassword({ email, token }),
onSuccess: async (password) => {
try {
await navigator.clipboard.writeText(password);
setMessage({ tone: 'success', text: `密码已重置,新密码已复制到剪贴板:${password}` });
setMessage({
tone: 'success',
text: `密码已重置,新密码已复制到剪贴板:${password}`,
});
} catch {
setMessage({ tone: 'success', text: `密码已重置:${password}` });
}
},
onError: (error: Error) => {
setMessage({ tone: 'danger', text: error.message || '密码重置失败,请重新获取链接。' });
setMessage({
tone: 'danger',
text: error.message || '密码重置失败,请重新获取链接。',
});
},
});
const missingParams = !email || !token;
return (
<AppCard title='密码重置确认' description='确认后,系统会生成新的随机密码。'>
<div className='space-y-4'>
<AuthFormField label='邮箱地址'>
<AppCard
title="密码重置确认"
description="确认后,系统会生成新的随机密码。"
>
<div className="space-y-4">
<AuthFormField label="邮箱地址">
<AuthInput value={email} readOnly />
</AuthFormField>
{missingParams ? (
<InlineMessage tone='danger' message='重置链接缺少必要参数,请重新发起密码重置。' />
<InlineMessage
tone="danger"
message="重置链接缺少必要参数,请重新发起密码重置。"
/>
) : null}
{message ? <InlineMessage tone={message.tone} message={message.text} /> : null}
{message ? (
<InlineMessage tone={message.tone} message={message.text} />
) : null}
<div className='flex flex-col gap-3 sm:flex-row'>
<AuthButton type='button' disabled={missingParams || mutation.isPending} onClick={() => mutation.mutate()}>
<div className="flex flex-col gap-3 sm:flex-row">
<AuthButton
type="button"
disabled={missingParams || mutation.isPending}
onClick={() => mutation.mutate()}
>
{mutation.isPending ? '处理中...' : '确认重置密码'}
</AuthButton>
{message?.tone === 'success' ? (
<SecondaryButton
type='button'
type="button"
onClick={async () => {
const password = message.text.split(':').pop() || '';
if (password) {
@@ -70,9 +91,12 @@ export function PasswordResetConfirmForm() {
) : null}
</div>
<div className='text-sm text-[var(--foreground-secondary)]'>
<div className="text-sm text-[var(--foreground-secondary)]">
处理完成后可返回
<Link href='/login' className='ml-2 text-[var(--brand-primary)] transition hover:opacity-80'>
<Link
href="/login"
className="ml-2 text-[var(--brand-primary)] transition hover:opacity-80"
>
登录页
</Link>
</div>
@@ -7,7 +7,13 @@ import { PasswordResetRequestForm } from '@/features/auth/components/password-re
export function PasswordResetFlow() {
const searchParams = useSearchParams();
const hasConfirmationParams = Boolean(searchParams?.get('email') && searchParams?.get('token'));
const hasConfirmationParams = Boolean(
searchParams?.get('email') && searchParams?.get('token'),
);
return hasConfirmationParams ? <PasswordResetConfirmForm /> : <PasswordResetRequestForm />;
return hasConfirmationParams ? (
<PasswordResetConfirmForm />
) : (
<PasswordResetRequestForm />
);
}
@@ -27,7 +27,10 @@ type ResetRequestFormValues = z.infer<typeof resetRequestSchema>;
export function PasswordResetRequestForm() {
const [turnstileToken, setTurnstileToken] = useState('');
const [message, setMessage] = useState<{ tone: 'success' | 'danger' | 'info'; text: string } | null>(null);
const [message, setMessage] = useState<{
tone: 'success' | 'danger' | 'info';
text: string;
} | null>(null);
const form = useForm<ResetRequestFormValues>({
resolver: zodResolver(resetRequestSchema),
@@ -47,7 +50,10 @@ export function PasswordResetRequestForm() {
form.reset();
},
onError: (error: Error) => {
setMessage({ tone: 'danger', text: error.message || '重置邮件发送失败,请稍后重试。' });
setMessage({
tone: 'danger',
text: error.message || '重置邮件发送失败,请稍后重试。',
});
},
});
@@ -62,18 +68,26 @@ export function PasswordResetRequestForm() {
return (
<PublicAuthGuard>
<AppCard title='密码重置' description='提交后,系统会向你的注册邮箱发送重置链接。'>
<form className='space-y-4' onSubmit={handleSubmit}>
<AuthFormField label='邮箱地址'>
<AuthInput type='email' placeholder='请输入邮箱地址' {...form.register('email')} />
<AppCard
title="密码重置"
description="提交后,系统会向你的注册邮箱发送重置链接。"
>
<form className="space-y-4" onSubmit={handleSubmit}>
<AuthFormField label="邮箱地址">
<AuthInput
type="email"
placeholder="请输入邮箱地址"
{...form.register('email')}
/>
{form.formState.errors.email ? (
<span className='text-xs text-[var(--status-danger-foreground)]'>
<span className="text-xs text-[var(--status-danger-foreground)]">
{form.formState.errors.email.message}
</span>
) : null}
</AuthFormField>
{statusQuery.data?.turnstile_check && statusQuery.data.turnstile_site_key ? (
{statusQuery.data?.turnstile_check &&
statusQuery.data.turnstile_site_key ? (
<TurnstileWidget
siteKey={statusQuery.data.turnstile_site_key}
onVerify={(token) => setTurnstileToken(token)}
@@ -82,16 +96,21 @@ export function PasswordResetRequestForm() {
/>
) : null}
{message ? <InlineMessage tone={message.tone} message={message.text} /> : null}
{message ? (
<InlineMessage tone={message.tone} message={message.text} />
) : null}
<AuthButton type='submit' disabled={mutation.isPending}>
<AuthButton type="submit" disabled={mutation.isPending}>
{mutation.isPending ? '提交中...' : '发送重置邮件'}
</AuthButton>
</form>
<div className='mt-6 text-sm text-[var(--foreground-secondary)]'>
<div className="mt-6 text-sm text-[var(--foreground-secondary)]">
想起密码了?
<Link href='/login' className='ml-2 text-[var(--brand-primary)] transition hover:opacity-80'>
<Link
href="/login"
className="ml-2 text-[var(--brand-primary)] transition hover:opacity-80"
>
返回登录
</Link>
</div>
@@ -45,7 +45,12 @@ export function CleanupConfigVersionsModal({
<SecondaryButton type="button" onClick={onClose} disabled={isPending}>
取消
</SecondaryButton>
<PrimaryButton type="submit" form="cleanup-form" disabled={isPending} className="bg-[var(--status-danger-foreground)] hover:bg-[var(--status-danger-foreground)] hover:opacity-90 border-[var(--status-danger-foreground)]">
<PrimaryButton
type="submit"
form="cleanup-form"
disabled={isPending}
className="border-[var(--status-danger-foreground)] bg-[var(--status-danger-foreground)] hover:bg-[var(--status-danger-foreground)] hover:opacity-90"
>
{isPending ? '清理中...' : '确认清理'}
</PrimaryButton>
</div>
@@ -285,7 +285,10 @@ function PublishPreviewCard({
{isActiveVersionDetailLoading ? (
<LoadingState />
) : activeVersionDetailError ? (
<InlineMessage tone="danger" message={activeVersionDetailError} />
<InlineMessage
tone="danger"
message={activeVersionDetailError}
/>
) : activeVersionDetail ? (
<CodeBlock className="max-h-[32rem] whitespace-pre-wrap">
{activeVersionDetail.main_config}
@@ -520,7 +523,11 @@ export function ConfigVersionsPage() {
<SecondaryButton
type="button"
onClick={() => {
if (window.confirm('确认强制重新发布吗?这会忽略配置变化检查并立即生成一个新版本。')) {
if (
window.confirm(
'确认强制重新发布吗?这会忽略配置变化检查并立即生成一个新版本。',
)
) {
publishMutation.mutate(true);
}
}}
@@ -672,7 +679,9 @@ export function ConfigVersionsPage() {
<CleanupConfigVersionsModal
isOpen={isCleanupModalOpen}
onClose={() => setIsCleanupModalOpen(false)}
onConfirm={(keepCount) => cleanupMutation.mutate({ keep_count: keepCount })}
onConfirm={(keepCount) =>
cleanupMutation.mutate({ keep_count: keepCount })
}
isPending={cleanupMutation.isPending}
/>
</>
@@ -27,7 +27,9 @@ function isCompactDistributionItem(
}
function isCompactTrafficTrendPoint(
value: DashboardOverview['trends']['traffic_24h'][number] | CompactTrafficTrendPoint,
value:
| DashboardOverview['trends']['traffic_24h'][number]
| CompactTrafficTrendPoint,
): value is CompactTrafficTrendPoint {
return Array.isArray(value);
}
@@ -74,7 +76,10 @@ function normalizeDistributionItems(
function normalizeTrafficTrendPoints(
items:
| Array<DashboardOverview['trends']['traffic_24h'][number] | CompactTrafficTrendPoint>
| Array<
| DashboardOverview['trends']['traffic_24h'][number]
| CompactTrafficTrendPoint
>
| null
| undefined,
) {
@@ -114,7 +119,8 @@ function normalizeCapacityTrendPoints(
function normalizeNetworkTrendPoints(
items:
| Array<
DashboardOverview['trends']['network_24h'][number] | CompactNetworkTrendPoint
| DashboardOverview['trends']['network_24h'][number]
| CompactNetworkTrendPoint
>
| null
| undefined,
@@ -136,7 +142,8 @@ function normalizeNetworkTrendPoints(
function normalizeDiskIOTrendPoints(
items:
| Array<
DashboardOverview['trends']['disk_io_24h'][number] | CompactDiskIOTrendPoint
| DashboardOverview['trends']['disk_io_24h'][number]
| CompactDiskIOTrendPoint
>
| null
| undefined,
@@ -154,7 +161,10 @@ function normalizeDiskIOTrendPoints(
}
function normalizeDashboardNodes(
items: Array<DashboardNodeHealth | CompactDashboardNodeHealth> | null | undefined,
items:
| Array<DashboardNodeHealth | CompactDashboardNodeHealth>
| null
| undefined,
): DashboardNodeHealth[] {
return arrayOrEmpty(items).map((item) =>
isCompactDashboardNode(item)
@@ -185,11 +195,7 @@ function normalizeDashboardNodes(
}
function normalizeDashboardOverview(
overview:
| DashboardOverview
| DashboardOverviewCompact
| null
| undefined,
overview: DashboardOverview | DashboardOverviewCompact | null | undefined,
): DashboardOverview | null {
if (!overview) {
return null;
@@ -209,8 +215,12 @@ function normalizeDashboardOverview(
source_countries: normalizeDistributionItems(
overview.distributions?.source_countries,
),
status_codes: normalizeDistributionItems(overview.distributions?.status_codes),
top_domains: normalizeDistributionItems(overview.distributions?.top_domains),
status_codes: normalizeDistributionItems(
overview.distributions?.status_codes,
),
top_domains: normalizeDistributionItems(
overview.distributions?.top_domains,
),
},
trends: {
traffic_24h: normalizeTrafficTrendPoints(overview.trends?.traffic_24h),
@@ -222,8 +232,8 @@ function normalizeDashboardOverview(
}
export async function getDashboardOverview() {
const overview = await apiRequest<DashboardOverview | DashboardOverviewCompact>(
'/dashboard/overview',
);
const overview = await apiRequest<
DashboardOverview | DashboardOverviewCompact
>('/dashboard/overview');
return normalizeDashboardOverview(overview);
}
@@ -137,8 +137,8 @@ function NodeHealthRow({ node }: { node: DashboardNodeHealth }) {
{isWSConnectedLastSeen(node.last_seen_at)
? ' WS 已连接'
: node.last_seen_at
? ` ${formatRelativeTime(node.last_seen_at)} · ${formatDateTime(node.last_seen_at)}`
: ' 暂无'}
? ` ${formatRelativeTime(node.last_seen_at)} · ${formatDateTime(node.last_seen_at)}`
: ' 暂无'}
</p>
</div>
</Link>
@@ -249,9 +249,7 @@ export function DashboardOverview() {
</div>
<div className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
<AppCard
title="24 小时网络与磁盘趋势"
>
<AppCard title="24 小时网络与磁盘趋势">
<div className="space-y-6">
<TrendChart
labels={overview.trends.network_24h.map((point) =>
@@ -311,9 +309,7 @@ export function DashboardOverview() {
</div>
</AppCard>
<AppCard
title="Top 节点榜单"
>
<AppCard title="Top 节点榜单">
<div className="grid gap-6 xl:grid-cols-1">
<div>
<p className="mb-3 text-xs tracking-[0.22em] text-[var(--foreground-muted)] uppercase">
@@ -352,10 +348,7 @@ export function DashboardOverview() {
</div>
<div className="grid gap-6 xl:grid-cols-3">
<AppCard
title="来源分布"
description="聚合最近 24 小时主要来源国家。"
>
<AppCard title="来源分布" description="聚合最近 24 小时主要来源国家。">
<RankChart
items={overview.distributions.source_countries.map((item) => ({
label: item.key,
@@ -380,10 +373,7 @@ export function DashboardOverview() {
/>
</AppCard>
<AppCard
title="Top Domain"
description="观察主要流量集中在哪些域名。"
>
<AppCard title="Top Domain" description="观察主要流量集中在哪些域名。">
<RankChart
items={overview.distributions.top_domains.map((item) => ({
label: item.key,
File diff suppressed because one or more lines are too long
@@ -15,7 +15,10 @@ export function createDnsAccount(payload: DnsAccountMutationPayload) {
});
}
export function updateDnsAccount(id: number, payload: DnsAccountMutationPayload) {
export function updateDnsAccount(
id: number,
payload: DnsAccountMutationPayload,
) {
return apiRequest<DnsAccountItem>(`/dns-accounts/${id}/update`, {
method: 'POST',
body: JSON.stringify(payload),
@@ -30,7 +30,10 @@ import { formatDateTime } from '@/lib/utils/date';
export function DnsAccountsPage() {
const queryClient = useQueryClient();
const [feedback, setFeedback] = useState<{ tone: 'info' | 'success' | 'danger'; message: string } | null>(null);
const [feedback, setFeedback] = useState<{
tone: 'info' | 'success' | 'danger';
message: string;
} | null>(null);
const [isCreateOpen, setIsCreateOpen] = useState(false);
const dnsAccountsQuery = useQuery({
@@ -57,7 +60,10 @@ export function DnsAccountsPage() {
deleteMutation.mutate(account.id);
};
const accounts = useMemo(() => dnsAccountsQuery.data ?? [], [dnsAccountsQuery.data]);
const accounts = useMemo(
() => dnsAccountsQuery.data ?? [],
[dnsAccountsQuery.data],
);
return (
<>
@@ -73,30 +79,47 @@ export function DnsAccountsPage() {
>
返回
</Link>
<PrimaryButton type="button" onClick={() => setIsCreateOpen(true)}>
<PrimaryButton
type="button"
onClick={() => setIsCreateOpen(true)}
>
添加账号
</PrimaryButton>
</div>
}
/>
{feedback ? <InlineMessage tone={feedback.tone} message={feedback.message} /> : null}
{feedback ? (
<InlineMessage tone={feedback.tone} message={feedback.message} />
) : null}
<AppCard title="DNS 账号列表">
{dnsAccountsQuery.isLoading ? (
<LoadingState />
) : dnsAccountsQuery.isError ? (
<ErrorState title="加载失败" description={getErrorMessage(dnsAccountsQuery.error)} />
<ErrorState
title="加载失败"
description={getErrorMessage(dnsAccountsQuery.error)}
/>
) : accounts.length === 0 ? (
<EmptyState title="暂无 DNS 账号" description="点击右上角“添加账号”开始录入。" />
<EmptyState
title="暂无 DNS 账号"
description="点击右上角“添加账号”开始录入。"
/>
) : (
<div className="space-y-3">
{accounts.map((account) => (
<div key={account.id} className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<div
key={account.id}
className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4"
>
<div className="flex items-start justify-between gap-4">
<div className="space-y-2">
<p className="text-sm font-semibold text-[var(--foreground-primary)]">
{account.name} <span className="ml-2 text-xs font-normal text-[var(--foreground-secondary)]">({account.type})</span>
{account.name}{' '}
<span className="ml-2 text-xs font-normal text-[var(--foreground-secondary)]">
({account.type})
</span>
</p>
<div className="text-xs leading-5 text-[var(--foreground-secondary)]">
<p>创建于:{formatDateTime(account.created_at)}</p>
@@ -121,17 +144,29 @@ export function DnsAccountsPage() {
</div>
{isCreateOpen && (
<DnsAccountCreateModal isOpen={isCreateOpen} onClose={() => setIsCreateOpen(false)} onCreated={() => {
setFeedback({ tone: 'success', message: 'DNS 账号已添加。' });
setIsCreateOpen(false);
queryClient.invalidateQueries({ queryKey: ['dns-accounts'] });
}} />
<DnsAccountCreateModal
isOpen={isCreateOpen}
onClose={() => setIsCreateOpen(false)}
onCreated={() => {
setFeedback({ tone: 'success', message: 'DNS 账号已添加。' });
setIsCreateOpen(false);
queryClient.invalidateQueries({ queryKey: ['dns-accounts'] });
}}
/>
)}
</>
);
}
function DnsAccountCreateModal({ isOpen, onClose, onCreated }: { isOpen: boolean; onClose: () => void; onCreated: () => void }) {
function DnsAccountCreateModal({
isOpen,
onClose,
onCreated,
}: {
isOpen: boolean;
onClose: () => void;
onCreated: () => void;
}) {
const [error, setError] = useState('');
const { register, handleSubmit, formState } = useForm({
defaultValues: { name: '', type: 'cloudflare', authorization: '' },
@@ -157,8 +192,14 @@ function DnsAccountCreateModal({ isOpen, onClose, onCreated }: { isOpen: boolean
<AppModal isOpen={isOpen} onClose={onClose} title="添加 DNS 账号">
<form onSubmit={onSubmit} className="space-y-5">
{error && <InlineMessage tone="danger" message={error} />}
<ResourceField label="账号名称" error={formState.errors.name?.message as string}>
<ResourceInput placeholder="Cloudlfare 邮箱账号" {...register('name', { required: '请输入名称' })} />
<ResourceField
label="账号名称"
error={formState.errors.name?.message as string}
>
<ResourceInput
placeholder="Cloudlfare 邮箱账号"
{...register('name', { required: '请输入名称' })}
/>
</ResourceField>
<ResourceField label="DNS 服务商">
<ResourceSelect {...register('type')}>
@@ -166,7 +207,9 @@ function DnsAccountCreateModal({ isOpen, onClose, onCreated }: { isOpen: boolean
</ResourceSelect>
</ResourceField>
<ResourceField label="API Token" hint="请勿使用 Global API Key">
<ResourceInput {...register('authorization', { required: '请输入 Token' })} />
<ResourceInput
{...register('authorization', { required: '请输入 Token' })}
/>
</ResourceField>
<PrimaryButton type="submit" disabled={createMutation.isPending}>
{createMutation.isPending ? '提交中...' : '提交'}
@@ -17,7 +17,10 @@ export function createManagedDomain(payload: ManagedDomainMutationPayload) {
});
}
export function updateManagedDomain(id: number, payload: ManagedDomainMutationPayload) {
export function updateManagedDomain(
id: number,
payload: ManagedDomainMutationPayload,
) {
return apiRequest<ManagedDomainItem>(`/managed-domains/${id}/update`, {
method: 'POST',
body: JSON.stringify(payload),
@@ -64,9 +64,9 @@ export function requestNodeAgentUpdate(
}
export function requestNodeForceSync(id: number) {
return apiRequest<NodeItem>(`/nodes/${id}/force-sync`, {
method: 'POST',
});
return apiRequest<NodeItem>(`/nodes/${id}/force-sync`, {
method: 'POST',
});
}
export function requestNodeOpenrestyRestart(id: number) {
@@ -404,7 +404,9 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
});
setHealthEventCleanupModalOpen(false);
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['node-observability', nodeId] }),
queryClient.invalidateQueries({
queryKey: ['node-observability', nodeId],
}),
queryClient.invalidateQueries({ queryKey: ['dashboard', 'overview'] }),
]);
},
@@ -869,9 +871,7 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
)}
</AppCard>
<AppCard
title="实时资源"
>
<AppCard title="实时资源">
{observabilityQuery.isLoading ? (
<LoadingState />
) : observabilityQuery.isError ? (
@@ -930,9 +930,7 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
)}
</AppCard>
<AppCard
title="网络流量"
>
<AppCard title="网络流量">
{observabilityQuery.isLoading ? (
<LoadingState />
) : observabilityQuery.isError ? (
@@ -1628,7 +1626,9 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
{nodeInstallCommand ? (
<div>
<p className="mb-2 text-sm font-medium text-[var(--foreground-primary)]">脚本部署 (Linux / macOS)</p>
<p className="mb-2 text-sm font-medium text-[var(--foreground-primary)]">
脚本部署 (Linux / macOS)
</p>
<CodeBlock className="whitespace-pre-wrap">
{nodeInstallCommand}
</CodeBlock>
@@ -1637,7 +1637,9 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
{nodeDockerInstallCommand ? (
<div>
<p className="mb-2 text-sm font-medium text-[var(--foreground-primary)]">Docker 部署</p>
<p className="mb-2 text-sm font-medium text-[var(--foreground-primary)]">
Docker 部署
</p>
<CodeBlock className="whitespace-pre-wrap">
{nodeDockerInstallCommand}
</CodeBlock>
@@ -1835,8 +1837,12 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
/>
) : (
<div className="space-y-3 text-sm text-[var(--foreground-secondary)]">
<p>该操作会删除当前节点已记录的全部健康事件,包括活动中与已恢复事件。</p>
<p>这不会影响节点后续继续上报新的健康事件,但现有时间线与相关摘要会立即刷新。</p>
<p>
该操作会删除当前节点已记录的全部健康事件,包括活动中与已恢复事件。
</p>
<p>
这不会影响节点后续继续上报新的健康事件,但现有时间线与相关摘要会立即刷新。
</p>
</div>
)}
</AppModal>
@@ -151,8 +151,8 @@ function getRegionCenter(feature: GeoJsonFeature) {
}
function buildRegionOptions() {
const features = ((worldGeoJson as { features?: GeoJsonFeature[] }).features ??
[]) as GeoJsonFeature[];
const features = ((worldGeoJson as { features?: GeoJsonFeature[] })
.features ?? []) as GeoJsonFeature[];
const options = new Map<string, RegionOption>();
for (const feature of features) {
@@ -186,7 +186,7 @@ function buildFormValues(node?: Partial<NodeItem> | null): NodeEditorValues {
ip: node.ip ?? '',
auto_update_enabled: node.auto_update_enabled ?? false,
geo_manual_override: node.geo_manual_override ?? false,
geo_region: node.geo_manual_override ? node.geo_name ?? '' : '',
geo_region: node.geo_manual_override ? (node.geo_name ?? '') : '',
geo_name: node.geo_name ?? '',
geo_latitude:
node.geo_latitude === undefined || node.geo_latitude === null
@@ -354,10 +354,10 @@ export function NodesPage() {
{isWSConnectedLastSeen(node.last_seen_at)
? 'WS 已连接'
: isMeaningfulTime(node.last_seen_at)
? `${formatRelativeTime(
node.last_seen_at,
)} · ${formatDateTime(node.last_seen_at)}`
: '暂无'}
? `${formatRelativeTime(
node.last_seen_at,
)} · ${formatDateTime(node.last_seen_at)}`
: '暂无'}
</td>
<td className="px-3 py-4">
<div className="flex flex-wrap gap-2">
+8 -3
View File
@@ -86,7 +86,9 @@ export function getUpdateMode(node: NodeItem) {
return { label: '手动', variant: 'info' as const };
}
export function getOpenrestyStatusVariant(status: NodeItem['openresty_status']) {
export function getOpenrestyStatusVariant(
status: NodeItem['openresty_status'],
) {
if (status === 'healthy') {
return 'success';
}
@@ -178,12 +180,15 @@ export function buildNodeInstallCommand(serverUrl: string, agentToken: string) {
].join('\n');
}
export function buildNodeDockerInstallCommand(serverUrl: string, agentToken: string) {
export function buildNodeDockerInstallCommand(
serverUrl: string,
agentToken: string,
) {
return [
`docker run -d --name openflare-agent --restart unless-stopped \\`,
` -p 80:80 -p 443:443 \\`,
` -e OPENFLARE_SERVER_URL=${serverUrl} \\`,
` -e OPENFLARE_AGENT_TOKEN=${agentToken} \\`,
` ghcr.io/rain-kl/openflare-agent:latest`
` ghcr.io/rain-kl/openflare-agent:latest`,
].join('\n');
}
File diff suppressed because it is too large Load Diff
@@ -22,7 +22,10 @@ export function createProxyRoute(payload: ProxyRouteMutationPayload) {
});
}
export function updateProxyRoute(id: number, payload: ProxyRouteMutationPayload) {
export function updateProxyRoute(
id: number,
payload: ProxyRouteMutationPayload,
) {
return apiRequest<ProxyRouteItem>(`/proxy-routes/${id}/update`, {
method: 'POST',
body: JSON.stringify(payload),
@@ -41,5 +44,7 @@ export function getTlsCertificates() {
export function matchManagedDomainCertificate(domain: string) {
const searchParams = new URLSearchParams({ domain });
return apiRequest<ManagedDomainMatchResult>(`/managed-domains/match?${searchParams.toString()}`);
return apiRequest<ManagedDomainMatchResult>(
`/managed-domains/match?${searchParams.toString()}`,
);
}
@@ -100,9 +100,7 @@ export function buildDomainRowsFromRoute(
if (domainCertIDs.length === domains.length) {
return domains.map((domain, index) => ({
domain,
certificateId: domainCertIDs[index]
? String(domainCertIDs[index])
: '',
certificateId: domainCertIDs[index] ? String(domainCertIDs[index]) : '',
}));
}
@@ -185,7 +183,9 @@ export function DomainListInput({
value={row.domain}
list={`${listId}-${index}`}
aria-label={`域名 ${index + 1}`}
placeholder={index === 0 ? domainPlaceholder : 'www.example.com'}
placeholder={
index === 0 ? domainPlaceholder : 'www.example.com'
}
onBlur={onBlur}
onChange={(event) => {
const nextRows = safeRows.slice();
@@ -123,7 +123,10 @@ const rateLimitSchema = z
limit_rate: z.string(),
})
.superRefine((value, context) => {
for (const field of ['limit_conn_per_server', 'limit_conn_per_ip'] as const) {
for (const field of [
'limit_conn_per_server',
'limit_conn_per_ip',
] as const) {
const rawValue = value[field].trim();
if (!rawValue) {
continue;
@@ -369,7 +372,9 @@ function DomainSettingsSection({
<ResourceField
label="域名列表"
hint="每行配置一个域名。可为不同域名选择不同证书,相同证书也可以重复选择。"
error={form.formState.errors.domain_rows?.message as string | undefined}
error={
form.formState.errors.domain_rows?.message as string | undefined
}
container="div"
>
<Controller
@@ -490,7 +495,10 @@ function RateLimitSection({
error={form.formState.errors.limit_rate?.message}
className="md:col-span-2"
>
<ResourceInput placeholder="512k/1m" {...form.register('limit_rate')} />
<ResourceInput
placeholder="512k/1m"
{...form.register('limit_rate')}
/>
</ResourceField>
</form>
</ConfigSectionShell>
@@ -538,7 +546,9 @@ function ReverseProxySection({
onSubmit={form.handleSubmit((values) => {
const { urls } = parseOriginUrls(values.origin_urls_text);
const primaryOrigin = parseOriginUrl(urls[0]);
const { headers } = parseCustomHeadersText(values.custom_headers_text);
const { headers } = parseCustomHeadersText(
values.custom_headers_text,
);
onSave(
buildPayloadFromRoute(route, {
@@ -565,7 +575,9 @@ function ReverseProxySection({
<ResourceTextarea
aria-label="上游地址"
className="min-h-40"
placeholder={'https://origin-a.internal:443\nhttps://origin-b.internal:443'}
placeholder={
'https://origin-a.internal:443\nhttps://origin-b.internal:443'
}
{...form.register('origin_urls_text')}
/>
</ResourceField>
@@ -593,7 +605,10 @@ function ReverseProxySection({
/>
</ResourceField>
<ResourceField label="备注" error={form.formState.errors.remark?.message}>
<ResourceField
label="备注"
error={form.formState.errors.remark?.message}
>
<ResourceTextarea
placeholder="例如:多活回源,优先使用上海入口"
{...form.register('remark')}
@@ -617,7 +632,8 @@ function CacheSection({
resolver: zodResolver(cacheSchema),
defaultValues: {
cache_enabled: route.cache_enabled,
cache_policy: (route.cache_policy || 'url') as CacheValues['cache_policy'],
cache_policy: (route.cache_policy ||
'url') as CacheValues['cache_policy'],
cache_rules_text: route.cache_rule_list.join('\n'),
},
});
@@ -625,7 +641,8 @@ function CacheSection({
useEffect(() => {
form.reset({
cache_enabled: route.cache_enabled,
cache_policy: (route.cache_policy || 'url') as CacheValues['cache_policy'],
cache_policy: (route.cache_policy ||
'url') as CacheValues['cache_policy'],
cache_rules_text: route.cache_rule_list.join('\n'),
});
}, [form, route]);
@@ -650,7 +667,9 @@ function CacheSection({
cache_enabled: values.cache_enabled,
cache_policy: values.cache_enabled ? values.cache_policy : 'url',
cache_rules:
values.cache_enabled && values.cache_policy !== 'url' ? rules : [],
values.cache_enabled && values.cache_policy !== 'url'
? rules
: [],
}),
{ message: '缓存设置已保存。' },
);
@@ -770,7 +789,13 @@ type PowValues = z.infer<typeof powSchema>;
function buildPowListFromConfig(
list:
| { ips?: string[]; ip_cidrs?: string[]; paths?: string[]; path_regexes?: string[]; user_agents?: string[] }
| {
ips?: string[];
ip_cidrs?: string[];
paths?: string[];
path_regexes?: string[];
user_agents?: string[];
}
| undefined,
): PowListValues {
return {
@@ -923,7 +948,7 @@ function PowSection({
<div className="grid grid-cols-1 gap-5 md:grid-cols-2">
<fieldset disabled={!watchedEnabled} className="space-y-4">
<legend className="text-sm font-medium text-[var(--foreground-primary)] mb-2">
<legend className="mb-2 text-sm font-medium text-[var(--foreground-primary)]">
白名单(匹配的请求跳过 PoW)
</legend>
<ResourceField label="IP" hint="每行一个 IP 地址">
@@ -964,7 +989,7 @@ function PowSection({
</fieldset>
<fieldset disabled={!watchedEnabled} className="space-y-4">
<legend className="text-sm font-medium text-[var(--foreground-primary)] mb-2">
<legend className="mb-2 text-sm font-medium text-[var(--foreground-primary)]">
黑名单(匹配的请求必须 PoW)
</legend>
<ResourceField label="IP" hint="每行一个 IP 地址">
@@ -1178,7 +1203,9 @@ export function ProxyRouteConfigPage({
setFeedback({ tone: 'success', message: context.message });
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['proxy-routes'] }),
queryClient.invalidateQueries({ queryKey: ['config-versions', 'diff'] }),
queryClient.invalidateQueries({
queryKey: ['config-versions', 'diff'],
}),
]);
},
onError: (error) => {
@@ -156,7 +156,9 @@ export function ProxyRouteCreateDrawer({
.map((item) => item.domain.trim().toLowerCase())
.filter(Boolean);
const domainCertIDs = buildDomainCertificateIDs(values.domain_rows);
const selectedCertIDs = normalizeSelectedCertificateIDs(values.domain_rows);
const selectedCertIDs = normalizeSelectedCertificateIDs(
values.domain_rows,
);
const { urls } = parseOriginUrls(values.origin_urls_text);
const primaryOrigin = parseOriginUrl(urls[0]);
@@ -182,7 +184,8 @@ export function ProxyRouteCreateDrawer({
cert_id: selectedCertIDs[0] ?? null,
cert_ids: selectedCertIDs,
domain_cert_ids: domainCertIDs,
redirect_http: selectedCertIDs.length > 0 ? values.redirect_http : false,
redirect_http:
selectedCertIDs.length > 0 ? values.redirect_http : false,
limit_conn_per_server: 0,
limit_conn_per_ip: 0,
limit_rate: '',
@@ -248,7 +251,9 @@ export function ProxyRouteCreateDrawer({
<ResourceField
label="域名列表"
hint="每行配置一个域名,可按需为该行选择证书。保存时会自动汇总站点证书集合。"
error={form.formState.errors.domain_rows?.message as string | undefined}
error={
form.formState.errors.domain_rows?.message as string | undefined
}
container="div"
>
<Controller
@@ -287,7 +292,9 @@ export function ProxyRouteCreateDrawer({
>
<ResourceTextarea
aria-label="上游地址"
placeholder={'https://origin-a.internal:443\nhttps://origin-b.internal:443'}
placeholder={
'https://origin-a.internal:443\nhttps://origin-b.internal:443'
}
{...form.register('origin_urls_text')}
/>
</ResourceField>
@@ -87,7 +87,9 @@ export function ProxyRoutesPage() {
setFeedback({ tone: 'success', message: '网站已删除。' });
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['proxy-routes'] }),
queryClient.invalidateQueries({ queryKey: ['config-versions', 'diff'] }),
queryClient.invalidateQueries({
queryKey: ['config-versions', 'diff'],
}),
]);
},
onError: (error) => {
@@ -104,7 +106,9 @@ export function ProxyRoutesPage() {
});
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['config-versions'] }),
queryClient.invalidateQueries({ queryKey: ['config-versions', 'diff'] }),
queryClient.invalidateQueries({
queryKey: ['config-versions', 'diff'],
}),
]);
},
onError: (error) => {
@@ -135,7 +139,10 @@ export function ProxyRoutesPage() {
}, [keyword, routes]);
const diff = diffQuery.data;
const totalDomains = routes.reduce((sum, route) => sum + route.domain_count, 0);
const totalDomains = routes.reduce(
(sum, route) => sum + route.domain_count,
0,
);
const enabledCount = routes.filter((route) => route.enabled).length;
const handleDelete = (route: ProxyRouteItem) => {
@@ -243,11 +250,11 @@ export function ProxyRoutesPage() {
<div className="space-y-3">
<StatusBadge
label={
diff && hasConfigChanges(diff) ? '有待发布变更' : '已与线上一致'
}
variant={
diff && hasConfigChanges(diff) ? 'warning' : 'success'
diff && hasConfigChanges(diff)
? '有待发布变更'
: '已与线上一致'
}
variant={diff && hasConfigChanges(diff) ? 'warning' : 'success'}
/>
<p className="text-sm text-[var(--foreground-secondary)]">
{diff
@@ -266,9 +273,7 @@ export function ProxyRoutesPage() {
</AppCard>
</div>
<AppCard
title="规则列表"
>
<AppCard title="规则列表">
<div className="space-y-4">
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div className="max-w-xl">
@@ -356,7 +361,7 @@ export function ProxyRoutesPage() {
<div className="grid gap-3 md:grid-cols-2">
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-panel)] px-4 py-3">
<p className="text-xs uppercase tracking-[0.18em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
域名列表
</p>
<p className="mt-2 text-sm text-[var(--foreground-primary)]">
@@ -365,7 +370,7 @@ export function ProxyRoutesPage() {
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-panel)] px-4 py-3">
<p className="text-xs uppercase tracking-[0.18em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
上游摘要
</p>
<p className="mt-2 text-sm text-[var(--foreground-primary)]">
@@ -393,7 +398,9 @@ export function ProxyRoutesPage() {
onCreated={async (route) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['proxy-routes'] }),
queryClient.invalidateQueries({ queryKey: ['config-versions', 'diff'] }),
queryClient.invalidateQueries({
queryKey: ['config-versions', 'diff'],
}),
]);
router.push(`/proxy-route/detail?id=${route.id}&section=domains`);
}}
@@ -386,7 +386,7 @@ export function AuthSourceModal({
}
/>
</ResourceField>
<div className="md:col-span-2 rounded-2xl border border-[var(--status-info-border)] bg-[var(--status-info-soft)] px-4 py-3 text-sm leading-6 text-[var(--status-info-foreground)]">
<div className="rounded-2xl border border-[var(--status-info-border)] bg-[var(--status-info-soft)] px-4 py-3 text-sm leading-6 text-[var(--status-info-foreground)] md:col-span-2">
第三方平台的 Redirect URI / Callback URL 请填写:
<span className="font-medium">
{' '}
@@ -927,7 +927,9 @@ export function SettingsPage() {
) : (
<PrimaryButton
type="button"
onClick={() => handleBindAuthSource(source.name)}
onClick={() =>
handleBindAuthSource(source.name)
}
disabled={
busyKey === `auth-source-bind-${source.name}`
}
@@ -1591,7 +1593,6 @@ export function SettingsPage() {
}
disabled={busyKey === 'toggle-EmailVerificationEnabled'}
/>
</div>
<div className="mt-5 text-sm text-[var(--foreground-secondary)]">
当前已配置 {authSourcesQuery.data?.length ?? 0} 个认证源。
@@ -14,12 +14,12 @@ export function ModulePageSkeleton({
description,
}: ModulePageSkeletonProps) {
return (
<div className='space-y-6'>
<div className="space-y-6">
<PageHeader title={title} description={description} />
<FeaturePlaceholder
title={`${title} 页面骨架`}
description='当前阶段先完成页面入口、统一头部和反馈组件接线,真实列表、表单与联动能力将在后续业务迁移阶段接入。'
description="当前阶段先完成页面入口、统一头部和反馈组件接线,真实列表、表单与联动能力将在后续业务迁移阶段接入。"
milestones={[
'路由入口已创建,可纳入统一导航。',
'页面标题区、说明区与内容容器已统一。',
@@ -27,10 +27,16 @@ export function ModulePageSkeleton({
]}
/>
<div className='grid gap-4 xl:grid-cols-3'>
<div className="grid gap-4 xl:grid-cols-3">
<LoadingState />
<EmptyState title='空态骨架' description='后续接入查询后,可将资源为空时的提示统一沉淀为此组件。' />
<ErrorState title='错误态骨架' description='后续请求失败、鉴权失效与重试提示可在此基础上扩展。' />
<EmptyState
title="空态骨架"
description="后续接入查询后,可将资源为空时的提示统一沉淀为此组件。"
/>
<ErrorState
title="错误态骨架"
description="后续请求失败、鉴权失效与重试提示可在此基础上扩展。"
/>
</div>
</div>
);
@@ -176,7 +176,7 @@ export function ToggleField({
onChange,
}: ToggleFieldProps) {
return (
<label className="flex self-start cursor-pointer items-start gap-3 rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3">
<label className="flex cursor-pointer items-start gap-3 self-start rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3">
<input
type="checkbox"
checked={checked}
@@ -1,489 +1,477 @@
'use client';
import {marked} from 'marked';
import {useEffect, useState} from 'react';
import { marked } from 'marked';
import { useEffect, useState } from 'react';
import {EmptyState} from '@/components/feedback/empty-state';
import {ErrorState} from '@/components/feedback/error-state';
import {LoadingState} from '@/components/feedback/loading-state';
import {AppCard} from '@/components/ui/app-card';
import {AppModal} from '@/components/ui/app-modal';
import {StatusBadge} from '@/components/ui/status-badge';
import { EmptyState } from '@/components/feedback/empty-state';
import { ErrorState } from '@/components/feedback/error-state';
import { LoadingState } from '@/components/feedback/loading-state';
import { AppCard } from '@/components/ui/app-card';
import { AppModal } from '@/components/ui/app-modal';
import { StatusBadge } from '@/components/ui/status-badge';
import type {
LatestReleaseInfo,
ReleaseChannel,
UploadedServerBinaryInfo,
LatestReleaseInfo,
ReleaseChannel,
UploadedServerBinaryInfo,
} from '@/features/update/types';
import {
PrimaryButton,
ResourceField,
ResourceInput,
SecondaryButton,
PrimaryButton,
ResourceField,
ResourceInput,
SecondaryButton,
} from '@/features/shared/components/resource-primitives';
import {formatDateTime, formatRelativeTime} from '@/lib/utils/date';
import { formatDateTime, formatRelativeTime } from '@/lib/utils/date';
interface VersionUpgradeModalProps {
isOpen: boolean;
onClose: () => void;
currentVersion: string;
release: LatestReleaseInfo | null | undefined;
selectedChannel: ReleaseChannel;
uploadedBinary: UploadedServerBinaryInfo | null;
isLoading: boolean;
releaseErrorMessage?: string;
manualStatusMessage?: string;
manualErrorMessage?: string;
canUpgrade: boolean;
isChecking: boolean;
isUpgrading: boolean;
isUploadingBinary: boolean;
uploadProgress: number;
isConfirmingManualUpgrade: boolean;
onChannelChange: (channel: ReleaseChannel) => void;
onCheck: () => void;
onUpgrade: () => void;
onUploadBinary: (file: File) => void;
onConfirmManualUpgrade: () => void;
isOpen: boolean;
onClose: () => void;
currentVersion: string;
release: LatestReleaseInfo | null | undefined;
selectedChannel: ReleaseChannel;
uploadedBinary: UploadedServerBinaryInfo | null;
isLoading: boolean;
releaseErrorMessage?: string;
manualStatusMessage?: string;
manualErrorMessage?: string;
canUpgrade: boolean;
isChecking: boolean;
isUpgrading: boolean;
isUploadingBinary: boolean;
uploadProgress: number;
isConfirmingManualUpgrade: boolean;
onChannelChange: (channel: ReleaseChannel) => void;
onCheck: () => void;
onUpgrade: () => void;
onUploadBinary: (file: File) => void;
onConfirmManualUpgrade: () => void;
}
function getUpgradeBadge(release: LatestReleaseInfo | null | undefined) {
if (!release) {
return {label: '未检查', variant: 'info' as const};
}
if (release.in_progress) {
return {label: '升级中', variant: 'warning' as const};
}
if (release.has_update) {
return {label: '可升级', variant: 'warning' as const};
}
return {label: '最新', variant: 'success' as const};
if (!release) {
return { label: '未检查', variant: 'info' as const };
}
if (release.in_progress) {
return { label: '升级中', variant: 'warning' as const };
}
if (release.has_update) {
return { label: '可升级', variant: 'warning' as const };
}
return { label: '最新', variant: 'success' as const };
}
function formatLogTimestamp(value: string) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return '0000-00-00 00:00:00.000';
}
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return '0000-00-00 00:00:00.000';
}
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
const hour = `${date.getHours()}`.padStart(2, '0');
const minute = `${date.getMinutes()}`.padStart(2, '0');
const second = `${date.getSeconds()}`.padStart(2, '0');
const millisecond = `${date.getMilliseconds()}`.padStart(3, '0');
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
const hour = `${date.getHours()}`.padStart(2, '0');
const minute = `${date.getMinutes()}`.padStart(2, '0');
const second = `${date.getSeconds()}`.padStart(2, '0');
const millisecond = `${date.getMilliseconds()}`.padStart(3, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}.${millisecond}`;
return `${year}-${month}-${day} ${hour}:${minute}:${second}.${millisecond}`;
}
function formatLogLevel(level: string) {
const normalized = (level || 'info').toUpperCase();
return normalized.padEnd(8, ' ');
const normalized = (level || 'info').toUpperCase();
return normalized.padEnd(8, ' ');
}
export function VersionUpgradeModal({
isOpen,
onClose,
currentVersion,
release,
selectedChannel,
uploadedBinary,
isLoading,
releaseErrorMessage,
manualStatusMessage,
manualErrorMessage,
canUpgrade,
isChecking,
isUpgrading,
isUploadingBinary,
uploadProgress,
isConfirmingManualUpgrade,
onChannelChange,
onCheck,
onUpgrade,
onUploadBinary,
onConfirmManualUpgrade,
}: VersionUpgradeModalProps) {
const upgradeBadge = getUpgradeBadge(release);
const [selectedBinary, setSelectedBinary] = useState<File | null>(null);
const uploadPhaseLabel =
uploadProgress >= 100
? '已上传,正在服务端校验版本...'
: '上传中...';
const selectedChannelLabel =
selectedChannel === 'preview' ? '预览版' : '正式版';
const toggleChannel = () => {
onChannelChange(selectedChannel === 'preview' ? 'stable' : 'preview');
};
const canConfirmManualUpgrade = Boolean(
uploadedBinary?.ready_to_upgrade && uploadedBinary.upload_token,
);
const showConfirmManualUpgradeAction = canConfirmManualUpgrade;
const upgradeLogs = release?.upgrade_logs ?? [];
isOpen,
onClose,
currentVersion,
release,
selectedChannel,
uploadedBinary,
isLoading,
releaseErrorMessage,
manualStatusMessage,
manualErrorMessage,
canUpgrade,
isChecking,
isUpgrading,
isUploadingBinary,
uploadProgress,
isConfirmingManualUpgrade,
onChannelChange,
onCheck,
onUpgrade,
onUploadBinary,
onConfirmManualUpgrade,
}: VersionUpgradeModalProps) {
const upgradeBadge = getUpgradeBadge(release);
const [selectedBinary, setSelectedBinary] = useState<File | null>(null);
const uploadPhaseLabel =
uploadProgress >= 100 ? '已上传,正在服务端校验版本...' : '上传中...';
const selectedChannelLabel =
selectedChannel === 'preview' ? '预览版' : '正式版';
const toggleChannel = () => {
onChannelChange(selectedChannel === 'preview' ? 'stable' : 'preview');
};
const canConfirmManualUpgrade = Boolean(
uploadedBinary?.ready_to_upgrade && uploadedBinary.upload_token,
);
const showConfirmManualUpgradeAction = canConfirmManualUpgrade;
const upgradeLogs = release?.upgrade_logs ?? [];
useEffect(() => {
if (!isOpen) {
setSelectedBinary(null);
}
}, [isOpen]);
useEffect(() => {
if (!isOpen) {
setSelectedBinary(null);
}
}, [isOpen]);
return (
<AppModal
isOpen={isOpen}
onClose={onClose}
title="版本"
description="默认检查正式版更新;你也可以手动检查 preview 发布并选择升级,或上传 Server 二进制确认升级。升级开始后服务会短暂重启。"
size="lg"
>
<div className="space-y-6">
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-2">
<AppCard title="服务端版本">
<div className="flex flex-wrap items-center gap-3">
<p className="text-sm font-medium text-[var(--foreground-primary)]">
{currentVersion || 'unknown'}
</p>
<StatusBadge
label={upgradeBadge.label}
variant={upgradeBadge.variant}
/>
</div>
</AppCard>
<AppCard title="最新版本">
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<p className="text-sm font-medium text-[var(--foreground-primary)]">
{release?.tag_name || '未检查'}
</p>
{canUpgrade ? (
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-2">
<StatusBadge
label={selectedChannelLabel}
variant={
selectedChannel === 'preview' ? 'warning' : 'info'
}
onClick={toggleChannel}
disabled={isChecking || isUpgrading || isUploadingBinary}
/>
</div>
</div>
) : null}
</div>
<SecondaryButton
type="button"
onClick={onCheck}
disabled={isChecking || isUpgrading || isUploadingBinary}
className="w-full md:w-auto"
>
{isChecking ? '检查中...' : '检查'}
</SecondaryButton>
</div>
</AppCard>
</div>
{isLoading ? <LoadingState/> : null}
{!isLoading && releaseErrorMessage ? (
<ErrorState title="版本检查失败" description={releaseErrorMessage}/>
) : null}
{!isLoading && !releaseErrorMessage && !release ? (
<EmptyState
title={`尚未检查${selectedChannelLabel}`}
description={`点击“检查${selectedChannelLabel}”后会在这里展示对应 GitHub Release 信息。`}
/>
) : null}
{!isLoading && !releaseErrorMessage && release ? (
<AppCard
title={`GitHub ${selectedChannelLabel} · ${release.tag_name}`}
description={
release.published_at
? `发布时间:${formatRelativeTime(release.published_at)} · ${formatDateTime(release.published_at)}`
: '未提供发布时间'
}
>
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<StatusBadge
label={release.has_update ? '发现新版本' : '已经是最新版本'}
variant={release.has_update ? 'warning' : 'success'}
/>
{release.prerelease ? (
<StatusBadge label="Preview 发布" variant="warning"/>
) : (
<StatusBadge label="正式发布" variant="info"/>
)}
{!release.upgrade_supported ? (
<StatusBadge
label="当前平台不支持自动升级"
variant="danger"
/>
) : null}
{release.in_progress ? (
<StatusBadge label="升级任务执行中" variant="warning"/>
) : null}
</div>
<div
className="prose prose-sm max-w-none text-[var(--foreground-primary)] [&_a]:text-[var(--brand-primary)]"
dangerouslySetInnerHTML={{
__html: marked.parse(
release.body || '暂无更新说明',
) as string,
}}
/>
<a
href={release.html_url}
target="_blank"
rel="noreferrer"
className="text-sm font-medium text-[var(--brand-primary)] transition hover:opacity-80"
>
查看发布详情
</a>
{canUpgrade ? (
<div className="flex justify-end">
<PrimaryButton
type="button"
onClick={onUpgrade}
disabled={
!release.has_update ||
release.in_progress ||
isUpgrading ||
!release.upgrade_supported ||
isUploadingBinary ||
isConfirmingManualUpgrade
}
>
{isUpgrading
? '升级中...'
: release.in_progress
? '升级中...'
: selectedChannel === 'preview'
? '升级预览版'
: '升级正式版'}
</PrimaryButton>
</div>
) : null}
</div>
</AppCard>
) : null}
{release ? (
<AppCard
title="升级日志"
>
{upgradeLogs.length > 0 ? (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-3">
<StatusBadge
label={
release.upgrade_status === 'failed'
? '升级失败'
: release.upgrade_status === 'succeeded'
? '准备重启'
: release.in_progress
? '升级中'
: '空闲'
}
variant={
release.upgrade_status === 'failed'
? 'danger'
: release.in_progress
? 'warning'
: release.upgrade_status === 'succeeded'
? 'success'
: 'info'
}
/>
</div>
<div className="max-h-72 overflow-y-auto rounded-2xl border border-[var(--border-default)] bg-[#0f172a] px-4 py-3">
{upgradeLogs.map((log, index) => (
<pre
key={`${log.created_at}-${index}`}
className="overflow-x-auto border-b border-white/8 py-2 font-mono text-[12px] leading-6 text-slate-200 last:border-b-0"
>
<span className="text-slate-400">
{formatLogTimestamp(log.created_at)}
</span>
<span className="text-slate-500"> | </span>
<span className="text-cyan-300">
{formatLogLevel(log.level)}
</span>
<span className="text-slate-500"> | </span>
<span className="whitespace-pre-wrap break-all text-slate-100">
{log.message}
</span>
</pre>
))}
</div>
</div>
) : (
<EmptyState
title="暂无升级日志"
/>
)}
</AppCard>
) : null}
{canUpgrade ? (
<AppCard
title="手动升级"
>
<div className="space-y-4">
<ResourceField
label="服务端二进制"
hint="支持上传已编译好的当前平台 Server 可执行文件。"
>
<ResourceInput
type="file"
onChange={(event) => {
const file = event.target.files?.[0] ?? null;
setSelectedBinary(file);
}}
disabled={isUploadingBinary || isConfirmingManualUpgrade}
/>
</ResourceField>
<div className="flex justify-end">
{showConfirmManualUpgradeAction ? (
<PrimaryButton
type="button"
onClick={onConfirmManualUpgrade}
disabled={
!canConfirmManualUpgrade ||
isConfirmingManualUpgrade ||
isUploadingBinary ||
isUpgrading
}
>
{isConfirmingManualUpgrade ? '升级中...' : '升级'}
</PrimaryButton>
) : (
<PrimaryButton
type="button"
onClick={() => {
if (selectedBinary) {
onUploadBinary(selectedBinary);
}
}}
disabled={
!selectedBinary ||
isUploadingBinary ||
isConfirmingManualUpgrade
}
>
{isUploadingBinary
? uploadProgress >= 100
? '服务端校验中...'
: '上传中...'
: '上传并检查'}
</PrimaryButton>
)}
</div>
{isUploadingBinary ? (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs text-[var(--foreground-secondary)]">
<span>{uploadPhaseLabel}</span>
<span>{uploadProgress}%</span>
</div>
<div className="h-2 w-full overflow-hidden rounded-full bg-[var(--border-default)]">
<div
className="h-full rounded-full bg-[var(--brand-primary)] transition-all duration-200"
style={{width: `${uploadProgress}%`}}
/>
</div>
</div>
) : null}
{manualErrorMessage ? (
<ErrorState
title="手动升级检查失败"
description={manualErrorMessage}
/>
) : null}
{!manualErrorMessage && manualStatusMessage ? (
<div
className="rounded-2xl border border-[var(--status-warning-border)] bg-[var(--status-warning-soft)] px-4 py-3 text-sm text-[var(--status-warning-foreground)]">
{manualStatusMessage}
</div>
) : null}
{uploadedBinary ? (
<div
className="space-y-4 rounded-3xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4">
<div className="flex flex-wrap items-center gap-3">
<StatusBadge
label={
uploadedBinary.ready_to_upgrade
? '可确认升级'
: uploadedBinary.has_update
? '待确认'
: '不可升级'
}
variant={
uploadedBinary.ready_to_upgrade ? 'warning' : 'info'
}
/>
{!uploadedBinary.upgrade_supported ? (
<StatusBadge
label="当前版本不支持手动升级"
variant="danger"
/>
) : null}
</div>
<div className="grid gap-4 md:grid-cols-2">
<div>
<p className="text-xs text-[var(--foreground-secondary)]">
文件名
</p>
<p className="mt-1 text-sm font-medium text-[var(--foreground-primary)]">
{uploadedBinary.file_name}
</p>
</div>
<div>
<p className="text-xs text-[var(--foreground-secondary)]">
上传时间
</p>
<p className="mt-1 text-sm font-medium text-[var(--foreground-primary)]">
{uploadedBinary.uploaded_at
? formatDateTime(uploadedBinary.uploaded_at)
: '未知'}
</p>
</div>
<div>
<p className="text-xs text-[var(--foreground-secondary)]">
当前版本
</p>
<p className="mt-1 text-sm font-medium text-[var(--foreground-primary)]">
{uploadedBinary.current_version}
</p>
</div>
<div>
<p className="text-xs text-[var(--foreground-secondary)]">
上传版本
</p>
<p className="mt-1 text-sm font-medium text-[var(--foreground-primary)]">
{uploadedBinary.detected_version}
</p>
</div>
</div>
<p className="text-sm text-[var(--foreground-secondary)]">
{uploadedBinary.comparison_message}
</p>
</div>
) : (
<EmptyState
title="尚未上传升级包"
/>
)}
</div>
</AppCard>
) : null}
return (
<AppModal
isOpen={isOpen}
onClose={onClose}
title="版本"
description="默认检查正式版更新;你也可以手动检查 preview 发布并选择升级,或上传 Server 二进制确认升级。升级开始后服务会短暂重启。"
size="lg"
>
<div className="space-y-6">
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-2">
<AppCard title="服务端版本">
<div className="flex flex-wrap items-center gap-3">
<p className="text-sm font-medium text-[var(--foreground-primary)]">
{currentVersion || 'unknown'}
</p>
<StatusBadge
label={upgradeBadge.label}
variant={upgradeBadge.variant}
/>
</div>
</AppModal>
);
</AppCard>
<AppCard title="最新版本">
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<p className="text-sm font-medium text-[var(--foreground-primary)]">
{release?.tag_name || '未检查'}
</p>
{canUpgrade ? (
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-2">
<StatusBadge
label={selectedChannelLabel}
variant={
selectedChannel === 'preview' ? 'warning' : 'info'
}
onClick={toggleChannel}
disabled={
isChecking || isUpgrading || isUploadingBinary
}
/>
</div>
</div>
) : null}
</div>
<SecondaryButton
type="button"
onClick={onCheck}
disabled={isChecking || isUpgrading || isUploadingBinary}
className="w-full md:w-auto"
>
{isChecking ? '检查中...' : '检查'}
</SecondaryButton>
</div>
</AppCard>
</div>
{isLoading ? <LoadingState /> : null}
{!isLoading && releaseErrorMessage ? (
<ErrorState title="版本检查失败" description={releaseErrorMessage} />
) : null}
{!isLoading && !releaseErrorMessage && !release ? (
<EmptyState
title={`尚未检查${selectedChannelLabel}`}
description={`点击“检查${selectedChannelLabel}”后会在这里展示对应 GitHub Release 信息。`}
/>
) : null}
{!isLoading && !releaseErrorMessage && release ? (
<AppCard
title={`GitHub ${selectedChannelLabel} · ${release.tag_name}`}
description={
release.published_at
? `发布时间:${formatRelativeTime(release.published_at)} · ${formatDateTime(release.published_at)}`
: '未提供发布时间'
}
>
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<StatusBadge
label={release.has_update ? '发现新版本' : '已经是最新版本'}
variant={release.has_update ? 'warning' : 'success'}
/>
{release.prerelease ? (
<StatusBadge label="Preview 发布" variant="warning" />
) : (
<StatusBadge label="正式发布" variant="info" />
)}
{!release.upgrade_supported ? (
<StatusBadge
label="当前平台不支持自动升级"
variant="danger"
/>
) : null}
{release.in_progress ? (
<StatusBadge label="升级任务执行中" variant="warning" />
) : null}
</div>
<div
className="prose prose-sm max-w-none text-[var(--foreground-primary)] [&_a]:text-[var(--brand-primary)]"
dangerouslySetInnerHTML={{
__html: marked.parse(
release.body || '暂无更新说明',
) as string,
}}
/>
<a
href={release.html_url}
target="_blank"
rel="noreferrer"
className="text-sm font-medium text-[var(--brand-primary)] transition hover:opacity-80"
>
查看发布详情
</a>
{canUpgrade ? (
<div className="flex justify-end">
<PrimaryButton
type="button"
onClick={onUpgrade}
disabled={
!release.has_update ||
release.in_progress ||
isUpgrading ||
!release.upgrade_supported ||
isUploadingBinary ||
isConfirmingManualUpgrade
}
>
{isUpgrading
? '升级中...'
: release.in_progress
? '升级中...'
: selectedChannel === 'preview'
? '升级预览版'
: '升级正式版'}
</PrimaryButton>
</div>
) : null}
</div>
</AppCard>
) : null}
{release ? (
<AppCard title="升级日志">
{upgradeLogs.length > 0 ? (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-3">
<StatusBadge
label={
release.upgrade_status === 'failed'
? '升级失败'
: release.upgrade_status === 'succeeded'
? '准备重启'
: release.in_progress
? '升级中'
: '空闲'
}
variant={
release.upgrade_status === 'failed'
? 'danger'
: release.in_progress
? 'warning'
: release.upgrade_status === 'succeeded'
? 'success'
: 'info'
}
/>
</div>
<div className="max-h-72 overflow-y-auto rounded-2xl border border-[var(--border-default)] bg-[#0f172a] px-4 py-3">
{upgradeLogs.map((log, index) => (
<pre
key={`${log.created_at}-${index}`}
className="overflow-x-auto border-b border-white/8 py-2 font-mono text-[12px] leading-6 text-slate-200 last:border-b-0"
>
<span className="text-slate-400">
{formatLogTimestamp(log.created_at)}
</span>
<span className="text-slate-500"> | </span>
<span className="text-cyan-300">
{formatLogLevel(log.level)}
</span>
<span className="text-slate-500"> | </span>
<span className="break-all whitespace-pre-wrap text-slate-100">
{log.message}
</span>
</pre>
))}
</div>
</div>
) : (
<EmptyState title="暂无升级日志" />
)}
</AppCard>
) : null}
{canUpgrade ? (
<AppCard title="手动升级">
<div className="space-y-4">
<ResourceField
label="服务端二进制"
hint="支持上传已编译好的当前平台 Server 可执行文件。"
>
<ResourceInput
type="file"
onChange={(event) => {
const file = event.target.files?.[0] ?? null;
setSelectedBinary(file);
}}
disabled={isUploadingBinary || isConfirmingManualUpgrade}
/>
</ResourceField>
<div className="flex justify-end">
{showConfirmManualUpgradeAction ? (
<PrimaryButton
type="button"
onClick={onConfirmManualUpgrade}
disabled={
!canConfirmManualUpgrade ||
isConfirmingManualUpgrade ||
isUploadingBinary ||
isUpgrading
}
>
{isConfirmingManualUpgrade ? '升级中...' : '升级'}
</PrimaryButton>
) : (
<PrimaryButton
type="button"
onClick={() => {
if (selectedBinary) {
onUploadBinary(selectedBinary);
}
}}
disabled={
!selectedBinary ||
isUploadingBinary ||
isConfirmingManualUpgrade
}
>
{isUploadingBinary
? uploadProgress >= 100
? '服务端校验中...'
: '上传中...'
: '上传并检查'}
</PrimaryButton>
)}
</div>
{isUploadingBinary ? (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs text-[var(--foreground-secondary)]">
<span>{uploadPhaseLabel}</span>
<span>{uploadProgress}%</span>
</div>
<div className="h-2 w-full overflow-hidden rounded-full bg-[var(--border-default)]">
<div
className="h-full rounded-full bg-[var(--brand-primary)] transition-all duration-200"
style={{ width: `${uploadProgress}%` }}
/>
</div>
</div>
) : null}
{manualErrorMessage ? (
<ErrorState
title="手动升级检查失败"
description={manualErrorMessage}
/>
) : null}
{!manualErrorMessage && manualStatusMessage ? (
<div className="rounded-2xl border border-[var(--status-warning-border)] bg-[var(--status-warning-soft)] px-4 py-3 text-sm text-[var(--status-warning-foreground)]">
{manualStatusMessage}
</div>
) : null}
{uploadedBinary ? (
<div className="space-y-4 rounded-3xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4">
<div className="flex flex-wrap items-center gap-3">
<StatusBadge
label={
uploadedBinary.ready_to_upgrade
? '可确认升级'
: uploadedBinary.has_update
? '待确认'
: '不可升级'
}
variant={
uploadedBinary.ready_to_upgrade ? 'warning' : 'info'
}
/>
{!uploadedBinary.upgrade_supported ? (
<StatusBadge
label="当前版本不支持手动升级"
variant="danger"
/>
) : null}
</div>
<div className="grid gap-4 md:grid-cols-2">
<div>
<p className="text-xs text-[var(--foreground-secondary)]">
文件名
</p>
<p className="mt-1 text-sm font-medium text-[var(--foreground-primary)]">
{uploadedBinary.file_name}
</p>
</div>
<div>
<p className="text-xs text-[var(--foreground-secondary)]">
上传时间
</p>
<p className="mt-1 text-sm font-medium text-[var(--foreground-primary)]">
{uploadedBinary.uploaded_at
? formatDateTime(uploadedBinary.uploaded_at)
: '未知'}
</p>
</div>
<div>
<p className="text-xs text-[var(--foreground-secondary)]">
当前版本
</p>
<p className="mt-1 text-sm font-medium text-[var(--foreground-primary)]">
{uploadedBinary.current_version}
</p>
</div>
<div>
<p className="text-xs text-[var(--foreground-secondary)]">
上传版本
</p>
<p className="mt-1 text-sm font-medium text-[var(--foreground-primary)]">
{uploadedBinary.detected_version}
</p>
</div>
</div>
<p className="text-sm text-[var(--foreground-secondary)]">
{uploadedBinary.comparison_message}
</p>
</div>
) : (
<EmptyState title="尚未上传升级包" />
)}
</div>
</AppCard>
) : null}
</div>
</AppModal>
);
}
@@ -12,7 +12,9 @@ export function getUsers(page: number) {
}
export function searchUsers(keyword: string) {
return apiRequest<UserItem[]>(`/user/search?keyword=${encodeURIComponent(keyword)}`);
return apiRequest<UserItem[]>(
`/user/search?keyword=${encodeURIComponent(keyword)}`,
);
}
export function getUser(id: number) {
@@ -40,12 +40,19 @@ const ITEMS_PER_PAGE = 10;
const usersListQueryKey = ['users', 'list'] as const;
const userSchema = z.object({
username: z.string().trim().min(1, '请输入用户名').max(12, '用户名不能超过 12 个字符'),
username: z
.string()
.trim()
.min(1, '请输入用户名')
.max(12, '用户名不能超过 12 个字符'),
display_name: z.string().trim().max(20, '显示名称不能超过 20 个字符'),
password: z
.string()
.max(20, '密码不能超过 20 个字符')
.refine((value) => value.length === 0 || value.length >= 8, '密码至少需要 8 个字符'),
.refine(
(value) => value.length === 0 || value.length >= 8,
'密码至少需要 8 个字符',
),
});
type UserFormValues = z.infer<typeof userSchema>;
@@ -171,7 +178,13 @@ export function UsersPage() {
});
const manageMutation = useMutation({
mutationFn: async ({ username, action }: { username: string; action: ManageUserAction }) => {
mutationFn: async ({
username,
action,
}: {
username: string;
action: ManageUserAction;
}) => {
await manageUser(username, action);
return action;
},
@@ -240,11 +253,17 @@ export function UsersPage() {
enable: '启用',
}[action];
if (action === 'delete' && !window.confirm(`确认删除用户“${targetUser.username}”吗?`)) {
if (
action === 'delete' &&
!window.confirm(`确认删除用户“${targetUser.username}”吗?`)
) {
return;
}
if ((action === 'disable' || action === 'enable') && !window.confirm(`确认${actionText}用户“${targetUser.username}”吗?`)) {
if (
(action === 'disable' || action === 'enable') &&
!window.confirm(`确认${actionText}用户“${targetUser.username}”吗?`)
) {
return;
}
@@ -259,14 +278,14 @@ export function UsersPage() {
if (!isAdmin) {
return (
<div className='space-y-6'>
<div className="space-y-6">
<PageHeader
title='用户管理'
description='阶段 4 已迁移用户管理页面,但当前账户没有管理员权限。'
title="用户管理"
description="阶段 4 已迁移用户管理页面,但当前账户没有管理员权限。"
/>
<EmptyState
title='权限不足'
description='用户列表、编辑与账户管理动作仅对管理员开放,请使用管理员账号登录后继续。'
title="权限不足"
description="用户列表、编辑与账户管理动作仅对管理员开放,请使用管理员账号登录后继续。"
/>
</div>
);
@@ -274,212 +293,317 @@ export function UsersPage() {
return (
<>
<div className='space-y-6'>
<PageHeader
title='用户管理'
description='支持搜索、分页、创建、编辑以及启用、封禁、权限调整等常见账户管理动作。'
action={
<PrimaryButton type='button' onClick={handleCreate}>
新建用户
</PrimaryButton>
<div className="space-y-6">
<PageHeader
title="用户管理"
description="支持搜索、分页、创建、编辑以及启用、封禁、权限调整等常见账户管理动作。"
action={
<PrimaryButton type="button" onClick={handleCreate}>
新建用户
</PrimaryButton>
}
/>
{feedback ? (
<InlineMessage tone={feedback.tone} message={feedback.message} />
) : null}
<AppCard
title="用户列表"
action={
<div className="flex flex-wrap gap-2">
<SecondaryButton
type="button"
onClick={() =>
void queryClient.invalidateQueries({
queryKey: usersListQueryKey,
})
}
>
刷新
</SecondaryButton>
</div>
}
>
<div className="space-y-5">
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div className="flex w-full flex-col gap-3 md:flex-row">
<ResourceInput
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
placeholder="搜索用户 ID、用户名、显示名称或邮箱地址"
className="md:max-w-xl"
/>
<div className="flex flex-wrap gap-2">
<PrimaryButton type="button" onClick={handleSearchSubmit}>
搜索
</PrimaryButton>
<SecondaryButton type="button" onClick={handleResetSearch}>
清空
</SecondaryButton>
</div>
</div>
{searchKeyword.length === 0 ? (
<div className="flex flex-wrap gap-2">
<SecondaryButton
type="button"
onClick={() => setPage((value) => Math.max(value - 1, 0))}
disabled={page === 0 || activeQuery.isLoading}
>
上一页
</SecondaryButton>
<SecondaryButton
type="button"
onClick={() => setPage((value) => value + 1)}
disabled={
activeQuery.isLoading || users.length < ITEMS_PER_PAGE
}
>
下一页
</SecondaryButton>
</div>
) : null}
</div>
{activeQuery.isLoading ? (
<LoadingState />
) : activeQuery.isError ? (
<ErrorState
title="用户列表加载失败"
description={getErrorMessage(activeQuery.error)}
/>
) : users.length === 0 ? (
<EmptyState
title="暂无用户"
description="当前条件下没有可展示的用户记录。"
/>
) : (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-[var(--border-default)] text-left text-sm">
<thead>
<tr className="text-[var(--foreground-secondary)]">
<th className="px-3 py-3 font-medium">用户</th>
<th className="px-3 py-3 font-medium">邮箱</th>
<th className="px-3 py-3 font-medium">角色</th>
<th className="px-3 py-3 font-medium">状态</th>
<th className="px-3 py-3 font-medium">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-[var(--border-default)]">
{users.map((targetUser) => {
const roleMeta = getRoleMeta(targetUser.role);
const statusMeta = getStatusMeta(targetUser.status);
const canManage =
(currentUser?.role ?? 0) > targetUser.role;
return (
<tr key={targetUser.id} className="align-top">
<td className="px-3 py-4">
<div className="space-y-1">
<p className="font-medium text-[var(--foreground-primary)]">
{targetUser.username}
</p>
<p className="text-xs text-[var(--foreground-secondary)]">
显示名称:{targetUser.display_name || '未设置'}
</p>
<p className="text-xs text-[var(--foreground-secondary)]">
ID:{targetUser.id}
</p>
</div>
</td>
<td className="px-3 py-4 text-[var(--foreground-secondary)]">
{targetUser.email || '未绑定'}
</td>
<td className="px-3 py-4">
<StatusBadge
label={roleMeta.label}
variant={roleMeta.variant}
/>
</td>
<td className="px-3 py-4">
<StatusBadge
label={statusMeta.label}
variant={statusMeta.variant}
/>
</td>
<td className="px-3 py-4">
<div className="flex flex-wrap gap-2">
<SecondaryButton
type="button"
onClick={() => handleEdit(targetUser)}
className="px-3 py-2 text-xs"
disabled={!canManage}
>
编辑
</SecondaryButton>
<SecondaryButton
type="button"
onClick={() =>
handleManage(
targetUser,
targetUser.status === 1
? 'disable'
: 'enable',
)
}
className="px-3 py-2 text-xs"
disabled={
!canManage || manageMutation.isPending
}
>
{targetUser.status === 1 ? '禁用' : '启用'}
</SecondaryButton>
<SecondaryButton
type="button"
onClick={() =>
handleManage(
targetUser,
targetUser.role >= 10
? 'demote'
: 'promote',
)
}
className="px-3 py-2 text-xs"
disabled={
!canManage ||
manageMutation.isPending ||
(!isRoot && targetUser.role < 10)
}
>
{targetUser.role >= 10 ? '降级' : '提升'}
</SecondaryButton>
<DangerButton
type="button"
onClick={() =>
handleManage(targetUser, 'delete')
}
className="px-3 py-2 text-xs"
disabled={
!canManage || manageMutation.isPending
}
>
删除
</DangerButton>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
</AppCard>
</div>
<AppModal
isOpen={isEditorOpen}
onClose={handleResetForm}
title={editingUserId ? '编辑用户' : '创建新用户'}
description={
editingUserId
? '可更新用户名、显示名称与密码。留空密码表示不修改。'
: '新建用户默认创建为普通用户。'
}
/>
{feedback ? <InlineMessage tone={feedback.tone} message={feedback.message} /> : null}
<AppCard
title='用户列表'
action={
<div className='flex flex-wrap gap-2'>
footer={
<div className="flex flex-wrap justify-end gap-3">
<SecondaryButton
type='button'
onClick={() => void queryClient.invalidateQueries({ queryKey: usersListQueryKey })}
type="button"
onClick={handleResetForm}
disabled={saveMutation.isPending}
>
刷新
取消
</SecondaryButton>
<PrimaryButton
type="submit"
form="user-editor-form"
disabled={saveMutation.isPending}
>
{saveMutation.isPending
? '保存中...'
: editingUserId
? '保存修改'
: '创建用户'}
</PrimaryButton>
</div>
}
>
<div className='space-y-5'>
<div className='flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between'>
<div className='flex w-full flex-col gap-3 md:flex-row'>
{editingUserId && editingUserQuery.isLoading ? (
<LoadingState />
) : editingUserId && editingUserQuery.isError ? (
<ErrorState
title="用户详情加载失败"
description={getErrorMessage(editingUserQuery.error)}
/>
) : (
<form
id="user-editor-form"
className="space-y-5"
onSubmit={handleSubmit}
>
<ResourceField
label="用户名"
error={form.formState.errors.username?.message}
>
<ResourceInput
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
placeholder='搜索用户 ID、用户名、显示名称或邮箱地址'
className='md:max-w-xl'
placeholder="请输入用户名"
{...form.register('username')}
/>
<div className='flex flex-wrap gap-2'>
<PrimaryButton type='button' onClick={handleSearchSubmit}>
搜索
</PrimaryButton>
<SecondaryButton type='button' onClick={handleResetSearch}>
清空
</SecondaryButton>
</div>
</div>
</ResourceField>
{searchKeyword.length === 0 ? (
<div className='flex flex-wrap gap-2'>
<SecondaryButton type='button' onClick={() => setPage((value) => Math.max(value - 1, 0))} disabled={page === 0 || activeQuery.isLoading}>
上一页
</SecondaryButton>
<SecondaryButton
type='button'
onClick={() => setPage((value) => value + 1)}
disabled={activeQuery.isLoading || users.length < ITEMS_PER_PAGE}
>
下一页
</SecondaryButton>
<ResourceField
label="显示名称"
error={form.formState.errors.display_name?.message}
>
<ResourceInput
placeholder="请输入显示名称"
{...form.register('display_name')}
/>
</ResourceField>
<ResourceField
label={editingUserId ? '新密码' : '密码'}
hint={
editingUserId
? '留空表示保持原密码不变。'
: '密码长度需为 8 到 20 个字符。'
}
error={form.formState.errors.password?.message}
>
<ResourceInput
type="password"
placeholder="请输入密码"
{...form.register('password')}
/>
</ResourceField>
{editingUserId && editingUserQuery.data ? (
<div className="grid gap-4 md:grid-cols-2">
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
绑定邮箱
</p>
<p className="mt-2 text-sm break-all text-[var(--foreground-primary)]">
{editingUserQuery.data.email || '未绑定'}
</p>
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
第三方账号
</p>
<p className="mt-2 text-sm text-[var(--foreground-primary)]">
GitHub:{editingUserQuery.data.github_id || '未绑定'}
</p>
<p className="mt-1 text-sm text-[var(--foreground-primary)]">
微信:{editingUserQuery.data.wechat_id || '未绑定'}
</p>
</div>
</div>
) : null}
</div>
{activeQuery.isLoading ? (
<LoadingState />
) : activeQuery.isError ? (
<ErrorState title='用户列表加载失败' description={getErrorMessage(activeQuery.error)} />
) : users.length === 0 ? (
<EmptyState title='暂无用户' description='当前条件下没有可展示的用户记录。' />
) : (
<div className='overflow-x-auto'>
<table className='min-w-full divide-y divide-[var(--border-default)] text-left text-sm'>
<thead>
<tr className='text-[var(--foreground-secondary)]'>
<th className='px-3 py-3 font-medium'>用户</th>
<th className='px-3 py-3 font-medium'>邮箱</th>
<th className='px-3 py-3 font-medium'>角色</th>
<th className='px-3 py-3 font-medium'>状态</th>
<th className='px-3 py-3 font-medium'>操作</th>
</tr>
</thead>
<tbody className='divide-y divide-[var(--border-default)]'>
{users.map((targetUser) => {
const roleMeta = getRoleMeta(targetUser.role);
const statusMeta = getStatusMeta(targetUser.status);
const canManage = (currentUser?.role ?? 0) > targetUser.role;
return (
<tr key={targetUser.id} className='align-top'>
<td className='px-3 py-4'>
<div className='space-y-1'>
<p className='font-medium text-[var(--foreground-primary)]'>{targetUser.username}</p>
<p className='text-xs text-[var(--foreground-secondary)]'>
显示名称:{targetUser.display_name || '未设置'}
</p>
<p className='text-xs text-[var(--foreground-secondary)]'>ID:{targetUser.id}</p>
</div>
</td>
<td className='px-3 py-4 text-[var(--foreground-secondary)]'>
{targetUser.email || '未绑定'}
</td>
<td className='px-3 py-4'>
<StatusBadge label={roleMeta.label} variant={roleMeta.variant} />
</td>
<td className='px-3 py-4'>
<StatusBadge label={statusMeta.label} variant={statusMeta.variant} />
</td>
<td className='px-3 py-4'>
<div className='flex flex-wrap gap-2'>
<SecondaryButton type='button' onClick={() => handleEdit(targetUser)} className='px-3 py-2 text-xs' disabled={!canManage}>
编辑
</SecondaryButton>
<SecondaryButton
type='button'
onClick={() => handleManage(targetUser, targetUser.status === 1 ? 'disable' : 'enable')}
className='px-3 py-2 text-xs'
disabled={!canManage || manageMutation.isPending}
>
{targetUser.status === 1 ? '禁用' : '启用'}
</SecondaryButton>
<SecondaryButton
type='button'
onClick={() => handleManage(targetUser, targetUser.role >= 10 ? 'demote' : 'promote')}
className='px-3 py-2 text-xs'
disabled={!canManage || manageMutation.isPending || (!isRoot && targetUser.role < 10)}
>
{targetUser.role >= 10 ? '降级' : '提升'}
</SecondaryButton>
<DangerButton
type='button'
onClick={() => handleManage(targetUser, 'delete')}
className='px-3 py-2 text-xs'
disabled={!canManage || manageMutation.isPending}
>
删除
</DangerButton>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
</AppCard>
</div>
<AppModal
isOpen={isEditorOpen}
onClose={handleResetForm}
title={editingUserId ? '编辑用户' : '创建新用户'}
description={editingUserId ? '可更新用户名、显示名称与密码。留空密码表示不修改。' : '新建用户默认创建为普通用户。'}
footer={
<div className='flex flex-wrap justify-end gap-3'>
<SecondaryButton type='button' onClick={handleResetForm} disabled={saveMutation.isPending}>
取消
</SecondaryButton>
<PrimaryButton type='submit' form='user-editor-form' disabled={saveMutation.isPending}>
{saveMutation.isPending ? '保存中...' : editingUserId ? '保存修改' : '创建用户'}
</PrimaryButton>
</div>
}
>
{editingUserId && editingUserQuery.isLoading ? (
<LoadingState />
) : editingUserId && editingUserQuery.isError ? (
<ErrorState title='用户详情加载失败' description={getErrorMessage(editingUserQuery.error)} />
) : (
<form id='user-editor-form' className='space-y-5' onSubmit={handleSubmit}>
<ResourceField label='用户名' error={form.formState.errors.username?.message}>
<ResourceInput placeholder='请输入用户名' {...form.register('username')} />
</ResourceField>
<ResourceField label='显示名称' error={form.formState.errors.display_name?.message}>
<ResourceInput placeholder='请输入显示名称' {...form.register('display_name')} />
</ResourceField>
<ResourceField
label={editingUserId ? '新密码' : '密码'}
hint={editingUserId ? '留空表示保持原密码不变。' : '密码长度需为 8 到 20 个字符。'}
error={form.formState.errors.password?.message}
>
<ResourceInput type='password' placeholder='请输入密码' {...form.register('password')} />
</ResourceField>
{editingUserId && editingUserQuery.data ? (
<div className='grid gap-4 md:grid-cols-2'>
<div className='rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4'>
<p className='text-xs uppercase tracking-[0.2em] text-[var(--foreground-muted)]'>绑定邮箱</p>
<p className='mt-2 break-all text-sm text-[var(--foreground-primary)]'>
{editingUserQuery.data.email || '未绑定'}
</p>
</div>
<div className='rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4'>
<p className='text-xs uppercase tracking-[0.2em] text-[var(--foreground-muted)]'>第三方账号</p>
<p className='mt-2 text-sm text-[var(--foreground-primary)]'>
GitHub:{editingUserQuery.data.github_id || '未绑定'}
</p>
<p className='mt-1 text-sm text-[var(--foreground-primary)]'>
微信:{editingUserQuery.data.wechat_id || '未绑定'}
</p>
</div>
</div>
) : null}
</form>
)}
</AppModal>
</form>
)}
</AppModal>
</>
);
}
+6 -1
View File
@@ -16,7 +16,12 @@ export interface UserMutationPayload {
password: string;
}
export type ManageUserAction = 'promote' | 'demote' | 'delete' | 'disable' | 'enable';
export type ManageUserAction =
| 'promote'
| 'demote'
| 'delete'
| 'disable'
| 'enable';
export interface ManageUserResult {
role: number;
File diff suppressed because it is too large Load Diff
@@ -13,7 +13,10 @@ import {
getTlsCertificate,
getTlsCertificateContent,
} from '@/features/tls-certificates/api/tls-certificates';
import { getCertificateStatus, getErrorMessage } from '@/features/websites/utils';
import {
getCertificateStatus,
getErrorMessage,
} from '@/features/websites/utils';
import {
CodeBlock,
DangerButton,
@@ -81,11 +84,7 @@ export function CertificateDetailModal({
<SecondaryButton type="button" onClick={onClose}>
关闭
</SecondaryButton>
<PrimaryButton
type="button"
onClick={onEdit}
disabled={!certificate}
>
<PrimaryButton type="button" onClick={onEdit} disabled={!certificate}>
编辑证书
</PrimaryButton>
<DangerButton
@@ -112,15 +111,12 @@ export function CertificateDetailModal({
)}
/>
) : !certificate || !content ? (
<EmptyState
title="证书不存在"
description="当前证书可能已被删除。"
/>
<EmptyState title="证书不存在" description="当前证书可能已被删除。" />
) : (
<div className="space-y-6">
<div className="grid gap-4 md:grid-cols-2">
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs uppercase tracking-[0.18em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
证书名称
</p>
<p className="mt-2 text-sm text-[var(--foreground-primary)]">
@@ -128,7 +124,7 @@ export function CertificateDetailModal({
</p>
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs uppercase tracking-[0.18em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
状态
</p>
<div className="mt-2">
@@ -138,7 +134,7 @@ export function CertificateDetailModal({
</div>
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs uppercase tracking-[0.18em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
生效时间
</p>
<p className="mt-2 text-sm text-[var(--foreground-primary)]">
@@ -146,7 +142,7 @@ export function CertificateDetailModal({
</p>
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs uppercase tracking-[0.18em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
到期时间
</p>
<p className="mt-2 text-sm text-[var(--foreground-primary)]">
@@ -156,7 +152,7 @@ export function CertificateDetailModal({
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs uppercase tracking-[0.18em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
备注
</p>
<p className="mt-2 text-sm leading-6 text-[var(--foreground-primary)]">
@@ -180,7 +176,7 @@ export function CertificateDetailModal({
复制
</SecondaryButton>
</div>
<CodeBlock className="max-h-56 overflow-y-auto whitespace-pre-wrap break-all">
<CodeBlock className="max-h-56 overflow-y-auto break-all whitespace-pre-wrap">
{content.cert_pem}
</CodeBlock>
</div>
@@ -199,7 +195,7 @@ export function CertificateDetailModal({
复制
</SecondaryButton>
</div>
<CodeBlock className="max-h-56 overflow-y-auto whitespace-pre-wrap break-all">
<CodeBlock className="max-h-56 overflow-y-auto break-all whitespace-pre-wrap">
{content.key_pem}
</CodeBlock>
</div>
@@ -52,8 +52,9 @@ export function CertificateImportModal({
const queryClient = useQueryClient();
const [importMode, setImportMode] = useState<'manual' | 'file'>('manual');
const [feedback, setFeedback] = useState<FeedbackState | null>(null);
const [fileForm, setFileForm] =
useState<FileImportFormValues>(defaultFileImportValues);
const [fileForm, setFileForm] = useState<FileImportFormValues>(
defaultFileImportValues,
);
const [certFile, setCertFile] = useState<File | null>(null);
const [keyFile, setKeyFile] = useState<File | null>(null);
const [fileInputNonce, setFileInputNonce] = useState(0);
@@ -280,9 +281,7 @@ export function CertificateImportModal({
<ResourceField
label="私钥文件"
hint={
keyFile
? `已选择:${keyFile.name}`
: '请选择 KEY/PEM 文件'
keyFile ? `已选择:${keyFile.name}` : '请选择 KEY/PEM 文件'
}
>
<ResourceInput
@@ -143,13 +143,16 @@ export function WebsiteDetailPage({ websiteId }: { websiteId: string }) {
enabled: Boolean(wafRouteID),
});
const wafMutation = useMutation({
mutationFn: (ids: number[]) => replaceWAFSiteRuleGroups(wafRouteID ?? 0, ids),
mutationFn: (ids: number[]) =>
replaceWAFSiteRuleGroups(wafRouteID ?? 0, ids),
onSuccess: async (view) => {
setWafSelectedIDs(view.applied_ids);
setFeedback({ tone: 'success', message: '网站 WAF 规则组已更新。' });
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['waf'] }),
queryClient.invalidateQueries({ queryKey: ['config-versions', 'diff'] }),
queryClient.invalidateQueries({
queryKey: ['config-versions', 'diff'],
}),
]);
},
onError: (error) => {
@@ -90,7 +90,7 @@ export function WebsiteEditorModal({
});
const currentCertificate = watchedCertId
? certificates.find((item) => item.id === Number(watchedCertId)) ?? null
? (certificates.find((item) => item.id === Number(watchedCertId)) ?? null)
: null;
const handleSubmit = form.handleSubmit((values) => {
@@ -215,7 +215,7 @@ export function WebsiteEditorModal({
<div className="grid gap-4 md:grid-cols-3">
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs uppercase tracking-[0.2em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
当前域名
</p>
<p className="mt-2 text-sm text-[var(--foreground-primary)]">
@@ -223,7 +223,7 @@ export function WebsiteEditorModal({
</p>
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs uppercase tracking-[0.2em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
匹配类型
</p>
<div className="mt-2">
@@ -235,12 +235,14 @@ export function WebsiteEditorModal({
</div>
</div>
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-4">
<p className="text-xs uppercase tracking-[0.2em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.2em] text-[var(--foreground-muted)] uppercase">
当前证书
</p>
<div className="mt-2">
<StatusBadge
label={currentCertificate ? currentCertificate.name : '未绑定证书'}
label={
currentCertificate ? currentCertificate.name : '未绑定证书'
}
variant={currentCertificate ? 'success' : 'warning'}
/>
</div>
@@ -136,7 +136,7 @@ export function WebsitesPage() {
<div className="grid gap-4 lg:grid-cols-2">
{domains.map((domain) => {
const certificate = domain.cert_id
? certificateMap.get(domain.cert_id) ?? null
? (certificateMap.get(domain.cert_id) ?? null)
: null;
const matchType = getMatchTypeMeta(domain.domain);
@@ -168,7 +168,7 @@ export function WebsitesPage() {
<div className="grid gap-3 md:grid-cols-1">
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-panel)] px-4 py-3">
<p className="text-xs uppercase tracking-[0.18em] text-[var(--foreground-muted)]">
<p className="text-xs tracking-[0.18em] text-[var(--foreground-muted)] uppercase">
绑定证书
</p>
<p className="mt-2 text-sm text-[var(--foreground-primary)]">
@@ -97,4 +97,3 @@ export const defaultAcmeApplyValues: AcmeApplyFormValues = {
dns2: '',
remark: '',
};
+3 -1
View File
@@ -6,7 +6,9 @@ export const themeModes = ['light', 'dark', 'system'] as const;
export type ThemeMode = (typeof themeModes)[number];
export type ResolvedTheme = Exclude<ThemeMode, 'system'>;
export function isThemeMode(value: string | null | undefined): value is ThemeMode {
export function isThemeMode(
value: string | null | undefined,
): value is ThemeMode {
return themeModes.includes(value as ThemeMode);
}
+3 -3
View File
@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
return twMerge(clsx(inputs));
}
+6 -2
View File
@@ -17,8 +17,12 @@ function toDate(value: string | Date | null | undefined) {
return null;
}
const normalizedValue = typeof value === 'string' ? value.replace(' ', 'T') : value;
const date = normalizedValue instanceof Date ? normalizedValue : new Date(normalizedValue);
const normalizedValue =
typeof value === 'string' ? value.replace(' ', 'T') : value;
const date =
normalizedValue instanceof Date
? normalizedValue
: new Date(normalizedValue);
return Number.isNaN(date.getTime()) ? null : date;
}
+12 -2
View File
@@ -1,5 +1,6 @@
const devBackendUrl =
process.env.NEXT_DEV_BACKEND_URL?.replace(/\/+$/, '') || 'http://127.0.0.1:3000';
process.env.NEXT_DEV_BACKEND_URL?.replace(/\/+$/, '') ||
'http://127.0.0.1:3000';
const enableDevProxy = process.env.NEXT_DEV_PROXY === 'true';
export default function createNextConfig() {
@@ -10,7 +11,16 @@ export default function createNextConfig() {
unoptimized: true,
},
eslint: {
dirs: ['app', 'components', 'features', 'hooks', 'lib', 'store', 'tests', 'types'],
dirs: [
'app',
'components',
'features',
'hooks',
'lib',
'store',
'tests',
'types',
],
},
};
+4761 -1626
View File
File diff suppressed because it is too large Load Diff
+25 -9
View File
@@ -6,7 +6,10 @@ import next from 'next';
const port = Number.parseInt(process.env.PORT ?? '3001', 10);
const hostname = process.env.HOSTNAME || '127.0.0.1';
const backendBaseUrl = new URL(
(process.env.NEXT_DEV_BACKEND_URL || 'http://127.0.0.1:3000').replace(/\/+$/, ''),
(process.env.NEXT_DEV_BACKEND_URL || 'http://127.0.0.1:3000').replace(
/\/+$/,
'',
),
);
const app = next({
@@ -55,11 +58,19 @@ function writeProxyError(res, error) {
function proxyHttpRequest(req, res) {
const targetUrl = new URL(req.url || '/', backendBaseUrl);
const requestImpl = targetUrl.protocol === 'https:' ? https.request : http.request;
const proxyReq = requestImpl(createProxyRequestOptions(req, targetUrl), (proxyRes) => {
res.writeHead(proxyRes.statusCode || 502, proxyRes.statusMessage, proxyRes.headers);
proxyRes.pipe(res);
});
const requestImpl =
targetUrl.protocol === 'https:' ? https.request : http.request;
const proxyReq = requestImpl(
createProxyRequestOptions(req, targetUrl),
(proxyRes) => {
res.writeHead(
proxyRes.statusCode || 502,
proxyRes.statusMessage,
proxyRes.headers,
);
proxyRes.pipe(res);
},
);
proxyReq.on('error', (error) => {
if (!res.headersSent) {
@@ -92,7 +103,8 @@ function formatUpgradeResponseHeaders(statusCode, statusMessage, headers) {
function proxyWebSocketUpgrade(req, socket, head) {
const targetUrl = new URL(req.url || '/', backendBaseUrl);
const requestImpl = targetUrl.protocol === 'https:' ? https.request : http.request;
const requestImpl =
targetUrl.protocol === 'https:' ? https.request : http.request;
const proxyReq = requestImpl(createProxyRequestOptions(req, targetUrl));
proxyReq.on('upgrade', (proxyRes, proxySocket, proxyHead) => {
@@ -156,6 +168,10 @@ server.on('upgrade', (req, socket, head) => {
});
server.listen(port, hostname, () => {
console.log(`OpenFlare web dev server listening on http://${hostname}:${port}`);
console.log(`Proxying /api/* and websocket upgrades to ${backendBaseUrl.href}`);
console.log(
`OpenFlare web dev server listening on http://${hostname}:${port}`,
);
console.log(
`Proxying /api/* and websocket upgrades to ${backendBaseUrl.href}`,
);
});
@@ -180,7 +180,10 @@ describe('Proxy route website pages', () => {
primary_domain: payload.domain,
domain_count: payload.domains.length,
origin_url: payload.origin_url,
upstreams: JSON.stringify([payload.origin_url, ...payload.upstreams]),
upstreams: JSON.stringify([
payload.origin_url,
...payload.upstreams,
]),
upstream_list: [payload.origin_url, ...payload.upstreams],
enabled: payload.enabled,
enable_https: payload.enable_https,
@@ -242,7 +245,9 @@ describe('Proxy route website pages', () => {
JSON.stringify({
success: true,
message: '',
data: [{ id: 1, domain: '*.example.com', cert_id: 1, enabled: true }],
data: [
{ id: 1, domain: '*.example.com', cert_id: 1, enabled: true },
],
}),
),
);
@@ -377,7 +382,9 @@ describe('Proxy route website pages', () => {
JSON.stringify({
success: true,
message: '',
data: [{ id: 1, domain: '*.example.com', cert_id: 1, enabled: true }],
data: [
{ id: 1, domain: '*.example.com', cert_id: 1, enabled: true },
],
}),
),
);