3x-ui/frontend
Sanaei d1882c7f29
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).
2026-05-30 21:51:33 +02:00
..
public feat(fallbacks): add per-rule dest override 2026-05-28 21:17:49 +02:00
scripts refactor(frontend): port api-docs/endpoints to TypeScript 2026-05-25 15:29:26 +02:00
src refactor(frontend): reorganize source tree & break down oversized modals/tabs (#4698) 2026-05-30 21:51:33 +02:00
.gitignore Vue3 migration (#4198) 2026-05-09 17:47:35 +02:00
eslint.config.js feat: complete Zod migration of frontend + bulk client batching (#4599) 2026-05-27 04:26:50 +02:00
eslint.deprecated.config.js feat: complete Zod migration of frontend + bulk client batching (#4599) 2026-05-27 04:26:50 +02:00
index.html feat(inbound): Advanced XHTTP and external TLS proxy settings (#4491) 2026-05-24 21:54:26 +02:00
login.html Frontend rewrite: React + TypeScript with AntD v6 (#4498) 2026-05-23 15:21:45 +02:00
package-lock.json refactor(frontend): reorganize source tree & break down oversized modals/tabs (#4698) 2026-05-30 21:51:33 +02:00
package.json refactor(frontend): reorganize source tree & break down oversized modals/tabs (#4698) 2026-05-30 21:51:33 +02:00
README.md feat: complete Zod migration of frontend + bulk client batching (#4599) 2026-05-27 04:26:50 +02:00
subpage.html Frontend rewrite: React + TypeScript with AntD v6 (#4498) 2026-05-23 15:21:45 +02:00
tsconfig.json Frontend rewrite: React + TypeScript with AntD v6 (#4498) 2026-05-23 15:21:45 +02:00
vite.config.js feat: complete Zod migration of frontend + bulk client batching (#4599) 2026-05-27 04:26:50 +02:00
vitest.config.ts refactor(frontend): reorganize source tree & break down oversized modals/tabs (#4698) 2026-05-30 21:51:33 +02:00

3x-ui frontend

React 19 + Ant Design 6 + TypeScript + Vite 8. Three SPA bundles — index.html (admin panel SPA, all /panel/* routes), login.html (login + 2FA), and subpage.html (public subscription viewer). All three are built into ../web/dist/ and embedded into the Go binary via embed.FS.

State is split between local useState, TanStack Query for server state, and useTheme / useWebSocket contexts. Form validation, API parsing, and the xray config model all run through a single shared Zod schema tree (see Schemas).

Dev

npm install
npm run dev

Vite serves on http://localhost:5173/. API calls and /panel/* routes proxy to the Go panel at http://localhost:2053/, so start the Go panel first (go run main.go) and then Vite. The proxy auto-rewrites /panel, /panel/settings, /panel/inbounds, /panel/xray to the matching Vite-served HTML, so the sidebar's production-style links work without round-tripping through Go.

Scripts

Command What
npm run dev Vite dev server with API + WS proxy to Go
npm run build Regenerates OpenAPI + Zod, then builds into ../web/dist/
npm run preview Serve the built bundle locally
npm run typecheck tsc --noEmit (strict, no emit)
npm run lint ESLint flat config (@typescript-eslint + react-hooks)
npm run test Vitest single run (schema fixtures, link parsers, …)
npm run test:watch Vitest watch mode
npm run gen:api Build public/openapi.json from pages/api-docs/endpoints.ts
npm run gen:zod Run the Go-side openapigen tool → src/generated/{zod,types}.ts

CI runs typecheck, lint, test, and build on every PR (see ../.github/workflows/ci.yml).

One-off: scan for deprecated APIs

Run this command to sweep the codebase for usages of APIs marked with the JSDoc @deprecated tag (AntD prop renames, Zod renames, removed Web APIs, etc.):

npx eslint --config eslint.deprecated.config.js src

It's a type-aware ESLint run against eslint.deprecated.config.js and is not wired into npm run lint because typed linting triples the wall-clock time.

Production build

npm run build

Outputs to ../web/dist/ (HTML at the root, hashed JS/CSS under assets/). manualChunks splits AntD, icons, codemirror, and react-query into separate vendor bundles to keep the per-page initial JS small. The Go binary embeds this directory at compile time and web/controller/dist.go serves the per-page HTML.

Layout

frontend/
├── index.html, login.html, subpage.html  # 3 Vite entries
├── tsconfig.json
├── eslint.config.js
├── eslint.deprecated.config.js           # On-demand type-aware lint config that flags
│                                         #   usages of APIs marked with JSDoc @deprecated
├── vitest.config.ts
├── vite.config.js
├── scripts/
│   └── build-openapi.mjs                 # endpoints.ts → openapi.json
└── src/
    ├── entries/         # Per-page bootstrap (createRoot + render)
    ├── main.tsx         # Shared root for the admin SPA (index.html)
    ├── routes.tsx       # react-router routes mounted under /panel/
    ├── pages/           # One folder per route, page component + helpers
    │   ├── index/, login/, inbounds/, clients/, xray/, nodes/,
    │   ├── settings/, api-docs/, sub/
    ├── layouts/         # AdminLayout (sidebar + header + outlet)
    ├── components/      # Cross-page React components
    ├── hooks/           # useClients, useTheme, useWebSocket, …
    ├── api/             # Axios + CSRF interceptor, TanStack Query bridge,
    │                    #   WebSocket client + queryClient.ts
    ├── i18n/            # react-i18next init (locales in web/translation/)
    ├── lib/xray/        # Pure functions: link generation, defaults,
    │                    #   form ⇄ wire adapters, protocol capabilities
    ├── schemas/         # Zod source-of-truth (see "Schemas" below)
    ├── generated/       # Code-generated zod + ts types from Go
    │                    #   (DO NOT hand-edit — regenerated by gen:zod)
    ├── models/          # Thin legacy types still in transit
    │                    #   (DBInbound, Status, AllSetting, reality-targets)
    ├── styles/          # Shared CSS modules
    ├── test/            # Vitest specs + golden fixtures
    │   ├── *.test.ts
    │   ├── __snapshots__/
    │   └── golden/fixtures/  # Per-(protocol × network × security) JSON
    └── utils/           # HttpUtil, ClipboardManager, SizeFormatter, …

Schemas

src/schemas/ is the single source of truth for the xray configuration model. Every API response is parsed through it, every form field is validated against it, and TypeScript types are inferred via z.infer<typeof X> — never hand-written.

schemas/
├── primitives/      # Atomic reusable schemas (port, protocol, sniffing, …)
├── api/             # Backend response shapes (e.g. SlimInboundSchema)
├── forms/           # User-facing form shapes (narrower than api/)
├── protocols/
│   ├── inbound/     # Per-protocol settings (vmess, vless, trojan, …)
│   ├── outbound/
│   ├── stream/      # Network transports (tcp, ws, grpc, xhttp, kcp, …)
│   └── security/    # TLS, Reality, none
├── client.ts, dns.ts, routing.ts, setting.ts, status.ts, xray.ts
└── _envelope.ts     # Generic `Msg<T>` envelope wrapper

Patterns:

  • Discriminated unions for polymorphic data — inbound settings is z.discriminatedUnion('protocol', […]), same for stream and security.
  • Three validation layers, non-overlapping:
    • API boundary: parseMsg(msg, schema, ctx) inside TanStack Query queryFn — warn-only in prod, throws in dev
    • Form input: antdRule(schema.shape.field) on every <Form.Item> — blocks submit + per-field inline error
    • Wire request: Schema.parse(payload) inside mutationFn — throws, because a malformed payload here is always a developer bug
  • No .loose() or [key: string]: any in production schemas. @typescript-eslint/no-explicit-any: error is enforced.

Form pattern (Pattern A)

All non-trivial modals use this single pattern:

const [form] = Form.useForm<InboundFormValues>();

const onFinish = async () => {
  const values = await form.validateFields();
  await createInbound.mutateAsync(values);
};

<Form form={form} onFinish={onFinish}>
  <Form.Item
    name="port"
    label="Port"
    rules={[antdRule(InboundFormSchema.shape.port, t)]}
  >
    <InputNumber min={1} max={65535} />
  </Form.Item>
</Form>

No safeParse-on-submit handlers, no useRef<any> for form references, no inline z.string().min(1) in rules. Conditional fields use <Form.Item dependencies={...} shouldUpdate> with the nested protocol schema.

Testing

Vitest runs everything under src/test/. Schemas have golden fixture suites — one JSON per (protocol × network × security) combination round-tripped through schema.parse → link generator → snapshot. Regenerate snapshots after intentional changes:

npx vitest run -u

Fixtures live in src/test/golden/fixtures/ and are auto-discovered via import.meta.glob.

Adding a new page

Most new routes go inside the admin SPA (index.html) via routes.tsx — no new HTML or Vite entry needed.

  1. Add the page component under src/pages/<page>/.
  2. Register it in src/routes.tsx under the /panel/... tree.
  3. If you need a brand-new top-level bundle (login-style standalone page), add the HTML at frontend/<page>.html, an entry at src/entries/<page>.tsx, and register it in rollupOptions.input in vite.config.js. Then add the Go controller call to serveDistPage(c, "<page>.html").