✨ feat: Add server form component with protocol configuration and localization support
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const protocols = [
|
||||
'shadowsocks',
|
||||
'vmess',
|
||||
'vless',
|
||||
'trojan',
|
||||
'hysteria2',
|
||||
'tuic',
|
||||
'anytls',
|
||||
] as const;
|
||||
|
||||
const nullableString = z.string().nullish();
|
||||
const portScheme = z.number().max(65535).nullish();
|
||||
|
||||
const securityConfigScheme = z
|
||||
.object({
|
||||
sni: nullableString,
|
||||
allow_insecure: z.boolean().nullable().default(false),
|
||||
fingerprint: nullableString,
|
||||
reality_private_key: nullableString,
|
||||
reality_public_key: nullableString,
|
||||
reality_short_id: nullableString,
|
||||
reality_server_addr: nullableString,
|
||||
reality_server_port: portScheme,
|
||||
})
|
||||
.nullish();
|
||||
|
||||
const transportConfigScheme = z
|
||||
.object({
|
||||
path: nullableString,
|
||||
host: nullableString,
|
||||
service_name: nullableString,
|
||||
})
|
||||
.nullish();
|
||||
|
||||
const shadowsocksScheme = z.object({
|
||||
method: z.string(),
|
||||
port: portScheme,
|
||||
server_key: nullableString,
|
||||
});
|
||||
|
||||
const vmessScheme = z.object({
|
||||
port: portScheme,
|
||||
transport: z.string(),
|
||||
transport_config: transportConfigScheme,
|
||||
security: z.string(),
|
||||
security_config: securityConfigScheme,
|
||||
});
|
||||
|
||||
const vlessScheme = z.object({
|
||||
port: portScheme,
|
||||
transport: z.string(),
|
||||
transport_config: transportConfigScheme,
|
||||
security: z.string(),
|
||||
security_config: securityConfigScheme,
|
||||
flow: nullableString,
|
||||
});
|
||||
|
||||
const trojanScheme = z.object({
|
||||
port: portScheme,
|
||||
transport: z.string(),
|
||||
transport_config: transportConfigScheme,
|
||||
security: z.string(),
|
||||
security_config: securityConfigScheme,
|
||||
});
|
||||
|
||||
const hysteria2Scheme = z.object({
|
||||
port: portScheme,
|
||||
hop_ports: nullableString,
|
||||
hop_interval: z.number().nullish(),
|
||||
obfs_password: nullableString,
|
||||
security: z.string(),
|
||||
security_config: securityConfigScheme,
|
||||
});
|
||||
|
||||
const tuicScheme = z.object({
|
||||
port: portScheme,
|
||||
disable_sni: z.boolean().default(false),
|
||||
reduce_rtt: z.boolean().default(false),
|
||||
udp_relay_mode: z.string().default('native'),
|
||||
congestion_controller: z.string().default('bbr'),
|
||||
security_config: securityConfigScheme,
|
||||
});
|
||||
|
||||
const anytlsScheme = z.object({
|
||||
port: portScheme,
|
||||
security_config: securityConfigScheme,
|
||||
});
|
||||
|
||||
export const protocolConfigScheme = z.discriminatedUnion('protocol', [
|
||||
z.object({
|
||||
protocol: z.literal('shadowsocks'),
|
||||
enabled: z.boolean().default(false),
|
||||
config: shadowsocksScheme,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('vmess'),
|
||||
enabled: z.boolean().default(false),
|
||||
config: vmessScheme,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('vless'),
|
||||
enabled: z.boolean().default(false),
|
||||
config: vlessScheme,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('trojan'),
|
||||
enabled: z.boolean().default(false),
|
||||
config: trojanScheme,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('hysteria2'),
|
||||
enabled: z.boolean().default(false),
|
||||
config: hysteria2Scheme,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('tuic'),
|
||||
enabled: z.boolean().default(false),
|
||||
config: tuicScheme,
|
||||
}),
|
||||
z.object({
|
||||
protocol: z.literal('anytls'),
|
||||
enabled: z.boolean().default(false),
|
||||
config: anytlsScheme,
|
||||
}),
|
||||
]);
|
||||
|
||||
export const formScheme = z.object({
|
||||
name: z.string(),
|
||||
server_addr: z.string(),
|
||||
country: z.string().optional(),
|
||||
city: z.string().optional(),
|
||||
protocols: z.array(protocolConfigScheme).min(1),
|
||||
});
|
||||
|
||||
export function getProtocolDefaultConfig(proto: (typeof protocols)[number]) {
|
||||
switch (proto) {
|
||||
case 'shadowsocks':
|
||||
return { method: 'chacha20-ietf-poly1305', port: null, server_key: null };
|
||||
case 'vmess':
|
||||
return {
|
||||
port: null,
|
||||
transport: 'tcp',
|
||||
transport_config: null,
|
||||
security: 'none',
|
||||
security_config: null,
|
||||
};
|
||||
case 'vless':
|
||||
return {
|
||||
port: null,
|
||||
transport: 'tcp',
|
||||
transport_config: null,
|
||||
security: 'none',
|
||||
security_config: null,
|
||||
flow: null,
|
||||
};
|
||||
case 'trojan':
|
||||
return {
|
||||
port: null,
|
||||
transport: 'tcp',
|
||||
transport_config: null,
|
||||
security: 'tls',
|
||||
security_config: {},
|
||||
};
|
||||
case 'hysteria2':
|
||||
return {
|
||||
port: null,
|
||||
hop_ports: null,
|
||||
hop_interval: null,
|
||||
obfs_password: null,
|
||||
security: 'tls',
|
||||
security_config: {},
|
||||
};
|
||||
case 'tuic':
|
||||
return {
|
||||
port: null,
|
||||
disable_sni: false,
|
||||
reduce_rtt: false,
|
||||
udp_relay_mode: 'native',
|
||||
congestion_controller: 'bbr',
|
||||
security_config: {},
|
||||
};
|
||||
case 'anytls':
|
||||
return { port: null, security_config: {} };
|
||||
default:
|
||||
return {} as any;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
'use client';
|
||||
import { UserDetail } from '@/app/dashboard/user/user-detail';
|
||||
import { IpLink } from '@/components/ip-link';
|
||||
import { ProTable, ProTableActions } from '@/components/pro-table';
|
||||
import { getUserSubscribeById } from '@/services/admin/user';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Badge } from '@workspace/ui/components/badge';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Card, CardContent } from '@workspace/ui/components/card';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@workspace/ui/components/tooltip';
|
||||
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
|
||||
import { cn } from '@workspace/ui/lib/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import ServerConfig from './server-config';
|
||||
import ServerForm from './server-form';
|
||||
|
||||
type ProtocolName = 'shadowsocks' | 'vmess' | 'vless' | 'trojan' | 'hysteria2' | 'tuic' | 'anytls';
|
||||
type ProtocolEntry = { protocol: ProtocolName; enabled: boolean; config: Record<string, unknown> };
|
||||
|
||||
interface ServerFormFields {
|
||||
name: string;
|
||||
server_addr: string;
|
||||
country?: string;
|
||||
city?: string;
|
||||
protocols: ProtocolEntry[];
|
||||
}
|
||||
|
||||
type ServerStatus = {
|
||||
online?: unknown;
|
||||
cpu?: number;
|
||||
mem?: number;
|
||||
disk?: number;
|
||||
updated_at?: number;
|
||||
};
|
||||
|
||||
type ServerItem = ServerFormFields & { id: number; status?: ServerStatus; [key: string]: unknown };
|
||||
|
||||
const mockList: ServerItem[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Server A',
|
||||
server_addr: '1.1.1.1',
|
||||
country: 'US',
|
||||
city: 'SFO',
|
||||
protocols: [
|
||||
{
|
||||
protocol: 'shadowsocks',
|
||||
enabled: true,
|
||||
config: { method: 'aes-128-gcm', port: 443, server_key: null },
|
||||
},
|
||||
{
|
||||
protocol: 'trojan',
|
||||
enabled: true,
|
||||
config: { port: 8443, transport: 'tcp', security: 'tls' },
|
||||
},
|
||||
{
|
||||
protocol: 'vmess',
|
||||
enabled: false,
|
||||
config: {
|
||||
port: 1443,
|
||||
transport: 'websocket',
|
||||
transport_config: { path: '/ws', host: 'example.com' },
|
||||
security: 'tls',
|
||||
},
|
||||
},
|
||||
],
|
||||
status: {
|
||||
online: { 1001: ['1.2.3.4'], 1002: ['5.6.7.8', '9.9.9.9'] },
|
||||
cpu: 34,
|
||||
mem: 62,
|
||||
disk: 48,
|
||||
updated_at: Date.now() / 1000,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: 'Server B',
|
||||
server_addr: '2.2.2.2',
|
||||
country: 'JP',
|
||||
city: 'Tokyo',
|
||||
protocols: [
|
||||
{
|
||||
protocol: 'vmess',
|
||||
enabled: true,
|
||||
config: { port: 2443, transport: 'tcp', security: 'none' },
|
||||
},
|
||||
{
|
||||
protocol: 'hysteria2',
|
||||
enabled: true,
|
||||
config: { port: 3443, hop_ports: '443,8443,10443', hop_interval: 15, security: 'tls' },
|
||||
},
|
||||
{ protocol: 'tuic', enabled: false, config: { port: 4443 } },
|
||||
],
|
||||
status: {
|
||||
online: { 2001: ['10.0.0.1'] },
|
||||
cpu: 72,
|
||||
mem: 81,
|
||||
disk: 67,
|
||||
updated_at: Date.now() / 1000,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: 'Server C',
|
||||
server_addr: '3.3.3.3',
|
||||
country: 'DE',
|
||||
city: 'FRA',
|
||||
protocols: [
|
||||
{ protocol: 'anytls', enabled: true, config: { port: 80 } },
|
||||
{
|
||||
protocol: 'shadowsocks',
|
||||
enabled: false,
|
||||
config: { method: 'chacha20-ietf-poly1305', port: 8080 },
|
||||
},
|
||||
],
|
||||
status: { online: {}, cpu: 0, mem: 0, disk: 0, updated_at: 0 },
|
||||
},
|
||||
];
|
||||
|
||||
let mockData: ServerItem[] = [...mockList];
|
||||
const getServerList = async () => ({ list: mockData, total: mockData.length });
|
||||
const createServer = async (values: Omit<ServerItem, 'id'>) => {
|
||||
mockData.push({
|
||||
id: Date.now(),
|
||||
name: '',
|
||||
server_addr: '',
|
||||
protocols: [],
|
||||
...values,
|
||||
});
|
||||
return true;
|
||||
};
|
||||
const updateServer = async (id: number, values: Omit<ServerItem, 'id'>) => {
|
||||
mockData = mockData.map((i) => (i.id === id ? { ...i, ...values } : i));
|
||||
return true;
|
||||
};
|
||||
const deleteServer = async (id: number) => {
|
||||
mockData = mockData.filter((i) => i.id !== id);
|
||||
return true;
|
||||
};
|
||||
|
||||
const PROTOCOL_COLORS: Record<ProtocolName, string> = {
|
||||
shadowsocks: 'bg-green-500',
|
||||
vmess: 'bg-rose-500',
|
||||
vless: 'bg-blue-500',
|
||||
trojan: 'bg-yellow-500',
|
||||
hysteria2: 'bg-purple-500',
|
||||
tuic: 'bg-cyan-500',
|
||||
anytls: 'bg-gray-500',
|
||||
};
|
||||
|
||||
function getEnabledProtocols(p: ServerItem['protocols']) {
|
||||
return Array.isArray(p) ? p.filter((x) => x.enabled) : [];
|
||||
}
|
||||
|
||||
function ProtocolBadge({
|
||||
item,
|
||||
t,
|
||||
}: {
|
||||
item: ServerItem['protocols'][number];
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
const color = PROTOCOL_COLORS[item.protocol];
|
||||
const port = (item?.config as any)?.port as number | undefined;
|
||||
const extra: string[] = [];
|
||||
if ((item.config as any)?.transport) extra.push(String((item.config as any).transport));
|
||||
if ((item.config as any)?.security && (item.config as any).security !== 'none')
|
||||
extra.push(String((item.config as any).security));
|
||||
const label = `${item.protocol}${port ? ` (${port})` : ''}`;
|
||||
const tipParts = [label, extra.length ? `· ${extra.join(' / ')}` : ''].filter(Boolean);
|
||||
const tooltip = tipParts.join(' ');
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge variant='outline' className={cn('text-primary-foreground', color)}>
|
||||
{label}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{tooltip || t('notAvailable')}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function PctBar({ value }: { value: number }) {
|
||||
const v = Math.max(0, Math.min(100, Math.round(value)));
|
||||
return (
|
||||
<div className='min-w-24'>
|
||||
<div className='text-xs leading-none'>{v}%</div>
|
||||
<div className='bg-muted h-1.5 w-full rounded'>
|
||||
<div className='bg-primary h-1.5 rounded' style={{ width: `${v}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RegionIpCell({
|
||||
country,
|
||||
city,
|
||||
ip,
|
||||
t,
|
||||
}: {
|
||||
country?: string;
|
||||
city?: string;
|
||||
ip: string;
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
const region = [country, city].filter(Boolean).join(' / ') || t('notAvailable');
|
||||
return (
|
||||
<div className='flex items-center gap-1'>
|
||||
<Badge variant='outline'>{region}</Badge>
|
||||
<Badge variant='outline'>{ip}</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UserSubscribeInfo({
|
||||
userId,
|
||||
type,
|
||||
t,
|
||||
}: {
|
||||
userId: number;
|
||||
type: 'account' | 'subscribeName' | 'subscribeId' | 'traffic' | 'expireTime';
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
const { data } = useQuery({
|
||||
enabled: userId !== 0,
|
||||
queryKey: ['getUserSubscribeById', userId],
|
||||
queryFn: async () => {
|
||||
const { data } = await getUserSubscribeById({ id: userId });
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
if (!data) return <span className='text-muted-foreground'>--</span>;
|
||||
if (type === 'account')
|
||||
return data.user_id ? (
|
||||
<UserDetail id={data.user_id} />
|
||||
) : (
|
||||
<span className='text-muted-foreground'>--</span>
|
||||
);
|
||||
if (type === 'subscribeName')
|
||||
return data.subscribe?.name ? (
|
||||
<span className='text-sm'>{data.subscribe.name}</span>
|
||||
) : (
|
||||
<span className='text-muted-foreground'>--</span>
|
||||
);
|
||||
if (type === 'subscribeId')
|
||||
return data.id ? (
|
||||
<span className='font-mono text-sm'>{data.id}</span>
|
||||
) : (
|
||||
<span className='text-muted-foreground'>--</span>
|
||||
);
|
||||
if (type === 'traffic') {
|
||||
const used = (data.upload || 0) + (data.download || 0);
|
||||
const total = data.traffic || 0;
|
||||
return (
|
||||
<div className='min-w-0 text-sm'>{`${(used / 1024 ** 3).toFixed(2)} GB / ${total > 0 ? (total / 1024 ** 3).toFixed(2) + ' GB' : t('unlimited')}`}</div>
|
||||
);
|
||||
}
|
||||
if (type === 'expireTime') {
|
||||
if (!data.expire_time) return <span className='text-muted-foreground'>--</span>;
|
||||
const expired = data.expire_time < Date.now() / 1000;
|
||||
return (
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='text-sm'>{new Date((data.expire_time || 0) * 1000).toLocaleString()}</span>
|
||||
{expired && (
|
||||
<Badge variant='destructive' className='w-fit px-1 py-0 text-xs'>
|
||||
{t('expired')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <span className='text-muted-foreground'>--</span>;
|
||||
}
|
||||
|
||||
function normalizeOnlineMap(online: unknown): { uid: string; ips: string[] }[] {
|
||||
if (!online || typeof online !== 'object' || Array.isArray(online)) return [];
|
||||
const m = online as Record<string, unknown>;
|
||||
const rows = Object.entries(m).map(([uid, ips]) => {
|
||||
if (Array.isArray(ips)) return { uid, ips: (ips as unknown[]).map(String) };
|
||||
if (typeof ips === 'string') return { uid, ips: [ips] };
|
||||
const o = ips as Record<string, unknown>;
|
||||
if (Array.isArray(o?.ips)) return { uid, ips: (o.ips as unknown[]).map(String) };
|
||||
return { uid, ips: [] };
|
||||
});
|
||||
return rows.filter((r) => r.ips.length > 0);
|
||||
}
|
||||
|
||||
function OnlineUsersCell({ status, t }: { status?: ServerStatus; t: (key: string) => string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const rows = normalizeOnlineMap(status?.online);
|
||||
const count = rows.length;
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<button className='hover:text-foreground text-muted-foreground flex items-center gap-2 bg-transparent p-0 text-sm'>
|
||||
<Badge variant='secondary'>{count}</Badge>
|
||||
<span>{t('onlineUsers')}</span>
|
||||
</button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='sm:w=[900px] h-screen w-screen max-w-none sm:h-auto sm:max-w-[90vw]'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('onlineUsers')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className='-mx-6 h-[calc(100vh-48px-16px)] overflow-y-auto px-6 py-4 sm:h-[calc(100dvh-48px-16px-env(safe-area-inset-top))]'>
|
||||
<ProTable<
|
||||
{
|
||||
uid: string;
|
||||
ips: string[];
|
||||
},
|
||||
Record<string, unknown>
|
||||
>
|
||||
header={{ hidden: true }}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'ips',
|
||||
header: t('ipAddresses'),
|
||||
cell: ({ row }) => {
|
||||
const ips = row.original.ips;
|
||||
return (
|
||||
<div className='flex min-w-0 flex-col gap-1'>
|
||||
{ips.map((ip, i) => (
|
||||
<div
|
||||
key={`${row.original.uid}-${ip}`}
|
||||
className='whitespace-nowrap text-sm'
|
||||
>
|
||||
{i === 0 ? (
|
||||
<IpLink ip={ip} className='font-medium' />
|
||||
) : (
|
||||
<IpLink ip={ip} className='text-muted-foreground' />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'user',
|
||||
header: t('user'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo userId={Number(row.original.uid)} type='account' t={t} />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'subscription',
|
||||
header: t('subscription'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo userId={Number(row.original.uid)} type='subscribeName' t={t} />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'subscribeId',
|
||||
header: t('subscribeId'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo userId={Number(row.original.uid)} type='subscribeId' t={t} />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'traffic',
|
||||
header: t('traffic'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo userId={Number(row.original.uid)} type='traffic' t={t} />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'expireTime',
|
||||
header: t('expireTime'),
|
||||
cell: ({ row }) => (
|
||||
<UserSubscribeInfo userId={Number(row.original.uid)} type='expireTime' t={t} />
|
||||
),
|
||||
},
|
||||
]}
|
||||
request={async () => ({ list: rows, total: rows.length })}
|
||||
/>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServersPage() {
|
||||
const t = useTranslations('servers');
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<div className='space-y-4'>
|
||||
<Card>
|
||||
<CardContent className='p-4'>
|
||||
<ServerConfig />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ProTable<ServerItem, { search: string }>
|
||||
action={ref}
|
||||
header={{
|
||||
title: t('pageTitle'),
|
||||
toolbar: (
|
||||
<ServerForm
|
||||
trigger={t('create')}
|
||||
title={t('drawerCreateTitle')}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
await createServer(values as any);
|
||||
toast.success(t('created'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: 'id',
|
||||
header: t('id'),
|
||||
cell: ({ row }) => <Badge>{row.getValue('id')}</Badge>,
|
||||
},
|
||||
{ accessorKey: 'name', header: t('name') },
|
||||
{
|
||||
id: 'region_ip',
|
||||
header: t('serverAddress'),
|
||||
cell: ({ row }) => (
|
||||
<RegionIpCell
|
||||
country={row.original.country as string}
|
||||
city={row.original.city as string}
|
||||
ip={row.original.server_addr as string}
|
||||
t={t}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: 'protocols',
|
||||
header: t('protocols'),
|
||||
cell: ({ row }) => {
|
||||
const enabled = getEnabledProtocols(row.original.protocols);
|
||||
if (!enabled.length) return t('noData');
|
||||
return (
|
||||
<div className='flex flex-wrap gap-1'>
|
||||
{enabled.map((p, idx) => (
|
||||
<ProtocolBadge key={idx} item={p} t={t} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: t('status'),
|
||||
cell: ({ row }) => {
|
||||
const s = (row.original.status ?? {}) as ServerStatus;
|
||||
const on = !!(
|
||||
s.online &&
|
||||
typeof s.online === 'object' &&
|
||||
!Array.isArray(s.online) &&
|
||||
Object.keys(s.online as Record<string, unknown>).length
|
||||
);
|
||||
return (
|
||||
<div className='flex items-center gap-2'>
|
||||
<span
|
||||
className={cn(
|
||||
'inline-block h-2.5 w-2.5 rounded-full',
|
||||
on ? 'bg-emerald-500' : 'bg-zinc-400',
|
||||
)}
|
||||
/>
|
||||
<span className='text-sm'>{on ? t('online') : t('offline')}</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'cpu',
|
||||
header: t('cpu'),
|
||||
cell: ({ row }) => <PctBar value={(row.original.status?.cpu as number) ?? 0} />,
|
||||
},
|
||||
{
|
||||
id: 'mem',
|
||||
header: t('memory'),
|
||||
cell: ({ row }) => <PctBar value={(row.original.status?.mem as number) ?? 0} />,
|
||||
},
|
||||
{
|
||||
id: 'disk',
|
||||
header: t('disk'),
|
||||
cell: ({ row }) => <PctBar value={(row.original.status?.disk as number) ?? 0} />,
|
||||
},
|
||||
{
|
||||
id: 'online_users',
|
||||
header: t('onlineUsers'),
|
||||
cell: ({ row }) => (
|
||||
<OnlineUsersCell status={row.original.status as ServerStatus} t={t} />
|
||||
),
|
||||
},
|
||||
]}
|
||||
params={[{ key: 'search' }]}
|
||||
request={async (_pagination, filter) => {
|
||||
const { list } = await getServerList();
|
||||
const keyword = (filter?.search || '').toLowerCase().trim();
|
||||
const filtered = keyword
|
||||
? list.filter((item) =>
|
||||
[item.name, item.server_addr, item.country, item.city]
|
||||
.filter(Boolean)
|
||||
.some((v) => String(v).toLowerCase().includes(keyword)),
|
||||
)
|
||||
: list;
|
||||
return { list: filtered, total: filtered.length };
|
||||
}}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<ServerForm
|
||||
key='edit'
|
||||
trigger={t('edit')}
|
||||
title={t('drawerEditTitle')}
|
||||
initialValues={{
|
||||
name: row.name as string,
|
||||
server_addr: row.server_addr as string,
|
||||
country: (row as any).country,
|
||||
city: (row as any).city,
|
||||
protocols: (row as ServerItem).protocols,
|
||||
}}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
await updateServer(row.id as number, values as any);
|
||||
toast.success(t('updated'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
}}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
key='delete'
|
||||
trigger={<Button variant='destructive'>{t('delete')}</Button>}
|
||||
title={t('confirmDeleteTitle')}
|
||||
description={t('confirmDeleteDesc')}
|
||||
onConfirm={async () => {
|
||||
await deleteServer(row.id as number);
|
||||
toast.success(t('deleted'));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
cancelText={t('cancel')}
|
||||
confirmText={t('confirm')}
|
||||
/>,
|
||||
<Button
|
||||
key='copy'
|
||||
variant='outline'
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
const { id, ...others } = row as ServerItem;
|
||||
await createServer(others as any);
|
||||
toast.success(t('copied'));
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
}}
|
||||
>
|
||||
{t('copy')}
|
||||
</Button>,
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
getNodeConfig,
|
||||
getNodeMultiplier,
|
||||
setNodeMultiplier,
|
||||
updateNodeConfig,
|
||||
} from '@/services/admin/system';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { ChartContainer, ChartTooltip } from '@workspace/ui/components/chart';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { Label } from '@workspace/ui/components/label';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { ArrayInput } from '@workspace/ui/custom-components/dynamic-Inputs';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { DicesIcon } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { uid } from 'radash';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Cell, Legend, Pie, PieChart } from 'recharts';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
const COLORS = [
|
||||
'hsl(var(--chart-1))',
|
||||
'hsl(var(--chart-2))',
|
||||
'hsl(var(--chart-3))',
|
||||
'hsl(var(--chart-4))',
|
||||
'hsl(var(--chart-5))',
|
||||
];
|
||||
|
||||
const MINUTES_IN_DAY = 1440;
|
||||
|
||||
function getTimeRangeData(slots: API.TimePeriod[]) {
|
||||
const timePoints = slots
|
||||
.filter((slot) => slot.start_time && slot.end_time)
|
||||
.flatMap((slot) => {
|
||||
const [startH = 0, startM = 0] = slot.start_time.split(':').map(Number);
|
||||
const [endH = 0, endM = 0] = slot.end_time.split(':').map(Number);
|
||||
const start = startH * 60 + startM;
|
||||
let end = endH * 60 + endM;
|
||||
if (end < start) end += MINUTES_IN_DAY;
|
||||
return { start, end, multiplier: slot.multiplier };
|
||||
})
|
||||
.sort((a, b) => a.start - b.start);
|
||||
|
||||
const result: { name: string; value: number; multiplier: number }[] = [];
|
||||
let currentMinute = 0;
|
||||
|
||||
timePoints.forEach((point) => {
|
||||
if (point.start > currentMinute) {
|
||||
result.push({
|
||||
name: `${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')} - ${Math.floor(point.start / 60)}:${String(point.start % 60).padStart(2, '0')}`,
|
||||
value: point.start - currentMinute,
|
||||
multiplier: 1,
|
||||
});
|
||||
}
|
||||
result.push({
|
||||
name: `${Math.floor(point.start / 60)}:${String(point.start % 60).padStart(2, '0')} - ${Math.floor((point.end / 60) % 24)}:${String(point.end % 60).padStart(2, '0')}`,
|
||||
value: point.end - point.start,
|
||||
multiplier: point.multiplier,
|
||||
});
|
||||
currentMinute = point.end % MINUTES_IN_DAY;
|
||||
});
|
||||
|
||||
if (currentMinute < MINUTES_IN_DAY) {
|
||||
result.push({
|
||||
name: `${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')} - 24:00`,
|
||||
value: MINUTES_IN_DAY - currentMinute,
|
||||
multiplier: 1,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const nodeConfigSchema = z.object({
|
||||
node_secret: z.string().optional(),
|
||||
node_pull_interval: z.number().or(z.string().pipe(z.coerce.number())).optional(),
|
||||
node_push_interval: z.number().or(z.string().pipe(z.coerce.number())).optional(),
|
||||
});
|
||||
type NodeConfigFormData = z.infer<typeof nodeConfigSchema>;
|
||||
|
||||
export default function ServerConfig() {
|
||||
const t = useTranslations('servers');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [timeSlots, setTimeSlots] = useState<API.TimePeriod[]>([]);
|
||||
|
||||
const { data: cfgResp, refetch: refetchCfg } = useQuery({
|
||||
queryKey: ['getNodeConfig'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeConfig();
|
||||
return data.data as API.NodeConfig | undefined;
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const { data: periodsResp, refetch: refetchPeriods } = useQuery({
|
||||
queryKey: ['getNodeMultiplier'],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeMultiplier();
|
||||
return (data.data?.periods || []) as API.TimePeriod[];
|
||||
},
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const form = useForm<NodeConfigFormData>({
|
||||
resolver: zodResolver(nodeConfigSchema),
|
||||
defaultValues: {
|
||||
node_secret: '',
|
||||
node_pull_interval: undefined,
|
||||
node_push_interval: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (cfgResp) {
|
||||
form.reset({
|
||||
node_secret: cfgResp.node_secret ?? '',
|
||||
node_pull_interval: cfgResp.node_pull_interval as number | undefined,
|
||||
node_push_interval: cfgResp.node_push_interval as number | undefined,
|
||||
});
|
||||
}
|
||||
}, [cfgResp, form]);
|
||||
|
||||
useEffect(() => {
|
||||
if (periodsResp) {
|
||||
setTimeSlots(periodsResp);
|
||||
}
|
||||
}, [periodsResp]);
|
||||
|
||||
const chartTimeSlots = useMemo(() => getTimeRangeData(timeSlots), [timeSlots]);
|
||||
const chartConfig = useMemo(() => {
|
||||
return chartTimeSlots.reduce(
|
||||
(acc, item, index) => {
|
||||
acc[item.name] = {
|
||||
label: item.name,
|
||||
color: COLORS[index % COLORS.length] || 'hsl(var(--default-chart-color))',
|
||||
};
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, { label: string; color: string }>,
|
||||
);
|
||||
}, [chartTimeSlots]);
|
||||
|
||||
async function onSubmit(values: NodeConfigFormData) {
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateNodeConfig(values as API.NodeConfig);
|
||||
toast.success(t('config.saveSuccess'));
|
||||
await refetchCfg();
|
||||
setOpen(false);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function savePeriods() {
|
||||
await setNodeMultiplier({ periods: timeSlots });
|
||||
await refetchPeriods();
|
||||
toast.success(t('config.saveSuccess'));
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<div className='flex cursor-pointer items-center justify-between'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
|
||||
<Icon icon='mdi:server-cog' className='text-primary h-5 w-5' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<p className='font-medium'>{t('config.title')}</p>
|
||||
<p className='text-muted-foreground text-sm'>{t('config.description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Icon icon='mdi:chevron-right' className='size-6' />
|
||||
</div>
|
||||
</SheetTrigger>
|
||||
|
||||
<SheetContent className='w-[720px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t('config.title')}</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
|
||||
<Form {...form}>
|
||||
<form
|
||||
id='server-config-form'
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className='space-y-4 pt-4'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='node_secret'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.communicationKey')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
placeholder={t('config.inputPlaceholder')}
|
||||
value={field.value || ''}
|
||||
onValueChange={field.onChange}
|
||||
suffix={
|
||||
<div className='bg-muted flex h-9 items-center px-3'>
|
||||
<DicesIcon
|
||||
onClick={() => {
|
||||
const id = uid(32).toLowerCase();
|
||||
const formatted = `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20)}`;
|
||||
form.setValue('node_secret', formatted);
|
||||
}}
|
||||
className='cursor-pointer'
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.communicationKeyDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='node_pull_interval'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.nodePullInterval')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={0}
|
||||
suffix='S'
|
||||
value={field.value as any}
|
||||
onValueChange={field.onChange}
|
||||
placeholder={t('config.inputPlaceholder')}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.nodePullIntervalDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='node_push_interval'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('config.nodePushInterval')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
type='number'
|
||||
min={0}
|
||||
step={0.1}
|
||||
value={field.value as any}
|
||||
onValueChange={field.onChange}
|
||||
placeholder={t('config.inputPlaceholder')}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>{t('config.nodePushIntervalDescription')}</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className='mt-6 space-y-3'>
|
||||
<Label className='text-base'>{t('config.dynamicMultiplier')}</Label>
|
||||
<p className='text-muted-foreground text-sm'>
|
||||
{t('config.dynamicMultiplierDescription')}
|
||||
</p>
|
||||
|
||||
<div className='flex flex-col-reverse gap-8 md:flex-row md:items-start'>
|
||||
<div className='w-full md:w-1/2'>
|
||||
<ArrayInput<API.TimePeriod>
|
||||
fields={[
|
||||
{ name: 'start_time', prefix: t('config.startTime'), type: 'time' },
|
||||
{ name: 'end_time', prefix: t('config.endTime'), type: 'time' },
|
||||
{
|
||||
name: 'multiplier',
|
||||
prefix: t('config.multiplier'),
|
||||
type: 'number',
|
||||
placeholder: '0',
|
||||
},
|
||||
]}
|
||||
value={timeSlots}
|
||||
onChange={setTimeSlots}
|
||||
/>
|
||||
<div className='mt-3 flex gap-2'>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
onClick={() => setTimeSlots(periodsResp || [])}
|
||||
>
|
||||
{t('config.reset')}
|
||||
</Button>
|
||||
<Button size='sm' onClick={savePeriods}>
|
||||
{t('config.save')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='w-full md:w-1/2'>
|
||||
<ChartContainer
|
||||
config={chartConfig}
|
||||
className='mx-auto aspect-[4/3] max-w-[400px]'
|
||||
>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartTimeSlots}
|
||||
cx='50%'
|
||||
cy='50%'
|
||||
labelLine={false}
|
||||
outerRadius='80%'
|
||||
fill='#8884d8'
|
||||
dataKey='value'
|
||||
label={({ percent, multiplier }) =>
|
||||
`${(multiplier || 0)?.toFixed(2)}x (${(percent * 100).toFixed(0)}%)`
|
||||
}
|
||||
>
|
||||
{chartTimeSlots.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<ChartTooltip
|
||||
content={({ payload }) => {
|
||||
if (payload && payload.length) {
|
||||
const d = payload[0]?.payload as any;
|
||||
return (
|
||||
<div className='bg-background rounded-lg border p-2 shadow-sm'>
|
||||
<div className='grid grid-cols-2 gap-2'>
|
||||
<div className='flex flex-col'>
|
||||
<span className='text-muted-foreground text-[0.70rem] uppercase'>
|
||||
{t('config.timeSlot')}
|
||||
</span>
|
||||
<span className='text-muted-foreground font-bold'>
|
||||
{d.name || '—'}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex flex-col'>
|
||||
<span className='text-muted-foreground text-[0.70rem] uppercase'>
|
||||
{t('config.multiplier')}
|
||||
</span>
|
||||
<span className='font-bold'>
|
||||
{Number(d.multiplier).toFixed(2)}x
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
<Legend />
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={saving} onClick={() => setOpen(false)}>
|
||||
{t('config.actions.cancel')}
|
||||
</Button>
|
||||
<Button disabled={saving} type='submit' form='server-config-form'>
|
||||
<Icon icon='mdi:loading' className={saving ? 'mr-2 animate-spin' : 'hidden'} />
|
||||
{t('config.actions.save')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,858 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Button } from '@workspace/ui/components/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@workspace/ui/components/card';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@workspace/ui/components/form';
|
||||
import { ScrollArea } from '@workspace/ui/components/scroll-area';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@workspace/ui/components/select';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from '@workspace/ui/components/sheet';
|
||||
import { Switch } from '@workspace/ui/components/switch';
|
||||
import { Tabs, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
|
||||
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
|
||||
import { Icon } from '@workspace/ui/custom-components/icon';
|
||||
import { cn } from '@workspace/ui/lib/utils';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useFieldArray, useForm, useWatch } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { formScheme, getProtocolDefaultConfig, protocols as PROTOCOLS } from './form-scheme';
|
||||
|
||||
interface ServerFormProps<T> {
|
||||
onSubmit: (data: T) => Promise<boolean> | boolean;
|
||||
initialValues?: T | any;
|
||||
loading?: boolean;
|
||||
trigger: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
function titleCase(s: string) {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
|
||||
function normalizeValues(raw: any) {
|
||||
const map = new Map<string, any>();
|
||||
const given = Array.isArray(raw?.protocols) ? raw.protocols : [];
|
||||
for (const it of given) map.set(it?.protocol, it);
|
||||
|
||||
const normalized = {
|
||||
name: raw?.name ?? '',
|
||||
server_addr: raw?.server_addr ?? '',
|
||||
country: raw?.country ?? '',
|
||||
city: raw?.city ?? '',
|
||||
protocols: PROTOCOLS.map((p) => {
|
||||
const incoming = map.get(p);
|
||||
const def = getProtocolDefaultConfig(p as any);
|
||||
if (incoming) {
|
||||
return {
|
||||
protocol: p,
|
||||
enabled: !!incoming.enabled,
|
||||
config: { ...def, ...(incoming.config ?? {}) },
|
||||
};
|
||||
}
|
||||
return { protocol: p, enabled: false, config: def };
|
||||
}),
|
||||
};
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export default function ServerForm<T extends { [x: string]: any }>({
|
||||
onSubmit,
|
||||
initialValues,
|
||||
loading,
|
||||
trigger,
|
||||
title,
|
||||
}: Readonly<ServerFormProps<T>>) {
|
||||
const t = useTranslations('servers');
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const defaultValues = useMemo(
|
||||
() =>
|
||||
normalizeValues({
|
||||
name: '',
|
||||
server_addr: '',
|
||||
country: '',
|
||||
city: '',
|
||||
protocols: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const form = useForm<any>({
|
||||
resolver: zodResolver(formScheme),
|
||||
defaultValues,
|
||||
});
|
||||
const { control } = form;
|
||||
useFieldArray({ control, name: 'protocols' });
|
||||
|
||||
const [activeProto, setActiveProto] = useState(PROTOCOLS[0]);
|
||||
const activeIndex = useMemo(() => PROTOCOLS.findIndex((p) => p === activeProto), [activeProto]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialValues) {
|
||||
const normalized = normalizeValues(initialValues);
|
||||
form.reset(normalized);
|
||||
const enabledFirst = normalized.protocols.find((p: any) => p.enabled)?.protocol;
|
||||
setActiveProto((enabledFirst as any) || PROTOCOLS[0]);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [initialValues]);
|
||||
|
||||
async function handleSubmit(data: { [x: string]: any }) {
|
||||
const ok = await onSubmit(data as unknown as T);
|
||||
if (ok) setOpen(false);
|
||||
}
|
||||
|
||||
function ProtocolEditor({ idx, proto }: { idx: number; proto: string }) {
|
||||
const transport = useWatch({ control, name: `protocols.${idx}.config.transport` as const });
|
||||
const security = useWatch({ control, name: `protocols.${idx}.config.security` as const });
|
||||
const method = useWatch({ control, name: `protocols.${idx}.config.method` as const });
|
||||
const enabled = useWatch({ control, name: `protocols.${idx}.enabled` as const });
|
||||
|
||||
return (
|
||||
<div className='grid gap-4 p-3'>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.enabled` as const}
|
||||
render={({ field }) => (
|
||||
<div className='flex items-center justify-between gap-2'>
|
||||
<FormLabel className='m-0'>{t('enabled')}</FormLabel>
|
||||
<Switch
|
||||
checked={!!field.value}
|
||||
onCheckedChange={(checked) => {
|
||||
field.onChange(checked);
|
||||
if (checked) {
|
||||
form.setValue(
|
||||
`protocols.${idx}.config` as const,
|
||||
getProtocolDefaultConfig(proto as any),
|
||||
);
|
||||
if (['trojan', 'hysteria2'].includes(proto)) {
|
||||
form.setValue(`protocols.${idx}.config.security` as const, 'tls');
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
|
||||
{enabled && (
|
||||
<>
|
||||
{['shadowsocks'].includes(proto) && (
|
||||
<div className='grid grid-cols-2 gap-2'>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.method` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('encryption_method')}</FormLabel>
|
||||
<FormControl>
|
||||
<Select
|
||||
value={field.value}
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('select_encryption_method')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value='aes-128-gcm'>aes-128-gcm</SelectItem>
|
||||
<SelectItem value='aes-192-gcm'>aes-192-gcm</SelectItem>
|
||||
<SelectItem value='aes-256-gcm'>aes-256-gcm</SelectItem>
|
||||
<SelectItem value='chacha20-ietf-poly1305'>
|
||||
chacha20-ietf-poly1305
|
||||
</SelectItem>
|
||||
<SelectItem value='2022-blake3-aes-128-gcm'>
|
||||
2022-blake3-aes-128-gcm
|
||||
</SelectItem>
|
||||
<SelectItem value='2022-blake3-aes-256-gcm'>
|
||||
2022-blake3-aes-256-gcm
|
||||
</SelectItem>
|
||||
<SelectItem value='2022-blake3-chacha20-poly1305'>
|
||||
2022-blake3-chacha20-poly1305
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.port` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('port')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
type='number'
|
||||
step={1}
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder={t('port_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{[
|
||||
'2022-blake3-aes-128-gcm',
|
||||
'2022-blake3-aes-256-gcm',
|
||||
'2022-blake3-chacha20-poly1305',
|
||||
].includes(method as any) && (
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.server_key` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('server_key')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{['vmess', 'vless', 'trojan', 'hysteria2', 'tuic', 'anytls'].includes(proto) && (
|
||||
<div
|
||||
className={cn('flex gap-4 *:flex-1', {
|
||||
'grid grid-cols-2': ['hysteria2', 'tuic'].includes(proto),
|
||||
})}
|
||||
>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.port` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('port')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
type='number'
|
||||
step={1}
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder={t('port_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{proto === 'vless' && (
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.flow` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('flow')}</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={(v) => field.onChange(v)}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('please_select')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value='none'>NONE</SelectItem>
|
||||
<SelectItem value='xtls-rprx-vision'>XTLS-RPRX-Vision</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{proto === 'hysteria2' && (
|
||||
<>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.obfs_password` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('obfs_password')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
placeholder={t('obfs_password_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.hop_ports` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('hop_ports')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
placeholder={t('hop_ports_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.hop_interval` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('hop_interval')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
type='number'
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
suffix={t('unitSecondsShort')}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{proto === 'tuic' && (
|
||||
<>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.udp_relay_mode` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('udp_relay_mode')}</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={(v) => field.onChange(v)}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('please_select')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value='native'>Native</SelectItem>
|
||||
<SelectItem value='quic'>QUIC</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.congestion_controller` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('congestion_controller')}</FormLabel>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={(v) => field.onChange(v)}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('please_select')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value='bbr'>BBR</SelectItem>
|
||||
<SelectItem value='cubic'>Cubic</SelectItem>
|
||||
<SelectItem value='reno'>Reno</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className='flex gap-2'>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.disable_sni` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('disable_sni')}</FormLabel>
|
||||
<FormControl>
|
||||
<div className='pt-2'>
|
||||
<Switch
|
||||
checked={!!field.value}
|
||||
onCheckedChange={(checked) => field.onChange(checked)}
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.reduce_rtt` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('reduce_rtt')}</FormLabel>
|
||||
<FormControl>
|
||||
<div className='pt-2'>
|
||||
<Switch
|
||||
checked={!!field.value}
|
||||
onCheckedChange={(checked) => field.onChange(checked)}
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{['vmess', 'vless', 'trojan'].includes(proto) && (
|
||||
<Card>
|
||||
<CardHeader className='flex flex-row items-center justify-between p-3'>
|
||||
<CardTitle>{t('transport_title')}</CardTitle>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.transport` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem className='!mt-0 min-w-32'>
|
||||
<FormControl>
|
||||
<Select value={field.value} onValueChange={(v) => field.onChange(v)}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('please_select')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value='tcp'>TCP</SelectItem>
|
||||
<SelectItem value='websocket'>WebSocket</SelectItem>
|
||||
{proto === 'vless' && <SelectItem value='http2'>HTTP/2</SelectItem>}
|
||||
<SelectItem value='grpc'>gRPC</SelectItem>
|
||||
{['vmess', 'vless'].includes(proto) && (
|
||||
<SelectItem value='httpupgrade'>HTTP Upgrade</SelectItem>
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</CardHeader>
|
||||
{transport !== 'tcp' && (
|
||||
<CardContent className='flex gap-4 p-3'>
|
||||
{['websocket', 'http2', 'httpupgrade'].includes(transport as any) && (
|
||||
<>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.transport_config.path` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('path')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.transport_config.host` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('host')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{transport === 'grpc' && (
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.transport_config.service_name` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('service_name')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{['vmess', 'vless', 'trojan', 'anytls', 'tuic', 'hysteria2'].includes(proto) && (
|
||||
<Card>
|
||||
<CardHeader className='flex flex-row items-center justify-between p-3'>
|
||||
<CardTitle>{t('security_title')}</CardTitle>
|
||||
{['vmess', 'vless', 'trojan'].includes(proto) && (
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.security` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem className='!mt-0 min-w-32'>
|
||||
<Select value={field.value} onValueChange={(v) => field.onChange(v)}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('please_select')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{['vmess', 'vless'].includes(proto) && (
|
||||
<SelectItem value='none'>NONE</SelectItem>
|
||||
)}
|
||||
<SelectItem value='tls'>TLS</SelectItem>
|
||||
{proto === 'vless' && (
|
||||
<SelectItem value='reality'>Reality</SelectItem>
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
{(['anytls', 'tuic', 'hysteria2'].includes(proto) ||
|
||||
(['vmess', 'vless', 'trojan'].includes(proto) && security !== 'none')) && (
|
||||
<CardContent className='grid grid-cols-2 gap-4 p-3'>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.security_config.sni` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('security_sni')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{proto === 'vless' && security === 'reality' && (
|
||||
<>
|
||||
<FormField
|
||||
control={control}
|
||||
name={
|
||||
`protocols.${idx}.config.security_config.reality_server_addr` as const
|
||||
}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('security_server_address')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
placeholder={t('security_server_address_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={
|
||||
`protocols.${idx}.config.security_config.reality_server_port` as const
|
||||
}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('security_server_port')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
type='number'
|
||||
min={1}
|
||||
max={65535}
|
||||
placeholder={t('security_server_port_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={
|
||||
`protocols.${idx}.config.security_config.reality_private_key` as const
|
||||
}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('security_private_key')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
placeholder={t('security_private_key_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={
|
||||
`protocols.${idx}.config.security_config.reality_public_key` as const
|
||||
}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('security_public_key')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
placeholder={t('security_public_key_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.security_config.reality_short_id` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('security_short_id')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
{...field}
|
||||
placeholder={t('security_short_id_placeholder')}
|
||||
onValueChange={(v) => field.onChange(v)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{proto === 'vless' && (
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.security_config.fingerprint` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('security_fingerprint')}</FormLabel>
|
||||
<Select value={field.value} onValueChange={(v) => field.onChange(v)}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('please_select')} />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value='chrome'>Chrome</SelectItem>
|
||||
<SelectItem value='firefox'>Firefox</SelectItem>
|
||||
<SelectItem value='safari'>Safari</SelectItem>
|
||||
<SelectItem value='ios'>iOS</SelectItem>
|
||||
<SelectItem value='android'>Android</SelectItem>
|
||||
<SelectItem value='edge'>Edge</SelectItem>
|
||||
<SelectItem value='360'>360</SelectItem>
|
||||
<SelectItem value='qq'>QQ</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name={`protocols.${idx}.config.security_config.allow_insecure` as const}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('security_allow_insecure')}</FormLabel>
|
||||
<FormControl>
|
||||
<div className='pt-2'>
|
||||
<Switch
|
||||
checked={!!field.value}
|
||||
onCheckedChange={(checked) => field.onChange(checked)}
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!initialValues) {
|
||||
form.reset(defaultValues);
|
||||
setActiveProto(PROTOCOLS[0]);
|
||||
}
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{trigger}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className='w-[580px] max-w-full md:max-w-screen-md'>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
|
||||
<Form {...form}>
|
||||
<form className='grid grid-cols-1 gap-2 px-6 pt-4'>
|
||||
<div className='grid grid-cols-2 gap-2'>
|
||||
<FormField
|
||||
control={control}
|
||||
name='name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('name')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name='server_addr'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('server_addr')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name='country'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('country')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={control}
|
||||
name='city'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t('city')}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Tabs
|
||||
value={activeProto}
|
||||
onValueChange={(v) => setActiveProto(v as any)}
|
||||
className='w-full pt-3'
|
||||
>
|
||||
<TabsList className='h-full w-full flex-wrap md:flex-nowrap'>
|
||||
{PROTOCOLS.map((p) => (
|
||||
<TabsTrigger value={p} key={p} className='relative'>
|
||||
<div className='flex items-center gap-2'>{titleCase(p)}</div>
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<ProtocolEditor idx={activeIndex} proto={activeProto as string} />
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
|
||||
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={form.handleSubmit(handleSubmit, () => {
|
||||
toast.error(t('validation_failed'));
|
||||
return false;
|
||||
})}
|
||||
>
|
||||
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />} {t('confirm')}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user