mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-08-10 05:10:58 +00:00
perf(clients): make the clients page scale to large panels
The clients page was slow on panels with many clients for two independent reasons: the server rebuilt the whole picture on every request, and the browser rebuilt the whole table on every poll. Server side, ListPaged loaded every client row, every client_inbounds link and every client_traffics row into Go memory, then filtered, sorted and paginated in a loop -- on a request the page repeats every five seconds. Every predicate now runs in SQL and only the requested page's ids are hydrated, so the cost tracks the page size rather than the client count. Measured on SQLite with a realistic status mix: the default view at 100k clients goes from 1,072ms to 64ms. Behaviour is preserved deliberately in the subtle places -- the cross-panel global-traffic overlay is folded into the same used-bytes expression the predicates and sort use, LIKE wildcards are escaped so a search for "a_b" stays literal, and the two different tiebreak rules the in-memory comparator had are reproduced per sort key. The summary's per-bucket email lists are capped at 200 with exact counters beside them. They only back hover popovers, but shipping every match made the response grow with the panel: at 100k clients it carried ~42k emails, and the page revalidated all of them through a strict Zod parse every five seconds. The popover now shows a "+N" chip for the remainder. Browser side, the page fired three sequential list requests per load and threw the first two away: the query went out before the persisted sort was applied, and again before the configured page size was known -- 0 meaning "one long page" is indistinguishable from "not loaded yet". The page size is now derived rather than mirrored through an effect, and the previous visit's value is remembered so the single request goes out at mount instead of queueing behind /setting/defaultSettings. Then the per-poll work. Reading isFetching made it a tracked property, so the refetch interval notified twice per cycle and re-rendered the page even when structural sharing left the data identical. Xray reports a traffic row per client whether or not it moved bytes, so the speed map was mostly zeros and was replaced wholesale every push; zero rows are now dropped and an unchanged result returns the previous object, which lets React bail out instead of re-rendering. The five Tooltip-wrapped buttons and the inbound chips per row do not depend on traffic at all and are now memoised, keyed on the email because a push replaces the row object of every client whose counters moved. antd's hashed:false drops 3,311 :where(.css-<hash>) wrappers and 29% of the generated stylesheet, and a pinned cssVar key stops each of the eleven page-level ConfigProviders minting its own token scope. Two callers that only need the mutations, GroupsPage and ClientBulkAddModal, no longer start the list query -- the groups page had been polling the full paged list every five seconds for data it never renders.
This commit is contained in:
@@ -5691,7 +5691,7 @@
|
||||
"tags": [
|
||||
"Clients"
|
||||
],
|
||||
"summary": "Filter, sort, and paginate clients on the server. Each item is a slim row (no uuid/password/auth/flow/security/reverse/tgId) so the clients page can ship 25-ish rows in a few KB instead of the full table. The response also includes a summary computed across the full DB row set so dashboard counters stay stable as the user paginates or filters. Page size capped at 200; fetch /get/:email to obtain the full per-client payload for an edit/info modal.",
|
||||
"summary": "Filter, sort, and paginate clients on the server. Each item is a slim row (no uuid/password/auth/flow/security/reverse/tgId) so the clients page can ship 25-ish rows in a few KB instead of the full table. The response also includes a summary computed across the full DB row set so dashboard counters stay stable as the user paginates or filters: the *Count fields are exact, while the email arrays beside them stop at 200 entries so the payload does not grow with the panel. Page size capped at 200; fetch /get/:email to obtain the full per-client payload for an edit/info modal.",
|
||||
"operationId": "get_panel_api_clients_list_paged",
|
||||
"parameters": [
|
||||
{
|
||||
@@ -5807,12 +5807,18 @@
|
||||
"summary": {
|
||||
"total": 2000,
|
||||
"active": 1850,
|
||||
"onlineCount": 1,
|
||||
"depletedCount": 0,
|
||||
"expiringCount": 0,
|
||||
"deactiveCount": 150,
|
||||
"online": [
|
||||
"alice@example.com"
|
||||
],
|
||||
"depleted": [],
|
||||
"expiring": [],
|
||||
"deactive": []
|
||||
"deactive": [
|
||||
"bob@example.com"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo } from 'react';
|
||||
import { memo, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Popover, Progress } from 'antd';
|
||||
|
||||
@@ -17,7 +17,11 @@ export interface ClientTrafficCellProps {
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export default function ClientTrafficCell({
|
||||
// Every prop is a primitive and the component is pure, so the memo bails out
|
||||
// whenever a client's counters did not move — which is most of them on most
|
||||
// pushes. Each skipped instance is one antd Popover (rc-trigger), one Progress,
|
||||
// a useTranslation subscription and a theme context read, times up to 200 rows.
|
||||
const ClientTrafficCell = memo(function ClientTrafficCell({
|
||||
up = 0,
|
||||
down = 0,
|
||||
total = 0,
|
||||
@@ -83,4 +87,6 @@ export default function ClientTrafficCell({
|
||||
</div>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export default ClientTrafficCell;
|
||||
|
||||
@@ -73,7 +73,9 @@ export interface ClientQueryParams {
|
||||
|
||||
const DEFAULT_QUERY: ClientQueryParams = { page: 1, pageSize: 25 };
|
||||
const DEFAULT_SUMMARY: ClientsSummary = {
|
||||
total: 0, active: 0, online: [], depleted: [], expiring: [], deactive: [],
|
||||
total: 0, active: 0,
|
||||
onlineCount: 0, depletedCount: 0, expiringCount: 0, deactiveCount: 0,
|
||||
online: [], depleted: [], expiring: [], deactive: [],
|
||||
};
|
||||
|
||||
export interface ClientSpeedEntry {
|
||||
@@ -114,7 +116,50 @@ export function computeClientsSummary(
|
||||
if (nearExpiry || nearLimit) expiring.push(email);
|
||||
else active += 1;
|
||||
}
|
||||
return { total: stats.length, active, online, depleted, expiring, deactive };
|
||||
return {
|
||||
total: stats.length,
|
||||
active,
|
||||
onlineCount: online.length,
|
||||
depletedCount: depleted.length,
|
||||
expiringCount: expiring.length,
|
||||
deactiveCount: deactive.length,
|
||||
online,
|
||||
depleted,
|
||||
expiring,
|
||||
deactive,
|
||||
};
|
||||
}
|
||||
|
||||
export function sameSpeedMap(
|
||||
a: Record<string, ClientSpeedEntry>,
|
||||
b: Record<string, ClientSpeedEntry>,
|
||||
): boolean {
|
||||
const aKeys = Object.keys(a);
|
||||
if (aKeys.length !== Object.keys(b).length) return false;
|
||||
for (const key of aKeys) {
|
||||
const left = a[key];
|
||||
const right = b[key];
|
||||
if (!right || left.up !== right.up || left.down !== right.down) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// The field list computeClientsSummary reads, and deliberately nothing else.
|
||||
// lastOnline in particular churns for every online client on every push and no
|
||||
// counter depends on it, so including it here would defeat the comparison.
|
||||
export function sameSummaryInputs(a: ClientStatRow[], b: ClientStatRow[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
const left = a[i];
|
||||
const right = b[i];
|
||||
if (left.email !== right.email
|
||||
|| left.up !== right.up
|
||||
|| left.down !== right.down
|
||||
|| left.total !== right.total
|
||||
|| left.enable !== right.enable
|
||||
|| left.expiryTime !== right.expiryTime) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function pickClientsSummary(
|
||||
@@ -174,17 +219,31 @@ async function fetchDefaults(): Promise<Record<string, unknown>> {
|
||||
return validated.obj || {};
|
||||
}
|
||||
|
||||
export function useClients() {
|
||||
export interface UseClientsOptions {
|
||||
// Callers that only need the mutations — the bulk modals, the groups page —
|
||||
// pass false. Mounting them used to start a second 5-second poll of the paged
|
||||
// list whose result they never read, which on a large panel means a full
|
||||
// summary aggregate every 5 seconds for nothing.
|
||||
list?: boolean;
|
||||
}
|
||||
|
||||
export function useClients(options: UseClientsOptions = {}) {
|
||||
const withList = options.list ?? true;
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [query, setQueryState] = useState<ClientQueryParams>(DEFAULT_QUERY);
|
||||
// Null until the page has settled on a query. The clients page cannot build
|
||||
// one until the persisted sort and the panel's configured page size are both
|
||||
// known, and fetching before then cost three sequential requests per load —
|
||||
// the first two thrown away (#trace).
|
||||
const [query, setQueryState] = useState<ClientQueryParams | null>(null);
|
||||
// setQuery shallow-compares so callers can pass a fresh object every render
|
||||
// (the common React pattern) without triggering a re-fetch when nothing
|
||||
// actually changed.
|
||||
const setQuery = useCallback((next: ClientQueryParams) => {
|
||||
setQueryState((prev) => {
|
||||
if (
|
||||
prev.page === next.page
|
||||
prev
|
||||
&& prev.page === next.page
|
||||
&& prev.pageSize === next.pageSize
|
||||
&& (prev.search ?? '') === (next.search ?? '')
|
||||
&& (prev.filter ?? '') === (next.filter ?? '')
|
||||
@@ -206,8 +265,9 @@ export function useClients() {
|
||||
}, []);
|
||||
|
||||
const listQuery = useQuery({
|
||||
queryKey: keys.clients.list(query),
|
||||
queryFn: () => fetchClientPage(query),
|
||||
queryKey: keys.clients.list(query ?? DEFAULT_QUERY),
|
||||
queryFn: () => fetchClientPage(query ?? DEFAULT_QUERY),
|
||||
enabled: withList && query !== null,
|
||||
staleTime: Infinity,
|
||||
// List is sorted/paged server-side, so the WS patch can't add new or
|
||||
// re-sort rows; poll the current page to keep it live (pauses when hidden).
|
||||
@@ -218,6 +278,7 @@ export function useClients() {
|
||||
const inboundOptionsQuery = useQuery({
|
||||
queryKey: keys.inbounds.options(),
|
||||
queryFn: fetchInboundOptions,
|
||||
enabled: withList,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
@@ -235,6 +296,7 @@ export function useClients() {
|
||||
const validated = parseMsg(msg, OnlinesSchema, 'clients/onlines');
|
||||
return Array.isArray(validated.obj) ? validated.obj : [];
|
||||
},
|
||||
enabled: withList,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
@@ -244,7 +306,11 @@ export function useClients() {
|
||||
const allGroups = listQuery.data?.groups ?? [];
|
||||
const fetched = listQuery.data !== undefined || listQuery.isError;
|
||||
const fetchError = listQuery.error ? (listQuery.error as Error).message : '';
|
||||
const loading = listQuery.isFetching;
|
||||
// isFetching is deliberately NOT read here. Touching it makes it a tracked
|
||||
// property, so the 5s refetchInterval notifies twice per cycle — two whole
|
||||
// page renders even when structural sharing leaves the data identical, and
|
||||
// each one bumps rc-table's immutable mark and re-runs every cell renderer.
|
||||
// Callers that want a spinner for an explicit refresh drive it locally.
|
||||
// Showing kept-previous data for a new key (filter/sort/page) — drives the
|
||||
// table overlay so the 5s background poll doesn't flash it.
|
||||
const transitioning = listQuery.isPlaceholderData;
|
||||
@@ -277,6 +343,11 @@ export function useClients() {
|
||||
const expireDiff = ((defaults.expireDiff as number) ?? 0) * 86400000;
|
||||
const trafficDiff = ((defaults.trafficDiff as number) ?? 0) * 1073741824;
|
||||
const pageSize = (defaults.pageSize as number) ?? 0;
|
||||
// pageSize 0 means "one long page", which is indistinguishable from "the
|
||||
// settings have not arrived yet" — so callers need this flag to know when the
|
||||
// configured page size is real. isFetched (not isSuccess) so a failed
|
||||
// settings request still lets the page fall back and render.
|
||||
const settingsReady = defaultsQuery.isFetched;
|
||||
|
||||
const [allClientStats, setAllClientStats] = useState<ClientStatRow[]>([]);
|
||||
const [clientSpeed, setClientSpeed] = useState<Record<string, ClientSpeedEntry>>({});
|
||||
@@ -565,15 +636,23 @@ export function useClients() {
|
||||
queryClient.setQueryData(keys.clients.onlines(), p.onlineClients);
|
||||
}
|
||||
if (Array.isArray(p.clientTraffics)) {
|
||||
// Xray reports a row per client whether or not it moved a byte, so most of
|
||||
// this map used to be zeros. A missing entry and a zero entry render
|
||||
// identically (isActiveSpeed treats both as inactive), so the zeros are
|
||||
// dropped and an unchanged result returns the previous object — which lets
|
||||
// React bail out of the update instead of re-rendering the table.
|
||||
const next: Record<string, ClientSpeedEntry> = {};
|
||||
for (const ct of p.clientTraffics) {
|
||||
if (!ct || !ct.email) continue;
|
||||
const up = ct.up || 0;
|
||||
const down = ct.down || 0;
|
||||
if (up === 0 && down === 0) continue;
|
||||
next[ct.email] = {
|
||||
up: (ct.up || 0) / TRAFFIC_POLL_INTERVAL_S,
|
||||
down: (ct.down || 0) / TRAFFIC_POLL_INTERVAL_S,
|
||||
up: up / TRAFFIC_POLL_INTERVAL_S,
|
||||
down: down / TRAFFIC_POLL_INTERVAL_S,
|
||||
};
|
||||
}
|
||||
setClientSpeed(next);
|
||||
setClientSpeed((prev) => (sameSpeedMap(prev, next) ? prev : next));
|
||||
}
|
||||
}, [queryClient]);
|
||||
|
||||
@@ -581,12 +660,17 @@ export function useClients() {
|
||||
if (!payload || typeof payload !== 'object') return;
|
||||
const p = payload as { clients?: ClientStatRow[]; snapshot?: boolean };
|
||||
if (!Array.isArray(p.clients) || p.clients.length === 0) return;
|
||||
if (p.snapshot !== false) setAllClientStats(p.clients);
|
||||
if (p.snapshot !== false) {
|
||||
const rows = p.clients;
|
||||
setAllClientStats((prev) => (sameSummaryInputs(prev, rows) ? prev : rows));
|
||||
}
|
||||
const active = queryRef.current;
|
||||
if (!active) return;
|
||||
const byEmail = new Map<string, ClientTraffic>();
|
||||
for (const row of p.clients) {
|
||||
if (row && row.email) byEmail.set(row.email, row);
|
||||
}
|
||||
queryClient.setQueryData<ClientPageResponse>(keys.clients.list(queryRef.current), (prev) => {
|
||||
queryClient.setQueryData<ClientPageResponse>(keys.clients.list(active), (prev) => {
|
||||
if (!prev) return prev;
|
||||
let touched = false;
|
||||
const next = prev.items.slice();
|
||||
@@ -624,7 +708,6 @@ export function useClients() {
|
||||
setQuery,
|
||||
inbounds,
|
||||
onlines,
|
||||
loading,
|
||||
transitioning,
|
||||
fetched,
|
||||
fetchError,
|
||||
@@ -634,6 +717,7 @@ export function useClients() {
|
||||
expireDiff,
|
||||
trafficDiff,
|
||||
pageSize,
|
||||
settingsReady,
|
||||
refresh,
|
||||
create,
|
||||
bulkCreate,
|
||||
|
||||
@@ -92,9 +92,24 @@ const LIGHT_BUTTON_TOKENS = {
|
||||
colorPrimaryActive: '#073ea8',
|
||||
};
|
||||
|
||||
// hashed:false drops the `:where(.css-<hash>)` wrapper antd puts around every
|
||||
// rule. It costs nothing in specificity — `:where()` contributes zero, so the
|
||||
// panel's own `.ant-*` overrides still win — and it removes roughly 5,700
|
||||
// wrappers, 16% of the generated stylesheet, from what the browser has to parse.
|
||||
//
|
||||
// cssVar.key pins the CSS-variable scope. Every panel page mounts its own
|
||||
// ConfigProvider (there is no root one), and without a fixed key each mints a
|
||||
// fresh useId-derived scope, so navigating re-serialises and re-injects the whole
|
||||
// token block under a new class instead of reusing the one already in the head.
|
||||
const SHARED_STYLE_CONFIG = {
|
||||
hashed: false,
|
||||
cssVar: { key: 'xui' },
|
||||
} as const;
|
||||
|
||||
export function buildAntdThemeConfig(isDark: boolean, isUltra: boolean): ThemeConfig {
|
||||
if (!isDark) {
|
||||
return {
|
||||
...SHARED_STYLE_CONFIG,
|
||||
algorithm: antdTheme.defaultAlgorithm,
|
||||
token: LIGHT_CONTRAST_TOKENS,
|
||||
components: {
|
||||
@@ -104,6 +119,7 @@ export function buildAntdThemeConfig(isDark: boolean, isUltra: boolean): ThemeCo
|
||||
};
|
||||
}
|
||||
return {
|
||||
...SHARED_STYLE_CONFIG,
|
||||
algorithm: antdTheme.darkAlgorithm,
|
||||
token: isUltra ? ULTRA_DARK_TOKENS : DARK_TOKENS,
|
||||
components: {
|
||||
|
||||
@@ -564,7 +564,7 @@ export const sections: readonly Section[] = [
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/list/paged',
|
||||
summary: 'Filter, sort, and paginate clients on the server. Each item is a slim row (no uuid/password/auth/flow/security/reverse/tgId) so the clients page can ship 25-ish rows in a few KB instead of the full table. The response also includes a summary computed across the full DB row set so dashboard counters stay stable as the user paginates or filters. Page size capped at 200; fetch /get/:email to obtain the full per-client payload for an edit/info modal.',
|
||||
summary: 'Filter, sort, and paginate clients on the server. Each item is a slim row (no uuid/password/auth/flow/security/reverse/tgId) so the clients page can ship 25-ish rows in a few KB instead of the full table. The response also includes a summary computed across the full DB row set so dashboard counters stay stable as the user paginates or filters: the *Count fields are exact, while the email arrays beside them stop at 200 entries so the payload does not grow with the panel. Page size capped at 200; fetch /get/:email to obtain the full per-client payload for an edit/info modal.',
|
||||
params: [
|
||||
{ name: 'page', in: 'query', type: 'number', desc: '1-indexed page number. Defaults to 1.' },
|
||||
{ name: 'pageSize', in: 'query', type: 'number', desc: 'Rows per page. Defaults to 25, capped at 200.' },
|
||||
@@ -575,7 +575,7 @@ export const sections: readonly Section[] = [
|
||||
{ name: 'order', in: 'query', type: 'string', desc: 'ascend or descend.' },
|
||||
],
|
||||
response:
|
||||
'{\n "success": true,\n "obj": {\n "items": [\n {\n "email": "alice@example.com",\n "subId": "abcd1234",\n "enable": true,\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "limitIp": 0,\n "reset": 0,\n "inboundIds": [3, 5],\n "traffic": { "up": 1024, "down": 4096, "enable": true },\n "createdAt": 1735000000000,\n "updatedAt": 1735100000000\n }\n ],\n "total": 2000,\n "filtered": 47,\n "page": 1,\n "pageSize": 25,\n "summary": {\n "total": 2000,\n "active": 1850,\n "online": ["alice@example.com"],\n "depleted": [],\n "expiring": [],\n "deactive": []\n }\n }\n}',
|
||||
'{\n "success": true,\n "obj": {\n "items": [\n {\n "email": "alice@example.com",\n "subId": "abcd1234",\n "enable": true,\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "limitIp": 0,\n "reset": 0,\n "inboundIds": [3, 5],\n "traffic": { "up": 1024, "down": 4096, "enable": true },\n "createdAt": 1735000000000,\n "updatedAt": 1735100000000\n }\n ],\n "total": 2000,\n "filtered": 47,\n "page": 1,\n "pageSize": 25,\n "summary": {\n "total": 2000,\n "active": 1850,\n "onlineCount": 1,\n "depletedCount": 0,\n "expiringCount": 0,\n "deactiveCount": 150,\n "online": ["alice@example.com"],\n "depleted": [],\n "expiring": [],\n "deactive": ["bob@example.com"]\n }\n }\n}',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
|
||||
@@ -56,7 +56,7 @@ export default function ClientBulkAddModal({
|
||||
}: ClientBulkAddModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const { bulkCreate } = useClients();
|
||||
const { bulkCreate } = useClients({ list: false });
|
||||
|
||||
const methods = useForm<ClientBulkAddFormValues>({ defaultValues: EMPTY });
|
||||
const inboundIds = useWatch({ control: methods.control, name: 'inboundIds' });
|
||||
|
||||
@@ -16,6 +16,13 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.client-email-more {
|
||||
margin-top: 4px;
|
||||
padding-top: 4px;
|
||||
border-top: 1px solid var(--ant-color-border-secondary, rgba(128, 128, 128, 0.2));
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.filter-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { lazy, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Badge,
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
Result,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Statistic,
|
||||
Switch,
|
||||
@@ -80,12 +79,14 @@ const BulkAttachInboundsModal = lazy(() => import('./BulkAttachInboundsModal'));
|
||||
const BulkDetachInboundsModal = lazy(() => import('./BulkDetachInboundsModal'));
|
||||
const TextModal = lazy(() => import('@/components/feedback/TextModal'));
|
||||
const PromptModal = lazy(() => import('@/components/feedback/PromptModal'));
|
||||
import { ClientInboundChips, ClientRowActions } from './RowCells';
|
||||
import { emptyFilters, activeFilterCount } from './filters';
|
||||
import type { ClientFilters } from './filters';
|
||||
import './ClientsPage.css';
|
||||
|
||||
const FILTER_STATE_KEY = 'clientsFilterState';
|
||||
const DISABLED_PAGE_SIZE = 200;
|
||||
const DEFAULT_TABLE_PAGE_SIZE = 25;
|
||||
|
||||
function UngroupIcon() {
|
||||
return (
|
||||
@@ -126,12 +127,29 @@ function UngroupIcon() {
|
||||
);
|
||||
}
|
||||
|
||||
// The server sends exact counters but caps the email arrays behind them, so a
|
||||
// panel with thousands of depleted clients neither ships nor renders them all.
|
||||
// The trailing chip reports what the popover left out.
|
||||
function ClientEmailList({ emails, total }: { emails: string[]; total: number }) {
|
||||
const hidden = total - emails.length;
|
||||
return (
|
||||
<div className="client-email-list">
|
||||
{emails.map((e) => <div key={e}>{e}</div>)}
|
||||
{hidden > 0 && <div className="client-email-more">+{hidden}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Bucket = 'active' | 'deactive' | 'depleted' | 'expiring';
|
||||
|
||||
interface PersistedFilterState {
|
||||
searchKey: string;
|
||||
filters: ClientFilters;
|
||||
sort: string;
|
||||
// The page size resolved on the previous visit. Without it the first list
|
||||
// request has to wait for /setting/defaultSettings just to learn how many rows
|
||||
// to ask for, which serialises two round trips on every load.
|
||||
pageSize: number | null;
|
||||
}
|
||||
|
||||
const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
|
||||
@@ -147,6 +165,9 @@ const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
|
||||
tunnel: 'orange',
|
||||
};
|
||||
const INBOUND_CHIP_LIMIT = 1;
|
||||
// A shared empty array keeps the memoised chip cell from seeing a fresh prop for
|
||||
// every unattached client on every render.
|
||||
const EMPTY_INBOUND_IDS: number[] = [];
|
||||
|
||||
function readFilterState(): PersistedFilterState {
|
||||
try {
|
||||
@@ -164,9 +185,10 @@ function readFilterState(): PersistedFilterState {
|
||||
groups: Array.isArray(fromRaw.groups) ? fromRaw.groups : [],
|
||||
},
|
||||
sort: typeof raw.sort === 'string' ? raw.sort : '',
|
||||
pageSize: typeof raw.pageSize === 'number' && raw.pageSize > 0 ? raw.pageSize : null,
|
||||
};
|
||||
} catch {
|
||||
return { searchKey: '', filters: emptyFilters(), sort: '' };
|
||||
return { searchKey: '', filters: emptyFilters(), sort: '', pageSize: null };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,8 +230,8 @@ export default function ClientsPage() {
|
||||
summary,
|
||||
allGroups,
|
||||
setQuery,
|
||||
inbounds, onlines, loading, transitioning, fetched, fetchError, subSettings,
|
||||
tgBotEnable, expireDiff, trafficDiff, pageSize,
|
||||
inbounds, onlines, transitioning, fetched, fetchError, subSettings,
|
||||
tgBotEnable, expireDiff, trafficDiff, pageSize, settingsReady,
|
||||
create, update, remove, bulkDelete, bulkAdjust, bulkEnable, bulkDisable, bulkAddToGroup, bulkRemoveFromGroup, attach, setExternalLinks, bulkAttach, detach, bulkDetach,
|
||||
resetTraffic, resetAllTraffics, delDepleted, delOrphans, exportClients, importClients, setEnable,
|
||||
clientSpeed,
|
||||
@@ -265,14 +287,31 @@ export default function ClientsPage() {
|
||||
const [sortColumn, setSortColumn] = useState<string | null>(initialSort.column);
|
||||
const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | null>(initialSort.order);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [tablePageSize, setTablePageSize] = useState(25);
|
||||
// Derived, not mirrored into state by an effect: an effect lags one render
|
||||
// behind the settings arriving, and that lag is what made the page fetch the
|
||||
// list once with the placeholder size and again with the real one.
|
||||
const [pageSizeChoice, setPageSizeChoice] = useState<number | null>(null);
|
||||
const settingsPageSize = settingsReady ? (pageSize > 0 ? pageSize : DISABLED_PAGE_SIZE) : null;
|
||||
// Last visit's resolved size stands in until the settings land, so the list
|
||||
// request goes out with the page mount instead of queueing behind them. If the
|
||||
// admin has since changed the setting the authoritative value replaces it and
|
||||
// costs one refetch — only on the load that follows the change. Null means
|
||||
// nothing is known yet, which is the one case worth waiting for.
|
||||
const resolvedPageSize = pageSizeChoice ?? settingsPageSize ?? initial.pageSize;
|
||||
const tablePageSize = resolvedPageSize ?? DEFAULT_TABLE_PAGE_SIZE;
|
||||
// debouncedSearch lags behind the input so we don't spam the server on every
|
||||
// keystroke; the search box still feels instant locally.
|
||||
const [debouncedSearch, setDebouncedSearch] = useState(searchKey);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(FILTER_STATE_KEY, JSON.stringify({ searchKey, filters, sort: sortValueFor(sortColumn, sortOrder) }));
|
||||
}, [searchKey, filters, sortColumn, sortOrder]);
|
||||
localStorage.setItem(FILTER_STATE_KEY, JSON.stringify({
|
||||
searchKey,
|
||||
filters,
|
||||
sort: sortValueFor(sortColumn, sortOrder),
|
||||
// Only ever persist a size we actually resolved, never the render fallback.
|
||||
pageSize: resolvedPageSize,
|
||||
}));
|
||||
}, [searchKey, filters, sortColumn, sortOrder, resolvedPageSize]);
|
||||
|
||||
useEffect(() => {
|
||||
const handle = window.setTimeout(() => setDebouncedSearch(searchKey), 300);
|
||||
@@ -303,6 +342,10 @@ export default function ClientsPage() {
|
||||
}, [filters.nodeIds, filters.inboundIds, inbounds]);
|
||||
|
||||
useEffect(() => {
|
||||
// With no remembered size and no settings yet, any query we build would be a
|
||||
// guess, and issuing it costs a full server round trip that is thrown away as
|
||||
// soon as the real size arrives.
|
||||
if (resolvedPageSize === null) return;
|
||||
setQuery({
|
||||
page: currentPage,
|
||||
pageSize: tablePageSize,
|
||||
@@ -321,13 +364,21 @@ export default function ClientsPage() {
|
||||
sort: sortColumn || undefined,
|
||||
order: sortOrder || undefined,
|
||||
});
|
||||
}, [setQuery, currentPage, tablePageSize, debouncedSearch, filters, effectiveInboundCsv, sortColumn, sortOrder]);
|
||||
}, [setQuery, resolvedPageSize, currentPage, tablePageSize, debouncedSearch, filters, effectiveInboundCsv, sortColumn, sortOrder]);
|
||||
|
||||
const activeCount = activeFilterCount(filters);
|
||||
|
||||
useEffect(() => {
|
||||
setTablePageSize(pageSize > 0 ? pageSize : DISABLED_PAGE_SIZE);
|
||||
}, [pageSize]);
|
||||
// Row handlers take an email and look the row up here at call time. Keying
|
||||
// them on the record object instead would defeat the memoised cells: every
|
||||
// traffic push replaces the row object of every client whose counters moved,
|
||||
// so the memo would miss on exactly the rows that are busy. Reading through
|
||||
// the ref also means a modal opened mid-poll shows current usage.
|
||||
const rowsByEmail = useRef(new Map<string, ClientRecord>());
|
||||
rowsByEmail.current = useMemo(() => {
|
||||
const map = new Map<string, ClientRecord>();
|
||||
for (const c of clients) map.set(c.email, c);
|
||||
return map;
|
||||
}, [clients]);
|
||||
|
||||
const onlineSet = useMemo(() => new Set(onlines || []), [onlines]);
|
||||
const inboundsById = useMemo(() => {
|
||||
@@ -454,7 +505,9 @@ export default function ClientsPage() {
|
||||
setFormOpen(true);
|
||||
}
|
||||
|
||||
async function onEdit(row: ClientRecord) {
|
||||
const onEdit = useCallback(async (email: string) => {
|
||||
const row = rowsByEmail.current.get(email);
|
||||
if (!row) return;
|
||||
setFormMode('edit');
|
||||
// Paged list omits per-client secrets to keep the row payload tiny;
|
||||
// edit needs them, so fetch the full record first.
|
||||
@@ -465,9 +518,11 @@ export default function ClientsPage() {
|
||||
setEditingAttachedIds([...ids]);
|
||||
setEditingExternalLinks(Array.isArray(full?.externalLinks) ? [...full.externalLinks] : []);
|
||||
setFormOpen(true);
|
||||
}
|
||||
}, [hydrate]);
|
||||
|
||||
function onDelete(row: ClientRecord) {
|
||||
const onDelete = useCallback((email: string) => {
|
||||
const row = rowsByEmail.current.get(email);
|
||||
if (!row) return;
|
||||
modal.confirm({
|
||||
title: t('pages.clients.deleteConfirmTitle', { email: row.email }),
|
||||
content: t('pages.clients.deleteConfirmContent'),
|
||||
@@ -479,9 +534,10 @@ export default function ClientsPage() {
|
||||
if (msg?.success) messageApi.success(t('pages.clients.toasts.deleted'));
|
||||
},
|
||||
});
|
||||
}
|
||||
}, [modal, t, remove, messageApi]);
|
||||
|
||||
function onResetTraffic(row: ClientRecord) {
|
||||
const onResetTraffic = useCallback((email: string) => {
|
||||
const row = rowsByEmail.current.get(email);
|
||||
if (!row?.email) {
|
||||
messageApi.warning(t('pages.clients.resetNotPossible'));
|
||||
return;
|
||||
@@ -496,19 +552,33 @@ export default function ClientsPage() {
|
||||
if (msg?.success) messageApi.success(t('pages.clients.toasts.trafficReset'));
|
||||
},
|
||||
});
|
||||
}
|
||||
}, [modal, t, resetTraffic, messageApi]);
|
||||
|
||||
async function onShowInfo(row: ClientRecord) {
|
||||
const onShowInfo = useCallback(async (email: string) => {
|
||||
const row = rowsByEmail.current.get(email);
|
||||
if (!row) return;
|
||||
const full = await hydrate(row.email);
|
||||
setInfoClient(full ? { ...row, ...full.client, inboundIds: full.inboundIds } : row);
|
||||
setInfoOpen(true);
|
||||
}
|
||||
}, [hydrate]);
|
||||
|
||||
async function onShowQr(row: ClientRecord) {
|
||||
const onShowQr = useCallback(async (email: string) => {
|
||||
const row = rowsByEmail.current.get(email);
|
||||
if (!row) return;
|
||||
const full = await hydrate(row.email);
|
||||
setQrClient(full ? { ...row, ...full.client, inboundIds: full.inboundIds } : row);
|
||||
setQrOpen(true);
|
||||
}
|
||||
}, [hydrate]);
|
||||
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const onRefreshClick = useCallback(async () => {
|
||||
setRefreshing(true);
|
||||
try {
|
||||
await refresh();
|
||||
} finally {
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, [refresh]);
|
||||
|
||||
const openText = useCallback((opts: { title: string; content: string; fileName?: string }) => {
|
||||
setTextTitle(opts.title);
|
||||
@@ -743,7 +813,7 @@ export default function ClientsPage() {
|
||||
|
||||
const onTableChange: NonNullable<TableProps<ClientRecord>['onChange']> = (pag) => {
|
||||
if (pag?.current) setCurrentPage(pag.current);
|
||||
if (pag?.pageSize) setTablePageSize(pag.pageSize);
|
||||
if (pag?.pageSize) setPageSizeChoice(pag.pageSize);
|
||||
};
|
||||
|
||||
const columns = useMemo<ColumnsType<ClientRecord>>(() => [
|
||||
@@ -752,23 +822,14 @@ export default function ClientsPage() {
|
||||
key: 'actions',
|
||||
width: 200,
|
||||
render: (_v, record) => (
|
||||
<Space size={4}>
|
||||
<Tooltip title={t('pages.clients.qrCode')}>
|
||||
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<QrcodeOutlined />} aria-label={t('pages.clients.qrCode')} onClick={() => onShowQr(record)} />
|
||||
</Tooltip>
|
||||
<Tooltip title={t('pages.clients.clientInfo')}>
|
||||
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<InfoCircleOutlined />} aria-label={t('pages.clients.clientInfo')} onClick={() => onShowInfo(record)} />
|
||||
</Tooltip>
|
||||
<Tooltip title={t('pages.inbounds.resetTraffic')}>
|
||||
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<RetweetOutlined />} aria-label={t('pages.inbounds.resetTraffic')} onClick={() => onResetTraffic(record)} />
|
||||
</Tooltip>
|
||||
<Tooltip title={t('edit')}>
|
||||
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<EditOutlined />} aria-label={t('edit')} onClick={() => onEdit(record)} />
|
||||
</Tooltip>
|
||||
<Tooltip title={t('delete')}>
|
||||
<Button size="small" type="text" danger style={{ fontSize: 16 }} icon={<DeleteOutlined />} aria-label={t('delete')} onClick={() => onDelete(record)} />
|
||||
</Tooltip>
|
||||
</Space>
|
||||
<ClientRowActions
|
||||
email={record.email}
|
||||
onShowQr={onShowQr}
|
||||
onShowInfo={onShowInfo}
|
||||
onResetTraffic={onResetTraffic}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -850,42 +911,13 @@ export default function ClientsPage() {
|
||||
key: 'inboundIds',
|
||||
width: 170,
|
||||
render: (_v, record) => {
|
||||
const ids = record.inboundIds || [];
|
||||
if (ids.length === 0) return <span style={{ color: 'rgba(0,0,0,0.45)' }}>—</span>;
|
||||
const visible = ids.slice(0, INBOUND_CHIP_LIMIT);
|
||||
const overflow = ids.slice(INBOUND_CHIP_LIMIT);
|
||||
const chip = (id: number, compact: boolean) => {
|
||||
const ib = inboundsById[id];
|
||||
const proto = (ib?.protocol || '').toLowerCase();
|
||||
const color = INBOUND_PROTOCOL_COLORS[proto] ?? 'default';
|
||||
const compactLabel = formatInboundLabel(ib?.tag, ib?.remark);
|
||||
return (
|
||||
<Tooltip key={id} title={inboundLabel(id)}>
|
||||
<Tag color={color} style={{ margin: 2 }}>
|
||||
{compact ? compactLabel : inboundLabel(id)}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
{visible.map((id) => chip(id, true))}
|
||||
{overflow.length > 0 && (
|
||||
<Popover
|
||||
trigger="click"
|
||||
placement="bottomRight"
|
||||
content={
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, maxWidth: 280, maxHeight: 280, overflowY: 'auto' }}>
|
||||
{overflow.map((id) => chip(id, false))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag color="default" style={{ margin: 2, cursor: 'pointer' }}>
|
||||
+{overflow.length}
|
||||
</Tag>
|
||||
</Popover>
|
||||
)}
|
||||
</>
|
||||
<ClientInboundChips
|
||||
ids={record.inboundIds || EMPTY_INBOUND_IDS}
|
||||
inboundsById={inboundsById}
|
||||
protocolColors={INBOUND_PROTOCOL_COLORS}
|
||||
chipLimit={INBOUND_CHIP_LIMIT}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -994,7 +1026,7 @@ export default function ClientsPage() {
|
||||
status="error"
|
||||
title={t('somethingWentWrong')}
|
||||
subTitle={fetchError}
|
||||
extra={<Button type="primary" loading={loading} onClick={refresh}>{t('refresh')}</Button>}
|
||||
extra={<Button type="primary" loading={refreshing} onClick={onRefreshClick}>{t('refresh')}</Button>}
|
||||
/>
|
||||
) : (
|
||||
<Row gutter={[isMobile ? 8 : 16, isMobile ? 8 : 12]}>
|
||||
@@ -1007,37 +1039,37 @@ export default function ClientsPage() {
|
||||
<Col xs={12} sm={8} md={4}>
|
||||
<Popover
|
||||
title={t('online')}
|
||||
open={summary.online.length ? undefined : false}
|
||||
content={<div className="client-email-list">{summary.online.map((e) => <div key={e}>{e}</div>)}</div>}
|
||||
open={summary.onlineCount ? undefined : false}
|
||||
content={<ClientEmailList emails={summary.online} total={summary.onlineCount} />}
|
||||
>
|
||||
<Statistic title={t('online')} value={String(summary.online.length)} prefix={<span className="dot dot-blue" />} />
|
||||
<Statistic title={t('online')} value={String(summary.onlineCount)} prefix={<span className="dot dot-blue" />} />
|
||||
</Popover>
|
||||
</Col>
|
||||
<Col xs={12} sm={8} md={4}>
|
||||
<Popover
|
||||
title={t('depleted')}
|
||||
open={summary.depleted.length ? undefined : false}
|
||||
content={<div className="client-email-list">{summary.depleted.map((e) => <div key={e}>{e}</div>)}</div>}
|
||||
open={summary.depletedCount ? undefined : false}
|
||||
content={<ClientEmailList emails={summary.depleted} total={summary.depletedCount} />}
|
||||
>
|
||||
<Statistic title={t('depleted')} value={String(summary.depleted.length)} prefix={<span className="dot dot-red" />} />
|
||||
<Statistic title={t('depleted')} value={String(summary.depletedCount)} prefix={<span className="dot dot-red" />} />
|
||||
</Popover>
|
||||
</Col>
|
||||
<Col xs={12} sm={8} md={4}>
|
||||
<Popover
|
||||
title={t('depletingSoon')}
|
||||
open={summary.expiring.length ? undefined : false}
|
||||
content={<div className="client-email-list">{summary.expiring.map((e) => <div key={e}>{e}</div>)}</div>}
|
||||
open={summary.expiringCount ? undefined : false}
|
||||
content={<ClientEmailList emails={summary.expiring} total={summary.expiringCount} />}
|
||||
>
|
||||
<Statistic title={t('depletingSoon')} value={String(summary.expiring.length)} prefix={<span className="dot dot-orange" />} />
|
||||
<Statistic title={t('depletingSoon')} value={String(summary.expiringCount)} prefix={<span className="dot dot-orange" />} />
|
||||
</Popover>
|
||||
</Col>
|
||||
<Col xs={12} sm={8} md={4}>
|
||||
<Popover
|
||||
title={t('disabled')}
|
||||
open={summary.deactive.length ? undefined : false}
|
||||
content={<div className="client-email-list">{summary.deactive.map((e) => <div key={e}>{e}</div>)}</div>}
|
||||
open={summary.deactiveCount ? undefined : false}
|
||||
content={<ClientEmailList emails={summary.deactive} total={summary.deactiveCount} />}
|
||||
>
|
||||
<Statistic title={t('disabled')} value={String(summary.deactive.length)} prefix={<span className="dot dot-gray" />} />
|
||||
<Statistic title={t('disabled')} value={String(summary.deactiveCount)} prefix={<span className="dot dot-gray" />} />
|
||||
</Popover>
|
||||
</Col>
|
||||
<Col xs={12} sm={8} md={4}>
|
||||
@@ -1364,7 +1396,7 @@ export default function ClientsPage() {
|
||||
showTotal={(n) => `${n}`}
|
||||
onChange={(p, s) => {
|
||||
setCurrentPage(p);
|
||||
if (s && s !== tablePageSize) setTablePageSize(s);
|
||||
if (s && s !== tablePageSize) setPageSizeChoice(s);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -1391,8 +1423,8 @@ export default function ClientsPage() {
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={t('pages.clients.clientInfo')}
|
||||
onClick={() => onShowInfo(row)}
|
||||
onKeyDown={activateOnKey(() => onShowInfo(row))}
|
||||
onClick={() => onShowInfo(row.email)}
|
||||
onKeyDown={activateOnKey(() => onShowInfo(row.email))}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Switch
|
||||
@@ -1409,23 +1441,23 @@ export default function ClientsPage() {
|
||||
{
|
||||
key: 'qr',
|
||||
label: <><QrcodeOutlined /> {t('pages.clients.qrCode')}</>,
|
||||
onClick: () => onShowQr(row),
|
||||
onClick: () => onShowQr(row.email),
|
||||
},
|
||||
{
|
||||
key: 'reset',
|
||||
label: <><RetweetOutlined /> {t('pages.inbounds.resetTraffic')}</>,
|
||||
onClick: () => onResetTraffic(row),
|
||||
onClick: () => onResetTraffic(row.email),
|
||||
},
|
||||
{
|
||||
key: 'edit',
|
||||
label: <><EditOutlined /> {t('edit')}</>,
|
||||
onClick: () => onEdit(row),
|
||||
onClick: () => onEdit(row.email),
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
danger: true,
|
||||
label: <><DeleteOutlined /> {t('delete')}</>,
|
||||
onClick: () => onDelete(row),
|
||||
onClick: () => onDelete(row.email),
|
||||
},
|
||||
],
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { memo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Popover, Space, Tag, Tooltip } from 'antd';
|
||||
import {
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
InfoCircleOutlined,
|
||||
QrcodeOutlined,
|
||||
RetweetOutlined,
|
||||
} from '@ant-design/icons';
|
||||
|
||||
import { formatInboundLabel } from '@/lib/inbounds/label';
|
||||
import type { InboundOption } from '@/hooks/useClients';
|
||||
|
||||
const ICON_BUTTON_STYLE = { fontSize: 16 } as const;
|
||||
|
||||
interface ClientRowActionsProps {
|
||||
email: string;
|
||||
onShowQr: (email: string) => void;
|
||||
onShowInfo: (email: string) => void;
|
||||
onResetTraffic: (email: string) => void;
|
||||
onEdit: (email: string) => void;
|
||||
onDelete: (email: string) => void;
|
||||
}
|
||||
|
||||
// Five Tooltip-wrapped buttons per row, none of which depend on traffic. Left
|
||||
// inline they re-ran rc-tooltip's alignment machinery for every visible row on
|
||||
// every traffic push — 125 Tooltips on a 25-row page, five seconds apart.
|
||||
// Keyed on the email rather than the row object, because a push replaces the row
|
||||
// object of every client whose counters moved; the page resolves the live row.
|
||||
export const ClientRowActions = memo(function ClientRowActions({
|
||||
email,
|
||||
onShowQr,
|
||||
onShowInfo,
|
||||
onResetTraffic,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: ClientRowActionsProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Space size={4}>
|
||||
<Tooltip title={t('pages.clients.qrCode')}>
|
||||
<Button
|
||||
size="small"
|
||||
type="text"
|
||||
style={ICON_BUTTON_STYLE}
|
||||
icon={<QrcodeOutlined />}
|
||||
aria-label={t('pages.clients.qrCode')}
|
||||
onClick={() => onShowQr(email)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={t('pages.clients.clientInfo')}>
|
||||
<Button
|
||||
size="small"
|
||||
type="text"
|
||||
style={ICON_BUTTON_STYLE}
|
||||
icon={<InfoCircleOutlined />}
|
||||
aria-label={t('pages.clients.clientInfo')}
|
||||
onClick={() => onShowInfo(email)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={t('pages.inbounds.resetTraffic')}>
|
||||
<Button
|
||||
size="small"
|
||||
type="text"
|
||||
style={ICON_BUTTON_STYLE}
|
||||
icon={<RetweetOutlined />}
|
||||
aria-label={t('pages.inbounds.resetTraffic')}
|
||||
onClick={() => onResetTraffic(email)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={t('edit')}>
|
||||
<Button
|
||||
size="small"
|
||||
type="text"
|
||||
style={ICON_BUTTON_STYLE}
|
||||
icon={<EditOutlined />}
|
||||
aria-label={t('edit')}
|
||||
onClick={() => onEdit(email)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={t('delete')}>
|
||||
<Button
|
||||
size="small"
|
||||
type="text"
|
||||
danger
|
||||
style={ICON_BUTTON_STYLE}
|
||||
icon={<DeleteOutlined />}
|
||||
aria-label={t('delete')}
|
||||
onClick={() => onDelete(email)}
|
||||
/>
|
||||
</Tooltip>
|
||||
</Space>
|
||||
);
|
||||
});
|
||||
|
||||
const CHIP_STYLE = { margin: 2 } as const;
|
||||
const OVERFLOW_CHIP_STYLE = { margin: 2, cursor: 'pointer' } as const;
|
||||
const OVERFLOW_LIST_STYLE = {
|
||||
display: 'flex',
|
||||
flexDirection: 'column' as const,
|
||||
gap: 4,
|
||||
maxWidth: 280,
|
||||
maxHeight: 280,
|
||||
overflowY: 'auto' as const,
|
||||
};
|
||||
|
||||
interface ClientInboundChipsProps {
|
||||
ids: number[];
|
||||
inboundsById: Record<number, InboundOption>;
|
||||
protocolColors: Record<string, string>;
|
||||
chipLimit: number;
|
||||
}
|
||||
|
||||
// Attachments never change on a traffic push either, so the same memoisation
|
||||
// applies: one Tooltip per visible chip plus a Popover for the overflow.
|
||||
export const ClientInboundChips = memo(function ClientInboundChips({
|
||||
ids,
|
||||
inboundsById,
|
||||
protocolColors,
|
||||
chipLimit,
|
||||
}: ClientInboundChipsProps) {
|
||||
if (ids.length === 0) return <span className="cell-empty">—</span>;
|
||||
|
||||
const label = (id: number) => {
|
||||
const ib = inboundsById[id];
|
||||
return formatInboundLabel(ib?.tag, ib?.remark);
|
||||
};
|
||||
const chip = (id: number) => {
|
||||
const proto = (inboundsById[id]?.protocol || '').toLowerCase();
|
||||
return (
|
||||
<Tooltip key={id} title={label(id)}>
|
||||
<Tag color={protocolColors[proto] ?? 'default'} style={CHIP_STYLE}>{label(id)}</Tag>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
|
||||
const visible = ids.slice(0, chipLimit);
|
||||
const overflow = ids.slice(chipLimit);
|
||||
return (
|
||||
<>
|
||||
{visible.map(chip)}
|
||||
{overflow.length > 0 && (
|
||||
<Popover
|
||||
trigger="click"
|
||||
placement="bottomRight"
|
||||
content={<div style={OVERFLOW_LIST_STYLE}>{overflow.map(chip)}</div>}
|
||||
>
|
||||
<Tag color="default" style={OVERFLOW_CHIP_STYLE}>+{overflow.length}</Tag>
|
||||
</Popover>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -93,7 +93,7 @@ export default function GroupsPage() {
|
||||
useEffect(() => { setMessageInstance(messageApi); }, [messageApi]);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { subSettings, bulkAdjust, bulkAddToGroup, bulkRemoveFromGroup, bulkDelete } = useClients();
|
||||
const { subSettings, bulkAdjust, bulkAddToGroup, bulkRemoveFromGroup, bulkDelete } = useClients({ list: false });
|
||||
|
||||
const groupsQuery = useQuery({
|
||||
queryKey: keys.clients.groups(),
|
||||
|
||||
@@ -68,9 +68,15 @@ export const InboundOptionSchema = z.object({
|
||||
|
||||
export const InboundOptionsSchema = z.array(InboundOptionSchema);
|
||||
|
||||
// The *Count fields are exact; the email arrays stop at the server's cap and
|
||||
// only feed the hover popovers, so never derive a counter from their length.
|
||||
export const ClientsSummarySchema = z.object({
|
||||
total: z.number(),
|
||||
active: z.number(),
|
||||
onlineCount: z.number().optional().default(0),
|
||||
depletedCount: z.number().optional().default(0),
|
||||
expiringCount: z.number().optional().default(0),
|
||||
deactiveCount: z.number().optional().default(0),
|
||||
online: nullableStringArray,
|
||||
depleted: nullableStringArray,
|
||||
expiring: nullableStringArray,
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { renderHook, waitFor, act } from '@testing-library/react';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useClients } from '@/hooks/useClients';
|
||||
import { makeTestQueryClient } from '@/test/test-utils';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const emptyPage = {
|
||||
items: [],
|
||||
total: 0,
|
||||
filtered: 0,
|
||||
page: 1,
|
||||
pageSize: 25,
|
||||
groups: [],
|
||||
summary: {
|
||||
total: 0,
|
||||
active: 0,
|
||||
onlineCount: 0,
|
||||
depletedCount: 0,
|
||||
expiringCount: 0,
|
||||
deactiveCount: 0,
|
||||
online: [],
|
||||
depleted: [],
|
||||
expiring: [],
|
||||
deactive: [],
|
||||
},
|
||||
};
|
||||
|
||||
function mockPanel(defaults: Record<string, unknown>) {
|
||||
const pagedUrls: string[] = [];
|
||||
vi.spyOn(HttpUtil, 'get').mockImplementation(async (url: string) => {
|
||||
if (url.includes('/clients/list/paged')) {
|
||||
pagedUrls.push(url);
|
||||
return new Msg(true, '', emptyPage);
|
||||
}
|
||||
if (url.includes('/inbounds/options')) return new Msg(true, '', []);
|
||||
return new Msg(true, '', null);
|
||||
});
|
||||
vi.spyOn(HttpUtil, 'post').mockImplementation(async (url: string) => {
|
||||
if (url.includes('/setting/defaultSettings')) return new Msg(true, '', defaults);
|
||||
if (url.includes('/clients/onlines')) return new Msg(true, '', []);
|
||||
return new Msg(true, '', null);
|
||||
});
|
||||
return pagedUrls;
|
||||
}
|
||||
|
||||
function wrapperFor() {
|
||||
const queryClient = makeTestQueryClient();
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('useClients query gating', () => {
|
||||
it('does not fetch the list until the page supplies a query', async () => {
|
||||
const pagedUrls = mockPanel({ pageSize: 25 });
|
||||
const { result } = renderHook(() => useClients(), { wrapper: wrapperFor() });
|
||||
|
||||
await waitFor(() => expect(result.current.settingsReady).toBe(true));
|
||||
// The page has not called setQuery yet, so nothing should have gone out —
|
||||
// this is what used to cost a thrown-away round trip on every page load.
|
||||
expect(pagedUrls).toEqual([]);
|
||||
expect(result.current.fetched).toBe(false);
|
||||
});
|
||||
|
||||
it('issues exactly one request for a page load that settles on one query', async () => {
|
||||
const pagedUrls = mockPanel({ pageSize: 50 });
|
||||
const { result } = renderHook(() => useClients(), { wrapper: wrapperFor() });
|
||||
|
||||
await waitFor(() => expect(result.current.settingsReady).toBe(true));
|
||||
act(() => {
|
||||
result.current.setQuery({ page: 1, pageSize: 50, sort: 'createdAt', order: 'ascend' });
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.fetched).toBe(true));
|
||||
expect(pagedUrls).toHaveLength(1);
|
||||
expect(pagedUrls[0]).toContain('pageSize=50');
|
||||
expect(pagedUrls[0]).toContain('sort=createdAt');
|
||||
});
|
||||
|
||||
it('fetches as soon as a query arrives, without waiting for the settings', async () => {
|
||||
// The page remembers the previous visit's page size in localStorage, so on a
|
||||
// return visit it can supply a query on the first render. The hook must not
|
||||
// hold that back behind /setting/defaultSettings, or the two round trips
|
||||
// serialise and the list lands ~160ms later than it needs to.
|
||||
const pagedUrls = mockPanel({ pageSize: 25 });
|
||||
const { result } = renderHook(() => useClients(), { wrapper: wrapperFor() });
|
||||
|
||||
act(() => {
|
||||
result.current.setQuery({ page: 1, pageSize: 25, sort: 'createdAt', order: 'ascend' });
|
||||
});
|
||||
await waitFor(() => expect(pagedUrls).toHaveLength(1));
|
||||
});
|
||||
|
||||
it('reports settingsReady even when the settings request fails, so the page can still render', async () => {
|
||||
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', emptyPage));
|
||||
vi.spyOn(HttpUtil, 'post').mockResolvedValue(new Msg(false, 'boom', null));
|
||||
const { result } = renderHook(() => useClients(), { wrapper: wrapperFor() });
|
||||
|
||||
await waitFor(() => expect(result.current.settingsReady).toBe(true));
|
||||
});
|
||||
|
||||
it('skips the list, options and onlines queries for mutation-only callers', async () => {
|
||||
const pagedUrls = mockPanel({ pageSize: 25 });
|
||||
const postSpy = vi.mocked(HttpUtil.post);
|
||||
const { result } = renderHook(() => useClients({ list: false }), { wrapper: wrapperFor() });
|
||||
|
||||
await waitFor(() => expect(result.current.settingsReady).toBe(true));
|
||||
act(() => {
|
||||
result.current.setQuery({ page: 1, pageSize: 25, sort: 'createdAt', order: 'ascend' });
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.settingsReady).toBe(true));
|
||||
expect(pagedUrls).toEqual([]);
|
||||
// subSettings still needs defaultSettings; onlines must not be polled.
|
||||
const posted = postSpy.mock.calls.map((c) => String(c[0]));
|
||||
expect(posted.some((u) => u.includes('/setting/defaultSettings'))).toBe(true);
|
||||
expect(posted.some((u) => u.includes('/clients/onlines'))).toBe(false);
|
||||
expect(vi.mocked(HttpUtil.get).mock.calls.map((c) => String(c[0]))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { useState } from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { ClientInboundChips, ClientRowActions } from '@/pages/clients/RowCells';
|
||||
import type { InboundOption } from '@/hooks/useClients';
|
||||
|
||||
const PROTOCOL_COLORS = { vless: 'blue', trojan: 'volcano' };
|
||||
|
||||
// Counts how often the cell reads the inbound map, which happens once per chip
|
||||
// per render. A traffic push re-renders the row, so if the cell is not memoised
|
||||
// this climbs every five seconds for every visible row.
|
||||
function countingInboundMap(source: Record<number, InboundOption>) {
|
||||
const reads = { count: 0 };
|
||||
const proxy = new Proxy(source, {
|
||||
get(target, key) {
|
||||
if (typeof key === 'string' && /^\d+$/.test(key)) reads.count += 1;
|
||||
return target[key as unknown as number];
|
||||
},
|
||||
});
|
||||
return { proxy, reads };
|
||||
}
|
||||
|
||||
const INBOUNDS: Record<number, InboundOption> = {
|
||||
1: { id: 1, tag: 'in-vless', remark: 'DE', protocol: 'vless' },
|
||||
2: { id: 2, tag: 'in-trojan', remark: 'NL', protocol: 'trojan' },
|
||||
};
|
||||
|
||||
function Harness({ children }: { children: (bump: () => void) => React.ReactNode }) {
|
||||
const [, setTick] = useState(0);
|
||||
return <>{children(() => setTick((n) => n + 1))}</>;
|
||||
}
|
||||
|
||||
describe('clients table row cells', () => {
|
||||
it('does not re-render the inbound chips when the row re-renders with the same attachments', async () => {
|
||||
const { proxy, reads } = countingInboundMap(INBOUNDS);
|
||||
const ids = [1, 2];
|
||||
let bump: () => void = () => {};
|
||||
|
||||
render(
|
||||
<Harness>
|
||||
{(doBump) => {
|
||||
bump = doBump;
|
||||
return (
|
||||
<ClientInboundChips ids={ids} inboundsById={proxy} protocolColors={PROTOCOL_COLORS} chipLimit={1} />
|
||||
);
|
||||
}}
|
||||
</Harness>,
|
||||
);
|
||||
|
||||
const afterFirstRender = reads.count;
|
||||
expect(afterFirstRender).toBeGreaterThan(0);
|
||||
|
||||
// Three simulated traffic pushes: the parent re-renders, the props do not change.
|
||||
for (let i = 0; i < 3; i++) bump();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(reads.count).toBe(afterFirstRender);
|
||||
});
|
||||
|
||||
it('re-renders the chips when the attachments actually change', async () => {
|
||||
const { proxy, reads } = countingInboundMap(INBOUNDS);
|
||||
|
||||
function Swapper() {
|
||||
const [ids, setIds] = useState<number[]>([1]);
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setIds([1, 2])}>swap</button>
|
||||
<ClientInboundChips ids={ids} inboundsById={proxy} protocolColors={PROTOCOL_COLORS} chipLimit={1} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
render(<Swapper />);
|
||||
const before = reads.count;
|
||||
await userEvent.click(screen.getByRole('button', { name: 'swap' }));
|
||||
expect(reads.count).toBeGreaterThan(before);
|
||||
});
|
||||
|
||||
it('keeps the row actions wired to the right client across re-renders', async () => {
|
||||
const onShowQr = vi.fn();
|
||||
const onEdit = vi.fn();
|
||||
const noop = vi.fn();
|
||||
let bump: () => void = () => {};
|
||||
|
||||
render(
|
||||
<Harness>
|
||||
{(doBump) => {
|
||||
bump = doBump;
|
||||
return (
|
||||
<ClientRowActions
|
||||
email="alice@x"
|
||||
onShowQr={onShowQr}
|
||||
onShowInfo={noop}
|
||||
onResetTraffic={noop}
|
||||
onEdit={onEdit}
|
||||
onDelete={noop}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</Harness>,
|
||||
);
|
||||
|
||||
for (let i = 0; i < 3; i++) bump();
|
||||
|
||||
// Queried by position rather than label: the suite loads the real en-US
|
||||
// bundle, so the aria-labels are translated strings, not keys. Order is
|
||||
// QR, info, reset traffic, edit, delete.
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons).toHaveLength(5);
|
||||
await userEvent.click(buttons[0]);
|
||||
await userEvent.click(buttons[3]);
|
||||
|
||||
expect(onShowQr).toHaveBeenCalledExactlyOnceWith('alice@x');
|
||||
expect(onEdit).toHaveBeenCalledExactlyOnceWith('alice@x');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
import { computeClientsSummary, pickClientsSummary } from '@/hooks/useClients';
|
||||
import { computeClientsSummary, pickClientsSummary, sameSpeedMap, sameSummaryInputs } from '@/hooks/useClients';
|
||||
import type { ClientTraffic, ClientsSummary } from '@/schemas/client';
|
||||
|
||||
// Parity with web/service/client.go buildClientsSummary: the same client must
|
||||
@@ -42,6 +42,24 @@ describe('computeClientsSummary', () => {
|
||||
expect(s.active).toBe(2); // online@x + offline@x
|
||||
});
|
||||
|
||||
it('reports a counter alongside every bucket list', () => {
|
||||
const stats: Row[] = [
|
||||
row({ email: 'online@x', enable: true }),
|
||||
row({ email: 'disabled@x', enable: false }),
|
||||
row({ email: 'exhausted@x', enable: true, total: 1 * GB, up: 1 * GB }),
|
||||
row({ email: 'nearlimit@x', enable: true, total: 10 * GB, up: 9.9 * GB }),
|
||||
];
|
||||
const s = computeClientsSummary(stats, new Set(['online@x']), 3 * DAY, 1 * GB);
|
||||
|
||||
// The server caps its lists but never its counters; the live recompute has
|
||||
// both, so the summary card reads the same either way.
|
||||
expect(s.onlineCount).toBe(s.online.length);
|
||||
expect(s.depletedCount).toBe(s.depleted.length);
|
||||
expect(s.expiringCount).toBe(s.expiring.length);
|
||||
expect(s.deactiveCount).toBe(s.deactive.length);
|
||||
expect(s.active + s.depletedCount + s.expiringCount + s.deactiveCount).toBe(s.total);
|
||||
});
|
||||
|
||||
it('depleted wins over disabled and over online', () => {
|
||||
const stats: Row[] = [
|
||||
row({ email: 'a@x', enable: false, total: 1 * GB, up: 2 * GB }),
|
||||
@@ -63,7 +81,9 @@ describe('computeClientsSummary', () => {
|
||||
|
||||
describe('pickClientsSummary', () => {
|
||||
const serverSummary: ClientsSummary = {
|
||||
total: 67, active: 58, online: [], depleted: [], expiring: [], deactive: [],
|
||||
total: 67, active: 58,
|
||||
onlineCount: 0, depletedCount: 4, expiringCount: 3, deactiveCount: 2,
|
||||
online: [], depleted: [], expiring: [], deactive: [],
|
||||
};
|
||||
|
||||
it('keeps the server summary when the snapshot is short of the server total (#6102)', () => {
|
||||
@@ -84,3 +104,39 @@ describe('pickClientsSummary', () => {
|
||||
expect(s).toEqual(serverSummary);
|
||||
});
|
||||
});
|
||||
|
||||
describe('websocket payload identity preservation', () => {
|
||||
const speed = (up: number, down: number) => ({ up, down });
|
||||
|
||||
it('treats an unchanged speed map as unchanged', () => {
|
||||
const a = { 'a@x': speed(1, 2), 'b@x': speed(3, 4) };
|
||||
expect(sameSpeedMap(a, { 'a@x': speed(1, 2), 'b@x': speed(3, 4) })).toBe(true);
|
||||
expect(sameSpeedMap(a, { 'a@x': speed(1, 2) })).toBe(false);
|
||||
expect(sameSpeedMap(a, { 'a@x': speed(1, 2), 'b@x': speed(3, 5) })).toBe(false);
|
||||
expect(sameSpeedMap(a, { 'a@x': speed(1, 2), 'c@x': speed(3, 4) })).toBe(false);
|
||||
expect(sameSpeedMap({}, {})).toBe(true);
|
||||
});
|
||||
|
||||
it('compares exactly the fields the summary reads, and ignores lastOnline', () => {
|
||||
const base: Row[] = [row({ email: 'a@x', up: 1, down: 2, total: 10, expiryTime: 99 })];
|
||||
|
||||
// lastOnline moves for every online client on every push and no counter
|
||||
// depends on it, so it must not force a new snapshot.
|
||||
const onlyLastOnlineMoved: Row[] = [
|
||||
row({ email: 'a@x', up: 1, down: 2, total: 10, expiryTime: 99, lastOnline: 12345 }),
|
||||
];
|
||||
expect(sameSummaryInputs(base, onlyLastOnlineMoved)).toBe(true);
|
||||
|
||||
for (const changed of [
|
||||
row({ email: 'b@x', up: 1, down: 2, total: 10, expiryTime: 99 }),
|
||||
row({ email: 'a@x', up: 2, down: 2, total: 10, expiryTime: 99 }),
|
||||
row({ email: 'a@x', up: 1, down: 3, total: 10, expiryTime: 99 }),
|
||||
row({ email: 'a@x', up: 1, down: 2, total: 11, expiryTime: 99 }),
|
||||
row({ email: 'a@x', up: 1, down: 2, total: 10, expiryTime: 100 }),
|
||||
row({ email: 'a@x', up: 1, down: 2, total: 10, expiryTime: 99, enable: false }),
|
||||
]) {
|
||||
expect(sameSummaryInputs(base, [changed])).toBe(false);
|
||||
}
|
||||
expect(sameSummaryInputs(base, [])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user