feat: 优化首页系统状态显示并移除自定义 API 地址设置

This commit is contained in:
xiaozhou233 committed 2026-08-11 01:49:16 +08:00
1 parent 7309520063
commit 63efceceb4
3 files changed
+125 -200

No files matched your search

+2 -27
View File
@@ -1,38 +1,13 @@
const STORAGE_KEY = 'workstation.apiBaseUrl'
function envApiBaseUrl(): string {
return import.meta.env.VITE_API_BASE_URL ?? ''
}
export function normalizeApiBaseUrl(url: string): string {
function normalizeApiBaseUrl(url: string): string {
return url.trim().replace(/\/+$/, '')
}
export function getApiBaseUrl(): string {
try {
const saved = localStorage.getItem(STORAGE_KEY)
if (saved !== null && saved !== '') return normalizeApiBaseUrl(saved)
} catch {
// localStorage 不可用时退回环境变量
}
return envApiBaseUrl()
}
export function setApiBaseUrl(url: string): void {
const normalized = normalizeApiBaseUrl(url)
try {
if (normalized === '') {
localStorage.removeItem(STORAGE_KEY)
} else {
localStorage.setItem(STORAGE_KEY, normalized)
}
} catch {
// 忽略写入失败
}
}
export function resolveApiUrl(path: string): string {
const base = normalizeApiBaseUrl(getApiBaseUrl())
const base = normalizeApiBaseUrl(envApiBaseUrl())
return `${base}${path}`
}
+119 -84
View File
@@ -9,6 +9,8 @@ interface CpuStats {
}
interface MemoryStats {
total: number
used: number
usagePercent: number
}
@@ -26,6 +28,8 @@ interface SystemStats {
os: OsStats
}
const REFRESH_INTERVAL = 5000
function formatUptime(seconds: number) {
const d = Math.floor(seconds / 86400)
const h = Math.floor((seconds % 86400) / 3600)
@@ -35,6 +39,14 @@ function formatUptime(seconds: number) {
return `${m} 分钟`
}
function formatBytes(bytes: number) {
if (!bytes || bytes <= 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))
const value = bytes / 1024 ** i
return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[i]}`
}
function UsageBar({ percent }: { percent: number }) {
return (
<div className="mt-3 h-2 w-full overflow-hidden rounded-full bg-slate-100">
@@ -78,15 +90,31 @@ const iconProps = {
export default function Home() {
const [stats, setStats] = useState<SystemStats | null>(null)
const [error, setError] = useState(false)
const [lastUpdated, setLastUpdated] = useState<Date | null>(null)
useEffect(() => {
apiFetch('/api/system/stats')
.then((res) => {
let cancelled = false
async function load() {
try {
const res = await apiFetch('/api/system/stats')
if (!res.ok) throw new Error('Failed to fetch stats')
return res.json()
})
.then((data: SystemStats) => setStats(data))
.catch(() => setError(true))
const data: SystemStats = await res.json()
if (cancelled) return
setStats(data)
setError(false)
setLastUpdated(new Date())
} catch {
if (!cancelled) setError(true)
}
}
load()
const timer = setInterval(load, REFRESH_INTERVAL)
return () => {
cancelled = true
clearInterval(timer)
}
}, [])
return (
@@ -107,92 +135,99 @@ export default function Home() {
<section className="border-t border-slate-200 py-20">
<div className="mx-auto max-w-6xl px-6">
<h2 className="text-center text-2xl font-semibold text-slate-900">系统状态</h2>
<p className="mt-1 text-center text-sm text-slate-500">
{error
? '无法获取系统信息,请确认后端服务已启动,或在「设置」中配置服务器 API 地址'
: stats
? '实时运行状态一览'
: '正在获取系统信息…'}
</p>
<div className="flex flex-wrap items-end justify-between gap-4">
<div>
<h2 className="text-2xl font-semibold text-slate-900">系统状态</h2>
<p className="mt-1 text-sm text-slate-500">
{error
? '无法获取系统信息,请确认后端服务已启动'
: stats
? `实时运行状态一览,每 ${REFRESH_INTERVAL / 1000} 秒自动刷新`
: '正在获取系统信息…'}
</p>
</div>
{stats && lastUpdated && (
<p className="text-xs text-slate-400">
最后更新于 {lastUpdated.toLocaleTimeString()}
</p>
)}
</div>
<div className="mt-10 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
{stats ? (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4 lg:divide-x lg:divide-slate-100">
<StatItem
icon={
<svg {...iconProps}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0V12a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 12V5.25"
/>
</svg>
}
label="CPU 占用率"
>
<span className="text-2xl font-bold text-slate-900">
{stats.cpu.usagePercent}%
</span>
<UsageBar percent={stats.cpu.usagePercent} />
</StatItem>
<StatItem
icon={
<svg {...iconProps}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M8.25 3v1.5M4.5 8.25H3m18 0h-1.5M4.5 12H3m18 0h-1.5m-15 3.75H3m18 0h-1.5M8.25 19.5V21M12 3v1.5m0 15V21m3.75-18v1.5m0 15V21m-9-1.5h10.5a2.25 2.25 0 002.25-2.25V6.75a2.25 2.25 0 00-2.25-2.25H6.75A2.25 2.25 0 004.5 6.75v10.5a2.25 2.25 0 002.25 2.25z"
/>
</svg>
}
label="内存占用率"
>
<span className="text-2xl font-bold text-slate-900">
{stats.memory.usagePercent}%
</span>
<UsageBar percent={stats.memory.usagePercent} />
</StatItem>
<StatItem
icon={
<svg {...iconProps}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M8.25 3v1.5M4.5 8.25H3m18 0h-1.5M4.5 12H3m18 0h-1.5m-15 3.75H3m18 0h-1.5M8.25 19.5V21M12 3v1.5m0 15V21m3.75-18v1.5m0 15V21m-9-1.5h10.5a2.25 2.25 0 002.25-2.25V6.75a2.25 2.25 0 00-2.25-2.25H6.75A2.25 2.25 0 004.5 6.75v10.5a2.25 2.25 0 002.25 2.25z"
/>
</svg>
}
label="系统与运行环境"
>
<p className="text-sm text-slate-600">
<div>
<div className="flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-slate-100 pb-4">
<span className="text-sm text-slate-500">
{stats.os.name} {stats.os.version} · {stats.os.arch}
</p>
<p className="text-sm text-slate-600">Java {stats.os.javaVersion}</p>
</StatItem>
<StatItem
icon={
<svg {...iconProps}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
}
label="开机时间"
>
<span className="text-2xl font-bold text-slate-900">
{formatUptime(stats.os.uptimeSeconds)}
</span>
</StatItem>
<span className="text-sm text-slate-500">Java {stats.os.javaVersion}</span>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 lg:divide-x lg:divide-slate-100">
<StatItem
icon={
<svg {...iconProps}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25m18 0A2.25 2.25 0 0018.75 3H5.25A2.25 2.25 0 003 5.25m18 0V12a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 12V5.25"
/>
</svg>
}
label="CPU 占用率"
>
<span className="text-2xl font-bold text-slate-900">
{stats.cpu.usagePercent}%
</span>
<UsageBar percent={stats.cpu.usagePercent} />
<p className="mt-2 text-xs text-slate-500">
{stats.cpu.model || '未知型号'} · {stats.cpu.cores} 核
</p>
</StatItem>
<StatItem
icon={
<svg {...iconProps}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M8.25 3v1.5M4.5 8.25H3m18 0h-1.5M4.5 12H3m18 0h-1.5m-15 3.75H3m18 0h-1.5M8.25 19.5V21M12 3v1.5m0 15V21m3.75-18v1.5m0 15V21m-9-1.5h10.5a2.25 2.25 0 002.25-2.25V6.75a2.25 2.25 0 00-2.25-2.25H6.75A2.25 2.25 0 004.5 6.75v10.5a2.25 2.25 0 002.25 2.25z"
/>
</svg>
}
label="内存占用率"
>
<span className="text-2xl font-bold text-slate-900">
{stats.memory.usagePercent}%
</span>
<UsageBar percent={stats.memory.usagePercent} />
<p className="mt-2 text-xs text-slate-500">
{formatBytes(stats.memory.used)} / {formatBytes(stats.memory.total)}
</p>
</StatItem>
<StatItem
icon={
<svg {...iconProps}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
}
label="开机时间"
>
<span className="text-2xl font-bold text-slate-900">
{formatUptime(stats.os.uptimeSeconds)}
</span>
<p className="mt-2 text-xs text-slate-500">持续运行</p>
</StatItem>
</div>
</div>
) : (
<p className="py-16 text-center text-sm text-slate-400">
{error ? '无法获取系统信息,请确认后端服务已启动,或在「设置」中配置服务器 API 地址' : '正在获取系统信息…'}
{error ? '无法获取系统信息,请确认后端服务已启动' : '正在获取系统信息…'}
</p>
)}
</div>
+4 -89
View File
@@ -1,99 +1,14 @@
import { useState } from 'react'
import { getApiBaseUrl, normalizeApiBaseUrl, resolveApiUrl, setApiBaseUrl } from '../lib/api'
type TestStatus = 'idle' | 'testing' | 'ok' | 'fail'
export default function Settings() {
const [value, setValue] = useState(getApiBaseUrl())
const [saved, setSaved] = useState(getApiBaseUrl())
const [status, setStatus] = useState<TestStatus>('idle')
const [message, setMessage] = useState('')
const dirty = normalizeApiBaseUrl(value) !== saved
function handleSave() {
setApiBaseUrl(value)
setSaved(getApiBaseUrl())
setStatus('idle')
setMessage('')
}
async function handleTest() {
setStatus('testing')
setMessage('')
const base = normalizeApiBaseUrl(value)
const oldBase = getApiBaseUrl()
if (base !== oldBase) setApiBaseUrl(base)
try {
const res = await fetch(resolveApiUrl('/api/system/stats'))
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
const label = (data.os?.name as string | undefined) ?? '后端'
setStatus('ok')
setMessage(`${label} 连接正常`)
} catch {
setStatus('fail')
setMessage('连接失败,请检查地址是否正确以及后端服务是否已启动')
} finally {
if (base !== oldBase) setApiBaseUrl(oldBase)
}
}
return (
<section className="mx-auto min-h-[70vh] max-w-3xl px-6 py-12">
<h1 className="text-2xl font-semibold text-slate-900">设置</h1>
<p className="mt-1 text-sm text-slate-500">系统偏好与账号配置</p>
<div className="mt-8 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h2 className="text-base font-semibold text-slate-900">服务器 API 地址</h2>
<p className="mt-1 text-sm text-slate-500">
配置前端连接后端服务的 API 基础地址,留空则使用环境变量或本地代理
<div className="mt-8 flex flex-col items-center justify-center rounded-xl border border-dashed border-slate-300 bg-white py-24 text-center">
<div className="grid size-16 place-items-center rounded-2xl bg-indigo-50 text-2xl">⚙️</div>
<p className="mt-4 rounded-md bg-slate-100 px-3 py-1 text-sm text-slate-500">
暂无设置项
</p>
<label className="mt-5 block">
<span className="text-sm font-medium text-slate-700">API 基础地址</span>
<input
type="url"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="例如 http://your-server:9018,留空表示使用默认"
spellCheck={false}
className="mt-2 w-full rounded-md border border-slate-300 px-3 py-2 text-sm text-slate-900 outline-none transition-colors focus:border-indigo-500 focus:ring-2 focus:ring-indigo-100"
/>
</label>
<p className="mt-2 text-xs text-slate-400">
当前生效地址:{saved === '' ? '默认(本地代理)' : saved}
</p>
{message && (
<p
className={`mt-3 text-sm ${
status === 'ok' ? 'text-emerald-600' : status === 'fail' ? 'text-red-600' : 'text-slate-500'
}`}
>
{message}
</p>
)}
<div className="mt-6 flex flex-wrap gap-3">
<button
type="button"
onClick={handleTest}
disabled={status === 'testing'}
className="rounded-md border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60"
>
{status === 'testing' ? '正在测试…' : '测试连接'}
</button>
<button
type="button"
onClick={handleSave}
disabled={!dirty}
className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-50"
>
保存
</button>
</div>
</div>
</section>
)