fix(frontend): serve zone detail static export fallback

This commit is contained in:
ryan
2026-07-12 18:50:13 +08:00
parent 50717d1baf
commit c624512da6
11 changed files with 167 additions and 29 deletions
+1
View File
@@ -41,6 +41,7 @@ sidebar: false
### 修复
- 修复嵌入式静态前端访问 `/websites/:zoneId` 时回退到首页 HTML,导致 Zone 详情页显示总览并触发 React hydration error 的问题。
- Docker ClickHouse 性能配置改为单文件挂载,避免覆盖镜像内置的 Docker 网络监听配置,导致宿主机无法通过 8123/9000 访问服务。
## [v3.1.2] - 2026-07-10
+1 -1
View File
@@ -2,7 +2,7 @@
## 目标
将“网站”重构为以可注册根域为入口的 Zone 管理体验。`arctel.de` 之类的 Zone 是稳定的管理边界;用户通过稳定 ID 路径进入该 Zone,查看并维护其中明确声明的域名、域名所绑定的反代路由和证书,以及路由级 WAF、Pages 等能力。
将“网站”重构为以可注册根域为入口的 Zone 管理体验。`example.com` 之类的 Zone 是稳定的管理边界;用户通过稳定 ID 路径进入该 Zone,查看并维护其中明确声明的域名、域名所绑定的反代路由和证书,以及路由级 WAF、Pages 等能力。
本设计替代 `managed_domains` 的概念、表与 API。它不引入权威 DNS 解析记录管理。
+2 -2
View File
@@ -315,7 +315,7 @@ cd frontend && pnpm add -D vitest @testing-library/react @testing-library/jest-d
```ts
expect(ZoneService.getOverview).toHaveBeenCalledWith(42)
expect(screen.getByRole('heading', {name: 'arctel.de'})).toBeVisible()
expect(screen.getByRole('heading', {name: 'example.com'})).toBeVisible()
```
覆盖 `/websites/42` 的加载、404、空域名、搜索列表和从列表点击 ID 链接。
@@ -374,7 +374,7 @@ git commit -m "feat(web): add zone-based website management"
```tsx
render(<ZoneDomainSelector value={[7]} onChange={onChange} domains={[apiDomain]} />)
expect(screen.getByText('api.arctel.de')).toBeVisible()
expect(screen.getByText('api.example.com')).toBeVisible()
expect(onChange).toHaveBeenCalledWith([7])
```
@@ -56,7 +56,7 @@ export function ZoneEditorDialog({
<DialogContent>
<DialogHeader>
<DialogTitle>{zone ? '编辑 Zone' : '新增 Zone'}</DialogTitle>
<DialogDescription>Zone 仅接受可注册根域,例如 arctel.de。</DialogDescription>
<DialogDescription>Zone 仅接受可注册根域,例如 example.com。</DialogDescription>
</DialogHeader>
<form
id="zone-editor"
@@ -67,7 +67,7 @@ export function ZoneEditorDialog({
>
<div className="space-y-1.5">
<Label htmlFor="zone-domain">根域</Label>
<Input id="zone-domain" placeholder="arctel.de" {...form.register('domain')} />
<Input id="zone-domain" placeholder="example.com" {...form.register('domain')} />
{form.formState.errors.domain && (
<p className="text-xs text-destructive">{form.formState.errors.domain.message}</p>
)}
@@ -1,6 +1,6 @@
'use client';
import {useParams, usePathname, useRouter, useSearchParams} from 'next/navigation';
import {usePathname, useRouter, useSearchParams} from 'next/navigation';
import {useCallback, useEffect, useMemo, useState} from 'react';
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query';
import {ArrowLeft, Globe, Pencil, Trash2} from 'lucide-react';
@@ -40,10 +40,12 @@ function getZonePageTab(value: string | null | undefined): ZonePageTab {
return zoneTabs.includes(value as ZonePageTab) ? (value as ZonePageTab) : 'overview';
}
export function ZonePageClient() {
const params = useParams();
const zoneId = Number(params?.zoneId);
function getZoneIdFromPathname(pathname: string | null): number {
const match = pathname?.match(/^\/websites\/([^/]+)$/);
return Number(match?.[1]);
}
export function ZonePageClient() {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
@@ -51,6 +53,7 @@ export function ZonePageClient() {
const router = useRouter();
const pathname = usePathname();
const zoneId = useMemo(() => getZoneIdFromPathname(pathname), [pathname]);
const searchParams = useSearchParams();
const queryClient = useQueryClient();
const activeTab = useMemo(
+5 -5
View File
@@ -34,14 +34,14 @@ describe('WebsitesPage', () => {
vi.mocked(ZoneService.list).mockResolvedValue([
{
id: 42,
domain: 'arctel.de',
domain: 'example.com',
domain_count: 3,
created_at: '',
updated_at: '',
},
{
id: 43,
domain: 'example.com',
domain: 'another.com',
domain_count: 0,
created_at: '',
updated_at: '',
@@ -50,18 +50,18 @@ describe('WebsitesPage', () => {
renderPage();
expect(await screen.findByText('arctel.de')).toBeVisible();
expect(await screen.findByText('example.com')).toBeVisible();
expect(screen.getByText('3')).toBeVisible();
expect(screen.getByText('0')).toBeVisible();
expect(screen.getByRole('columnheader', {name: '根域'})).toBeVisible();
fireEvent.change(screen.getByPlaceholderText('搜索 Zone 根域'), {
target: {value: 'arctel'},
target: {value: 'example'},
});
expect(screen.getByRole('link', {name: '管理'})).toHaveAttribute(
'href',
'/websites/42',
);
expect(screen.queryByText('example.com')).not.toBeInTheDocument();
expect(screen.queryByText('another.com')).not.toBeInTheDocument();
});
});
@@ -13,7 +13,7 @@ vi.mock('next/link', () => ({
}));
const zones: ZoneItem[] = [
{id: 1, domain: 'arctel.de', created_at: '', updated_at: ''},
{id: 1, domain: 'example.com', created_at: '', updated_at: ''},
];
const domains: ZoneDomainItem[] = [
@@ -21,7 +21,7 @@ const domains: ZoneDomainItem[] = [
id: 7,
zone_id: 1,
proxy_route_id: null,
domain: 'api.arctel.de',
domain: 'api.example.com',
cert_id: 9,
created_at: '',
updated_at: '',
@@ -30,7 +30,7 @@ const domains: ZoneDomainItem[] = [
id: 8,
zone_id: 1,
proxy_route_id: 99,
domain: 'bound.arctel.de',
domain: 'bound.example.com',
cert_id: null,
created_at: '',
updated_at: '',
@@ -56,12 +56,12 @@ describe('ZoneDomainSelector', () => {
/>,
);
expect(screen.getByText('api.arctel.de')).toBeVisible();
expect(screen.getByText('api.example.com')).toBeVisible();
// Bound to another route — hidden by default
expect(screen.queryByText('bound.arctel.de')).not.toBeInTheDocument();
expect(screen.queryByText('bound.example.com')).not.toBeInTheDocument();
expect(screen.getByRole('button', {name: /快捷新增域名/})).toBeVisible();
await user.click(screen.getByText('api.arctel.de'));
await user.click(screen.getByText('api.example.com'));
expect(onChange).toHaveBeenCalledWith([]);
});
@@ -76,8 +76,8 @@ describe('ZoneDomainSelector', () => {
/>,
);
expect(screen.getByText('api.arctel.de')).toBeVisible();
expect(screen.queryByText('bound.arctel.de')).not.toBeInTheDocument();
expect(screen.getByText('api.example.com')).toBeVisible();
expect(screen.queryByText('bound.example.com')).not.toBeInTheDocument();
});
it('still shows domains already bound to the current route', () => {
@@ -91,7 +91,7 @@ describe('ZoneDomainSelector', () => {
/>,
);
expect(screen.getByText('bound.arctel.de')).toBeVisible();
expect(screen.getByText('api.arctel.de')).toBeVisible();
expect(screen.getByText('bound.example.com')).toBeVisible();
expect(screen.getByText('api.example.com')).toBeVisible();
});
});
+21 -4
View File
@@ -14,6 +14,7 @@ class ResizeObserverMock {
vi.stubGlobal('ResizeObserver', ResizeObserverMock);
let mockZoneId = '42';
let mockParamZoneId = '42';
const replaceMock = vi.fn();
@@ -27,7 +28,7 @@ vi.mock('next/navigation', () => ({
useRouter: () => ({replace: replaceMock, back: vi.fn()}),
usePathname: () => `/websites/${mockZoneId}`,
useSearchParams: () => new URLSearchParams(),
useParams: () => ({zoneId: mockZoneId}),
useParams: () => ({zoneId: mockParamZoneId}),
}));
vi.mock('@/lib/services/openflare', async (importOriginal) => {
@@ -49,8 +50,9 @@ vi.mock('@/lib/services/openflare', async (importOriginal) => {
};
});
function renderPage(zoneId: number) {
function renderPage(zoneId: number, paramZoneId = zoneId) {
mockZoneId = String(zoneId);
mockParamZoneId = String(paramZoneId);
const client = new QueryClient({
defaultOptions: {
queries: {retry: false, gcTime: 0},
@@ -65,6 +67,7 @@ function renderPage(zoneId: number) {
describe('ZonePageClient', () => {
beforeEach(() => {
mockParamZoneId = mockZoneId;
vi.mocked(ZoneService.getOverview).mockReset();
vi.mocked(ZoneService.getStats).mockReset();
vi.mocked(ZoneService.getStats).mockResolvedValue({
@@ -89,7 +92,7 @@ describe('ZonePageClient', () => {
it('loads the overview by stable ID and exposes all tabs including empty domains', async () => {
vi.mocked(ZoneService.getOverview).mockImplementation(async () => ({
zone: {id: 42, domain: 'arctel.de', created_at: '', updated_at: ''},
zone: {id: 42, domain: 'example.com', created_at: '', updated_at: ''},
domains: [],
}));
@@ -98,7 +101,7 @@ describe('ZonePageClient', () => {
await waitFor(() => {
expect(ZoneService.getOverview).toHaveBeenCalledWith(42);
});
expect(await screen.findByRole('heading', {name: 'arctel.de'})).toBeVisible();
expect(await screen.findByRole('heading', {name: 'example.com'})).toBeVisible();
expect(await screen.findByText('唯一访问者')).toBeVisible();
expect(screen.getByText('请求总数')).toBeVisible();
expect(screen.getByText('已提供的数据总计')).toBeVisible();
@@ -108,6 +111,20 @@ describe('ZonePageClient', () => {
expect(screen.getByRole('tab', {name: '设置'})).toBeVisible();
});
it('uses the browser pathname ID when serving a static-export fallback shell', async () => {
vi.mocked(ZoneService.getOverview).mockImplementation(async () => ({
zone: {id: 42, domain: 'example.com', created_at: '', updated_at: ''},
domains: [],
}));
renderPage(42, 1);
await waitFor(() => {
expect(ZoneService.getOverview).toHaveBeenCalledWith(42);
});
expect(ZoneService.getOverview).not.toHaveBeenCalledWith(1);
});
it('renders a not-found state for a missing Zone', async () => {
vi.mocked(ZoneService.getOverview).mockRejectedValue(new Error('Zone 不存在'));
+10 -1
View File
@@ -101,7 +101,16 @@ func init() {
}
}
// 4. 单页应用(SPA)前端路由兜底:返回 index.html
// 4. Next.js static export dynamic route fallback. Runtime IDs cannot be
// enumerated at build time, so serve the generated route shell instead of
// falling back to the dashboard index.html.
if fallbackPath, ok := resolveNextExportDynamicFallback(subFS, cleanPath); ok {
if serveFileDirect(c, subFS, fallbackPath) {
return
}
}
// 5. 单页应用(SPA)前端路由兜底:返回 index.html
if serveFileDirect(c, subFS, "index.html") {
return
}
+34
View File
@@ -0,0 +1,34 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package root
import (
"io/fs"
"strings"
)
//nolint:unused // Used by frontend.go in embed_frontend builds; default lint runs without that tag.
func resolveNextExportDynamicFallback(subFS fs.FS, cleanPath string) (string, bool) {
parts := strings.Split(cleanPath, "/")
if len(parts) < 2 || parts[0] != "websites" || parts[1] == "" {
return "", false
}
var templatePath string
switch {
case len(parts) == 2 && !strings.Contains(parts[1], "."):
templatePath = "websites/1.html"
case len(parts) == 2 && strings.HasSuffix(parts[1], ".txt"):
templatePath = "websites/1.txt"
case len(parts) == 3 && parts[2] != "" && strings.HasPrefix(parts[2], "__next.") && strings.HasSuffix(parts[2], ".txt"):
templatePath = "websites/1/" + parts[2]
default:
return "", false
}
if _, err := fs.Stat(subFS, templatePath); err != nil {
return "", false
}
return templatePath, true
}
@@ -0,0 +1,74 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package root
import (
"testing"
"testing/fstest"
)
func TestResolveNextExportDynamicFallbackUsesZoneTemplate(t *testing.T) {
subFS := fstest.MapFS{
"index.html": &fstest.MapFile{Data: []byte("dashboard")},
"websites/1.html": &fstest.MapFile{Data: []byte("zone detail")},
"websites/1.txt": &fstest.MapFile{Data: []byte("zone flight")},
"websites/1/__next.!KG1haW4p.websites.$d$zoneId.__PAGE__.txt": &fstest.MapFile{Data: []byte("zone segment")},
}
tests := []struct {
name string
input string
want string
}{
{name: "html", input: "websites/3", want: "websites/1.html"},
{name: "route payload", input: "websites/3.txt", want: "websites/1.txt"},
{
name: "segment payload",
input: "websites/3/__next.!KG1haW4p.websites.$d$zoneId.__PAGE__.txt",
want: "websites/1/__next.!KG1haW4p.websites.$d$zoneId.__PAGE__.txt",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok := resolveNextExportDynamicFallback(subFS, tt.input)
if !ok {
t.Fatal("expected dynamic websites route fallback")
}
if got != tt.want {
t.Fatalf("expected %q fallback, got %q", tt.want, got)
}
})
}
}
func TestResolveNextExportDynamicFallbackRejectsNestedOrAssetPath(t *testing.T) {
subFS := fstest.MapFS{
"websites/1.html": &fstest.MapFile{Data: []byte("zone detail")},
}
tests := []string{
"websites",
"websites/3/settings",
"websites/3.js",
"websites/3/",
"websites/3/missing.txt",
}
for _, tt := range tests {
t.Run(tt, func(t *testing.T) {
if got, ok := resolveNextExportDynamicFallback(subFS, tt); ok {
t.Fatalf("expected no fallback, got %q", got)
}
})
}
}
func TestResolveNextExportDynamicFallbackRequiresGeneratedTemplate(t *testing.T) {
subFS := fstest.MapFS{
"index.html": &fstest.MapFile{Data: []byte("dashboard")},
}
if got, ok := resolveNextExportDynamicFallback(subFS, "websites/3"); ok {
t.Fatalf("expected no fallback without generated template, got %q", got)
}
}