refactor(frontend): unify error pages into responses page and remove error-pages route

This commit is contained in:
ryan
2026-08-08 20:39:51 +08:00
parent 074edf17a1
commit 8758f9a061
13 changed files with 255 additions and 710 deletions
+2 -1
View File
@@ -14,7 +14,8 @@ export default defineConfig({
'components/**',
'snippets/**',
'plan/**',
'guideline/**'
'guideline/**',
'superpowers/**'
],
markdown: {
+4
View File
@@ -26,6 +26,10 @@ sidebar: false
- 支持 Service Worker 离线兜底:为启用 HTTPS 的网站下发 Service Worker 并缓存离线联系页,域名无法访问时浏览器展示联系站长页面,减少用户流失。可指定生效域名范围(仅对选中的 HTTPS 域名生效),配置位于「响应页面」-「联系页」,可在版本发布中批量生效。
### 改进
- 响应页面统一:将源站错误页与 Service Worker 离线兜底联系页整合至统一的「响应页面」(`/responses`)标签页中,移除原 `/error-pages` 独立路由。
## [v3.4.5] - 2026-08-08
### 改进
@@ -546,7 +546,7 @@ function parseDomains(raw: string | undefined): string[] {
- 无橙云 Switch、无 Cloudflare 依赖。
- 数据源为 `{ zoneDomain: string; domains: { domain: string }[] }` 分组(zone 根域并入)。
- 预勾选:打开时以当前已生效域名初始化 `selected`(Set<string>)。
- 预勾选:打开时以当前已生效域名初始化 `selected`(`Set<string>`)。
- 确认回调 `onSubmit([...selected])`(域名字符串数组)。
组件骨架(沿用 member-add-dialog 的 Dialog 结构,`sw` 前缀类名无冲突):
@@ -1,70 +0,0 @@
'use client';
import type { ReactNode } from 'react';
import { FileWarning } from 'lucide-react';
import type { UseQueryResult } from '@tanstack/react-query';
import { useAuth } from '@/components/providers/auth-provider';
import { EmptyStateWithBorder } from '@/components/layout/empty';
import { ErrorInline } from '@/components/layout/error';
import { LoadingStateWithBorder } from '@/components/layout/loading';
type ErrorPageGateProps = {
optionsQuery: UseQueryResult<Array<{ key: string; value: string }>, Error>;
children: ReactNode;
};
export function ErrorPageGate({ optionsQuery, children }: ErrorPageGateProps) {
const { user, loading: authLoading } = useAuth();
if (authLoading) {
return (
<div className='py-6 px-1'>
<LoadingStateWithBorder
icon={FileWarning}
description='加载权限信息...'
/>
</div>
);
}
if (!user?.is_admin) {
return (
<div className='py-6 px-1'>
<EmptyStateWithBorder
icon={FileWarning}
title='权限不足'
description='只有管理员可以访问源站错误页设置。'
/>
</div>
);
}
if (optionsQuery.isLoading) {
return (
<div className='py-6 px-1'>
<LoadingStateWithBorder
icon={FileWarning}
description='加载错误页配置...'
/>
</div>
);
}
if (optionsQuery.isError) {
return (
<div className='py-6 px-1'>
<ErrorInline
message={
optionsQuery.error instanceof Error
? optionsQuery.error.message
: '加载失败'
}
onRetry={() => void optionsQuery.refetch()}
/>
</div>
);
}
return <>{children}</>;
}
@@ -1,77 +0,0 @@
import { ORIGIN_ERROR_PAGE_HTML_MAX_BYTES } from '@/lib/openflare/default-origin-error-page-html';
import {
DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS,
parseStatusCodeTagsJSON,
validateStatusCodeTags,
} from '@/lib/openflare/status-code-tags';
export const OPTIONS_QUERY_KEY = ['openflare', 'options'] as const;
export const KEY_ENABLED = 'origin_error_page_enabled';
export const KEY_STATUS_CODES = 'origin_error_page_status_codes';
export const KEY_HTML = 'origin_error_page_html';
export const KEY_GET_ONLY = 'origin_error_page_get_only';
export type ErrorPageFields = {
enabled: boolean;
getOnly: boolean;
statusCodes: string[];
html: string;
};
export const defaultErrorPageFields: ErrorPageFields = {
enabled: true,
getOnly: false,
statusCodes: [...DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS],
html: '',
};
export function optionsToMap(options: Array<{ key: string; value: string }>) {
return options.reduce<Record<string, string>>((acc, option) => {
acc[option.key] = option.value;
return acc;
}, {});
}
export function mapOptionsToFields(
optionMap: Record<string, string>,
): ErrorPageFields {
const enabledRaw = optionMap[KEY_ENABLED];
const getOnlyRaw = optionMap[KEY_GET_ONLY];
return {
enabled: enabledRaw === undefined ? true : enabledRaw === 'true',
getOnly: getOnlyRaw === undefined ? false : getOnlyRaw === 'true',
statusCodes: parseStatusCodeTagsJSON(optionMap[KEY_STATUS_CODES]),
html: optionMap[KEY_HTML] ?? '',
};
}
export function validateErrorPageFields(fields: ErrorPageFields) {
validateStatusCodeTags(fields.statusCodes);
validateErrorPageHTML(fields.html);
}
export function validateErrorPageHTML(html: string) {
const htmlBytes = new TextEncoder().encode(html).length;
if (htmlBytes > ORIGIN_ERROR_PAGE_HTML_MAX_BYTES) {
throw new Error(
`HTML 超过最大长度限制(${ORIGIN_ERROR_PAGE_HTML_MAX_BYTES} 字节)`,
);
}
}
export async function invalidateErrorPageQueries(queryClient: {
invalidateQueries: (opts: {
queryKey: readonly unknown[];
}) => Promise<unknown>;
}) {
await Promise.all([
queryClient.invalidateQueries({ queryKey: OPTIONS_QUERY_KEY }),
queryClient.invalidateQueries({
queryKey: ['openflare', 'config-preview'],
}),
queryClient.invalidateQueries({
queryKey: ['openflare', 'config-versions'],
}),
]);
}
@@ -1,204 +0,0 @@
'use client';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
ArrowLeft,
FileCode2,
Loader2,
RotateCcw,
Save,
Sparkles,
} from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@/components/providers/auth-provider';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import {
DEFAULT_ORIGIN_ERROR_PAGE_TEMPLATE_ID,
getOriginErrorPageTemplate,
ORIGIN_ERROR_PAGE_TEMPLATES,
} from '@/lib/openflare/origin-error-page-templates';
import { OptionService } from '@/lib/services/openflare';
import { HtmlEditorWorkspace } from '@/components/common/html-editor-workspace';
import { ErrorPageGate } from '../components/error-page-gate';
import {
invalidateErrorPageQueries,
KEY_HTML,
mapOptionsToFields,
OPTIONS_QUERY_KEY,
optionsToMap,
validateErrorPageHTML,
} from '../components/shared';
export default function ErrorPageEditPage() {
const { user } = useAuth();
const queryClient = useQueryClient();
const [html, setHtml] = useState('');
const [restoreOpen, setRestoreOpen] = useState(false);
const [templateId, setTemplateId] = useState(
DEFAULT_ORIGIN_ERROR_PAGE_TEMPLATE_ID,
);
const optionsQuery = useQuery({
queryKey: OPTIONS_QUERY_KEY,
queryFn: () => OptionService.list(),
enabled: !!user?.is_admin,
});
useEffect(() => {
if (!optionsQuery.data) return;
setHtml(mapOptionsToFields(optionsToMap(optionsQuery.data)).html);
}, [optionsQuery.data]);
const saveMutation = useMutation({
mutationFn: async () => {
validateErrorPageHTML(html);
await OptionService.updateBatch([{ key: KEY_HTML, value: html }]);
},
onSuccess: async () => {
toast.success('HTML 模板已保存,请前往版本发布使配置生效');
await invalidateErrorPageQueries(queryClient);
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : '保存失败');
},
});
const loadSelectedTemplate = () => {
const tmpl = getOriginErrorPageTemplate(templateId);
if (!tmpl) {
toast.error('未找到所选模板');
return;
}
setHtml(tmpl.html);
toast.success(`已加载模板「${tmpl.name}」到编辑器`);
};
const restoreDefault = () => {
setHtml('');
setRestoreOpen(false);
toast.success('已清空为使用服务端内置默认模板(需保存后生效)');
};
return (
<ErrorPageGate optionsQuery={optionsQuery}>
<div className='flex flex-col gap-4 py-6 px-1'>
<div className='flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between'>
<div className='flex items-center gap-3'>
<Button variant='outline' size='icon' className='h-8 w-8' asChild>
<Link href='/error-pages' aria-label='返回错误页'>
<ArrowLeft className='size-4' />
</Link>
</Button>
<div className='flex items-center gap-2'>
<FileCode2 className='size-5 text-primary' />
<div>
<h1 className='text-2xl font-semibold tracking-tight'>编辑</h1>
</div>
</div>
</div>
</div>
<HtmlEditorWorkspace
value={html}
onChange={setHtml}
toolbarRight={
<>
<div className='flex items-center gap-1.5'>
<span className='text-[11px] text-muted-foreground hidden sm:inline'>
内置模板
</span>
<Select value={templateId} onValueChange={setTemplateId}>
<SelectTrigger className='h-7 w-[160px] text-[11px] bg-background'>
<SelectValue placeholder='选择模板' />
</SelectTrigger>
<SelectContent>
{ORIGIN_ERROR_PAGE_TEMPLATES.map((tmpl) => (
<SelectItem
key={tmpl.id}
value={tmpl.id}
className='text-xs'
>
{tmpl.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Button
type='button'
variant='ghost'
size='sm'
className='h-7 px-2 text-[11px]'
onClick={loadSelectedTemplate}
>
<Sparkles className='size-3.5' />
加载模板
</Button>
</div>
<Button
type='button'
variant='ghost'
size='sm'
className='h-7 px-2 text-[11px]'
onClick={() => setRestoreOpen(true)}
>
<RotateCcw className='size-3.5' />
恢复默认
</Button>
<Button
size='sm'
className='h-7 px-3 text-[11px]'
disabled={saveMutation.isPending}
onClick={() => saveMutation.mutate()}
>
{saveMutation.isPending ? (
<Loader2 className='size-3 animate-spin' />
) : (
<Save className='size-3' />
)}
保存
</Button>
</>
}
/>
</div>
<AlertDialog open={restoreOpen} onOpenChange={setRestoreOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>恢复默认 HTML?</AlertDialogTitle>
<AlertDialogDescription>
将清空编辑器内容,保存后使用服务端内置默认模板。此操作不会自动保存。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction onClick={restoreDefault}>
确认恢复
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</ErrorPageGate>
);
}
-236
View File
@@ -1,236 +0,0 @@
'use client';
import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Expand, FileWarning, Loader2, Pencil, Save } from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@/components/providers/auth-provider';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { TagsInput } from '@/components/ui/tags-input';
import { previewOriginErrorPageHTML } from '@/lib/openflare/default-origin-error-page-html';
import {
validateStatusCodeTagMessage,
validateStatusCodeTags,
} from '@/lib/openflare/status-code-tags';
import { OptionService } from '@/lib/services/openflare';
import { ErrorPageGate } from './components/error-page-gate';
import {
defaultErrorPageFields,
invalidateErrorPageQueries,
KEY_ENABLED,
KEY_GET_ONLY,
KEY_STATUS_CODES,
mapOptionsToFields,
OPTIONS_QUERY_KEY,
optionsToMap,
type ErrorPageFields,
} from './components/shared';
export default function ErrorPagesPage() {
const { user } = useAuth();
const queryClient = useQueryClient();
const [fields, setFields] = useState<ErrorPageFields>(defaultErrorPageFields);
const [tagError, setTagError] = useState<string | null>(null);
const optionsQuery = useQuery({
queryKey: OPTIONS_QUERY_KEY,
queryFn: () => OptionService.list(),
enabled: !!user?.is_admin,
});
useEffect(() => {
if (!optionsQuery.data) return;
setFields(mapOptionsToFields(optionsToMap(optionsQuery.data)));
setTagError(null);
}, [optionsQuery.data]);
const previewSrcDoc = useMemo(
() => previewOriginErrorPageHTML(fields.html),
[fields.html],
);
/** 仅保存策略项(HTML 在编辑页单独保存) */
const savePolicyMutation = useMutation({
mutationFn: async () => {
validateStatusCodeTags(fields.statusCodes);
await OptionService.updateBatch([
{ key: KEY_ENABLED, value: String(fields.enabled) },
{ key: KEY_GET_ONLY, value: String(fields.getOnly) },
{
key: KEY_STATUS_CODES,
value: JSON.stringify(fields.statusCodes),
},
]);
},
onSuccess: async () => {
toast.success('触发策略已保存,请前往版本发布使配置生效');
await invalidateErrorPageQueries(queryClient);
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : '保存失败');
},
});
const handleValidateTag = (tag: string) => {
const message = validateStatusCodeTagMessage(tag);
if (message) {
setTagError(message);
toast.error(message);
return message;
}
setTagError(null);
return null;
};
return (
<ErrorPageGate optionsQuery={optionsQuery}>
<div className='flex flex-col gap-6 py-6 px-1'>
<div className='flex items-center gap-2'>
<FileWarning className='size-5 text-primary' />
<div>
<h1 className='text-2xl font-semibold tracking-tight'>错误页</h1>
<p className='text-sm text-muted-foreground'>
配置源站/网关错误响应时的统一 HTML
页面。策略与模板保存后需发布配置版本后生效。
</p>
</div>
</div>
<Card className='border-dashed shadow-none'>
<CardHeader className='flex flex-row items-start justify-between gap-4 space-y-0'>
<div className='space-y-1.5'>
<CardTitle className='text-base'>触发策略</CardTitle>
<CardDescription>
配置源站错误页的启用条件与触发状态码。修改后需点击保存。
</CardDescription>
</div>
<Button
size='sm'
className='shrink-0'
disabled={savePolicyMutation.isPending}
onClick={() => savePolicyMutation.mutate()}
>
{savePolicyMutation.isPending ? (
<Loader2 className='size-3.5 animate-spin' />
) : (
<Save className='size-3.5' />
)}
保存
</Button>
</CardHeader>
<CardContent className='space-y-0 divide-y'>
<div className='flex items-start justify-between gap-6 pb-5'>
<div className='space-y-1'>
<Label className='text-sm font-medium'>启用源站错误页</Label>
<p className='text-sm text-muted-foreground'>
关闭后会透传源站或 Nginx 默认错误响应。
</p>
</div>
<Switch
checked={fields.enabled}
onCheckedChange={(enabled) =>
setFields((prev) => ({ ...prev, enabled }))
}
aria-label='启用源站错误页'
className='mt-0.5 shrink-0'
/>
</div>
<div className='flex items-start justify-between gap-6 py-5'>
<div className='space-y-1'>
<Label className='text-sm font-medium'>仅针对 GET 请求</Label>
<p className='text-sm text-muted-foreground'>
开启后仅对 GET 请求的匹配错误状态码返回自定义错误页;POST/PUT
等其它方法直接透传源站响应。
</p>
</div>
<Switch
checked={fields.getOnly}
disabled={!fields.enabled}
onCheckedChange={(getOnly) =>
setFields((prev) => ({ ...prev, getOnly }))
}
aria-label='仅针对 GET 请求'
className='mt-0.5 shrink-0'
/>
</div>
<div className='flex flex-col gap-3 pt-5'>
<div className='space-y-1'>
<Label
htmlFor='origin-error-status-codes'
className='text-sm font-medium'
>
触发状态码
</Label>
<p className='text-sm text-muted-foreground'>
支持单码(如 502)或闭区间(如 500-599),范围 400–599。默认
500-599。
</p>
</div>
<TagsInput
id='origin-error-status-codes'
value={fields.statusCodes}
onChange={(statusCodes) => {
setFields((prev) => ({ ...prev, statusCodes }));
setTagError(null);
}}
validateTag={handleValidateTag}
placeholder='例如 502 或 500-599,回车添加'
aria-invalid={!!tagError}
disabled={!fields.enabled}
/>
{tagError ? (
<p className='text-xs text-destructive'>{tagError}</p>
) : null}
</div>
</CardContent>
</Card>
<Card className='border-dashed shadow-none overflow-hidden'>
<CardHeader className='flex flex-row items-start justify-between gap-3 space-y-0'>
<div className='space-y-1.5'>
<CardTitle className='text-base'>页面预览</CardTitle>
</div>
<div className='flex shrink-0 flex-wrap gap-2'>
<Button variant='outline' size='sm' asChild>
<Link href='/error-pages/preview'>
<Expand className='size-3.5' />
预览
</Link>
</Button>
<Button size='sm' asChild>
<Link href='/error-pages/edit'>
<Pencil className='size-3.5' />
编辑
</Link>
</Button>
</div>
</CardHeader>
<CardContent>
<div className='overflow-hidden rounded-md border bg-muted/30'>
<iframe
title='源站错误页预览'
sandbox=''
srcDoc={previewSrcDoc}
className='h-[32rem] w-full bg-background'
/>
</div>
</CardContent>
</Card>
</div>
</ErrorPageGate>
);
}
@@ -1,79 +0,0 @@
'use client';
import Link from 'next/link';
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ArrowLeft, Pencil, X } from 'lucide-react';
import { useAuth } from '@/components/providers/auth-provider';
import { Button } from '@/components/ui/button';
import { previewOriginErrorPageHTML } from '@/lib/openflare/default-origin-error-page-html';
import { OptionService } from '@/lib/services/openflare';
import { ErrorPageGate } from '../components/error-page-gate';
import {
mapOptionsToFields,
OPTIONS_QUERY_KEY,
optionsToMap,
} from '../components/shared';
/**
* 全屏「真实预览」:覆盖主布局,按访客视角展示替换后的 HTML。
*/
export default function ErrorPagePreviewPage() {
const { user } = useAuth();
const optionsQuery = useQuery({
queryKey: OPTIONS_QUERY_KEY,
queryFn: () => OptionService.list(),
enabled: !!user?.is_admin,
});
const html = useMemo(() => {
if (!optionsQuery.data) return '';
return mapOptionsToFields(optionsToMap(optionsQuery.data)).html;
}, [optionsQuery.data]);
const previewSrcDoc = useMemo(() => previewOriginErrorPageHTML(html), [html]);
return (
<ErrorPageGate optionsQuery={optionsQuery}>
<div className='fixed inset-0 z-50 flex flex-col bg-background'>
<div className='flex items-center justify-between gap-3 border-b bg-background/95 px-4 py-2 backdrop-blur shrink-0'>
<div className='flex items-center gap-2 min-w-0'>
<Button variant='outline' size='icon' className='h-8 w-8' asChild>
<Link href='/error-pages' aria-label='返回错误页'>
<ArrowLeft className='size-4' />
</Link>
</Button>
<div className='min-w-0'>
<p className='text-sm font-semibold truncate'>错误页真实预览</p>
<p className='text-[11px] text-muted-foreground font-mono truncate'>
{'{{status}}'}→502 · {'{{host}}'}→example.com · 全屏展示
</p>
</div>
</div>
<div className='flex items-center gap-2 shrink-0'>
<Button variant='outline' size='sm' asChild>
<Link href='/error-pages/edit'>
<Pencil className='size-3.5' />
编辑
</Link>
</Button>
<Button variant='ghost' size='icon' className='h-8 w-8' asChild>
<Link href='/error-pages' aria-label='关闭预览'>
<X className='size-4' />
</Link>
</Button>
</div>
</div>
<iframe
title='源站错误页真实预览'
sandbox=''
srcDoc={previewSrcDoc}
className='flex-1 w-full border-0 bg-background min-h-0'
/>
</div>
</ErrorPageGate>
);
}
@@ -0,0 +1,198 @@
'use client';
import { useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Loader2, Save } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { TagsInput } from '@/components/ui/tags-input';
import { HtmlEditorWorkspace } from '@/components/common/html-editor-workspace';
import { previewOriginErrorPageHTML } from '@/lib/openflare/default-origin-error-page-html';
import {
validateStatusCodeTagMessage,
validateStatusCodeTags,
} from '@/lib/openflare/status-code-tags';
import { OptionService } from '@/lib/services/openflare';
import { cn } from '@/lib/utils';
import {
defaultErrorPageFields,
invalidateResponseQueries,
KEY_ENABLED,
KEY_GET_ONLY,
KEY_HTML,
KEY_STATUS_CODES,
mapOptionsToErrorFields,
type ErrorPageFields,
} from './shared';
export function ErrorPageTab({
optionMap,
}: {
optionMap: Record<string, string>;
}) {
const queryClient = useQueryClient();
const [fields, setFields] = useState<ErrorPageFields>(
defaultErrorPageFields,
);
const [tagError, setTagError] = useState<string | null>(null);
useEffect(() => {
setFields(mapOptionsToErrorFields(optionMap));
setTagError(null);
}, [optionMap]);
const saveMutation = useMutation({
mutationFn: async () => {
validateStatusCodeTags(fields.statusCodes);
await OptionService.updateBatch([
{ key: KEY_ENABLED, value: String(fields.enabled) },
{ key: KEY_GET_ONLY, value: String(fields.getOnly) },
{
key: KEY_STATUS_CODES,
value: JSON.stringify(fields.statusCodes),
},
{ key: KEY_HTML, value: fields.html },
]);
},
onSuccess: async () => {
toast.success('源站错误页已保存,请前往版本发布使配置生效');
await invalidateResponseQueries(queryClient);
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : '保存失败');
},
});
const handleValidateTag = (tag: string) => {
const message = validateStatusCodeTagMessage(tag);
if (message) {
setTagError(message);
toast.error(message);
return message;
}
setTagError(null);
return null;
};
return (
<div className='space-y-6'>
<Card className='border-dashed shadow-none'>
<CardHeader className='flex flex-row items-start justify-between gap-4 space-y-0'>
<div className='space-y-1.5'>
<CardTitle className='text-base'>触发策略</CardTitle>
<CardDescription>
配置源站错误页的启用条件与触发状态码。修改后需点击保存。
</CardDescription>
</div>
<Button
size='sm'
className='shrink-0'
disabled={saveMutation.isPending}
onClick={() => saveMutation.mutate()}
>
{saveMutation.isPending ? (
<Loader2 className='size-3.5 animate-spin' />
) : (
<Save className='size-3.5' />
)}
保存
</Button>
</CardHeader>
<CardContent className='space-y-0 divide-y'>
<div className='flex items-start justify-between gap-6 pb-5'>
<div className='space-y-1'>
<Label className='text-sm font-medium'>启用源站错误页</Label>
<p className='text-sm text-muted-foreground'>
关闭后会透传源站或 Nginx 默认错误响应。
</p>
</div>
<Switch
checked={fields.enabled}
onCheckedChange={(enabled) =>
setFields((prev) => ({ ...prev, enabled }))
}
aria-label='启用源站错误页'
className='mt-0.5 shrink-0'
/>
</div>
<div className='flex items-start justify-between gap-6 py-5'>
<div className='space-y-1'>
<Label className='text-sm font-medium'>仅针对 GET 请求</Label>
<p className='text-sm text-muted-foreground'>
开启后仅对 GET 请求的匹配错误状态码返回自定义错误页;POST/PUT
等其它方法直接透传源站响应。
</p>
</div>
<Switch
checked={fields.getOnly}
disabled={!fields.enabled}
onCheckedChange={(getOnly) =>
setFields((prev) => ({ ...prev, getOnly }))
}
aria-label='仅针对 GET 请求'
className='mt-0.5 shrink-0'
/>
</div>
<div className='flex flex-col gap-3 pt-5'>
<div className='space-y-1'>
<Label
htmlFor='origin-error-status-codes'
className='text-sm font-medium'
>
触发状态码
</Label>
<p className='text-sm text-muted-foreground'>
支持单码(如 502)或闭区间(如 500-599),范围 400–599。默认
500-599。
</p>
</div>
<TagsInput
id='origin-error-status-codes'
value={fields.statusCodes}
onChange={(statusCodes) => {
setFields((prev) => ({ ...prev, statusCodes }));
setTagError(null);
}}
validateTag={handleValidateTag}
placeholder='例如 502 或 500-599,回车添加'
aria-invalid={!!tagError}
disabled={!fields.enabled}
/>
{tagError ? (
<p className='text-xs text-destructive'>{tagError}</p>
) : null}
</div>
</CardContent>
</Card>
<Card className='border-dashed shadow-none'>
<CardHeader>
<CardTitle className='text-base'>错误页 HTML</CardTitle>
<CardDescription>留空则使用内置默认模板。</CardDescription>
</CardHeader>
<CardContent
className={cn(!fields.enabled && 'pointer-events-none opacity-60')}
>
<HtmlEditorWorkspace
value={fields.html}
onChange={(v) => setFields((prev) => ({ ...prev, html: v }))}
preview={previewOriginErrorPageHTML}
/>
</CardContent>
</Card>
</div>
);
}
@@ -1,9 +1,33 @@
import {
DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS,
parseStatusCodeTagsJSON,
} from '@/lib/openflare/status-code-tags';
export const OPTIONS_QUERY_KEY = ['openflare', 'options'] as const;
export const KEY_ENABLED = 'origin_error_page_enabled';
export const KEY_STATUS_CODES = 'origin_error_page_status_codes';
export const KEY_HTML = 'origin_error_page_html';
export const KEY_GET_ONLY = 'origin_error_page_get_only';
export const KEY_SW_ENABLED = 'sw_offline_enabled';
export const KEY_SW_HTML = 'sw_offline_html';
export const KEY_SW_DOMAINS = 'sw_offline_domains';
export type ErrorPageFields = {
enabled: boolean;
getOnly: boolean;
statusCodes: string[];
html: string;
};
export const defaultErrorPageFields: ErrorPageFields = {
enabled: true,
getOnly: false,
statusCodes: [...DEFAULT_ORIGIN_ERROR_PAGE_STATUS_TAGS],
html: '',
};
export type ContactPageFields = {
enabled: boolean;
html: string;
@@ -35,6 +59,19 @@ function parseDomains(raw: string | undefined): string[] {
}
}
export function mapOptionsToErrorFields(
optionMap: Record<string, string>,
): ErrorPageFields {
const enabledRaw = optionMap[KEY_ENABLED];
const getOnlyRaw = optionMap[KEY_GET_ONLY];
return {
enabled: enabledRaw === undefined ? true : enabledRaw === 'true',
getOnly: getOnlyRaw === undefined ? false : getOnlyRaw === 'true',
statusCodes: parseStatusCodeTagsJSON(optionMap[KEY_STATUS_CODES]),
html: optionMap[KEY_HTML] ?? '',
};
}
export function mapOptionsToContactFields(
optionMap: Record<string, string>,
): ContactPageFields {
+4 -35
View File
@@ -1,26 +1,18 @@
'use client';
import Link from 'next/link';
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { FileWarning, MessageSquareText } from 'lucide-react';
import { MessageSquareText } from 'lucide-react';
import { EmptyStateWithBorder } from '@/components/layout/empty';
import { ErrorInline } from '@/components/layout/error';
import { LoadingStateWithBorder } from '@/components/layout/loading';
import { useAuth } from '@/components/providers/auth-provider';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { OptionService } from '@/lib/services/openflare';
import { ContactPageTab } from './components/contact-page-tab';
import { ErrorPageTab } from './components/error-page-tab';
import { OPTIONS_QUERY_KEY, optionsToMap } from './components/shared';
export default function ResponsesPage() {
@@ -117,31 +109,8 @@ export default function ResponsesPage() {
</TabsTrigger>
</TabsList>
<TabsContent
value='error'
className='space-y-4 focus-visible:outline-none'
>
<Card className='border-dashed shadow-none'>
<CardHeader className='flex flex-row items-start justify-between gap-4 space-y-0'>
<div className='space-y-1.5'>
<CardTitle className='text-base'>源站错误页</CardTitle>
<CardDescription>
配置源站/网关错误响应时的统一 HTML 页面与触发策略。
</CardDescription>
</div>
<Button size='sm' className='shrink-0' asChild>
<Link href='/error-pages'>
<FileWarning className='size-3.5' />
前往错误页设置
</Link>
</Button>
</CardHeader>
<CardContent>
<p className='text-sm text-muted-foreground'>
错误页的触发策略、模板编辑与页面预览仍在「错误页」页面维护。
</p>
</CardContent>
</Card>
<TabsContent value='error' className='focus-visible:outline-none'>
<ErrorPageTab optionMap={optionMap} />
</TabsContent>
<TabsContent value='contact' className='focus-visible:outline-none'>
+1 -1
View File
@@ -63,7 +63,7 @@ export const openflareWebsiteNavGroup: OpenFlareNavGroup = {
{
title: '响应页面',
url: '/responses',
childUrls: ['/error-pages', '/responses/contact'],
childUrls: ['/error-pages'],
},
],
};
+8 -6
View File
@@ -131,20 +131,22 @@ export const searchData: SearchItem[] = [
keywords: ['origin', '源站', '后端', 'backend', '服务器', '负载均衡'],
},
{
id: 'console-error-pages',
title: '错误页',
description: '配置源站错误状态码触发的统一 HTML 错误页',
url: '/error-pages',
id: 'console-responses',
title: '响应页面',
description: '配置源站错误页与离线兜底联系页',
url: '/responses',
category: 'page',
keywords: [
'响应页面',
'错误页',
'联系页',
'源站',
'502',
'503',
'5xx',
'Service Worker',
'离线兜底',
'error page',
'origin error',
'error_page',
],
},
{