A modern and elegant dashboard for network traffic visualization and analysis.
refactor: Migrate data fetching to `@tanstack/react-query` for improved state management and caching across stats components.
luoleic66773713c23
diff --git a/apps/web/app/[locale]/layout.tsx b/apps/web/app/[locale]/layout.tsxindex 587440c..78e8f3d 100644--- a/apps/web/app/[locale]/layout.tsx+++ b/apps/web/app/[locale]/layout.tsx@@ -2,6 +2,7 @@ import type { Metadata, Viewport } from "next";import { Geist, Geist_Mono } from "next/font/google";import "../globals.css";import { ThemeProvider } from "@/components/providers/theme-provider";+import { QueryProvider } from "@/components/providers/query-provider";import { NextIntlClientProvider } from "next-intl";import { getMessages } from "next-intl/server";import { notFound } from "next/navigation";@@ -75,9 +76,11 @@ export default async function RootLayout({<bodyclassName={`${geistSans.variable} ${geistMono.variable} antialiased`}><ThemeProvider attribute="class" defaultTheme="dark" enableSystem>- <NextIntlClientProvider messages={messages}>- {children}- </NextIntlClientProvider>+ <QueryProvider>+ <NextIntlClientProvider messages={messages}>+ {children}+ </NextIntlClientProvider>+ </QueryProvider></ThemeProvider><ServiceWorkerRegister /><Toaster position="top-center" />diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsxindex 760613f..faa195b 100644--- a/apps/web/app/[locale]/page.tsx+++ b/apps/web/app/[locale]/page.tsx@@ -1,8 +1,9 @@"use client";-import { useEffect, useState, useCallback, useRef, memo, useMemo } from "react";+import { useEffect, useState, useCallback, memo, useMemo } from "react";import { useTranslations, useLocale } from "next-intl";import { useTheme } from "next-themes";+import { keepPreviousData, useIsFetching, useQuery, useQueryClient } from "@tanstack/react-query";import {Globe,MapPin,@@ -68,8 +69,12 @@ import {api,getPresetTimeRange,type TimeRange,- type Backend,} from "@/lib/api";+import {+ getCountriesQueryKey,+ getDevicesQueryKey,+ getSummaryQueryKey,+} from "@/lib/stats-query-keys";import { cn } from "@/lib/utils";import type { StatsSummary, CountryStats, DeviceStats } from "@clashmaster/shared";@@ -193,12 +198,10 @@ const CountriesContent = memo(function CountriesContent({});const ProxiesContent = memo(function ProxiesContent({- data,activeBackendId,timeRange,backendStatus,}: {- data: StatsSummary | null;activeBackendId?: number;timeRange: TimeRange;backendStatus: BackendStatus;@@ -206,7 +209,6 @@ const ProxiesContent = memo(function ProxiesContent({return (<div className="space-y-6"><InteractiveProxyStats- data={data?.proxyStats || []}activeBackendId={activeBackendId}timeRange={timeRange}backendStatus={backendStatus}@@ -216,12 +218,10 @@ const ProxiesContent = memo(function ProxiesContent({});const RulesContent = memo(function RulesContent({- data,activeBackendId,timeRange,backendStatus,}: {- data: StatsSummary | null;activeBackendId?: number;timeRange: TimeRange;backendStatus: BackendStatus;@@ -229,7 +229,6 @@ const RulesContent = memo(function RulesContent({return (<div className="space-y-6"><InteractiveRuleStats- data={data?.ruleStats || []}activeBackendId={activeBackendId}timeRange={timeRange}backendStatus={backendStatus}@@ -247,44 +246,20 @@ const DevicesContent = memo(function DevicesContent({timeRange: TimeRange;backendStatus: BackendStatus;}) {- const [deviceStats, setDeviceStats] = useState<DeviceStats[]>([]);- const [loading, setLoading] = useState(true);- const requestIdRef = useRef(0);- const hasLoadedRef = useRef(false);-- useEffect(() => {- let cancelled = false;+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);- const fetchDevices = async () => {- const requestId = ++requestIdRef.current;- const shouldShowLoading = !hasLoadedRef.current;- if (shouldShowLoading) {- setLoading(true);- }-- try {- const data = await api.getDevices(activeBackendId, 50, timeRange);- if (cancelled || requestId !== requestIdRef.current) return;- setDeviceStats(data);- hasLoadedRef.current = true;- } catch (err) {- if (cancelled || requestId !== requestIdRef.current) return;- console.error("Failed to fetch device stats:", err);- if (!hasLoadedRef.current) {- setDeviceStats([]);- }- } finally {- if (shouldShowLoading && !cancelled) {- setLoading(false);- }- }- };+ const devicesQuery = useQuery({+ queryKey: getDevicesQueryKey(activeBackendId, 50, stableTimeRange),+ queryFn: () => api.getDevices(activeBackendId, 50, stableTimeRange),+ enabled: !!activeBackendId,+ placeholderData: keepPreviousData,+ });- fetchDevices();- return () => {- cancelled = true;- };- }, [activeBackendId, timeRange]);+ const deviceStats: DeviceStats[] = devicesQuery.data ?? [];+ const loading = devicesQuery.isLoading && !devicesQuery.data;if (loading) {return (@@ -326,151 +301,118 @@ export default function DashboardPage() {const pathname = usePathname();const locale = useLocale();const { theme, setTheme } = useTheme();+ const queryClient = useQueryClient();const [activeTab, setActiveTab] = useState("overview");- const [data, setData] = useState<StatsSummary | null>(null);- const [countryData, setCountryData] = useState<CountryStats[]>([]);- const [error, setError] = useState<string | null>(null);const [timeRange, setTimeRange] = useState<TimeRange>(getPresetTimeRange("24h"));const [timePreset, setTimePreset] = useState<TimePreset>("24h");- const [lastUpdated, setLastUpdated] = useState<Date>(new Date());- const [isLoading, setIsLoading] = useState(false);+ const [isManualRefreshing, setIsManualRefreshing] = useState(false);const [autoRefresh, setAutoRefresh] = useState(true);const [showBackendDialog, setShowBackendDialog] = useState(false);const [isFirstTime, setIsFirstTime] = useState(false);const [showAboutDialog, setShowAboutDialog] = useState(false);- const [backends, setBackends] = useState<Backend[]>([]);- const [activeBackend, setActiveBackend] = useState<Backend | null>(null);- const [listeningBackends, setListeningBackends] = useState<Backend[]>([]);- const initialLoaded = useRef(false);- const lastSummaryRef = useRef<string>("");- const lastCountriesRef = useRef<string>("");++ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);++ const backendsQuery = useQuery({+ queryKey: ["backends"],+ queryFn: () => api.getBackends(),+ });++ const backends = backendsQuery.data ?? [];+ const activeBackend = useMemo(+ () => backends.find((backend) => backend.is_active) || backends[0] || null,+ [backends],+ );+ const listeningBackends = useMemo(+ () => backends.filter((backend) => backend.listening),+ [backends],+ );const activeBackendId = activeBackend?.id;+ const needsSummary = activeTab === "overview";+ const needsCountries = activeTab === "overview" || activeTab === "countries";++ const summaryQuery = useQuery({+ queryKey: getSummaryQueryKey(activeBackendId, stableTimeRange),+ queryFn: () => api.getSummary(activeBackendId, stableTimeRange),+ enabled: !!activeBackendId && needsSummary,+ placeholderData: keepPreviousData,+ });++ const countriesQuery = useQuery({+ queryKey: getCountriesQueryKey(activeBackendId, 50, stableTimeRange),+ queryFn: () => api.getCountries(activeBackendId, 50, stableTimeRange),+ enabled: !!activeBackendId && needsCountries,+ placeholderData: keepPreviousData,+ });++ const data: StatsSummary | null = summaryQuery.data ?? null;+ const countryData: CountryStats[] = countriesQuery.data ?? [];+ const statsFetchingCount = useIsFetching({ queryKey: ["stats"] });+ const isLoading = isManualRefreshing || statsFetchingCount > 0;++ const queryError = useMemo(() => {+ if (needsSummary && summaryQuery.error) {+ return summaryQuery.error instanceof Error+ ? summaryQuery.error.message+ : "Unknown error";+ }+ if (needsCountries && countriesQuery.error) {+ return countriesQuery.error instanceof Error+ ? countriesQuery.error.message+ : "Unknown error";+ }+ return null;+ }, [needsSummary, summaryQuery.error, needsCountries, countriesQuery.error]);+const backendStatus: BackendStatus = useMemo(() => {if (!activeBackend) return "unknown";- if (error) return "unhealthy";+ if (queryError) return "unhealthy";if (activeBackend.listening) return "healthy";return "unhealthy";- }, [activeBackend, error]);+ }, [activeBackend, queryError]);const backendStatusHint = useMemo(() => {- if (error) return error;+ if (queryError) return queryError;if (activeBackend && !activeBackend.listening) return dashboardT("backendUnavailableHint");return null;- }, [error, activeBackend, dashboardT]);+ }, [queryError, activeBackend, dashboardT]);- // Check if backend is configured- const checkBackend = useCallback(async () => {- try {- const backendsData = await api.getBackends();- setBackends(backendsData);-- if (backendsData.length === 0) {- setIsFirstTime(true);- setShowBackendDialog(true);- } else {- // Find active backend- const active = backendsData.find((b) => b.is_active) || backendsData[0];- setActiveBackend(active);-- // Find listening backends- const listening = backendsData.filter((b) => b.listening);- setListeningBackends(listening);+ const refreshNow = useCallback(+ async (showLoading = false) => {+ if (showLoading) {+ setIsManualRefreshing(true);}- } catch (err) {- console.error("Failed to check backends:", err);- }- }, []);-- // Load stats with deduplication- const loadStats = useCallback(- async (showLoading = false, rangeOverride?: TimeRange) => {- if (showLoading) setIsLoading(true);-try {- const queryRange = rangeOverride ?? timeRange;- let backendId = activeBackendId;- if (!backendId) {- const activeBackendData = await api.getActiveBackend();- if ("error" in activeBackendData) {- setData(null);- setCountryData([]);- setError(null);- lastSummaryRef.current = "";- lastCountriesRef.current = "";- return;- }- backendId = activeBackendData.id;- if (!activeBackend || activeBackend.id !== activeBackendData.id) {- setActiveBackend(activeBackendData);- }+ if (isRollingTimePreset(timePreset)) {+ setTimeRange(getPresetTimeRange(timePreset));}-- const needsSummary =- activeTab === "overview" || activeTab === "proxies" || activeTab === "rules";- const needsCountries = activeTab === "overview" || activeTab === "countries";-- const [stats, countries] = await Promise.all([- needsSummary ? api.getSummary(backendId, queryRange) : Promise.resolve(null),- needsCountries ? api.getCountries(backendId, 50, queryRange) : Promise.resolve(null),- ]);-- if (stats) {- const summarySignature = JSON.stringify(stats);- if (summarySignature !== lastSummaryRef.current) {- lastSummaryRef.current = summarySignature;- setData(stats);- }- }-- if (countries) {- const countriesSignature = JSON.stringify(countries);- if (countriesSignature !== lastCountriesRef.current) {- lastCountriesRef.current = countriesSignature;- setCountryData(countries);- }- }-- setLastUpdated(new Date());- setError(null);- } catch (err) {- setError(err instanceof Error ? err.message : "Unknown error");+ await queryClient.invalidateQueries({ queryKey: ["stats"] });} finally {- if (showLoading) setIsLoading(false);- }- },- [timeRange, activeBackendId, activeBackend, activeTab],- );-- const refreshNow = useCallback(- async (showLoading = false) => {- if (isRollingTimePreset(timePreset)) {- const latestRange = getPresetTimeRange(timePreset);- setTimeRange(latestRange);- await loadStats(showLoading, latestRange);- return;+ if (showLoading) {+ setIsManualRefreshing(false);+ }}- await loadStats(showLoading);},- [timePreset, loadStats],+ [queryClient, timePreset],);const handleTimeRangeChange = useCallback((range: TimeRange, preset: TimePreset) => {setTimePreset(preset);setTimeRange(range);- if (initialLoaded.current) {- loadStats(true, range);- }},- [loadStats],+ [],);// Switch active backendconst handleSwitchBackend = async (backendId: number) => {try {await api.setActiveBackend(backendId);- await checkBackend();+ await backendsQuery.refetch();await refreshNow(true);} catch (err) {console.error("Failed to switch backend:", err);@@ -479,34 +421,41 @@ export default function DashboardPage() {// Handle backend configuration changesconst handleBackendChange = useCallback(async () => {- await checkBackend();+ await backendsQuery.refetch();await refreshNow(true);- }, [checkBackend, refreshNow]);+ }, [backendsQuery.refetch, refreshNow]);- // Initial load+ // Open setup dialog automatically when no backend is configured.useEffect(() => {- if (!initialLoaded.current) {- checkBackend();- loadStats(true);- initialLoaded.current = true;+ if (backendsQuery.isError) return;+ if (backendsQuery.isLoading || backendsQuery.isFetching) return;+ if (backends.length === 0) {+ setIsFirstTime(true);+ setShowBackendDialog(true);+ return;+ }+ if (isFirstTime) {+ setIsFirstTime(false);}- }, [loadStats, checkBackend]);+ }, [backends.length, backendsQuery.isError, backendsQuery.isFetching, backendsQuery.isLoading, isFirstTime]);- // Background polling - every 5 seconds without loading state (only when autoRefresh is on)+ // Keep rolling windows fresh by moving the range every 5s.useEffect(() => {- if (!autoRefresh) return;+ if (!autoRefresh || !isRollingTimePreset(timePreset)) return;+ const interval = setInterval(() => {+ setTimeRange(getPresetTimeRange(timePreset));+ }, 5000);+ return () => clearInterval(interval);+ }, [autoRefresh, timePreset]);+ // For fixed windows, keep polling active stats queries.+ useEffect(() => {+ if (!autoRefresh || isRollingTimePreset(timePreset)) return;const interval = setInterval(() => {- if (isRollingTimePreset(timePreset)) {- const latestRange = getPresetTimeRange(timePreset);- setTimeRange(latestRange);- loadStats(false, latestRange);- return;- }- loadStats(false);+ queryClient.invalidateQueries({ queryKey: ["stats"] });}, 5000);return () => clearInterval(interval);- }, [loadStats, autoRefresh, timePreset]);+ }, [autoRefresh, timePreset, queryClient]);const renderContent = () => {switch (activeTab) {@@ -515,7 +464,7 @@ export default function DashboardPage() {<OverviewContentdata={data}countryData={countryData}- error={error}+ error={queryError}timeRange={timeRange}timePreset={timePreset}activeBackendId={activeBackendId}@@ -530,7 +479,6 @@ export default function DashboardPage() {case "proxies":return (<ProxiesContent- data={data}activeBackendId={activeBackendId}timeRange={timeRange}backendStatus={backendStatus}@@ -539,7 +487,6 @@ export default function DashboardPage() {case "rules":return (<RulesContent- data={data}activeBackendId={activeBackendId}timeRange={timeRange}backendStatus={backendStatus}@@ -560,7 +507,7 @@ export default function DashboardPage() {<OverviewContentdata={data}countryData={countryData}- error={error}+ error={queryError}timeRange={timeRange}timePreset={timePreset}activeBackendId={activeBackendId}diff --git a/apps/web/components/domains-table.tsx b/apps/web/components/domains-table.tsxindex 2145597..8c22988 100644--- a/apps/web/components/domains-table.tsx+++ b/apps/web/components/domains-table.tsx@@ -1,8 +1,9 @@"use client";-import { useState, useCallback, useEffect, useMemo, useRef } from "react";+import { useState, useEffect, useMemo, useRef } from "react";import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, ChevronDown, ChevronUp, Server, Loader2 } from "lucide-react";import { useTranslations } from "next-intl";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import { Input } from "@/components/ui/input";import { Button } from "@/components/ui/button";import { Favicon } from "@/components/favicon";@@ -10,8 +11,13 @@ import { DomainExpandedDetails } from "@/components/stats-tables/expanded-detailimport { ProxyChainBadge } from "@/components/proxy-chain-badge";import { formatBytes, formatNumber, formatDuration } from "@/lib/utils";import { cn } from "@/lib/utils";-import type { DomainStats, ProxyTrafficStats, IPStats } from "@clashmaster/shared";+import type { DomainStats } from "@clashmaster/shared";import { api, type TimeRange } from "@/lib/api";+import {+ getDomainIPDetailsQueryKey,+ getDomainProxyStatsQueryKey,+ getDomainsQueryKey,+} from "@/lib/stats-query-keys";import {DropdownMenu,DropdownMenuContent,@@ -36,9 +42,6 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)if (!timeRange?.start && !timeRange?.end) return undefined;return { start: timeRange.start, end: timeRange.end };}, [timeRange?.start, timeRange?.end]);- const [data, setData] = useState<DomainStats[]>([]);- const [total, setTotal] = useState(0);- const [loading, setLoading] = useState(false);const [search, setSearch] = useState("");const [debouncedSearch, setDebouncedSearch] = useState("");const [sortKey, setSortKey] = useState<SortKey>("totalDownload");@@ -46,24 +49,8 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)const [currentPage, setCurrentPage] = useState(1);const [pageSize, setPageSize] = useState<PageSize>(10);const [expandedDomain, setExpandedDomain] = useState<string | null>(null);- const [proxyStats, setProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});- const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);- const [ipDetails, setIPDetails] = useState<Record<string, IPStats[]>>({});- const [ipDetailsLoading, setIPDetailsLoading] = useState<string | null>(null);- const proxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});- const ipDetailsRef = useRef<Record<string, IPStats[]>>({});- const proxyStatsInFlightRef = useRef<Set<string>>(new Set());- const ipDetailsInFlightRef = useRef<Set<string>>(new Set());const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);- useEffect(() => {- proxyStatsRef.current = proxyStats;- }, [proxyStats]);-- useEffect(() => {- ipDetailsRef.current = ipDetails;- }, [ipDetails]);-// Debounce search inputuseEffect(() => {debounceRef.current = setTimeout(() => {@@ -73,121 +60,54 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps)return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };}, [search]);- // Fetch data from server- useEffect(() => {- let cancelled = false;- const fetchData = async () => {- setLoading(true);- try {- const result = await api.getDomains(activeBackendId, {- offset: (currentPage - 1) * pageSize,- limit: pageSize,- sortBy: sortKey,- sortOrder,- search: debouncedSearch || undefined,- start: stableTimeRange?.start,- end: stableTimeRange?.end,- });- if (!cancelled) {- setData(result.data);- setTotal(result.total);- }- } catch (err) {- console.error("Failed to fetch domains:", err);- if (!cancelled) {- setData([]);- setTotal(0);- }- } finally {- if (!cancelled) setLoading(false);- }- };- fetchData();- return () => { cancelled = true; };- }, [activeBackendId, currentPage, pageSize, sortKey, sortOrder, debouncedSearch, stableTimeRange]);+ const domainsQuery = useQuery({+ queryKey: getDomainsQueryKey(+ activeBackendId,+ {+ offset: (currentPage - 1) * pageSize,+ limit: pageSize,+ sortBy: sortKey,+ sortOrder,+ search: debouncedSearch || undefined,+ },+ stableTimeRange,+ ),+ queryFn: () =>+ api.getDomains(activeBackendId, {+ offset: (currentPage - 1) * pageSize,+ limit: pageSize,+ sortBy: sortKey,+ sortOrder,+ search: debouncedSearch || undefined,+ start: stableTimeRange?.start,+ end: stableTimeRange?.end,+ }),+ enabled: !!activeBackendId,+ placeholderData: keepPreviousData,+ });++ const data = domainsQuery.data?.data ?? [];+ const total = domainsQuery.data?.total ?? 0;+ const loading = domainsQuery.isLoading && !domainsQuery.data;useEffect(() => {// Backend switch means a different data universe, collapse safely.setExpandedDomain(null);- setProxyStats({});- setIPDetails({});- setProxyStatsLoading(null);- setIPDetailsLoading(null);- proxyStatsInFlightRef.current.clear();- ipDetailsInFlightRef.current.clear();}, [activeBackendId]);- // Fetch proxy stats when a domain is expanded- const fetchProxyStats = useCallback(async (- domain: string,- options?: { force?: boolean; background?: boolean },- ) => {- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasCached = !!proxyStatsRef.current[domain];- if (!force && hasCached) return;- if (proxyStatsInFlightRef.current.has(domain)) return;- if (!background || !hasCached) {- setProxyStatsLoading(domain);- }- proxyStatsInFlightRef.current.add(domain);- try {- const stats = await api.getDomainProxyStats(- domain,- activeBackendId,- stableTimeRange,- );- setProxyStats(prev => ({ ...prev, [domain]: stats }));- } catch (err) {- console.error(`Failed to fetch proxy stats for ${domain}:`, err);- setProxyStats(prev => ({ ...prev, [domain]: [] }));- } finally {- proxyStatsInFlightRef.current.delete(domain);- setProxyStatsLoading((prev) => (prev === domain ? null : prev));- }- }, [activeBackendId, stableTimeRange]);-- // Fetch IP details when a domain is expanded- const fetchIPDetails = useCallback(async (- domain: string,- options?: { force?: boolean; background?: boolean },- ) => {- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasCached = !!ipDetailsRef.current[domain];- if (!force && hasCached) return;- if (ipDetailsInFlightRef.current.has(domain)) return;- if (!background || !hasCached) {- setIPDetailsLoading(domain);- }- ipDetailsInFlightRef.current.add(domain);- try {- const details = await api.getDomainIPDetails(- domain,- activeBackendId,- stableTimeRange,- );- setIPDetails(prev => ({ ...prev, [domain]: details }));- } catch (err) {- console.error(`Failed to fetch IP details for ${domain}:`, err);- setIPDetails(prev => ({ ...prev, [domain]: [] }));- } finally {- ipDetailsInFlightRef.current.delete(domain);- setIPDetailsLoading((prev) => (prev === domain ? null : prev));- }- }, [activeBackendId, stableTimeRange]);+ const expandedDomainProxyQuery = useQuery({+ queryKey: getDomainProxyStatsQueryKey(expandedDomain, activeBackendId, stableTimeRange),+ queryFn: () => api.getDomainProxyStats(expandedDomain!, activeBackendId, stableTimeRange),+ enabled: !!activeBackendId && !!expandedDomain,+ placeholderData: keepPreviousData,+ });- useEffect(() => {- if (!expandedDomain) return;- fetchProxyStats(expandedDomain);- fetchIPDetails(expandedDomain);- }, [expandedDomain, fetchProxyStats, fetchIPDetails]);-- useEffect(() => {- if (!expandedDomain) return;- fetchProxyStats(expandedDomain, { force: true, background: true });- fetchIPDetails(expandedDomain, { force: true, background: true });- }, [timeRange?.start, timeRange?.end, fetchProxyStats, fetchIPDetails]);+ const expandedDomainIPDetailsQuery = useQuery({+ queryKey: getDomainIPDetailsQueryKey(expandedDomain, activeBackendId, stableTimeRange),+ queryFn: () => api.getDomainIPDetails(expandedDomain!, activeBackendId, stableTimeRange),+ enabled: !!activeBackendId && !!expandedDomain,+ placeholderData: keepPreviousData,+ });const handleSort = (key: SortKey) => {if (sortKey === key) {@@ -487,12 +407,18 @@ export function DomainsTable({ activeBackendId, timeRange }: DomainsTableProps){/* Expanded Details: Proxy Traffic + IP List */}{isExpanded && (- <DomainExpandedDetails- domain={domain}- proxyStats={proxyStats[domain.domain]}- proxyStatsLoading={proxyStatsLoading === domain.domain}- ipDetails={ipDetails[domain.domain]}- ipDetailsLoading={ipDetailsLoading === domain.domain}+ <DomainExpandedDetails+ domain={domain}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }labels={{proxyTraffic: t("proxyTraffic"),associatedIPs: t("associatedIPs"),diff --git a/apps/web/components/interactive-device-stats.tsx b/apps/web/components/interactive-device-stats.tsxindex 1c06b0e..e9527fb 100644--- a/apps/web/components/interactive-device-stats.tsx+++ b/apps/web/components/interactive-device-stats.tsx@@ -1,8 +1,9 @@"use client";-import { useState, useCallback, useMemo, useEffect, useRef } from "react";-import { Loader2, BarChart3, Link2, Smartphone, Monitor, Tablet, HelpCircle } from "lucide-react";+import { useState, useCallback, useMemo, useEffect } from "react";+import { Loader2, BarChart3, Link2, Smartphone } from "lucide-react";import { useTranslations } from "next-intl";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip, BarChart, Bar, XAxis, YAxis, Cell as BarCell, LabelList } from "recharts";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";@@ -10,10 +11,14 @@ import { ScrollArea } from "@/components/ui/scroll-area";import { formatBytes, formatNumber } from "@/lib/utils";import { cn } from "@/lib/utils";import { api, type TimeRange } from "@/lib/api";+import {+ getDeviceDomainsQueryKey,+ getDeviceIPsQueryKey,+} from "@/lib/stats-query-keys";import { Favicon } from "@/components/favicon";import { DomainStatsTable, IPStatsTable } from "@/components/stats-tables";import { COLORS } from "@/lib/stats-utils";-import type { DeviceStats, DomainStats, IPStats } from "@clashmaster/shared";+import type { DeviceStats } from "@clashmaster/shared";interface InteractiveDeviceStatsProps {data: DeviceStats[];@@ -48,14 +53,8 @@ export function InteractiveDeviceStats({}, [timeRange?.start, timeRange?.end]);const [selectedDevice, setSelectedDevice] = useState<string | null>(null);- const [deviceDomains, setDeviceDomains] = useState<DomainStats[]>([]);- const [deviceIPs, setDeviceIPs] = useState<IPStats[]>([]);- const [loading, setLoading] = useState(false);const [activeTab, setActiveTab] = useState("domains");const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);- const requestIdRef = useRef(0);- const prevSelectedDeviceRef = useRef<string | null>(null);- const prevBackendRef = useRef<number | undefined>(undefined);useEffect(() => {const media = window.matchMedia("(min-width: 640px)");@@ -83,38 +82,9 @@ export function InteractiveDeviceStats({const topDevices = useMemo(() => [...chartData].sort((a, b) => b.value - a.value).slice(0, 4), [chartData]);const maxTotal = useMemo(() => chartData.length ? Math.max(...chartData.map(d => d.value)) : 1, [chartData]);- const loadDeviceDetails = useCallback(async (sourceIP: string, options?: { background?: boolean }) => {- const background = options?.background ?? false;- const requestId = ++requestIdRef.current;- if (!background) {- setLoading(true);- }- try {- const [domains, ips] = await Promise.all([- api.getDeviceDomains(sourceIP, activeBackendId, stableTimeRange),- api.getDeviceIPs(sourceIP, activeBackendId, stableTimeRange),- ]);- if (requestId !== requestIdRef.current) return;- setDeviceDomains(domains);- setDeviceIPs(ips);- } catch (err) {- console.error(`Failed to load details for ${sourceIP}:`, err);- if (!background) {- setDeviceDomains([]);- setDeviceIPs([]);- }- } finally {- if (!background && requestId === requestIdRef.current) {- setLoading(false);- }- }- }, [activeBackendId, stableTimeRange]);-useEffect(() => {if (chartData.length === 0) {setSelectedDevice(null);- setDeviceDomains([]);- setDeviceIPs([]);return;}const exists = !!selectedDevice && chartData.some((item) => item.rawName === selectedDevice);@@ -123,18 +93,33 @@ export function InteractiveDeviceStats({}}, [chartData, selectedDevice]);- useEffect(() => {- if (!selectedDevice) return;+ const deviceDomainsQuery = useQuery({+ queryKey: getDeviceDomainsQueryKey(selectedDevice, activeBackendId, stableTimeRange),+ queryFn: () =>+ api.getDeviceDomains(+ selectedDevice!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedDevice,+ placeholderData: keepPreviousData,+ });- const selectedChanged = prevSelectedDeviceRef.current !== selectedDevice;- const backendChanged = prevBackendRef.current !== activeBackendId;+ const deviceIPsQuery = useQuery({+ queryKey: getDeviceIPsQueryKey(selectedDevice, activeBackendId, stableTimeRange),+ queryFn: () =>+ api.getDeviceIPs(+ selectedDevice!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedDevice,+ placeholderData: keepPreviousData,+ });- prevSelectedDeviceRef.current = selectedDevice;- prevBackendRef.current = activeBackendId;- loadDeviceDetails(selectedDevice, {- background: !selectedChanged && !backendChanged,- });- }, [selectedDevice, activeBackendId, timeRange?.start, timeRange?.end, loadDeviceDetails]);+ const deviceDomains = deviceDomainsQuery.data ?? [];+ const deviceIPs = deviceIPsQuery.data ?? [];+ const loading = !!selectedDevice && !deviceDomainsQuery.data && !deviceIPsQuery.data;const handleDeviceClick = useCallback((rawName: string) => {if (selectedDevice !== rawName) {diff --git a/apps/web/components/interactive-proxy-stats.tsx b/apps/web/components/interactive-proxy-stats.tsxindex 23c3d7e..17a0657 100644--- a/apps/web/components/interactive-proxy-stats.tsx+++ b/apps/web/components/interactive-proxy-stats.tsx@@ -1,8 +1,9 @@"use client";-import { useState, useCallback, useMemo, useEffect, useRef } from "react";+import { useState, useCallback, useMemo, useEffect } from "react";import { Loader2, BarChart3, Link2, Waypoints } from "lucide-react";import { useTranslations } from "next-intl";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip, BarChart, Bar, XAxis, YAxis, Cell as BarCell, LabelList } from "recharts";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";@@ -11,13 +12,18 @@ import { CountryFlag, extractCountryCodeFromText, stripLeadingFlagEmoji } from "import { formatBytes, formatNumber } from "@/lib/utils";import { cn } from "@/lib/utils";import { api, type TimeRange } from "@/lib/api";+import {+ getProxiesQueryKey,+ getProxyDomainsQueryKey,+ getProxyIPsQueryKey,+} from "@/lib/stats-query-keys";import { Favicon } from "@/components/favicon";import { DomainStatsTable, IPStatsTable } from "@/components/stats-tables";import { COLORS } from "@/lib/stats-utils";-import type { ProxyStats, DomainStats, IPStats } from "@clashmaster/shared";+import type { ProxyStats } from "@clashmaster/shared";interface InteractiveProxyStatsProps {- data: ProxyStats[];+ data?: ProxyStats[];activeBackendId?: number;timeRange?: TimeRange;backendStatus?: "healthy" | "unhealthy" | "unknown";@@ -70,16 +76,19 @@ export function InteractiveProxyStats({if (!timeRange?.start && !timeRange?.end) return undefined;return { start: timeRange.start, end: timeRange.end };}, [timeRange?.start, timeRange?.end]);++ const proxyListQuery = useQuery({+ queryKey: getProxiesQueryKey(activeBackendId, 50, stableTimeRange),+ queryFn: () => api.getProxies(activeBackendId, 50, stableTimeRange),+ enabled: !data && !!activeBackendId,+ placeholderData: keepPreviousData,+ });+ const proxyData = data ?? proxyListQuery.data ?? [];+ const listLoading = !data && proxyListQuery.isLoading && !proxyListQuery.data;const [selectedProxy, setSelectedProxy] = useState<string | null>(null);- const [proxyDomains, setProxyDomains] = useState<DomainStats[]>([]);- const [proxyIPs, setProxyIPs] = useState<IPStats[]>([]);- const [loading, setLoading] = useState(false);const [activeTab, setActiveTab] = useState("domains");const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);- const requestIdRef = useRef(0);- const prevSelectedProxyRef = useRef<string | null>(null);- const prevBackendRef = useRef<number | undefined>(undefined);useEffect(() => {const media = window.matchMedia("(min-width: 640px)");@@ -90,8 +99,8 @@ export function InteractiveProxyStats({}, []);const chartData = useMemo(() => {- if (!data) return [];- return data.map((proxy, index) => ({+ if (!proxyData) return [];+ return proxyData.map((proxy, index) => ({name: simplifyProxyName(proxy.chain),rawName: proxy.chain,value: proxy.totalDownload + proxy.totalUpload,@@ -102,44 +111,15 @@ export function InteractiveProxyStats({countryCode: getProxyCountryCode(proxy.chain),rank: index,}));- }, [data]);+ }, [proxyData]);const totalTraffic = useMemo(() => chartData.reduce((sum, item) => sum + item.value, 0), [chartData]);const topProxies = useMemo(() => [...chartData].sort((a, b) => b.value - a.value).slice(0, 4), [chartData]);const maxTotal = useMemo(() => chartData.length ? Math.max(...chartData.map(p => p.value)) : 1, [chartData]);- const loadProxyDetails = useCallback(async (chain: string, options?: { background?: boolean }) => {- const background = options?.background ?? false;- const requestId = ++requestIdRef.current;- if (!background) {- setLoading(true);- }- try {- const [domains, ips] = await Promise.all([- api.getProxyDomains(chain, activeBackendId, stableTimeRange),- api.getProxyIPs(chain, activeBackendId, stableTimeRange),- ]);- if (requestId !== requestIdRef.current) return;- setProxyDomains(domains);- setProxyIPs(ips);- } catch (err) {- console.error(`Failed to load details for ${chain}:`, err);- if (!background) {- setProxyDomains([]);- setProxyIPs([]);- }- } finally {- if (!background && requestId === requestIdRef.current) {- setLoading(false);- }- }- }, [activeBackendId, stableTimeRange]);-useEffect(() => {if (chartData.length === 0) {setSelectedProxy(null);- setProxyDomains([]);- setProxyIPs([]);return;}const exists = !!selectedProxy && chartData.some((item) => item.rawName === selectedProxy);@@ -148,18 +128,33 @@ export function InteractiveProxyStats({}}, [chartData, selectedProxy]);- useEffect(() => {- if (!selectedProxy) return;+ const proxyDomainsQuery = useQuery({+ queryKey: getProxyDomainsQueryKey(selectedProxy, activeBackendId, stableTimeRange),+ queryFn: () =>+ api.getProxyDomains(+ selectedProxy!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedProxy,+ placeholderData: keepPreviousData,+ });- const selectedChanged = prevSelectedProxyRef.current !== selectedProxy;- const backendChanged = prevBackendRef.current !== activeBackendId;+ const proxyIPsQuery = useQuery({+ queryKey: getProxyIPsQueryKey(selectedProxy, activeBackendId, stableTimeRange),+ queryFn: () =>+ api.getProxyIPs(+ selectedProxy!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedProxy,+ placeholderData: keepPreviousData,+ });- prevSelectedProxyRef.current = selectedProxy;- prevBackendRef.current = activeBackendId;- loadProxyDetails(selectedProxy, {- background: !selectedChanged && !backendChanged,- });- }, [selectedProxy, activeBackendId, timeRange?.start, timeRange?.end, loadProxyDetails]);+ const proxyDomains = proxyDomainsQuery.data ?? [];+ const proxyIPs = proxyIPsQuery.data ?? [];+ const loading = !!selectedProxy && !proxyDomainsQuery.data && !proxyIPsQuery.data;const handleProxyClick = useCallback((rawName: string) => {if (selectedProxy !== rawName) {@@ -189,6 +184,18 @@ export function InteractiveProxyStats({? backendT("backendUnavailableHint"): t("noDataHint");+ if (listLoading) {+ return (+ <Card>+ <CardContent className="p-5 sm:p-6">+ <div className="flex items-center justify-center py-12">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ </CardContent>+ </Card>+ );+ }+if (chartData.length === 0) {return (<Card>diff --git a/apps/web/components/interactive-rule-stats.tsx b/apps/web/components/interactive-rule-stats.tsxindex feb6623..24a0d06 100644--- a/apps/web/components/interactive-rule-stats.tsx+++ b/apps/web/components/interactive-rule-stats.tsx@@ -1,8 +1,9 @@"use client";-import { useState, useCallback, useMemo, useEffect, useRef } from "react";+import { useState, useCallback, useMemo, useEffect } from "react";import { Server, ChevronLeft, ChevronRight, Loader2, BarChart3, Link2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, Waypoints, ChevronDown, ChevronUp } from "lucide-react";import { useTranslations } from "next-intl";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip } from "recharts";import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Cell as BarCell, LabelList } from "recharts";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";@@ -19,15 +20,24 @@ import {import { formatBytes, formatNumber } from "@/lib/utils";import { cn } from "@/lib/utils";import { api, type ClashRulesResponse, type TimeRange } from "@/lib/api";+import {+ getRuleDomainsQueryKey,+ getRuleIPsQueryKey,+ getIPDomainDetailsQueryKey,+ getIPProxyStatsQueryKey,+ getDomainIPDetailsQueryKey,+ getDomainProxyStatsQueryKey,+ getRulesQueryKey,+} from "@/lib/stats-query-keys";import { CountryFlag } from "@/components/country-flag";import { Favicon } from "@/components/favicon";import { ProxyChainBadge } from "@/components/proxy-chain-badge";import { DomainExpandedDetails, IPExpandedDetails } from "@/components/stats-tables/expanded-details";import { UnifiedRuleChainFlow } from "@/components/rule-chain-flow";-import type { RuleStats, DomainStats, IPStats, ProxyTrafficStats } from "@clashmaster/shared";+import type { RuleStats, DomainStats, IPStats } from "@clashmaster/shared";interface InteractiveRuleStatsProps {- data: RuleStats[];+ data?: RuleStats[];activeBackendId?: number;timeRange?: TimeRange;backendStatus?: "healthy" | "unhealthy" | "unknown";@@ -105,11 +115,17 @@ export function InteractiveRuleStats({if (!timeRange?.start && !timeRange?.end) return undefined;return { start: timeRange.start, end: timeRange.end };}, [timeRange?.start, timeRange?.end]);++ const ruleListQuery = useQuery({+ queryKey: getRulesQueryKey(activeBackendId, 50, stableTimeRange),+ queryFn: () => api.getRules(activeBackendId, 50, stableTimeRange),+ enabled: !data && !!activeBackendId,+ placeholderData: keepPreviousData,+ });+ const rulesData = data ?? ruleListQuery.data ?? [];+ const listLoading = !data && ruleListQuery.isLoading && !ruleListQuery.data;const [selectedRule, setSelectedRule] = useState<string | null>(null);- const [ruleDomains, setRuleDomains] = useState<DomainStats[]>([]);- const [ruleIPs, setRuleIPs] = useState<IPStats[]>([]);- const [loading, setLoading] = useState(false);const [activeTab, setActiveTab] = useState("domains");// Pagination states@@ -131,23 +147,6 @@ export function InteractiveRuleStats({// Expanded statesconst [expandedDomain, setExpandedDomain] = useState<string | null>(null);const [expandedIP, setExpandedIP] = useState<string | null>(null);- const [domainProxyStats, setDomainProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});- const [domainProxyStatsLoading, setDomainProxyStatsLoading] = useState<string | null>(null);- const [domainIPDetails, setDomainIPDetails] = useState<Record<string, IPStats[]>>({});- const [domainIPDetailsLoading, setDomainIPDetailsLoading] = useState<string | null>(null);- const [ipProxyStats, setIPProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});- const [ipProxyStatsLoading, setIPProxyStatsLoading] = useState<string | null>(null);- const [ipDomainDetails, setIPDomainDetails] = useState<Record<string, DomainStats[]>>({});- const [ipDomainDetailsLoading, setIPDomainDetailsLoading] = useState<string | null>(null);- const domainProxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});- const domainIPDetailsRef = useRef<Record<string, IPStats[]>>({});- const ipProxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});- const ipDomainDetailsRef = useRef<Record<string, DomainStats[]>>({});- const domainDetailsInFlightRef = useRef<Set<string>>(new Set());- const ipDetailsInFlightRef = useRef<Set<string>>(new Set());- const requestIdRef = useRef(0);- const prevSelectedRuleRef = useRef<string | null>(null);- const prevBackendRef = useRef<number | undefined>(undefined);useEffect(() => {const media = window.matchMedia("(min-width: 640px)");@@ -157,22 +156,6 @@ export function InteractiveRuleStats({return () => media.removeEventListener("change", update);}, []);- useEffect(() => {- domainProxyStatsRef.current = domainProxyStats;- }, [domainProxyStats]);-- useEffect(() => {- domainIPDetailsRef.current = domainIPDetails;- }, [domainIPDetails]);-- useEffect(() => {- ipProxyStatsRef.current = ipProxyStats;- }, [ipProxyStats]);-- useEffect(() => {- ipDomainDetailsRef.current = ipDomainDetails;- }, [ipDomainDetails]);-// Fetch Clash rules to find zero-traffic rulesuseEffect(() => {let cancelled = false;@@ -190,9 +173,9 @@ export function InteractiveRuleStats({}, [activeBackendId]);const chartData = useMemo(() => {- if (!data) return [];- const existingRuleNames = new Set(data.map(r => r.rule));- const trafficItems = data.map((rule, index) => ({+ if (!rulesData) return [];+ const existingRuleNames = new Set(rulesData.map(r => r.rule));+ const trafficItems = rulesData.map((rule, index) => ({name: rule.rule,rawName: rule.rule,value: rule.totalDownload + rule.totalUpload,@@ -232,7 +215,7 @@ export function InteractiveRuleStats({}return trafficItems;- }, [data, clashRules]);+ }, [rulesData, clashRules]);const totalTraffic = useMemo(() => {return chartData.reduce((sum, item) => sum + item.value, 0);@@ -281,79 +264,93 @@ export function InteractiveRuleStats({setExpandedIP(newExpanded);};- const fetchExpandedDomainDetails = useCallback(async (- domain: string,- options?: { force?: boolean; background?: boolean },- ) => {- if (!selectedRule) return;- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasProxyCached = !!domainProxyStatsRef.current[domain];- const hasIPCached = !!domainIPDetailsRef.current[domain];- if (!force && hasProxyCached && hasIPCached) return;- if (domainDetailsInFlightRef.current.has(domain)) return;-- if (!background || !hasProxyCached) setDomainProxyStatsLoading(domain);- if (!background || !hasIPCached) setDomainIPDetailsLoading(domain);- domainDetailsInFlightRef.current.add(domain);- try {- const [proxyStats, ipDetails] = await Promise.all([- api.getRuleDomainProxyStats(selectedRule, domain, activeBackendId, stableTimeRange),- api.getRuleDomainIPDetails(selectedRule, domain, activeBackendId, stableTimeRange),- ]);- setDomainProxyStats((prev) => ({ ...prev, [domain]: proxyStats }));- setDomainIPDetails((prev) => ({ ...prev, [domain]: ipDetails }));- } catch (err) {- console.error(`Failed to fetch rule-domain details for ${domain}:`, err);- setDomainProxyStats((prev) => ({ ...prev, [domain]: [] }));- setDomainIPDetails((prev) => ({ ...prev, [domain]: [] }));- } finally {- domainDetailsInFlightRef.current.delete(domain);- setDomainProxyStatsLoading((prev) => (prev === domain ? null : prev));- setDomainIPDetailsLoading((prev) => (prev === domain ? null : prev));- }- }, [- selectedRule,- activeBackendId,- stableTimeRange,- ]);-- const fetchExpandedIPDetails = useCallback(async (- ip: string,- options?: { force?: boolean; background?: boolean },- ) => {- if (!selectedRule) return;- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasProxyCached = !!ipProxyStatsRef.current[ip];- const hasDomainCached = !!ipDomainDetailsRef.current[ip];- if (!force && hasProxyCached && hasDomainCached) return;- if (ipDetailsInFlightRef.current.has(ip)) return;-- if (!background || !hasProxyCached) setIPProxyStatsLoading(ip);- if (!background || !hasDomainCached) setIPDomainDetailsLoading(ip);- ipDetailsInFlightRef.current.add(ip);- try {- const [proxyStats, domainDetails] = await Promise.all([- api.getRuleIPProxyStats(selectedRule, ip, activeBackendId, stableTimeRange),- api.getRuleIPDomainDetails(selectedRule, ip, activeBackendId, stableTimeRange),- ]);- setIPProxyStats((prev) => ({ ...prev, [ip]: proxyStats }));- setIPDomainDetails((prev) => ({ ...prev, [ip]: domainDetails }));- } catch (err) {- console.error(`Failed to fetch rule-ip details for ${ip}:`, err);- setIPProxyStats((prev) => ({ ...prev, [ip]: [] }));- setIPDomainDetails((prev) => ({ ...prev, [ip]: [] }));- } finally {- ipDetailsInFlightRef.current.delete(ip);- setIPProxyStatsLoading((prev) => (prev === ip ? null : prev));- setIPDomainDetailsLoading((prev) => (prev === ip ? null : prev));- }- }, [- selectedRule,- activeBackendId,- stableTimeRange,- ]);+ const expandedDomainProxyQuery = useQuery({+ queryKey: getDomainProxyStatsQueryKey(expandedDomain, activeBackendId, stableTimeRange, {+ rule: selectedRule ?? undefined,+ }),+ queryFn: () =>+ api.getRuleDomainProxyStats(+ selectedRule!,+ expandedDomain!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedRule && !!expandedDomain,+ placeholderData: keepPreviousData,+ });++ const expandedDomainIPDetailsQuery = useQuery({+ queryKey: getDomainIPDetailsQueryKey(expandedDomain, activeBackendId, stableTimeRange, {+ rule: selectedRule ?? undefined,+ }),+ queryFn: () =>+ api.getRuleDomainIPDetails(+ selectedRule!,+ expandedDomain!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedRule && !!expandedDomain,+ placeholderData: keepPreviousData,+ });++ const expandedIPProxyQuery = useQuery({+ queryKey: getIPProxyStatsQueryKey(expandedIP, activeBackendId, stableTimeRange, {+ rule: selectedRule ?? undefined,+ }),+ queryFn: () =>+ api.getRuleIPProxyStats(+ selectedRule!,+ expandedIP!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedRule && !!expandedIP,+ placeholderData: keepPreviousData,+ });++ const expandedIPDomainDetailsQuery = useQuery({+ queryKey: getIPDomainDetailsQueryKey(expandedIP, activeBackendId, stableTimeRange, {+ rule: selectedRule ?? undefined,+ }),+ queryFn: () =>+ api.getRuleIPDomainDetails(+ selectedRule!,+ expandedIP!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedRule && !!expandedIP,+ placeholderData: keepPreviousData,+ });++ const ruleDomainsQuery = useQuery({+ queryKey: getRuleDomainsQueryKey(selectedRule, activeBackendId, stableTimeRange),+ queryFn: () =>+ api.getRuleDomains(+ selectedRule!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedRule,+ placeholderData: keepPreviousData,+ });++ const ruleIPsQuery = useQuery({+ queryKey: getRuleIPsQueryKey(selectedRule, activeBackendId, stableTimeRange),+ queryFn: () =>+ api.getRuleIPs(+ selectedRule!,+ activeBackendId,+ stableTimeRange,+ ),+ enabled: !!activeBackendId && !!selectedRule,+ placeholderData: keepPreviousData,+ });++ const ruleDomains: DomainStats[] = ruleDomainsQuery.data ?? [];+ const ruleIPs: IPStats[] = ruleIPsQuery.data ?? [];+ const loading = !!selectedRule && !ruleDomainsQuery.data && !ruleIPsQuery.data;// Sort icon componentconst DomainSortIcon = ({ column }: { column: DomainSortKey }) => {@@ -374,52 +371,10 @@ export function InteractiveRuleStats({);};- // Load rule details- const loadRuleDetails = useCallback(async (- rule: string,- options?: { background?: boolean; preserveUiState?: boolean },- ) => {- const background = options?.background ?? false;- const preserveUiState = options?.preserveUiState ?? false;- const requestId = ++requestIdRef.current;-- if (!background) {- setLoading(true);- }-- try {- const [domains, ips] = await Promise.all([- api.getRuleDomains(rule, activeBackendId, stableTimeRange),- api.getRuleIPs(rule, activeBackendId, stableTimeRange),- ]);- if (requestId !== requestIdRef.current) return;- setRuleDomains(domains);- setRuleIPs(ips);- if (!preserveUiState) {- setDomainPage(1);- setIpPage(1);- setDomainSearch("");- setIpSearch("");- }- } catch (err) {- console.error(`Failed to load details for ${rule}:`, err);- if (!background) {- setRuleDomains([]);- setRuleIPs([]);- }- } finally {- if (!background && requestId === requestIdRef.current) {- setLoading(false);- }- }- }, [activeBackendId, stableTimeRange]);-// Default select first rule when data loadsuseEffect(() => {if (chartData.length === 0) {setSelectedRule(null);- setRuleDomains([]);- setRuleIPs([]);return;}const exists = !!selectedRule && chartData.some((item) => item.rawName === selectedRule);@@ -429,58 +384,19 @@ export function InteractiveRuleStats({}, [chartData, selectedRule]);useEffect(() => {- if (!selectedRule) return;-- const selectedChanged = prevSelectedRuleRef.current !== selectedRule;- const backendChanged = prevBackendRef.current !== activeBackendId;- const background = !selectedChanged && !backendChanged;-- prevSelectedRuleRef.current = selectedRule;- prevBackendRef.current = activeBackendId;- loadRuleDetails(selectedRule, {- background,- preserveUiState: background,- });- }, [selectedRule, activeBackendId, timeRange?.start, timeRange?.end, loadRuleDetails]);-- useEffect(() => {+ // Rule changed: reset table controls for a clean context.+ setDomainPage(1);+ setIpPage(1);+ setDomainSearch("");+ setIpSearch("");setExpandedDomain(null);setExpandedIP(null);- setDomainProxyStats({});- setDomainIPDetails({});- setIPProxyStats({});- setIPDomainDetails({});- setDomainProxyStatsLoading(null);- setDomainIPDetailsLoading(null);- setIPProxyStatsLoading(null);- setIPDomainDetailsLoading(null);- domainDetailsInFlightRef.current.clear();- ipDetailsInFlightRef.current.clear();- }, [selectedRule, activeBackendId]);-- useEffect(() => {- if (!expandedDomain) return;- fetchExpandedDomainDetails(expandedDomain);- }, [expandedDomain, fetchExpandedDomainDetails]);-- useEffect(() => {- if (!expandedIP) return;- fetchExpandedIPDetails(expandedIP);- }, [expandedIP, fetchExpandedIPDetails]);+ }, [selectedRule]);useEffect(() => {- if (expandedDomain) {- fetchExpandedDomainDetails(expandedDomain, { force: true, background: true });- }- if (expandedIP) {- fetchExpandedIPDetails(expandedIP, { force: true, background: true });- }- }, [- timeRange?.start,- timeRange?.end,- fetchExpandedDomainDetails,- fetchExpandedIPDetails,- ]);+ setExpandedDomain(null);+ setExpandedIP(null);+ }, [activeBackendId]);const handleRuleClick = useCallback((rule: string) => {if (selectedRule !== rule) {@@ -594,6 +510,18 @@ export function InteractiveRuleStats({return pages;};+ if (listLoading) {+ return (+ <Card>+ <CardContent className="p-5 sm:p-6">+ <div className="flex items-center justify-center py-12">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ </CardContent>+ </Card>+ );+ }+if (chartData.length === 0) {return (<Card>@@ -1173,10 +1101,16 @@ export function InteractiveRuleStats({{isExpanded && (<DomainExpandedDetailsdomain={domain}- proxyStats={domainProxyStats[domain.domain]}- proxyStatsLoading={domainProxyStatsLoading === domain.domain}- ipDetails={domainIPDetails[domain.domain]}- ipDetailsLoading={domainIPDetailsLoading === domain.domain}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }labels={{proxyTraffic: domainsT("proxyTraffic"),associatedIPs: domainsT("associatedIPs"),@@ -1538,10 +1472,16 @@ export function InteractiveRuleStats({{isExpanded && (<IPExpandedDetailsip={ip}- proxyStats={ipProxyStats[ip.ip]}- proxyStatsLoading={ipProxyStatsLoading === ip.ip}- domainDetails={ipDomainDetails[ip.ip]}- domainDetailsLoading={ipDomainDetailsLoading === ip.ip}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }associatedDomainsIcon="link"labels={{proxyTraffic: ipsT("proxyTraffic"),diff --git a/apps/web/components/ips-table.tsx b/apps/web/components/ips-table.tsxindex 314d6c8..d79bfd8 100644--- a/apps/web/components/ips-table.tsx+++ b/apps/web/components/ips-table.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useCallback, useEffect, useMemo, useRef } from "react";+import { useState, useEffect, useMemo, useRef } from "react";import {Search,ArrowUpDown,@@ -17,6 +17,7 @@ import {Loader2,} from "lucide-react";import { useTranslations } from "next-intl";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import { Input } from "@/components/ui/input";import { Button } from "@/components/ui/button";import { CountryFlag } from "@/components/country-flag";@@ -24,8 +25,13 @@ import { formatBytes, formatNumber } from "@/lib/utils";import { cn } from "@/lib/utils";import { IPExpandedDetails } from "@/components/stats-tables/expanded-details";import { ProxyChainBadge } from "@/components/proxy-chain-badge";-import type { DomainStats, IPStats, ProxyTrafficStats } from "@clashmaster/shared";+import type { IPStats } from "@clashmaster/shared";import { api, type TimeRange } from "@/lib/api";+import {+ getIPDomainDetailsQueryKey,+ getIPProxyStatsQueryKey,+ getIPsQueryKey,+} from "@/lib/stats-query-keys";import {DropdownMenu,DropdownMenuContent,@@ -76,9 +82,6 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {if (!timeRange?.start && !timeRange?.end) return undefined;return { start: timeRange.start, end: timeRange.end };}, [timeRange?.start, timeRange?.end]);- const [data, setData] = useState<IPStats[]>([]);- const [total, setTotal] = useState(0);- const [loading, setLoading] = useState(false);const [search, setSearch] = useState("");const [debouncedSearch, setDebouncedSearch] = useState("");const [sortKey, setSortKey] = useState<SortKey>("totalDownload");@@ -86,32 +89,8 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {const [currentPage, setCurrentPage] = useState(1);const [pageSize, setPageSize] = useState<PageSize>(10);const [expandedIP, setExpandedIP] = useState<string | null>(null);- const [proxyStats, setProxyStats] = useState<- Record<string, ProxyTrafficStats[]>- >({});- const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(- null,- );- const [domainDetails, setDomainDetails] = useState<- Record<string, DomainStats[]>- >({});- const [domainDetailsLoading, setDomainDetailsLoading] = useState<string | null>(- null,- );- const proxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});- const domainDetailsRef = useRef<Record<string, DomainStats[]>>({});- const proxyStatsInFlightRef = useRef<Set<string>>(new Set());- const domainDetailsInFlightRef = useRef<Set<string>>(new Set());const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);- useEffect(() => {- proxyStatsRef.current = proxyStats;- }, [proxyStats]);-- useEffect(() => {- domainDetailsRef.current = domainDetails;- }, [domainDetails]);-// Debounce search inputuseEffect(() => {debounceRef.current = setTimeout(() => {@@ -123,123 +102,54 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {};}, [search]);- // Fetch data from server- useEffect(() => {- let cancelled = false;- const fetchData = async () => {- setLoading(true);- try {- const result = await api.getIPs(activeBackendId, {- offset: (currentPage - 1) * pageSize,- limit: pageSize,- sortBy: sortKey,- sortOrder,- search: debouncedSearch || undefined,- start: stableTimeRange?.start,- end: stableTimeRange?.end,- });- if (!cancelled) {- setData(result.data);- setTotal(result.total);- }- } catch (err) {- console.error("Failed to fetch IPs:", err);- if (!cancelled) {- setData([]);- setTotal(0);- }- } finally {- if (!cancelled) setLoading(false);- }- };- fetchData();- return () => {- cancelled = true;- };- }, [- activeBackendId,- currentPage,- pageSize,- sortKey,- sortOrder,- debouncedSearch,- stableTimeRange,- ]);+ const ipsQuery = useQuery({+ queryKey: getIPsQueryKey(+ activeBackendId,+ {+ offset: (currentPage - 1) * pageSize,+ limit: pageSize,+ sortBy: sortKey,+ sortOrder,+ search: debouncedSearch || undefined,+ },+ stableTimeRange,+ ),+ queryFn: () =>+ api.getIPs(activeBackendId, {+ offset: (currentPage - 1) * pageSize,+ limit: pageSize,+ sortBy: sortKey,+ sortOrder,+ search: debouncedSearch || undefined,+ start: stableTimeRange?.start,+ end: stableTimeRange?.end,+ }),+ enabled: !!activeBackendId,+ placeholderData: keepPreviousData,+ });++ const data = ipsQuery.data?.data ?? [];+ const total = ipsQuery.data?.total ?? 0;+ const loading = ipsQuery.isLoading && !ipsQuery.data;useEffect(() => {// Backend switch means a different data universe, collapse safely.setExpandedIP(null);- setProxyStats({});- setDomainDetails({});- setProxyStatsLoading(null);- setDomainDetailsLoading(null);- proxyStatsInFlightRef.current.clear();- domainDetailsInFlightRef.current.clear();}, [activeBackendId]);- // Fetch proxy stats when an IP is expanded- const fetchProxyStats = useCallback(- async (ip: string, options?: { force?: boolean; background?: boolean }) => {- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasCached = !!proxyStatsRef.current[ip];- if (!force && hasCached) return;- if (proxyStatsInFlightRef.current.has(ip)) return;- if (!background || !hasCached) {- setProxyStatsLoading(ip);- }- proxyStatsInFlightRef.current.add(ip);- try {- const stats = await api.getIPProxyStats(ip, activeBackendId, stableTimeRange);- setProxyStats((prev) => ({ ...prev, [ip]: stats }));- } catch (err) {- console.error(`Failed to fetch proxy stats for ${ip}:`, err);- setProxyStats((prev) => ({ ...prev, [ip]: [] }));- } finally {- proxyStatsInFlightRef.current.delete(ip);- setProxyStatsLoading((prev) => (prev === ip ? null : prev));- }- },- [activeBackendId, stableTimeRange],- );+ const expandedIPProxyQuery = useQuery({+ queryKey: getIPProxyStatsQueryKey(expandedIP, activeBackendId, stableTimeRange),+ queryFn: () => api.getIPProxyStats(expandedIP!, activeBackendId, stableTimeRange),+ enabled: !!activeBackendId && !!expandedIP,+ placeholderData: keepPreviousData,+ });- // Fetch domain details (with traffic) when an IP is expanded- const fetchDomainDetails = useCallback(- async (ip: string, options?: { force?: boolean; background?: boolean }) => {- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasCached = !!domainDetailsRef.current[ip];- if (!force && hasCached) return;- if (domainDetailsInFlightRef.current.has(ip)) return;- if (!background || !hasCached) {- setDomainDetailsLoading(ip);- }- domainDetailsInFlightRef.current.add(ip);- try {- const details = await api.getIPDomainDetails(ip, activeBackendId, stableTimeRange);- setDomainDetails((prev) => ({ ...prev, [ip]: details }));- } catch (err) {- console.error(`Failed to fetch domain details for ${ip}:`, err);- setDomainDetails((prev) => ({ ...prev, [ip]: [] }));- } finally {- domainDetailsInFlightRef.current.delete(ip);- setDomainDetailsLoading((prev) => (prev === ip ? null : prev));- }- },- [activeBackendId, stableTimeRange],- );-- useEffect(() => {- if (!expandedIP) return;- fetchProxyStats(expandedIP);- fetchDomainDetails(expandedIP);- }, [expandedIP, fetchProxyStats, fetchDomainDetails]);-- useEffect(() => {- if (!expandedIP) return;- fetchProxyStats(expandedIP, { force: true, background: true });- fetchDomainDetails(expandedIP, { force: true, background: true });- }, [timeRange?.start, timeRange?.end, fetchProxyStats, fetchDomainDetails]);+ const expandedIPDomainDetailsQuery = useQuery({+ queryKey: getIPDomainDetailsQueryKey(expandedIP, activeBackendId, stableTimeRange),+ queryFn: () => api.getIPDomainDetails(expandedIP!, activeBackendId, stableTimeRange),+ enabled: !!activeBackendId && !!expandedIP,+ placeholderData: keepPreviousData,+ });const handleSort = (key: SortKey) => {if (sortKey === key) {@@ -564,12 +474,18 @@ export function IPsTable({ activeBackendId, timeRange }: IPsTableProps) {{/* Expanded Details: Proxy Traffic + Domains List */}{isExpanded && (- <IPExpandedDetails- ip={ip}- proxyStats={proxyStats[ip.ip]}- proxyStatsLoading={proxyStatsLoading === ip.ip}- domainDetails={domainDetails[ip.ip]}- domainDetailsLoading={domainDetailsLoading === ip.ip}+ <IPExpandedDetails+ ip={ip}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }associatedDomainsIcon="link"labels={{proxyTraffic: t("proxyTraffic"),diff --git a/apps/web/components/providers/query-provider.tsx b/apps/web/components/providers/query-provider.tsxnew file mode 100644index 0000000..d0e22b8--- /dev/null+++ b/apps/web/components/providers/query-provider.tsx@@ -0,0 +1,28 @@+"use client";++import { useState, type ReactNode } from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++interface QueryProviderProps {+ children: ReactNode;+}++export function QueryProvider({ children }: QueryProviderProps) {+ const [queryClient] = useState(+ () =>+ new QueryClient({+ defaultOptions: {+ queries: {+ staleTime: 1500,+ gcTime: 5 * 60 * 1000,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ retry: 1,+ },+ },+ }),+ );++ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;+}+diff --git a/apps/web/components/stats-tables/domain-stats-table.tsx b/apps/web/components/stats-tables/domain-stats-table.tsxindex 2d2c6f0..0437ee1 100644--- a/apps/web/components/stats-tables/domain-stats-table.tsx+++ b/apps/web/components/stats-tables/domain-stats-table.tsx@@ -1,6 +1,7 @@"use client";-import { useState, useMemo, useCallback, useEffect, useRef } from "react";+import { useState, useMemo, useEffect } from "react";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import {ChevronLeft,ChevronRight,@@ -26,6 +27,10 @@ import {import { formatBytes, formatNumber } from "@/lib/utils";import { cn } from "@/lib/utils";import { api, type TimeRange } from "@/lib/api";+import {+ getDomainIPDetailsQueryKey,+ getDomainProxyStatsQueryKey,+} from "@/lib/stats-query-keys";import { Favicon } from "@/components/favicon";import { DomainExpandedDetails } from "@/components/stats-tables/expanded-details";import { ProxyChainBadge } from "@/components/proxy-chain-badge";@@ -36,7 +41,7 @@ import {type DomainSortKey,type SortOrder,} from "@/lib/stats-utils";-import type { DomainStats, ProxyTrafficStats, IPStats } from "@clashmaster/shared";+import type { DomainStats } from "@clashmaster/shared";interface DomainStatsTableProps {domains: DomainStats[];@@ -78,107 +83,44 @@ export function DomainStatsTable({const [sortOrder, setSortOrder] = useState<SortOrder>("desc");const [expandedDomain, setExpandedDomain] = useState<string | null>(null);- const [proxyStats, setProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});- const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);- const [ipDetails, setIPDetails] = useState<Record<string, IPStats[]>>({});- const [ipDetailsLoading, setIPDetailsLoading] = useState<string | null>(null);- const proxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});- const ipDetailsRef = useRef<Record<string, IPStats[]>>({});- const proxyStatsInFlightRef = useRef<Set<string>>(new Set());- const ipDetailsInFlightRef = useRef<Set<string>>(new Set());-- useEffect(() => {- proxyStatsRef.current = proxyStats;- }, [proxyStats]);-- useEffect(() => {- ipDetailsRef.current = ipDetails;- }, [ipDetails]);-useEffect(() => {// Context switch (backend/device/proxy/rule binding change): collapse.setExpandedDomain(null);- setProxyStats({});- setIPDetails({});- setProxyStatsLoading(null);- setIPDetailsLoading(null);- proxyStatsInFlightRef.current.clear();- ipDetailsInFlightRef.current.clear();}, [activeBackendId, sourceIP, sourceChain, richExpand]);- const fetchProxyStats = useCallback(- async (domain: string, options?: { force?: boolean; background?: boolean }) => {- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasCached = !!proxyStatsRef.current[domain];- if (!richExpand || (!force && hasCached)) return;- if (proxyStatsInFlightRef.current.has(domain)) return;- if (!background || !hasCached) {- setProxyStatsLoading(domain);- }- proxyStatsInFlightRef.current.add(domain);- try {- const stats = await api.getDomainProxyStats(- domain,- activeBackendId,- stableTimeRange,- sourceIP,- sourceChain,- );- setProxyStats((prev) => ({ ...prev, [domain]: stats }));- } catch (err) {- console.error(`Failed to fetch proxy stats for ${domain}:`, err);- setProxyStats((prev) => ({ ...prev, [domain]: [] }));- } finally {- proxyStatsInFlightRef.current.delete(domain);- setProxyStatsLoading((prev) => (prev === domain ? null : prev));- }- },- [activeBackendId, stableTimeRange, sourceIP, sourceChain, richExpand],- );-- const fetchIPDetails = useCallback(- async (domain: string, options?: { force?: boolean; background?: boolean }) => {- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasCached = !!ipDetailsRef.current[domain];- if (!richExpand || (!force && hasCached)) return;- if (ipDetailsInFlightRef.current.has(domain)) return;- if (!background || !hasCached) {- setIPDetailsLoading(domain);- }- ipDetailsInFlightRef.current.add(domain);- try {- const details = await api.getDomainIPDetails(- domain,- activeBackendId,- stableTimeRange,- sourceIP,- sourceChain,- );- setIPDetails((prev) => ({ ...prev, [domain]: details }));- } catch (err) {- console.error(`Failed to fetch IP details for ${domain}:`, err);- setIPDetails((prev) => ({ ...prev, [domain]: [] }));- } finally {- ipDetailsInFlightRef.current.delete(domain);- setIPDetailsLoading((prev) => (prev === domain ? null : prev));- }- },- [activeBackendId, stableTimeRange, sourceIP, sourceChain, richExpand],- );-- useEffect(() => {- if (!expandedDomain || !richExpand) return;- fetchProxyStats(expandedDomain);- fetchIPDetails(expandedDomain);- }, [expandedDomain, richExpand, fetchProxyStats, fetchIPDetails]);-- useEffect(() => {- if (!expandedDomain || !richExpand) return;- fetchProxyStats(expandedDomain, { force: true, background: true });- fetchIPDetails(expandedDomain, { force: true, background: true });- }, [timeRange?.start, timeRange?.end, richExpand, fetchProxyStats, fetchIPDetails]);+ const expandedDomainProxyQuery = useQuery({+ queryKey: getDomainProxyStatsQueryKey(expandedDomain, activeBackendId, stableTimeRange, {+ sourceIP,+ sourceChain,+ }),+ queryFn: () =>+ api.getDomainProxyStats(+ expandedDomain!,+ activeBackendId,+ stableTimeRange,+ sourceIP,+ sourceChain,+ ),+ enabled: richExpand && !!activeBackendId && !!expandedDomain,+ placeholderData: keepPreviousData,+ });++ const expandedDomainIPDetailsQuery = useQuery({+ queryKey: getDomainIPDetailsQueryKey(expandedDomain, activeBackendId, stableTimeRange, {+ sourceIP,+ sourceChain,+ }),+ queryFn: () =>+ api.getDomainIPDetails(+ expandedDomain!,+ activeBackendId,+ stableTimeRange,+ sourceIP,+ sourceChain,+ ),+ enabled: richExpand && !!activeBackendId && !!expandedDomain,+ placeholderData: keepPreviousData,+ });const handleSort = (key: DomainSortKey) => {if (sortKey === key) {@@ -444,10 +386,16 @@ export function DomainStatsTable({<DomainExpandedDetailsdomain={domain}richExpand={richExpand}- proxyStats={proxyStats[domain.domain]}- proxyStatsLoading={proxyStatsLoading === domain.domain}- ipDetails={ipDetails[domain.domain]}- ipDetailsLoading={ipDetailsLoading === domain.domain}+ proxyStats={expandedDomainProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedDomainProxyQuery.isLoading &&+ !expandedDomainProxyQuery.data+ }+ ipDetails={expandedDomainIPDetailsQuery.data ?? []}+ ipDetailsLoading={+ expandedDomainIPDetailsQuery.isLoading &&+ !expandedDomainIPDetailsQuery.data+ }labels={{proxyTraffic: t("proxyTraffic"),associatedIPs: t("associatedIPs"),diff --git a/apps/web/components/stats-tables/ip-stats-table.tsx b/apps/web/components/stats-tables/ip-stats-table.tsxindex 0f83362..299a1db 100644--- a/apps/web/components/stats-tables/ip-stats-table.tsx+++ b/apps/web/components/stats-tables/ip-stats-table.tsx@@ -1,6 +1,7 @@"use client";-import { useState, useMemo, useCallback, useEffect, useRef } from "react";+import { useState, useMemo, useEffect } from "react";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import {ChevronLeft,ChevronRight,@@ -28,6 +29,10 @@ import {import { formatBytes, formatNumber } from "@/lib/utils";import { cn } from "@/lib/utils";import { api, type TimeRange } from "@/lib/api";+import {+ getIPDomainDetailsQueryKey,+ getIPProxyStatsQueryKey,+} from "@/lib/stats-query-keys";import { IPExpandedDetails } from "@/components/stats-tables/expanded-details";import { ProxyChainBadge } from "@/components/proxy-chain-badge";import {@@ -38,7 +43,7 @@ import {type IPSortKey,type SortOrder,} from "@/lib/stats-utils";-import type { IPStats, ProxyTrafficStats, DomainStats } from "@clashmaster/shared";+import type { IPStats } from "@clashmaster/shared";interface IPStatsTableProps {ips: IPStats[];@@ -80,108 +85,45 @@ export function IPStatsTable({const [sortOrder, setSortOrder] = useState<SortOrder>("desc");const [expandedIP, setExpandedIP] = useState<string | null>(null);- const [proxyStats, setProxyStats] = useState<Record<string, ProxyTrafficStats[]>>({});- const [proxyStatsLoading, setProxyStatsLoading] = useState<string | null>(null);- const [domainDetails, setDomainDetails] = useState<Record<string, DomainStats[]>>({});- const [domainDetailsLoading, setDomainDetailsLoading] = useState<string | null>(null);- const proxyStatsRef = useRef<Record<string, ProxyTrafficStats[]>>({});- const domainDetailsRef = useRef<Record<string, DomainStats[]>>({});- const proxyStatsInFlightRef = useRef<Set<string>>(new Set());- const domainDetailsInFlightRef = useRef<Set<string>>(new Set());-- useEffect(() => {- proxyStatsRef.current = proxyStats;- }, [proxyStats]);-- useEffect(() => {- domainDetailsRef.current = domainDetails;- }, [domainDetails]);-useEffect(() => {// Context switch (backend/device/proxy/rule binding change): collapse.setExpandedIP(null);- setProxyStats({});- setDomainDetails({});- setProxyStatsLoading(null);- setDomainDetailsLoading(null);- proxyStatsInFlightRef.current.clear();- domainDetailsInFlightRef.current.clear();}, [activeBackendId, sourceIP, sourceChain, richExpand]);- const fetchProxyStats = useCallback(- async (ip: string, options?: { force?: boolean; background?: boolean }) => {- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasCached = !!proxyStatsRef.current[ip];- if (!richExpand || (!force && hasCached)) return;- if (proxyStatsInFlightRef.current.has(ip)) return;- if (!background || !hasCached) {- setProxyStatsLoading(ip);- }- proxyStatsInFlightRef.current.add(ip);- try {- const stats = await api.getIPProxyStats(- ip,- activeBackendId,- stableTimeRange,- sourceIP,- sourceChain,- );- setProxyStats((prev) => ({ ...prev, [ip]: stats }));- } catch (err) {- console.error(`Failed to fetch proxy stats for ${ip}:`, err);- setProxyStats((prev) => ({ ...prev, [ip]: [] }));- } finally {- proxyStatsInFlightRef.current.delete(ip);- setProxyStatsLoading((prev) => (prev === ip ? null : prev));- }- },- [activeBackendId, stableTimeRange, sourceIP, sourceChain, richExpand],- );-- const fetchDomainDetails = useCallback(- async (ip: string, options?: { force?: boolean; background?: boolean }) => {- const force = options?.force ?? false;- const background = options?.background ?? false;- const hasCached = !!domainDetailsRef.current[ip];- if (!richExpand || (!force && hasCached)) return;- if (domainDetailsInFlightRef.current.has(ip)) return;- if (!background || !hasCached) {- setDomainDetailsLoading(ip);- }- domainDetailsInFlightRef.current.add(ip);- try {- const details = await api.getIPDomainDetails(- ip,- activeBackendId,- stableTimeRange,- sourceIP,- undefined,- sourceChain,- );- setDomainDetails((prev) => ({ ...prev, [ip]: details }));- } catch (err) {- console.error(`Failed to fetch domain details for ${ip}:`, err);- setDomainDetails((prev) => ({ ...prev, [ip]: [] }));- } finally {- domainDetailsInFlightRef.current.delete(ip);- setDomainDetailsLoading((prev) => (prev === ip ? null : prev));- }- },- [activeBackendId, stableTimeRange, sourceIP, sourceChain, richExpand],- );-- useEffect(() => {- if (!expandedIP || !richExpand) return;- fetchProxyStats(expandedIP);- fetchDomainDetails(expandedIP);- }, [expandedIP, richExpand, fetchProxyStats, fetchDomainDetails]);-- useEffect(() => {- if (!expandedIP || !richExpand) return;- fetchProxyStats(expandedIP, { force: true, background: true });- fetchDomainDetails(expandedIP, { force: true, background: true });- }, [timeRange?.start, timeRange?.end, richExpand, fetchProxyStats, fetchDomainDetails]);+ const expandedIPProxyQuery = useQuery({+ queryKey: getIPProxyStatsQueryKey(expandedIP, activeBackendId, stableTimeRange, {+ sourceIP,+ sourceChain,+ }),+ queryFn: () =>+ api.getIPProxyStats(+ expandedIP!,+ activeBackendId,+ stableTimeRange,+ sourceIP,+ sourceChain,+ ),+ enabled: richExpand && !!activeBackendId && !!expandedIP,+ placeholderData: keepPreviousData,+ });++ const expandedIPDomainDetailsQuery = useQuery({+ queryKey: getIPDomainDetailsQueryKey(expandedIP, activeBackendId, stableTimeRange, {+ sourceIP,+ sourceChain,+ }),+ queryFn: () =>+ api.getIPDomainDetails(+ expandedIP!,+ activeBackendId,+ stableTimeRange,+ sourceIP,+ undefined,+ sourceChain,+ ),+ enabled: richExpand && !!activeBackendId && !!expandedIP,+ placeholderData: keepPreviousData,+ });const handleSort = (key: IPSortKey) => {if (sortKey === key) {@@ -468,10 +410,16 @@ export function IPStatsTable({<IPExpandedDetailsip={ip}richExpand={richExpand}- proxyStats={proxyStats[ip.ip]}- proxyStatsLoading={proxyStatsLoading === ip.ip}- domainDetails={domainDetails[ip.ip]}- domainDetailsLoading={domainDetailsLoading === ip.ip}+ proxyStats={expandedIPProxyQuery.data ?? []}+ proxyStatsLoading={+ expandedIPProxyQuery.isLoading &&+ !expandedIPProxyQuery.data+ }+ domainDetails={expandedIPDomainDetailsQuery.data ?? []}+ domainDetailsLoading={+ expandedIPDomainDetailsQuery.isLoading &&+ !expandedIPDomainDetailsQuery.data+ }associatedDomainsIcon="link"labels={{proxyTraffic: t("proxyTraffic"),diff --git a/apps/web/components/top-domains-chart.tsx b/apps/web/components/top-domains-chart.tsxindex b548c81..3e39841 100644--- a/apps/web/components/top-domains-chart.tsx+++ b/apps/web/components/top-domains-chart.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useMemo, useRef, useEffect, useCallback } from "react";+import { useState, useMemo, useRef, useEffect } from "react";import {BarChart,Bar,@@ -14,11 +14,13 @@ import {} from "recharts";import { useTranslations } from "next-intl";import { BarChart3, Loader2 } from "lucide-react";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";import { Favicon } from "@/components/favicon";import { formatBytes } from "@/lib/utils";import { api, type TimeRange } from "@/lib/api";+import { getDomainsQueryKey } from "@/lib/stats-query-keys";import type { DomainStats } from "@clashmaster/shared";interface TopDomainsChartProps {@@ -72,38 +74,42 @@ export function TopDomainsChart({ activeBackendId, timeRange }: TopDomainsChartPconst t = useTranslations("domains");const commonT = useTranslations("stats");const [topN, setTopN] = useState<TopOption>(10);- const [domains, setDomains] = useState<DomainStats[]>([]);- const [isLoading, setIsLoading] = useState(false);// Track whether this is the initial render to only animate on first loadconst hasRenderedRef = useRef(false);// Track container width to hide labels on small screensconst containerRef = useRef<HTMLDivElement>(null);const [containerWidth, setContainerWidth] = useState(0);+ const stableTimeRange = useMemo<TimeRange | undefined>(() => {+ if (!timeRange?.start && !timeRange?.end) return undefined;+ return { start: timeRange.start, end: timeRange.end };+ }, [timeRange?.start, timeRange?.end]);- // Fetch domains data based on topN selection- const fetchData = useCallback(async () => {- setIsLoading(true);- try {- const result = await api.getDomains(activeBackendId, {+ const domainsQuery = useQuery({+ queryKey: getDomainsQueryKey(+ activeBackendId,+ {offset: 0,limit: topN,sortBy: "totalDownload",sortOrder: "desc",- start: timeRange?.start,- end: timeRange?.end,- });- setDomains(result.data);- } catch (error) {- console.error("Failed to fetch top domains:", error);- } finally {- setIsLoading(false);- }- }, [activeBackendId, topN, timeRange]);+ },+ stableTimeRange,+ ),+ queryFn: () =>+ api.getDomains(activeBackendId, {+ offset: 0,+ limit: topN,+ sortBy: "totalDownload",+ sortOrder: "desc",+ start: stableTimeRange?.start,+ end: stableTimeRange?.end,+ }),+ enabled: !!activeBackendId,+ placeholderData: keepPreviousData,+ });- // Fetch data when topN or activeBackendId changes- useEffect(() => {- fetchData();- }, [fetchData]);+ const domains = domainsQuery.data?.data ?? [];+ const isLoading = domainsQuery.isLoading && !domainsQuery.data;useEffect(() => {if (!containerRef.current) return;diff --git a/apps/web/lib/stats-query-keys.ts b/apps/web/lib/stats-query-keys.tsnew file mode 100644index 0000000..ed2b265--- /dev/null+++ b/apps/web/lib/stats-query-keys.ts@@ -0,0 +1,305 @@+import type { TimeRange } from "@/lib/api";++type DomainQueryParams = {+ offset?: number;+ limit?: number;+ sortBy?: string;+ sortOrder?: string;+ search?: string;+};++type IPQueryParams = {+ offset?: number;+ limit?: number;+ sortBy?: string;+ sortOrder?: string;+ search?: string;+};++function normalizeRange(range?: TimeRange) {+ return {+ start: range?.start ?? "",+ end: range?.end ?? "",+ };+}++export function getSummaryQueryKey(backendId?: number, range?: TimeRange) {+ return [+ "stats",+ "summary",+ {+ backendId: backendId ?? null,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getCountriesQueryKey(backendId?: number, limit = 50, range?: TimeRange) {+ return [+ "stats",+ "countries",+ {+ backendId: backendId ?? null,+ limit,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getDevicesQueryKey(backendId?: number, limit = 50, range?: TimeRange) {+ return [+ "stats",+ "devices",+ {+ backendId: backendId ?? null,+ limit,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getProxiesQueryKey(backendId?: number, limit = 50, range?: TimeRange) {+ return [+ "stats",+ "proxies",+ {+ backendId: backendId ?? null,+ limit,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getRulesQueryKey(backendId?: number, limit = 50, range?: TimeRange) {+ return [+ "stats",+ "rules",+ {+ backendId: backendId ?? null,+ limit,+ ...normalizeRange(range),+ },+ ] as const;+}++type DetailScope = {+ sourceIP?: string;+ sourceChain?: string;+ rule?: string;+};++export function getDomainProxyStatsQueryKey(+ domain: string | null,+ backendId?: number,+ range?: TimeRange,+ scope?: DetailScope,+) {+ return [+ "stats",+ "domain-proxy-stats",+ {+ domain: domain ?? "",+ backendId: backendId ?? null,+ sourceIP: scope?.sourceIP ?? "",+ sourceChain: scope?.sourceChain ?? "",+ rule: scope?.rule ?? "",+ ...normalizeRange(range),+ },+ ] as const;+}++export function getDomainIPDetailsQueryKey(+ domain: string | null,+ backendId?: number,+ range?: TimeRange,+ scope?: DetailScope,+) {+ return [+ "stats",+ "domain-ip-details",+ {+ domain: domain ?? "",+ backendId: backendId ?? null,+ sourceIP: scope?.sourceIP ?? "",+ sourceChain: scope?.sourceChain ?? "",+ rule: scope?.rule ?? "",+ ...normalizeRange(range),+ },+ ] as const;+}++export function getIPProxyStatsQueryKey(+ ip: string | null,+ backendId?: number,+ range?: TimeRange,+ scope?: DetailScope,+) {+ return [+ "stats",+ "ip-proxy-stats",+ {+ ip: ip ?? "",+ backendId: backendId ?? null,+ sourceIP: scope?.sourceIP ?? "",+ sourceChain: scope?.sourceChain ?? "",+ rule: scope?.rule ?? "",+ ...normalizeRange(range),+ },+ ] as const;+}++export function getIPDomainDetailsQueryKey(+ ip: string | null,+ backendId?: number,+ range?: TimeRange,+ scope?: DetailScope,+) {+ return [+ "stats",+ "ip-domain-details",+ {+ ip: ip ?? "",+ backendId: backendId ?? null,+ sourceIP: scope?.sourceIP ?? "",+ sourceChain: scope?.sourceChain ?? "",+ rule: scope?.rule ?? "",+ ...normalizeRange(range),+ },+ ] as const;+}++export function getDomainsQueryKey(+ backendId?: number,+ params?: DomainQueryParams,+ range?: TimeRange,+) {+ return [+ "stats",+ "domains",+ {+ backendId: backendId ?? null,+ offset: params?.offset ?? 0,+ limit: params?.limit ?? 10,+ sortBy: params?.sortBy ?? "totalDownload",+ sortOrder: params?.sortOrder ?? "desc",+ search: params?.search ?? "",+ ...normalizeRange(range),+ },+ ] as const;+}++export function getIPsQueryKey(+ backendId?: number,+ params?: IPQueryParams,+ range?: TimeRange,+) {+ return [+ "stats",+ "ips",+ {+ backendId: backendId ?? null,+ offset: params?.offset ?? 0,+ limit: params?.limit ?? 10,+ sortBy: params?.sortBy ?? "totalDownload",+ sortOrder: params?.sortOrder ?? "desc",+ search: params?.search ?? "",+ ...normalizeRange(range),+ },+ ] as const;+}++export function getProxyDomainsQueryKey(+ chain: string | null,+ backendId?: number,+ range?: TimeRange,+) {+ return [+ "stats",+ "proxy-domains",+ {+ chain: chain ?? "",+ backendId: backendId ?? null,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getProxyIPsQueryKey(+ chain: string | null,+ backendId?: number,+ range?: TimeRange,+) {+ return [+ "stats",+ "proxy-ips",+ {+ chain: chain ?? "",+ backendId: backendId ?? null,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getDeviceDomainsQueryKey(+ sourceIP: string | null,+ backendId?: number,+ range?: TimeRange,+) {+ return [+ "stats",+ "device-domains",+ {+ sourceIP: sourceIP ?? "",+ backendId: backendId ?? null,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getDeviceIPsQueryKey(+ sourceIP: string | null,+ backendId?: number,+ range?: TimeRange,+) {+ return [+ "stats",+ "device-ips",+ {+ sourceIP: sourceIP ?? "",+ backendId: backendId ?? null,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getRuleDomainsQueryKey(+ rule: string | null,+ backendId?: number,+ range?: TimeRange,+) {+ return [+ "stats",+ "rule-domains",+ {+ rule: rule ?? "",+ backendId: backendId ?? null,+ ...normalizeRange(range),+ },+ ] as const;+}++export function getRuleIPsQueryKey(+ rule: string | null,+ backendId?: number,+ range?: TimeRange,+) {+ return [+ "stats",+ "rule-ips",+ {+ rule: rule ?? "",+ backendId: backendId ?? null,+ ...normalizeRange(range),+ },+ ] as const;+}diff --git a/apps/web/package.json b/apps/web/package.jsonindex 4b6a8df..fc94a88 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -15,6 +15,7 @@"@radix-ui/react-popover": "^1.1.15","@radix-ui/react-radio-group": "^1.3.8","@radix-ui/react-scroll-area": "^1.2.10",+ "@tanstack/react-query": "^5.90.20","@xyflow/react": "^12.10.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 93fc82f..39efa04 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -69,6 +69,9 @@ importers:'@radix-ui/react-scroll-area':specifier: ^1.2.10version: 1.2.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@tanstack/react-query':+ specifier: ^5.90.20+ version: 5.90.20([email protected])'@xyflow/react':specifier: ^12.10.0@@ -2222,6 +2225,14 @@ packages:'@tailwindcss/[email protected]':resolution: {integrity: sha512-Ce0GFnzAOuPyfV5SxjXGn0CubwGcuDB0zcdaPuCSzAa/2vII24JTkH+I6jcbXLb1ctjZMZZI6OjDaLPJQL1S0g==}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-vXBxa+qeyveVO7OA0jX1z+DeyCA4JKnThKv411jd5SORpBKgkcVnYKCiBgECvADvniBX7tobwBmg01qq9JmMJw==}+ peerDependencies:+ react: ^18 || ^19+'@tybys/[email protected]':resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==}@@ -6941,6 +6952,13 @@ snapshots:postcss: 8.5.6tailwindcss: 4.1.18+ '@tanstack/[email protected]': {}++ '@tanstack/[email protected]([email protected])':+ dependencies:+ '@tanstack/query-core': 5.90.20+ react: 19.2.4+'@tybys/[email protected]':dependencies:tslib: 2.8.1