Migrate frontend models/api/utils to TypeScript and modernize AntD theming (#4563)

* refactor(frontend): port api/* and reality-targets to TypeScript

Phase 1 of the JS→TS migration: convert three small, isolated files
(axios-init, websocket, reality-targets) to typed sources so future
phases can lean on their interfaces.

- api/axios-init.ts: typed CSRF cache, interceptors, request retry
- api/websocket.ts: typed listener map, message envelope guard,
  reconnect timer
- models/reality-targets.ts: RealityTarget interface, readonly list
- env.d.ts: minimal qs module shim (stringify/parse)
- consumers: drop ".js" extension from @/api imports

* refactor(frontend): port utils/index to TypeScript

Phase 2 of the JS→TS migration: convert the 858-line utility module
that 30+ pages and hooks depend on.

- Msg<T = any> generic with success/msg/obj shape preserved
- HttpUtil get/post/postWithModal generic over response shape
- RandomUtil, Wireguard, Base64 fully typed
- SizeFormatter/CPUFormatter/TimeFormatter/NumberFormatter typed
- ColorUtils.usageColor returns 'green'|'orange'|'red'|'purple' union
- LanguageManager.supportedLanguages readonly typed
- IntlUtil.formatDate/formatRelativeTime accept null/undefined
- ObjectUtil.clone/deepClone/cloneProps/equals kept as `any`-shaped
  to preserve the prior JS contract used by class-instance callers
  (AllSetting.cloneProps(this, data), etc.)

* refactor(frontend): port models/outbound to TypeScript (hybrid typing)

Phase 4 of the JS→TS migration: rename outbound.js to outbound.ts and
make it compile under strict mode with a minimal hybrid type pass.

- Enum-like constants kept as typed objects (Protocols, SSMethods, …)
- Top-level DNS helpers strictly typed
- CommonClass gets [key: string]: any so all subclasses can keep their
  loose this.foo = bar assignments without per-field declarations
- Constructor / fromJson / toJson signatures typed as any to preserve
  the prior JS contract used by consumers and parsers
- Outbound declares static fields for the dynamically-attached Settings
  subclasses (Settings, FreedomSettings, VmessSettings, …)
- urlParams.get() results that feed parseInt now use the non-null
  assertion since the surrounding has() check already guards them
- File-level eslint-disable for no-explicit-any/no-var/prefer-const to
  keep the JS-derived code building without churn

* refactor(frontend): port models/inbound to TypeScript (hybrid typing)

Phase 5 of the JS→TS migration. Same hybrid approach as outbound.ts:
constants typed strictly, classes get [key: string]: any from
XrayCommonClass, constructor / fromJson / toJson signatures use any.

- XrayCommonClass gains [key: string]: any plus typed static helpers
  (toJsonArray, fallbackToJson, toHeaders, toV2Headers)
- TcpStreamSettings/TlsStreamSettings/RealityStreamSettings/Inbound
  declare static fields for their dynamically-attached subclasses
  (TcpRequest, TcpResponse, Cert, Settings, ClientBase, Vmess/VLESS/
  Trojan/Shadowsocks/Hysteria/Tunnel/Mixed/Http/Wireguard/TunSettings)
- All gen*Link, applyXhttpExtra*, applyExternalProxyTLS*, applyFinalMask*
  and related helpers explicitly any-typed
- Constructor positional client-args (email, limitIp, totalGB, …) typed
  as optional any across Vmess/VLESS/Trojan/Shadowsocks/Hysteria.VMESS|
  VLESS|Trojan|Shadowsocks|Hysteria
- File-level eslint-disable for no-explicit-any/prefer-const/
  no-case-declarations/no-array-constructor to silence churn without
  changing behavior

* refactor(frontend): port models/dbinbound to TypeScript

Phase 6 — final phase of the JS→TS migration. Frontend src/ no
longer contains any *.js files.

- DBInbound declares all fields explicitly (id, userId, up, down,
  total, …, nodeId, fallbackParent) with proper types
- _expiryTime getter/setter typed against dayjs.Dayjs
- coerceInboundJsonField takes unknown, returns any
- Private cache fields (_cachedInbound, _clientStatsMap) declared
- Consumers (InboundFormModal, InboundsPage, useInbounds): drop ".js"
  extension from @/models/dbinbound imports

* refactor(frontend): drop .js extensions from TS-resolved imports

Cleanup after the JS→TS migration:

- All consumers that imported @/models/{inbound,outbound,dbinbound}.js
  now drop the .js extension (TS module resolution lands on the .ts
  file automatically)
- eslint.config.js: remove the **/*.js block since the only remaining
  JS file under src/ is endpoints.js (build-script consumed only) and
  js.configs.recommended already covers it correctly

* refactor(frontend): tighten inbound.ts cleanup wins

Checkpoint before the full any → typed pass:
- Wrap 15 case bodies in braces (no-case-declarations)
- Convert 14 let → const in genLink helpers (prefer-const)
- new Array() → [] for shadowsocks passwords (no-array-constructor)
- XrayCommonClass: HeaderEntry, FallbackEntry, JsonObject interfaces;
  fromJson/toV2Headers/toHeaders typed against them; static methods
  return JsonObject / HeaderEntry[] instead of any
- Reduce file-level eslint-disable scope from 4 rules to just
  no-explicit-any (the only one still needed)

* refactor(frontend): drop eslint-disable from models/dbinbound

Replace `any` with explicit domain types:
- `coerceInboundJsonField` returns `Record<string, unknown>` (settings/streamSettings/sniffing are always objects).
- Add `RawJsonField`, `ClientStats`, `FallbackParentRef`, `DBInboundInit` types.
- `_cachedInbound: Inbound | null`, `toInbound(): Inbound`.
- `getClientStats(email): ClientStats | undefined`.
- `genInboundLinks(): string` (matches actual return from Inbound.genInboundLinks).
- Constructor now accepts `DBInboundInit`.

* refactor(frontend): drop eslint-disable from InboundsPage

Type all callbacks against DBInbound from @/models/dbinbound:
- state setters use DBInbound | null
- helpers (projectChildThroughMaster, checkFallback, findClientIndex,
  exportInboundLinks, etc.) take DBInbound
- drop `(dbInbounds as any[])` casts; useInbounds already returns DBInbound[]
- introduce ClientMatchTarget for findClientIndex's `client` param
- tighten DBInbound.clientStats to ClientStats[] (default [])
- single boundary cast at <InboundList onRowAction=> to bridge
  InboundList's narrower DBInboundRecord (cleanup belongs with InboundList)

* refactor(frontend): drop file-level eslint-disable from utils/index

- ObjectUtil.clone/deepClone become generic <T>
- cloneProps/delProps accept `object` (cast internally to AnyRecord)
- equals accepts `unknown` with proper narrowing
- ColorUtils.usageColor narrows data/threshold to `number`; total widened
  to `number | { valueOf(): number } | null | undefined` so Dayjs works
- Utils.debounce replaces `const self = this` with lexical arrow
  closure (no-this-alias clean)
- InboundList._expiryTime narrowed from `unknown` to `{ valueOf(): number } | null`
- Single-line eslint-disable remains on `Msg<T = any>` and HttpUtil
  generic defaults (idiomatic API envelope; changing default to unknown
  cascades through 34 consumer files)

* refactor(frontend): drop eslint-disable from OutboundFormModal field section

Replace `type OB = any` with `type OB = Outbound`. Body code still
sees protocol fields as `any` via Outbound's inherited [key: string]: any
index signature (CommonClass) — that escape hatch will narrow as
Phase 6 tightens outbound.ts itself.

The intentional `// eslint-disable-next-line` on `useRef<any>(null)`
at line 72 stays — out of scope per plan.

* refactor(frontend): drop file-level eslint-disable from InboundFormModal

Add minimal local interfaces for protocol-specific shapes the form reads:
- StreamLike, TlsCert, VlessClient, ShadowsocksClient, HttpAccount,
  WireguardPeer (replace with real exports from inbound.ts as Phase 7
  exports them).
- Props typed as DBInbound | null + DBInbound[].
- Drop unnecessary `(Inbound as any).X`, `(RandomUtil as any).X`,
  `(Wireguard as any).X`, `(DBInbound as any)(...)` casts — they are
  already typed classes; only `Inbound.Settings`/`Inbound.HttpSettings`
  remain `any` via static field on Inbound (will tighten in Phase 7).
- inboundRef/dbFormRef retain single-line `// eslint-disable-next-line`
  for `useRef<any>(null)` — nullable narrowing across ~30 callsites
  exceeds Phase 5 scope.
- payload locals typed Record<string, unknown>; setAdvancedAllValue
  parses JSON into a narrowed object instead of `let parsed: any`.

* refactor(frontend): narrow outbound.ts eslint-disable to no-explicit-any only

- Fix all 36 prefer-const violations: convert never-reassigned `let` to
  `const`; for mixed-mutability destructuring (fromParamLink,
  fromHysteriaLink) split into separate `const`/`let` declarations
  by index instead of destructuring.
- Fix both no-var violations: `var stream` / `var settings` → `let`.
- File still carries `/* eslint-disable @typescript-eslint/no-explicit-any */`
  because tightening 223 `any` uses requires removing CommonClass's
  `[key: string]: any` escape hatch and reshaping ~30 dynamically-attached
  subclass patterns into named classes — multi-hour architectural work
  tracked as Phase 7's twin for outbound.

* refactor(frontend): align sub page chrome with login + AntD defaults

- Theme + language buttons now both use AntD `<Button shape="circle"
  size="large" className="toolbar-btn">` with TranslationOutlined and
  the SVG theme icon — identical hover/border behaviour.
- Language popover content switched from hand-rolled `<ul.lang-list>`
  to AntD `<Menu mode="vertical" selectable />`; gains native
  hover/keyboard nav + active highlight.
- Drop `.info-table` `!important` border overrides (8 selectors) so
  Descriptions inherits the AntD theme border colour.
- Drop `.qr-code` padding/background/border-radius overrides; only
  `cursor: pointer` remains (QRCode handles padding/bg itself).
- Remove now-unused `.theme-cycle`, `.lang-list`, `.lang-item*`,
  `.lang-select`, `.settings-popover` rules.

* refactor(frontend): drop CustomStatistic wrapper, move overrides to theme tokens

- Delete `<CustomStatistic>` (a pass-through wrapper over <Statistic>)
  and its unscoped global `.ant-statistic-*` CSS overrides; consumers
  (IndexPage, ClientsPage, InboundsPage, NodesPage) now import AntD
  `<Statistic>` directly.
- Add Statistic component tokens to ConfigProvider so the title (11px)
  and content (17px) font sizes still apply, without `!important`
  global selectors.
- Move dark / ultra-dark card border colours from `body.dark .ant-card`
  + `html[data-theme='ultra-dark'] .ant-card` selectors into Card
  `colorBorderSecondary` tokens; page-cards.css now only carries the
  custom radius/shadow/transition that has no token equivalent.
- Simplify XrayStatusCard badge: remove the custom `xray-pulse` dot
  keyframe and per-state ring-colour overrides; AntD `<Badge
  status="processing" color={…}>` already pulses the ring in the same
  colour, no extra CSS needed.

* refactor(frontend): modernize login page with AntD primitives

- Theme cycle button switched from `<button.theme-cycle>` + custom CSS
  to AntD `<Button shape="circle" className="toolbar-btn">` (matches
  sub page chrome already established).
- Theme icons switched from hand-rolled inline SVG (sun, moon,
  moon+star) to AntD `<SunOutlined />`, `<MoonOutlined />`,
  `<MoonFilled />` for the three light / dark / ultra-dark states.
- Language popover content switched from `<ul.lang-list>` +
  `<button.lang-item>` to AntD `<Menu mode="vertical" selectable />`
  with `selectedKeys=[lang]`; native hover / keyboard nav / active
  highlight come for free.
- Drop CSS for `.theme-cycle`, `.lang-list`, `.lang-item*` (now unused).
  `.toolbar-btn` retained since it sizes both circular buttons.

* refactor(frontend): switch sub page theme icons to AntD primitives

Replace the three hand-rolled SVG theme icons (sun, moon, moon+star)
with AntD `<SunOutlined />`, `<MoonOutlined />`, `<MoonFilled />`
for the light / dark / ultra-dark states. Switch the theme `<Button>`
to use the `icon` prop instead of children so it renders the same
way as the language button. Drop `.toolbar-btn svg` CSS — no longer
needed once the icon comes from AntD.

* refactor(frontend): drop !important overrides from pages CSS (Clients + Log modals + Settings tabs)

- ClientsPage: pagination size-changer `min-width !important` removed;
  the 3-level selector specificity already beats AntD's defaults.
  Scope `body.dark .client-card` to `.clients-page.is-dark .client-card`
  (avoid leaking into other pages).
- LogModal + XrayLogModal: move the mobile full-screen tweaks
  (`top: 0`, `padding-bottom: 0`, `max-width: 100vw`) from `!important`
  class rules to the Modal's `style` prop; keep `.ant-modal-content`
  / `.ant-modal-body` overrides as plain CSS via the className.
- SubscriptionFormatsTab: drop `display: block !important` on
  `.nested-block` — div is already block by default.
- TwoFactorModal: drop `padding/background/border-radius !important`
  on `.qr-code`; AntD QRCode handles those itself.

* refactor(frontend): scope dark overrides and switch list borders to AntD CSS variables

Scope page-level dark overrides:
- inbounds/InboundList: scope `.ant-table` border-radius rules and the
  mobile @media `.ant-card-*` tweaks to `.inbounds-page` (were global
  and leaked into other pages); scope `.inbound-card` dark variant to
  `.inbounds-page.is-dark`.
- nodes/NodeList: scope `.node-card` dark to `.nodes-page.is-dark`.
- xray/RoutingTab, OutboundsTab: scope `.rule-card`, `.criterion-chip`,
  `.criterion-more`, `.address-pill` dark to `.xray-page.is-dark`.

Modernize list borders to use AntD CSS vars instead of body.dark forks:
- index/BackupModal, PanelUpdateModal, VersionModal: replace
  hard-coded `rgba(5,5,5,0.06)` + `body.dark`/`html[data-theme]`
  override pairs with `var(--ant-color-border-secondary)`; replace
  custom text colours with `var(--ant-color-text)` /
  `var(--ant-color-text-tertiary)`.
- xray/DnsPresetsModal: same border-color treatment.
- xray/NordModal, WarpModal: collapse `.row-odd` light + `body.dark`
  pair into a single neutral `rgba(128,128,128,0.06)` that works on
  both themes; scope under `.nord-data-table` / `.warp-data-table`.

* refactor(frontend): switch shared components CSS to AntD CSS variables

Replace body.dark / html[data-theme] forks with AntD CSS variables
in shared components (work in both light and dark, scale to ultra):
- SettingListItem: borders + text colours via
  `--ant-color-border-secondary`, `--ant-color-text`,
  `--ant-color-text-tertiary`.
- InputAddon: bg/border/text via `--ant-color-fill-tertiary`,
  `--ant-color-border`, `--ant-color-text`.
- JsonEditor: host border/bg via `--ant-color-border`,
  `--ant-color-bg-container`; focus border via `--ant-color-primary`.
- Sparkline (SVG): grid/text colours via `--ant-color-text*`
  and `--ant-color-border-secondary`; only the tooltip drop-shadow
  retains a body.dark fork (filter opacity needs explicit value).

* refactor(frontend): swap custom Sparkline SVG for Recharts AreaChart

Replace the 368-line hand-rolled SVG sparkline (with manual
ResizeObserver, gradient/shadow/glow filters, grid + ticks + tooltip,
custom Y-axis label thinning) with a thin Recharts `<AreaChart>`
wrapper that keeps the same prop API.

- Preserved props: data, labels, height, stroke, strokeWidth,
  maxPoints, showGrid, fillOpacity, showMarker, markerRadius,
  showAxes, yTickStep, tickCountX, showTooltip, valueMin, valueMax,
  yFormatter, tooltipFormatter.
- Dropped: `vbWidth`, `gridColor`, `paddingLeft/Right/Top/Bottom` —
  Recharts' ResponsiveContainer handles width, and margins are wired
  to whether axes are visible. Removed the unused `vbWidth` prop from
  SystemHistoryModal, XrayMetricsModal, NodeHistoryPanel callsites.
- Tooltip, grid, and axis text now use AntD CSS variables for
  automatic light/dark adaptation; replaced the SVG body.dark forks
  in Sparkline.css with a single 5-line stylesheet.
- Bundle: vendor +~100KB gzip (Recharts + its d3 deps), trade-off
  for less custom chart code to maintain and a more standard API
  for future charts (multi-series, brush, etc.).

* build(frontend): split Recharts + d3 deps into vendor-recharts chunk

Pulls Recharts (~75KB gzip) and its d3-shape/array/color/path/scale
+ victory-vendor deps out of the catch-all vendor chunk so they
load on demand on the three pages that use Sparkline
(SystemHistoryModal, XrayMetricsModal, NodeHistoryPanel) and cache
independently from the rest of the panel JS.

* refactor(frontend): drop body.dark forks in favor of AntD CSS variables

- ClientInfoModal/InboundInfoModal: link-panel-text and link-panel-anchor now use
  var(--ant-color-fill-tertiary) and color-mix on --ant-color-primary, removing
  the body.dark light/dark background pair.
- InboundFormModal: advanced-panel uses --ant-color-border-secondary and
  --ant-color-fill-quaternary; body.dark/html[data-theme='ultra-dark'] pair gone.
- CustomGeoSection: custom-geo-count, custom-geo-ext-code, custom-geo-copyable:hover
  use --ant-color-fill-tertiary/-secondary; body.dark forks gone.
- SystemHistoryModal: cpu-chart-wrap collapsed from three theme-specific gradients
  into one using color-mix on --ant-color-primary and --ant-color-fill-quaternary.
- page-cards.css: body.dark / html[data-theme='ultra-dark'] selectors renamed to
  page-scoped .is-dark / .is-dark.is-ultra, keeping the same shadow tuning but
  consistent with the page-scoping convention used elsewhere.

* refactor(sidebar): modernize AppSidebar with AntD CSS variables and icons

- Replace hardcoded rgba(0,0,0,X) colors with var(--ant-color-text)
  and var(--ant-color-text-secondary) so light/dark adapt automatically.
- Replace rgba(128,128,128,0.15) borders with var(--ant-color-border-secondary)
  and rgba(128,128,128,0.18) backgrounds with var(--ant-color-fill-tertiary).
- Drop all body.dark/html[data-theme='ultra-dark'] color forks for
  .drawer-brand, .sider-brand, .drawer-close, .sidebar-theme-cycle,
  .sidebar-donate (CSS variables already adapt).
- Drop the body.dark Drawer background !important pair; AntD's
  colorBgElevated token from the dark algorithm handles it now.
- Replace inline sun/moon SVGs in ThemeCycleButton with AntD's
  SunOutlined/MoonOutlined/MoonFilled to match LoginPage/SubPage.
- Convert .sidebar-theme-cycle hover and the menu item selected/hover
  highlights from hardcoded #4096ff to color-mix on --ant-color-primary,
  keeping !important on menu rules to beat AntD's CSS-in-JS specificity.

* refactor(frontend): swap hardcoded AntD palette colors for CSS variables

The dot/badge/pill styles still hardcoded AntD's default palette values
(#52c41a, #1677ff, #ff4d4f, #fa8c16, #ff4d4f). Replace each with its
semantic --ant-color-* equivalent so they auto-adapt to any theme
customization through ConfigProvider.

- ClientsPage: .dot-green/.dot-blue/.dot-red/.dot-orange/.dot-gray now
  use --ant-color-success / -primary / -error / -warning / -text-quaternary.
  .bulk-count / .client-card / .client-card.is-selected backgrounds use
  color-mix on --ant-color-primary and --ant-color-fill-quaternary, which
  also let the body-dark .client-card fork go away.
- XrayMetricsModal: .obs-dot is-alive/is-dead and its pulse keyframe now
  build their box-shadow tint via color-mix on --ant-color-success and
  --ant-color-error instead of rgba literals.
- IndexPage: .action-update warning color uses --ant-color-warning.
- OutboundsTab: .outbound-card border, .address-pill background, and
  .mode-badge tint now use AntD CSS variables; the .xray-page.is-dark
  .address-pill fork is gone.
- InboundFormModal/InboundsPage/ClientBulkAddModal: drop the stale
  `, #1677ff`/`, #1890ff` fallbacks on var(--ant-color-primary), and
  switch .danger-icon to --ant-color-error.

The teal/cyan brand colors (#008771, #3c89e8, #e04141) used by traffic
and pill rows are intentionally kept hardcoded — they are brand-specific
shades, not AntD palette colors.

* refactor(frontend): swap neutral gray rgba literals for AntD CSS variables

Across 12 files the same neutral grays kept reappearing — rgba(128,128,128,
0.06|0.08|0.12|0.15|0.18|0.2|0.25) for borders, dividers, and subtle
backgrounds. Each maps cleanly to an AntD CSS variable that already
adapts to light/dark and to any theme customization through ConfigProvider:

- 0.12–0.18 borders → var(--ant-color-border-secondary)
- 0.2–0.25 borders → var(--ant-color-border)
- 0.06–0.08 backgrounds → var(--ant-color-fill-tertiary)
- 0.02–0.03 card surfaces → var(--ant-color-fill-quaternary)

Card surfaces (InboundList .inbound-card, NodeList .node-card) had a
light/dark fork pair — the variable covers both, so the .is-dark .card
override is gone.

RoutingTab .rule-card.drop-before/after used hardcoded #1677ff for the
inset focus shadow; replaced with var(--ant-color-primary) so reordering
indicators follow the theme primary.

ClientsPage bucketBadgeColor returned hex literals (#ff4d4f, #fa8c16,
#52c41a, rgba gray) for a Badge color prop. Switched to status="error"|
"warning"|"success"|"default" so the dot color now comes from AntD's
semantic palette directly.

* refactor(xray): collapse RoutingTab dark forks into AntD CSS variables

- .criterion-more bg light/dark fork → var(--ant-color-fill-tertiary)
- .xray-page.is-dark .rule-card and .criterion-chip overrides removed;
  the rules already use --bg-card and --ant-color-fill-tertiary that
  adapt to the theme on their own.

* refactor(frontend): inline style hex literals and Alert icon redundancy

- FinalMaskForm: five DeleteOutlined icons used rgb(255,77,79) inline;
  swap for var(--ant-color-error) so they follow theme customization.
- NodesPage: CheckCircleOutlined / CloseCircleOutlined statistic prefixes
  switch to var(--ant-color-success) / -error.
- NodeList: ExclamationCircleOutlined warning icons (two callsites) now
  use var(--ant-color-warning).
- BasicsTab: four <Alert type="warning"> blocks shipped a custom
  ExclamationCircleFilled icon styled to match the warning palette —
  exactly the icon and color AntD Alert renders for type="warning" by
  default. Replace the icon prop with showIcon and drop the now-unused
  ExclamationCircleFilled import.
- JsonEditor: focus-within box-shadow tint now uses color-mix on
  --ant-color-primary instead of an rgba(22,119,255,0.1) literal.

* refactor(logs): collapse log-container dark forks to AntD CSS variables

LogModal and XrayLogModal each had a body.dark fork that overrode the
log container's background, border-color, and text color in addition
to the --log-* severity tokens. Background/border/color all map cleanly
to var(--ant-color-fill-tertiary) / var(--ant-color-border) /
var(--ant-color-text) which already adapt to the theme, so only the
severity color tokens remain inside the dark/ultra-dark blocks.

* refactor(xray): drop stale --ant-primary-color fallbacks and hex literals

- RoutingTab .drop-before/.drop-after box-shadow: #1677ff → var(--ant-color-primary)
- OutboundFormModal .random-icon: drop the --ant-primary-color/#1890ff
  pair (the old AntD v4 token name with stale fallback) for the v6
  --ant-color-primary; .danger-icon hex #ff4d4f → var(--ant-color-error).
- XrayPage .restart-icon: same drop of the --ant-primary-color fallback.

These were all leftovers from the AntD v4 → v6 rename — the v6
--ant-color-primary is already populated by ConfigProvider, so the
fallback hex was dead code that would only trigger if AntD wasn't
mounted.

* refactor(frontend): consolidate margin utility classes into one stylesheet

Page CSS files each carried their own copies of the same atomic margin
utilities (.mt-4, .mt-8, .mb-12, .ml-8, .my-10, ...). The definitions
were identical everywhere they appeared, with each file holding only
the subset it happened to need.

Move all of them into a single styles/utils.css imported once from
main.tsx, and delete the per-page copies from InboundFormModal,
CustomGeoSection, PanelUpdateModal, VersionModal, BasicsTab, NordModal,
OutboundFormModal, and WarpModal. The classes are available globally
on the panel app; login.tsx and subpage.tsx entries do not consume any
of them so they stay untouched.

* refactor(frontend): consolidate shared page-shell rules into one stylesheet

Every panel page CSS file repeated the same wrapper boilerplate — the
--bg-page/--bg-card token triples for light/dark/ultra-dark, the
min-height + background root rule, the .ant-layout transparent reset,
the .content-shell transparent reset, and the .loading-spacer min-height.
That's ~30 identical lines duplicated across IndexPage, ClientsPage,
InboundsPage, XrayPage, SettingsPage, NodesPage, and ApiDocsPage.

Move all of it into styles/page-shell.css and import it once from
main.tsx alongside utils.css and page-cards.css. Each page CSS file
now only contains genuinely page-specific rules (content-area padding
overrides, page-specific tokens like ApiDocs's Swagger --sw-* set).

Also drop the per-page `import '@/styles/page-cards.css'` statements
from the 7 page tsx files now that main.tsx loads it globally.

Net: -211 deleted, +6 inserted in the touched files, plus the new
page-shell.css. .zero-margin (Divider override used by Nord/Warp
modals) folded into utils.css alongside the margin classes.

* refactor(frontend): move default content-area padding to page-shell.css

After page-shell.css landed, six of the seven panel pages still kept an
identical `.X-page .content-area { padding: 24px }` desktop rule, plus
three of them kept an identical `padding: 8px` mobile rule. Hoist both
defaults into page-shell.css under a single 6-page selector group and
delete the per-page copies.

What stays page-specific:
- IndexPage keeps its mobile override (padding 12px + padding-top: 64px
  for the fixed drawer handle clearance).
- ApiDocsPage keeps its tighter desktop padding (16px) and its own
  mobile padding-top: 56px.

Settings .ldap-no-inbounds also switches from #999 to
var(--ant-color-text-tertiary) for theme adaptation.

* refactor(frontend): hoist .header-row, .icons-only, .summary-card to page-shell.css

Settings and Xray pages both carried identical .header-row /
.header-actions / .header-info rules and an identical six-rule
.icons-only block that styles tabbed page navigation. Clients, Inbounds,
and Nodes all carried identical .summary-card padding rules with the
same mobile reduction. None of these are page-specific.

Consolidate:
- .header-row family → page-shell scoped to .settings-page, .xray-page
- .icons-only family → page-shell global (the class is a deliberate
  opt-in marker, no scope needed)
- .summary-card → page-shell scoped to .clients-page, .inbounds-page,
  .nodes-page (also fixes InboundsPage's missing scope — its rule was
  global and would have matched stray .summary-card uses elsewhere)

InboundsPage.css and NodesPage.css became empty after the move so the
files and their per-page imports are deleted.

* refactor(frontend): hoist .random-icon to utils.css

Three form modals each carried identical .random-icon styles (small
primary-tinted icon next to randomizable inputs):
  ClientBulkAddModal, InboundFormModal, OutboundFormModal

Single definition lives in utils.css now. ClientBulkAddModal.css was
just this one rule, so the file and its import are deleted along the way.

.danger-icon is left per file — the margin-left differs slightly
between InboundFormModal (6px) and OutboundFormModal (8px), so it
stays as a page-local rule rather than getting averaged into utils.css.

* refactor(frontend): hoist .danger-icon to utils.css and use it everywhere

InboundFormModal (margin-left 6px) and OutboundFormModal (margin-left
8px) each carried their own .danger-icon, and FinalMaskForm wrote the
same color/cursor/marginLeft trio inline five times. Unify on a single
.danger-icon in utils.css with margin-left: 8px — matching the more
generous OutboundFormModal value — and:
- Drop the per-file .danger-icon copies from InboundFormModal.css and
  OutboundFormModal.css.
- Replace the five inline style props in FinalMaskForm.tsx with
  className="danger-icon".

The visible change is a 2px wider gap to the right of the delete icons
on InboundFormModal's protocol/peer dividers.
This commit is contained in:
Sanaei
2026-05-25 14:34:53 +02:00
committed by GitHub
parent 19e88c4610
commit dc37f9b731
93 changed files with 2961 additions and 3755 deletions
-965
View File
@@ -1,965 +0,0 @@
import axios from 'axios';
import { getMessage } from './messageBus';
export class Msg {
constructor(success = false, msg = "", obj = null) {
this.success = success;
this.msg = msg;
this.obj = obj;
}
}
export class HttpUtil {
static _handleMsg(msg) {
if (!(msg instanceof Msg) || msg.msg === "") {
return;
}
const messageType = msg.success ? 'success' : 'error';
getMessage()[messageType](msg.msg);
}
static _respToMsg(resp) {
if (!resp || !resp.data) {
return new Msg(false, 'No response data');
}
const { data } = resp;
if (data == null) {
return new Msg(true);
}
if (typeof data === 'object' && 'success' in data) {
return new Msg(data.success, data.msg, data.obj);
}
return typeof data === 'object' ? data : new Msg(false, 'unknown data:', data);
}
static async get(url, params, options = {}) {
const { silent, ...axiosOpts } = options;
try {
const resp = await axios.get(url, { params, ...axiosOpts });
const msg = this._respToMsg(resp);
if (!silent) this._handleMsg(msg);
return msg;
} catch (error) {
console.error('GET request failed:', error);
const errorMsg = new Msg(false, error.response?.data?.message || error.message || 'Request failed');
if (!silent) this._handleMsg(errorMsg);
return errorMsg;
}
}
static async post(url, data, options = {}) {
const { silent, ...axiosOpts } = options;
try {
const resp = await axios.post(url, data, axiosOpts);
const msg = this._respToMsg(resp);
if (!silent) this._handleMsg(msg);
return msg;
} catch (error) {
console.error('POST request failed:', error);
const errorMsg = new Msg(false, error.response?.data?.message || error.message || 'Request failed');
if (!silent) this._handleMsg(errorMsg);
return errorMsg;
}
}
static async postWithModal(url, data, modal) {
if (modal) {
modal.loading(true);
}
const msg = await this.post(url, data);
if (modal) {
modal.loading(false);
if (msg instanceof Msg && msg.success) {
modal.close();
}
}
return msg;
}
}
export function applyDocumentTitle() {
const host = window.location.hostname;
if (!host) return;
const current = document.title.trim();
document.title = current ? `${host} - ${current}` : host;
}
export class PromiseUtil {
static async sleep(timeout) {
await new Promise(resolve => {
setTimeout(resolve, timeout)
});
}
}
export class RandomUtil {
static getSeq({ type = "default", hasNumbers = true, hasLowercase = true, hasUppercase = true } = {}) {
let seq = '';
switch (type) {
case "hex":
seq += "0123456789abcdef";
break;
default:
if (hasNumbers) seq += "0123456789";
if (hasLowercase) seq += "abcdefghijklmnopqrstuvwxyz";
if (hasUppercase) seq += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
break;
}
return seq;
}
static randomInteger(min, max) {
const range = max - min + 1;
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
return Math.floor((randomBuffer[0] / (0xFFFFFFFF + 1)) * range) + min;
}
static randomSeq(count, options = {}) {
const seq = this.getSeq(options);
const seqLength = seq.length;
const randomValues = new Uint32Array(count);
window.crypto.getRandomValues(randomValues);
return Array.from(randomValues, v => seq[v % seqLength]).join('');
}
static randomShortIds() {
const lengths = [2, 4, 6, 8, 10, 12, 14, 16].sort(() => Math.random() - 0.5);
return lengths.map(len => this.randomSeq(len, { type: "hex" })).join(',');
}
static randomLowerAndNum(len) {
return this.randomSeq(len, { hasUppercase: false });
}
static randomUUID() {
if (window.location.protocol === "https:") {
return window.crypto.randomUUID();
} else {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/[xy]/g, function (c) {
const randomValues = new Uint8Array(1);
window.crypto.getRandomValues(randomValues);
let randomValue = randomValues[0] % 16;
let calculatedValue = (c === 'x') ? randomValue : (randomValue & 0x3 | 0x8);
return calculatedValue.toString(16);
});
}
}
static randomShadowsocksPassword(method = '2022-blake3-aes-256-gcm') {
let length = 32;
if (method === '2022-blake3-aes-128-gcm') {
length = 16;
}
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return Base64.alternativeEncode(String.fromCharCode(...array));
}
static randomBase64(length = 16) {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return Base64.alternativeEncode(String.fromCharCode(...array));
}
static randomBase32String(length = 16) {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
const base32Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
let result = '';
let bits = 0;
let buffer = 0;
for (let i = 0; i < array.length; i++) {
buffer = (buffer << 8) | array[i];
bits += 8;
while (bits >= 5) {
bits -= 5;
result += base32Chars[(buffer >>> bits) & 0x1F];
}
}
if (bits > 0) {
result += base32Chars[(buffer << (5 - bits)) & 0x1F];
}
return result;
}
}
export class ObjectUtil {
static getPropIgnoreCase(obj, prop) {
for (const name in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, name)) {
continue;
}
if (name.toLowerCase() === prop.toLowerCase()) {
return obj[name];
}
}
return undefined;
}
static deepSearch(obj, key) {
if (obj instanceof Array) {
for (let i = 0; i < obj.length; ++i) {
if (this.deepSearch(obj[i], key)) {
return true;
}
}
} else if (obj instanceof Object) {
for (let name in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, name)) {
continue;
}
if (this.deepSearch(obj[name], key)) {
return true;
}
}
} else {
return this.isEmpty(obj) ? false : obj.toString().toLowerCase().indexOf(key.toLowerCase()) >= 0;
}
return false;
}
static isEmpty(obj) {
return obj === null || obj === undefined || obj === '';
}
static isArrEmpty(arr) {
return !Array.isArray(arr) || arr.length === 0;
}
static copyArr(dest, src) {
dest.splice(0);
for (const item of src) {
dest.push(item);
}
}
static clone(obj) {
let newObj;
if (obj instanceof Array) {
newObj = [];
this.copyArr(newObj, obj);
} else if (obj instanceof Object) {
newObj = {};
for (const key of Object.keys(obj)) {
newObj[key] = obj[key];
}
} else {
newObj = obj;
}
return newObj;
}
static deepClone(obj) {
let newObj;
if (obj instanceof Array) {
newObj = [];
for (const item of obj) {
newObj.push(this.deepClone(item));
}
} else if (obj instanceof Object) {
newObj = {};
for (const key of Object.keys(obj)) {
newObj[key] = this.deepClone(obj[key]);
}
} else {
newObj = obj;
}
return newObj;
}
static cloneProps(dest, src, ...ignoreProps) {
if (dest == null || src == null) {
return;
}
const ignoreEmpty = this.isArrEmpty(ignoreProps);
for (const key of Object.keys(src)) {
if (!Object.prototype.hasOwnProperty.call(src, key)) {
continue;
} else if (!Object.prototype.hasOwnProperty.call(dest, key)) {
continue;
} else if (src[key] === undefined) {
continue;
}
if (ignoreEmpty) {
dest[key] = src[key];
} else {
let ignore = false;
for (let i = 0; i < ignoreProps.length; ++i) {
if (key === ignoreProps[i]) {
ignore = true;
break;
}
}
if (!ignore) {
dest[key] = src[key];
}
}
}
}
static delProps(obj, ...props) {
for (const prop of props) {
if (prop in obj) {
delete obj[prop];
}
}
}
static execute(func, ...args) {
if (!this.isEmpty(func) && typeof func === 'function') {
func(...args);
}
}
static orDefault(obj, defaultValue) {
if (obj == null) {
return defaultValue;
}
return obj;
}
static equals(a, b) {
// shallow, symmetric comparison so newly added fields also affect equality
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) return false;
for (const key of aKeys) {
if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
if (a[key] !== b[key]) return false;
}
return true;
}
}
export class Wireguard {
static gf(init) {
var r = new Float64Array(16);
if (init) {
for (var i = 0; i < init.length; ++i)
r[i] = init[i];
}
return r;
}
static pack(o, n) {
let b;
const m = this.gf(), t = this.gf();
for (let i = 0; i < 16; ++i)
t[i] = n[i];
this.carry(t);
this.carry(t);
this.carry(t);
for (let j = 0; j < 2; ++j) {
m[0] = t[0] - 0xffed;
for (let i = 1; i < 15; ++i) {
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
this.cswap(t, m, 1 - b);
}
for (let i = 0; i < 16; ++i) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
static carry(o) {
for (let i = 0; i < 16; ++i) {
o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536);
o[i] &= 0xffff;
}
}
static cswap(p, q, b) {
const c = ~(b - 1);
let t;
for (let i = 0; i < 16; ++i) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
static add(o, a, b) {
for (let i = 0; i < 16; ++i)
o[i] = (a[i] + b[i]) | 0;
}
static subtract(o, a, b) {
for (let i = 0; i < 16; ++i)
o[i] = (a[i] - b[i]) | 0;
}
static multmod(o, a, b) {
const t = new Float64Array(31);
for (let i = 0; i < 16; ++i) {
for (let j = 0; j < 16; ++j)
t[i + j] += a[i] * b[j];
}
for (let i = 0; i < 15; ++i)
t[i] += 38 * t[i + 16];
for (let i = 0; i < 16; ++i)
o[i] = t[i];
this.carry(o);
this.carry(o);
}
static invert(o, i) {
const c = this.gf();
for (let a = 0; a < 16; ++a)
c[a] = i[a];
for (let a = 253; a >= 0; --a) {
this.multmod(c, c, c);
if (a !== 2 && a !== 4)
this.multmod(c, c, i);
}
for (let a = 0; a < 16; ++a)
o[a] = c[a];
}
static clamp(z) {
z[31] = (z[31] & 127) | 64;
z[0] &= 248;
}
static generatePublicKey(privateKey) {
let r;
const z = new Uint8Array(32);
const a = this.gf([1]),
b = this.gf([9]),
c = this.gf(),
d = this.gf([1]),
e = this.gf(),
f = this.gf(),
_121665 = this.gf([0xdb41, 1]),
_9 = this.gf([9]);
for (let i = 0; i < 32; ++i)
z[i] = privateKey[i];
this.clamp(z);
for (let i = 254; i >= 0; --i) {
r = (z[i >>> 3] >>> (i & 7)) & 1;
this.cswap(a, b, r);
this.cswap(c, d, r);
this.add(e, a, c);
this.subtract(a, a, c);
this.add(c, b, d);
this.subtract(b, b, d);
this.multmod(d, e, e);
this.multmod(f, a, a);
this.multmod(a, c, a);
this.multmod(c, b, e);
this.add(e, a, c);
this.subtract(a, a, c);
this.multmod(b, a, a);
this.subtract(c, d, f);
this.multmod(a, c, _121665);
this.add(a, a, d);
this.multmod(c, c, a);
this.multmod(a, d, f);
this.multmod(d, b, _9);
this.multmod(b, e, e);
this.cswap(a, b, r);
this.cswap(c, d, r);
}
this.invert(c, c);
this.multmod(a, a, c);
this.pack(z, a);
return z;
}
static generatePresharedKey() {
var privateKey = new Uint8Array(32);
window.crypto.getRandomValues(privateKey);
return privateKey;
}
static generatePrivateKey() {
var privateKey = this.generatePresharedKey();
this.clamp(privateKey);
return privateKey;
}
static encodeBase64(dest, src) {
var input = Uint8Array.from([(src[0] >> 2) & 63, ((src[0] << 4) | (src[1] >> 4)) & 63, ((src[1] << 2) | (src[2] >> 6)) & 63, src[2] & 63]);
for (var i = 0; i < 4; ++i)
dest[i] = input[i] + 65 +
(((25 - input[i]) >> 8) & 6) -
(((51 - input[i]) >> 8) & 75) -
(((61 - input[i]) >> 8) & 15) +
(((62 - input[i]) >> 8) & 3);
}
static keyToBase64(key) {
var i, base64 = new Uint8Array(44);
for (i = 0; i < 32 / 3; ++i)
this.encodeBase64(base64.subarray(i * 4), key.subarray(i * 3));
this.encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0]));
base64[43] = 61;
return String.fromCharCode.apply(null, base64);
}
static keyFromBase64(encoded) {
const binaryStr = atob(encoded);
const bytes = new Uint8Array(binaryStr.length);
for (let i = 0; i < binaryStr.length; i++) {
bytes[i] = binaryStr.charCodeAt(i);
}
return bytes;
}
static generateKeypair(secretKey = '') {
var privateKey = secretKey.length > 0 ? this.keyFromBase64(secretKey) : this.generatePrivateKey();
var publicKey = this.generatePublicKey(privateKey);
return {
publicKey: this.keyToBase64(publicKey),
privateKey: secretKey.length > 0 ? secretKey : this.keyToBase64(privateKey)
};
}
}
export class ClipboardManager {
static async copyText(content = "") {
const text = String(content ?? "");
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
/* fall through to legacy path */
}
}
return ClipboardManager._legacyCopy(text);
}
static _legacyCopy(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.setAttribute('aria-hidden', 'true');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.style.top = '0';
textarea.style.opacity = '1';
const active = document.activeElement;
const host = (active && active !== document.body && active.parentElement)
? active.parentElement
: document.body;
host.appendChild(textarea);
const prevSelection = document.getSelection()?.rangeCount
? document.getSelection().getRangeAt(0)
: null;
let ok = false;
try {
textarea.focus({ preventScroll: true });
textarea.select();
textarea.setSelectionRange(0, text.length);
ok = document.execCommand('copy');
} catch {
/* keep ok as false */
}
host.removeChild(textarea);
if (active && typeof active.focus === 'function') {
try { active.focus({ preventScroll: true }); } catch { /* ignore */ }
}
if (prevSelection) {
const sel = document.getSelection();
sel?.removeAllRanges();
sel?.addRange(prevSelection);
}
return ok;
}
}
export class Base64 {
static encode(content = "", safe = false) {
if (safe) {
return Base64.encode(content)
.replace(/\+/g, '-')
.replace(/=/g, '')
.replace(/\//g, '_')
}
return window.btoa(
String.fromCharCode(...new TextEncoder().encode(content))
)
}
static alternativeEncode(content) {
return window.btoa(
content
)
}
static decode(content = "") {
return new TextDecoder()
.decode(
Uint8Array.from(window.atob(content), c => c.charCodeAt(0))
)
}
}
export class SizeFormatter {
static ONE_KB = 1024;
static ONE_MB = this.ONE_KB * 1024;
static ONE_GB = this.ONE_MB * 1024;
static ONE_TB = this.ONE_GB * 1024;
static ONE_PB = this.ONE_TB * 1024;
static sizeFormat(size) {
if (size <= 0) return "0 B";
if (size < this.ONE_KB) return size.toFixed(0) + " B";
if (size < this.ONE_MB) return (size / this.ONE_KB).toFixed(2) + " KB";
if (size < this.ONE_GB) return (size / this.ONE_MB).toFixed(2) + " MB";
if (size < this.ONE_TB) return (size / this.ONE_GB).toFixed(2) + " GB";
if (size < this.ONE_PB) return (size / this.ONE_TB).toFixed(2) + " TB";
return (size / this.ONE_PB).toFixed(2) + " PB";
}
}
export class CPUFormatter {
static cpuSpeedFormat(speed) {
return speed > 1000 ? (speed / 1000).toFixed(2) + " GHz" : speed.toFixed(2) + " MHz";
}
static cpuCoreFormat(cores) {
return cores === 1 ? "1 Core" : cores + " Cores";
}
}
export class TimeFormatter {
static formatSecond(second) {
if (second < 60) return second.toFixed(0) + 's';
if (second < 3600) return (second / 60).toFixed(0) + 'm';
if (second < 3600 * 24) return (second / 3600).toFixed(0) + 'h';
let day = Math.floor(second / 3600 / 24);
let remain = ((second / 3600) - (day * 24)).toFixed(0);
return day + 'd' + (remain > 0 ? ' ' + remain + 'h' : '');
}
}
export class NumberFormatter {
static addZero(num) {
return num < 10 ? "0" + num : num;
}
static toFixed(num, n) {
n = Math.pow(10, n);
return Math.floor(num * n) / n;
}
}
export class Utils {
static debounce(fn, delay) {
let timeoutID = null;
return function () {
clearTimeout(timeoutID);
let args = arguments;
let that = this;
timeoutID = setTimeout(() => fn.apply(that, args), delay);
};
}
}
export class CookieManager {
static getCookie(cname) {
let name = cname + '=';
let ca = document.cookie.split(';');
for (let c of ca) {
c = c.trim();
if (c.indexOf(name) === 0) {
return decodeURIComponent(c.substring(name.length, c.length));
}
}
return '';
}
static setCookie(cname, cvalue, exdays) {
let expires = '';
if (exdays) {
const d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
expires = 'expires=' + d.toUTCString() + ';';
}
document.cookie = cname + '=' + encodeURIComponent(cvalue) + ';' + expires + 'path=/';
}
}
// AD-Vue 4 semantic palette — kept in one place so the client/inbound
// rows match the rest of the panel. Purple is reserved for the
// "no quota / no expiry / unlimited" sentinel since the AD-Vue green
// would otherwise read as "healthy / under limit".
const COLORS = {
success: '#389e0a', // AD-Vue green-7 — within quota (toned down from green-6 #52c41a, which was too bright on dark themes)
warning: '#faad14', // AD-Vue gold — close to quota / about to expire
danger: '#ff4d4f', // AD-Vue red — depleted / expired
purple: '#722ed1', // AD-Vue purple — unlimited / no expiry
};
export class ColorUtils {
static usageColor(data, threshold, total) {
switch (true) {
case data === null: return "purple";
case total < 0: return "green";
case total == 0: return "purple";
case data < total - threshold: return "green";
case data < total: return "orange";
default: return "red";
}
}
static clientUsageColor(clientStats, trafficDiff) {
switch (true) {
case !clientStats || clientStats.total == 0: return COLORS.purple;
case clientStats.up + clientStats.down < clientStats.total - trafficDiff: return COLORS.success;
case clientStats.up + clientStats.down < clientStats.total: return COLORS.warning;
default: return COLORS.danger;
}
}
static userExpiryColor(threshold, client, isDark = false) {
if (!client.enable) return isDark ? '#2c3950' : '#bcbcbc';
let now = new Date().getTime(), expiry = client.expiryTime;
switch (true) {
case expiry === null: return COLORS.purple;
case expiry < 0: return COLORS.success;
case expiry == 0: return COLORS.purple;
case now < expiry - threshold: return COLORS.success;
case now < expiry: return COLORS.warning;
default: return COLORS.danger;
}
}
}
export class ArrayUtils {
static doAllItemsExist(array1, array2) {
return array1.every(item => array2.includes(item));
}
}
export class URLBuilder {
static buildURL({ host, port, isTLS, base, path }) {
if (!host || host.length === 0) host = window.location.hostname;
if (!port || port.length === 0) port = window.location.port;
if (isTLS === undefined) isTLS = window.location.protocol === "https:";
const protocol = isTLS ? "https:" : "http:";
port = String(port);
if (port === "" || (isTLS && port === "443") || (!isTLS && port === "80")) {
port = "";
} else {
port = `:${port}`;
}
return `${protocol}//${host}${port}${base}${path}`;
}
}
export class LanguageManager {
static supportedLanguages = [
{
name: "العربية",
value: "ar-EG",
icon: "🇪🇬",
},
{
name: "English",
value: "en-US",
icon: "🇺🇸",
},
{
name: "فارسی",
value: "fa-IR",
icon: "🇮🇷",
},
{
name: "简体中文",
value: "zh-CN",
icon: "🇨🇳",
},
{
name: "繁體中文",
value: "zh-TW",
icon: "🇹🇼",
},
{
name: "日本語",
value: "ja-JP",
icon: "🇯🇵",
},
{
name: "Русский",
value: "ru-RU",
icon: "🇷🇺",
},
{
name: "Tiếng Việt",
value: "vi-VN",
icon: "🇻🇳",
},
{
name: "Español",
value: "es-ES",
icon: "🇪🇸",
},
{
name: "Indonesian",
value: "id-ID",
icon: "🇮🇩",
},
{
name: "Український",
value: "uk-UA",
icon: "🇺🇦",
},
{
name: "Türkçe",
value: "tr-TR",
icon: "🇹🇷",
},
{
name: "Português",
value: "pt-BR",
icon: "🇧🇷",
}
]
static getLanguage() {
let lang = CookieManager.getCookie("lang");
if (!lang) {
if (window.navigator) {
lang = window.navigator.language || window.navigator.userLanguage;
const simularLangs = [
["ar", this.supportedLanguages[0].value],
["fa", this.supportedLanguages[2].value],
["ja", this.supportedLanguages[5].value],
["ru", this.supportedLanguages[6].value],
["vi", this.supportedLanguages[7].value],
["es", this.supportedLanguages[8].value],
["id", this.supportedLanguages[9].value],
["uk", this.supportedLanguages[10].value],
["tr", this.supportedLanguages[11].value],
["pt", this.supportedLanguages[12].value],
]
simularLangs.forEach((pair) => {
if (lang === pair[0]) {
lang = pair[1];
}
});
if (LanguageManager.isSupportLanguage(lang)) {
CookieManager.setCookie("lang", lang);
} else {
CookieManager.setCookie("lang", "en-US");
window.location.reload();
}
} else {
CookieManager.setCookie("lang", "en-US");
window.location.reload();
}
}
return lang;
}
static setLanguage(language) {
if (!LanguageManager.isSupportLanguage(language)) {
language = "en-US";
}
CookieManager.setCookie("lang", language);
window.location.reload();
}
static isSupportLanguage(language) {
const languageFilter = LanguageManager.supportedLanguages.filter((lang) => {
return lang.value === language
})
return languageFilter.length > 0;
}
}
export class FileManager {
static downloadTextFile(content, filename = 'file.txt', options = { type: "text/plain" }) {
let link = window.document.createElement('a');
link.download = filename;
link.style.border = '0';
link.style.padding = '0';
link.style.margin = '0';
link.style.position = 'absolute';
link.style.left = '-9999px';
link.style.top = `${window.pageYOffset || window.document.documentElement.scrollTop}px`;
link.href = URL.createObjectURL(new Blob([content], options));
link.click();
URL.revokeObjectURL(link.href);
link.remove();
}
}
export class IntlUtil {
// For Jalali display, always use fa-IR locale (its default calendar
// is Persian) so we get a clean "1405/07/03 12:00:00" format with
// Persian digits, without the awkward "AP" era suffix that appears
// when other locales force `-u-ca-persian`.
static formatDate(date, calendar = "gregorian") {
const language = LanguageManager.getLanguage()
const locale = calendar === "jalalian" ? "fa-IR" : language
const intlOptions = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
}
const intl = new Intl.DateTimeFormat(
locale,
intlOptions
)
return intl.format(new Date(date))
}
static formatRelativeTime(date) {
const language = LanguageManager.getLanguage()
const now = new Date()
// Handle delayed start (negative expiryTime values)
const diff = date < 0
? Math.round(date / (1000 * 60 * 60 * 24))
: Math.round((date - now) / (1000 * 60 * 60 * 24))
const formatter = new Intl.RelativeTimeFormat(language, { numeric: 'auto' })
return formatter.format(diff, 'day');
}
}
+932
View File
@@ -0,0 +1,932 @@
import axios from 'axios';
import type { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { getMessage } from './messageBus';
type RespEnvelope = { success?: unknown; msg?: unknown; obj?: unknown };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export class Msg<T = any> {
success: boolean;
msg: string;
obj: T | null;
constructor(success: boolean = false, msg: string = '', obj: T | null = null) {
this.success = success;
this.msg = msg;
this.obj = obj;
}
}
export interface HttpOptions extends AxiosRequestConfig {
silent?: boolean;
}
export interface HttpModal {
loading: (state: boolean) => void;
close: () => void;
}
export class HttpUtil {
static _handleMsg(msg: unknown): void {
if (!(msg instanceof Msg) || msg.msg === '') {
return;
}
const messageType = msg.success ? 'success' : 'error';
getMessage()[messageType](msg.msg);
}
static _respToMsg(resp: AxiosResponse | undefined): Msg {
if (!resp || !resp.data) {
return new Msg(false, 'No response data');
}
const { data } = resp;
if (data == null) {
return new Msg(true);
}
if (typeof data === 'object' && 'success' in (data as object)) {
const d = data as RespEnvelope;
return new Msg(Boolean(d.success), typeof d.msg === 'string' ? d.msg : '', d.obj ?? null);
}
return typeof data === 'object' ? (data as Msg) : new Msg(false, 'unknown data:', data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static async get<T = any>(url: string, params?: unknown, options: HttpOptions = {}): Promise<Msg<T>> {
const { silent, ...axiosOpts } = options;
try {
const resp = await axios.get(url, { params, ...axiosOpts });
const msg = this._respToMsg(resp) as Msg<T>;
if (!silent) this._handleMsg(msg);
return msg;
} catch (error) {
console.error('GET request failed:', error);
const err = error as AxiosError<{ message?: string }>;
const errorMsg = new Msg<T>(false, err.response?.data?.message || err.message || 'Request failed');
if (!silent) this._handleMsg(errorMsg);
return errorMsg;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static async post<T = any>(url: string, data?: unknown, options: HttpOptions = {}): Promise<Msg<T>> {
const { silent, ...axiosOpts } = options;
try {
const resp = await axios.post(url, data, axiosOpts);
const msg = this._respToMsg(resp) as Msg<T>;
if (!silent) this._handleMsg(msg);
return msg;
} catch (error) {
console.error('POST request failed:', error);
const err = error as AxiosError<{ message?: string }>;
const errorMsg = new Msg<T>(false, err.response?.data?.message || err.message || 'Request failed');
if (!silent) this._handleMsg(errorMsg);
return errorMsg;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static async postWithModal<T = any>(url: string, data?: unknown, modal?: HttpModal | null): Promise<Msg<T>> {
if (modal) {
modal.loading(true);
}
const msg = await this.post<T>(url, data);
if (modal) {
modal.loading(false);
if (msg instanceof Msg && msg.success) {
modal.close();
}
}
return msg;
}
}
export function applyDocumentTitle(): void {
const host = window.location.hostname;
if (!host) return;
const current = document.title.trim();
document.title = current ? `${host} - ${current}` : host;
}
export class PromiseUtil {
static async sleep(timeout: number): Promise<void> {
await new Promise<void>((resolve) => {
setTimeout(resolve, timeout);
});
}
}
export interface RandomSeqOptions {
type?: 'default' | 'hex';
hasNumbers?: boolean;
hasLowercase?: boolean;
hasUppercase?: boolean;
}
export class RandomUtil {
static getSeq({ type = 'default', hasNumbers = true, hasLowercase = true, hasUppercase = true }: RandomSeqOptions = {}): string {
let seq = '';
switch (type) {
case 'hex':
seq += '0123456789abcdef';
break;
default:
if (hasNumbers) seq += '0123456789';
if (hasLowercase) seq += 'abcdefghijklmnopqrstuvwxyz';
if (hasUppercase) seq += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
}
return seq;
}
static randomInteger(min: number, max: number): number {
const range = max - min + 1;
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
return Math.floor((randomBuffer[0] / (0xFFFFFFFF + 1)) * range) + min;
}
static randomSeq(count: number, options: RandomSeqOptions = {}): string {
const seq = this.getSeq(options);
const seqLength = seq.length;
const randomValues = new Uint32Array(count);
window.crypto.getRandomValues(randomValues);
return Array.from(randomValues, (v) => seq[v % seqLength]).join('');
}
static randomShortIds(): string {
const lengths = [2, 4, 6, 8, 10, 12, 14, 16].sort(() => Math.random() - 0.5);
return lengths.map((len) => this.randomSeq(len, { type: 'hex' })).join(',');
}
static randomLowerAndNum(len: number): string {
return this.randomSeq(len, { hasUppercase: false });
}
static randomUUID(): string {
if (window.location.protocol === 'https:') {
return window.crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const randomValues = new Uint8Array(1);
window.crypto.getRandomValues(randomValues);
const randomValue = randomValues[0] % 16;
const calculatedValue = c === 'x' ? randomValue : (randomValue & 0x3) | 0x8;
return calculatedValue.toString(16);
});
}
static randomShadowsocksPassword(method: string = '2022-blake3-aes-256-gcm'): string {
let length = 32;
if (method === '2022-blake3-aes-128-gcm') {
length = 16;
}
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return Base64.alternativeEncode(String.fromCharCode(...array));
}
static randomBase64(length: number = 16): string {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return Base64.alternativeEncode(String.fromCharCode(...array));
}
static randomBase32String(length: number = 16): string {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
const base32Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
let result = '';
let bits = 0;
let buffer = 0;
for (let i = 0; i < array.length; i++) {
buffer = (buffer << 8) | array[i];
bits += 8;
while (bits >= 5) {
bits -= 5;
result += base32Chars[(buffer >>> bits) & 0x1F];
}
}
if (bits > 0) {
result += base32Chars[(buffer << (5 - bits)) & 0x1F];
}
return result;
}
}
type AnyRecord = Record<string, unknown>;
export class ObjectUtil {
static getPropIgnoreCase(obj: AnyRecord, prop: string): unknown {
for (const name in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, name)) continue;
if (name.toLowerCase() === prop.toLowerCase()) {
return obj[name];
}
}
return undefined;
}
static deepSearch(obj: unknown, key: string): boolean {
if (obj instanceof Array) {
for (let i = 0; i < obj.length; ++i) {
if (this.deepSearch(obj[i], key)) return true;
}
} else if (obj instanceof Object) {
const rec = obj as AnyRecord;
for (const name in rec) {
if (!Object.prototype.hasOwnProperty.call(rec, name)) continue;
if (this.deepSearch(rec[name], key)) return true;
}
} else {
return this.isEmpty(obj) ? false : String(obj).toLowerCase().indexOf(key.toLowerCase()) >= 0;
}
return false;
}
static isEmpty(obj: unknown): boolean {
return obj === null || obj === undefined || obj === '';
}
static isArrEmpty(arr: unknown): boolean {
return !Array.isArray(arr) || arr.length === 0;
}
static copyArr<T>(dest: T[], src: T[]): void {
dest.splice(0);
for (const item of src) {
dest.push(item);
}
}
static clone<T>(obj: T): T {
if (obj instanceof Array) {
const newArr: unknown[] = [];
this.copyArr(newArr, obj);
return newArr as unknown as T;
}
if (obj instanceof Object) {
const newObj: AnyRecord = {};
const rec = obj as unknown as AnyRecord;
for (const key of Object.keys(rec)) {
newObj[key] = rec[key];
}
return newObj as unknown as T;
}
return obj;
}
static deepClone<T>(obj: T): T {
if (obj instanceof Array) {
const newArr: unknown[] = [];
for (const item of obj) {
newArr.push(this.deepClone(item));
}
return newArr as unknown as T;
}
if (obj instanceof Object) {
const newObj: AnyRecord = {};
const rec = obj as unknown as AnyRecord;
for (const key of Object.keys(rec)) {
newObj[key] = this.deepClone(rec[key]);
}
return newObj as unknown as T;
}
return obj;
}
static cloneProps(dest: object, src: object, ...ignoreProps: string[]): void {
if (dest == null || src == null) return;
const ignoreEmpty = this.isArrEmpty(ignoreProps);
const d = dest as AnyRecord;
const s = src as AnyRecord;
for (const key of Object.keys(s)) {
if (!Object.prototype.hasOwnProperty.call(s, key)) continue;
if (!Object.prototype.hasOwnProperty.call(d, key)) continue;
if (s[key] === undefined) continue;
if (ignoreEmpty) {
d[key] = s[key];
} else {
let ignore = false;
for (let i = 0; i < ignoreProps.length; ++i) {
if (key === ignoreProps[i]) {
ignore = true;
break;
}
}
if (!ignore) {
d[key] = s[key];
}
}
}
}
static delProps(obj: object, ...props: string[]): void {
const o = obj as AnyRecord;
for (const prop of props) {
if (prop in o) {
delete o[prop];
}
}
}
static execute(func: unknown, ...args: unknown[]): void {
if (!this.isEmpty(func) && typeof func === 'function') {
(func as (...a: unknown[]) => unknown)(...args);
}
}
static orDefault<T>(obj: T | null | undefined, defaultValue: T): T {
if (obj == null) return defaultValue;
return obj;
}
static equals(a: unknown, b: unknown): boolean {
if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {
return a === b;
}
const ra = a as AnyRecord;
const rb = b as AnyRecord;
const aKeys = Object.keys(ra);
const bKeys = Object.keys(rb);
if (aKeys.length !== bKeys.length) return false;
for (const key of aKeys) {
if (!Object.prototype.hasOwnProperty.call(rb, key)) return false;
if (ra[key] !== rb[key]) return false;
}
return true;
}
}
export class Wireguard {
static gf(init?: ArrayLike<number>): Float64Array {
const r = new Float64Array(16);
if (init) {
for (let i = 0; i < init.length; ++i) r[i] = init[i];
}
return r;
}
static pack(o: Uint8Array, n: Float64Array): void {
let b: number;
const m = this.gf();
const t = this.gf();
for (let i = 0; i < 16; ++i) t[i] = n[i];
this.carry(t);
this.carry(t);
this.carry(t);
for (let j = 0; j < 2; ++j) {
m[0] = t[0] - 0xffed;
for (let i = 1; i < 15; ++i) {
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
this.cswap(t, m, 1 - b);
}
for (let i = 0; i < 16; ++i) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
static carry(o: Float64Array): void {
for (let i = 0; i < 16; ++i) {
o[(i + 1) % 16] += (i < 15 ? 1 : 38) * Math.floor(o[i] / 65536);
o[i] &= 0xffff;
}
}
static cswap(p: Float64Array, q: Float64Array, b: number): void {
const c = ~(b - 1);
let t: number;
for (let i = 0; i < 16; ++i) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
static add(o: Float64Array, a: Float64Array, b: Float64Array): void {
for (let i = 0; i < 16; ++i) o[i] = (a[i] + b[i]) | 0;
}
static subtract(o: Float64Array, a: Float64Array, b: Float64Array): void {
for (let i = 0; i < 16; ++i) o[i] = (a[i] - b[i]) | 0;
}
static multmod(o: Float64Array, a: Float64Array, b: Float64Array): void {
const t = new Float64Array(31);
for (let i = 0; i < 16; ++i) {
for (let j = 0; j < 16; ++j) t[i + j] += a[i] * b[j];
}
for (let i = 0; i < 15; ++i) t[i] += 38 * t[i + 16];
for (let i = 0; i < 16; ++i) o[i] = t[i];
this.carry(o);
this.carry(o);
}
static invert(o: Float64Array, i: Float64Array): void {
const c = this.gf();
for (let a = 0; a < 16; ++a) c[a] = i[a];
for (let a = 253; a >= 0; --a) {
this.multmod(c, c, c);
if (a !== 2 && a !== 4) this.multmod(c, c, i);
}
for (let a = 0; a < 16; ++a) o[a] = c[a];
}
static clamp(z: Uint8Array): void {
z[31] = (z[31] & 127) | 64;
z[0] &= 248;
}
static generatePublicKey(privateKey: Uint8Array): Uint8Array {
let r: number;
const z = new Uint8Array(32);
const a = this.gf([1]);
const b = this.gf([9]);
const c = this.gf();
const d = this.gf([1]);
const e = this.gf();
const f = this.gf();
const _121665 = this.gf([0xdb41, 1]);
const _9 = this.gf([9]);
for (let i = 0; i < 32; ++i) z[i] = privateKey[i];
this.clamp(z);
for (let i = 254; i >= 0; --i) {
r = (z[i >>> 3] >>> (i & 7)) & 1;
this.cswap(a, b, r);
this.cswap(c, d, r);
this.add(e, a, c);
this.subtract(a, a, c);
this.add(c, b, d);
this.subtract(b, b, d);
this.multmod(d, e, e);
this.multmod(f, a, a);
this.multmod(a, c, a);
this.multmod(c, b, e);
this.add(e, a, c);
this.subtract(a, a, c);
this.multmod(b, a, a);
this.subtract(c, d, f);
this.multmod(a, c, _121665);
this.add(a, a, d);
this.multmod(c, c, a);
this.multmod(a, d, f);
this.multmod(d, b, _9);
this.multmod(b, e, e);
this.cswap(a, b, r);
this.cswap(c, d, r);
}
this.invert(c, c);
this.multmod(a, a, c);
this.pack(z, a);
return z;
}
static generatePresharedKey(): Uint8Array {
const privateKey = new Uint8Array(32);
window.crypto.getRandomValues(privateKey);
return privateKey;
}
static generatePrivateKey(): Uint8Array {
const privateKey = this.generatePresharedKey();
this.clamp(privateKey);
return privateKey;
}
static encodeBase64(dest: Uint8Array, src: Uint8Array): void {
const input = Uint8Array.from([
(src[0] >> 2) & 63,
((src[0] << 4) | (src[1] >> 4)) & 63,
((src[1] << 2) | (src[2] >> 6)) & 63,
src[2] & 63,
]);
for (let i = 0; i < 4; ++i) {
dest[i] = input[i] + 65 +
(((25 - input[i]) >> 8) & 6) -
(((51 - input[i]) >> 8) & 75) -
(((61 - input[i]) >> 8) & 15) +
(((62 - input[i]) >> 8) & 3);
}
}
static keyToBase64(key: Uint8Array): string {
let i: number;
const base64 = new Uint8Array(44);
for (i = 0; i < 32 / 3; ++i) {
this.encodeBase64(base64.subarray(i * 4), key.subarray(i * 3));
}
this.encodeBase64(base64.subarray(i * 4), Uint8Array.from([key[i * 3 + 0], key[i * 3 + 1], 0]));
base64[43] = 61;
return String.fromCharCode.apply(null, Array.from(base64));
}
static keyFromBase64(encoded: string): Uint8Array {
const binaryStr = atob(encoded);
const bytes = new Uint8Array(binaryStr.length);
for (let i = 0; i < binaryStr.length; i++) {
bytes[i] = binaryStr.charCodeAt(i);
}
return bytes;
}
static generateKeypair(secretKey: string = ''): { publicKey: string; privateKey: string } {
const privateKey = secretKey.length > 0 ? this.keyFromBase64(secretKey) : this.generatePrivateKey();
const publicKey = this.generatePublicKey(privateKey);
return {
publicKey: this.keyToBase64(publicKey),
privateKey: secretKey.length > 0 ? secretKey : this.keyToBase64(privateKey),
};
}
}
export class ClipboardManager {
static async copyText(content: unknown = ''): Promise<boolean> {
const text = String(content ?? '');
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {}
}
return ClipboardManager._legacyCopy(text);
}
static _legacyCopy(text: string): boolean {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.setAttribute('aria-hidden', 'true');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.style.top = '0';
textarea.style.opacity = '1';
const active = document.activeElement as HTMLElement | null;
const host = (active && active !== document.body && active.parentElement)
? active.parentElement
: document.body;
host.appendChild(textarea);
const sel0 = document.getSelection();
const prevSelection = sel0 && sel0.rangeCount ? sel0.getRangeAt(0) : null;
let ok = false;
try {
textarea.focus({ preventScroll: true });
textarea.select();
textarea.setSelectionRange(0, text.length);
ok = document.execCommand('copy');
} catch {}
host.removeChild(textarea);
if (active && typeof active.focus === 'function') {
try { active.focus({ preventScroll: true }); } catch {}
}
if (prevSelection) {
const sel = document.getSelection();
sel?.removeAllRanges();
sel?.addRange(prevSelection);
}
return ok;
}
}
export class Base64 {
static encode(content: string = '', safe: boolean = false): string {
if (safe) {
return Base64.encode(content)
.replace(/\+/g, '-')
.replace(/=/g, '')
.replace(/\//g, '_');
}
return window.btoa(String.fromCharCode(...new TextEncoder().encode(content)));
}
static alternativeEncode(content: string): string {
return window.btoa(content);
}
static decode(content: string = ''): string {
return new TextDecoder().decode(
Uint8Array.from(window.atob(content), (c) => c.charCodeAt(0)),
);
}
}
export class SizeFormatter {
static readonly ONE_KB = 1024;
static readonly ONE_MB = SizeFormatter.ONE_KB * 1024;
static readonly ONE_GB = SizeFormatter.ONE_MB * 1024;
static readonly ONE_TB = SizeFormatter.ONE_GB * 1024;
static readonly ONE_PB = SizeFormatter.ONE_TB * 1024;
static sizeFormat(size: number | null | undefined): string {
if (size == null || size <= 0) return '0 B';
if (size < SizeFormatter.ONE_KB) return size.toFixed(0) + ' B';
if (size < SizeFormatter.ONE_MB) return (size / SizeFormatter.ONE_KB).toFixed(2) + ' KB';
if (size < SizeFormatter.ONE_GB) return (size / SizeFormatter.ONE_MB).toFixed(2) + ' MB';
if (size < SizeFormatter.ONE_TB) return (size / SizeFormatter.ONE_GB).toFixed(2) + ' GB';
if (size < SizeFormatter.ONE_PB) return (size / SizeFormatter.ONE_TB).toFixed(2) + ' TB';
return (size / SizeFormatter.ONE_PB).toFixed(2) + ' PB';
}
}
export class CPUFormatter {
static cpuSpeedFormat(speed: number): string {
return speed > 1000 ? (speed / 1000).toFixed(2) + ' GHz' : speed.toFixed(2) + ' MHz';
}
static cpuCoreFormat(cores: number): string {
return cores === 1 ? '1 Core' : cores + ' Cores';
}
}
export class TimeFormatter {
static formatSecond(second: number): string {
if (second < 60) return second.toFixed(0) + 's';
if (second < 3600) return (second / 60).toFixed(0) + 'm';
if (second < 3600 * 24) return (second / 3600).toFixed(0) + 'h';
const day = Math.floor(second / 3600 / 24);
const remain = Number(((second / 3600) - (day * 24)).toFixed(0));
return day + 'd' + (remain > 0 ? ' ' + remain + 'h' : '');
}
}
export class NumberFormatter {
static addZero(num: number): string | number {
return num < 10 ? '0' + num : num;
}
static toFixed(num: number, n: number): number {
const m = Math.pow(10, n);
return Math.floor(num * m) / m;
}
}
export class Utils {
static debounce<A extends unknown[]>(fn: (...args: A) => unknown, delay: number): (...args: A) => void {
let timeoutID: ReturnType<typeof setTimeout> | null = null;
return function (this: unknown, ...args: A) {
if (timeoutID !== null) clearTimeout(timeoutID);
timeoutID = setTimeout(() => fn.apply(this, args), delay);
};
}
}
export class CookieManager {
static getCookie(cname: string): string {
const name = cname + '=';
const ca = document.cookie.split(';');
for (let c of ca) {
c = c.trim();
if (c.indexOf(name) === 0) {
return decodeURIComponent(c.substring(name.length, c.length));
}
}
return '';
}
static setCookie(cname: string, cvalue: string, exdays?: number): void {
let expires = '';
if (exdays) {
const d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
expires = 'expires=' + d.toUTCString() + ';';
}
document.cookie = cname + '=' + encodeURIComponent(cvalue) + ';' + expires + 'path=/';
}
}
const COLORS = {
success: '#389e0a',
warning: '#faad14',
danger: '#ff4d4f',
purple: '#722ed1',
} as const;
export type UsageColor = 'purple' | 'green' | 'orange' | 'red';
export interface ClientUsageStats {
total: number;
up: number;
down: number;
}
export interface ExpiryClient {
enable: boolean;
expiryTime: number | null;
}
export class ColorUtils {
static usageColor(
data: number | null | undefined,
threshold: number,
total: number | { valueOf(): number } | null | undefined,
): UsageColor {
const t = Number(total ?? 0);
const d = Number(data);
switch (true) {
case data === null || data === undefined: return 'purple';
case t < 0: return 'green';
case t == 0: return 'purple';
case d < t - threshold: return 'green';
case d < t: return 'orange';
default: return 'red';
}
}
static clientUsageColor(clientStats: ClientUsageStats | null | undefined, trafficDiff: number): string {
switch (true) {
case !clientStats || clientStats.total == 0: return COLORS.purple;
case clientStats!.up + clientStats!.down < clientStats!.total - trafficDiff: return COLORS.success;
case clientStats!.up + clientStats!.down < clientStats!.total: return COLORS.warning;
default: return COLORS.danger;
}
}
static userExpiryColor(threshold: number, client: ExpiryClient, isDark: boolean = false): string {
if (!client.enable) return isDark ? '#2c3950' : '#bcbcbc';
const now = new Date().getTime();
const expiry = client.expiryTime;
switch (true) {
case expiry === null: return COLORS.purple;
case (expiry as number) < 0: return COLORS.success;
case (expiry as number) == 0: return COLORS.purple;
case now < (expiry as number) - threshold: return COLORS.success;
case now < (expiry as number): return COLORS.warning;
default: return COLORS.danger;
}
}
}
export class ArrayUtils {
static doAllItemsExist<T>(array1: T[], array2: T[]): boolean {
return array1.every((item) => array2.includes(item));
}
}
export interface BuildURLOptions {
host?: string;
port?: string;
isTLS?: boolean;
base: string;
path: string;
}
export class URLBuilder {
static buildURL({ host, port, isTLS, base, path }: BuildURLOptions): string {
if (!host || host.length === 0) host = window.location.hostname;
if (!port || port.length === 0) port = window.location.port;
if (isTLS === undefined) isTLS = window.location.protocol === 'https:';
const protocol = isTLS ? 'https:' : 'http:';
let portPart = String(port);
if (portPart === '' || (isTLS && portPart === '443') || (!isTLS && portPart === '80')) {
portPart = '';
} else {
portPart = `:${portPart}`;
}
return `${protocol}//${host}${portPart}${base}${path}`;
}
}
export interface SupportedLanguage {
name: string;
value: string;
icon: string;
}
export class LanguageManager {
static readonly supportedLanguages: readonly SupportedLanguage[] = [
{ name: 'العربية', value: 'ar-EG', icon: '🇪🇬' },
{ name: 'English', value: 'en-US', icon: '🇺🇸' },
{ name: 'فارسی', value: 'fa-IR', icon: '🇮🇷' },
{ name: '简体中文', value: 'zh-CN', icon: '🇨🇳' },
{ name: '繁體中文', value: 'zh-TW', icon: '🇹🇼' },
{ name: '日本語', value: 'ja-JP', icon: '🇯🇵' },
{ name: 'Русский', value: 'ru-RU', icon: '🇷🇺' },
{ name: 'Tiếng Việt', value: 'vi-VN', icon: '🇻🇳' },
{ name: 'Español', value: 'es-ES', icon: '🇪🇸' },
{ name: 'Indonesian', value: 'id-ID', icon: '🇮🇩' },
{ name: 'Український', value: 'uk-UA', icon: '🇺🇦' },
{ name: 'Türkçe', value: 'tr-TR', icon: '🇹🇷' },
{ name: 'Português', value: 'pt-BR', icon: '🇧🇷' },
];
static getLanguage(): string {
let lang = CookieManager.getCookie('lang');
if (lang) return lang;
if (window.navigator) {
const nav = window.navigator as Navigator & { userLanguage?: string };
lang = nav.language || nav.userLanguage || '';
const simularLangs: [string, string][] = [
['ar', LanguageManager.supportedLanguages[0].value],
['fa', LanguageManager.supportedLanguages[2].value],
['ja', LanguageManager.supportedLanguages[5].value],
['ru', LanguageManager.supportedLanguages[6].value],
['vi', LanguageManager.supportedLanguages[7].value],
['es', LanguageManager.supportedLanguages[8].value],
['id', LanguageManager.supportedLanguages[9].value],
['uk', LanguageManager.supportedLanguages[10].value],
['tr', LanguageManager.supportedLanguages[11].value],
['pt', LanguageManager.supportedLanguages[12].value],
];
simularLangs.forEach((pair) => {
if (lang === pair[0]) {
lang = pair[1];
}
});
if (LanguageManager.isSupportLanguage(lang)) {
CookieManager.setCookie('lang', lang);
} else {
CookieManager.setCookie('lang', 'en-US');
window.location.reload();
}
} else {
CookieManager.setCookie('lang', 'en-US');
window.location.reload();
}
return lang;
}
static setLanguage(language: string): void {
if (!LanguageManager.isSupportLanguage(language)) {
language = 'en-US';
}
CookieManager.setCookie('lang', language);
window.location.reload();
}
static isSupportLanguage(language: string): boolean {
return LanguageManager.supportedLanguages.some((lang) => lang.value === language);
}
}
export class FileManager {
static downloadTextFile(content: BlobPart, filename: string = 'file.txt', options: BlobPropertyBag = { type: 'text/plain' }): void {
const link = window.document.createElement('a');
link.download = filename;
link.style.border = '0';
link.style.padding = '0';
link.style.margin = '0';
link.style.position = 'absolute';
link.style.left = '-9999px';
link.style.top = `${window.pageYOffset || window.document.documentElement.scrollTop}px`;
link.href = URL.createObjectURL(new Blob([content], options));
link.click();
URL.revokeObjectURL(link.href);
link.remove();
}
}
export type CalendarKind = 'gregorian' | 'jalalian';
export class IntlUtil {
static formatDate(date: string | number | Date | null | undefined, calendar: CalendarKind = 'gregorian'): string {
if (date == null) return '';
const language = LanguageManager.getLanguage();
const locale = calendar === 'jalalian' ? 'fa-IR' : language;
const intlOptions: Intl.DateTimeFormatOptions = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
};
const intl = new Intl.DateTimeFormat(locale, intlOptions);
return intl.format(new Date(date));
}
static formatRelativeTime(date: number | null | undefined): string {
if (date == null) return '';
const language = LanguageManager.getLanguage();
const now = new Date();
const diff = date < 0
? Math.round(date / (1000 * 60 * 60 * 24))
: Math.round((date - now.getTime()) / (1000 * 60 * 60 * 24));
const formatter = new Intl.RelativeTimeFormat(language, { numeric: 'auto' });
return formatter.format(diff, 'day');
}
}