feat: 品牌统一 LokiStack + 全站中英 i18n + 用户批量删除 + 主题定时切换与浅色侧栏

- 品牌: Go 模块/数据文件/二进制/构建部署资产全部 opsx→lokistack;前端 localStorage 命名空间迁移(读旧写新,含按用户 id 前缀迁移);修复 nginx upstream 与 Makefile 引用已改名服务的断裂
- i18n: react-i18next 落地,common + 11 个页面域命名空间全站中英(菜单/顶栏/登录/列表页/表单/确认弹窗/状态徽章);设置页语言即时切换;修复词典自注册导致的循环导入白屏
- 用户管理: 批量删除(POST /users/batch-delete,不删自己/最后管理员,部分失败不阻断)+ 行复选/全选/批量工具条
- 主题: 浅色侧栏(中性灰激活态)、四态模式(浅色/深色/跟随系统/定时切换,按时区判定)、顶栏太阳月亮二态、设置页紧凑分段选择器
- UI: 登录记住用户名、CardActionButton 统一五页卡片操作钮、shadcn Badge 替换手写徽章、语义色修正
- 清理: 移除主机 Web 终端(前后端)、k8s-helm/Helm 遗留代码与字段、README 重写精简
- 修复: 侧栏与日志告警 order 重复、路由标题 i18n key 未翻译、词典双逗号等
This commit is contained in:
opsx committed 2026-10-27 17:11:38 +08:00
1 parent 02d1bd87a7
commit f3733f0bfc
201 files changed
+5438 -2388

No files matched your search

@@ -1,15 +1,15 @@
import { memo } from 'react'
import { Monitor, RefreshCw, Trash2, Eye, Terminal, Pencil } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Monitor, RefreshCw, Trash2, Eye, Pencil } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { StatusBadge } from '@/components/StatusBadge'
import { ResourceCard } from '@/components/ResourceCard'
import { CardActionButton } from '@/components/CardActionButton'
import type { Host } from '@/types'
interface HostCardProps {
host: Host
validating: number | null
onViewInfo: (h: Host) => void
onOpenTerminal: (h: Host) => void
onValidate: (id: number) => void
onDelete: (h: Host) => void
onEdit: (h: Host) => void
@@ -17,37 +17,33 @@ interface HostCardProps {
/** 主机卡片 — 统一 ResourceCard 样式 */
export const HostCard = memo(function HostCard({
host, validating, onViewInfo, onOpenTerminal, onValidate, onDelete, onEdit,
host, validating, onViewInfo, onValidate, onDelete, onEdit,
}: HostCardProps) {
const { t } = useTranslation('hosts')
return (
<ResourceCard
icon={Monitor}
iconClassName="text-purple-500"
iconClassName="text-info"
title={host.name}
badges={<StatusBadge status={host.status} />}
fields={[
{ label: '地址', value: `${host.hostIP}:${host.port}` },
{ label: '用户', value: host.user },
{ label: '认证', value: host.authType === 'key' ? 'SSH 密钥' : '密码' },
{ label: '系统', value: `${host.os || '未知'} / ${host.arch || '未知'}` },
{ label: t('fields.address'), value: `${host.hostIP}:${host.port}` },
{ label: t('fields.user'), value: host.user },
{ label: t('fields.auth'), value: host.authType === 'key' ? t('fields.authKey') : t('fields.authPassword') },
{ label: t('fields.os'), value: `${host.os || t('fields.unknown')} / ${host.arch || t('fields.unknown')}` },
]}
actions={
<>
<Button variant="outline" size="sm" aria-label={'编辑主机 ' + host.name} onClick={() => onEdit(host)}>
<Pencil className="size-3.5" />
</Button>
<Button variant="outline" size="sm" className="flex-1 text-xs" onClick={() => onViewInfo(host)}>
<Eye className="size-3 mr-1" />详情
</Button>
<Button variant="outline" size="sm" className="flex-1 text-xs" onClick={() => onOpenTerminal(host)}>
<Terminal className="size-3 mr-1" />终端
</Button>
<Button variant="outline" size="sm" aria-label={`验证主机 ${host.name}`} disabled={validating === host.id} onClick={() => onValidate(host.id)}>
<RefreshCw className={`size-3 ${validating === host.id ? 'animate-spin' : ''}`} />
</Button>
<Button variant="outline" size="sm" aria-label={`删除主机 ${host.name}`} className="text-destructive hover:text-destructive hover:bg-destructive/10" onClick={() => onDelete(host)}>
<Trash2 className="size-3.5" />
</Button>
<CardActionButton icon={Pencil} ariaLabel={t('actions.editAria', { name: host.name })} onClick={() => onEdit(host)} />
<CardActionButton icon={Eye} label={t('actions.detail')} onClick={() => onViewInfo(host)} />
<CardActionButton
icon={RefreshCw}
ariaLabel={t('actions.validateAria', { name: host.name })}
spinning={validating === host.id}
disabled={validating === host.id}
onClick={() => onValidate(host.id)}
/>
<CardActionButton icon={Trash2} ariaLabel={t('actions.deleteAria', { name: host.name })} destructive onClick={() => onDelete(host)} />
</>
}
/>
@@ -1,5 +1,6 @@
import { memo, useEffect, useState } from 'react'
import { Monitor } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import {
Dialog,
DialogContent,
@@ -25,6 +26,7 @@ export const HostDetailDialog = memo(function HostDetailDialog({
host,
onClose,
}: HostDetailDialogProps) {
const { t } = useTranslation('hosts')
const [info, setInfo] = useState<HostInfo | null>(null)
const [error, setError] = useState<string | null>(null)
@@ -37,19 +39,19 @@ export const HostDetailDialog = memo(function HostDetailDialog({
if (!cancelled) setInfo(data)
})
.catch((err) => {
if (!cancelled) setError(err instanceof Error ? err.message : '加载主机详情失败')
if (!cancelled) setError(err instanceof Error ? err.message : t('detail.loadError'))
})
return () => {
cancelled = true
}
}, [host])
}, [host, t])
return (
<Dialog open={host !== null} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Monitor className="w-5 h-5 text-purple-500" />
<Monitor className="w-5 h-5 text-info" />
{host?.name}
</DialogTitle>
</DialogHeader>
@@ -68,20 +70,21 @@ export const HostDetailDialog = memo(function HostDetailDialog({
/** 主机详情内容:资源使用率 + 基本信息 */
const HostDetail = memo(function HostDetail({ info }: { info: HostInfo }) {
const { t } = useTranslation('hosts')
return (
<div className="space-y-5">
{/* 资源使用率 */}
<div>
<h4 className="text-sm font-semibold mb-3">资源使用率</h4>
<h4 className="text-sm font-semibold mb-3">{t('detail.usage')}</h4>
<div className="space-y-3">
<UsageBar label="CPU" value={info.cpuUsage} />
<UsageBar
label="内存"
label={t('detail.memory')}
value={info.memUsage}
detail={`${info.memUsed} / ${info.memTotal}`}
/>
<UsageBar
label="磁盘"
label={t('detail.disk')}
value={info.diskUsage}
detail={`${info.diskUsed} / ${info.diskTotal}`}
/>
@@ -90,14 +93,14 @@ const HostDetail = memo(function HostDetail({ info }: { info: HostInfo }) {
{/* 基本信息 */}
<div>
<h4 className="text-sm font-semibold mb-3">基本信息</h4>
<h4 className="text-sm font-semibold mb-3">{t('detail.basicInfo')}</h4>
<div className="grid grid-cols-2 gap-3">
<InfoCard label="主机名" value={info.hostname || '未知'} />
<InfoCard label="系统" value={`${info.os || '未知'} ${info.version}`} />
<InfoCard label="架构" value={info.arch || '未知'} />
<InfoCard label="内核" value={info.kernel || '未知'} />
<InfoCard label="CPU 核数" value={info.cpu || '未知'} />
<InfoCard label="运行时长" value={info.uptime || '未知'} />
<InfoCard label={t('detail.hostname')} value={info.hostname || t('detail.unknown')} />
<InfoCard label={t('detail.os')} value={`${info.os || t('detail.unknown')} ${info.version}`} />
<InfoCard label={t('detail.arch')} value={info.arch || t('detail.unknown')} />
<InfoCard label={t('detail.kernel')} value={info.kernel || t('detail.unknown')} />
<InfoCard label={t('detail.cpuCores')} value={info.cpu || t('detail.unknown')} />
<InfoCard label={t('detail.uptime')} value={info.uptime || t('detail.unknown')} />
</div>
</div>
</div>
@@ -114,15 +117,16 @@ const UsageBar = memo(function UsageBar({
value: number
detail?: string
}) {
const { t } = useTranslation('hosts')
return (
<div>
<div className="flex justify-between text-xs mb-1">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium">
{value.toFixed(1)}% {detail && `(${detail})`}
{value.toFixed(1)}%{detail ? ` ${t('detail.usageDetail', { detail })}` : ''}
</span>
</div>
<div className="h-2 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
<div className="h-2 bg-muted rounded-full overflow-hidden">
<div
className={`h-full ${usageColor(value)} rounded-full transition-all`}
style={{ width: `${Math.min(value, 100)}%` }}
@@ -1,7 +1,9 @@
import { memo, useEffect, useState } from 'react'
import { memo, useEffect, useMemo, useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import type { TFunction } from 'i18next'
import { useTranslation } from 'react-i18next'
import { Key, Lock } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -24,43 +26,47 @@ import { hostApi } from '@/api'
import { PasswordInput } from '@/components/PasswordInput'
import { toast } from 'sonner'
// 表单 schema:zod 为唯一校验源,消息中文且具体
// (port 在表单内为字符串、提交时转数字,避免 z.coerce 输入/输出类型分叉导致 RHF 泛型不兼容)
const hostFormSchema = z
.object({
name: z.string().min(1, '请输入主机名称'),
hostIP: z.string().min(1, '请输入主机 IP'),
port: z
.string()
.min(1, '请输入端口')
.regex(/^\d+$/, '端口必须为数字')
.refine((v) => Number(v) >= 1 && Number(v) <= 65535, '端口必须在 1-65535 之间'),
user: z.string().min(1, '请输入用户名'),
authType: z.enum(['password', 'key']),
password: z.string().optional(),
privateKey: z.string().optional(),
keyPhrase: z.string().optional(),
labels: z.string().optional(),
})
.superRefine((data, ctx) => {
if (EDITING_REF.current) return
if (data.authType === 'password' && !data.password?.trim()) {
ctx.addIssue({
code: 'custom',
path: ['password'],
message: '请填写 SSH 登录密码',
})
}
if (data.authType === 'key' && !data.privateKey?.trim()) {
ctx.addIssue({
code: 'custom',
path: ['privateKey'],
message: '请粘贴 SSH 私钥内容',
})
}
})
/** 添加 SSH 主机弹窗 — react-hook-form + zod,自包含表单逻辑,页面只传开关与回调 */
const EDITING_REF = { current: false as boolean | null }
type HostFormValues = z.infer<typeof hostFormSchema>
// 表单 schema:zod 为唯一校验源,消息随语言(由组件内以 t 构造)
// (port 在表单内为字符串、提交时转数字,避免 z.coerce 输入/输出类型分叉导致 RHF 泛型不兼容)
const makeHostFormSchema = (t: TFunction<'hosts'>) =>
z
.object({
name: z.string().min(1, t('form.validation.nameRequired')),
hostIP: z.string().min(1, t('form.validation.hostIpRequired')),
port: z
.string()
.min(1, t('form.validation.portRequired'))
.regex(/^\d+$/, t('form.validation.portNumeric'))
.refine((v) => Number(v) >= 1 && Number(v) <= 65535, t('form.validation.portRange')),
user: z.string().min(1, t('form.validation.userRequired')),
authType: z.enum(['password', 'key']),
password: z.string().optional(),
privateKey: z.string().optional(),
keyPhrase: z.string().optional(),
labels: z.string().optional(),
})
.superRefine((data, ctx) => {
if (EDITING_REF.current) return
if (data.authType === 'password' && !data.password?.trim()) {
ctx.addIssue({
code: 'custom',
path: ['password'],
message: t('form.validation.passwordRequired'),
})
}
if (data.authType === 'key' && !data.privateKey?.trim()) {
ctx.addIssue({
code: 'custom',
path: ['privateKey'],
message: t('form.validation.privateKeyRequired'),
})
}
})
type HostFormValues = z.infer<ReturnType<typeof makeHostFormSchema>>
const DEFAULT_VALUES: HostFormValues = {
name: '',
@@ -82,19 +88,18 @@ interface HostFormDialogProps {
editing?: import('@/types').Host | null
}
/** 添加 SSH 主机弹窗 — react-hook-form + zod,自包含表单逻辑,页面只传开关与回调 */
const EDITING_REF = { current: false as boolean | null }
export const HostFormDialog = memo(function HostFormDialog({
open,
onOpenChange,
onCreated,
editing,
}: HostFormDialogProps) {
const { t } = useTranslation('hosts')
const [submitting, setSubmitting] = useState(false)
const schema = useMemo(() => makeHostFormSchema(t), [t])
const form = useForm<HostFormValues>({
resolver: zodResolver(hostFormSchema),
resolver: zodResolver(schema),
defaultValues: DEFAULT_VALUES,
})
const authType = form.watch('authType')
@@ -132,7 +137,7 @@ export const HostFormDialog = memo(function HostFormDialog({
onOpenChange(false)
onCreated()
} catch (err) {
toast.error(err instanceof Error ? err.message : '添加主机失败')
toast.error(err instanceof Error ? err.message : t('toast.createFailed'))
} finally {
setSubmitting(false)
}
@@ -142,7 +147,13 @@ export const HostFormDialog = memo(function HostFormDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{editing ? `编辑主机${editing.name ? ` · ${editing.name}` : ''}` : '添加 SSH 主机'}</DialogTitle>
<DialogTitle>
{editing
? editing.name
? t('form.editTitleWithName', { name: editing.name })
: t('form.editTitle')
: t('form.addTitle')}
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={onSubmit} className="space-y-4">
@@ -152,7 +163,7 @@ export const HostFormDialog = memo(function HostFormDialog({
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>名称 *</FormLabel>
<FormLabel>{t('form.nameLabel')}</FormLabel>
<FormControl>
<Input placeholder="loki-server-1" {...field} />
</FormControl>
@@ -165,7 +176,7 @@ export const HostFormDialog = memo(function HostFormDialog({
name="hostIP"
render={({ field }) => (
<FormItem>
<FormLabel>主机 IP *</FormLabel>
<FormLabel>{t('form.hostIpLabel')}</FormLabel>
<FormControl>
<Input placeholder="192.168.1.100" {...field} />
</FormControl>
@@ -180,7 +191,7 @@ export const HostFormDialog = memo(function HostFormDialog({
name="port"
render={({ field }) => (
<FormItem>
<FormLabel>端口</FormLabel>
<FormLabel>{t('form.portLabel')}</FormLabel>
<FormControl>
<Input type="number" placeholder="22" {...field} />
</FormControl>
@@ -193,7 +204,7 @@ export const HostFormDialog = memo(function HostFormDialog({
name="user"
render={({ field }) => (
<FormItem>
<FormLabel>用户名 *</FormLabel>
<FormLabel>{t('form.userLabel')}</FormLabel>
<FormControl>
<Input placeholder="root" {...field} />
</FormControl>
@@ -208,7 +219,7 @@ export const HostFormDialog = memo(function HostFormDialog({
name="authType"
render={({ field }) => (
<FormItem>
<FormLabel>认证方式</FormLabel>
<FormLabel>{t('form.authTypeLabel')}</FormLabel>
<FormControl>
<div className="flex gap-4">
<label className="flex items-center gap-2 cursor-pointer">
@@ -220,7 +231,7 @@ export const HostFormDialog = memo(function HostFormDialog({
onChange={() => field.onChange('password')}
/>
<Lock className="w-4 h-4" />
<span className="text-sm">密码</span>
<span className="text-sm">{t('fields.authPassword')}</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
@@ -231,7 +242,7 @@ export const HostFormDialog = memo(function HostFormDialog({
onChange={() => field.onChange('key')}
/>
<Key className="w-4 h-4" />
<span className="text-sm">SSH 密钥</span>
<span className="text-sm">{t('fields.authKey')}</span>
</label>
</div>
</FormControl>
@@ -246,9 +257,11 @@ export const HostFormDialog = memo(function HostFormDialog({
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>密码{editing ? '(留空保持不变)' : ' *'}</FormLabel>
<FormLabel>
{editing ? t('form.passwordLabelEdit') : t('form.passwordLabel')}
</FormLabel>
<FormControl>
<PasswordInput placeholder="SSH 登录密码" {...field} />
<PasswordInput placeholder={t('form.passwordPlaceholder')} {...field} />
</FormControl>
<FormMessage />
</FormItem>
@@ -261,7 +274,9 @@ export const HostFormDialog = memo(function HostFormDialog({
name="privateKey"
render={({ field }) => (
<FormItem>
<FormLabel>私钥{editing ? '(留空保持不变)' : ' *'}</FormLabel>
<FormLabel>
{editing ? t('form.privateKeyLabelEdit') : t('form.privateKeyLabel')}
</FormLabel>
<FormControl>
<Textarea
placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
@@ -278,9 +293,9 @@ export const HostFormDialog = memo(function HostFormDialog({
name="keyPhrase"
render={({ field }) => (
<FormItem>
<FormLabel>密钥口令(可选)</FormLabel>
<FormLabel>{t('form.keyPhraseLabel')}</FormLabel>
<FormControl>
<PasswordInput placeholder="无口令则留空" {...field} />
<PasswordInput placeholder={t('form.keyPhrasePlaceholder')} {...field} />
</FormControl>
<FormMessage />
</FormItem>
@@ -294,7 +309,7 @@ export const HostFormDialog = memo(function HostFormDialog({
name="labels"
render={({ field }) => (
<FormItem>
<FormLabel>标签(JSON)</FormLabel>
<FormLabel>{t('form.labelsLabel')}</FormLabel>
<FormControl>
<Input placeholder='["loki", "logging"]' {...field} />
</FormControl>
@@ -308,7 +323,13 @@ export const HostFormDialog = memo(function HostFormDialog({
className="w-full bg-primary hover:bg-primary/90"
disabled={submitting}
>
{submitting ? (editing ? '保存中...' : '添加中...') : editing ? '保存修改' : '添加主机'}
{submitting
? editing
? t('form.submittingSave')
: t('form.submittingAdd')
: editing
? t('form.submitSave')
: t('form.submitAdd')}
</Button>
</form>
</Form>
@@ -1,86 +0,0 @@
import { memo, useEffect, useState } from 'react'
import { Terminal } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { hostApi } from '@/api'
import type { Host } from '@/types'
interface TerminalDialogProps {
host: Host | null
onClose: () => void
}
/** 命令执行终端弹窗 — 打开即初始化欢迎输出,命令执行与输出渲染自包含 */
export const TerminalDialog = memo(function TerminalDialog({
host,
onClose,
}: TerminalDialogProps) {
const [command, setCommand] = useState('')
const [output, setOutput] = useState('')
const [executing, setExecuting] = useState(false)
// 切换主机/重新打开时重置终端
useEffect(() => {
if (host) {
setCommand('')
setOutput(`已连接到 ${host.name} (${host.hostIP})\n输入命令后按"执行"...\n`)
}
}, [host])
const executeCommand = async () => {
if (!host || !command.trim() || executing) return
setExecuting(true)
setOutput((prev) => prev + `\n$ ${command}\n`)
try {
const res = await hostApi.execute(host.id, command)
setOutput((prev) => prev + (res.stdout || '') + (res.stderr || '') + '\n')
} catch (err) {
const message = err instanceof Error ? err.message : '命令执行失败'
setOutput((prev) => prev + `错误:${message}\n`)
} finally {
setExecuting(false)
setCommand('')
}
}
return (
<Dialog open={host !== null} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Terminal className="w-5 h-5 text-primary" />
终端 - {host?.name}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="bg-card dark:bg-card text-green-400 font-mono text-xs p-4 rounded-lg h-80 overflow-auto whitespace-pre-wrap">
{output}
</div>
<div className="flex gap-2">
<Input
value={command}
onChange={(e) => setCommand(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && executeCommand()}
placeholder="输入命令..."
className="flex-1 font-mono text-sm"
disabled={executing}
/>
<Button
onClick={executeCommand}
disabled={executing || !command.trim()}
className="bg-primary hover:bg-primary/90"
>
{executing ? '执行中...' : '执行'}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
)
})