mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-28 05:46:36 +08:00
feat(option): add sw offline
fix(openresty): scope sw injection per cert partition fix(lint): satisfy revive and biome format for sw offline feature docs: sw offline scope changelog fix(frontend): use scoped query key for sw scope zones fix(frontend): hide preview link in sw contact page editor feat(frontend): add sw scope domain picker and contact page fields refactor(frontend): generalize html editor workspace for reuse feat(openresty): scope sw offline injection by route domains feat(openresty): add sw offline domains snapshot field feat(option): add sw offline domains scope option docs: fill html editor workspace generalization detail docs: sw offline scope implementation plan docs: sw offline scope design test(openresty): assert single merged access block in sw enabled servers fix(openresty): restrict sw intercept to https server blocks fix(openresty): version sw offline cache by html content fix(agent): escape redir in sw challenge page to prevent xss fix(agent): return sw.runtime module table and add lua spec docs: sw offline fallback changelog fix(frontend): memoize option map to preserve unsaved contact page edits feat(frontend): add response pages module with contact page tab feat(agent): ship sw offline lua assets and placeholder substitution feat(config): wire sw offline options into config snapshot feat(openresty): render sw offline assets and challenge intercept feat(openresty): add sw offline ConfigSnapshot fields and placeholder feat(db): seed sw offline options feat(option): add sw offline config keys and validation docs: add service worker offline fallback implementation plan docs: adopt global-option pattern for SW offline fallback (matches origin error page) docs: unify offline contact page with error pages as response pages docs: service worker offline fallback design (issue #23)
This commit is contained in:
@@ -39,8 +39,8 @@ import {
|
||||
} 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 { HtmlEditorWorkspace } from '../components/html-editor-workspace';
|
||||
import {
|
||||
invalidateErrorPageQueries,
|
||||
KEY_HTML,
|
||||
|
||||
@@ -152,8 +152,7 @@ export default function ErrorPagesPage() {
|
||||
<div className='space-y-1'>
|
||||
<Label className='text-sm font-medium'>仅针对 GET 请求</Label>
|
||||
<p className='text-sm text-muted-foreground'>
|
||||
开启后仅对 GET
|
||||
请求的匹配错误状态码返回自定义错误页;POST/PUT
|
||||
开启后仅对 GET 请求的匹配错误状态码返回自定义错误页;POST/PUT
|
||||
等其它方法直接透传源站响应。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Loader2, Plus, Save, X } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
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 { HtmlEditorWorkspace } from '@/components/common/html-editor-workspace';
|
||||
import {
|
||||
OptionService,
|
||||
ZoneService,
|
||||
zoneQueryKey,
|
||||
} from '@/lib/services/openflare';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { ScopeDomainDialog } from './scope-domain-dialog';
|
||||
import {
|
||||
defaultContactPageFields,
|
||||
invalidateResponseQueries,
|
||||
KEY_SW_DOMAINS,
|
||||
KEY_SW_ENABLED,
|
||||
KEY_SW_HTML,
|
||||
mapOptionsToContactFields,
|
||||
type ContactPageFields,
|
||||
} from './shared';
|
||||
|
||||
export function ContactPageTab({
|
||||
optionMap,
|
||||
}: {
|
||||
optionMap: Record<string, string>;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const [fields, setFields] = useState<ContactPageFields>(
|
||||
defaultContactPageFields,
|
||||
);
|
||||
const [scopeOpen, setScopeOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setFields(mapOptionsToContactFields(optionMap));
|
||||
}, [optionMap]);
|
||||
|
||||
const zonesQuery = useQuery({
|
||||
queryKey: [...zoneQueryKey, 'sw-scope'],
|
||||
queryFn: async () => {
|
||||
const zones = await ZoneService.list();
|
||||
const overviews = await Promise.all(
|
||||
zones.map((zone) => ZoneService.getOverview(zone.id)),
|
||||
);
|
||||
return overviews.map((ov) => ({
|
||||
zoneDomain: ov.zone.domain,
|
||||
domains: [ov.zone.domain, ...ov.domains.map((d) => d.domain)],
|
||||
}));
|
||||
},
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
await OptionService.updateBatch([
|
||||
{ key: KEY_SW_ENABLED, value: String(fields.enabled) },
|
||||
{ key: KEY_SW_HTML, value: fields.html },
|
||||
{ key: KEY_SW_DOMAINS, value: JSON.stringify(fields.domains) },
|
||||
]);
|
||||
},
|
||||
onSuccess: async () => {
|
||||
toast.success('联系页已保存,请前往版本发布使配置生效');
|
||||
await invalidateResponseQueries(queryClient);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : '保存失败');
|
||||
},
|
||||
});
|
||||
|
||||
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>
|
||||
启用后给启用 HTTPS 的网站下发 Service
|
||||
Worker,域名被墙时浏览器从缓存展示此联系页。
|
||||
</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-4'>
|
||||
<div className='flex items-start justify-between gap-6'>
|
||||
<div className='space-y-1'>
|
||||
<Label className='text-sm font-medium'>
|
||||
启用 Service Worker 离线兜底
|
||||
</Label>
|
||||
<p className='text-sm text-muted-foreground'>
|
||||
仅对 HTTPS 网站生效;未启用的站点不受影响。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={fields.enabled}
|
||||
onCheckedChange={(enabled) =>
|
||||
setFields((prev) => ({ ...prev, enabled }))
|
||||
}
|
||||
aria-label='启用离线兜底'
|
||||
className='mt-0.5 shrink-0'
|
||||
/>
|
||||
</div>
|
||||
<div className='space-y-2'>
|
||||
<div className='flex items-center justify-between gap-3'>
|
||||
<div>
|
||||
<Label className='text-sm font-medium'>生效范围</Label>
|
||||
<p className='text-sm text-muted-foreground'>
|
||||
仅对选中的 HTTPS 域名生效;留空则不注入。
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type='button'
|
||||
size='sm'
|
||||
variant='outline'
|
||||
disabled={!fields.enabled || saveMutation.isPending}
|
||||
onClick={() => setScopeOpen(true)}
|
||||
>
|
||||
<Plus className='size-3.5' />
|
||||
添加域名
|
||||
</Button>
|
||||
</div>
|
||||
{fields.domains.length === 0 ? (
|
||||
<p className='text-sm text-muted-foreground'>
|
||||
{fields.enabled
|
||||
? '尚未选择生效域名,保存后不注入任何站点。'
|
||||
: '启用离线兜底后可选择生效域名。'}
|
||||
</p>
|
||||
) : (
|
||||
<div className='flex flex-wrap gap-2'>
|
||||
{fields.domains.map((domain) => (
|
||||
<Badge
|
||||
key={domain}
|
||||
variant='secondary'
|
||||
className='gap-1 font-normal'
|
||||
>
|
||||
{domain}
|
||||
<button
|
||||
type='button'
|
||||
className='hover:text-destructive'
|
||||
disabled={!fields.enabled}
|
||||
aria-label={`移除 ${domain}`}
|
||||
onClick={() =>
|
||||
setFields((prev) => ({
|
||||
...prev,
|
||||
domains: prev.domains.filter((d) => d !== domain),
|
||||
}))
|
||||
}
|
||||
>
|
||||
<X className='size-3' />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</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={(html) => html}
|
||||
footerHint={null}
|
||||
showPreviewLink={false}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ScopeDomainDialog
|
||||
open={scopeOpen}
|
||||
onOpenChange={setScopeOpen}
|
||||
zones={zonesQuery.data ?? []}
|
||||
selected={fields.domains}
|
||||
pending={saveMutation.isPending}
|
||||
onSubmit={(domains) => {
|
||||
setFields((prev) => ({ ...prev, domains }));
|
||||
setScopeOpen(false);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Check, ChevronDown, Search } from 'lucide-react';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type ScopeZoneGroup = {
|
||||
zoneDomain: string;
|
||||
domains: string[];
|
||||
};
|
||||
|
||||
export function ScopeDomainDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
zones,
|
||||
selected,
|
||||
pending,
|
||||
onSubmit,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
zones: ScopeZoneGroup[];
|
||||
selected: string[];
|
||||
pending: boolean;
|
||||
onSubmit: (domains: string[]) => void;
|
||||
}) {
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [selectedSet, setSelectedSet] = useState<Set<string>>(() => new Set());
|
||||
const [collapsedZones, setCollapsedZones] = useState<Set<string>>(
|
||||
() => new Set(),
|
||||
);
|
||||
|
||||
const selectedRef = useRef(selected);
|
||||
selectedRef.current = selected;
|
||||
const prevOpenRef = useRef(open);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && !prevOpenRef.current) {
|
||||
setKeyword('');
|
||||
setSelectedSet(new Set(selectedRef.current));
|
||||
setCollapsedZones(new Set());
|
||||
}
|
||||
prevOpenRef.current = open;
|
||||
}, [open]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const normalized = keyword.trim().toLowerCase();
|
||||
if (!normalized) return zones;
|
||||
return zones
|
||||
.map((group) => ({
|
||||
zoneDomain: group.zoneDomain,
|
||||
domains: group.domains.filter(
|
||||
(d) =>
|
||||
d.toLowerCase().includes(normalized) ||
|
||||
group.zoneDomain.toLowerCase().includes(normalized),
|
||||
),
|
||||
}))
|
||||
.filter((group) => group.domains.length > 0);
|
||||
}, [zones, keyword]);
|
||||
|
||||
const visibleDomains = useMemo(
|
||||
() => filtered.flatMap((group) => group.domains),
|
||||
[filtered],
|
||||
);
|
||||
const allVisibleSelected =
|
||||
visibleDomains.length > 0 &&
|
||||
visibleDomains.every((d) => selectedSet.has(d));
|
||||
|
||||
const toggleOne = (domain: string) => {
|
||||
setSelectedSet((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(domain)) next.delete(domain);
|
||||
else next.add(domain);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleGroup = (domains: string[]) => {
|
||||
setSelectedSet((prev) => {
|
||||
const next = new Set(prev);
|
||||
const allSelected = domains.every((d) => next.has(d));
|
||||
for (const d of domains) {
|
||||
if (allSelected) next.delete(d);
|
||||
else next.add(d);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleAllVisible = () => {
|
||||
setSelectedSet((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (allVisibleSelected) {
|
||||
for (const d of visibleDomains) next.delete(d);
|
||||
} else {
|
||||
for (const d of visibleDomains) next.add(d);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleCollapsed = (zoneDomain: string) => {
|
||||
setCollapsedZones((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(zoneDomain)) next.delete(zoneDomain);
|
||||
else next.add(zoneDomain);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className='sm:max-w-lg'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>选择生效域名</DialogTitle>
|
||||
<DialogDescription>
|
||||
仅对选中的 HTTPS 域名注入离线兜底;搜索筛选与批量勾选。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor='sw-scope-search'>域名</FieldLabel>
|
||||
<div className='space-y-2'>
|
||||
<div className='relative'>
|
||||
<Search className='pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground' />
|
||||
<Input
|
||||
id='sw-scope-search'
|
||||
value={keyword}
|
||||
onChange={(event) => setKeyword(event.target.value)}
|
||||
placeholder='搜索域名或顶级域…'
|
||||
className='pl-8'
|
||||
disabled={pending}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex flex-wrap items-center justify-between gap-2'>
|
||||
<div className='flex items-center gap-2 text-xs text-muted-foreground'>
|
||||
<Badge variant='secondary' className='font-normal'>
|
||||
已选 {selectedSet.size}
|
||||
</Badge>
|
||||
<span>可见 {visibleDomains.length}</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-1'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
className='h-7 text-xs'
|
||||
disabled={pending || visibleDomains.length === 0}
|
||||
onClick={toggleAllVisible}
|
||||
>
|
||||
{allVisibleSelected ? '取消全选' : '全选可见'}
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
className='h-7 text-xs'
|
||||
disabled={pending || selectedSet.size === 0}
|
||||
onClick={() => setSelectedSet(new Set())}
|
||||
>
|
||||
清空
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{zones.length === 0 ? (
|
||||
<div className='rounded-lg border border-dashed px-4 py-8 text-center text-sm text-muted-foreground'>
|
||||
暂无可用域名,请先在 Zone 管理中注册域名。
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div className='rounded-lg border border-dashed px-4 py-8 text-center text-sm text-muted-foreground'>
|
||||
没有匹配的域名
|
||||
</div>
|
||||
) : (
|
||||
<div className='max-h-72 space-y-1 overflow-y-auto rounded-lg border p-2'>
|
||||
{filtered.map((group) => {
|
||||
const groupSelected = group.domains.filter((d) =>
|
||||
selectedSet.has(d),
|
||||
);
|
||||
const allSelected =
|
||||
groupSelected.length === group.domains.length;
|
||||
const someSelected =
|
||||
groupSelected.length > 0 && !allSelected;
|
||||
const open = !collapsedZones.has(group.zoneDomain);
|
||||
return (
|
||||
<Collapsible
|
||||
key={group.zoneDomain}
|
||||
open={open}
|
||||
onOpenChange={() => toggleCollapsed(group.zoneDomain)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-md',
|
||||
(allSelected || someSelected) && 'bg-muted/30',
|
||||
)}
|
||||
>
|
||||
<div className='flex items-center gap-1 px-1 py-0.5'>
|
||||
<Checkbox
|
||||
checked={
|
||||
allSelected
|
||||
? true
|
||||
: someSelected
|
||||
? 'indeterminate'
|
||||
: false
|
||||
}
|
||||
disabled={pending}
|
||||
onCheckedChange={() => toggleGroup(group.domains)}
|
||||
aria-label={`选择顶级域 ${group.zoneDomain}`}
|
||||
className='ml-1'
|
||||
/>
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
type='button'
|
||||
className='flex min-w-0 flex-1 items-center gap-2 rounded-md px-1.5 py-1.5 text-left text-sm font-medium hover:bg-muted/60'
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-4 shrink-0 text-muted-foreground transition-transform',
|
||||
!open && '-rotate-90',
|
||||
)}
|
||||
/>
|
||||
<span className='truncate'>
|
||||
{group.zoneDomain}
|
||||
</span>
|
||||
<Badge
|
||||
variant='outline'
|
||||
className='ml-auto shrink-0 font-normal text-[10px]'
|
||||
>
|
||||
{groupSelected.length}/{group.domains.length}
|
||||
</Badge>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
</div>
|
||||
<CollapsibleContent>
|
||||
<div className='ml-4 space-y-0.5 border-l border-border/70 py-0.5 pl-2'>
|
||||
{group.domains.map((domain) => {
|
||||
const checked = selectedSet.has(domain);
|
||||
const isApex = domain === group.zoneDomain;
|
||||
return (
|
||||
<label
|
||||
key={domain}
|
||||
className={cn(
|
||||
'flex cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 transition-colors hover:bg-muted/60',
|
||||
checked && 'bg-muted/40',
|
||||
)}
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
disabled={pending}
|
||||
onCheckedChange={() => toggleOne(domain)}
|
||||
/>
|
||||
<span className='min-w-0 flex-1 truncate text-sm'>
|
||||
{domain}
|
||||
</span>
|
||||
{isApex ? (
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='shrink-0 text-[10px] font-normal'
|
||||
>
|
||||
顶级域
|
||||
</Badge>
|
||||
) : null}
|
||||
{checked ? (
|
||||
<Check className='size-3.5 shrink-0 text-primary' />
|
||||
) : null}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</div>
|
||||
</Collapsible>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant='outline'
|
||||
disabled={pending}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
disabled={pending}
|
||||
onClick={() => onSubmit([...selectedSet].sort())}
|
||||
>
|
||||
确定
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
export const OPTIONS_QUERY_KEY = ['openflare', 'options'] as const;
|
||||
|
||||
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 ContactPageFields = {
|
||||
enabled: boolean;
|
||||
html: string;
|
||||
domains: string[];
|
||||
};
|
||||
|
||||
export const defaultContactPageFields: ContactPageFields = {
|
||||
enabled: false,
|
||||
html: '',
|
||||
domains: [],
|
||||
};
|
||||
|
||||
export function optionsToMap(options: Array<{ key: string; value: string }>) {
|
||||
return options.reduce<Record<string, string>>((acc, option) => {
|
||||
acc[option.key] = option.value;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function parseDomains(raw: string | undefined): string[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((item): item is string => typeof item === 'string')
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function mapOptionsToContactFields(
|
||||
optionMap: Record<string, string>,
|
||||
): ContactPageFields {
|
||||
return {
|
||||
enabled: optionMap[KEY_SW_ENABLED] === 'true',
|
||||
html: optionMap[KEY_SW_HTML] ?? '',
|
||||
domains: parseDomains(optionMap[KEY_SW_DOMAINS]),
|
||||
};
|
||||
}
|
||||
|
||||
export async function invalidateResponseQueries(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'],
|
||||
}),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
'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 { 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 { OPTIONS_QUERY_KEY, optionsToMap } from './components/shared';
|
||||
|
||||
export default function ResponsesPage() {
|
||||
const { user, loading: authLoading } = useAuth();
|
||||
const [activeTab, setActiveTab] = useState('error');
|
||||
|
||||
const optionsQuery = useQuery({
|
||||
queryKey: OPTIONS_QUERY_KEY,
|
||||
queryFn: () => OptionService.list(),
|
||||
enabled: !!user?.is_admin,
|
||||
});
|
||||
|
||||
const optionMap = useMemo(
|
||||
() => optionsToMap(optionsQuery.data ?? []),
|
||||
[optionsQuery.data],
|
||||
);
|
||||
|
||||
if (authLoading) {
|
||||
return (
|
||||
<div className='w-full py-6 px-1'>
|
||||
<LoadingStateWithBorder
|
||||
icon={MessageSquareText}
|
||||
description='加载权限信息...'
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user?.is_admin) {
|
||||
return (
|
||||
<div className='w-full py-6 px-1'>
|
||||
<EmptyStateWithBorder
|
||||
icon={MessageSquareText}
|
||||
title='权限不足'
|
||||
description='只有管理员可以访问响应页面设置。'
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (optionsQuery.isLoading) {
|
||||
return (
|
||||
<div className='w-full py-6 px-1'>
|
||||
<LoadingStateWithBorder
|
||||
icon={MessageSquareText}
|
||||
description='加载响应页面配置...'
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (optionsQuery.isError) {
|
||||
return (
|
||||
<div className='w-full py-6 px-1'>
|
||||
<ErrorInline
|
||||
message={
|
||||
optionsQuery.error instanceof Error
|
||||
? optionsQuery.error.message
|
||||
: '加载失败'
|
||||
}
|
||||
onRetry={() => void optionsQuery.refetch()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!optionsQuery.data) return null;
|
||||
|
||||
return (
|
||||
<div className='flex w-full flex-col gap-6 py-6 px-1'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<MessageSquareText className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>响应页面</h1>
|
||||
<p className='text-sm text-muted-foreground'>
|
||||
配置源站错误页与离线兜底联系页。保存后需发布配置版本后生效。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className='w-full'>
|
||||
<TabsList variant='line' className='mb-6 inline-flex w-fit gap-8'>
|
||||
<TabsTrigger
|
||||
value='error'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
错误页
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value='contact'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
联系页
|
||||
</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>
|
||||
|
||||
<TabsContent value='contact' className='focus-visible:outline-none'>
|
||||
<ContactPageTab optionMap={optionMap} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+32
-17
@@ -17,22 +17,33 @@ type HtmlEditorWorkspaceProps = {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
toolbarRight?: React.ReactNode;
|
||||
maxBytes?: number;
|
||||
preview?: (html: string) => string;
|
||||
footerHint?: React.ReactNode;
|
||||
showPreviewLink?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* SQL 查询终端同款工作区:整体边框 + 工具栏 + 可拖拽分隔;
|
||||
* 本页为左代码 / 右实时预览横向布局。
|
||||
* 通用 HTML 编辑器工作区:左代码 / 右实时预览横向布局,可拖拽分隔。
|
||||
*/
|
||||
export function HtmlEditorWorkspace({
|
||||
value,
|
||||
onChange,
|
||||
toolbarRight,
|
||||
maxBytes = ORIGIN_ERROR_PAGE_HTML_MAX_BYTES,
|
||||
preview = previewOriginErrorPageHTML,
|
||||
footerHint = (
|
||||
<>
|
||||
{'{{status}}'}→502 · {'{{host}}'}→example.com
|
||||
</>
|
||||
),
|
||||
showPreviewLink = true,
|
||||
}: HtmlEditorWorkspaceProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [editorWidthPercent, setEditorWidthPercent] = useState(48);
|
||||
const { resolvedTheme } = useTheme();
|
||||
const cmTheme = resolvedTheme === 'dark' ? 'dark' : 'light';
|
||||
const previewSrcDoc = previewOriginErrorPageHTML(value);
|
||||
const previewSrcDoc = preview(value);
|
||||
const htmlBytes = new TextEncoder().encode(value).length;
|
||||
|
||||
const handleMouseDown = (e: React.MouseEvent) => {
|
||||
@@ -68,7 +79,7 @@ export function HtmlEditorWorkspace({
|
||||
<Terminal className='size-4 text-primary shrink-0' />
|
||||
<span className='text-xs font-semibold'>HTML 编辑器</span>
|
||||
<span className='text-[11px] text-muted-foreground font-mono truncate'>
|
||||
{htmlBytes} / {ORIGIN_ERROR_PAGE_HTML_MAX_BYTES} 字节
|
||||
{htmlBytes} / {maxBytes} 字节
|
||||
{value.trim() === '' ? ' · 空则使用内置默认' : ''}
|
||||
</span>
|
||||
</div>
|
||||
@@ -112,20 +123,24 @@ export function HtmlEditorWorkspace({
|
||||
<div className='flex items-center justify-between px-4 py-1.5 border-b bg-muted/20 shrink-0 text-[11px] text-muted-foreground font-mono gap-2'>
|
||||
<span className='font-semibold'>实时预览</span>
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='hidden sm:inline'>
|
||||
{'{{status}}'}→502 · {'{{host}}'}→example.com
|
||||
</span>
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
className='h-6 px-2 text-[11px]'
|
||||
asChild
|
||||
<span
|
||||
className={footerHint === null ? 'hidden' : 'hidden sm:inline'}
|
||||
>
|
||||
<Link href='/error-pages/preview'>
|
||||
<Expand className='size-3' />
|
||||
真实预览
|
||||
</Link>
|
||||
</Button>
|
||||
{footerHint ?? null}
|
||||
</span>
|
||||
{showPreviewLink ? (
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
className='h-6 px-2 text-[11px]'
|
||||
asChild
|
||||
>
|
||||
<Link href='/error-pages/preview'>
|
||||
<Expand className='size-3' />
|
||||
真实预览
|
||||
</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex-1 min-h-0 overflow-hidden bg-background'>
|
||||
@@ -61,9 +61,9 @@ export const openflareWebsiteNavGroup: OpenFlareNavGroup = {
|
||||
},
|
||||
{ title: '源站地址', url: '/origins', childUrls: ['/origins/detail'] },
|
||||
{
|
||||
title: '错误页',
|
||||
url: '/error-pages',
|
||||
childUrls: ['/error-pages/edit', '/error-pages/preview'],
|
||||
title: '响应页面',
|
||||
url: '/responses',
|
||||
childUrls: ['/error-pages', '/responses/contact'],
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -120,7 +120,7 @@ export const openflareWebsiteSubNav = [
|
||||
{ title: '证书', url: '/certificates' },
|
||||
{ title: 'DNS 账号', url: '/dns-accounts' },
|
||||
{ title: 'Cloudflare', url: '/cloudflare' },
|
||||
{ title: '错误页', url: '/error-pages' },
|
||||
{ title: '响应页面', url: '/responses' },
|
||||
] as const;
|
||||
|
||||
const nonConsoleRoutePrefixes = [
|
||||
|
||||
Reference in New Issue
Block a user