feat(web): improve zone domain list and detail navigation

合并 Zone 域名与路由展示,上游地址多行显示并支持路由详情跳转;
域名列表对齐用户管理页样式;Zone 页支持 ?tab= 定位;反代详情返回
使用浏览器历史上一级。
This commit is contained in:
ryan
2026-07-12 15:50:43 +08:00
parent 96b8ddc077
commit 7ef84cce52
6 changed files with 268 additions and 102 deletions
@@ -93,21 +93,36 @@ export function getRouteDomainsLabel(route: ProxyRouteItem): string {
return names.length > 0 ? names.join(', ') : '未绑定域名';
}
export function getUpstreamSummary(route: ProxyRouteItem): string {
/** Upstream address labels for display (supports multi-upstream). */
export function getUpstreamLabels(route: ProxyRouteItem): string[] {
if (route.upstream_type === 'pages') {
return route.pages_project_id
? `Pages 项目 #${route.pages_project_id}`
: 'Pages 项目未绑定';
return [
route.pages_project_id
? `Pages 项目 #${route.pages_project_id}`
: 'Pages 项目未绑定',
];
}
if (route.upstream_type === 'tunnel') {
const protocol = route.tunnel_target_protocol || 'http';
const target = route.tunnel_target_addr || '未配置目标';
return `Tunnel → ${protocol}://${target}`;
return [`Tunnel → ${protocol}://${target}`];
}
if ((route.upstream_list ?? []).length <= 1) {
return route.origin_url;
const list = (route.upstream_list ?? []).filter(Boolean);
if (list.length > 0) {
return list;
}
return `${route.upstream_list.length} 个上游,主上游 ${route.origin_url}`;
return route.origin_url ? [route.origin_url] : [];
}
export function getUpstreamSummary(route: ProxyRouteItem): string {
const labels = getUpstreamLabels(route);
if (labels.length === 0) {
return '未配置上游';
}
if (labels.length === 1) {
return labels[0];
}
return labels.join(' · ');
}
const originHostPattern =
@@ -1,6 +1,6 @@
'use client';
import Link from 'next/link';
import {useRouter} from 'next/navigation';
import {useCallback, useState} from 'react';
import {ArrowLeft, Loader2, Route, Upload} from 'lucide-react';
import {toast} from 'sonner';
@@ -41,6 +41,7 @@ interface RouteHeaderProps {
}
export function RouteHeader({ route }: RouteHeaderProps) {
const router = useRouter();
const [publishConfirmOpen, setPublishConfirmOpen] = useState(false);
const [diff, setDiff] = useState<ConfigDiffResult | null>(null);
const [diffLoading, setDiffLoading] = useState(false);
@@ -90,11 +91,14 @@ export function RouteHeader({ route }: RouteHeaderProps) {
return (
<>
<div className="space-y-4">
<Button variant="ghost" size="sm" className="h-8 gap-1.5 px-0 text-xs" asChild>
<Link href="/proxy-routes">
<ArrowLeft className="size-3.5" />
返回规则列表
</Link>
<Button
variant="ghost"
size="sm"
className="h-8 gap-1.5 px-0 text-xs"
onClick={() => router.back()}
>
<ArrowLeft className="size-3.5" />
返回
</Button>
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
@@ -1,8 +1,9 @@
'use client';
import {useState} from 'react';
import Link from 'next/link';
import {useMemo, useState} from 'react';
import {useMutation} from '@tanstack/react-query';
import {MoreHorizontal, Pencil, Plus, Trash2} from 'lucide-react';
import {Eye, Pencil, Plus, Trash2} from 'lucide-react';
import {toast} from 'sonner';
import {
@@ -16,27 +17,32 @@ import {
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {Button} from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {EmptyStateWithBorder} from '@/components/layout/empty';
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from '@/components/ui/table';
import {ZoneDomainService, type TlsCertificateItem, type ZoneDomainItem} from '@/lib/services/openflare';
import {Tooltip, TooltipContent, TooltipProvider, TooltipTrigger} from '@/components/ui/tooltip';
import {
ZoneDomainService,
type ProxyRouteItem,
type TlsCertificateItem,
type ZoneDomainItem,
} from '@/lib/services/openflare';
import {getUpstreamLabels} from '../../../proxy-routes/components/helpers';
import {ZoneDomainDialog} from './zone-domain-dialog';
export function ZoneDomainsTable({
zoneId,
domains,
certificates,
routes,
routesLoading = false,
onChanged,
}: {
zoneId: number;
domains: ZoneDomainItem[];
certificates: TlsCertificateItem[];
routes: ProxyRouteItem[];
routesLoading?: boolean;
onChanged(): Promise<unknown> | void;
}) {
const [editing, setEditing] = useState<ZoneDomainItem | null | undefined>(undefined);
@@ -52,12 +58,24 @@ export function ZoneDomainsTable({
onError: (error) => toast.error(error instanceof Error ? error.message : '删除失败'),
});
const certificateMap = new Map(certificates.map((certificate) => [certificate.id, certificate]));
const certificateMap = useMemo(
() => new Map(certificates.map((certificate) => [certificate.id, certificate])),
[certificates],
);
const routeMap = useMemo(
() => new Map(routes.map((route) => [route.id, route])),
[routes],
);
return (
<>
<div className="mb-4 flex justify-end">
<Button size="sm" className="h-7 text-xs" onClick={() => setEditing(null)}>
<div className="mb-3 flex justify-end">
<Button
variant="secondary"
size="sm"
className="h-7 text-xs"
onClick={() => setEditing(null)}
>
<Plus className="mr-1 size-3.5" />
添加域名
</Button>
@@ -66,62 +84,151 @@ export function ZoneDomainsTable({
{domains.length === 0 ? (
<EmptyStateWithBorder description="暂无已添加域名" />
) : (
<div className="rounded-lg border">
<Table>
<TableHeader>
<TableRow>
<TableHead>FQDN</TableHead>
<TableHead>证书</TableHead>
<TableHead>关联路由</TableHead>
<TableHead>备注</TableHead>
<TableHead className="w-12" />
</TableRow>
</TableHeader>
<TableBody>
{domains.map((domain) => (
<TableRow key={domain.id}>
<TableCell className="font-medium">{domain.domain}</TableCell>
<TableCell className="text-muted-foreground">
{domain.cert_id
? (certificateMap.get(domain.cert_id)?.name ?? `证书 #${domain.cert_id}`)
: '未绑定'}
</TableCell>
<TableCell>
{domain.proxy_route_id ? `#${domain.proxy_route_id}` : '未关联'}
</TableCell>
<TableCell className="max-w-48 truncate text-muted-foreground">
{domain.remark || '—'}
</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
aria-label={`操作 ${domain.domain}`}
>
<MoreHorizontal />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setEditing(domain)}>
<Pencil />
编辑
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => setDeleting(domain)}
>
<Trash2 />
删除
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
<div className="overflow-hidden rounded-lg border border-dashed shadow-none">
<TooltipProvider delayDuration={0}>
<Table className="w-full min-w-full caption-bottom text-sm">
<TableHeader className="sticky top-0 z-20 bg-background">
<TableRow className="border-b border-dashed hover:bg-transparent">
<TableHead className="h-8 whitespace-nowrap py-2 min-w-[160px]">
FQDN
</TableHead>
<TableHead className="h-8 whitespace-nowrap py-2 min-w-[120px]">
证书
</TableHead>
<TableHead className="h-8 whitespace-nowrap py-2 min-w-[200px]">
上游
</TableHead>
<TableHead className="h-8 whitespace-nowrap py-2 min-w-[120px]">
备注
</TableHead>
<TableHead className="sticky right-0 z-10 h-8 w-[110px] bg-background py-2 text-center">
操作
</TableHead>
</TableRow>
))}
</TableBody>
</Table>
</TableHeader>
<TableBody>
{domains.map((domain) => {
const route =
domain.proxy_route_id != null
? routeMap.get(domain.proxy_route_id)
: undefined;
const upstreams = route ? getUpstreamLabels(route) : [];
const certLabel = domain.cert_id
? (certificateMap.get(domain.cert_id)?.name ?? `证书 #${domain.cert_id}`)
: '未绑定';
return (
<TableRow
key={domain.id}
className="group border-dashed hover:bg-muted/30"
>
<TableCell className="py-1">
<span
className="max-w-[220px] truncate text-[11px] font-medium leading-tight"
title={domain.domain}
>
{domain.domain}
</span>
</TableCell>
<TableCell className="py-1 font-mono text-[10px] whitespace-nowrap text-muted-foreground">
{certLabel}
</TableCell>
<TableCell className="max-w-[280px] py-1">
{!domain.proxy_route_id ? (
<span className="font-mono text-[10px] text-muted-foreground">
未关联路由
</span>
) : routesLoading && !route ? (
<span className="font-mono text-[10px] text-muted-foreground">
加载中…
</span>
) : upstreams.length === 0 ? (
<span className="font-mono text-[10px] text-muted-foreground">
未配置上游
</span>
) : (
<div className="flex flex-col gap-0">
{upstreams.map((upstream) => (
<span
key={upstream}
className="truncate font-mono text-[10px] leading-tight text-muted-foreground"
title={upstream}
>
{upstream}
</span>
))}
</div>
)}
</TableCell>
<TableCell className="max-w-[160px] truncate py-1 font-mono text-[10px] text-muted-foreground">
{domain.remark || '—'}
</TableCell>
<TableCell
className="sticky right-0 z-10 bg-background py-1 text-center"
onClick={(event) => event.stopPropagation()}
>
<div className="flex items-center justify-center gap-0.5">
{domain.proxy_route_id ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-muted-foreground hover:text-foreground"
asChild
>
<Link
href={`/proxy-routes/detail?id=${domain.proxy_route_id}`}
>
<Eye className="size-3" />
</Link>
</Button>
</TooltipTrigger>
<TooltipContent side="top" className="text-xs">
查看路由详情
</TooltipContent>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-muted-foreground hover:text-foreground"
onClick={() => setEditing(domain)}
>
<Pencil className="size-3" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" className="text-xs">
编辑域名
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-muted-foreground hover:text-destructive"
onClick={() => setDeleting(domain)}
>
<Trash2 className="size-3" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" className="text-xs">
删除域名
</TooltipContent>
</Tooltip>
</div>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TooltipProvider>
</div>
)}
@@ -1,9 +0,0 @@
import {EmptyStateWithBorder} from '@/components/layout/empty'
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from '@/components/ui/card'
import type {ZoneDomainItem} from '@/lib/services/openflare'
import {Route} from 'lucide-react'
export function ZoneRouteSummary({domains}: {domains: ZoneDomainItem[]}) {
const groups = Map.groupBy(domains.filter((domain) => domain.proxy_route_id !== null), (domain) => domain.proxy_route_id!)
return <Card className="shadow-none"><CardHeader><CardTitle className="text-base">路由关联</CardTitle><CardDescription>域名只能关联一个反代路由;路由可关联多个 Zone 域名。</CardDescription></CardHeader><CardContent>{groups.size === 0 ? <EmptyStateWithBorder icon={Route} description="暂无关联反代路由。" /> : <div className="space-y-3">{[...groups].map(([routeID, items]) => <div key={routeID} className="rounded-lg border p-3"><p className="text-sm font-semibold">路由 #{routeID}</p><p className="mt-1 text-xs text-muted-foreground">{items.map((item) => item.domain).join(' · ')}</p></div>)}</div>}</CardContent></Card>
}
@@ -1,7 +1,8 @@
'use client';
import Link from 'next/link';
import {useState} from 'react';
import {usePathname, useRouter, useSearchParams} from 'next/navigation';
import {useCallback, useMemo, useState} from 'react';
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query';
import {ArrowLeft, Globe, Pencil, Trash2} from 'lucide-react';
import {toast} from 'sonner';
@@ -20,21 +21,53 @@ import {Button} from '@/components/ui/button';
import {EmptyStateWithBorder} from '@/components/layout/empty';
import {LoadingStateWithBorder} from '@/components/layout/loading';
import {Tabs, TabsContent, TabsList, TabsTrigger} from '@/components/ui/tabs';
import {TlsCertificateService, ZoneService, zoneQueryKey} from '@/lib/services/openflare';
import {
ProxyRouteService,
TlsCertificateService,
ZoneService,
zoneQueryKey,
} from '@/lib/services/openflare';
import {getErrorMessage} from '../components/website-utils';
import {ZoneCertificatesPanel} from './components/zone-certificates';
import {ZoneDomainsTable} from './components/zone-domains-table';
import {ZoneEditorDialog} from './components/zone-editor-dialog';
import {ZoneOverviewPanel} from './components/zone-overview';
import {ZoneRouteSummary} from './components/zone-route-summary';
const zoneTabs = ['overview', 'domains', 'certificates', 'settings'] as const;
export type ZonePageTab = (typeof zoneTabs)[number];
function getZonePageTab(value: string | null | undefined): ZonePageTab {
return zoneTabs.includes(value as ZonePageTab) ? (value as ZonePageTab) : 'overview';
}
export function ZonePageClient({zoneId}: {zoneId: number}) {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const queryClient = useQueryClient();
const [activeTab, setActiveTab] = useState('overview');
const activeTab = useMemo(
() => getZonePageTab(searchParams.get('tab')),
[searchParams],
);
const [editZone, setEditZone] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const setActiveTab = useCallback(
(tab: string) => {
const next = getZonePageTab(tab);
const params = new URLSearchParams(searchParams.toString());
if (next === 'overview') {
params.delete('tab');
} else {
params.set('tab', next);
}
const query = params.toString();
router.replace(query ? `${pathname}?${query}` : pathname, {scroll: false});
},
[pathname, router, searchParams],
);
const overviewQuery = useQuery({
queryKey: [...zoneQueryKey, zoneId],
queryFn: () => ZoneService.getOverview(zoneId),
@@ -47,6 +80,12 @@ export function ZonePageClient({zoneId}: {zoneId: number}) {
enabled: overviewQuery.isSuccess,
});
const routesQuery = useQuery({
queryKey: ['openflare', 'proxy-routes'],
queryFn: () => ProxyRouteService.list(),
enabled: overviewQuery.isSuccess,
});
const deleteZone = useMutation({
mutationFn: () => ZoneService.deleteById(zoneId),
onSuccess: async () => {
@@ -95,6 +134,7 @@ export function ZonePageClient({zoneId}: {zoneId: number}) {
const overview = overviewQuery.data;
const certificates = certificatesQuery.data ?? [];
const routes = routesQuery.data ?? [];
const boundCertCount = new Set(
overview.domains.map((domain) => domain.cert_id).filter((id): id is number => id != null),
).size;
@@ -145,9 +185,6 @@ export function ZonePageClient({zoneId}: {zoneId: number}) {
<TabsTrigger value="domains" className="px-0 pb-2 text-xs font-semibold">
域名 ({overview.domains.length})
</TabsTrigger>
<TabsTrigger value="routes" className="px-0 pb-2 text-xs font-semibold">
路由
</TabsTrigger>
<TabsTrigger value="certificates" className="px-0 pb-2 text-xs font-semibold">
证书 ({boundCertCount})
</TabsTrigger>
@@ -164,12 +201,11 @@ export function ZonePageClient({zoneId}: {zoneId: number}) {
zoneId={zoneId}
domains={overview.domains}
certificates={certificates}
routes={routes}
routesLoading={routesQuery.isLoading}
onChanged={() => overviewQuery.refetch()}
/>
</TabsContent>
<TabsContent value="routes">
<ZoneRouteSummary domains={overview.domains} />
</TabsContent>
<TabsContent value="certificates">
<ZoneCertificatesPanel domains={overview.domains} certificates={certificates} />
</TabsContent>
+15 -2
View File
@@ -3,7 +3,9 @@ import {render, screen, waitFor} from '@testing-library/react';
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {ZonePageClient} from '@/app/(main)/websites/[zoneId]/page-client';
import {TlsCertificateService, ZoneService} from '@/lib/services/openflare';
import {ProxyRouteService, TlsCertificateService, ZoneService} from '@/lib/services/openflare';
const replaceMock = vi.fn();
vi.mock('next/link', () => ({
default: ({children, href}: {children: React.ReactNode; href: string}) => (
@@ -11,6 +13,12 @@ vi.mock('next/link', () => ({
),
}));
vi.mock('next/navigation', () => ({
useRouter: () => ({replace: replaceMock}),
usePathname: () => '/websites/42',
useSearchParams: () => new URLSearchParams(),
}));
vi.mock('@/lib/services/openflare', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/services/openflare')>();
return {
@@ -23,6 +31,9 @@ vi.mock('@/lib/services/openflare', async (importOriginal) => {
TlsCertificateService: {
list: vi.fn(),
},
ProxyRouteService: {
list: vi.fn(),
},
};
});
@@ -45,6 +56,8 @@ describe('ZonePageClient', () => {
vi.mocked(ZoneService.deleteById).mockReset();
vi.mocked(TlsCertificateService.list).mockReset();
vi.mocked(TlsCertificateService.list).mockResolvedValue([]);
vi.mocked(ProxyRouteService.list).mockReset();
vi.mocked(ProxyRouteService.list).mockResolvedValue([]);
});
it('loads the overview by stable ID and exposes all tabs including empty domains', async () => {
@@ -61,7 +74,7 @@ describe('ZonePageClient', () => {
expect(await screen.findByRole('heading', {name: 'arctel.de'})).toBeVisible();
expect(screen.getByRole('tab', {name: '域名 (0)'})).toBeVisible();
expect(screen.getByRole('tab', {name: '证书 (0)'})).toBeVisible();
expect(screen.getByRole('tab', {name: '路由'})).toBeVisible();
expect(screen.queryByRole('tab', {name: '路由'})).not.toBeInTheDocument();
expect(screen.getByRole('tab', {name: '设置'})).toBeVisible();
});