NodeFormModal.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import { useEffect, useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. Alert,
  5. Button,
  6. Col,
  7. Form,
  8. Input,
  9. InputNumber,
  10. Modal,
  11. Row,
  12. Select,
  13. Switch,
  14. message,
  15. } from 'antd';
  16. import { FormProvider, useForm, useWatch } from 'react-hook-form';
  17. import type { NodeRecord } from '@/api/queries/useNodesQuery';
  18. import type { RemoteInboundOption } from '@/api/queries/useNodeMutations';
  19. import type { Msg } from '@/utils';
  20. import { NodeFormSchema, type NodeFormValues, type ProbeResult } from '@/schemas/node';
  21. import { FormField, rhfZodValidate } from '@/components/form/rhf';
  22. import { useOutboundTagGroups } from '@/api/queries/useOutboundTags';
  23. import './NodeFormModal.css';
  24. type Mode = 'add' | 'edit';
  25. interface NodeFormModalProps {
  26. open: boolean;
  27. mode: Mode;
  28. node: NodeRecord | null;
  29. testConnection: (payload: Partial<NodeRecord>) => Promise<Msg<ProbeResult>>;
  30. fetchFingerprint: (payload: Partial<NodeRecord>) => Promise<Msg<string>>;
  31. fetchInbounds: (payload: Partial<NodeRecord>) => Promise<Msg<RemoteInboundOption[]>>;
  32. save: (payload: Partial<NodeRecord>) => Promise<Msg<unknown>>;
  33. onOpenChange: (open: boolean) => void;
  34. }
  35. function defaultValues(): NodeFormValues {
  36. return {
  37. id: 0,
  38. name: '',
  39. remark: '',
  40. scheme: 'https',
  41. address: '',
  42. port: 2053,
  43. basePath: '/',
  44. apiToken: '',
  45. enable: true,
  46. allowPrivateAddress: false,
  47. tlsVerifyMode: 'verify',
  48. pinnedCertSha256: '',
  49. inboundSyncMode: 'all',
  50. inboundTags: [],
  51. outboundTag: '',
  52. };
  53. }
  54. export default function NodeFormModal({
  55. open,
  56. mode,
  57. node,
  58. testConnection,
  59. fetchFingerprint,
  60. fetchInbounds,
  61. save,
  62. onOpenChange,
  63. }: NodeFormModalProps) {
  64. const { t } = useTranslation();
  65. const methods = useForm<NodeFormValues>({ defaultValues: defaultValues() });
  66. const [messageApi, messageContextHolder] = message.useMessage();
  67. const [submitting, setSubmitting] = useState(false);
  68. const [testing, setTesting] = useState(false);
  69. const [fetchingPin, setFetchingPin] = useState(false);
  70. const [fetchingInbounds, setFetchingInbounds] = useState(false);
  71. const [inboundOptions, setInboundOptions] = useState<RemoteInboundOption[]>([]);
  72. const [testResult, setTestResult] = useState<ProbeResult | null>(null);
  73. const scheme = useWatch({ control: methods.control, name: 'scheme' }) ?? 'https';
  74. const tlsVerifyMode = useWatch({ control: methods.control, name: 'tlsVerifyMode' }) ?? 'verify';
  75. const inboundSyncMode = useWatch({ control: methods.control, name: 'inboundSyncMode' }) ?? 'all';
  76. const { data: outboundGroups } = useOutboundTagGroups({ excludeBlackhole: true });
  77. // Outbounds and balancers share one picker (like the panel-outbound selector);
  78. // when balancers exist they get a labeled group so it's clear the selection
  79. // routes through a balancer. Empty falls back to the placeholder ("Direct
  80. // connection") rather than a synthetic option, so it can't read as a second
  81. // "direct" next to a real freedom outbound.
  82. const outboundOptions = useMemo<
  83. ({ label: string; value: string } | { label: string; options: { label: string; value: string }[] })[]
  84. >(() => {
  85. const outOpts = (outboundGroups?.outbounds ?? []).map((tag) => ({ label: tag, value: tag }));
  86. if (!outboundGroups?.balancers.length) return outOpts;
  87. return [
  88. { label: t('pages.xray.Outbounds'), options: outOpts },
  89. { label: t('pages.xray.Balancers'), options: outboundGroups.balancers.map((tag) => ({ label: tag, value: tag })) },
  90. ];
  91. }, [outboundGroups, t]);
  92. useEffect(() => {
  93. if (!open) return;
  94. const base = defaultValues();
  95. const next: NodeFormValues = mode === 'edit' && node
  96. ? {
  97. ...base,
  98. ...(node as unknown as Partial<NodeFormValues>),
  99. id: node.id,
  100. scheme: (node.scheme as 'http' | 'https') || base.scheme,
  101. inboundSyncMode: (node.inboundSyncMode as 'all' | 'selected') || base.inboundSyncMode,
  102. inboundTags: node.inboundTags ?? [],
  103. }
  104. : base;
  105. if (next.scheme === 'http') next.tlsVerifyMode = 'skip';
  106. methods.reset(next);
  107. setInboundOptions((next.inboundTags || []).map((tag) => ({ tag })));
  108. setTestResult(null);
  109. }, [open, mode, node, methods]);
  110. const title = useMemo(
  111. () => (mode === 'edit' ? t('pages.nodes.editNode') : t('pages.nodes.addNode')),
  112. [mode, t],
  113. );
  114. function buildPayload(values: NodeFormValues): Partial<NodeRecord> {
  115. return {
  116. id: values.id || 0,
  117. name: values.name.trim(),
  118. remark: values.remark?.trim() || '',
  119. scheme: values.scheme,
  120. address: values.address.trim(),
  121. port: values.port,
  122. basePath: values.basePath.trim() || '/',
  123. apiToken: values.apiToken.trim(),
  124. enable: values.enable,
  125. allowPrivateAddress: values.allowPrivateAddress,
  126. tlsVerifyMode: values.tlsVerifyMode,
  127. pinnedCertSha256: values.tlsVerifyMode === 'pin' ? values.pinnedCertSha256.trim() : '',
  128. inboundSyncMode: values.inboundSyncMode,
  129. inboundTags: values.inboundSyncMode === 'selected' ? values.inboundTags : [],
  130. outboundTag: values.outboundTag || '',
  131. };
  132. }
  133. async function onTest() {
  134. if (!(await methods.trigger(['address', 'port']))) return;
  135. setTesting(true);
  136. setTestResult(null);
  137. try {
  138. const payload = buildPayload(methods.getValues());
  139. const msg = await testConnection(payload);
  140. if (msg?.success && msg.obj) {
  141. setTestResult(msg.obj);
  142. } else {
  143. setTestResult({ status: 'offline', error: msg?.msg || 'unknown error' });
  144. }
  145. } finally {
  146. setTesting(false);
  147. }
  148. }
  149. async function onFetchPin() {
  150. if (!(await methods.trigger(['address', 'port']))) return;
  151. setFetchingPin(true);
  152. try {
  153. const payload = buildPayload(methods.getValues());
  154. const msg = await fetchFingerprint(payload);
  155. if (msg?.success && msg.obj) {
  156. methods.setValue('pinnedCertSha256', msg.obj);
  157. messageApi.success(t('pages.nodes.pinFetched'));
  158. } else {
  159. messageApi.error(msg?.msg || t('pages.nodes.pinFetchFailed'));
  160. }
  161. } finally {
  162. setFetchingPin(false);
  163. }
  164. }
  165. async function onFetchInbounds() {
  166. if (!(await methods.trigger(['name', 'address', 'port', 'apiToken']))) return;
  167. setFetchingInbounds(true);
  168. try {
  169. const msg = await fetchInbounds(buildPayload(methods.getValues()));
  170. if (msg?.success && Array.isArray(msg.obj)) {
  171. setInboundOptions(msg.obj);
  172. messageApi.success(t('pages.nodes.inboundsLoaded', { count: msg.obj.length }));
  173. } else {
  174. messageApi.error(msg?.msg || t('pages.nodes.inboundsLoadFailed'));
  175. }
  176. } finally {
  177. setFetchingInbounds(false);
  178. }
  179. }
  180. async function onFinish(values: NodeFormValues) {
  181. const result = NodeFormSchema.safeParse(values);
  182. if (!result.success) {
  183. messageApi.error(t(result.error.issues[0]?.message ?? 'pages.nodes.toasts.fillRequired'));
  184. return;
  185. }
  186. setSubmitting(true);
  187. try {
  188. const payload = buildPayload(result.data);
  189. const test = await testConnection(payload);
  190. const probe = test?.success ? test.obj : null;
  191. if (!probe || probe.status !== 'online') {
  192. setTestResult(probe ?? { status: 'offline', error: test?.msg || t('pages.nodes.connectionFailed') });
  193. return;
  194. }
  195. setTestResult(probe);
  196. const msg = await save(payload);
  197. if (msg?.success) {
  198. onOpenChange(false);
  199. }
  200. } finally {
  201. setSubmitting(false);
  202. }
  203. }
  204. function close() {
  205. if (!submitting) onOpenChange(false);
  206. }
  207. return (
  208. <>
  209. {messageContextHolder}
  210. <Modal
  211. open={open}
  212. title={title}
  213. confirmLoading={submitting}
  214. okText={t('save')}
  215. cancelText={t('cancel')}
  216. mask={{ closable: false }}
  217. width="640px"
  218. onOk={methods.handleSubmit(onFinish)}
  219. onCancel={close}
  220. >
  221. <FormProvider {...methods}>
  222. <Form layout="vertical">
  223. <Row gutter={16}>
  224. <Col xs={24} md={12}>
  225. <FormField
  226. label={t('pages.nodes.name')}
  227. name="name"
  228. rules={{ validate: rhfZodValidate(NodeFormSchema.shape.name) }}
  229. >
  230. <Input placeholder={t('pages.nodes.namePlaceholder')} />
  231. </FormField>
  232. </Col>
  233. <Col xs={24} md={12}>
  234. <FormField label={t('pages.nodes.remark')} name="remark">
  235. <Input />
  236. </FormField>
  237. </Col>
  238. </Row>
  239. <Row gutter={16}>
  240. <Col xs={24} md={6}>
  241. <FormField
  242. label={t('pages.nodes.scheme')}
  243. name="scheme"
  244. onAfterChange={(value) => {
  245. if (value === 'http') methods.setValue('tlsVerifyMode', 'skip');
  246. }}
  247. >
  248. <Select
  249. options={[
  250. { value: 'https', label: 'https' },
  251. { value: 'http', label: 'http' },
  252. ]}
  253. />
  254. </FormField>
  255. </Col>
  256. <Col xs={24} md={12}>
  257. <FormField
  258. label={t('pages.nodes.address')}
  259. name="address"
  260. rules={{ validate: rhfZodValidate(NodeFormSchema.shape.address) }}
  261. >
  262. <Input placeholder={t('pages.nodes.addressPlaceholder')} />
  263. </FormField>
  264. </Col>
  265. <Col xs={24} md={6}>
  266. <FormField
  267. label={t('pages.nodes.port')}
  268. name="port"
  269. rules={{ validate: rhfZodValidate(NodeFormSchema.shape.port) }}
  270. >
  271. <InputNumber min={1} max={65535} style={{ width: '100%' }} />
  272. </FormField>
  273. </Col>
  274. </Row>
  275. <Row gutter={16}>
  276. <Col xs={24} md={12}>
  277. <FormField label={t('pages.nodes.basePath')} name="basePath">
  278. <Input placeholder="/" />
  279. </FormField>
  280. </Col>
  281. <Col xs={24} md={12}>
  282. <FormField
  283. label={t('pages.nodes.enable')}
  284. name="enable"
  285. valueProp="checked"
  286. >
  287. <Switch />
  288. </FormField>
  289. </Col>
  290. </Row>
  291. <FormField
  292. label={t('pages.nodes.allowPrivateAddress')}
  293. name="allowPrivateAddress"
  294. valueProp="checked"
  295. tooltip={t('pages.nodes.allowPrivateAddressHint')}
  296. >
  297. <Switch />
  298. </FormField>
  299. <FormField
  300. label={t('pages.nodes.tlsVerifyMode')}
  301. name="tlsVerifyMode"
  302. tooltip={t('pages.nodes.tlsVerifyModeHint')}
  303. >
  304. <Select
  305. disabled={scheme === 'http'}
  306. options={[
  307. { value: 'verify', label: t('pages.nodes.tlsVerify') },
  308. { value: 'pin', label: t('pages.nodes.tlsPin') },
  309. { value: 'skip', label: t('pages.nodes.tlsSkip') },
  310. { value: 'mtls', label: t('pages.nodes.tlsMtls') },
  311. ]}
  312. />
  313. </FormField>
  314. {tlsVerifyMode === 'skip' && (
  315. <Alert
  316. type="warning"
  317. showIcon
  318. style={{ marginBottom: 16 }}
  319. title={t('pages.nodes.tlsSkipWarning')}
  320. />
  321. )}
  322. {tlsVerifyMode === 'mtls' && (
  323. <Alert
  324. type="info"
  325. showIcon
  326. style={{ marginBottom: 16 }}
  327. title={t('pages.nodes.mtlsFormHint')}
  328. />
  329. )}
  330. {tlsVerifyMode === 'pin' && (
  331. <FormField
  332. label={t('pages.nodes.pinnedCert')}
  333. name="pinnedCertSha256"
  334. tooltip={t('pages.nodes.pinnedCertHint')}
  335. >
  336. <Input.Search
  337. placeholder={t('pages.nodes.pinnedCertPlaceholder')}
  338. enterButton={t('pages.nodes.fetchPin')}
  339. loading={fetchingPin}
  340. onSearch={onFetchPin}
  341. />
  342. </FormField>
  343. )}
  344. <FormField
  345. label={t('pages.nodes.apiToken')}
  346. name="apiToken"
  347. rules={{ validate: rhfZodValidate(NodeFormSchema.shape.apiToken) }}
  348. tooltip={t('pages.nodes.apiTokenHint')}
  349. >
  350. <Input.Password placeholder={t('pages.nodes.apiTokenPlaceholder')} />
  351. </FormField>
  352. <FormField
  353. label={t('pages.nodes.outboundTag')}
  354. name="outboundTag"
  355. tooltip={t('pages.nodes.outboundTagHint')}
  356. transform={{ input: (v) => (v as string) || undefined }}
  357. >
  358. <Select
  359. allowClear
  360. showSearch
  361. placeholder={t('pages.nodes.outboundTagPlaceholder')}
  362. options={outboundOptions}
  363. />
  364. </FormField>
  365. <FormField
  366. label={t('pages.nodes.inboundSyncMode')}
  367. name="inboundSyncMode"
  368. tooltip={t('pages.nodes.inboundSyncModeHint')}
  369. >
  370. <Select
  371. options={[
  372. { value: 'all', label: t('pages.nodes.allInbounds') },
  373. { value: 'selected', label: t('pages.nodes.selectedInbounds') },
  374. ]}
  375. />
  376. </FormField>
  377. {inboundSyncMode === 'selected' && (
  378. <FormField
  379. label={t('pages.nodes.inboundTags')}
  380. name="inboundTags"
  381. tooltip={t('pages.nodes.inboundTagsHint')}
  382. >
  383. <Select
  384. mode="multiple"
  385. allowClear
  386. loading={fetchingInbounds}
  387. placeholder={t('pages.nodes.inboundTagsPlaceholder')}
  388. popupRender={(menu) => (
  389. <>
  390. <Button type="text" block loading={fetchingInbounds} onClick={onFetchInbounds}>
  391. {t('pages.nodes.loadInbounds')}
  392. </Button>
  393. {menu}
  394. </>
  395. )}
  396. options={inboundOptions.map((inbound) => ({
  397. value: inbound.tag,
  398. label: `${inbound.remark || inbound.tag}${inbound.protocol ? ` (${inbound.protocol}:${inbound.port || 0})` : ''}`,
  399. }))}
  400. />
  401. </FormField>
  402. )}
  403. <div className="test-row">
  404. <Button type="default" loading={testing} onClick={onTest}>
  405. {t('pages.nodes.testConnection')}
  406. </Button>
  407. {testResult && (
  408. <div className="test-result">
  409. {testResult.status === 'online' ? (
  410. <Alert
  411. type="success"
  412. showIcon
  413. title={t('pages.nodes.connectionOk', { ms: testResult.latencyMs })}
  414. description={testResult.xrayVersion ? `Xray ${testResult.xrayVersion}` : undefined}
  415. />
  416. ) : (
  417. <Alert
  418. type="error"
  419. showIcon
  420. title={t('pages.nodes.connectionFailed')}
  421. description={testResult.error}
  422. />
  423. )}
  424. </div>
  425. )}
  426. </div>
  427. </Form>
  428. </FormProvider>
  429. </Modal>
  430. </>
  431. );
  432. }