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:
Sanaei
2026-05-30 21:51:33 +02:00
committed by GitHub
parent 84a689cf10
commit d1882c7f29
188 changed files with 10471 additions and 7812 deletions
-283
View File
@@ -1,283 +0,0 @@
.ant-sidebar > .ant-layout-sider {
position: sticky;
top: 0;
height: 100vh;
align-self: flex-start;
}
.sider-brand,
.drawer-brand {
font-weight: 600;
font-size: 18px;
letter-spacing: 0.5px;
color: var(--ant-color-text);
}
.sider-brand {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 14px 16px 14px 24px;
border-bottom: 1px solid var(--ant-color-border-secondary);
user-select: none;
}
.sider-brand-collapsed {
justify-content: center;
font-size: 16px;
padding: 14px 4px;
letter-spacing: 0;
}
.brand-block {
display: inline-flex;
align-items: center;
min-width: 0;
line-height: 1.1;
}
.sider-brand-collapsed .brand-block {
flex: 0 0 auto;
}
.brand-actions {
display: inline-flex;
align-items: center;
gap: 2px;
flex-shrink: 0;
}
.sidebar-donate {
background: transparent;
border: none;
width: 30px;
height: 30px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--ant-color-text-secondary);
text-decoration: none;
flex-shrink: 0;
transition: background-color 0.2s, transform 0.15s, color 0.2s;
}
.sidebar-donate:hover,
.sidebar-donate:focus-visible {
background-color: rgba(236, 72, 153, 0.12);
color: #ec4899;
transform: scale(1.08);
outline: none;
}
.sidebar-donate .anticon {
font-size: 16px;
}
.sidebar-theme-cycle {
background: transparent;
border: none;
width: 30px;
height: 30px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: var(--ant-color-text-secondary);
padding: 0;
flex-shrink: 0;
transition: background-color 0.2s, transform 0.15s, color 0.2s;
}
.sidebar-theme-cycle:hover,
.sidebar-theme-cycle:focus-visible {
background-color: color-mix(in srgb, var(--ant-color-primary) 12%, transparent);
color: var(--ant-color-primary);
transform: scale(1.08);
outline: none;
}
.sidebar-theme-cycle .anticon {
font-size: 16px;
}
.drawer-header-actions {
display: inline-flex;
align-items: center;
gap: 4px;
}
.drawer-handle {
position: fixed;
top: 12px;
left: 12px;
z-index: 1100;
background: rgba(0, 0, 0, 0.55);
color: #fff;
border: none;
width: 40px;
height: 40px;
border-radius: 50%;
cursor: pointer;
display: none;
align-items: center;
justify-content: center;
font-size: 18px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
}
.drawer-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 16px;
border-bottom: 1px solid var(--ant-color-border-secondary);
}
.drawer-close {
background: transparent;
border: none;
width: 32px;
height: 32px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
font-size: 16px;
color: var(--ant-color-text-secondary);
}
.drawer-close:hover,
.drawer-close:focus-visible {
background: var(--ant-color-fill-tertiary);
}
.drawer-menu .ant-menu-item {
height: 48px;
line-height: 48px;
margin: 0;
border-radius: 0;
}
.drawer-menu .ant-menu-item .anticon {
font-size: 16px;
}
.drawer-utility {
margin-top: auto;
border-top: 1px solid var(--ant-color-border-secondary);
}
.ant-sidebar > .ant-layout-sider .ant-layout-sider-children {
display: flex;
flex-direction: column;
height: 100%;
}
.sider-nav {
flex: 1 1 auto;
overflow-y: auto;
overflow-x: hidden;
min-height: 0;
}
.sider-utility {
flex: 0 0 auto;
border-top: 1px solid var(--ant-color-border-secondary);
}
.sider-footer {
flex: 0 0 auto;
padding: 8px 8px 12px;
}
.sider-version {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 10px;
width: 100%;
padding: 8px 16px;
color: var(--ant-color-text-secondary);
font-size: 13px;
font-weight: 500;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
text-decoration: none;
transition: color 0.2s;
}
.sider-version .anticon {
font-size: 16px;
}
.sider-version:hover,
.sider-version:focus-visible {
color: var(--ant-color-primary);
outline: none;
}
.sider-version.is-collapsed {
justify-content: center;
padding: 8px 0;
}
.drawer-footer {
flex: 0 0 auto;
padding: 8px 8px 12px;
}
@media (max-width: 768px) {
.drawer-handle {
display: inline-flex;
}
.ant-sidebar > .ant-layout-sider .ant-layout-sider-children,
.ant-sidebar > .ant-layout-sider .ant-layout-sider-trigger {
display: none;
}
.ant-sidebar > .ant-layout-sider {
flex: 0 0 0 !important;
max-width: 0 !important;
min-width: 0 !important;
width: 0 !important;
}
}
body.dark .ant-drawer-content,
body.dark .ant-drawer-body {
background-color: #15161a;
}
html[data-theme="ultra-dark"] body.dark .ant-drawer-content,
html[data-theme="ultra-dark"] body.dark .ant-drawer-body {
background-color: #050507;
}
body.dark .ant-drawer-body .drawer-menu,
body.dark .ant-drawer-body .drawer-menu.ant-menu-dark,
body.dark .ant-drawer-body .drawer-menu .ant-menu-item,
body.dark .ant-drawer-body .drawer-menu .ant-menu-sub,
body.dark .ant-drawer-body .drawer-menu .ant-menu-item-group-list {
background-color: transparent;
}
.sider-nav .ant-menu-item-selected,
.sider-utility .ant-menu-item-selected,
.drawer-menu .ant-menu-item-selected {
background-color: color-mix(in srgb, var(--ant-color-primary) 20%, transparent) !important;
color: var(--ant-color-primary) !important;
}
.sider-nav .ant-menu-item-active:not(.ant-menu-item-selected),
.sider-utility .ant-menu-item-active:not(.ant-menu-item-selected),
.drawer-menu .ant-menu-item-active:not(.ant-menu-item-selected),
.sider-nav .ant-menu-item:not(.ant-menu-item-selected):not(.ant-menu-item-disabled):hover,
.sider-utility .ant-menu-item:not(.ant-menu-item-selected):not(.ant-menu-item-disabled):hover,
.drawer-menu .ant-menu-item:not(.ant-menu-item-selected):not(.ant-menu-item-disabled):hover {
background-color: color-mix(in srgb, var(--ant-color-primary) 10%, transparent) !important;
color: var(--ant-color-primary) !important;
}
-301
View File
@@ -1,301 +0,0 @@
import { useCallback, useMemo, useState } from 'react';
import type { ComponentType } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Drawer, Layout, Menu } from 'antd';
import type { MenuProps } from 'antd';
import {
ApiOutlined,
ClusterOutlined,
CloseOutlined,
DashboardOutlined,
GithubOutlined,
HeartOutlined,
ImportOutlined,
LogoutOutlined,
MenuOutlined,
MoonFilled,
MoonOutlined,
SettingOutlined,
SunOutlined,
TagsOutlined,
TeamOutlined,
ToolOutlined,
} from '@ant-design/icons';
import { HttpUtil } from '@/utils';
import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme';
import './AppSidebar.css';
const SIDEBAR_COLLAPSED_KEY = 'isSidebarCollapsed';
const DONATE_URL = 'https://donate.sanaei.dev/';
const REPO_URL = 'https://github.com/MHSanaei/3x-ui';
const LOGOUT_KEY = '__logout__';
type IconName = 'dashboard' | 'inbound' | 'team' | 'groups' | 'setting' | 'tool' | 'cluster' | 'logout' | 'apidocs';
const iconByName: Record<IconName, ComponentType> = {
dashboard: DashboardOutlined,
inbound: ImportOutlined,
team: TeamOutlined,
groups: TagsOutlined,
setting: SettingOutlined,
tool: ToolOutlined,
cluster: ClusterOutlined,
logout: LogoutOutlined,
apidocs: ApiOutlined,
};
function readCollapsed(): boolean {
try {
return JSON.parse(localStorage.getItem(SIDEBAR_COLLAPSED_KEY) || 'false');
} catch {
return false;
}
}
function DonateButton({ ariaLabel }: { ariaLabel: string }) {
return (
<a
href={DONATE_URL}
target="_blank"
rel="noopener noreferrer"
className="sidebar-donate"
aria-label={ariaLabel}
title={ariaLabel}
>
<HeartOutlined />
</a>
);
}
function VersionBadge({ version, collapsed }: { version: string; collapsed?: boolean }) {
if (!version) return null;
const label = `v${version}`;
return (
<a
href={REPO_URL}
target="_blank"
rel="noopener noreferrer"
className={`sider-version${collapsed ? ' is-collapsed' : ''}`}
aria-label={`GitHub ${label}`}
title={label}
>
<GithubOutlined />
{!collapsed && <span className="sider-version-text">{label}</span>}
</a>
);
}
function ThemeCycleButton({ id, isDark, isUltra, onCycle, ariaLabel }: {
id: string;
isDark: boolean;
isUltra: boolean;
onCycle: () => void;
ariaLabel: string;
}) {
const icon = !isDark ? <SunOutlined /> : !isUltra ? <MoonOutlined /> : <MoonFilled />;
return (
<button
id={id}
type="button"
className="sidebar-theme-cycle"
aria-label={ariaLabel}
title={ariaLabel}
onClick={onCycle}
>
{icon}
</button>
);
}
export default function AppSidebar() {
const { t } = useTranslation();
const { isDark, isUltra, toggleTheme, toggleUltra } = useTheme();
const navigate = useNavigate();
const { pathname } = useLocation();
const [collapsed, setCollapsed] = useState<boolean>(() => readCollapsed());
const [drawerOpen, setDrawerOpen] = useState(false);
const currentTheme: 'light' | 'dark' = isDark ? 'dark' : 'light';
const panelVersion = window.X_UI_CUR_VER || '';
const tabs = useMemo<{ key: string; icon: IconName; title: string }[]>(() => [
{ key: '/', icon: 'dashboard', title: t('menu.dashboard') },
{ key: '/inbounds', icon: 'inbound', title: t('menu.inbounds') },
{ key: '/clients', icon: 'team', title: t('menu.clients') },
{ key: '/groups', icon: 'groups', title: t('menu.groups') },
{ key: '/nodes', icon: 'cluster', title: t('menu.nodes') },
{ key: '/settings', icon: 'setting', title: t('menu.settings') },
{ key: '/xray', icon: 'tool', title: t('menu.xray') },
{ key: '/api-docs', icon: 'apidocs', title: t('menu.apiDocs') },
{ key: LOGOUT_KEY, icon: 'logout', title: t('logout') },
], [t]);
const navItems = useMemo(() => tabs.filter((tab) => tab.icon !== 'logout'), [tabs]);
const utilItems = useMemo(() => tabs.filter((tab) => tab.icon === 'logout'), [tabs]);
const selectedKey = pathname === '' ? '/' : pathname;
const toMenuItems = useCallback((items: typeof tabs): MenuProps['items'] =>
items.map((tab) => {
const Icon = iconByName[tab.icon];
return {
key: tab.key,
icon: <Icon />,
label: tab.title,
};
}),
[]);
const openLink = useCallback(async (key: string) => {
if (key === LOGOUT_KEY) {
await HttpUtil.post('/logout');
window.location.href = window.X_UI_BASE_PATH || '/';
return;
}
navigate(key);
}, [navigate]);
const onMenuClick = useCallback<NonNullable<MenuProps['onClick']>>(({ key }) => {
openLink(String(key));
}, [openLink]);
const onSiderCollapse = useCallback((isCollapsed: boolean, type: 'clickTrigger' | 'responsive') => {
if (type === 'clickTrigger') {
localStorage.setItem(SIDEBAR_COLLAPSED_KEY, String(isCollapsed));
setCollapsed(isCollapsed);
}
}, []);
const cycleTheme = useCallback((id: string) => {
pauseAnimationsUntilLeave(id);
if (!isDark) {
toggleTheme();
if (isUltra) toggleUltra();
} else if (!isUltra) {
toggleUltra();
} else {
toggleUltra();
toggleTheme();
}
}, [isDark, isUltra, toggleTheme, toggleUltra]);
return (
<div className="ant-sidebar">
<Layout.Sider
theme={currentTheme}
collapsible
collapsed={collapsed}
breakpoint="md"
onCollapse={onSiderCollapse}
>
<div className={`sider-brand${collapsed ? ' sider-brand-collapsed' : ''}`}>
<div className="brand-block">
<span className="brand-text">{collapsed ? '3X' : '3X-UI'}</span>
</div>
{!collapsed && (
<div className="brand-actions">
<DonateButton ariaLabel={t('menu.donate') || 'Donate'} />
<ThemeCycleButton
id="theme-cycle"
isDark={isDark}
isUltra={isUltra}
onCycle={() => cycleTheme('theme-cycle')}
ariaLabel={t('menu.theme')}
/>
</div>
)}
</div>
<Menu
theme={currentTheme}
mode="inline"
selectedKeys={[selectedKey]}
className="sider-nav"
items={toMenuItems(navItems)}
onClick={onMenuClick}
/>
<Menu
theme={currentTheme}
mode="inline"
selectedKeys={[selectedKey]}
className="sider-utility"
items={toMenuItems(utilItems)}
onClick={onMenuClick}
/>
<div className="sider-footer">
<VersionBadge version={panelVersion} collapsed={collapsed} />
</div>
</Layout.Sider>
<Drawer
placement="left"
closable={false}
open={drawerOpen}
rootClassName={currentTheme}
size="min(82vw, 320px)"
styles={{
wrapper: { padding: 0 },
body: { padding: 0, display: 'flex', flexDirection: 'column', height: '100%' },
header: { display: 'none' },
}}
onClose={() => setDrawerOpen(false)}
>
<div className="drawer-header">
<div className="brand-block">
<span className="drawer-brand">3X-UI</span>
</div>
<div className="drawer-header-actions">
<DonateButton ariaLabel={t('menu.donate') || 'Donate'} />
<ThemeCycleButton
id="theme-cycle-drawer"
isDark={isDark}
isUltra={isUltra}
onCycle={() => cycleTheme('theme-cycle-drawer')}
ariaLabel={t('menu.theme')}
/>
<button
className="drawer-close"
type="button"
aria-label={t('close')}
onClick={() => setDrawerOpen(false)}
>
<CloseOutlined />
</button>
</div>
</div>
<Menu
theme={currentTheme}
mode="inline"
selectedKeys={[selectedKey]}
className="drawer-menu drawer-nav"
items={toMenuItems(navItems)}
onClick={(info) => { onMenuClick(info); setDrawerOpen(false); }}
/>
<Menu
theme={currentTheme}
mode="inline"
selectedKeys={[selectedKey]}
className="drawer-menu drawer-utility"
items={toMenuItems(utilItems)}
onClick={(info) => { onMenuClick(info); setDrawerOpen(false); }}
/>
<div className="drawer-footer">
<VersionBadge version={panelVersion} />
</div>
</Drawer>
{!drawerOpen && (
<button
className="drawer-handle"
type="button"
aria-label={t('menu.dashboard')}
onClick={() => setDrawerOpen(true)}
>
<MenuOutlined />
</button>
)}
</div>
);
}
-766
View File
@@ -1,766 +0,0 @@
import { Button, Divider, Form, Input, InputNumber, Select, Space, Switch } from 'antd';
import { DeleteOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd/es/form';
import type { NamePath } from 'antd/es/form/interface';
import { RandomUtil } from '@/utils';
import { OutboundProtocols } from '@/schemas/primitives';
// Pattern A FinalMaskForm. Renders a Fragment of Form.Items at absolute
// paths under `name`; the parent modal owns the Form instance.
//
// Naming convention inside Form.List: AntD prefixes Form.Item `name`
// with the Form.List's own `name`. So Form.Items inside the render
// prop use RELATIVE paths (e.g. `[field.name, 'type']`). Nested
// Form.Lists also use relative names. Using absolute paths here would
// double up the prefix and silently route reads/writes to the wrong
// storage path.
export interface FinalMaskFormProps {
name: NamePath;
network: string;
protocol: string;
form: FormInstance;
}
const TCP_NETWORKS = ['raw', 'tcp', 'httpupgrade', 'ws', 'grpc', 'xhttp'];
function asPath(name: NamePath): (string | number)[] {
return Array.isArray(name) ? [...name] : [name];
}
function defaultTcpMaskSettings(type: string): Record<string, unknown> {
switch (type) {
case 'fragment':
return { packets: '1-3', length: '', delay: '', maxSplit: '' };
case 'sudoku':
return {
password: '', ascii: '', customTable: '', customTables: '',
paddingMin: 0, paddingMax: 0,
};
case 'header-custom':
return { clients: [], servers: [] };
default:
return {};
}
}
function defaultUdpMaskSettings(type: string): Record<string, unknown> {
switch (type) {
case 'salamander':
case 'mkcp-aes128gcm':
return { password: '' };
case 'header-dns':
return { domain: '' };
case 'xdns':
return { domains: [] };
case 'xicmp':
return { ip: '0.0.0.0', id: 0 };
case 'header-custom':
return { client: [], server: [] };
case 'noise':
return { reset: 0, noise: [] };
default:
return {};
}
}
function defaultClientServerItem(): Record<string, unknown> {
return { delay: 0, rand: 0, randRange: '0-255', type: 'array', packet: [] };
}
function defaultUdpClientServerItem(): Record<string, unknown> {
return { rand: 0, randRange: '0-255', type: 'array', packet: [] };
}
function defaultNoiseItem(): Record<string, unknown> {
return {
rand: '1-8192', randRange: '0-255', type: 'array', packet: [], delay: '10-20',
};
}
function defaultQuicParams(): Record<string, unknown> {
return {
congestion: 'bbr',
debug: false,
maxIdleTimeout: 30,
keepAlivePeriod: 10,
disablePathMTUDiscovery: false,
maxIncomingStreams: 1024,
initStreamReceiveWindow: 8388608,
maxStreamReceiveWindow: 8388608,
initConnectionReceiveWindow: 20971520,
maxConnectionReceiveWindow: 20971520,
};
}
function defaultUdpHop(): Record<string, unknown> {
return { ports: '20000-50000', interval: '5-10' };
}
export default function FinalMaskForm({ name, network, protocol, form }: FinalMaskFormProps) {
const base = asPath(name);
const isHysteria = protocol === OutboundProtocols.Hysteria || protocol === 'hysteria';
const showTcp = TCP_NETWORKS.includes(network);
const showUdp = isHysteria || network === 'kcp';
const showQuic = isHysteria || network === 'xhttp';
const quicParams = Form.useWatch([...base, 'quicParams'], { form, preserve: true });
const hasQuicParams = quicParams != null;
if (!showTcp && !showUdp && !showQuic) return null;
return (
<>
{showTcp && <TcpMasksList base={base} form={form} />}
{showUdp && <UdpMasksList base={base} form={form} isHysteria={isHysteria} network={network} />}
{showQuic && (
<>
<Form.Item label="QUIC Params">
<Switch
checked={hasQuicParams}
onChange={(v) => {
form.setFieldValue([...base, 'quicParams'], v ? defaultQuicParams() : undefined);
}}
/>
</Form.Item>
{hasQuicParams && <QuicParamsForm base={[...base, 'quicParams']} form={form} />}
</>
)}
</>
);
}
function TcpMasksList({ base, form }: { base: (string | number)[]; form: FormInstance }) {
return (
<Form.List name={[...base, 'tcp']}>
{(fields, { add, remove }) => (
<>
<Form.Item label="TCP Masks">
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={() => add({ type: 'fragment', settings: defaultTcpMaskSettings('fragment') })}
/>
</Form.Item>
{fields.map((field, mIdx) => (
<TcpMaskItem
key={field.key}
fieldName={field.name}
displayIndex={mIdx + 1}
form={form}
listPath={[...base, 'tcp']}
onRemove={() => remove(field.name)}
/>
))}
</>
)}
</Form.List>
);
}
function TcpMaskItem({
fieldName, displayIndex, form, listPath, onRemove,
}: {
fieldName: number;
displayIndex: number;
form: FormInstance;
listPath: (string | number)[];
onRemove: () => void;
}) {
// Absolute path for setFieldValue side effects (resetting settings on
// type change). All Form.Item `name=` use RELATIVE paths within the
// outer Form.List context.
const absolutePath = [...listPath, fieldName];
return (
<div>
<Divider style={{ margin: 0 }}>
TCP Mask {displayIndex}
<DeleteOutlined className="danger-icon" onClick={onRemove} />
</Divider>
<Form.Item label="Type" name={[fieldName, 'type']}>
<Select
onChange={(v) =>
form.setFieldValue([...absolutePath, 'settings'], defaultTcpMaskSettings(v))
}
options={[
{ value: 'fragment', label: 'Fragment' },
{ value: 'header-custom', label: 'Header Custom' },
{ value: 'sudoku', label: 'Sudoku' },
]}
/>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prev, curr) => {
const a = getDeep(prev, [...absolutePath, 'type']);
const b = getDeep(curr, [...absolutePath, 'type']);
return a !== b;
}}
>
{({ getFieldValue }) => {
const type = getFieldValue([...absolutePath, 'type']) as string | undefined;
if (type === 'fragment') {
return (
<>
<Form.Item label="Packets" name={[fieldName, 'settings', 'packets']}>
<Select
options={[
{ value: 'tlshello', label: 'tlshello' },
{ value: '1-3', label: '1-3' },
{ value: '1-5', label: '1-5' },
]}
/>
</Form.Item>
<Form.Item label="Length" name={[fieldName, 'settings', 'length']}>
<Input />
</Form.Item>
<Form.Item label="Delay" name={[fieldName, 'settings', 'delay']}>
<Input />
</Form.Item>
<Form.Item label="Max Split" name={[fieldName, 'settings', 'maxSplit']}>
<Input />
</Form.Item>
</>
);
}
if (type === 'sudoku') {
return (
<>
<Form.Item label="Password" name={[fieldName, 'settings', 'password']}><Input /></Form.Item>
<Form.Item label="ASCII" name={[fieldName, 'settings', 'ascii']}><Input /></Form.Item>
<Form.Item label="Custom Table" name={[fieldName, 'settings', 'customTable']}><Input /></Form.Item>
<Form.Item label="Custom Tables" name={[fieldName, 'settings', 'customTables']}><Input /></Form.Item>
<Form.Item label="Padding Min" name={[fieldName, 'settings', 'paddingMin']}>
<InputNumber min={0} />
</Form.Item>
<Form.Item label="Padding Max" name={[fieldName, 'settings', 'paddingMax']}>
<InputNumber min={0} />
</Form.Item>
</>
);
}
if (type === 'header-custom') {
return (
<HeaderCustomGroups
tcpFieldName={fieldName}
form={form}
absoluteSettingsPath={[...absolutePath, 'settings']}
/>
);
}
return null;
}}
</Form.Item>
</div>
);
}
// Walks a deep object path safely. Used inside shouldUpdate which gets
// the whole form values blob; we need to compare a deep field across
// prev/curr without crashing on missing intermediates.
function getDeep(obj: unknown, path: (string | number)[]): unknown {
let cur: unknown = obj;
for (const key of path) {
if (cur == null || typeof cur !== 'object') return undefined;
cur = (cur as Record<string | number, unknown>)[key];
}
return cur;
}
function HeaderCustomGroups({
tcpFieldName, form, absoluteSettingsPath,
}: {
tcpFieldName: number;
form: FormInstance;
absoluteSettingsPath: (string | number)[];
}) {
return (
<>
{(['clients', 'servers'] as const).map((groupKey) => (
<Form.List key={groupKey} name={[tcpFieldName, 'settings', groupKey]}>
{(groups, { add: addGroup, remove: removeGroup }) => (
<>
<Form.Item label={groupKey === 'clients' ? 'Clients' : 'Servers'}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={() => addGroup([defaultClientServerItem()])}
/>
</Form.Item>
{groups.map((group, gi) => (
<div key={group.key}>
<Divider style={{ margin: 0 }}>
{groupKey === 'clients' ? 'Clients' : 'Servers'} Group {gi + 1}
<DeleteOutlined className="danger-icon" onClick={() => removeGroup(group.name)} />
</Divider>
<Form.List name={[group.name]}>
{(items, { add: addItem, remove: removeItem }) => (
<>
<Form.Item label="Items">
<Button
size="small"
icon={<PlusOutlined />}
onClick={() => addItem(defaultClientServerItem())}
/>
</Form.Item>
{items.map((item) => (
<ItemEditor
key={item.key}
fieldName={item.name}
form={form}
absoluteItemPath={[...absoluteSettingsPath, groupKey, group.name, item.name]}
delayMode="number"
onRemove={() => removeItem(item.name)}
/>
))}
</>
)}
</Form.List>
</div>
))}
</>
)}
</Form.List>
))}
</>
);
}
function UdpMasksList({
base, form, isHysteria, network,
}: { base: (string | number)[]; form: FormInstance; isHysteria: boolean; network: string }) {
return (
<Form.List name={[...base, 'udp']}>
{(fields, { add, remove }) => (
<>
<Form.Item label="UDP Masks">
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={() => {
const def = isHysteria ? 'salamander' : 'mkcp-aes128gcm';
add({ type: def, settings: defaultUdpMaskSettings(def) });
}}
/>
</Form.Item>
{fields.map((field, mIdx) => (
<UdpMaskItem
key={field.key}
fieldName={field.name}
displayIndex={mIdx + 1}
form={form}
listPath={[...base, 'udp']}
isHysteria={isHysteria}
network={network}
onRemove={() => remove(field.name)}
/>
))}
</>
)}
</Form.List>
);
}
function UdpMaskItem({
fieldName, displayIndex, form, listPath, isHysteria, network, onRemove,
}: {
fieldName: number;
displayIndex: number;
form: FormInstance;
listPath: (string | number)[];
isHysteria: boolean;
network: string;
onRemove: () => void;
}) {
const absolutePath = [...listPath, fieldName];
const onTypeChange = (v: string) => {
form.setFieldValue([...absolutePath, 'settings'], defaultUdpMaskSettings(v));
if (network === 'kcp') {
const kcpMtuPath = [...listPath.slice(0, -1), 'kcpSettings', 'mtu'];
form.setFieldValue(kcpMtuPath, v === 'xdns' ? 900 : 1350);
}
};
const options = isHysteria
? [{ value: 'salamander', label: 'Salamander (Hysteria2)' }]
: [
{ value: 'mkcp-aes128gcm', label: 'mKCP AES-128-GCM' },
{ value: 'header-dns', label: 'Header DNS' },
{ value: 'header-dtls', label: 'Header DTLS 1.2' },
{ value: 'header-srtp', label: 'Header SRTP' },
{ value: 'header-utp', label: 'Header uTP' },
{ value: 'header-wechat', label: 'Header WeChat Video' },
{ value: 'header-wireguard', label: 'Header WireGuard' },
{ value: 'mkcp-original', label: 'mKCP Original' },
{ value: 'xdns', label: 'xDNS' },
{ value: 'xicmp', label: 'xICMP' },
{ value: 'header-custom', label: 'Header Custom' },
{ value: 'noise', label: 'Noise' },
];
return (
<div>
<Divider style={{ margin: 0 }}>
UDP Mask {displayIndex}
<DeleteOutlined className="danger-icon" onClick={onRemove} />
</Divider>
<Form.Item label="Type" name={[fieldName, 'type']}>
<Select onChange={onTypeChange} options={options} />
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prev, curr) => getDeep(prev, [...absolutePath, 'type']) !== getDeep(curr, [...absolutePath, 'type'])}
>
{({ getFieldValue }) => {
const type = getFieldValue([...absolutePath, 'type']) as string | undefined;
if (type === 'mkcp-aes128gcm' || type === 'salamander') {
return (
<Form.Item label="Password">
<Space.Compact block>
<Form.Item name={[fieldName, 'settings', 'password']} noStyle>
<Input placeholder="Obfuscation password" style={{ width: 'calc(100% - 32px)' }} />
</Form.Item>
<Button
icon={<ReloadOutlined />}
onClick={() => form.setFieldValue(
[...absolutePath, 'settings', 'password'],
RandomUtil.randomLowerAndNum(16),
)}
/>
</Space.Compact>
</Form.Item>
);
}
if (type === 'header-dns') {
return (
<Form.Item label="Domain" name={[fieldName, 'settings', 'domain']}>
<Input placeholder="e.g., www.example.com" />
</Form.Item>
);
}
if (type === 'xdns') {
return (
<Form.Item label="Domains" name={[fieldName, 'settings', 'domains']}>
<Select mode="tags" style={{ width: '100%' }} tokenSeparators={[',']} />
</Form.Item>
);
}
if (type === 'xicmp') {
return (
<>
<Form.Item label="IP" name={[fieldName, 'settings', 'ip']}>
<Input placeholder="0.0.0.0" />
</Form.Item>
<Form.Item label="ID" name={[fieldName, 'settings', 'id']}>
<InputNumber min={0} />
</Form.Item>
</>
);
}
if (type === 'header-custom') {
return (
<UdpHeaderCustom
udpFieldName={fieldName}
form={form}
absoluteSettingsPath={[...absolutePath, 'settings']}
/>
);
}
if (type === 'noise') {
return (
<NoiseItems
udpFieldName={fieldName}
form={form}
absoluteSettingsPath={[...absolutePath, 'settings']}
/>
);
}
return null;
}}
</Form.Item>
</div>
);
}
function UdpHeaderCustom({
udpFieldName, form, absoluteSettingsPath,
}: {
udpFieldName: number;
form: FormInstance;
absoluteSettingsPath: (string | number)[];
}) {
return (
<>
{(['client', 'server'] as const).map((groupKey) => (
<Form.List key={groupKey} name={[udpFieldName, 'settings', groupKey]}>
{(items, { add, remove }) => (
<>
<Form.Item label={groupKey === 'client' ? 'Client' : 'Server'}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={() => add(defaultUdpClientServerItem())}
/>
</Form.Item>
{items.map((item, ci) => (
<div key={item.key}>
<Divider style={{ margin: 0 }}>
{groupKey === 'client' ? 'Client' : 'Server'} {ci + 1}
<DeleteOutlined className="danger-icon" onClick={() => remove(item.name)} />
</Divider>
<ItemEditor
fieldName={item.name}
form={form}
absoluteItemPath={[...absoluteSettingsPath, groupKey, item.name]}
onRemove={() => remove(item.name)}
/>
</div>
))}
</>
)}
</Form.List>
))}
</>
);
}
function NoiseItems({
udpFieldName, form, absoluteSettingsPath,
}: {
udpFieldName: number;
form: FormInstance;
absoluteSettingsPath: (string | number)[];
}) {
return (
<>
<Form.Item label="Reset" name={[udpFieldName, 'settings', 'reset']}>
<InputNumber min={0} />
</Form.Item>
<Form.List name={[udpFieldName, 'settings', 'noise']}>
{(items, { add, remove }) => (
<>
<Form.Item label="Noise">
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={() => add(defaultNoiseItem())}
/>
</Form.Item>
{items.map((item, ni) => (
<div key={item.key}>
<Divider style={{ margin: 0 }}>
Noise {ni + 1}
<DeleteOutlined className="danger-icon" onClick={() => remove(item.name)} />
</Divider>
<ItemEditor
fieldName={item.name}
form={form}
absoluteItemPath={[...absoluteSettingsPath, 'noise', item.name]}
delayMode="string"
onRemove={() => remove(item.name)}
/>
</div>
))}
</>
)}
</Form.List>
</>
);
}
function ItemEditor({
fieldName, form, absoluteItemPath, delayMode, onRemove: _onRemove,
}: {
fieldName: number;
form: FormInstance;
absoluteItemPath: (string | number)[];
delayMode?: 'number' | 'string';
onRemove?: () => void;
}) {
const onTypeChange = (v: string) => {
if (v === 'base64') {
form.setFieldValue([...absoluteItemPath, 'packet'], RandomUtil.randomBase64());
} else if (v === 'array') {
form.setFieldValue([...absoluteItemPath, 'rand'], delayMode === 'string' ? '1-8192' : 0);
form.setFieldValue([...absoluteItemPath, 'packet'], []);
} else {
form.setFieldValue([...absoluteItemPath, 'packet'], '');
}
};
return (
<>
<Form.Item label="Type" name={[fieldName, 'type']}>
<Select
onChange={onTypeChange}
options={[
{ value: 'array', label: 'Array' },
{ value: 'str', label: 'String' },
{ value: 'hex', label: 'Hex' },
{ value: 'base64', label: 'Base64' },
]}
/>
</Form.Item>
{delayMode === 'number' && (
<Form.Item label="Delay (ms)" name={[fieldName, 'delay']}>
<InputNumber min={0} />
</Form.Item>
)}
{delayMode === 'string' && (
<Form.Item label="Delay" name={[fieldName, 'delay']}>
<Input placeholder="10-20" />
</Form.Item>
)}
<Form.Item
noStyle
shouldUpdate={(prev, curr) => getDeep(prev, [...absoluteItemPath, 'type']) !== getDeep(curr, [...absoluteItemPath, 'type'])}
>
{({ getFieldValue }) => {
const type = getFieldValue([...absoluteItemPath, 'type']) as string | undefined;
if (type === 'array') {
return (
<>
<Form.Item label="Rand" name={[fieldName, 'rand']}>
{delayMode === 'string' ? (
<Input placeholder="0 or 1-8192" />
) : (
<InputNumber min={0} />
)}
</Form.Item>
<Form.Item label="Rand Range" name={[fieldName, 'randRange']}>
<Input placeholder="0-255" />
</Form.Item>
</>
);
}
if (type === 'base64') {
return (
<Form.Item label="Packet">
<Space.Compact block>
<Form.Item name={[fieldName, 'packet']} noStyle>
<Input placeholder="binary data" style={{ width: 'calc(100% - 32px)' }} />
</Form.Item>
<Button
icon={<ReloadOutlined />}
onClick={() => form.setFieldValue([...absoluteItemPath, 'packet'], RandomUtil.randomBase64())}
/>
</Space.Compact>
</Form.Item>
);
}
return (
<Form.Item label="Packet" name={[fieldName, 'packet']}>
<Input placeholder="binary data" />
</Form.Item>
);
}}
</Form.Item>
</>
);
}
function QuicParamsForm({ base, form }: { base: (string | number)[]; form: FormInstance }) {
const congestion = Form.useWatch([...base, 'congestion'], form) as string | undefined;
const udpHop = Form.useWatch([...base, 'udpHop'], { form, preserve: true }) as Record<string, unknown> | undefined;
const hasUdpHop = udpHop != null;
return (
<>
<Form.Item label="Congestion" name={[...base, 'congestion']}>
<Select
options={[
{ value: 'reno', label: 'Reno' },
{ value: 'bbr', label: 'BBR' },
{ value: 'brutal', label: 'Brutal' },
{ value: 'force-brutal', label: 'Force Brutal' },
]}
/>
</Form.Item>
{congestion === 'bbr' && (
<Form.Item label="BBR Profile" name={[...base, 'bbrProfile']}>
<Select
allowClear
placeholder="standard"
options={[
{ value: 'conservative', label: 'Conservative' },
{ value: 'standard', label: 'Standard' },
{ value: 'aggressive', label: 'Aggressive' },
]}
/>
</Form.Item>
)}
<Form.Item label="Debug" name={[...base, 'debug']} valuePropName="checked">
<Switch />
</Form.Item>
{(congestion === 'brutal' || congestion === 'force-brutal') && (
<>
<Form.Item label="Brutal Up" name={[...base, 'brutalUp']}>
<Input placeholder="e.g. 60 mbps" />
</Form.Item>
<Form.Item label="Brutal Down" name={[...base, 'brutalDown']}>
<Input placeholder="e.g. 100 mbps" />
</Form.Item>
</>
)}
<Form.Item label="UDP Hop">
<Switch
checked={hasUdpHop}
onChange={(v) => {
form.setFieldValue([...base, 'udpHop'], v ? defaultUdpHop() : undefined);
}}
/>
</Form.Item>
{hasUdpHop && (
<>
<Form.Item label="Hop Ports" name={[...base, 'udpHop', 'ports']}>
<Input placeholder="e.g. 20000-50000" />
</Form.Item>
<Form.Item label="Hop Interval (s)" name={[...base, 'udpHop', 'interval']}>
<Input placeholder="e.g. 5-10" />
</Form.Item>
</>
)}
<Form.Item label="Max Idle Timeout (s)" name={[...base, 'maxIdleTimeout']}>
<InputNumber min={4} max={120} />
</Form.Item>
<Form.Item label="Keep Alive Period (s)" name={[...base, 'keepAlivePeriod']}>
<InputNumber min={2} max={60} />
</Form.Item>
<Form.Item label="Disable Path MTU Dis" name={[...base, 'disablePathMTUDiscovery']} valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item label="Max Incoming Streams" name={[...base, 'maxIncomingStreams']}>
<InputNumber min={8} placeholder="1024 = default" />
</Form.Item>
<Form.Item label="Init Stream Window" name={[...base, 'initStreamReceiveWindow']}>
<InputNumber min={16384} placeholder="8388608 = default" />
</Form.Item>
<Form.Item label="Max Stream Window" name={[...base, 'maxStreamReceiveWindow']}>
<InputNumber min={16384} placeholder="8388608 = default" />
</Form.Item>
<Form.Item label="Init Conn Window" name={[...base, 'initConnectionReceiveWindow']}>
<InputNumber min={16384} placeholder="20971520 = default" />
</Form.Item>
<Form.Item label="Max Conn Window" name={[...base, 'maxConnectionReceiveWindow']}>
<InputNumber min={16384} placeholder="20971520 = default" />
</Form.Item>
</>
);
}
@@ -1,120 +0,0 @@
import { useTranslation } from 'react-i18next';
import { Form, Input, InputNumber, Select, Switch } from 'antd';
import type { FormInstance } from 'antd';
import HeaderMapEditor from '@/components/HeaderMapEditor';
const MASQ_PATH = ['streamSettings', 'hysteriaSettings', 'masquerade'];
interface HysteriaMasqueradeFormProps {
form: FormInstance;
}
export default function HysteriaMasqueradeForm({ form }: HysteriaMasqueradeFormProps) {
const { t } = useTranslation();
return (
<>
<Form.Item label={t('pages.inbounds.form.masquerade')}>
<Form.Item shouldUpdate noStyle>
{() => {
const m = form.getFieldValue(MASQ_PATH);
return (
<Switch
checked={!!m}
onChange={(checked) =>
form.setFieldValue(
MASQ_PATH,
checked
? {
type: '', dir: '', url: '',
rewriteHost: false, insecure: false,
content: '', headers: {}, statusCode: 0,
}
: undefined,
)
}
/>
);
}}
</Form.Item>
</Form.Item>
<Form.Item shouldUpdate noStyle>
{() => {
const m = form.getFieldValue(MASQ_PATH) as { type?: string } | undefined;
if (!m) return null;
return (
<>
<Form.Item
label={t('pages.inbounds.form.type')}
name={[...MASQ_PATH, 'type']}
>
<Select
options={[
{ value: '', label: 'default (404 page)' },
{ value: 'proxy', label: 'proxy (reverse proxy)' },
{ value: 'file', label: 'file (serve directory)' },
{ value: 'string', label: 'string (fixed body)' },
]}
/>
</Form.Item>
{m.type === 'proxy' && (
<>
<Form.Item
label={t('pages.inbounds.form.upstreamUrl')}
name={[...MASQ_PATH, 'url']}
>
<Input placeholder="https://www.example.com" />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.rewriteHost')}
name={[...MASQ_PATH, 'rewriteHost']}
valuePropName="checked"
>
<Switch />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.skipTlsVerify')}
name={[...MASQ_PATH, 'insecure']}
valuePropName="checked"
>
<Switch />
</Form.Item>
</>
)}
{m.type === 'file' && (
<Form.Item
label={t('pages.inbounds.form.directory')}
name={[...MASQ_PATH, 'dir']}
>
<Input placeholder="/var/www/html" />
</Form.Item>
)}
{m.type === 'string' && (
<>
<Form.Item
label={t('pages.inbounds.form.statusCode')}
name={[...MASQ_PATH, 'statusCode']}
>
<InputNumber min={0} max={599} style={{ width: '100%' }} />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.body')}
name={[...MASQ_PATH, 'content']}
>
<Input.TextArea autoSize={{ minRows: 3 }} />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.headers')}
name={[...MASQ_PATH, 'headers']}
>
<HeaderMapEditor mode="v1" />
</Form.Item>
</>
)}
</>
);
}}
</Form.Item>
</>
);
}
@@ -0,0 +1,2 @@
export { default as PromptModal } from './PromptModal';
export { default as TextModal } from './TextModal';
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
import { Button, Input, Space } from 'antd';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import InputAddon from '@/components/InputAddon';
import { InputAddon } from '@/components/ui';
// Reusable header-map editor. Handles the two wire shapes Xray uses for
// HTTP-style header maps:
+3
View File
@@ -0,0 +1,3 @@
export { default as DateTimePicker } from './DateTimePicker';
export { default as JsonEditor } from './JsonEditor';
export { default as HeaderMapEditor } from './HeaderMapEditor';
+3
View File
@@ -0,0 +1,3 @@
export { default as InputAddon } from './InputAddon';
export { default as InfinityIcon } from './InfinityIcon';
export { default as SettingListItem } from './SettingListItem';
+1
View File
@@ -0,0 +1 @@
export { default as LazyMount } from './LazyMount';
+1
View File
@@ -0,0 +1 @@
export { default as Sparkline } from './Sparkline';