NodeFormModal.tsx 17 KB

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