Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { ChangePasswordDialog } from "./components/ChangePasswordDialog";
import { FirstRunWizard } from "./components/FirstRunWizard";
import { ActivatePage } from "./pages/ActivatePage";
import { LoginPage } from "./pages/LoginPage";
import { useI18n } from "./i18n";

// 路由级懒加载:recharts / 大页面不进首屏 chunk(900KB 单 chunk → 拆包)
const CredentialsPage = lazy(() => import("./pages/CredentialsPage").then(m => ({ default: m.CredentialsPage })));
Expand All @@ -24,9 +25,14 @@ const LogsPage = lazy(() => import("./pages/LogsPage").then(m => ({ default: m.L
const UpstreamStatusPage = lazy(() => import("./pages/UpstreamStatusPage").then(m => ({ default: m.UpstreamStatusPage })));
const BillingPage = lazy(() => import("./pages/BillingPage").then(m => ({ default: m.BillingPage })));

const LOADING = (
<div className="grid h-full place-items-center text-sm text-[var(--color-ink-muted)]">载入中…</div>
);
function Loading() {
const { t } = useI18n();
return (
<div className="grid h-full place-items-center text-sm text-[var(--color-ink-muted)]">
{t("common.loading")}
</div>
);
}

/**
* admin-only 页面的路由守卫:非 admin 直接送回首页。
Expand Down Expand Up @@ -68,7 +74,7 @@ export function App() {
}, [queryClient]);

if (session.isLoading) {
return LOADING;
return <Loading />;
}

if (!session.data) {
Expand All @@ -91,7 +97,7 @@ export function App() {
return (
<>
<FirstRunWizard username={session.data.username} isAdmin={session.data.is_admin} />
<Suspense fallback={LOADING}>
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/login" element={<Navigate to="/" replace />} />
<Route element={<Layout session={session.data} />}>
Expand Down
76 changes: 40 additions & 36 deletions web/src/components/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,49 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { RotateCcw, TriangleAlert } from "lucide-react";
import { Button } from "./ui/button";
import { useI18n } from "../i18n";

type Props = { children: ReactNode };
type State = { error: Error | null };

/** 失败面板(函数组件以便读 i18n;仍由上方 class 边界捕获)。 */
function ErrorFallback({ error }: { error: Error }) {
const { t } = useI18n();
return (
<div
role="alert"
data-testid="error-boundary"
className="grid min-h-[50vh] place-items-center p-6"
>
<div className="w-full max-w-md space-y-3 rounded-xl border border-border bg-card p-5 shadow-sm">
<div className="flex items-center gap-2 text-sm font-semibold">
<TriangleAlert className="size-4 text-[var(--color-danger,#dc2626)]" />
{t("common.errorBoundaryTitle")}
</div>
<p className="text-sm text-muted-foreground">{t("common.errorBoundaryDesc")}</p>
<pre
data-testid="error-boundary-message"
className="max-h-40 overflow-auto rounded-md bg-muted p-2 text-xs whitespace-pre-wrap break-words"
>
{error.message || String(error)}
</pre>
<div className="flex justify-end gap-2">
<Button asChild variant="ghost">
<a href="/">{t("common.backHome")}</a>
</Button>
<Button
variant="default"
data-testid="error-boundary-reload"
onClick={() => window.location.reload()}
>
<RotateCcw className="size-3.5" /> {t("common.reload")}
</Button>
</div>
</div>
</div>
);
}

/**
* 渲染错误兜底:任何页面组件抛错时给一页可读的失败面板,而不是白屏。
*
Expand All @@ -30,41 +69,6 @@ export class ErrorBoundary extends Component<Props, State> {
render(): ReactNode {
const { error } = this.state;
if (!error) return this.props.children;
return (
<div
role="alert"
data-testid="error-boundary"
className="grid min-h-[50vh] place-items-center p-6"
>
<div className="w-full max-w-md space-y-3 rounded-xl border border-border bg-card p-5 shadow-sm">
<div className="flex items-center gap-2 text-sm font-semibold">
<TriangleAlert className="size-4 text-[var(--color-danger,#dc2626)]" />
页面出错了
</div>
<p className="text-sm text-muted-foreground">
这个页面渲染时遇到异常,其他功能不受影响。可以重载页面重试;若反复出现,
请把下面的错误信息与浏览器控制台日志一并反馈。
</p>
<pre
data-testid="error-boundary-message"
className="max-h-40 overflow-auto rounded-md bg-muted p-2 text-xs whitespace-pre-wrap break-words"
>
{error.message || String(error)}
</pre>
<div className="flex justify-end gap-2">
<Button asChild variant="ghost">
<a href="/">回到首页</a>
</Button>
<Button
variant="default"
data-testid="error-boundary-reload"
onClick={() => window.location.reload()}
>
<RotateCcw className="size-3.5" /> 重新加载
</Button>
</div>
</div>
</div>
);
return <ErrorFallback error={error} />;
}
}
4 changes: 3 additions & 1 deletion web/src/components/PageSkeleton.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Skeleton } from "../ui";
import { cn } from "@/lib/utils";
import { useI18n } from "../i18n";

/**
* 页面加载骨架:替代纯文字「载入中…」,让布局在数据到达前就稳定,
Expand All @@ -16,9 +17,10 @@ export function PageSkeleton({
rows?: number;
className?: string;
}) {
const { t } = useI18n();
return (
<div className={cn("space-y-6", className)} data-testid="page-skeleton">
<span className="sr-only">载入中…</span>
<span className="sr-only">{t("common.loading")}</span>

{/* 页头占位 */}
<div className="space-y-2">
Expand Down
16 changes: 10 additions & 6 deletions web/src/components/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ChevronLeft, ChevronRight } from "lucide-react";
import { Button, Select } from "../ui";
import { DEFAULT_PAGE_SIZE, PAGE_SIZE_OPTIONS } from "../lib/constants";
import { useI18n } from "../i18n";

/**
* 全站统一的分页控件。
Expand Down Expand Up @@ -50,6 +51,7 @@ export function Pagination({
busy?: boolean;
className?: string;
}) {
const { t } = useI18n();
// 页数优先用显式 pageCount;否则由 total 现算;都没有 = 未知(游标模式)
const resolvedCount =
pageCount ?? (total !== null && total !== undefined
Expand All @@ -58,8 +60,10 @@ export function Pagination({
const next = hasNext ?? (resolvedCount !== null ? page < resolvedCount - 1 : false);

const info = resolvedCount !== null
? `第 ${page + 1} / ${resolvedCount} 页`
: `第 ${page + 1} 页`;
? t("pagination.pageInfo")
.replace("{page}", String(page + 1))
.replace("{total}", String(resolvedCount))
: t("pagination.pageInfoUnknown").replace("{page}", String(page + 1));

return (
<div
Expand All @@ -70,15 +74,15 @@ export function Pagination({
<span data-testid={`${testId}-page-info`}>{info}</span>
{onPageSizeChange && (
<label className="flex items-center gap-1.5">
每页
{t("pagination.perPage")}
<Select
value={String(pageSize)}
data-testid={`${testId}-page-size`}
className="h-7 w-20 text-xs"
onChange={(event) => onPageSizeChange(Number(event.target.value))}
>
{pageSizeOptions.map((size) => (
<option key={size} value={size}>{size} 条</option>
<option key={size} value={size}>{t("pagination.itemCount").replace("{n}", String(size))}</option>
))}
</Select>
</label>
Expand All @@ -93,7 +97,7 @@ export function Pagination({
onClick={() => onPageChange(Math.max(0, page - 1))}
>
<ChevronLeft className="size-3.5" />
上一页
{t("pagination.prev")}
</Button>
<Button
size="sm"
Expand All @@ -102,7 +106,7 @@ export function Pagination({
disabled={!next || busy}
onClick={() => onPageChange(page + 1)}
>
下一页
{t("pagination.next")}
<ChevronRight className="size-3.5" />
</Button>
</div>
Expand Down
4 changes: 3 additions & 1 deletion web/src/components/ThemeToggle.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { useState } from "react";
import { Moon, Sun } from "lucide-react";
import { Button } from "../ui";
import { useI18n } from "../i18n";

/** 明暗主题切换:切换 <html>.dark 并持久化到 localStorage(首次跟随系统)。 */
export function ThemeToggle() {
const { t } = useI18n();
const [dark, setDark] = useState(() =>
document.documentElement.classList.contains("dark"),
);
Expand All @@ -20,7 +22,7 @@ export function ThemeToggle() {
};

return (
<Button size="icon" variant="ghost" onClick={toggle} aria-label="切换主题">
<Button size="icon" variant="ghost" onClick={toggle} aria-label={t("common.themeToggle")}>
{dark ? <Sun /> : <Moon />}
</Button>
);
Expand Down
4 changes: 3 additions & 1 deletion web/src/components/Toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { CircleAlert, CircleCheck, Info, TriangleAlert, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { useI18n } from "../i18n";

/**
* 浮层轻提示(toast):操作结果不再以插入式横幅撑开页面,改为顶部居中浮动、
Expand Down Expand Up @@ -126,6 +127,7 @@ function ToastCard({
toast: ToastItem;
onDismiss: (id: number) => void;
}) {
const { t } = useI18n();
const duration = toast.duration ?? DEFAULT_DURATION;
const Icon = ICON[toast.tone];

Expand All @@ -150,7 +152,7 @@ function ToastCard({
<div className="min-w-0 flex-1 break-words">{toast.content}</div>
<button
type="button"
aria-label="关闭提示"
aria-label={t("common.dismissToast")}
onClick={() => onDismiss(toast.id)}
className="-mt-0.5 -mr-0.5 shrink-0 rounded-md p-1 text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"
>
Expand Down
18 changes: 13 additions & 5 deletions web/src/components/UserMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "../ui";
import { ROLE_LABELS, type Role } from "../api/types";
import type { Role } from "../api/types";
import { useI18n, type MessageKey } from "../i18n";

const ROLE_KEYS: Record<Role, MessageKey> = {
admin: "role.admin",
operator: "role.operator",
viewer: "role.viewer",
};

/** 用户菜单:合并「用户名/角色信息」与「改密 / 退出」为单个下拉。 */
export function UserMenu({
Expand All @@ -22,18 +29,19 @@ export function UserMenu({
onChangePassword: () => void;
onLogout: () => void;
}) {
const { t } = useI18n();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="gap-1.5 px-2 sm:px-2.5" aria-label="用户菜单">
<Button variant="ghost" size="sm" className="gap-1.5 px-2 sm:px-2.5" aria-label={t("user.menu")}>
<UserRound className="size-4" />
<span className="hidden sm:inline">{username}</span>
<ChevronDown className="hidden size-3.5 text-muted-foreground sm:inline" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
{username} · {ROLE_LABELS[role]}
{username} · {t(ROLE_KEYS[role])}
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem
Expand All @@ -42,11 +50,11 @@ export function UserMenu({
className="cursor-pointer"
>
<KeyRound className="mr-2 size-4" />
修改密码
{t("user.changePassword")}
</DropdownMenuItem>
<DropdownMenuItem data-testid="menu-logout" onSelect={onLogout} className="cursor-pointer">
<LogOut className="mr-2 size-4" />
退出
{t("user.signOut")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
Expand Down
5 changes: 5 additions & 0 deletions web/src/i18n/__tests__/i18n.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
translate,
useI18n,
} from "@/i18n";
import { EN, ZH } from "@/i18n/messages";
import type { MessageKey } from "@/i18n";

function Probe() {
Expand All @@ -24,6 +25,10 @@ afterEach(() => {
});

describe("t() 与文案表", () => {
it("中英键集合完全一致(无缺键 / 多键)", () => {
expect(Object.keys(EN).sort()).toEqual(Object.keys(ZH).sort());
});

it("同一 key 命中 zh 与 en", () => {
expect(translate("nav.credentials", "zh")).toBe("凭证管理");
expect(translate("nav.credentials", "en")).toBe("Credentials");
Expand Down
48 changes: 48 additions & 0 deletions web/src/i18n/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,30 @@ export const ZH = {
"row.creditFlow": "变动流水",
"row.confirmDelete": "确认删除",
"common.cancel": "取消",
"common.loading": "载入中…",
"common.retry": "重试",
"common.dismissToast": "关闭提示",
"common.themeToggle": "切换主题",
"common.footnoteSummary": "口径说明",
"common.queryErrorTitle": "数据加载失败",
"common.queryErrorDesc": "请稍后重试;若持续失败,到「服务端日志与告警」查看后端原因。",
"common.errorBoundaryTitle": "页面出错了",
"common.errorBoundaryDesc":
"这个页面渲染时遇到异常,其他功能不受影响。可以重载页面重试;若反复出现,请把下面的错误信息与浏览器控制台日志一并反馈。",
"common.backHome": "回到首页",
"common.reload": "重新加载",
"role.admin": "管理员",
"role.operator": "操作员",
"role.viewer": "只读",
"user.menu": "用户菜单",
"user.changePassword": "修改密码",
"user.signOut": "退出",
"pagination.perPage": "每页",
"pagination.itemCount": "{n} 条",
"pagination.pageInfo": "第 {page} / {total} 页",
"pagination.pageInfoUnknown": "第 {page} 页",
"pagination.prev": "上一页",
"pagination.next": "下一页",

"credentialDialog.open": "添加凭证",
"credentialDialog.close": "关闭",
Expand Down Expand Up @@ -336,6 +360,30 @@ export const EN: Record<MessageKey, string> = {
"row.creditFlow": "Usage history",
"row.confirmDelete": "Confirm delete",
"common.cancel": "Cancel",
"common.loading": "Loading…",
"common.retry": "Retry",
"common.dismissToast": "Dismiss notification",
"common.themeToggle": "Toggle theme",
"common.footnoteSummary": "About these numbers",
"common.queryErrorTitle": "Failed to load data",
"common.queryErrorDesc": "Please try again later. If it keeps failing, check the backend cause in Server logs & alerts.",
"common.errorBoundaryTitle": "Something went wrong",
"common.errorBoundaryDesc":
"This page failed to render; other features are unaffected. Reload the page to retry, and if it keeps happening, please share the error below along with the browser console log.",
"common.backHome": "Back to home",
"common.reload": "Reload",
"role.admin": "Admin",
"role.operator": "Operator",
"role.viewer": "Read-only",
"user.menu": "User menu",
"user.changePassword": "Change password",
"user.signOut": "Sign out",
"pagination.perPage": "Per page",
"pagination.itemCount": "{n} items",
"pagination.pageInfo": "Page {page} of {total}",
"pagination.pageInfoUnknown": "Page {page}",
"pagination.prev": "Previous",
"pagination.next": "Next",

"credentialDialog.open": "Add credential",
"credentialDialog.close": "Close",
Expand Down
Loading