mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-08-22 02:47:14 +00:00
refactor(frontend): reorganize source tree & break down oversized modals/tabs (#4698)
* refactor(frontend): reorganize components & pages into feature folders
No behavior change; pure file relocation + import path updates.
* refactor(frontend): move shared protocol enums to schemas/protocols/shared
Decouple Outbound from Inbound schemas: SSMethodSchema and VmessSecuritySchema (shared between inbound & outbound) now live in a neutral schemas/protocols/shared/ module. Outbound no longer reaches into schemas/protocols/inbound/*. Pure relocation + import rewiring; schema values identical, snapshots & golden tests unchanged.
* refactor(frontend): break InboundList into helpers/types/RowActions/columns hook/stats modal
InboundList.tsx 781 -> 203 lines. Extracted pure helpers (network labels, sort fns, isInboundMultiUser), shared types, the row-actions menu/cell, the table columns hook, and the mobile stats modal into the list/ folder. Code moved verbatim; no behavior change. typecheck/lint/test/build green, 337 tests pass.
* refactor(frontend): extract InboundInfoModal helpers, types & buildInboundInfo
InboundInfoModal.tsx 1081 -> 836 lines. Moved the pure data helpers (network host/path readers, link-protocol check, copy/download/statsColor/IP formatting) plus all shared types and the buildInboundInfo data builder into info/helpers.ts and info/types.ts. The state-coupled render body is left intact (no React render tests to guard a deeper split). Code moved verbatim; no behavior change. All gates green, 337 tests pass.
* test(frontend): add React Testing Library + jsdom render-test harness
- vitest projects: node unit tests stay lean; new jsdom 'components' project runs *.test.tsx
- component setup: matchMedia/ResizeObserver/localStorage polyfills, react-i18next init, persian-calendar-suite stub (only used under jalali locale)
- smoke + field-label structure snapshots for Inbound & Outbound form modals
- establishes the regression net required before decomposing the oversized form modals
- 341 tests pass (337 unit + 4 component); typecheck/lint/build green
* test(frontend): per-protocol field-structure coverage for both form modals
- drive the protocol Select in jsdom and snapshot rendered Form.Item labels for every protocol
- 10 outbound + 10 inbound protocol states captured as the regression net for protocol-core extraction
- add robust select-driving helpers (test-utils) + post-test body cleanup (setup.components)
- 341 tests pass; typecheck/lint green
* refactor(frontend): extract OutboundFormModal constants & stream helpers
OutboundFormModal.tsx 2238 -> 2080. Moved the pure option arrays/sets and the stream-slice helpers (newStreamSlice, hysteriaStreamSlice, isMuxAllowed, buildAddModeValues) into outbound-form-constants.ts and outbound-form-helpers.ts. Per-protocol render snapshots unchanged -> verified no behavior change. typecheck/lint/build green.
* refactor(frontend): extract InboundFormModal advanced JSON editors
InboundFormModal.tsx 3129 -> 2863. Moved AdvancedSliceEditor and AdvancedAllEditor (the in-modal JSON slice/all editors) into advanced-editors.tsx along with their adapter-helper imports. Per-protocol render snapshots unchanged -> verified no behavior change. typecheck/lint/build green.
* refactor(frontend): extract OutboundFormModal loopback/blackhole/dns field blocks
Moved the outbound-only protocol field blocks (loopback, blackhole, dns) out of the modal render body into outbound-only-fields.tsx. First render-body extraction behind the per-protocol snapshot net: loopback/blackhole/dns snapshots unchanged -> verified no behavior change. typecheck/lint/build green.
* refactor(frontend): extract OutboundFormModal freedom field block
OutboundFormModal.tsx 2063 -> 1753. Moved the freedom protocol field block (domainStrategy, fragment, noises, finalRules) into outbound-freedom-fields.tsx. Verbatim relocation; freedom per-protocol snapshot unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): extract OutboundFormModal wireguard field block
OutboundFormModal.tsx 1753 -> 1622. Moved the wireguard protocol field block (address, keypair gen, domainStrategy, peers + allowedIPs) into outbound-wireguard-fields.tsx; dropped now-unused icon/InputAddon/WireguardDomainStrategy imports. Verbatim relocation; wireguard snapshot unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): extract OutboundFormModal core protocol fields
OutboundFormModal.tsx 1622 -> 1538. Moved the shared protocol core field blocks (vmess/vless ID, vmess security, vless encryption/reverseTag, trojan/ss password, ss method/uot, socks/http user/pass) into outbound-core-fields.tsx; dropped now-unused schema/option imports. Per-protocol snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): fold OutboundFormModal server address/port block into core fields
OutboundFormModal.tsx 1538 -> 1516. Moved the shared connect-target (address/port) block into OutboundCoreProtocolFields at the same render position; dropped the now-unused SERVER_PROTOCOLS import. Snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): split outbound-only protocol forms into per-protocol files
Replace the grouped outbound-only-fields.tsx + outbound-freedom-fields.tsx with one file per protocol under outbounds/protocols/: freedom.tsx, blackhole.tsx, dns.tsx, loopback.tsx (+ barrel). Matches the prompt's 1-file-per-protocol structure. Outbound snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): split outbound protocol forms into per-protocol files
Replace the grouped outbound-core-fields / outbound-wireguard-fields with one file per protocol under outbounds/protocols/: vmess, vless, trojan, shadowsocks, http, socks, wireguard, freedom, blackhole, dns, loopback (+ shared server-target). Matches the prompt's 1-file-per-protocol structure (per-modal). Outbound snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): split outbound transport forms into per-transport files
Extract the tcp(raw)/kcp/ws/grpc/httpupgrade transport blocks into outbounds/transport/ per-file components (RawForm, KcpForm, WsForm, GrpcForm, HttpUpgradeForm). xhttp + hysteria transport remain inline for a follow-up. Verbatim relocation; outbound snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): extract OutboundFormModal xhttp transport form
Move the xhttp transport block into transport/xhttp.tsx (takes form + onXmuxToggle prop); drop now-unused HeaderMapEditor and MODE_OPTIONS imports from the modal. OutboundFormModal.tsx down to ~1001 lines (from 2238 originally). Verbatim relocation; outbound snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): extract OutboundFormModal tls/reality security forms
Move the TLS and Reality field blocks into outbounds/security/{tls,reality}.tsx; the none/TLS/Reality Radio.Group selector stays in the modal. Drop now-unused ALPN_OPTIONS/UTLS_OPTIONS imports. OutboundFormModal.tsx down to ~918 lines (from 2238 originally). Verbatim relocation; outbound snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): split inbound-only protocol forms (tun, tunnel) into per-file
Extract the tun and tunnel protocol blocks from InboundFormModal into inbounds/form/protocols/{tun,tunnel}.tsx (presentational, declarative). First inbound-side per-protocol split. Verbatim relocation; inbound snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): split inbound wireguard & shadowsocks protocol forms
Extract the wireguard and shadowsocks protocol blocks from InboundFormModal into inbounds/form/protocols/{wireguard,shadowsocks}.tsx (presentational; form + regen handlers / isSSWith2022 passed as props). Drop now-unused Divider + SSMethodSchema imports. Verbatim relocation; inbound snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): split inbound vless/http/mixed/hysteria protocol forms
Extract the remaining inbound protocol blocks into inbounds/form/protocols/: vless (auth handlers/state as props), http + mixed (shared accounts-list), hysteria. Drop now-unused HysteriaMasqueradeForm/Typography/Text imports from the modal. InboundFormModal.tsx 2841 -> 2478. Inbound snapshots unchanged -> no behavior change. typecheck/lint/build green.
* refactor(frontend): move HysteriaMasqueradeForm to lib/xray/forms/transport
The hysteria masquerade form edits streamSettings.hysteriaSettings.masquerade (a transport/stream concept) and is rendered identically by both modals, so it belongs next to FinalMaskForm in lib/xray/forms/transport/ rather than protocols/shared/. Moved the file, updated the transport barrel + both consumers (inbound hysteria protocol form, outbound modal), and removed the now-empty protocols/shared/ folder. Pure relocation; snapshots unchanged, typecheck/lint/build green.
* refactor(frontend): extract inbound transport forms into transport/ folder
Move the six inbound stream-transport blocks (tcp/raw, ws, grpc, xhttp,
httpupgrade, kcp) out of InboundFormModal into presentational components
under inbounds/form/transport/. XhttpForm takes the form instance and
re-derives its mode/obfs/placement watches internally; the rest are
declarative. InboundFormModal drops from 2566 to 2105 lines. No behavior
change — per-protocol field-label snapshots unchanged.
* refactor(frontend): extract inbound security forms into security/ folder
Move the inbound TLS and Reality stream-security blocks out of
InboundFormModal into presentational components under
inbounds/form/security/. The Radio.Group security selector stays in the
modal; TlsForm and RealityForm receive their cert/key/ECH generation
handlers and the saving flag as props. InboundFormModal drops from 2105
to 1708 lines.
Add inbound-form-blocks.test.tsx: render-snapshot coverage for each
extracted transport (raw/ws/grpc/kcp/httpupgrade/xhttp) and security
(tls/reality) component in isolation inside a minimal Form. The full
modal cannot exercise the stream/security tabs in jsdom because they are
gated behind Form.useWatch values that do not propagate in the test
harness, so component-level snapshots are the regression net for these
blocks. No behavior change.
* refactor(frontend): extract outbound sockopt/mux/hysteria transport blocks
Move the last three oversized inline stream blocks out of
OutboundFormModal into presentational components under
xray/outbounds/transport/: SockoptForm (~260 lines, the worst offender),
MuxForm, and HysteriaForm. Each takes the form instance; MuxForm also
takes protocol/network and keeps its isMuxAllowed gate. OutboundFormModal
drops from 962 to 621 lines and no inline section now exceeds the
250-line guideline. Existing outbound-form-modal snapshots already cover
sockopt/mux and stay byte-identical, confirming no behavior change.
* refactor(frontend): extract inbound sockopt + external-proxy blocks
Move the inbound Sockopt (~250 lines) and External Proxy stream blocks
out of InboundFormModal into presentational components under
inbounds/form/transport/, mirroring the outbound extraction. Each takes
its toggle handler (toggleSockopt / toggleExternalProxy) as a prop and
keeps its render-prop getFieldValue gate. InboundFormModal drops from
1708 to 1332 lines.
Extend inbound-form-blocks.test.tsx with isolated render-snapshot
coverage for both (SockoptForm seeded enabled + happyEyeballs;
ExternalProxyForm seeded with one TLS entry). No behavior change.
* refactor(frontend): break down RoutingTab into sections
Extract RoutingTab's presentational pieces into the routing/ folder:
helpers.ts (arrJoin/csv/chipPreview/ruleCriteriaChips), types.ts
(RuleRow), CriterionRow.tsx, RuleCardList.tsx (mobile card view), and
useRoutingColumns.tsx (desktop table columns hook). RoutingTab stays the
orchestrator holding rule state, mutate, tag-option memos and the
pointer-drag reorder logic, and drops from 550 to 291 lines. No behavior
change.
* refactor(frontend): extract BasicsTab constants and rule helpers
Move BasicsTab's geo option arrays + freedom/ipv4 outbound presets into
basics/constants.ts and the routing-rule get/set/sync helpers into
basics/helpers.ts. BasicsTab drops from 550 to 447 lines and keeps its
Collapse-of-settings panels (which stay coupled to mutate + derived
state, so splitting them into components would only add prop-drilling).
No behavior change.
* refactor(frontend): break down DnsTab columns/helpers/types
Extract DnsTab's pure pieces into the dns/ folder: helpers.ts
(STRATEGIES/DEFAULT_FAKEDNS + addr/domains/expectedIPs accessors),
types.ts (DnsConfig/HostRow/FakednsRow), and useDnsColumns.tsx
(useDnsServerColumns + useFakednsColumns table-column hooks taking their
row handlers as params). DnsTab stays the orchestrator for dns state,
mutate, hosts sync and the Collapse panels, and drops from 539 to 424
lines. No behavior change.
* refactor(frontend): break down OutboundsTab into sections
Extract OutboundsTab's pieces: outbounds-tab-types.ts (OutboundRow),
outbounds-tab-helpers.ts (address/untestable/security/breakdown +
traffic/testing/result accessors), useOutboundColumns.tsx (desktop table
columns hook) and OutboundCardList.tsx (mobile card view). OutboundsTab
stays the orchestrator for outbound state, mutate, reorder and the
toolbar, and drops from 516 to 238 lines. No behavior change.
This completes plan section 2.4.5 — all four oversized Xray tabs
(Basics/Routing/Dns/Outbounds) are now broken into sections + hooks.
* refactor(frontend): fold HysteriaMasqueradeForm into the hysteria forms
Inline the masquerade fields directly into both hysteria transport forms
(inbounds/form/protocols/hysteria + xray/outbounds/transport/hysteria)
and delete the shared lib/xray/forms/transport/HysteriaMasqueradeForm so
each hysteria form is self-contained. The masquerade JSX is unchanged;
form is typed as the untyped FormInstance (as the shared component was)
so the masquerade name paths still resolve. No behavior change.
* refactor(frontend): slim InboundFormModal by extracting hooks + sections
Pull the modal's non-layout logic into focused files at the form root:
- useSecurityActions.ts: TLS/Reality key + cert generation handlers and
onSecurityChange (consumed by the security tab)
- useInboundFallbacks.ts: fallback row state + load/save/derive/add/
update/remove/move handlers + eligible-child options
- FallbacksCard.tsx: the fallbacks card UI (presentational)
- SniffingTab.tsx: the sniffing tab UI (presentational)
Also drop the stale "Pattern A rewrite / sibling file" header comment and
the imports the extractions made unused. InboundFormModal goes from 1332
to 868 lines with no behavior change (351 tests green, snapshots
unchanged).
This commit is contained in:
@@ -0,0 +1,868 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import dayjs from 'dayjs';
|
||||
import {
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Radio,
|
||||
Select,
|
||||
Switch,
|
||||
Tabs,
|
||||
Tooltip,
|
||||
message,
|
||||
} from 'antd';
|
||||
|
||||
import { HttpUtil, NumberFormatter, RandomUtil, SizeFormatter, Wireguard } from '@/utils';
|
||||
import {
|
||||
rawInboundToFormValues,
|
||||
formValuesToWirePayload,
|
||||
} from '@/lib/xray/inbound-form-adapter';
|
||||
import { createDefaultInboundSettings } from '@/lib/xray/inbound-defaults';
|
||||
import {
|
||||
canEnableReality,
|
||||
canEnableStream,
|
||||
canEnableTls,
|
||||
isSS2022,
|
||||
} from '@/lib/xray/protocol-capabilities';
|
||||
import {
|
||||
InboundFormBaseSchema,
|
||||
InboundFormSchema,
|
||||
type InboundFormValues,
|
||||
} from '@/schemas/forms/inbound-form';
|
||||
import { antdRule } from '@/utils/zodForm';
|
||||
import { Protocols } from '@/schemas/primitives';
|
||||
import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
|
||||
import { HysteriaStreamSettingsSchema } from '@/schemas/protocols/stream/hysteria';
|
||||
import { TlsStreamSettingsSchema } from '@/schemas/protocols/security/tls';
|
||||
import { SniffingSchema } from '@/schemas/primitives/sniffing';
|
||||
import { TcpStreamSettingsSchema } from '@/schemas/protocols/stream/tcp';
|
||||
import { KcpStreamSettingsSchema } from '@/schemas/protocols/stream/kcp';
|
||||
import { WsStreamSettingsSchema } from '@/schemas/protocols/stream/ws';
|
||||
import { GrpcStreamSettingsSchema } from '@/schemas/protocols/stream/grpc';
|
||||
import { HttpUpgradeStreamSettingsSchema } from '@/schemas/protocols/stream/httpupgrade';
|
||||
import { XHttpStreamSettingsSchema } from '@/schemas/protocols/stream/xhttp';
|
||||
import { DateTimePicker } from '@/components/form';
|
||||
import { FinalMaskForm } from '@/lib/xray/forms/transport';
|
||||
import './InboundFormModal.css';
|
||||
|
||||
import { AdvancedAllEditor, AdvancedSliceEditor } from './advanced-editors';
|
||||
import {
|
||||
HttpFields,
|
||||
HysteriaFields,
|
||||
MixedFields,
|
||||
ShadowsocksFields,
|
||||
TunFields,
|
||||
TunnelFields,
|
||||
VlessFields,
|
||||
WireguardFields,
|
||||
} from './protocols';
|
||||
import {
|
||||
ExternalProxyForm,
|
||||
GrpcForm,
|
||||
HttpUpgradeForm,
|
||||
KcpForm,
|
||||
RawForm,
|
||||
SockoptForm,
|
||||
WsForm,
|
||||
XhttpForm,
|
||||
} from './transport';
|
||||
import { RealityForm, TlsForm } from './security';
|
||||
import { useSecurityActions } from './useSecurityActions';
|
||||
import { useInboundFallbacks } from './useInboundFallbacks';
|
||||
import FallbacksCard from './FallbacksCard';
|
||||
import SniffingTab from './SniffingTab';
|
||||
|
||||
import type { DBInbound } from '@/models/dbinbound';
|
||||
import type { NodeRecord } from '@/api/queries/useNodesQuery';
|
||||
|
||||
|
||||
const PROTOCOL_OPTIONS = Object.values(Protocols).map((p) => ({ value: p, label: p }));
|
||||
const TRAFFIC_RESETS = ['never', 'hourly', 'daily', 'weekly', 'monthly'] as const;
|
||||
const NODE_ELIGIBLE_PROTOCOLS = new Set<string>([
|
||||
Protocols.VLESS,
|
||||
Protocols.VMESS,
|
||||
Protocols.TROJAN,
|
||||
Protocols.SHADOWSOCKS,
|
||||
Protocols.HYSTERIA,
|
||||
Protocols.WIREGUARD,
|
||||
]);
|
||||
|
||||
interface InboundFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
mode: 'add' | 'edit';
|
||||
dbInbound: DBInbound | null;
|
||||
dbInbounds: DBInbound[];
|
||||
availableNodes?: NodeRecord[];
|
||||
}
|
||||
|
||||
function buildAddModeValues(): InboundFormValues {
|
||||
const settings = createDefaultInboundSettings('vless') ?? undefined;
|
||||
return rawInboundToFormValues({
|
||||
protocol: 'vless',
|
||||
settings,
|
||||
streamSettings: {
|
||||
network: 'tcp',
|
||||
security: 'none',
|
||||
tcpSettings: TcpStreamSettingsSchema.parse({ header: { type: 'none' } }),
|
||||
},
|
||||
sniffing: SniffingSchema.parse({}),
|
||||
port: RandomUtil.randomInteger(10000, 60000),
|
||||
listen: '',
|
||||
tag: '',
|
||||
enable: true,
|
||||
trafficReset: 'never',
|
||||
});
|
||||
}
|
||||
|
||||
export default function InboundFormModal({
|
||||
open,
|
||||
onClose,
|
||||
onSaved,
|
||||
mode,
|
||||
dbInbound,
|
||||
dbInbounds,
|
||||
availableNodes,
|
||||
}: InboundFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const [form] = Form.useForm<InboundFormValues>();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const {
|
||||
fallbacks,
|
||||
fallbackChildOptions,
|
||||
loadFallbacks,
|
||||
saveFallbacks,
|
||||
addFallback,
|
||||
updateFallback,
|
||||
removeFallback,
|
||||
moveFallback,
|
||||
addAllFallbacks,
|
||||
} = useInboundFallbacks(dbInbound, dbInbounds);
|
||||
|
||||
const selectableNodes = (availableNodes || []).filter((n) => n.enable);
|
||||
const protocol = (Form.useWatch('protocol', form) ?? '') as string;
|
||||
const isNodeEligible = NODE_ELIGIBLE_PROTOCOLS.has(protocol);
|
||||
const sniffingEnabled = Form.useWatch(['sniffing', 'enabled'], form) ?? false;
|
||||
const vlessEncryption = Form.useWatch(['settings', 'encryption'], form) ?? '';
|
||||
const ssMethod = Form.useWatch(['settings', 'method'], form);
|
||||
const isSSWith2022 = isSS2022({
|
||||
protocol,
|
||||
settings: typeof ssMethod === 'string' ? { method: ssMethod } : {},
|
||||
});
|
||||
const mixedUdpOn = Form.useWatch(['settings', 'udp'], form) ?? false;
|
||||
const network = Form.useWatch(['streamSettings', 'network'], form) ?? '';
|
||||
const security = Form.useWatch(['streamSettings', 'security'], form) ?? 'none';
|
||||
const streamEnabled = canEnableStream({ protocol });
|
||||
const isFallbackHost =
|
||||
(protocol === Protocols.VLESS || protocol === Protocols.TROJAN)
|
||||
&& network === 'tcp'
|
||||
&& (security === 'tls' || security === 'reality');
|
||||
|
||||
const {
|
||||
genRealityKeypair,
|
||||
clearRealityKeypair,
|
||||
genMldsa65,
|
||||
clearMldsa65,
|
||||
randomizeRealityTarget,
|
||||
randomizeShortIds,
|
||||
getNewEchCert,
|
||||
clearEchCert,
|
||||
generateRandomPinHash,
|
||||
setCertFromPanel,
|
||||
clearCertFiles,
|
||||
onSecurityChange,
|
||||
} = useSecurityActions({ form, setSaving, messageApi });
|
||||
|
||||
const toggleExternalProxy = (on: boolean) => {
|
||||
if (on) {
|
||||
const port = (form.getFieldValue('port') as number) ?? 443;
|
||||
form.setFieldValue(['streamSettings', 'externalProxy'], [{
|
||||
forceTls: 'same',
|
||||
dest: typeof window !== 'undefined' ? window.location.hostname : '',
|
||||
port,
|
||||
remark: '',
|
||||
sni: '',
|
||||
fingerprint: '',
|
||||
alpn: [],
|
||||
}]);
|
||||
} else {
|
||||
form.setFieldValue(['streamSettings', 'externalProxy'], []);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleSockopt = (on: boolean) => {
|
||||
if (on) {
|
||||
form.setFieldValue(
|
||||
['streamSettings', 'sockopt'],
|
||||
SockoptStreamSettingsSchema.parse({}),
|
||||
);
|
||||
} else {
|
||||
form.setFieldValue(['streamSettings', 'sockopt'], undefined);
|
||||
}
|
||||
};
|
||||
const wgSecretKey = Form.useWatch(['settings', 'secretKey'], form);
|
||||
const wgPubKey = typeof wgSecretKey === 'string' && wgSecretKey.length > 0
|
||||
? Wireguard.generateKeypair(wgSecretKey).publicKey
|
||||
: '';
|
||||
|
||||
const regenInboundWg = () => {
|
||||
const kp = Wireguard.generateKeypair();
|
||||
form.setFieldValue(['settings', 'secretKey'], kp.privateKey);
|
||||
};
|
||||
|
||||
const regenWgPeerKeypair = (peerName: number) => {
|
||||
const kp = Wireguard.generateKeypair();
|
||||
form.setFieldValue(['settings', 'peers', peerName, 'privateKey'], kp.privateKey);
|
||||
form.setFieldValue(['settings', 'peers', peerName, 'publicKey'], kp.publicKey);
|
||||
};
|
||||
|
||||
const matchesVlessAuth = (
|
||||
block: { id?: string; label?: string } | undefined | null,
|
||||
authId: string,
|
||||
) => {
|
||||
if (block?.id === authId) return true;
|
||||
const label = (block?.label || '').toLowerCase().replace(/[-_\s]/g, '');
|
||||
if (authId === 'mlkem768') return label.includes('mlkem768');
|
||||
if (authId === 'x25519') return label.includes('x25519');
|
||||
return false;
|
||||
};
|
||||
|
||||
const getNewVlessEnc = async (authId: string) => {
|
||||
if (!authId) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const msg = await HttpUtil.get('/panel/api/server/getNewVlessEnc');
|
||||
if (!msg?.success) return;
|
||||
const obj = msg.obj as {
|
||||
auths?: { decryption: string; encryption: string; label?: string; id?: string }[];
|
||||
};
|
||||
const block = (obj.auths || []).find((a) => matchesVlessAuth(a, authId));
|
||||
if (!block) return;
|
||||
form.setFieldValue(['settings', 'decryption'], block.decryption);
|
||||
form.setFieldValue(['settings', 'encryption'], block.encryption);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const clearVlessEnc = () => {
|
||||
form.setFieldValue(['settings', 'decryption'], 'none');
|
||||
form.setFieldValue(['settings', 'encryption'], 'none');
|
||||
};
|
||||
|
||||
const selectedVlessAuth = (() => {
|
||||
const enc = typeof vlessEncryption === 'string' ? vlessEncryption : '';
|
||||
if (!enc || enc === 'none') return 'None';
|
||||
const parts = enc.split('.').filter(Boolean);
|
||||
const authKey = parts[parts.length - 1] || '';
|
||||
if (!authKey) return t('pages.inbounds.vlessAuthCustom');
|
||||
return authKey.length > 300
|
||||
? t('pages.inbounds.vlessAuthMlkem768')
|
||||
: t('pages.inbounds.vlessAuthX25519');
|
||||
})();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const initial = mode === 'edit' && dbInbound
|
||||
? rawInboundToFormValues(dbInbound)
|
||||
: buildAddModeValues();
|
||||
form.resetFields();
|
||||
form.setFieldsValue(initial);
|
||||
if (
|
||||
mode === 'edit'
|
||||
&& dbInbound
|
||||
&& (dbInbound.protocol === Protocols.VLESS || dbInbound.protocol === Protocols.TROJAN)
|
||||
) {
|
||||
loadFallbacks(dbInbound.id);
|
||||
} else {
|
||||
loadFallbacks(null);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, mode, dbInbound, form]);
|
||||
|
||||
// Why: protocol picker reset cascades through the form — clearing the
|
||||
// settings DU branch and dropping a nodeId that no longer applies. The
|
||||
// legacy modal did this imperatively in onProtocolChange; here we hook
|
||||
// into AntD's onValuesChange and let setFieldValue keep the rest of
|
||||
// the form state intact.
|
||||
const onValuesChange = (changed: Partial<InboundFormValues>) => {
|
||||
if (mode === 'edit') return;
|
||||
if ('protocol' in changed && typeof changed.protocol === 'string') {
|
||||
const next = changed.protocol;
|
||||
const settings = createDefaultInboundSettings(next) ?? undefined;
|
||||
form.setFieldValue('settings', settings);
|
||||
if (!NODE_ELIGIBLE_PROTOCOLS.has(next)) {
|
||||
form.setFieldValue('nodeId', null);
|
||||
}
|
||||
// Hysteria uses its dedicated transport — force the network branch
|
||||
// so the stream tab renders the hysteria sub-form, not the leftover
|
||||
// tcpSettings from the previous protocol. When leaving hysteria,
|
||||
// snap back to TCP so the standard network selector has a valid
|
||||
// starting point.
|
||||
if (next === Protocols.HYSTERIA) {
|
||||
const tls = TlsStreamSettingsSchema.parse({}) as Record<string, unknown>;
|
||||
tls.certificates = [{
|
||||
useFile: true,
|
||||
certificateFile: '',
|
||||
keyFile: '',
|
||||
certificate: [],
|
||||
key: [],
|
||||
oneTimeLoading: false,
|
||||
usage: 'encipherment',
|
||||
buildChain: false,
|
||||
}];
|
||||
form.setFieldValue('streamSettings', {
|
||||
network: 'hysteria',
|
||||
security: 'tls',
|
||||
hysteriaSettings: HysteriaStreamSettingsSchema.parse({}),
|
||||
tlsSettings: tls,
|
||||
// Hysteria2 needs an obfs wrapper on the FinalMask side; seed
|
||||
// it with salamander + a random password so the listener boots
|
||||
// with a usable default. Re-selecting Hysteria from another
|
||||
// protocol re-runs this and refreshes the password — that's
|
||||
// intentional, the form was already being reset.
|
||||
finalmask: {
|
||||
tcp: [],
|
||||
udp: [{
|
||||
type: 'salamander',
|
||||
settings: { password: RandomUtil.randomLowerAndNum(16) },
|
||||
}],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const current = form.getFieldValue('streamSettings') as { network?: string } | undefined;
|
||||
if (current?.network === 'hysteria') {
|
||||
form.setFieldValue('streamSettings', { network: 'tcp', security: 'none', tcpSettings: {} });
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
try {
|
||||
await form.validateFields();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
// Why getFieldsValue(true) instead of the validateFields return value:
|
||||
// rc-component/form's validateFields filters its output by REGISTERED
|
||||
// name paths. settings.clients and settings.fallbacks have no Form.Item
|
||||
// bound to them (clients are managed via the standalone Client modal,
|
||||
// not inside this inbound modal) — so validateFields would drop them
|
||||
// and the update wire payload would silently delete every client on
|
||||
// every save. getFieldsValue(true) returns the entire form store and
|
||||
// keeps those sub-trees intact.
|
||||
const values = form.getFieldsValue(true) as InboundFormValues;
|
||||
const parsed = InboundFormSchema.safeParse(values);
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
const path = Array.isArray(issue?.path) && issue.path.length > 0
|
||||
? issue.path.join('.')
|
||||
: '';
|
||||
const baseMsg = issue?.message ?? 'somethingWentWrong';
|
||||
const display = path ? `${path}: ${baseMsg}` : baseMsg;
|
||||
messageApi.error(t(baseMsg, { defaultValue: display }));
|
||||
console.error('[InboundFormModal] schema validation failed', {
|
||||
path: issue?.path,
|
||||
message: issue?.message,
|
||||
values,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = formValuesToWirePayload(parsed.data);
|
||||
const url = mode === 'edit' && dbInbound
|
||||
? `/panel/api/inbounds/update/${dbInbound.id}`
|
||||
: '/panel/api/inbounds/add';
|
||||
const msg = await HttpUtil.post(url, payload);
|
||||
if (msg?.success) {
|
||||
if (isFallbackHost) {
|
||||
const obj = msg.obj as { id?: number; Id?: number } | null;
|
||||
const masterId = mode === 'edit'
|
||||
? dbInbound!.id
|
||||
: (obj?.id ?? obj?.Id ?? 0);
|
||||
if (masterId) await saveFallbacks(masterId);
|
||||
}
|
||||
onSaved();
|
||||
onClose();
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const title = mode === 'edit'
|
||||
? t('pages.inbounds.modifyInbound')
|
||||
: t('pages.inbounds.addInbound');
|
||||
|
||||
const okText = mode === 'edit'
|
||||
? t('pages.clients.submitEdit')
|
||||
: t('create');
|
||||
|
||||
const basicTab = (
|
||||
<>
|
||||
<Form.Item name="tag" hidden noStyle><Input /></Form.Item>
|
||||
<Form.Item name="up" hidden noStyle><InputNumber /></Form.Item>
|
||||
<Form.Item name="down" hidden noStyle><InputNumber /></Form.Item>
|
||||
<Form.Item name="total" hidden noStyle><InputNumber /></Form.Item>
|
||||
<Form.Item name="expiryTime" hidden noStyle><InputNumber /></Form.Item>
|
||||
<Form.Item name="lastTrafficResetTime" hidden noStyle><InputNumber /></Form.Item>
|
||||
<Form.Item name="clientStats" hidden noStyle><Input /></Form.Item>
|
||||
|
||||
<Form.Item name="enable" label={t('enable')} valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="remark" label={t('pages.inbounds.remark')}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
|
||||
{selectableNodes.length > 0 && isNodeEligible && (
|
||||
<Form.Item name="nodeId" label={t('pages.inbounds.deployTo')}>
|
||||
<Select
|
||||
disabled={mode === 'edit'}
|
||||
placeholder={t('pages.inbounds.localPanel')}
|
||||
allowClear
|
||||
options={selectableNodes.map((n) => ({
|
||||
value: n.id,
|
||||
label: `${n.name}${n.status === 'offline' ? ' (offline)' : ''}`,
|
||||
disabled: n.status === 'offline',
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
|
||||
<Form.Item name="protocol" label={t('pages.inbounds.protocol')}>
|
||||
<Select disabled={mode === 'edit'} options={PROTOCOL_OPTIONS} />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="listen" label={t('pages.inbounds.address')}>
|
||||
<Input placeholder={t('pages.inbounds.monitorDesc')} />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="port"
|
||||
label={t('pages.inbounds.port')}
|
||||
rules={[antdRule(InboundFormBaseSchema.shape.port, t)]}
|
||||
>
|
||||
<InputNumber min={1} max={65535} />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label={
|
||||
<Tooltip title={t('pages.inbounds.meansNoLimit')}>
|
||||
{t('pages.inbounds.totalFlow')}
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
<Form.Item
|
||||
noStyle
|
||||
shouldUpdate={(prev, curr) => prev.total !== curr.total}
|
||||
>
|
||||
{({ getFieldValue, setFieldValue }) => {
|
||||
const totalBytes = (getFieldValue('total') as number) ?? 0;
|
||||
const totalGB = totalBytes
|
||||
? Math.round((totalBytes / SizeFormatter.ONE_GB) * 100) / 100
|
||||
: 0;
|
||||
return (
|
||||
<InputNumber
|
||||
value={totalGB}
|
||||
min={0}
|
||||
step={1}
|
||||
onChange={(v) => {
|
||||
const bytes = NumberFormatter.toFixed(
|
||||
(Number(v) || 0) * SizeFormatter.ONE_GB,
|
||||
0,
|
||||
);
|
||||
setFieldValue('total', bytes);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</Form.Item>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item name="trafficReset" label={t('pages.inbounds.periodicTrafficResetTitle')}>
|
||||
<Select
|
||||
options={TRAFFIC_RESETS.map((r) => ({
|
||||
value: r,
|
||||
label: t(`pages.inbounds.periodicTrafficReset.${r}`),
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label={
|
||||
<Tooltip title={t('pages.inbounds.leaveBlankToNeverExpire')}>
|
||||
{t('pages.inbounds.expireDate')}
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
<Form.Item
|
||||
noStyle
|
||||
shouldUpdate={(prev, curr) => prev.expiryTime !== curr.expiryTime}
|
||||
>
|
||||
{({ getFieldValue, setFieldValue }) => {
|
||||
const expiry = (getFieldValue('expiryTime') as number) ?? 0;
|
||||
return (
|
||||
<DateTimePicker
|
||||
value={expiry > 0 ? dayjs(expiry) : null}
|
||||
onChange={(d) => setFieldValue('expiryTime', d ? d.valueOf() : 0)}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</Form.Item>
|
||||
</Form.Item>
|
||||
</>
|
||||
);
|
||||
|
||||
const fallbacksCard = (
|
||||
<FallbacksCard
|
||||
fallbacks={fallbacks}
|
||||
fallbackChildOptions={fallbackChildOptions}
|
||||
addFallback={addFallback}
|
||||
updateFallback={updateFallback}
|
||||
removeFallback={removeFallback}
|
||||
moveFallback={moveFallback}
|
||||
addAllFallbacks={addAllFallbacks}
|
||||
/>
|
||||
);
|
||||
|
||||
const protocolTab = (
|
||||
<>
|
||||
{protocol === Protocols.WIREGUARD && <WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} regenWgPeerKeypair={regenWgPeerKeypair} />}
|
||||
|
||||
{protocol === Protocols.TUN && <TunFields />}
|
||||
|
||||
{protocol === Protocols.TUNNEL && <TunnelFields />}
|
||||
|
||||
{protocol === Protocols.HTTP && <HttpFields />}
|
||||
{protocol === Protocols.MIXED && <MixedFields mixedUdpOn={mixedUdpOn} />}
|
||||
|
||||
{protocol === Protocols.SHADOWSOCKS && <ShadowsocksFields form={form} isSSWith2022={isSSWith2022} />}
|
||||
|
||||
{protocol === Protocols.VLESS && <VlessFields saving={saving} selectedVlessAuth={selectedVlessAuth} network={network} security={security} getNewVlessEnc={getNewVlessEnc} clearVlessEnc={clearVlessEnc} />}
|
||||
|
||||
{isFallbackHost && fallbacksCard}
|
||||
</>
|
||||
);
|
||||
|
||||
// Switching `network` swaps which per-network key (tcpSettings,
|
||||
// wsSettings, grpcSettings, ...) appears on the wire. Clear the old
|
||||
// network's blob and seed the new one with the schema defaults so the
|
||||
// Form.Items inside it have valid initial values (KCP needs MTU=1350
|
||||
// etc., not empty strings).
|
||||
// Seed each network's settings blob with its Zod schema defaults so
|
||||
// every Form.Item inside the network sub-form has a defined starting
|
||||
// value. XHTTP in particular has ~20 fields (sessionPlacement,
|
||||
// seqPlacement, xPaddingMethod, uplinkHTTPMethod, ...) whose value
|
||||
// is the literal "" sentinel meaning "let xray-core pick its
|
||||
// default". Without seeding "", the Form.Item reads `undefined` and
|
||||
// the Select shows blank instead of the "Default (path)" option.
|
||||
const newStreamSlice = (n: string): Record<string, unknown> => {
|
||||
switch (n) {
|
||||
case 'tcp': return TcpStreamSettingsSchema.parse({ header: { type: 'none' } });
|
||||
case 'kcp': return KcpStreamSettingsSchema.parse({});
|
||||
case 'ws': return WsStreamSettingsSchema.parse({});
|
||||
case 'grpc': return GrpcStreamSettingsSchema.parse({});
|
||||
case 'httpupgrade': return HttpUpgradeStreamSettingsSchema.parse({});
|
||||
case 'xhttp': return XHttpStreamSettingsSchema.parse({});
|
||||
default: return {};
|
||||
}
|
||||
};
|
||||
const onNetworkChange = (next: string) => {
|
||||
const ALL = ['tcpSettings', 'kcpSettings', 'wsSettings', 'grpcSettings', 'httpupgradeSettings', 'xhttpSettings'];
|
||||
const current = (form.getFieldValue('streamSettings') as Record<string, unknown>) ?? {};
|
||||
const cleaned: Record<string, unknown> = { ...current, network: next };
|
||||
for (const k of ALL) {
|
||||
if (k !== `${next}Settings`) delete cleaned[k];
|
||||
}
|
||||
cleaned[`${next}Settings`] = newStreamSlice(next);
|
||||
// mKCP wants a UDP mask wrapper on the FinalMask side; seed it with
|
||||
// `mkcp-original` so the inbound boots with a sensible default
|
||||
// instead of unobfuscated mKCP traffic. The user can still edit or
|
||||
// clear the mask via the FinalMask section.
|
||||
if (next === 'kcp') {
|
||||
const fm = (cleaned.finalmask as Record<string, unknown> | undefined) ?? {};
|
||||
const udp = Array.isArray(fm.udp) ? (fm.udp as unknown[]) : [];
|
||||
const hasMkcp = udp.some((m) => {
|
||||
const entry = m as { type?: string };
|
||||
return entry?.type === 'mkcp-original';
|
||||
});
|
||||
if (!hasMkcp) {
|
||||
cleaned.finalmask = {
|
||||
...fm,
|
||||
udp: [...udp, { type: 'mkcp-original', settings: {} }],
|
||||
};
|
||||
}
|
||||
}
|
||||
form.setFieldValue('streamSettings', cleaned);
|
||||
};
|
||||
|
||||
const streamTab = (
|
||||
<>
|
||||
{protocol !== Protocols.HYSTERIA && (
|
||||
<Form.Item label={t('transmission')} name={['streamSettings', 'network']}>
|
||||
<Select
|
||||
style={{ width: '75%' }}
|
||||
onChange={onNetworkChange}
|
||||
options={[
|
||||
{ value: 'tcp', label: 'RAW' },
|
||||
{ value: 'kcp', label: 'mKCP' },
|
||||
{ value: 'ws', label: 'WebSocket' },
|
||||
{ value: 'grpc', label: 'gRPC' },
|
||||
{ value: 'httpupgrade', label: 'HTTPUpgrade' },
|
||||
{ value: 'xhttp', label: 'XHTTP' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
|
||||
{/* Inbound Hysteria stream sub-form. The transport for hysteria
|
||||
isn't user-selectable (always 'hysteria'), so the network
|
||||
dropdown is hidden above. Fields here mirror the legacy
|
||||
HysteriaStreamSettings inbound class: version is locked to 2,
|
||||
auth + udpIdleTimeout are required, masquerade is an optional
|
||||
sub-object that lets xray-core disguise the listener as an
|
||||
HTTP server when probed. */}
|
||||
{protocol === Protocols.HYSTERIA && <HysteriaFields form={form} />}
|
||||
|
||||
{network === 'tcp' && <RawForm />}
|
||||
|
||||
{network === 'ws' && <WsForm />}
|
||||
|
||||
{network === 'grpc' && <GrpcForm />}
|
||||
|
||||
{network === 'xhttp' && <XhttpForm form={form} />}
|
||||
|
||||
{network === 'httpupgrade' && <HttpUpgradeForm />}
|
||||
|
||||
{network === 'kcp' && <KcpForm />}
|
||||
|
||||
<ExternalProxyForm toggleExternalProxy={toggleExternalProxy} />
|
||||
|
||||
<SockoptForm toggleSockopt={toggleSockopt} />
|
||||
|
||||
<FinalMaskForm
|
||||
name={['streamSettings', 'finalmask']}
|
||||
network={network as string}
|
||||
protocol={protocol}
|
||||
form={form}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
const securityTab = (
|
||||
<>
|
||||
<Form.Item name={['streamSettings', 'security']} hidden noStyle>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item label={t('pages.inbounds.securityTab')}>
|
||||
<Form.Item
|
||||
noStyle
|
||||
shouldUpdate={(prev, curr) =>
|
||||
prev.streamSettings?.security !== curr.streamSettings?.security
|
||||
|| prev.streamSettings?.network !== curr.streamSettings?.network
|
||||
|| prev.protocol !== curr.protocol
|
||||
}
|
||||
>
|
||||
{({ getFieldValue }) => {
|
||||
const sec = getFieldValue(['streamSettings', 'security']) ?? 'none';
|
||||
const net = getFieldValue(['streamSettings', 'network']) ?? '';
|
||||
const proto = getFieldValue('protocol') ?? '';
|
||||
const tlsOk = canEnableTls({ protocol: proto, streamSettings: { network: net, security: sec } });
|
||||
const realityOk = canEnableReality({ protocol: proto, streamSettings: { network: net, security: sec } });
|
||||
const tlsOnly = proto === Protocols.HYSTERIA;
|
||||
return (
|
||||
<Radio.Group
|
||||
value={sec}
|
||||
buttonStyle="solid"
|
||||
disabled={!tlsOk}
|
||||
onChange={(e) => onSecurityChange(e.target.value)}
|
||||
>
|
||||
{!tlsOnly && <Radio.Button value="none">{t('none')}</Radio.Button>}
|
||||
<Radio.Button value="tls">TLS</Radio.Button>
|
||||
{realityOk && <Radio.Button value="reality">Reality</Radio.Button>}
|
||||
</Radio.Group>
|
||||
);
|
||||
}}
|
||||
</Form.Item>
|
||||
</Form.Item>
|
||||
|
||||
{security === 'tls' && (
|
||||
<TlsForm
|
||||
saving={saving}
|
||||
setCertFromPanel={setCertFromPanel}
|
||||
clearCertFiles={clearCertFiles}
|
||||
generateRandomPinHash={generateRandomPinHash}
|
||||
getNewEchCert={getNewEchCert}
|
||||
clearEchCert={clearEchCert}
|
||||
/>
|
||||
)}
|
||||
|
||||
{security === 'reality' && (
|
||||
<RealityForm
|
||||
saving={saving}
|
||||
randomizeRealityTarget={randomizeRealityTarget}
|
||||
randomizeShortIds={randomizeShortIds}
|
||||
genRealityKeypair={genRealityKeypair}
|
||||
clearRealityKeypair={clearRealityKeypair}
|
||||
genMldsa65={genMldsa65}
|
||||
clearMldsa65={clearMldsa65}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
const advancedTab = (
|
||||
<div className="advanced-shell">
|
||||
<div className="advanced-panel">
|
||||
<div className="advanced-panel__header">
|
||||
<div>
|
||||
<div className="advanced-panel__title">{t('pages.inbounds.advanced.title')}</div>
|
||||
<div className="advanced-panel__subtitle">{t('pages.inbounds.advanced.subtitle')}</div>
|
||||
</div>
|
||||
</div>
|
||||
<Tabs
|
||||
className="advanced-inner-tabs"
|
||||
items={[
|
||||
{
|
||||
key: 'all',
|
||||
label: t('pages.inbounds.advanced.all'),
|
||||
children: (
|
||||
<>
|
||||
<div className="advanced-editor-meta">
|
||||
{t('pages.inbounds.advanced.allHelp')}
|
||||
</div>
|
||||
<AdvancedAllEditor form={form} streamEnabled={streamEnabled} />
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'settings',
|
||||
label: t('pages.inbounds.advanced.settings'),
|
||||
children: (
|
||||
<>
|
||||
<div className="advanced-editor-meta">
|
||||
{t('pages.inbounds.advanced.settingsHelp')}{' '}
|
||||
<code>{'{ settings: { ... } }'}</code>.
|
||||
</div>
|
||||
<AdvancedSliceEditor
|
||||
form={form}
|
||||
path="settings"
|
||||
wrapKey="settings"
|
||||
minHeight="320px"
|
||||
maxHeight="540px"
|
||||
/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
...(streamEnabled
|
||||
? [{
|
||||
key: 'stream',
|
||||
label: t('pages.inbounds.advanced.stream'),
|
||||
children: (
|
||||
<>
|
||||
<div className="advanced-editor-meta">
|
||||
{t('pages.inbounds.advanced.streamHelp')}{' '}
|
||||
<code>{'{ streamSettings: { ... } }'}</code>.
|
||||
</div>
|
||||
<AdvancedSliceEditor
|
||||
form={form}
|
||||
path="streamSettings"
|
||||
wrapKey="streamSettings"
|
||||
minHeight="320px"
|
||||
maxHeight="540px"
|
||||
/>
|
||||
</>
|
||||
),
|
||||
}]
|
||||
: []),
|
||||
{
|
||||
key: 'sniffing',
|
||||
label: t('pages.inbounds.advanced.sniffing'),
|
||||
children: (
|
||||
<>
|
||||
<div className="advanced-editor-meta">
|
||||
{t('pages.inbounds.advanced.sniffingHelp')}{' '}
|
||||
<code>{'{ sniffing: { ... } }'}</code>.
|
||||
</div>
|
||||
<AdvancedSliceEditor
|
||||
form={form}
|
||||
path="sniffing"
|
||||
wrapKey="sniffing"
|
||||
minHeight="240px"
|
||||
maxHeight="420px"
|
||||
/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const sniffingTab = <SniffingTab sniffingEnabled={sniffingEnabled} />;
|
||||
|
||||
return (
|
||||
<>
|
||||
{messageContextHolder}
|
||||
<Modal
|
||||
open={open}
|
||||
title={title}
|
||||
okText={okText}
|
||||
cancelText={t('close')}
|
||||
confirmLoading={saving}
|
||||
mask={{ closable: false }}
|
||||
width={780}
|
||||
onOk={submit}
|
||||
onCancel={onClose}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Form
|
||||
form={form}
|
||||
colon={false}
|
||||
labelCol={{ sm: { span: 8 } }}
|
||||
wrapperCol={{ sm: { span: 14 } }}
|
||||
onValuesChange={onValuesChange}
|
||||
>
|
||||
<Tabs items={[
|
||||
// forceRender on every tab so all Form.Items register at modal
|
||||
// open, not lazily on first visit. Without it, AntD's items API
|
||||
// lazy-mounts inactive tabs — their fields don't register, so
|
||||
// Form.useWatch on a parent path (e.g. 'sniffing') returns the
|
||||
// partial-view {} until the user touches the tab and the
|
||||
// inner Form.Item for `sniffing.enabled` registers.
|
||||
{ key: 'basic', label: t('pages.xray.basicTemplate'), children: basicTab, forceRender: true },
|
||||
...(([
|
||||
Protocols.VLESS,
|
||||
Protocols.SHADOWSOCKS,
|
||||
Protocols.HTTP,
|
||||
Protocols.MIXED,
|
||||
Protocols.TUNNEL,
|
||||
Protocols.TUN,
|
||||
Protocols.WIREGUARD,
|
||||
] as string[]).includes(protocol) || isFallbackHost
|
||||
? [{ key: 'protocol', label: t('pages.inbounds.protocol'), children: protocolTab, forceRender: true }]
|
||||
: []),
|
||||
...(streamEnabled
|
||||
? [
|
||||
{ key: 'stream', label: t('pages.inbounds.streamTab'), children: streamTab, forceRender: true },
|
||||
{ key: 'security', label: t('pages.inbounds.securityTab'), children: securityTab, forceRender: true },
|
||||
]
|
||||
: []),
|
||||
{ key: 'sniffing', label: t('pages.inbounds.sniffingTab'), children: sniffingTab, forceRender: true },
|
||||
{ key: 'advanced', label: t('pages.xray.advancedTemplate'), children: advancedTab, forceRender: true },
|
||||
]} />
|
||||
</Form>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user