InboundFormModal.new.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import { useEffect, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import dayjs from 'dayjs';
  4. import {
  5. Checkbox,
  6. Form,
  7. Input,
  8. InputNumber,
  9. Modal,
  10. Select,
  11. Switch,
  12. Tabs,
  13. Tooltip,
  14. message,
  15. } from 'antd';
  16. import { HttpUtil, NumberFormatter, RandomUtil, SizeFormatter } from '@/utils';
  17. import {
  18. rawInboundToFormValues,
  19. formValuesToWirePayload,
  20. } from '@/lib/xray/inbound-form-adapter';
  21. import { createDefaultInboundSettings } from '@/lib/xray/inbound-defaults';
  22. import {
  23. InboundFormBaseSchema,
  24. InboundFormSchema,
  25. type InboundFormValues,
  26. } from '@/schemas/forms/inbound-form';
  27. import { antdRule } from '@/utils/zodForm';
  28. import { Protocols, SNIFFING_OPTION } from '@/schemas/primitives';
  29. import DateTimePicker from '@/components/DateTimePicker';
  30. import type { DBInbound } from '@/models/dbinbound';
  31. import type { NodeRecord } from '@/api/queries/useNodesQuery';
  32. // Pattern A rewrite of InboundFormModal. Built as a sibling file so the
  33. // build stays green while the rewrite progresses section by section.
  34. // InboundsPage continues to render the old InboundFormModal.tsx until the
  35. // atomic swap at the end (Core Decision 7).
  36. const PROTOCOL_OPTIONS = Object.values(Protocols).map((p) => ({ value: p, label: p }));
  37. const TRAFFIC_RESETS = ['never', 'hourly', 'daily', 'weekly', 'monthly'] as const;
  38. const NODE_ELIGIBLE_PROTOCOLS = new Set<string>([
  39. Protocols.VLESS,
  40. Protocols.VMESS,
  41. Protocols.TROJAN,
  42. Protocols.SHADOWSOCKS,
  43. Protocols.HYSTERIA,
  44. Protocols.WIREGUARD,
  45. ]);
  46. interface InboundFormModalProps {
  47. open: boolean;
  48. onClose: () => void;
  49. onSaved: () => void;
  50. mode: 'add' | 'edit';
  51. dbInbound: DBInbound | null;
  52. dbInbounds: DBInbound[];
  53. availableNodes?: NodeRecord[];
  54. }
  55. function buildAddModeValues(): InboundFormValues {
  56. const settings = createDefaultInboundSettings('vless') ?? undefined;
  57. return rawInboundToFormValues({
  58. protocol: 'vless',
  59. settings,
  60. streamSettings: { network: 'tcp', security: 'none' },
  61. sniffing: {},
  62. port: RandomUtil.randomInteger(10000, 60000),
  63. listen: '',
  64. tag: '',
  65. enable: true,
  66. trafficReset: 'never',
  67. });
  68. }
  69. export default function InboundFormModalNew({
  70. open,
  71. onClose,
  72. onSaved,
  73. mode,
  74. dbInbound,
  75. availableNodes,
  76. }: InboundFormModalProps) {
  77. const { t } = useTranslation();
  78. const [messageApi, messageContextHolder] = message.useMessage();
  79. const [form] = Form.useForm<InboundFormValues>();
  80. const [saving, setSaving] = useState(false);
  81. const selectableNodes = (availableNodes || []).filter((n) => n.enable);
  82. const protocol = Form.useWatch('protocol', form) ?? '';
  83. const isNodeEligible = NODE_ELIGIBLE_PROTOCOLS.has(protocol);
  84. const sniffingEnabled = Form.useWatch(['sniffing', 'enabled'], form) ?? false;
  85. useEffect(() => {
  86. if (!open) return;
  87. const initial = mode === 'edit' && dbInbound
  88. ? rawInboundToFormValues(dbInbound)
  89. : buildAddModeValues();
  90. form.resetFields();
  91. form.setFieldsValue(initial);
  92. }, [open, mode, dbInbound, form]);
  93. // Why: protocol picker reset cascades through the form — clearing the
  94. // settings DU branch and dropping a nodeId that no longer applies. The
  95. // legacy modal did this imperatively in onProtocolChange; here we hook
  96. // into AntD's onValuesChange and let setFieldValue keep the rest of
  97. // the form state intact.
  98. const onValuesChange = (changed: Partial<InboundFormValues>) => {
  99. if (mode === 'edit') return;
  100. if ('protocol' in changed && typeof changed.protocol === 'string') {
  101. const next = changed.protocol;
  102. const settings = createDefaultInboundSettings(next) ?? undefined;
  103. form.setFieldValue('settings', settings);
  104. if (!NODE_ELIGIBLE_PROTOCOLS.has(next)) {
  105. form.setFieldValue('nodeId', null);
  106. }
  107. }
  108. };
  109. const submit = async () => {
  110. let values: InboundFormValues;
  111. try {
  112. values = await form.validateFields();
  113. } catch {
  114. return;
  115. }
  116. const parsed = InboundFormSchema.safeParse(values);
  117. if (!parsed.success) {
  118. const issue = parsed.error.issues[0];
  119. messageApi.error(
  120. t(issue?.message ?? 'somethingWentWrong', {
  121. defaultValue: issue?.message ?? 'invalid',
  122. }),
  123. );
  124. return;
  125. }
  126. setSaving(true);
  127. try {
  128. const payload = formValuesToWirePayload(parsed.data);
  129. const url = mode === 'edit' && dbInbound
  130. ? `/panel/api/inbounds/update/${dbInbound.id}`
  131. : '/panel/api/inbounds/add';
  132. const msg = await HttpUtil.post(url, payload);
  133. if (msg?.success) {
  134. onSaved();
  135. onClose();
  136. }
  137. } finally {
  138. setSaving(false);
  139. }
  140. };
  141. const title = mode === 'edit'
  142. ? t('pages.inbounds.modifyInbound')
  143. : t('pages.inbounds.addInbound');
  144. const okText = mode === 'edit'
  145. ? t('pages.clients.submitEdit')
  146. : t('create');
  147. const basicTab = (
  148. <>
  149. <Form.Item name="enable" label={t('enable')} valuePropName="checked">
  150. <Switch />
  151. </Form.Item>
  152. <Form.Item name="remark" label={t('pages.inbounds.remark')}>
  153. <Input />
  154. </Form.Item>
  155. {selectableNodes.length > 0 && isNodeEligible && (
  156. <Form.Item name="nodeId" label={t('pages.inbounds.deployTo')}>
  157. <Select
  158. disabled={mode === 'edit'}
  159. placeholder={t('pages.inbounds.localPanel')}
  160. allowClear
  161. >
  162. <Select.Option value={null}>{t('pages.inbounds.localPanel')}</Select.Option>
  163. {selectableNodes.map((n) => (
  164. <Select.Option
  165. key={n.id}
  166. value={n.id}
  167. disabled={n.status === 'offline'}
  168. >
  169. {n.name}{n.status === 'offline' ? ' (offline)' : ''}
  170. </Select.Option>
  171. ))}
  172. </Select>
  173. </Form.Item>
  174. )}
  175. <Form.Item name="protocol" label={t('pages.inbounds.protocol')}>
  176. <Select disabled={mode === 'edit'} options={PROTOCOL_OPTIONS} />
  177. </Form.Item>
  178. <Form.Item name="listen" label={t('pages.inbounds.address')}>
  179. <Input placeholder={t('pages.inbounds.monitorDesc')} />
  180. </Form.Item>
  181. <Form.Item
  182. name="port"
  183. label={t('pages.inbounds.port')}
  184. rules={[antdRule(InboundFormBaseSchema.shape.port, t)]}
  185. >
  186. <InputNumber min={1} max={65535} />
  187. </Form.Item>
  188. <Form.Item
  189. label={
  190. <Tooltip title={t('pages.inbounds.meansNoLimit')}>
  191. {t('pages.inbounds.totalFlow')}
  192. </Tooltip>
  193. }
  194. >
  195. <Form.Item
  196. noStyle
  197. shouldUpdate={(prev, curr) => prev.total !== curr.total}
  198. >
  199. {({ getFieldValue, setFieldValue }) => {
  200. const totalBytes = (getFieldValue('total') as number) ?? 0;
  201. const totalGB = totalBytes
  202. ? Math.round((totalBytes / SizeFormatter.ONE_GB) * 100) / 100
  203. : 0;
  204. return (
  205. <InputNumber
  206. value={totalGB}
  207. min={0}
  208. step={1}
  209. onChange={(v) => {
  210. const bytes = NumberFormatter.toFixed(
  211. (Number(v) || 0) * SizeFormatter.ONE_GB,
  212. 0,
  213. );
  214. setFieldValue('total', bytes);
  215. }}
  216. />
  217. );
  218. }}
  219. </Form.Item>
  220. </Form.Item>
  221. <Form.Item name="trafficReset" label={t('pages.inbounds.periodicTrafficResetTitle')}>
  222. <Select>
  223. {TRAFFIC_RESETS.map((r) => (
  224. <Select.Option key={r} value={r}>
  225. {t(`pages.inbounds.periodicTrafficReset.${r}`)}
  226. </Select.Option>
  227. ))}
  228. </Select>
  229. </Form.Item>
  230. <Form.Item
  231. label={
  232. <Tooltip title={t('pages.inbounds.leaveBlankToNeverExpire')}>
  233. {t('pages.inbounds.expireDate')}
  234. </Tooltip>
  235. }
  236. >
  237. <Form.Item
  238. noStyle
  239. shouldUpdate={(prev, curr) => prev.expiryTime !== curr.expiryTime}
  240. >
  241. {({ getFieldValue, setFieldValue }) => {
  242. const expiry = (getFieldValue('expiryTime') as number) ?? 0;
  243. return (
  244. <DateTimePicker
  245. value={expiry > 0 ? dayjs(expiry) : null}
  246. onChange={(d) => setFieldValue('expiryTime', d ? d.valueOf() : 0)}
  247. />
  248. );
  249. }}
  250. </Form.Item>
  251. </Form.Item>
  252. </>
  253. );
  254. const sniffingTab = (
  255. <>
  256. <Form.Item name={['sniffing', 'enabled']} label={t('enable')} valuePropName="checked">
  257. <Switch />
  258. </Form.Item>
  259. {sniffingEnabled && (
  260. <>
  261. <Form.Item name={['sniffing', 'destOverride']} wrapperCol={{ span: 24 }}>
  262. <Checkbox.Group>
  263. {Object.entries(SNIFFING_OPTION).map(([key, value]) => (
  264. <Checkbox key={key} value={value}>{key}</Checkbox>
  265. ))}
  266. </Checkbox.Group>
  267. </Form.Item>
  268. <Form.Item
  269. name={['sniffing', 'metadataOnly']}
  270. label={t('pages.inbounds.sniffingMetadataOnly')}
  271. valuePropName="checked"
  272. >
  273. <Switch />
  274. </Form.Item>
  275. <Form.Item
  276. name={['sniffing', 'routeOnly']}
  277. label={t('pages.inbounds.sniffingRouteOnly')}
  278. valuePropName="checked"
  279. >
  280. <Switch />
  281. </Form.Item>
  282. <Form.Item
  283. name={['sniffing', 'ipsExcluded']}
  284. label={t('pages.inbounds.sniffingIpsExcluded')}
  285. >
  286. <Select
  287. mode="tags"
  288. tokenSeparators={[',']}
  289. placeholder="IP/CIDR/geoip:*/ext:*"
  290. style={{ width: '100%' }}
  291. />
  292. </Form.Item>
  293. <Form.Item
  294. name={['sniffing', 'domainsExcluded']}
  295. label={t('pages.inbounds.sniffingDomainsExcluded')}
  296. >
  297. <Select
  298. mode="tags"
  299. tokenSeparators={[',']}
  300. placeholder="domain:*/ext:*"
  301. style={{ width: '100%' }}
  302. />
  303. </Form.Item>
  304. </>
  305. )}
  306. </>
  307. );
  308. return (
  309. <>
  310. {messageContextHolder}
  311. <Modal
  312. open={open}
  313. title={title}
  314. okText={okText}
  315. cancelText={t('close')}
  316. confirmLoading={saving}
  317. mask={{ closable: false }}
  318. width={780}
  319. onOk={submit}
  320. onCancel={onClose}
  321. destroyOnHidden
  322. >
  323. <Form
  324. form={form}
  325. colon={false}
  326. labelCol={{ sm: { span: 8 } }}
  327. wrapperCol={{ sm: { span: 14 } }}
  328. onValuesChange={onValuesChange}
  329. >
  330. <Tabs items={[
  331. { key: 'basic', label: t('pages.xray.basicTemplate'), children: basicTab },
  332. { key: 'sniffing', label: t('pages.inbounds.sniffingTab'), children: sniffingTab },
  333. ]} />
  334. </Form>
  335. </Modal>
  336. </>
  337. );
  338. }