Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

refactor: extract domain and IP statistics display and logic into dedicated table components

luoleiac0c7751d162
diff --git a/apps/web/components/features/rules/interactive-rule-stats.tsx b/apps/web/components/features/rules/interactive-rule-stats.tsx
index 9cdfce8..42a0cc9 100644
--- a/apps/web/components/features/rules/interactive-rule-stats.tsx
+++ b/apps/web/components/features/rules/interactive-rule-stats.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState, useCallback, useMemo, useEffect, useRef, startTransition } from "react";
-import { Server, ChevronLeft, ChevronRight, BarChart3, Link2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, Waypoints, ChevronDown, ChevronUp } from "lucide-react";
+import { BarChart3, Link2, Waypoints } from "lucide-react";
import { useTranslations } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip } from "recharts";
@@ -9,14 +9,7 @@ import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Cell as BarCell, LabelList
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
import { formatBytes, formatNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
import { api, type GatewayRulesResponse, type TimeRange } from "@/lib/api";
@@ -28,24 +21,15 @@ import {
} from "@/lib/stats-query-keys";
import { useRules, useGatewayRules, useRuleDomains, useRuleIPs } from "@/hooks/api/use-rules";
import {
- useRuleDomainProxyStats,
- useRuleDomainIPDetails,
- useRuleIPProxyStats,
- useRuleIPDomainDetails,
-} from "@/hooks/api/use-rule-details";
-import { CountryFlag } from "@/components/features/countries/country-flag";
+ DomainStatsTable,
+ IPStatsTable,
+} from "@/components/features/stats/table";
import { Favicon } from "@/components/common/favicon";
-import { CopyIconButton } from "@/components/common/copy-icon-button";
-import { DomainPreview } from "@/components/features/domains/domain-preview";
-import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";
-import { DomainExpandedDetails, IPExpandedDetails } from "@/components/features/stats/table/expanded-details";
import { useIsWindows } from "@/lib/hooks/use-is-windows";
-import { ExpandReveal } from "@/components/ui/expand-reveal";
-import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";
-import { normalizeGeoIP } from "@neko-master/shared";
+import type { PageSize } from "@/lib/stats-utils";
import { UnifiedRuleChainFlow } from "@/components/features/rules/rule-chain-flow";
-import { InsightChartSkeleton, InsightDetailSectionSkeleton, InsightTableSkeleton, InsightThreePanelSkeleton } from "@/components/ui/insight-skeleton";
-import type { RuleStats, DomainStats, IPStats, StatsSummary } from "@neko-master/shared";
+import { InsightChartSkeleton, InsightDetailSectionSkeleton, InsightThreePanelSkeleton } from "@/components/ui/insight-skeleton";
+import type { RuleStats, StatsSummary } from "@neko-master/shared";
interface InteractiveRuleStatsProps {
data?: RuleStats[];
@@ -65,12 +49,7 @@ const CHART_COLORS = [
"#EF4444", "#EC4899", "#6366F1", "#14B8A6", "#F97316",
];
-const PAGE_SIZE_OPTIONS = [10, 20, 50] as const;
-type PageSize = typeof PAGE_SIZE_OPTIONS[number];
-const RULE_DETAIL_WS_MERGE_MS = 5_000;
const RULE_DETAIL_WS_MIN_PUSH_MS = 5_000;
-const EMPTY_DOMAINS: DomainStats[] = [];
-const EMPTY_IPS: IPStats[] = [];
interface RuleChartItem {
name: string;
@@ -95,33 +74,6 @@ interface RuleDomainChartItem {
color: string;
}
-// Domain sort keys
-type DomainSortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections";
-type SortOrder = "asc" | "desc";
-
-// IP sort keys
-type IPSortKey = "ip" | "totalDownload" | "totalUpload" | "totalConnections";
-
-// Color palette for icons
-const ICON_COLORS = [
- { bg: "bg-blue-500", text: "text-white" },
- { bg: "bg-violet-500", text: "text-white" },
- { bg: "bg-emerald-500", text: "text-white" },
- { bg: "bg-amber-500", text: "text-white" },
- { bg: "bg-rose-500", text: "text-white" },
- { bg: "bg-cyan-500", text: "text-white" },
- { bg: "bg-indigo-500", text: "text-white" },
- { bg: "bg-teal-500", text: "text-white" },
-];
-
-const getIPColor = (ip: string) => {
- let hash = 0;
- for (let i = 0; i < ip.length; i++) {
- hash = ip.charCodeAt(i) + ((hash << 5) - hash);
- }
- return ICON_COLORS[Math.abs(hash) % ICON_COLORS.length];
-};
-
// Custom label renderer for bar chart
function renderCustomBarLabel(props: any) {
const { x, y, width, value, height } = props;
@@ -189,13 +141,7 @@ export function InteractiveRuleStats({
const [selectedRule, setSelectedRule] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState("domains");
-
- // Pagination states
- const [domainPage, setDomainPage] = useState(1);
const [detailPageSize, setDetailPageSize] = useState<PageSize>(10);
- const [domainSearch, setDomainSearch] = useState("");
- const [ipPage, setIpPage] = useState(1);
- const [ipSearch, setIpSearch] = useState("");
const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);
// Ref for TOP DOMAINS card to detect container width
@@ -209,25 +155,6 @@ export function InteractiveRuleStats({
enabled: !!activeBackendId,
});
- // Sort states
- const [domainSortKey, setDomainSortKey] = useState<DomainSortKey>("totalDownload");
- const [domainSortOrder, setDomainSortOrder] = useState<SortOrder>("desc");
- const [ipSortKey, setIpSortKey] = useState<IPSortKey>("totalDownload");
- const [ipSortOrder, setIpSortOrder] = useState<SortOrder>("desc");
-
- // Expanded states
- const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
- const [expandedIP, setExpandedIP] = useState<string | null>(null);
- const [mobileDomainDetailsOpen, setMobileDomainDetailsOpen] = useState(false);
- const [mobileDomainDetail, setMobileDomainDetail] = useState<DomainStats | null>(null);
- const [mobileIPDetailsOpen, setMobileIPDetailsOpen] = useState(false);
- const [mobileIPDetail, setMobileIPDetail] = useState<IPStats | null>(null);
- const detailDomainKey = mobileDomainDetailsOpen
- ? (mobileDomainDetail?.domain ?? null)
- : expandedDomain;
- const detailIPKey = mobileIPDetailsOpen ? (mobileIPDetail?.ip ?? null) : expandedIP;
- const mobileIPColor = getIPColor(mobileIPDetail?.ip ?? "0.0.0.0");
-
useEffect(() => {
const media = window.matchMedia("(min-width: 640px)");
const update = () => setShowDomainBarLabels(media.matches);
@@ -317,41 +244,8 @@ export function InteractiveRuleStats({
return new Set(chartData.map(item => item.rawName));
}, [chartData]);
- // Domain sort handler
- const handleDomainSort = (key: DomainSortKey) => {
- if (domainSortKey === key) {
- setDomainSortOrder(domainSortOrder === "asc" ? "desc" : "asc");
- } else {
- setDomainSortKey(key);
- setDomainSortOrder("desc");
- }
- setDomainPage(1);
- };
-
- // IP sort handler
- const handleIPSort = (key: IPSortKey) => {
- if (ipSortKey === key) {
- setIpSortOrder(ipSortOrder === "asc" ? "desc" : "asc");
- } else {
- setIpSortKey(key);
- setIpSortOrder("desc");
- }
- setIpPage(1);
- };
-
- // Toggle expand handlers
- const toggleExpandDomain = (domain: string) => {
- const newExpanded = expandedDomain === domain ? null : domain;
- setExpandedDomain(newExpanded);
- };
-
- const toggleExpandIP = (ip: string) => {
- const newExpanded = expandedIP === ip ? null : ip;
- setExpandedIP(newExpanded);
- };
-
const wsDetailEnabled = autoRefresh && !!activeBackendId && !!selectedRule;
- const { status: wsDetailStatus } = useStatsWebSocket({
+ useStatsWebSocket({
backendId: activeBackendId,
range: detailTimeRange,
minPushIntervalMs: RULE_DETAIL_WS_MIN_PUSH_MS,
@@ -379,38 +273,6 @@ export function InteractiveRuleStats({
}, [selectedRule, activeBackendId, detailTimeRange, queryClient]),
});
- const expandedDomainProxyQuery = useRuleDomainProxyStats({
- rule: selectedRule ?? undefined,
- domain: detailDomainKey ?? undefined,
- activeBackendId,
- range: detailTimeRange,
- enabled: !!detailDomainKey,
- });
-
- const expandedDomainIPDetailsQuery = useRuleDomainIPDetails({
- rule: selectedRule ?? undefined,
- domain: detailDomainKey ?? undefined,
- activeBackendId,
- range: detailTimeRange,
- enabled: !!detailDomainKey,
- });
-
- const expandedIPProxyQuery = useRuleIPProxyStats({
- rule: selectedRule ?? undefined,
- ip: detailIPKey ?? undefined,
- activeBackendId,
- range: detailTimeRange,
- enabled: !!detailIPKey,
- });
-
- const expandedIPDomainDetailsQuery = useRuleIPDomainDetails({
- rule: selectedRule ?? undefined,
- ip: detailIPKey ?? undefined,
- activeBackendId,
- range: detailTimeRange,
- enabled: !!detailIPKey,
- });
-
const { data: ruleDomains = [], isLoading: domainsLoading } = useRuleDomains({
rule: selectedRule,
activeBackendId,
@@ -427,26 +289,6 @@ export function InteractiveRuleStats({
const loading = !!selectedRule && (domainsLoading || ipsLoading) && ruleDomains.length === 0 && ruleIPs.length === 0;
-
- // Sort icon component
- const DomainSortIcon = ({ column }: { column: DomainSortKey }) => {
- if (domainSortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
- return domainSortOrder === "asc" ? (
- <ArrowUp className="ml-1 h-3 w-3 text-primary" />
- ) : (
- <ArrowDown className="ml-1 h-3 w-3 text-primary" />
- );
- };
-
- const IPSortIcon = ({ column }: { column: IPSortKey }) => {
- if (ipSortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
- return ipSortOrder === "asc" ? (
- <ArrowUp className="ml-1 h-3 w-3 text-primary" />
- ) : (
- <ArrowDown className="ml-1 h-3 w-3 text-primary" />
- );
- };
-
// Default select first rule when data loads
useEffect(() => {
if (chartData.length === 0) {
@@ -459,141 +301,16 @@ export function InteractiveRuleStats({
}
}, [chartData, selectedRule]);
- useEffect(() => {
- // Rule changed: reset table controls for a clean context.
- setDomainPage(1);
- setIpPage(1);
- setDomainSearch("");
- setIpSearch("");
- setExpandedDomain(null);
- setExpandedIP(null);
- setMobileDomainDetailsOpen(false);
- setMobileDomainDetail(null);
- setMobileIPDetailsOpen(false);
- setMobileIPDetail(null);
- }, [selectedRule]);
-
- useEffect(() => {
- setExpandedDomain(null);
- setExpandedIP(null);
- setMobileDomainDetailsOpen(false);
- setMobileDomainDetail(null);
- setMobileIPDetailsOpen(false);
- setMobileIPDetail(null);
- }, [activeBackendId]);
-
const handleRuleClick = useCallback((rule: string) => {
if (selectedRule !== rule) {
setSelectedRule(rule);
}
}, [selectedRule]);
- const openMobileDomainDetails = (domain: DomainStats) => {
- setMobileDomainDetail(domain);
- setMobileDomainDetailsOpen(true);
- };
-
- const handleMobileDomainDetailsOpenChange = (open: boolean) => {
- setMobileDomainDetailsOpen(open);
- if (!open) {
- setMobileDomainDetail(null);
- }
- };
-
- const openMobileIPDetails = (ip: IPStats) => {
- setMobileIPDetail(ip);
- setMobileIPDetailsOpen(true);
- };
-
- const handleMobileIPDetailsOpenChange = (open: boolean) => {
- setMobileIPDetailsOpen(open);
- if (!open) {
- setMobileIPDetail(null);
- }
- };
-
const selectedRuleData = useMemo(() => {
return chartData.find(r => r.rawName === selectedRule);
}, [chartData, selectedRule]);
- const isDomainsTab = activeTab === "domains";
- const isIPsTab = activeTab === "ips";
-
- // Filter, sort and paginate domains
- const filteredDomains = useMemo(() => {
- if (!isDomainsTab) return EMPTY_DOMAINS;
- let result = ruleDomains;
- if (domainSearch) {
- result = ruleDomains.filter(d =>
- d.domain.toLowerCase().includes(domainSearch.toLowerCase())
- );
- }
- // Sort
- return [...result].sort((a, b) => {
- const aValue = a[domainSortKey];
- const bValue = b[domainSortKey];
- const modifier = domainSortOrder === "asc" ? 1 : -1;
- if (typeof aValue === "string" && typeof bValue === "string") {
- return aValue.localeCompare(bValue) * modifier;
- }
- return ((aValue as number) - (bValue as number)) * modifier;
- });
- }, [isDomainsTab, ruleDomains, domainSearch, domainSortKey, domainSortOrder]);
-
- const paginatedDomains = useMemo(() => {
- if (!isDomainsTab) return EMPTY_DOMAINS;
- const start = (domainPage - 1) * detailPageSize;
- return filteredDomains.slice(start, start + detailPageSize);
- }, [isDomainsTab, filteredDomains, domainPage, detailPageSize]);
-
- const domainTotalPages = isDomainsTab
- ? Math.max(1, Math.ceil(filteredDomains.length / detailPageSize))
- : 1;
- const totalFilteredDomainTraffic = useMemo(
- () => (isDomainsTab
- ? filteredDomains.reduce((sum, d) => sum + d.totalDownload + d.totalUpload, 0)
- : 0),
- [isDomainsTab, filteredDomains],
- );
-
- // Filter, sort and paginate IPs
- const filteredIPs = useMemo(() => {
- if (!isIPsTab) return EMPTY_IPS;
- let result = ruleIPs;
- if (ipSearch) {
- result = ruleIPs.filter(ip =>
- ip.ip.toLowerCase().includes(ipSearch.toLowerCase()) ||
- ip.domains.some(d => d.toLowerCase().includes(ipSearch.toLowerCase()))
- );
- }
- // Sort
- return [...result].sort((a, b) => {
- const aValue = a[ipSortKey];
- const bValue = b[ipSortKey];
- const modifier = ipSortOrder === "asc" ? 1 : -1;
- if (typeof aValue === "string" && typeof bValue === "string") {
- return aValue.localeCompare(bValue) * modifier;
- }
- return ((aValue as number) - (bValue as number)) * modifier;
- });
- }, [isIPsTab, ruleIPs, ipSearch, ipSortKey, ipSortOrder]);
-
- const paginatedIPs = useMemo(() => {
- if (!isIPsTab) return EMPTY_IPS;
- const start = (ipPage - 1) * detailPageSize;
- return filteredIPs.slice(start, start + detailPageSize);
- }, [isIPsTab, filteredIPs, ipPage, detailPageSize]);
-
- const ipTotalPages = isIPsTab
- ? Math.max(1, Math.ceil(filteredIPs.length / detailPageSize))
- : 1;
- const totalFilteredIPTraffic = useMemo(
- () => (isIPsTab
- ? filteredIPs.reduce((sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0)
- : 0),
- [isIPsTab, filteredIPs],
- );
-
// Chart data
const domainChartData = useMemo<RuleDomainChartItem[]>(() => {
if (!ruleDomains?.length) return [];
@@ -618,32 +335,6 @@ export function InteractiveRuleStats({
? backendT("backendUnavailableHint")
: t("noDataHint");
- const getPageNumbers = (currentPage: number, totalPages: number) => {
- const pages: (number | string)[] = [];
- const maxVisible = 5;
-
- if (totalPages <= maxVisible) {
- for (let i = 1; i <= totalPages; i++) pages.push(i);
- } else {
- if (currentPage <= 3) {
- for (let i = 1; i <= 4; i++) pages.push(i);
- pages.push('...');
- pages.push(totalPages);
- } else if (currentPage >= totalPages - 2) {
- pages.push(1);
- pages.push('...');
- for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
- } else {
- pages.push(1);
- pages.push('...');
- for (let i = currentPage - 1; i <= currentPage + 1; i++) pages.push(i);
- pages.push('...');
- pages.push(totalPages);
- }
- }
- return pages;
- };
-
if (listLoading) {
return (
<div className="space-y-6">
@@ -1059,843 +750,31 @@ export function InteractiveRuleStats({
</TabsList>
<TabsContent value="domains" className="mt-4">
- <Card>
- {/* Header with search */}
- <div className="p-4 border-b border-border/50">
- <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
- <div>
- <h3 className="text-base font-semibold">{domainsT("associatedDomains")}</h3>
- <p className="text-sm text-muted-foreground">
- {filteredDomains.length} {domainsT("domainsCount")}
- </p>
- </div>
- <div className="relative">
- <Input
- placeholder={domainsT("search")}
- value={domainSearch}
- onChange={(e) => {
- setDomainSearch(e.target.value);
- setDomainPage(1);
- }}
- className="h-9 w-full sm:w-[240px] bg-secondary/50 border-0"
- />
- </div>
- </div>
- </div>
-
- <CardContent className="p-0">
- {loading ? (
- <InsightTableSkeleton />
- ) : filteredDomains.length === 0 ? (
- <div className="px-4 py-6">
- <div className="min-h-[180px] rounded-xl border border-dashed border-border/60 bg-card/30 px-4 py-5 flex flex-col items-center justify-center text-center">
- <Globe className="h-5 w-5 text-muted-foreground/70 mb-2" />
- <p className="text-sm font-medium text-muted-foreground">
- {domainSearch ? domainsT("noResults") : domainsT("noData")}
- </p>
- {!domainSearch && (
- <p className="text-xs text-muted-foreground/80 mt-1 max-w-xs">
- {isBackendUnavailable ? backendT("backendUnavailableHint") : domainsT("noDataHint")}
- </p>
- )}
- </div>
- </div>
- ) : (
- <>
- {/* Desktop Table Header */}
- <div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
- <div
- className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleDomainSort("domain")}
- >
- {domainsT("domain")}
- <DomainSortIcon column="domain" />
- </div>
- <div className="col-span-2 flex items-center">
- {domainsT("proxy")}
- </div>
- <div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleDomainSort("totalDownload")}
- >
- {domainsT("download")}
- <DomainSortIcon column="totalDownload" />
- </div>
- <div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleDomainSort("totalUpload")}
- >
- {domainsT("upload")}
- <DomainSortIcon column="totalUpload" />
- </div>
- <div
- className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleDomainSort("totalConnections")}
- >
- {domainsT("conn")}
- <DomainSortIcon column="totalConnections" />
- </div>
- <div className="col-span-2 flex items-center justify-end">
- {domainsT("ipCount")}
- </div>
- </div>
-
- {/* Mobile Sort Bar */}
- <div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
- {([
- { key: "domain" as DomainSortKey, label: domainsT("domain") },
- { key: "totalDownload" as DomainSortKey, label: domainsT("download") },
- { key: "totalUpload" as DomainSortKey, label: domainsT("upload") },
- { key: "totalConnections" as DomainSortKey, label: domainsT("conn") },
- ]).map(({ key, label }) => (
- <button
- key={key}
- className={cn(
- "flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
- domainSortKey === key
- ? "bg-primary/10 text-primary"
- : "text-muted-foreground hover:text-foreground"
- )}
- onClick={() => handleDomainSort(key)}
- >
- {label}
- {domainSortKey === key && (
- domainSortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
- )}
- </button>
- ))}
- </div>
-
- {/* Domain List */}
- <div className="divide-y divide-border/30">
- {(() => {
- return paginatedDomains.map((domain, index) => {
- const domainTraffic = domain.totalDownload + domain.totalUpload;
- const percent =
- totalFilteredDomainTraffic > 0
- ? (domainTraffic / totalFilteredDomainTraffic) * 100
- : 0;
- const isDesktopExpanded = expandedDomain === domain.domain;
- const isMobileActive =
- mobileDomainDetailsOpen && mobileDomainDetail?.domain === domain.domain;
-
- return (
- <div key={domain.domain} className="group">
- {/* Desktop Row */}
- <div
- className={cn(
- "hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",
- isDesktopExpanded && "bg-secondary/10"
- )}
- style={{ animationDelay: `${index * 50}ms` }}
- onClick={() => toggleExpandDomain(domain.domain)}
- >
- {/* Domain with Favicon */}
- <div className="col-span-3 flex items-center gap-3 min-w-0">
- <Favicon domain={domain.domain} size="sm" className="shrink-0" />
- <DomainPreview
- className="flex-1"
- domain={domain.domain}
- unknownLabel={domainsT("unknown")}
- copyLabel={domainsT("copyDomain")}
- copiedLabel={domainsT("copied")}
- />
- </div>
-
- {/* Proxy */}
- <div className="col-span-2 flex items-center gap-1.5 min-w-0">
- <ProxyChainBadge chains={domain.chains} />
- </div>
-
- {/* Download */}
- <div className="col-span-2 text-right tabular-nums text-sm whitespace-nowrap">
- <span className="text-blue-500">{formatBytes(domain.totalDownload)}</span>
- </div>
-
- {/* Upload */}
- <div className="col-span-2 text-right tabular-nums text-sm whitespace-nowrap">
- <span className="text-purple-500">{formatBytes(domain.totalUpload)}</span>
- </div>
-
- {/* Connections */}
- <div className="col-span-1 flex items-center justify-end">
- <span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
- {formatNumber(domain.totalConnections)}
- </span>
- </div>
-
- {/* IP Count - Clickable */}
- <div className="col-span-2 flex items-center justify-end">
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium transition-all",
- isDesktopExpanded
- ? "bg-primary/10 text-primary hover:bg-primary/20"
- : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
- )}
- onClick={(e) => {
- e.stopPropagation();
- toggleExpandDomain(domain.domain);
- }}
- >
- <Server className="h-3 w-3" />
- {domain.ips.length}
- {isDesktopExpanded ? (
- <ChevronUp className="h-3 w-3 ml-0.5" />
- ) : (
- <ChevronDown className="h-3 w-3 ml-0.5" />
- )}
- </Button>
- </div>
- </div>
-
- {/* Mobile Row - Card-style layout */}
- <div
- className={cn(
- "sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
- isMobileActive && "bg-secondary/10"
- )}
- onClick={() => openMobileDomainDetails(domain)}
- >
- {/* Top: Favicon + Domain + Expand */}
- <div className="flex items-center gap-2.5 mb-2">
- <Favicon domain={domain.domain} size="sm" className="shrink-0" />
- <DomainPreview
- className="flex-1"
- domain={domain.domain}
- unknownLabel={domainsT("unknown")}
- copyLabel={domainsT("copyDomain")}
- copiedLabel={domainsT("copied")}
- interactive={false}
- />
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isMobileActive
- ? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground"
- )}
- onClick={(e) => {
- e.stopPropagation();
- openMobileDomainDetails(domain);
- }}
- >
- <Server className="h-3 w-3" />
- {domain.ips.length}
- {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
- </Button>
- </div>
-
- {/* Proxy row */}
- {domain.chains && domain.chains.length > 0 && (
- <div className="flex items-center gap-1.5 mb-2 pl-[30px]">
- <ProxyChainBadge
- chains={domain.chains}
- truncateLabel={false}
- interactive={false}
- />
- </div>
- )}
-
- {/* Bottom: Stats row */}
- <div className="flex items-center justify-between text-xs pl-[30px]">
- <span className="text-blue-500 tabular-nums whitespace-nowrap">↓ {formatBytes(domain.totalDownload)}</span>
- <span className="text-purple-500 tabular-nums whitespace-nowrap">↑ {formatBytes(domain.totalUpload)}</span>
- <span className="px-2 py-0.5 rounded-full bg-secondary text-muted-foreground font-medium">
- {formatNumber(domain.totalConnections)} {domainsT("conn")}
- </span>
- </div>
- </div>
-
- {/* Expanded Details: Proxy Traffic + Associated IPs */}
- {isDesktopExpanded && (
- <div className="hidden sm:block">
- <ExpandReveal>
- <DomainExpandedDetails
- 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"),
- conn: domainsT("conn"),
- }}
- />
- </ExpandReveal>
- </div>
- )}
- </div>
- );
- });
- })()}
- </div>
-
- <Drawer open={mobileDomainDetailsOpen} onOpenChange={handleMobileDomainDetailsOpenChange}>
- <DrawerContent className="sm:hidden">
- <DrawerHeader className="border-b border-border/60 bg-background/95 px-4 pt-2 pb-2">
- <div className="flex items-center gap-2.5 min-w-0 rounded-lg border border-border/60 bg-muted/25 px-3 py-2">
- <Favicon domain={mobileDomainDetail?.domain || ""} size="sm" className="shrink-0" />
- <div className="min-w-0 flex-1">
- <DrawerTitle className="text-left text-[15px] font-semibold leading-5 break-all">
- {mobileDomainDetail?.domain || domainsT("unknown")}
- </DrawerTitle>
- </div>
- <CopyIconButton
- value={mobileDomainDetail?.domain || ""}
- copyLabel={domainsT("copyDomain")}
- copiedLabel={domainsT("copied")}
- disabled={!mobileDomainDetail?.domain}
- />
- </div>
- </DrawerHeader>
- <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">
- {mobileDomainDetail ? (
- <DomainExpandedDetails
- domain={mobileDomainDetail}
- proxyStats={expandedDomainProxyQuery.data ?? []}
- proxyStatsLoading={
- expandedDomainProxyQuery.isLoading &&
- !expandedDomainProxyQuery.data
- }
- ipDetails={expandedDomainIPDetailsQuery.data ?? []}
- ipDetailsLoading={
- expandedDomainIPDetailsQuery.isLoading &&
- !expandedDomainIPDetailsQuery.data
- }
- labels={{
- proxyTraffic: domainsT("proxyTraffic"),
- associatedIPs: domainsT("associatedIPs"),
- conn: domainsT("conn"),
- }}
- showFullProxyChains
- />
- ) : null}
- </div>
- </DrawerContent>
- </Drawer>
-
- {/* Pagination */}
- {filteredDomains.length > 0 && (
- <div className="p-3 border-t border-border/50 bg-secondary/20">
- <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
- <div className="flex items-center gap-2">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
- <Rows3 className="h-4 w-4" />
- <span>{detailPageSize} / {domainsT("page")}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {PAGE_SIZE_OPTIONS.map((size) => (
- <DropdownMenuItem
- key={size}
- onClick={() => {
- setDetailPageSize(size);
- setDomainPage(1);
- setIpPage(1);
- }}
- className={detailPageSize === size ? "bg-primary/10" : ""}
- >
- {size} / {domainsT("page")}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- <div className="flex flex-col sm:flex-row items-center gap-1 sm:gap-2">
- <p className="text-xs text-muted-foreground whitespace-nowrap shrink-0">
- {(domainPage - 1) * detailPageSize + 1}-{Math.min(domainPage * detailPageSize, filteredDomains.length)} / {filteredDomains.length}
- </p>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8"
- onClick={() => setDomainPage(p => Math.max(1, p - 1))}
- disabled={domainPage === 1}
- >
- <ChevronLeft className="h-4 w-4" />
- </Button>
- {getPageNumbers(domainPage, domainTotalPages).map((page, idx) => (
- page === '...' ? (
- <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">...</span>
- ) : (
- <Button
- key={page}
- variant={domainPage === page ? "default" : "ghost"}
- size="sm"
- className="h-8 w-8 px-0 text-xs"
- onClick={() => setDomainPage(page as number)}
- >
- {page}
- </Button>
- )
- ))}
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8"
- onClick={() => setDomainPage(p => Math.min(domainTotalPages, p + 1))}
- disabled={domainPage === domainTotalPages}
- >
- <ChevronRight className="h-4 w-4" />
- </Button>
- </div>
- </div>
- </div>
- </div>
- )}
- </>
- )}
- </CardContent>
- </Card>
+ <DomainStatsTable
+ domains={ruleDomains}
+ loading={loading}
+ pageSize={detailPageSize}
+ onPageSizeChange={setDetailPageSize}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ richExpand
+ ruleName={selectedRule}
+ contextKey={selectedRule}
+ />
</TabsContent>
<TabsContent value="ips" className="mt-4">
- <Card>
- {/* Header with search */}
- <div className="p-4 border-b border-border/50">
- <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
- <div>
- <h3 className="text-base font-semibold">{ipsT("associatedIPs")}</h3>
- <p className="text-sm text-muted-foreground">
- {filteredIPs.length} IPs
- </p>
- </div>
- <div className="relative">
- <Input
- placeholder={ipsT("search")}
- value={ipSearch}
- onChange={(e) => {
- setIpSearch(e.target.value);
- setIpPage(1);
- }}
- className="h-9 w-full sm:w-[240px] bg-secondary/50 border-0"
- />
- </div>
- </div>
- </div>
-
- <CardContent className="p-0">
- {loading ? (
- <InsightTableSkeleton />
- ) : filteredIPs.length === 0 ? (
- <div className="px-4 py-6">
- <div className="min-h-[180px] rounded-xl border border-dashed border-border/60 bg-card/30 px-4 py-5 flex flex-col items-center justify-center text-center">
- <Server className="h-5 w-5 text-muted-foreground/70 mb-2" />
- <p className="text-sm font-medium text-muted-foreground">
- {ipSearch ? ipsT("noResults") : ipsT("noData")}
- </p>
- {!ipSearch && (
- <p className="text-xs text-muted-foreground/80 mt-1 max-w-xs">
- {isBackendUnavailable ? backendT("backendUnavailableHint") : ipsT("noDataHint")}
- </p>
- )}
- </div>
- </div>
- ) : (
- <>
- {/* Desktop Table Header */}
- <div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
- <div
- className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleIPSort("ip")}
- >
- {ipsT("ipAddress")}
- <IPSortIcon column="ip" />
- </div>
- <div className="col-span-2 flex items-center">
- {ipsT("proxy")}
- </div>
- <div className="col-span-2 flex items-center">
- {ipsT("location")}
- </div>
- <div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleIPSort("totalDownload")}
- >
- {ipsT("download")}
- <IPSortIcon column="totalDownload" />
- </div>
- <div
- className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleIPSort("totalUpload")}
- >
- {ipsT("upload")}
- <IPSortIcon column="totalUpload" />
- </div>
- <div
- className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleIPSort("totalConnections")}
- >
- {ipsT("conn")}
- <IPSortIcon column="totalConnections" />
- </div>
- <div className="col-span-1 flex items-center justify-end">
- {ipsT("domainCount")}
- </div>
- </div>
-
- {/* Mobile Sort Bar */}
- <div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
- {([
- { key: "ip" as IPSortKey, label: ipsT("ipAddress") },
- { key: "totalDownload" as IPSortKey, label: ipsT("download") },
- { key: "totalUpload" as IPSortKey, label: ipsT("upload") },
- { key: "totalConnections" as IPSortKey, label: ipsT("conn") },
- ]).map(({ key, label }) => (
- <button
- key={key}
- className={cn(
- "flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
- ipSortKey === key
- ? "bg-primary/10 text-primary"
- : "text-muted-foreground hover:text-foreground"
- )}
- onClick={() => handleIPSort(key)}
- >
- {label}
- {ipSortKey === key && (
- ipSortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
- )}
- </button>
- ))}
- </div>
-
- {/* IP List */}
- <div className="divide-y divide-border/30">
- {(() => {
- return paginatedIPs.map((ip, index) => {
- const ipTraffic = ip.totalDownload + ip.totalUpload;
- const percent =
- totalFilteredIPTraffic > 0
- ? (ipTraffic / totalFilteredIPTraffic) * 100
- : 0;
- const isDesktopExpanded = expandedIP === ip.ip;
- const isMobileActive = mobileIPDetailsOpen && mobileIPDetail?.ip === ip.ip;
- const ipColor = getIPColor(ip.ip);
- const geo = normalizeGeoIP(ip.geoIP);
- const locationName = geo?.countryName || geo?.countryCode || null;
-
- return (
- <div key={ip.ip} className="group">
- {/* Desktop Row */}
- <div
- className={cn(
- "hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer",
- isDesktopExpanded && "bg-secondary/10"
- )}
- style={{ animationDelay: `${index * 50}ms` }}
- onClick={() => toggleExpandIP(ip.ip)}
- >
- {/* IP with Icon */}
- <div className="col-span-3 flex items-center gap-3 min-w-0">
- <div className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
- <Server className="w-3 h-3" />
- </div>
- <code className="text-sm font-mono truncate">{ip.ip}</code>
- </div>
-
- {/* Proxy */}
- <div className="col-span-2 flex items-center gap-1.5 min-w-0">
- <ProxyChainBadge chains={ip.chains} />
- </div>
-
- {/* Location */}
- <div className="col-span-2 flex items-center gap-1.5 min-w-0">
- {locationName ? (
- <>
- <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" title={locationName} />
- <span className="text-xs whitespace-nowrap">{locationName}</span>
- </>
- ) : (
- <span className="text-xs text-muted-foreground">-</span>
- )}
- </div>
-
- {/* Download */}
- <div className="col-span-2 text-right tabular-nums text-sm whitespace-nowrap">
- <span className="text-blue-500">{formatBytes(ip.totalDownload)}</span>
- </div>
-
- {/* Upload */}
- <div className="col-span-1 text-right tabular-nums text-sm whitespace-nowrap">
- <span className="text-purple-500">{formatBytes(ip.totalUpload)}</span>
- </div>
-
- {/* Connections */}
- <div className="col-span-1 flex items-center justify-end">
- <span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
- {formatNumber(ip.totalConnections)}
- </span>
- </div>
-
- {/* Domains Count - Clickable */}
- <div className="col-span-1 flex items-center justify-end">
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium transition-all",
- isDesktopExpanded
- ? "bg-primary/10 text-primary hover:bg-primary/20"
- : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
- )}
- onClick={(e) => {
- e.stopPropagation();
- toggleExpandIP(ip.ip);
- }}
- >
- <Link2 className="h-3 w-3" />
- {ip.domains.length}
- {isDesktopExpanded ? (
- <ChevronUp className="h-3 w-3 ml-0.5" />
- ) : (
- <ChevronDown className="h-3 w-3 ml-0.5" />
- )}
- </Button>
- </div>
- </div>
-
- {/* Mobile Row - Card-style layout */}
- <div
- className={cn(
- "sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
- isMobileActive && "bg-secondary/10"
- )}
- onClick={() => openMobileIPDetails(ip)}
- >
- {/* Top: IP Icon + IP + Location + Expand */}
- <div className="flex items-center gap-2.5 mb-2">
- <div className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
- <Server className="w-3 h-3" />
- </div>
- <div className="flex-1 min-w-0">
- <code className="text-sm font-medium truncate block">{ip.ip}</code>
- {locationName && (
- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
- <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" />
- <span className="truncate">{locationName}</span>
- </div>
- )}
- </div>
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isMobileActive
- ? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground"
- )}
- onClick={(e) => {
- e.stopPropagation();
- openMobileIPDetails(ip);
- }}
- >
- <Link2 className="h-3 w-3" />
- {ip.domains.length}
- {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
- </Button>
- </div>
-
- {/* Proxy row */}
- {ip.chains && ip.chains.length > 0 && (
- <div className="flex items-center gap-1.5 mb-2 pl-[30px]">
- <ProxyChainBadge
- chains={ip.chains}
- truncateLabel={false}
- interactive={false}
- />
- </div>
- )}
-
- {/* Bottom: Stats row */}
- <div className="flex items-center justify-between text-xs pl-[30px]">
- <span className="text-blue-500 tabular-nums whitespace-nowrap">↓ {formatBytes(ip.totalDownload)}</span>
- <span className="text-purple-500 tabular-nums whitespace-nowrap">↑ {formatBytes(ip.totalUpload)}</span>
- <span className="px-2 py-0.5 rounded-full bg-secondary text-muted-foreground font-medium">
- {formatNumber(ip.totalConnections)} {ipsT("conn")}
- </span>
- </div>
- </div>
-
- {/* Expanded Details: Proxy Traffic + Associated Domains */}
- {isDesktopExpanded && (
- <div className="hidden sm:block">
- <ExpandReveal>
- <IPExpandedDetails
- ip={ip}
- proxyStats={expandedIPProxyQuery.data ?? []}
- proxyStatsLoading={
- expandedIPProxyQuery.isLoading &&
- !expandedIPProxyQuery.data
- }
- domainDetails={expandedIPDomainDetailsQuery.data ?? []}
- domainDetailsLoading={
- expandedIPDomainDetailsQuery.isLoading &&
- !expandedIPDomainDetailsQuery.data
- }
- associatedDomainsIcon="link"
- labels={{
- proxyTraffic: ipsT("proxyTraffic"),
- associatedDomains: ipsT("associatedDomains"),
- conn: ipsT("conn"),
- }}
- />
- </ExpandReveal>
- </div>
- )}
- </div>
- );
- });
- })()}
- </div>
-
- <Drawer open={mobileIPDetailsOpen} onOpenChange={handleMobileIPDetailsOpenChange}>
- <DrawerContent className="sm:hidden">
- <DrawerHeader className="border-b border-border/60 bg-background/95 px-4 pt-2 pb-2">
- <div className="flex items-center gap-2.5 min-w-0 rounded-lg border border-border/60 bg-muted/25 px-3 py-2">
- <div
- className={cn(
- "w-5 h-5 rounded-md flex items-center justify-center shrink-0",
- mobileIPColor.bg,
- mobileIPColor.text,
- )}
- >
- <Server className="w-3 h-3" />
- </div>
- <div className="min-w-0 flex-1">
- <DrawerTitle className="text-left font-mono text-[15px] font-semibold leading-5 break-all">
- {mobileIPDetail?.ip || ipsT("unknownIP")}
- </DrawerTitle>
- </div>
- <CopyIconButton
- value={mobileIPDetail?.ip || ""}
- copyLabel={ipsT("copyIP")}
- copiedLabel={ipsT("copied")}
- disabled={!mobileIPDetail?.ip}
- />
- </div>
- </DrawerHeader>
- <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">
- {mobileIPDetail ? (
- <IPExpandedDetails
- ip={mobileIPDetail}
- proxyStats={expandedIPProxyQuery.data ?? []}
- proxyStatsLoading={
- expandedIPProxyQuery.isLoading &&
- !expandedIPProxyQuery.data
- }
- domainDetails={expandedIPDomainDetailsQuery.data ?? []}
- domainDetailsLoading={
- expandedIPDomainDetailsQuery.isLoading &&
- !expandedIPDomainDetailsQuery.data
- }
- associatedDomainsIcon="link"
- labels={{
- proxyTraffic: ipsT("proxyTraffic"),
- associatedDomains: ipsT("associatedDomains"),
- conn: ipsT("conn"),
- }}
- showFullProxyChains
- disableNestedInteractions
- showIPLookupDetails
- />
- ) : null}
- </div>
- </DrawerContent>
- </Drawer>
-
- {/* Pagination */}
- {filteredIPs.length > 0 && (
- <div className="p-3 border-t border-border/50 bg-secondary/20">
- <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
- <div className="flex items-center gap-2">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
- <Rows3 className="h-4 w-4" />
- <span>{detailPageSize} / {ipsT("page")}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {PAGE_SIZE_OPTIONS.map((size) => (
- <DropdownMenuItem
- key={size}
- onClick={() => {
- setDetailPageSize(size);
- setDomainPage(1);
- setIpPage(1);
- }}
- className={detailPageSize === size ? "bg-primary/10" : ""}
- >
- {size} / {ipsT("page")}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- <div className="flex flex-col sm:flex-row items-center gap-1 sm:gap-2">
- <p className="text-xs text-muted-foreground whitespace-nowrap shrink-0">
- {(ipPage - 1) * detailPageSize + 1}-{Math.min(ipPage * detailPageSize, filteredIPs.length)} / {filteredIPs.length}
- </p>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8"
- onClick={() => setIpPage(p => Math.max(1, p - 1))}
- disabled={ipPage === 1}
- >
- <ChevronLeft className="h-4 w-4" />
- </Button>
- {getPageNumbers(ipPage, ipTotalPages).map((page, idx) => (
- page === '...' ? (
- <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">...</span>
- ) : (
- <Button
- key={page}
- variant={ipPage === page ? "default" : "ghost"}
- size="sm"
- className="h-8 w-8 px-0 text-xs"
- onClick={() => setIpPage(page as number)}
- >
- {page}
- </Button>
- )
- ))}
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8"
- onClick={() => setIpPage(p => Math.min(ipTotalPages, p + 1))}
- disabled={ipPage === ipTotalPages}
- >
- <ChevronRight className="h-4 w-4" />
- </Button>
- </div>
- </div>
- </div>
- </div>
- )}
- </>
- )}
- </CardContent>
- </Card>
+ <IPStatsTable
+ ips={ruleIPs}
+ loading={loading}
+ pageSize={detailPageSize}
+ onPageSizeChange={setDetailPageSize}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ richExpand
+ ruleName={selectedRule}
+ contextKey={selectedRule}
+ />
</TabsContent>
</Tabs>
) : (
diff --git a/apps/web/components/features/stats/table/domain-stats-table.tsx b/apps/web/components/features/stats/table/domain-stats-table.tsx
index 6aa42da..5790152 100644
--- a/apps/web/components/features/stats/table/domain-stats-table.tsx
+++ b/apps/web/components/features/stats/table/domain-stats-table.tsx
@@ -23,7 +23,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { formatBytes, formatNumber } from "@/lib/utils";
+import { formatBytes, formatDuration, formatNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
@@ -38,7 +38,12 @@ import { DomainPreview } from "@/components/features/domains/domain-preview";
import { DomainExpandedDetails } from "./expanded-details";
import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";
import { ExpandReveal } from "@/components/ui/expand-reveal";
-import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";
+import {
+ Drawer,
+ DrawerContent,
+ DrawerHeader,
+ DrawerTitle,
+} from "@/components/ui/drawer";
import { InsightTableSkeleton } from "@/components/ui/insight-skeleton";
import {
PAGE_SIZE_OPTIONS,
@@ -48,8 +53,11 @@ import {
type SortOrder,
} from "@/lib/stats-utils";
import type { DomainStats } from "@neko-master/shared";
+
const DETAIL_QUERY_STALE_MS = 30_000;
+type DomainTableMode = "local" | "remote";
+
interface DomainStatsTableProps {
domains: DomainStats[];
loading?: boolean;
@@ -64,6 +72,18 @@ interface DomainStatsTableProps {
richExpand?: boolean;
showProxyColumn?: boolean;
showProxyTrafficInExpand?: boolean;
+ showLastSeenColumn?: boolean;
+ mode?: DomainTableMode;
+ searchValue?: string;
+ onSearchChange?: (value: string) => void;
+ sortKeyValue?: DomainSortKey;
+ sortOrderValue?: SortOrder;
+ onSortChange?: (key: DomainSortKey) => void;
+ pageValue?: number;
+ totalValue?: number;
+ onPageChange?: (page: number) => void;
+ ruleName?: string;
+ contextKey?: string | number;
}
export function DomainStatsTable({
@@ -80,19 +100,39 @@ export function DomainStatsTable({
richExpand = false,
showProxyColumn = true,
showProxyTrafficInExpand = true,
+ showLastSeenColumn = false,
+ mode = "local",
+ searchValue,
+ onSearchChange,
+ sortKeyValue,
+ sortOrderValue,
+ onSortChange,
+ pageValue,
+ totalValue,
+ onPageChange,
+ ruleName,
+ contextKey,
}: DomainStatsTableProps) {
const t = useTranslations("domains");
const detailTimeRange = useStableTimeRange(timeRange);
+ const isRemoteMode = mode === "remote";
- const [page, setPage] = useState(1);
+ const [internalPage, setInternalPage] = useState(1);
const [internalPageSize, setInternalPageSize] = useState<PageSize>(10);
- const pageSize = controlledPageSize ?? internalPageSize;
- const [search, setSearch] = useState("");
- const [sortKey, setSortKey] = useState<DomainSortKey>("totalDownload");
- const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
+ const [internalSearch, setInternalSearch] = useState("");
+ const [internalSortKey, setInternalSortKey] =
+ useState<DomainSortKey>("totalDownload");
+ const [internalSortOrder, setInternalSortOrder] = useState<SortOrder>("desc");
const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);
- const [mobileDetailDomain, setMobileDetailDomain] = useState<DomainStats | null>(null);
+ const [mobileDetailDomain, setMobileDetailDomain] =
+ useState<DomainStats | null>(null);
+
+ const pageSize = controlledPageSize ?? internalPageSize;
+ const page = isRemoteMode ? pageValue ?? 1 : internalPage;
+ const search = isRemoteMode ? searchValue ?? "" : internalSearch;
+ const sortKey = isRemoteMode ? sortKeyValue ?? "totalDownload" : internalSortKey;
+ const sortOrder = isRemoteMode ? sortOrderValue ?? "desc" : internalSortOrder;
const detailDomainKey = mobileDetailsOpen
? (mobileDetailDomain?.domain ?? null)
: expandedDomain;
@@ -102,33 +142,49 @@ export function DomainStatsTable({
setExpandedDomain(null);
setMobileDetailsOpen(false);
setMobileDetailDomain(null);
- }, [activeBackendId, sourceIP, sourceChain, richExpand]);
+ }, [activeBackendId, sourceIP, sourceChain, richExpand, ruleName, contextKey]);
useEffect(() => {
- setPage(1);
- }, [pageSize]);
+ if (!isRemoteMode) {
+ setInternalPage(1);
+ setInternalSearch("");
+ setInternalSortKey("totalDownload");
+ setInternalSortOrder("desc");
+ }
+ }, [contextKey, isRemoteMode]);
- const setEffectivePageSize = (size: PageSize) => {
- if (onPageSizeChange) {
- onPageSizeChange(size);
- return;
+ useEffect(() => {
+ if (!isRemoteMode) {
+ setInternalPage(1);
}
- setInternalPageSize(size);
- };
+ }, [pageSize, isRemoteMode]);
const expandedDomainProxyQuery = useQuery({
- queryKey: getDomainProxyStatsQueryKey(detailDomainKey, activeBackendId, detailTimeRange, {
- sourceIP,
- sourceChain,
- }),
- queryFn: () =>
- api.getDomainProxyStats(
- detailDomainKey!,
- activeBackendId,
- detailTimeRange,
+ queryKey: getDomainProxyStatsQueryKey(
+ detailDomainKey,
+ activeBackendId,
+ detailTimeRange,
+ {
sourceIP,
sourceChain,
- ),
+ rule: ruleName,
+ },
+ ),
+ queryFn: () =>
+ ruleName
+ ? api.getRuleDomainProxyStats(
+ ruleName,
+ detailDomainKey!,
+ activeBackendId,
+ detailTimeRange,
+ )
+ : api.getDomainProxyStats(
+ detailDomainKey!,
+ activeBackendId,
+ detailTimeRange,
+ sourceIP,
+ sourceChain,
+ ),
enabled: richExpand && !!activeBackendId && !!detailDomainKey,
staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
@@ -137,22 +193,36 @@ export function DomainStatsTable({
backendId: activeBackendId ?? null,
sourceIP: sourceIP ?? "",
sourceChain: sourceChain ?? "",
+ rule: ruleName ?? "",
}),
});
const expandedDomainIPDetailsQuery = useQuery({
- queryKey: getDomainIPDetailsQueryKey(detailDomainKey, activeBackendId, detailTimeRange, {
- sourceIP,
- sourceChain,
- }),
- queryFn: () =>
- api.getDomainIPDetails(
- detailDomainKey!,
- activeBackendId,
- detailTimeRange,
+ queryKey: getDomainIPDetailsQueryKey(
+ detailDomainKey,
+ activeBackendId,
+ detailTimeRange,
+ {
sourceIP,
sourceChain,
- ),
+ rule: ruleName,
+ },
+ ),
+ queryFn: () =>
+ ruleName
+ ? api.getRuleDomainIPDetails(
+ ruleName,
+ detailDomainKey!,
+ activeBackendId,
+ detailTimeRange,
+ )
+ : api.getDomainIPDetails(
+ detailDomainKey!,
+ activeBackendId,
+ detailTimeRange,
+ sourceIP,
+ sourceChain,
+ ),
enabled: richExpand && !!activeBackendId && !!detailDomainKey,
staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
@@ -161,17 +231,55 @@ export function DomainStatsTable({
backendId: activeBackendId ?? null,
sourceIP: sourceIP ?? "",
sourceChain: sourceChain ?? "",
+ rule: ruleName ?? "",
}),
});
+ const setEffectivePage = (nextPage: number) => {
+ if (isRemoteMode) {
+ onPageChange?.(nextPage);
+ return;
+ }
+ setInternalPage(nextPage);
+ };
+
+ const setEffectivePageSize = (size: PageSize) => {
+ if (onPageSizeChange) {
+ onPageSizeChange(size);
+ } else {
+ setInternalPageSize(size);
+ }
+
+ if (isRemoteMode) {
+ onPageChange?.(1);
+ } else {
+ setInternalPage(1);
+ }
+ };
+
+ const handleSearchInputChange = (value: string) => {
+ if (isRemoteMode) {
+ onSearchChange?.(value);
+ onPageChange?.(1);
+ return;
+ }
+ setInternalSearch(value);
+ setInternalPage(1);
+ };
+
const handleSort = (key: DomainSortKey) => {
- if (sortKey === key) {
- setSortOrder(sortOrder === "asc" ? "desc" : "asc");
+ if (isRemoteMode) {
+ onSortChange?.(key);
+ return;
+ }
+
+ if (internalSortKey === key) {
+ setInternalSortOrder(internalSortOrder === "asc" ? "desc" : "asc");
} else {
- setSortKey(key);
- setSortOrder("desc");
+ setInternalSortKey(key);
+ setInternalSortOrder("desc");
}
- setPage(1);
+ setInternalPage(1);
};
const toggleExpand = (domain: string) => {
@@ -192,7 +300,9 @@ export function DomainStatsTable({
};
const SortIcon = ({ column }: { column: DomainSortKey }) => {
- if (sortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
+ if (sortKey !== column) {
+ return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
+ }
return sortOrder === "asc" ? (
<ArrowUp className="ml-1 h-3 w-3 text-primary" />
) : (
@@ -201,6 +311,10 @@ export function DomainStatsTable({
};
const filteredDomains = useMemo(() => {
+ if (isRemoteMode) {
+ return domains;
+ }
+
let result = [...domains];
if (search) {
const lower = search.toLowerCase();
@@ -215,15 +329,25 @@ export function DomainStatsTable({
return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
});
return result;
- }, [domains, search, sortKey, sortOrder]);
+ }, [domains, isRemoteMode, search, sortKey, sortOrder]);
- const paginatedDomains = useMemo(() => {
+ const visibleDomains = useMemo(() => {
+ if (isRemoteMode) {
+ return domains;
+ }
const start = (page - 1) * pageSize;
return filteredDomains.slice(start, start + pageSize);
- }, [filteredDomains, page, pageSize]);
+ }, [domains, filteredDomains, isRemoteMode, page, pageSize]);
- const totalPages = Math.ceil(filteredDomains.length / pageSize);
+ const totalItems = isRemoteMode ? totalValue ?? domains.length : filteredDomains.length;
+ const totalPages =
+ totalItems > 0 ? Math.max(1, Math.ceil(totalItems / pageSize)) : 0;
const domainColumnClass = showProxyColumn ? "col-span-3" : "col-span-5";
+ const uploadColumnClass = showLastSeenColumn ? "col-span-1" : "col-span-2";
+ const ipCountColumnClass = "col-span-2";
+ const hasRows = visibleDomains.length > 0;
+ const startIndex = totalItems === 0 ? 0 : Math.min((page - 1) * pageSize + 1, totalItems);
+ const endIndex = Math.min(page * pageSize, totalItems);
return (
<Card>
@@ -231,19 +355,18 @@ export function DomainStatsTable({
<div className="p-4 border-b border-border/50">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<div>
- <h3 className="text-base font-semibold">{title || t("associatedDomains")}</h3>
+ <h3 className="text-base font-semibold">
+ {title || t("associatedDomains")}
+ </h3>
<p className="text-sm text-muted-foreground">
- {filteredDomains.length} {t("domainsCount")}
+ {totalItems} {t("domainsCount")}
</p>
</div>
<div className="relative">
<Input
placeholder={t("search")}
value={search}
- onChange={(e) => {
- setSearch(e.target.value);
- setPage(1);
- }}
+ onChange={(e) => handleSearchInputChange(e.target.value)}
className="h-9 w-full sm:w-[240px] bg-secondary/50 border-0"
/>
</div>
@@ -254,7 +377,7 @@ export function DomainStatsTable({
<CardContent className="p-0">
{loading ? (
<InsightTableSkeleton />
- ) : filteredDomains.length === 0 ? (
+ ) : !hasRows ? (
<div className="text-center py-12 text-muted-foreground">
{search ? t("noResults") : t("noData")}
</div>
@@ -282,7 +405,10 @@ export function DomainStatsTable({
<SortIcon column="totalDownload" />
</div>
<div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
+ className={cn(
+ uploadColumnClass,
+ "flex items-center justify-end cursor-pointer hover:text-foreground transition-colors",
+ )}
onClick={() => handleSort("totalUpload")}
>
{t("upload")}
@@ -295,7 +421,19 @@ export function DomainStatsTable({
{t("conn")}
<SortIcon column="totalConnections" />
</div>
- <div className="col-span-2 flex items-center justify-end">{t("ipCount")}</div>
+ {showLastSeenColumn && (
+ <div className="col-span-1 flex items-center justify-end">
+ {t("last")}
+ </div>
+ )}
+ <div
+ className={cn(
+ ipCountColumnClass,
+ "flex items-center justify-end",
+ )}
+ >
+ {t("ipCount")}
+ </div>
</div>
<div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
@@ -303,7 +441,10 @@ export function DomainStatsTable({
{ key: "domain" as DomainSortKey, label: t("domain") },
{ key: "totalDownload" as DomainSortKey, label: t("download") },
{ key: "totalUpload" as DomainSortKey, label: t("upload") },
- { key: "totalConnections" as DomainSortKey, label: t("conn") },
+ {
+ key: "totalConnections" as DomainSortKey,
+ label: t("conn"),
+ },
]).map(({ key, label }) => (
<button
key={key}
@@ -317,13 +458,17 @@ export function DomainStatsTable({
>
{label}
{sortKey === key &&
- (sortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />)}
+ (sortOrder === "asc" ? (
+ <ArrowUp className="h-3 w-3" />
+ ) : (
+ <ArrowDown className="h-3 w-3" />
+ ))}
</button>
))}
</div>
<div className="divide-y divide-border/30">
- {paginatedDomains.map((domain, index) => {
+ {visibleDomains.map((domain, index) => {
const isDesktopExpanded = expandedDomain === domain.domain;
const isMobileActive =
mobileDetailsOpen && mobileDetailDomain?.domain === domain.domain;
@@ -359,7 +504,12 @@ export function DomainStatsTable({
<span className="text-blue-500">{formatBytes(domain.totalDownload)}</span>
</div>
- <div className="col-span-2 text-right tabular-nums text-sm whitespace-nowrap">
+ <div
+ className={cn(
+ uploadColumnClass,
+ "text-right tabular-nums text-sm whitespace-nowrap",
+ )}
+ >
<span className="text-purple-500">{formatBytes(domain.totalUpload)}</span>
</div>
@@ -369,7 +519,20 @@ export function DomainStatsTable({
</span>
</div>
- <div className="col-span-2 flex items-center justify-end">
+ {showLastSeenColumn && (
+ <div className="col-span-1 text-right">
+ <p className="text-xs text-muted-foreground">
+ {formatDuration(domain.lastSeen)}
+ </p>
+ </div>
+ )}
+
+ <div
+ className={cn(
+ ipCountColumnClass,
+ "flex items-center justify-end",
+ )}
+ >
<Button
variant="ghost"
size="sm"
@@ -417,7 +580,9 @@ export function DomainStatsTable({
size="sm"
className={cn(
"h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isMobileActive ? "bg-primary/10 text-primary" : "bg-secondary/50 text-muted-foreground",
+ isMobileActive
+ ? "bg-primary/10 text-primary"
+ : "bg-secondary/50 text-muted-foreground",
)}
onClick={(e) => {
e.stopPropagation();
@@ -426,7 +591,11 @@ export function DomainStatsTable({
>
<Server className="h-3 w-3" />
{domain.ips?.length || 0}
- {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
+ {isMobileActive ? (
+ <ChevronUp className="h-3 w-3" />
+ ) : (
+ <ChevronDown className="h-3 w-3" />
+ )}
</Button>
</div>
@@ -441,8 +610,12 @@ export function DomainStatsTable({
)}
<div className="flex items-center justify-between text-xs pl-[30px]">
- <span className="text-blue-500 tabular-nums whitespace-nowrap">↓ {formatBytes(domain.totalDownload)}</span>
- <span className="text-purple-500 tabular-nums whitespace-nowrap">↑ {formatBytes(domain.totalUpload)}</span>
+ <span className="text-blue-500 tabular-nums whitespace-nowrap">
+ ↓ {formatBytes(domain.totalDownload)}
+ </span>
+ <span className="text-purple-500 tabular-nums whitespace-nowrap">
+ ↑ {formatBytes(domain.totalUpload)}
+ </span>
<span className="px-2 py-0.5 rounded-full bg-secondary text-muted-foreground font-medium">
{formatNumber(domain.totalConnections)} {t("conn")}
</span>
@@ -526,13 +699,17 @@ export function DomainStatsTable({
</DrawerContent>
</Drawer>
- {filteredDomains.length > 0 && (
+ {totalItems > 0 && (
<div className="p-3 border-t border-border/50 bg-secondary/20">
<div className="flex flex-col sm:flex-row items-center justify-between gap-3">
<div className="flex items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 gap-1.5 text-muted-foreground hover:text-foreground"
+ >
<Rows3 className="h-4 w-4" />
<span>{pageSize} / {t("page")}</span>
</Button>
@@ -541,10 +718,7 @@ export function DomainStatsTable({
{PAGE_SIZE_OPTIONS.map((size) => (
<DropdownMenuItem
key={size}
- onClick={() => {
- setEffectivePageSize(size);
- setPage(1);
- }}
+ onClick={() => setEffectivePageSize(size)}
className={pageSize === size ? "bg-primary/10" : ""}
>
{size} / {t("page")}
@@ -555,15 +729,15 @@ export function DomainStatsTable({
</div>
<div className="flex flex-col sm:flex-row items-center gap-1 sm:gap-2">
<p className="text-xs text-muted-foreground whitespace-nowrap shrink-0">
- {(page - 1) * pageSize + 1}-{Math.min(page * pageSize, filteredDomains.length)} / {filteredDomains.length}
+ {startIndex}-{endIndex} / {totalItems}
</p>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setPage((p) => Math.max(1, p - 1))}
- disabled={page === 1}
+ onClick={() => setEffectivePage(Math.max(1, page - 1))}
+ disabled={page <= 1}
>
<ChevronLeft className="h-4 w-4" />
</Button>
@@ -578,7 +752,7 @@ export function DomainStatsTable({
variant={page === p ? "default" : "ghost"}
size="sm"
className="h-8 w-8 px-0 text-xs"
- onClick={() => setPage(p as number)}
+ onClick={() => setEffectivePage(p as number)}
>
{p}
</Button>
@@ -588,8 +762,8 @@ export function DomainStatsTable({
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
- disabled={page === totalPages}
+ onClick={() => setEffectivePage(Math.min(totalPages, page + 1))}
+ disabled={page >= totalPages}
>
<ChevronRight className="h-4 w-4" />
</Button>
diff --git a/apps/web/components/features/stats/table/domain-table.tsx b/apps/web/components/features/stats/table/domain-table.tsx
index 0948c21..8dd8023 100644
--- a/apps/web/components/features/stats/table/domain-table.tsx
+++ b/apps/web/components/features/stats/table/domain-table.tsx
@@ -1,36 +1,19 @@
"use client";
import { useState, useEffect, useRef, useCallback } from "react";
-import { Search, ArrowUpDown, ArrowDown, ArrowUp, ChevronLeft, ChevronRight, Rows3, ChevronDown, ChevronUp, Server } 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 { InsightTableSkeleton } from "@/components/ui/insight-skeleton";
-import { Favicon } from "@/components/common/favicon";
-import { CopyIconButton } from "@/components/common/copy-icon-button";
-import { DomainPreview } from "@/components/features/domains/domain-preview";
-import { DomainExpandedDetails } from "@/components/features/stats/table/expanded-details";
-import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";
-import { ExpandReveal } from "@/components/ui/expand-reveal";
-import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";
-import { formatBytes, formatNumber, formatDuration } from "@/lib/utils";
-import { cn } from "@/lib/utils";
-import type { DomainStats, StatsSummary } from "@neko-master/shared";
+import { useTranslations } from "next-intl";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { useStatsWebSocket } from "@/lib/websocket";
+import { getDomainsQueryKey } from "@/lib/stats-query-keys";
import {
- getDomainIPDetailsQueryKey,
- getDomainProxyStatsQueryKey,
- getDomainsQueryKey,
-} from "@/lib/stats-query-keys";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
+ type DomainSortKey,
+ type PageSize,
+ type SortOrder,
+} from "@/lib/stats-utils";
+import { DomainStatsTable } from "./domain-stats-table";
+import type { DomainStats, StatsSummary } from "@neko-master/shared";
interface DomainsTableProps {
activeBackendId?: number;
@@ -40,12 +23,8 @@ interface DomainsTableProps {
onPageSizeChange?: (size: PageSize) => void;
}
-type SortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections" | "lastSeen";
-type SortOrder = "asc" | "desc";
-
-import { PAGE_SIZE_OPTIONS, type PageSize } from "@/lib/stats-utils";
-const DETAIL_QUERY_STALE_MS = 30_000;
const DOMAINS_WS_MIN_PUSH_MS = 3_000;
+
type DomainsPageQueryState = {
offset: number;
limit: number;
@@ -53,6 +32,7 @@ type DomainsPageQueryState = {
sortOrder?: "asc" | "desc";
search?: string;
};
+
type DomainsPageState = {
data: DomainStats[];
total: number;
@@ -69,29 +49,33 @@ export function DomainsTable({
}: DomainsTableProps) {
const t = useTranslations("domains");
const stableTimeRange = useStableTimeRange(timeRange);
- const detailTimeRange = stableTimeRange;
+
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
- const [sortKey, setSortKey] = useState<SortKey>("totalDownload");
+ const [sortKey, setSortKey] = useState<DomainSortKey>("totalDownload");
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
const [currentPage, setCurrentPage] = useState(1);
const [internalPageSize, setInternalPageSize] = useState<PageSize>(10);
- const pageSize = controlledPageSize ?? internalPageSize;
- const setEffectivePageSize = useCallback((size: PageSize) => {
- if (onPageSizeChange) {
- onPageSizeChange(size);
- return;
- }
- setInternalPageSize(size);
- }, [onPageSizeChange]);
- const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
- const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);
- const [mobileDetailDomain, setMobileDetailDomain] = useState<DomainStats | null>(null);
- const [wsDomainsPage, setWsDomainsPage] = useState<DomainsPageState | null>(null);
+ const [wsDomainsPage, setWsDomainsPage] = useState<DomainsPageState | null>(
+ null,
+ );
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const pageSize = controlledPageSize ?? internalPageSize;
const pageOffset = (currentPage - 1) * pageSize;
const wsPageSearch = debouncedSearch || undefined;
+ const setEffectivePageSize = useCallback(
+ (size: PageSize) => {
+ if (onPageSizeChange) {
+ onPageSizeChange(size);
+ } else {
+ setInternalPageSize(size);
+ }
+ },
+ [onPageSizeChange],
+ );
+
const wsPageEnabled = autoRefresh && !!activeBackendId;
const { status: wsPageStatus } = useStatsWebSocket({
backendId: activeBackendId,
@@ -105,23 +89,27 @@ export function DomainsTable({
domainsPageSearch: wsPageSearch,
trackLastMessage: false,
enabled: wsPageEnabled,
- onMessage: useCallback((stats: StatsSummary) => {
- const query = stats.domainsPageQuery;
- const page = stats.domainsPage;
- if (!page || !query) return;
- setWsDomainsPage({
- data: page.data,
- total: page.total,
- query: {
- offset: query.offset,
- limit: query.limit,
- sortBy: query.sortBy || "totalDownload",
- sortOrder: query.sortOrder === "asc" ? "asc" : "desc",
- search: query.search || undefined,
- },
- backendId: activeBackendId,
- });
- }, [activeBackendId]),
+ onMessage: useCallback(
+ (stats: StatsSummary) => {
+ const query = stats.domainsPageQuery;
+ const page = stats.domainsPage;
+ if (!page || !query) return;
+
+ setWsDomainsPage({
+ data: page.data,
+ total: page.total,
+ query: {
+ offset: query.offset,
+ limit: query.limit,
+ sortBy: query.sortBy || "totalDownload",
+ sortOrder: query.sortOrder === "asc" ? "asc" : "desc",
+ search: query.search || undefined,
+ },
+ backendId: activeBackendId,
+ });
+ },
+ [activeBackendId],
+ ),
});
const wsDomainsPageMatchesCurrent =
@@ -133,20 +121,23 @@ export function DomainsTable({
(wsDomainsPage.query.sortOrder || "desc") === sortOrder &&
(wsDomainsPage.query.search || undefined) === wsPageSearch;
- // Debounce search input
useEffect(() => {
debounceRef.current = setTimeout(() => {
setDebouncedSearch(search);
- setCurrentPage(1);
}, 300);
- return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
+
+ return () => {
+ if (debounceRef.current) {
+ clearTimeout(debounceRef.current);
+ }
+ };
}, [search]);
const domainsQuery = useQuery({
queryKey: getDomainsQueryKey(
activeBackendId,
{
- offset: (currentPage - 1) * pageSize,
+ offset: pageOffset,
limit: pageSize,
sortBy: sortKey,
sortOrder,
@@ -156,7 +147,7 @@ export function DomainsTable({
),
queryFn: () =>
api.getDomains(activeBackendId, {
- offset: (currentPage - 1) * pageSize,
+ offset: pageOffset,
limit: pageSize,
sortBy: sortKey,
sortOrder,
@@ -172,523 +163,44 @@ export function DomainsTable({
const hasWsDomainsPage =
wsPageEnabled && wsPageStatus === "connected" && wsDomainsPageMatchesCurrent;
- const data = hasWsDomainsPage ? wsDomainsPage!.data : domainsQuery.data?.data ?? [];
- const total = hasWsDomainsPage ? wsDomainsPage!.total : domainsQuery.data?.total ?? 0;
+ const data = hasWsDomainsPage ? wsDomainsPage.data : domainsQuery.data?.data ?? [];
+ const total = hasWsDomainsPage ? wsDomainsPage.total : domainsQuery.data?.total ?? 0;
const loading = !hasWsDomainsPage && domainsQuery.isLoading && !domainsQuery.data;
- const detailDomainKey = mobileDetailsOpen
- ? (mobileDetailDomain?.domain ?? null)
- : expandedDomain;
-
- useEffect(() => {
- // Backend switch means a different data universe, collapse safely.
- setExpandedDomain(null);
- setMobileDetailsOpen(false);
- setMobileDetailDomain(null);
- }, [activeBackendId]);
-
- const expandedDomainProxyQuery = useQuery({
- queryKey: getDomainProxyStatsQueryKey(detailDomainKey, activeBackendId, detailTimeRange),
- queryFn: () => api.getDomainProxyStats(detailDomainKey!, activeBackendId, detailTimeRange),
- enabled: !!activeBackendId && !!detailDomainKey,
- staleTime: DETAIL_QUERY_STALE_MS,
- placeholderData: (previousData, previousQuery) => {
- const prevKey = (previousQuery?.queryKey?.[2] ?? null) as
- | { domain?: string; backendId?: number | null }
- | null;
- if (!prevKey) return undefined;
- if (prevKey.domain !== (detailDomainKey ?? "")) return undefined;
- if (prevKey.backendId !== (activeBackendId ?? null)) return undefined;
- return previousData;
- },
- });
-
- const expandedDomainIPDetailsQuery = useQuery({
- queryKey: getDomainIPDetailsQueryKey(detailDomainKey, activeBackendId, detailTimeRange),
- queryFn: () => api.getDomainIPDetails(detailDomainKey!, activeBackendId, detailTimeRange),
- enabled: !!activeBackendId && !!detailDomainKey,
- staleTime: DETAIL_QUERY_STALE_MS,
- placeholderData: (previousData, previousQuery) => {
- const prevKey = (previousQuery?.queryKey?.[2] ?? null) as
- | { domain?: string; backendId?: number | null }
- | null;
- if (!prevKey) return undefined;
- if (prevKey.domain !== (detailDomainKey ?? "")) return undefined;
- if (prevKey.backendId !== (activeBackendId ?? null)) return undefined;
- return previousData;
- },
- });
-
- const handleSort = (key: SortKey) => {
- if (sortKey === key) {
- setSortOrder(sortOrder === "asc" ? "desc" : "asc");
- } else {
- setSortKey(key);
- setSortOrder("desc");
- }
- setCurrentPage(1);
- };
- const totalPages = Math.ceil(total / pageSize);
-
- const handleSearchChange = (value: string) => {
- setSearch(value);
- };
-
- const handlePageSizeChange = (size: PageSize) => {
- setEffectivePageSize(size);
- setCurrentPage(1);
- };
-
- const toggleExpand = (domain: string) => {
- const newExpanded = expandedDomain === domain ? null : domain;
- setExpandedDomain(newExpanded);
- };
-
- const openMobileDetails = (domain: DomainStats) => {
- setMobileDetailDomain(domain);
- setMobileDetailsOpen(true);
- };
-
- const handleMobileDetailsOpenChange = (open: boolean) => {
- setMobileDetailsOpen(open);
- if (!open) {
- setMobileDetailDomain(null);
- }
- };
-
- const SortIcon = ({ column }: { column: SortKey }) => {
- if (sortKey !== column) return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
- return sortOrder === "asc" ? (
- <ArrowUp className="ml-1 h-3 w-3 text-primary" />
- ) : (
- <ArrowDown className="ml-1 h-3 w-3 text-primary" />
- );
- };
-
- // Generate page numbers to display
- const getPageNumbers = () => {
- const pages: (number | string)[] = [];
- const maxVisible = 5;
-
- if (totalPages <= maxVisible) {
- for (let i = 1; i <= totalPages; i++) pages.push(i);
- } else {
- if (currentPage <= 3) {
- for (let i = 1; i <= 4; i++) pages.push(i);
- pages.push('...');
- pages.push(totalPages);
- } else if (currentPage >= totalPages - 2) {
- pages.push(1);
- pages.push('...');
- for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
+ const handleSortChange = useCallback(
+ (key: DomainSortKey) => {
+ if (sortKey === key) {
+ setSortOrder(sortOrder === "asc" ? "desc" : "asc");
} else {
- pages.push(1);
- pages.push('...');
- for (let i = currentPage - 1; i <= currentPage + 1; i++) pages.push(i);
- pages.push('...');
- pages.push(totalPages);
+ setSortKey(key);
+ setSortOrder("desc");
}
- }
- return pages;
- };
+ setCurrentPage(1);
+ },
+ [sortKey, sortOrder],
+ );
return (
- <div className="glass-card rounded-2xl overflow-hidden overflow-x-hidden">
- {/* Header */}
- <div className="p-4 sm:p-5 border-b border-border/50">
- <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
- <div>
- <h3 className="text-lg font-semibold">{t("title")}</h3>
- <p className="text-sm text-muted-foreground">
- {total} {t("domainsCount")}
- </p>
- </div>
- <div className="relative">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder={t("search")}
- value={search}
- onChange={(e) => handleSearchChange(e.target.value)}
- className="pl-10 h-10 w-full sm:w-[240px] bg-secondary/50 border-0"
- />
- </div>
- </div>
- </div>
-
- {/* Desktop Table Header - Hidden on mobile */}
- <div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
- <div
- className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("domain")}
- >
- {t("domain")}
- <SortIcon column="domain" />
- </div>
- <div className="col-span-2 flex items-center">
- {t("proxy")}
- </div>
- <div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalDownload")}
- >
- {t("download")}
- <SortIcon column="totalDownload" />
- </div>
- <div
- className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalUpload")}
- >
- {t("upload")}
- <SortIcon column="totalUpload" />
- </div>
- <div
- className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalConnections")}
- >
- {t("conn")}
- <SortIcon column="totalConnections" />
- </div>
- <div className="col-span-1 flex items-center justify-end">
- {t("last")}
- </div>
- <div className="col-span-2 flex items-center justify-end">
- {t("ipCount")}
- </div>
- </div>
-
- {/* Mobile Sort Bar - Shown only on mobile */}
- <div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
- {([
- { key: "domain" as SortKey, label: t("domain") },
- { key: "totalDownload" as SortKey, label: t("download") },
- { key: "totalUpload" as SortKey, label: t("upload") },
- { key: "totalConnections" as SortKey, label: t("conn") },
- ]).map(({ key, label }) => (
- <button
- key={key}
- className={cn(
- "flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
- sortKey === key
- ? "bg-primary/10 text-primary"
- : "text-muted-foreground hover:text-foreground"
- )}
- onClick={() => handleSort(key)}
- >
- {label}
- {sortKey === key && (
- sortOrder === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />
- )}
- </button>
- ))}
- </div>
-
- {/* Table Body */}
- <div className="divide-y divide-border/30 min-h-[300px]">
- {loading && data.length === 0 ? (
- <InsightTableSkeleton />
- ) : data.length === 0 ? (
- <div className="px-5 py-12 text-center text-muted-foreground">
- {t("noResults")}
- </div>
- ) : (
- data.map((domain, index) => {
- const isDesktopExpanded = expandedDomain === domain.domain;
- const isMobileActive =
- mobileDetailsOpen && mobileDetailDomain?.domain === domain.domain;
-
- return (
- <div key={domain.domain} className="group">
- {/* Desktop Row */}
- <div
- className={cn(
- "hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer min-w-0",
- isDesktopExpanded && "bg-secondary/10"
- )}
- style={{ animationDelay: `${index * 50}ms` }}
- onClick={() => toggleExpand(domain.domain)}
- >
- {/* Domain with Favicon */}
- <div className="col-span-3 flex items-center gap-3 min-w-0">
- <Favicon domain={domain.domain} size="sm" className="shrink-0" />
- <div className="min-w-0">
- <DomainPreview
- domain={domain.domain}
- unknownLabel={t("unknown")}
- copyLabel={t("copyDomain")}
- copiedLabel={t("copied")}
- />
- </div>
- </div>
-
- {/* Proxy */}
- <div className="col-span-2 flex items-center gap-1.5 min-w-0">
- <ProxyChainBadge chains={domain.chains} />
- </div>
-
- {/* Download */}
- <div className="col-span-2 text-right tabular-nums text-sm whitespace-nowrap">
- <span className="text-blue-500">{formatBytes(domain.totalDownload)}</span>
- </div>
-
- {/* Upload */}
- <div className="col-span-1 text-right tabular-nums text-sm whitespace-nowrap">
- <span className="text-purple-500">{formatBytes(domain.totalUpload)}</span>
- </div>
-
- {/* Connections */}
- <div className="col-span-1 flex items-center justify-end">
- <span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
- {formatNumber(domain.totalConnections)}
- </span>
- </div>
-
- {/* Last Seen */}
- <div className="col-span-1 text-right">
- <p className="text-xs text-muted-foreground">
- {formatDuration(domain.lastSeen)}
- </p>
- </div>
-
- {/* IP Count - Clickable */}
- <div className="col-span-2 flex items-center justify-end">
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium transition-all",
- isDesktopExpanded
- ? "bg-primary/10 text-primary hover:bg-primary/20"
- : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary"
- )}
- onClick={(e) => {
- e.stopPropagation();
- toggleExpand(domain.domain);
- }}
- >
- <Server className="h-3 w-3" />
- {domain.ips.length}
- {isDesktopExpanded ? (
- <ChevronUp className="h-3 w-3 ml-0.5" />
- ) : (
- <ChevronDown className="h-3 w-3 ml-0.5" />
- )}
- </Button>
- </div>
- </div>
-
- {/* Mobile Row - Card-style layout */}
- <div
- className={cn(
- "sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
- isMobileActive && "bg-secondary/10"
- )}
- onClick={() => openMobileDetails(domain)}
- >
- {/* Row 1: Favicon + Domain (truncate) + IP Count */}
- <div className="flex items-center gap-2.5 mb-2">
- <Favicon domain={domain.domain} size="sm" className="shrink-0" />
- <div className="flex-1 min-w-0">
- <DomainPreview
- domain={domain.domain}
- unknownLabel={t("unknown")}
- copyLabel={t("copyDomain")}
- copiedLabel={t("copied")}
- interactive={false}
- />
- </div>
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isMobileActive
- ? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground"
- )}
- onClick={(e) => {
- e.stopPropagation();
- openMobileDetails(domain);
- }}
- >
- <Server className="h-3 w-3" />
- {domain.ips.length}
- {isMobileActive ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
- </Button>
- </div>
-
- {/* Row 2: Proxy tag - full width, no truncation */}
- {domain.chains && domain.chains.length > 0 && (
- <div className="flex items-center gap-1.5 mb-2 pl-[30px]">
- <ProxyChainBadge
- chains={domain.chains}
- truncateLabel={false}
- interactive={false}
- />
- </div>
- )}
-
- {/* Row 3: Traffic stats - compact layout */}
- <div className="flex items-center gap-3 text-[11px] pl-[30px]">
- <span className="text-blue-500 tabular-nums whitespace-nowrap">↓ {formatBytes(domain.totalDownload)}</span>
- <span className="text-purple-500 tabular-nums whitespace-nowrap">↑ {formatBytes(domain.totalUpload)}</span>
- <span className="text-muted-foreground tabular-nums ml-auto">
- {formatNumber(domain.totalConnections)} {t("conn")}
- </span>
- </div>
- </div>
-
- {/* Expanded Details: Proxy Traffic + IP List */}
- {isDesktopExpanded && (
- <div className="hidden sm:block">
- <ExpandReveal>
- <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"),
- conn: t("conn"),
- }}
- />
- </ExpandReveal>
- </div>
- )}
- </div>
- );
- })
- )}
- </div>
-
- <Drawer open={mobileDetailsOpen} onOpenChange={handleMobileDetailsOpenChange}>
- <DrawerContent className="sm:hidden">
- <DrawerHeader className="border-b border-border/60 bg-background/95 px-5 pt-2 pb-2.5">
- <div className="flex items-center gap-2.5 min-w-0 rounded-md border border-border/60 bg-muted/25 px-2.5 py-2">
- <Favicon domain={mobileDetailDomain?.domain || ""} size="sm" className="shrink-0" />
- <div className="min-w-0 flex-1">
- <DrawerTitle className="text-left text-[15px] font-semibold leading-5 break-all">
- {mobileDetailDomain?.domain || t("unknown")}
- </DrawerTitle>
- </div>
- <CopyIconButton
- value={mobileDetailDomain?.domain || ""}
- copyLabel={t("copyDomain")}
- copiedLabel={t("copied")}
- disabled={!mobileDetailDomain?.domain}
- />
- </div>
- </DrawerHeader>
- <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">
- {mobileDetailDomain ? (
- <DomainExpandedDetails
- domain={mobileDetailDomain}
- proxyStats={expandedDomainProxyQuery.data ?? []}
- proxyStatsLoading={
- expandedDomainProxyQuery.isLoading &&
- !expandedDomainProxyQuery.data
- }
- ipDetails={expandedDomainIPDetailsQuery.data ?? []}
- ipDetailsLoading={
- expandedDomainIPDetailsQuery.isLoading &&
- !expandedDomainIPDetailsQuery.data
- }
- labels={{
- proxyTraffic: t("proxyTraffic"),
- associatedIPs: t("associatedIPs"),
- conn: t("conn"),
- }}
- showFullProxyChains
- />
- ) : null}
- </div>
- </DrawerContent>
- </Drawer>
-
- {/* Pagination Footer */}
- {totalPages > 0 && (
- <div className="p-3 sm:p-4 border-t border-border/50 bg-secondary/20">
- <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
- {/* Page size selector */}
- <div className="flex items-center gap-2">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
- <Rows3 className="h-4 w-4" />
- <span>{pageSize} / {t("page")}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {PAGE_SIZE_OPTIONS.map((size) => (
- <DropdownMenuItem
- key={size}
- onClick={() => handlePageSizeChange(size)}
- className={pageSize === size ? "bg-primary/10" : ""}
- >
- {size} / {t("page")}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
-
- {/* Pagination info and controls */}
- <div className="flex flex-col sm:flex-row items-center gap-1 sm:gap-3">
- <p className="text-xs sm:text-sm text-muted-foreground hidden sm:block whitespace-nowrap shrink-0">
- {t("showing")} {Math.min((currentPage - 1) * pageSize + 1, total)} - {Math.min(currentPage * pageSize, total)} {t("of")} {total}
- </p>
- <p className="text-xs text-muted-foreground sm:hidden whitespace-nowrap shrink-0">
- {Math.min((currentPage - 1) * pageSize + 1, total)}-{Math.min(currentPage * pageSize, total)} / {total}
- </p>
-
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8"
- onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
- disabled={currentPage === 1}
- >
- <ChevronLeft className="h-4 w-4" />
- </Button>
-
- {getPageNumbers().map((page, idx) => (
- page === '...' ? (
- <span key={`ellipsis-${idx}`} className="px-1 sm:px-2 text-muted-foreground text-xs">...</span>
- ) : (
- <Button
- key={page}
- variant={currentPage === page ? "default" : "ghost"}
- size="sm"
- className="h-8 w-8 px-0 text-xs"
- onClick={() => setCurrentPage(page as number)}
- >
- {page}
- </Button>
- )
- ))}
-
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8"
- onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
- disabled={currentPage === totalPages}
- >
- <ChevronRight className="h-4 w-4" />
- </Button>
- </div>
- </div>
- </div>
- </div>
- )}
- </div>
+ <DomainStatsTable
+ domains={data}
+ loading={loading}
+ title={t("title")}
+ showHeader
+ showLastSeenColumn
+ pageSize={pageSize}
+ onPageSizeChange={setEffectivePageSize}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ richExpand
+ mode="remote"
+ searchValue={search}
+ onSearchChange={setSearch}
+ sortKeyValue={sortKey}
+ sortOrderValue={sortOrder}
+ onSortChange={handleSortChange}
+ pageValue={currentPage}
+ totalValue={total}
+ onPageChange={setCurrentPage}
+ />
);
}
diff --git a/apps/web/components/features/stats/table/ip-stats-table.tsx b/apps/web/components/features/stats/table/ip-stats-table.tsx
index b9c3feb..2a2954c 100644
--- a/apps/web/components/features/stats/table/ip-stats-table.tsx
+++ b/apps/web/components/features/stats/table/ip-stats-table.tsx
@@ -51,7 +51,9 @@ import {
} from "@/lib/stats-utils";
import { normalizeGeoIP } from "@neko-master/shared";
import type { IPStats } from "@neko-master/shared";
+
const DETAIL_QUERY_STALE_MS = 30_000;
+type IPTableMode = "local" | "remote";
interface IPStatsTableProps {
ips: IPStats[];
@@ -67,6 +69,17 @@ interface IPStatsTableProps {
richExpand?: boolean;
showProxyColumn?: boolean;
showProxyTrafficInExpand?: boolean;
+ mode?: IPTableMode;
+ searchValue?: string;
+ onSearchChange?: (value: string) => void;
+ sortKeyValue?: IPSortKey;
+ sortOrderValue?: SortOrder;
+ onSortChange?: (key: IPSortKey) => void;
+ pageValue?: number;
+ totalValue?: number;
+ onPageChange?: (page: number) => void;
+ ruleName?: string;
+ contextKey?: string | number;
}
export function IPStatsTable({
@@ -83,19 +96,37 @@ export function IPStatsTable({
richExpand = false,
showProxyColumn = true,
showProxyTrafficInExpand = true,
+ mode = "local",
+ searchValue,
+ onSearchChange,
+ sortKeyValue,
+ sortOrderValue,
+ onSortChange,
+ pageValue,
+ totalValue,
+ onPageChange,
+ ruleName,
+ contextKey,
}: IPStatsTableProps) {
const t = useTranslations("ips");
const detailTimeRange = useStableTimeRange(timeRange);
+ const isRemoteMode = mode === "remote";
- const [page, setPage] = useState(1);
+ const [internalPage, setInternalPage] = useState(1);
const [internalPageSize, setInternalPageSize] = useState<PageSize>(10);
const pageSize = controlledPageSize ?? internalPageSize;
- const [search, setSearch] = useState("");
- const [sortKey, setSortKey] = useState<IPSortKey>("totalDownload");
- const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
+ const [internalSearch, setInternalSearch] = useState("");
+ const [internalSortKey, setInternalSortKey] =
+ useState<IPSortKey>("totalDownload");
+ const [internalSortOrder, setInternalSortOrder] =
+ useState<SortOrder>("desc");
const [expandedIP, setExpandedIP] = useState<string | null>(null);
const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);
const [mobileDetailIP, setMobileDetailIP] = useState<IPStats | null>(null);
+ const page = isRemoteMode ? pageValue ?? 1 : internalPage;
+ const search = isRemoteMode ? searchValue ?? "" : internalSearch;
+ const sortKey = isRemoteMode ? sortKeyValue ?? "totalDownload" : internalSortKey;
+ const sortOrder = isRemoteMode ? sortOrderValue ?? "desc" : internalSortOrder;
const detailIPKey = mobileDetailsOpen ? (mobileDetailIP?.ip ?? null) : expandedIP;
const mobileDetailIPGradient = getIPGradient(mobileDetailIP?.ip ?? "0.0.0.0");
@@ -104,33 +135,76 @@ export function IPStatsTable({
setExpandedIP(null);
setMobileDetailsOpen(false);
setMobileDetailIP(null);
- }, [activeBackendId, sourceIP, sourceChain, richExpand]);
+ }, [activeBackendId, sourceIP, sourceChain, richExpand, ruleName, contextKey]);
+
+ useEffect(() => {
+ if (!isRemoteMode) {
+ setInternalPage(1);
+ setInternalSearch("");
+ setInternalSortKey("totalDownload");
+ setInternalSortOrder("desc");
+ }
+ }, [contextKey, isRemoteMode]);
useEffect(() => {
- setPage(1);
- }, [pageSize]);
+ if (!isRemoteMode) {
+ setInternalPage(1);
+ }
+ }, [pageSize, isRemoteMode]);
const setEffectivePageSize = (size: PageSize) => {
if (onPageSizeChange) {
onPageSizeChange(size);
+ } else {
+ setInternalPageSize(size);
+ }
+
+ if (isRemoteMode) {
+ onPageChange?.(1);
+ } else {
+ setInternalPage(1);
+ }
+ };
+
+ const setEffectivePage = (nextPage: number) => {
+ if (isRemoteMode) {
+ onPageChange?.(nextPage);
return;
}
- setInternalPageSize(size);
+ setInternalPage(nextPage);
+ };
+
+ const handleSearchInputChange = (value: string) => {
+ if (isRemoteMode) {
+ onSearchChange?.(value);
+ onPageChange?.(1);
+ return;
+ }
+ setInternalSearch(value);
+ setInternalPage(1);
};
const expandedIPProxyQuery = useQuery({
queryKey: getIPProxyStatsQueryKey(detailIPKey, activeBackendId, detailTimeRange, {
sourceIP,
sourceChain,
+ rule: ruleName,
}),
queryFn: () =>
- api.getIPProxyStats(
- detailIPKey!,
- activeBackendId,
- detailTimeRange,
- sourceIP,
- sourceChain,
- ),
+ ruleName
+ ? api.getRuleIPProxyStats(
+ ruleName,
+ detailIPKey!,
+ activeBackendId,
+ detailTimeRange,
+ )
+ : api.getIPProxyStats(
+ detailIPKey!,
+ activeBackendId,
+ detailTimeRange,
+ sourceIP,
+ sourceChain,
+ ),
enabled: richExpand && !!activeBackendId && !!detailIPKey,
staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
@@ -139,6 +213,7 @@ export function IPStatsTable({
backendId: activeBackendId ?? null,
sourceIP: sourceIP ?? "",
sourceChain: sourceChain ?? "",
+ rule: ruleName ?? "",
}),
});
@@ -146,16 +221,24 @@ export function IPStatsTable({
queryKey: getIPDomainDetailsQueryKey(detailIPKey, activeBackendId, detailTimeRange, {
sourceIP,
sourceChain,
+ rule: ruleName,
}),
queryFn: () =>
- api.getIPDomainDetails(
- detailIPKey!,
- activeBackendId,
- detailTimeRange,
- sourceIP,
- undefined,
- sourceChain,
- ),
+ ruleName
+ ? api.getRuleIPDomainDetails(
+ ruleName,
+ detailIPKey!,
+ activeBackendId,
+ detailTimeRange,
+ )
+ : api.getIPDomainDetails(
+ detailIPKey!,
+ activeBackendId,
+ detailTimeRange,
+ sourceIP,
+ undefined,
+ sourceChain,
+ ),
enabled: richExpand && !!activeBackendId && !!detailIPKey,
staleTime: DETAIL_QUERY_STALE_MS,
placeholderData: (previousData, previousQuery) =>
@@ -164,17 +247,23 @@ export function IPStatsTable({
backendId: activeBackendId ?? null,
sourceIP: sourceIP ?? "",
sourceChain: sourceChain ?? "",
+ rule: ruleName ?? "",
}),
});
const handleSort = (key: IPSortKey) => {
- if (sortKey === key) {
- setSortOrder(sortOrder === "asc" ? "desc" : "asc");
+ if (isRemoteMode) {
+ onSortChange?.(key);
+ return;
+ }
+
+ if (internalSortKey === key) {
+ setInternalSortOrder(internalSortOrder === "asc" ? "desc" : "asc");
} else {
- setSortKey(key);
- setSortOrder("desc");
+ setInternalSortKey(key);
+ setInternalSortOrder("desc");
}
- setPage(1);
+ setInternalPage(1);
};
const toggleExpand = (ip: string) => {
@@ -204,6 +293,10 @@ export function IPStatsTable({
};
const filteredIPs = useMemo(() => {
+ if (isRemoteMode) {
+ return ips;
+ }
+
let result = [...ips];
if (search) {
const lower = search.toLowerCase();
@@ -218,14 +311,22 @@ export function IPStatsTable({
return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
});
return result;
- }, [ips, search, sortKey, sortOrder]);
+ }, [ips, isRemoteMode, search, sortKey, sortOrder]);
- const paginatedIPs = useMemo(() => {
+ const visibleIPs = useMemo(() => {
+ if (isRemoteMode) {
+ return ips;
+ }
const start = (page - 1) * pageSize;
return filteredIPs.slice(start, start + pageSize);
- }, [filteredIPs, page, pageSize]);
-
- const totalPages = Math.ceil(filteredIPs.length / pageSize);
+ }, [ips, filteredIPs, isRemoteMode, page, pageSize]);
+
+ const totalItems = isRemoteMode ? totalValue ?? ips.length : filteredIPs.length;
+ const totalPages =
+ totalItems > 0 ? Math.max(1, Math.ceil(totalItems / pageSize)) : 0;
+ const hasRows = visibleIPs.length > 0;
+ const startIndex = totalItems === 0 ? 0 : Math.min((page - 1) * pageSize + 1, totalItems);
+ const endIndex = Math.min(page * pageSize, totalItems);
const ipColumnClass = showProxyColumn ? "col-span-3" : "col-span-4";
const locationColumnClass = "col-span-2";
const domainCountColumnClass = showProxyColumn ? "col-span-1" : "col-span-2";
@@ -238,17 +339,14 @@ export function IPStatsTable({
<div>
<h3 className="text-base font-semibold">{title || t("associatedIPs")}</h3>
<p className="text-sm text-muted-foreground">
- {filteredIPs.length} {t("ipsCount")}
+ {totalItems} {t("ipsCount")}
</p>
</div>
<div className="relative">
<Input
placeholder={t("search")}
value={search}
- onChange={(e) => {
- setSearch(e.target.value);
- setPage(1);
- }}
+ onChange={(e) => handleSearchInputChange(e.target.value)}
className="h-9 w-full sm:w-[240px] bg-secondary/50 border-0"
/>
</div>
@@ -259,7 +357,7 @@ export function IPStatsTable({
<CardContent className="p-0">
{loading ? (
<InsightTableSkeleton />
- ) : filteredIPs.length === 0 ? (
+ ) : !hasRows ? (
<div className="text-center py-12 text-muted-foreground">
{search ? t("noResults") : t("noData")}
</div>
@@ -331,7 +429,7 @@ export function IPStatsTable({
</div>
<div className="divide-y divide-border/30">
- {paginatedIPs.map((ip) => {
+ {visibleIPs.map((ip) => {
const isDesktopExpanded = expandedIP === ip.ip;
const isMobileActive = mobileDetailsOpen && mobileDetailIP?.ip === ip.ip;
const geo = normalizeGeoIP(ip.geoIP);
@@ -577,7 +675,7 @@ export function IPStatsTable({
</DrawerContent>
</Drawer>
- {filteredIPs.length > 0 && (
+ {totalItems > 0 && (
<div className="p-3 border-t border-border/50 bg-secondary/20">
<div className="flex flex-col sm:flex-row items-center justify-between gap-3">
<div className="flex items-center gap-2">
@@ -592,10 +690,7 @@ export function IPStatsTable({
{PAGE_SIZE_OPTIONS.map((size) => (
<DropdownMenuItem
key={size}
- onClick={() => {
- setEffectivePageSize(size);
- setPage(1);
- }}
+ onClick={() => setEffectivePageSize(size)}
className={pageSize === size ? "bg-primary/10" : ""}
>
{size} / {t("page")}
@@ -606,15 +701,15 @@ export function IPStatsTable({
</div>
<div className="flex flex-col sm:flex-row items-center gap-1 sm:gap-2">
<p className="text-xs text-muted-foreground whitespace-nowrap shrink-0">
- {(page - 1) * pageSize + 1}-{Math.min(page * pageSize, filteredIPs.length)} / {filteredIPs.length}
+ {startIndex}-{endIndex} / {totalItems}
</p>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setPage((p) => Math.max(1, p - 1))}
- disabled={page === 1}
+ onClick={() => setEffectivePage(Math.max(1, page - 1))}
+ disabled={page <= 1}
>
<ChevronLeft className="h-4 w-4" />
</Button>
@@ -629,7 +724,7 @@ export function IPStatsTable({
variant={page === p ? "default" : "ghost"}
size="sm"
className="h-8 w-8 px-0 text-xs"
- onClick={() => setPage(p as number)}
+ onClick={() => setEffectivePage(p as number)}
>
{p}
</Button>
@@ -639,8 +734,8 @@ export function IPStatsTable({
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
- disabled={page === totalPages}
+ onClick={() => setEffectivePage(Math.min(totalPages, page + 1))}
+ disabled={page >= totalPages}
>
<ChevronRight className="h-4 w-4" />
</Button>
diff --git a/apps/web/components/features/stats/table/ip-table.tsx b/apps/web/components/features/stats/table/ip-table.tsx
index 645672c..2efccad 100644
--- a/apps/web/components/features/stats/table/ip-table.tsx
+++ b/apps/web/components/features/stats/table/ip-table.tsx
@@ -1,50 +1,19 @@
"use client";
import { useState, useEffect, useRef, useCallback } from "react";
-import {
- Search,
- ArrowUpDown,
- ArrowDown,
- ArrowUp,
- ChevronLeft,
- ChevronRight,
- Rows3,
- Globe,
- Server,
- ChevronDown,
- ChevronUp,
- Link2,
-} 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 { InsightTableSkeleton } from "@/components/ui/insight-skeleton";
-import { CopyIconButton } from "@/components/common/copy-icon-button";
-import { CountryFlag } from "@/components/features/countries/country-flag";
-import { formatBytes, formatNumber } from "@/lib/utils";
-import { cn } from "@/lib/utils";
-import { IPExpandedDetails } from "@/components/features/stats/table/expanded-details";
-import { ProxyChainBadge } from "@/components/features/proxies/proxy-chain-badge";
-import { IPPreview } from "@/components/features/stats/table/ip-preview";
-import { ExpandReveal } from "@/components/ui/expand-reveal";
-import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from "@/components/ui/drawer";
-import type { IPStats, StatsSummary } from "@neko-master/shared";
+import { useTranslations } from "next-intl";
import { api, type TimeRange } from "@/lib/api";
import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";
import { useStatsWebSocket } from "@/lib/websocket";
-import { normalizeGeoIP } from "@neko-master/shared";
-import {
- getIPDomainDetailsQueryKey,
- getIPProxyStatsQueryKey,
- getIPsQueryKey,
-} from "@/lib/stats-query-keys";
+import { getIPsQueryKey } from "@/lib/stats-query-keys";
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
+ type IPSortKey,
+ type PageSize,
+ type SortOrder,
+} from "@/lib/stats-utils";
+import { IPStatsTable } from "./ip-stats-table";
+import type { IPStats, StatsSummary } from "@neko-master/shared";
interface IPsTableProps {
activeBackendId?: number;
@@ -54,17 +23,8 @@ interface IPsTableProps {
onPageSizeChange?: (size: PageSize) => void;
}
-type SortKey =
- | "ip"
- | "totalDownload"
- | "totalUpload"
- | "totalConnections"
- | "lastSeen";
-type SortOrder = "asc" | "desc";
-
-import { PAGE_SIZE_OPTIONS, type PageSize } from "@/lib/stats-utils";
-const DETAIL_QUERY_STALE_MS = 30_000;
const IPS_WS_MIN_PUSH_MS = 3_000;
+
type IPsPageQueryState = {
offset: number;
limit: number;
@@ -72,6 +32,7 @@ type IPsPageQueryState = {
sortOrder?: "asc" | "desc";
search?: string;
};
+
type IPsPageState = {
data: IPStats[];
total: number;
@@ -79,27 +40,6 @@ type IPsPageState = {
backendId?: number;
};
-// Color palette for IP icons - solid colors that work in both light/dark modes
-const IP_COLORS = [
- { bg: "bg-blue-500", text: "text-white" },
- { bg: "bg-violet-500", text: "text-white" },
- { bg: "bg-emerald-500", text: "text-white" },
- { bg: "bg-amber-500", text: "text-white" },
- { bg: "bg-rose-500", text: "text-white" },
- { bg: "bg-cyan-500", text: "text-white" },
- { bg: "bg-indigo-500", text: "text-white" },
- { bg: "bg-teal-500", text: "text-white" },
-];
-
-// Get color for IP
-const getIPColor = (ip: string) => {
- let hash = 0;
- for (let i = 0; i < ip.length; i++) {
- hash = ip.charCodeAt(i) + ((hash << 5) - hash);
- }
- return IP_COLORS[Math.abs(hash) % IP_COLORS.length];
-};
-
export function IPsTable({
activeBackendId,
timeRange,
@@ -109,29 +49,31 @@ export function IPsTable({
}: IPsTableProps) {
const t = useTranslations("ips");
const stableTimeRange = useStableTimeRange(timeRange);
- const detailTimeRange = stableTimeRange;
+
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
- const [sortKey, setSortKey] = useState<SortKey>("totalDownload");
+ const [sortKey, setSortKey] = useState<IPSortKey>("totalDownload");
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
const [currentPage, setCurrentPage] = useState(1);
const [internalPageSize, setInternalPageSize] = useState<PageSize>(10);
- const pageSize = controlledPageSize ?? internalPageSize;
- const setEffectivePageSize = useCallback((size: PageSize) => {
- if (onPageSizeChange) {
- onPageSizeChange(size);
- return;
- }
- setInternalPageSize(size);
- }, [onPageSizeChange]);
- const [expandedIP, setExpandedIP] = useState<string | null>(null);
- const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);
- const [mobileDetailIP, setMobileDetailIP] = useState<IPStats | null>(null);
const [wsIPsPage, setWsIPsPage] = useState<IPsPageState | null>(null);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const pageSize = controlledPageSize ?? internalPageSize;
const pageOffset = (currentPage - 1) * pageSize;
const wsPageSearch = debouncedSearch || undefined;
+ const setEffectivePageSize = useCallback(
+ (size: PageSize) => {
+ if (onPageSizeChange) {
+ onPageSizeChange(size);
+ } else {
+ setInternalPageSize(size);
+ }
+ },
+ [onPageSizeChange],
+ );
+
const wsPageEnabled = autoRefresh && !!activeBackendId;
const { status: wsPageStatus } = useStatsWebSocket({
backendId: activeBackendId,
@@ -145,23 +87,27 @@ export function IPsTable({
ipsPageSearch: wsPageSearch,
trackLastMessage: false,
enabled: wsPageEnabled,
- onMessage: useCallback((stats: StatsSummary) => {
- const query = stats.ipsPageQuery;
- const page = stats.ipsPage;
- if (!page || !query) return;
- setWsIPsPage({
- data: page.data,
- total: page.total,
- query: {
- offset: query.offset,
- limit: query.limit,
- sortBy: query.sortBy || "totalDownload",
- sortOrder: query.sortOrder === "asc" ? "asc" : "desc",
- search: query.search || undefined,
- },
- backendId: activeBackendId,
- });
- }, [activeBackendId]),
+ onMessage: useCallback(
+ (stats: StatsSummary) => {
+ const query = stats.ipsPageQuery;
+ const page = stats.ipsPage;
+ if (!page || !query) return;
+
+ setWsIPsPage({
+ data: page.data,
+ total: page.total,
+ query: {
+ offset: query.offset,
+ limit: query.limit,
+ sortBy: query.sortBy || "totalDownload",
+ sortOrder: query.sortOrder === "asc" ? "asc" : "desc",
+ search: query.search || undefined,
+ },
+ backendId: activeBackendId,
+ });
+ },
+ [activeBackendId],
+ ),
});
const wsIPsPageMatchesCurrent =
@@ -173,14 +119,15 @@ export function IPsTable({
(wsIPsPage.query.sortOrder || "desc") === sortOrder &&
(wsIPsPage.query.search || undefined) === wsPageSearch;
- // Debounce search input
useEffect(() => {
debounceRef.current = setTimeout(() => {
setDebouncedSearch(search);
- setCurrentPage(1);
}, 300);
+
return () => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
+ if (debounceRef.current) {
+ clearTimeout(debounceRef.current);
+ }
};
}, [search]);
@@ -188,7 +135,7 @@ export function IPsTable({
queryKey: getIPsQueryKey(
activeBackendId,
{
- offset: (currentPage - 1) * pageSize,
+ offset: pageOffset,
limit: pageSize,
sortBy: sortKey,
sortOrder,
@@ -198,7 +145,7 @@ export function IPsTable({
),
queryFn: () =>
api.getIPs(activeBackendId, {
- offset: (currentPage - 1) * pageSize,
+ offset: pageOffset,
limit: pageSize,
sortBy: sortKey,
sortOrder,
@@ -214,581 +161,43 @@ export function IPsTable({
const hasWsIPsPage =
wsPageEnabled && wsPageStatus === "connected" && wsIPsPageMatchesCurrent;
- const data = hasWsIPsPage ? wsIPsPage!.data : ipsQuery.data?.data ?? [];
- const total = hasWsIPsPage ? wsIPsPage!.total : ipsQuery.data?.total ?? 0;
+ const data = hasWsIPsPage ? wsIPsPage.data : ipsQuery.data?.data ?? [];
+ const total = hasWsIPsPage ? wsIPsPage.total : ipsQuery.data?.total ?? 0;
const loading = !hasWsIPsPage && ipsQuery.isLoading && !ipsQuery.data;
- const detailIPKey = mobileDetailsOpen ? (mobileDetailIP?.ip ?? null) : expandedIP;
- const mobileIPColor = getIPColor(mobileDetailIP?.ip ?? "0.0.0.0");
-
- useEffect(() => {
- // Backend switch means a different data universe, collapse safely.
- setExpandedIP(null);
- setMobileDetailsOpen(false);
- setMobileDetailIP(null);
- }, [activeBackendId]);
-
- const expandedIPProxyQuery = useQuery({
- queryKey: getIPProxyStatsQueryKey(detailIPKey, activeBackendId, detailTimeRange),
- queryFn: () => api.getIPProxyStats(detailIPKey!, activeBackendId, detailTimeRange),
- enabled: !!activeBackendId && !!detailIPKey,
- staleTime: DETAIL_QUERY_STALE_MS,
- placeholderData: (previousData, previousQuery) => {
- const prevKey = (previousQuery?.queryKey?.[2] ?? null) as
- | { ip?: string; backendId?: number | null }
- | null;
- if (!prevKey) return undefined;
- if (prevKey.ip !== (detailIPKey ?? "")) return undefined;
- if (prevKey.backendId !== (activeBackendId ?? null)) return undefined;
- return previousData;
- },
- });
-
- const expandedIPDomainDetailsQuery = useQuery({
- queryKey: getIPDomainDetailsQueryKey(detailIPKey, activeBackendId, detailTimeRange),
- queryFn: () => api.getIPDomainDetails(detailIPKey!, activeBackendId, detailTimeRange),
- enabled: !!activeBackendId && !!detailIPKey,
- staleTime: DETAIL_QUERY_STALE_MS,
- placeholderData: (previousData, previousQuery) => {
- const prevKey = (previousQuery?.queryKey?.[2] ?? null) as
- | { ip?: string; backendId?: number | null }
- | null;
- if (!prevKey) return undefined;
- if (prevKey.ip !== (detailIPKey ?? "")) return undefined;
- if (prevKey.backendId !== (activeBackendId ?? null)) return undefined;
- return previousData;
- },
- });
-
- const handleSort = (key: SortKey) => {
- if (sortKey === key) {
- setSortOrder(sortOrder === "asc" ? "desc" : "asc");
- } else {
- setSortKey(key);
- setSortOrder("desc");
- }
- setCurrentPage(1);
- };
-
- const totalPages = Math.ceil(total / pageSize);
-
- const handleSearchChange = (value: string) => {
- setSearch(value);
- };
-
- const handlePageSizeChange = (size: PageSize) => {
- setEffectivePageSize(size);
- setCurrentPage(1);
- };
-
- const toggleExpand = (ip: string) => {
- const newExpanded = expandedIP === ip ? null : ip;
- setExpandedIP(newExpanded);
- };
-
- const openMobileDetails = (ip: IPStats) => {
- setMobileDetailIP(ip);
- setMobileDetailsOpen(true);
- };
-
- const handleMobileDetailsOpenChange = (open: boolean) => {
- setMobileDetailsOpen(open);
- if (!open) {
- setMobileDetailIP(null);
- }
- };
-
- const SortIcon = ({ column }: { column: SortKey }) => {
- if (sortKey !== column)
- return <ArrowUpDown className="ml-1 h-3 w-3 text-muted-foreground" />;
- return sortOrder === "asc" ? (
- <ArrowUp className="ml-1 h-3 w-3 text-primary" />
- ) : (
- <ArrowDown className="ml-1 h-3 w-3 text-primary" />
- );
- };
- // Generate page numbers to display
- const getPageNumbers = () => {
- const pages: (number | string)[] = [];
- const maxVisible = 5;
-
- if (totalPages <= maxVisible) {
- for (let i = 1; i <= totalPages; i++) pages.push(i);
- } else {
- if (currentPage <= 3) {
- for (let i = 1; i <= 4; i++) pages.push(i);
- pages.push("...");
- pages.push(totalPages);
- } else if (currentPage >= totalPages - 2) {
- pages.push(1);
- pages.push("...");
- for (let i = totalPages - 3; i <= totalPages; i++) pages.push(i);
+ const handleSortChange = useCallback(
+ (key: IPSortKey) => {
+ if (sortKey === key) {
+ setSortOrder(sortOrder === "asc" ? "desc" : "asc");
} else {
- pages.push(1);
- pages.push("...");
- for (let i = currentPage - 1; i <= currentPage + 1; i++) pages.push(i);
- pages.push("...");
- pages.push(totalPages);
+ setSortKey(key);
+ setSortOrder("desc");
}
- }
- return pages;
- };
+ setCurrentPage(1);
+ },
+ [sortKey, sortOrder],
+ );
return (
- <div className="glass-card rounded-2xl overflow-hidden overflow-x-hidden">
- {/* Header */}
- <div className="p-4 sm:p-5 border-b border-border/50">
- <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
- <div>
- <h3 className="text-lg font-semibold">{t("title")}</h3>
- <p className="text-sm text-muted-foreground">
- {total} {t("ipsCount")}
- </p>
- </div>
- <div className="relative">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder={t("search")}
- value={search}
- onChange={(e) => handleSearchChange(e.target.value)}
- className="pl-10 h-10 w-full sm:w-[240px] bg-secondary/50 border-0"
- />
- </div>
- </div>
- </div>
-
- {/* Desktop Table Header */}
- <div className="hidden sm:grid grid-cols-12 gap-3 px-5 py-3 bg-secondary/30 text-xs font-medium text-muted-foreground uppercase tracking-wider">
- <div
- className="col-span-3 flex items-center cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("ip")}>
- {t("ipAddress")}
- <SortIcon column="ip" />
- </div>
- <div className="col-span-2 flex items-center">{t("proxy")}</div>
- <div className="col-span-2 flex items-center">{t("location")}</div>
- <div
- className="col-span-2 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalDownload")}>
- {t("download")}
- <SortIcon column="totalDownload" />
- </div>
- <div
- className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalUpload")}>
- {t("upload")}
- <SortIcon column="totalUpload" />
- </div>
- <div
- className="col-span-1 flex items-center justify-end cursor-pointer hover:text-foreground transition-colors"
- onClick={() => handleSort("totalConnections")}>
- {t("conn")}
- <SortIcon column="totalConnections" />
- </div>
- <div className="col-span-1 flex items-center justify-end">
- {t("domainCount")}
- </div>
- </div>
-
- {/* Mobile Sort Bar */}
- <div className="sm:hidden flex items-center gap-2 px-4 py-2 bg-secondary/30 overflow-x-auto scrollbar-hide">
- {[
- { key: "ip" as SortKey, label: t("ipAddress") },
- { key: "totalDownload" as SortKey, label: t("download") },
- { key: "totalUpload" as SortKey, label: t("upload") },
- { key: "totalConnections" as SortKey, label: t("conn") },
- ].map(({ key, label }) => (
- <button
- key={key}
- className={cn(
- "flex items-center gap-0.5 px-2 py-1 rounded-md text-xs font-medium whitespace-nowrap transition-colors",
- sortKey === key
- ? "bg-primary/10 text-primary"
- : "text-muted-foreground hover:text-foreground",
- )}
- onClick={() => handleSort(key)}>
- {label}
- {sortKey === key &&
- (sortOrder === "asc" ? (
- <ArrowUp className="h-3 w-3" />
- ) : (
- <ArrowDown className="h-3 w-3" />
- ))}
- </button>
- ))}
- </div>
-
- {/* Table Body */}
- <div className="divide-y divide-border/30 min-h-[300px]">
- {loading && data.length === 0 ? (
- <InsightTableSkeleton />
- ) : data.length === 0 ? (
- <div className="px-5 py-12 text-center text-muted-foreground">
- {t("noResults")}
- </div>
- ) : (
- data.map((ip, index) => {
- const ipColor = getIPColor(ip.ip);
- const isDesktopExpanded = expandedIP === ip.ip;
- const isMobileActive = mobileDetailsOpen && mobileDetailIP?.ip === ip.ip;
- const geo = normalizeGeoIP(ip.geoIP);
- const locationName = geo?.countryName || geo?.countryCode || null;
-
- return (
- <div key={ip.ip} className="group">
- {/* Desktop Row */}
- <div
- className={cn(
- "hidden sm:grid grid-cols-12 gap-3 px-5 py-4 items-center hover:bg-secondary/20 transition-colors cursor-pointer min-w-0",
- isDesktopExpanded && "bg-secondary/10",
- )}
- style={{ animationDelay: `${index * 50}ms` }}
- onClick={() => toggleExpand(ip.ip)}>
- {/* IP with Icon */}
- <div className="col-span-3 flex items-center gap-3 min-w-0">
- <div
- className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
- <Server className="w-3 h-3" />
- </div>
- <IPPreview
- ip={ip.ip}
- geoIP={ip.geoIP}
- asn={ip.asn}
- unknownLabel={t("unknownIP")}
- unavailableLabel={t("unknown")}
- copyLabel={t("copyIP")}
- copiedLabel={t("copied")}
- locationLabel={t("location")}
- cityLabel={t("city")}
- asnLabel={t("asn")}
- asOrganizationLabel={t("asOrganization")}
- className="flex-1"
- triggerClassName="font-mono font-medium"
- />
- </div>
-
- {/* Proxy */}
- <div className="col-span-2 flex items-center gap-1.5 min-w-0">
- <ProxyChainBadge chains={ip.chains} />
- </div>
-
- {/* Location */}
- <div className="col-span-2 flex items-center min-w-0">
- {locationName ? (
- <div className="flex items-center gap-1.5 min-w-0">
- <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" title={locationName} />
- <span className="text-xs whitespace-nowrap">
- {locationName}
- </span>
- </div>
- ) : (
- <span className="text-xs text-muted-foreground">-</span>
- )}
- </div>
-
- {/* Download */}
- <div className="col-span-2 text-right tabular-nums text-sm whitespace-nowrap">
- <span className="text-blue-500">
- {formatBytes(ip.totalDownload)}
- </span>
- </div>
-
- {/* Upload */}
- <div className="col-span-1 text-right tabular-nums text-sm whitespace-nowrap">
- <span className="text-purple-500">
- {formatBytes(ip.totalUpload)}
- </span>
- </div>
-
- {/* Connections */}
- <div className="col-span-1 flex items-center justify-end">
- <span className="px-2 py-0.5 rounded-full bg-secondary text-xs font-medium">
- {formatNumber(ip.totalConnections)}
- </span>
- </div>
-
- {/* Domains Count - Clickable */}
- <div className="col-span-1 flex items-center justify-end">
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium transition-all",
- isDesktopExpanded
- ? "bg-primary/10 text-primary hover:bg-primary/20"
- : "bg-secondary/50 text-muted-foreground hover:text-foreground hover:bg-secondary",
- )}
- onClick={(e) => {
- e.stopPropagation();
- toggleExpand(ip.ip);
- }}>
- <Link2 className="h-3 w-3" />
- {ip.domains.length}
- {isDesktopExpanded ? (
- <ChevronUp className="h-3 w-3 ml-0.5" />
- ) : (
- <ChevronDown className="h-3 w-3 ml-0.5" />
- )}
- </Button>
- </div>
- </div>
-
- {/* Mobile Row - Card-style layout */}
- <div
- className={cn(
- "sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
- isMobileActive && "bg-secondary/10",
- )}
- onClick={() => openMobileDetails(ip)}>
- {/* Row 1: IP Icon + IP (truncate) + Domain Count */}
- <div className="flex items-center gap-2.5 mb-2">
- <div
- className={`w-5 h-5 rounded-md ${ipColor.bg} ${ipColor.text} flex items-center justify-center shrink-0`}>
- <Server className="w-3 h-3" />
- </div>
- <div className="flex-1 min-w-0">
- <IPPreview
- ip={ip.ip}
- geoIP={ip.geoIP}
- asn={ip.asn}
- unknownLabel={t("unknownIP")}
- unavailableLabel={t("unknown")}
- copyLabel={t("copyIP")}
- copiedLabel={t("copied")}
- locationLabel={t("location")}
- cityLabel={t("city")}
- asnLabel={t("asn")}
- asOrganizationLabel={t("asOrganization")}
- triggerClassName="font-mono font-medium"
- interactive={false}
- />
- </div>
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isMobileActive
- ? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground",
- )}
- onClick={(e) => {
- e.stopPropagation();
- openMobileDetails(ip);
- }}>
- <Link2 className="h-3 w-3" />
- {ip.domains.length}
- {isMobileActive ? (
- <ChevronUp className="h-3 w-3" />
- ) : (
- <ChevronDown className="h-3 w-3" />
- )}
- </Button>
- </div>
-
- {/* Row 2: Location + Proxy tag */}
- <div className="flex items-center gap-2 mb-2 pl-[30px] flex-wrap">
- {locationName && (
- <span className="inline-flex items-center gap-1 text-[11px] text-muted-foreground">
- <CountryFlag country={geo?.countryCode || "UN"} className="h-3.5 w-5" />
- <span className="truncate">
- {locationName}
- </span>
- </span>
- )}
- {ip.chains && ip.chains.length > 0 && (
- <ProxyChainBadge
- chains={ip.chains}
- truncateLabel={false}
- interactive={false}
- />
- )}
- </div>
-
- {/* Row 3: Traffic stats - compact layout */}
- <div className="flex items-center gap-3 text-[11px] pl-[30px]">
- <span className="text-blue-500 tabular-nums whitespace-nowrap">
- ↓ {formatBytes(ip.totalDownload)}
- </span>
- <span className="text-purple-500 tabular-nums whitespace-nowrap">
- ↑ {formatBytes(ip.totalUpload)}
- </span>
- <span className="text-muted-foreground tabular-nums ml-auto">
- {formatNumber(ip.totalConnections)} {t("conn")}
- </span>
- </div>
- </div>
-
- {/* Expanded Details: Proxy Traffic + Domains List */}
- {isDesktopExpanded && (
- <div className="hidden sm:block">
- <ExpandReveal>
- <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"),
- associatedDomains: t("associatedDomains"),
- conn: t("conn"),
- }}
- />
- </ExpandReveal>
- </div>
- )}
- </div>
- );
- })
- )}
- </div>
-
- <Drawer open={mobileDetailsOpen} onOpenChange={handleMobileDetailsOpenChange}>
- <DrawerContent className="sm:hidden">
- <DrawerHeader className="border-b border-border/60 bg-background/95 px-5 pt-2 pb-2.5">
- <div className="flex items-center gap-2.5 min-w-0 rounded-md border border-border/60 bg-muted/25 px-2.5 py-2">
- <div
- className={`w-5 h-5 rounded-md ${mobileIPColor.bg} ${mobileIPColor.text} flex items-center justify-center shrink-0`}
- >
- <Server className="w-3 h-3" />
- </div>
- <div className="min-w-0 flex-1">
- <DrawerTitle className="text-left font-mono text-[15px] font-semibold leading-5 break-all">
- {mobileDetailIP?.ip || t("unknownIP")}
- </DrawerTitle>
- </div>
- <CopyIconButton
- value={mobileDetailIP?.ip || ""}
- copyLabel={t("copyIP")}
- copiedLabel={t("copied")}
- disabled={!mobileDetailIP?.ip}
- />
- </div>
- </DrawerHeader>
- <div className="max-h-[76vh] overflow-y-auto pb-[max(env(safe-area-inset-bottom),0px)]">
- {mobileDetailIP ? (
- <IPExpandedDetails
- ip={mobileDetailIP}
- proxyStats={expandedIPProxyQuery.data ?? []}
- proxyStatsLoading={
- expandedIPProxyQuery.isLoading &&
- !expandedIPProxyQuery.data
- }
- domainDetails={expandedIPDomainDetailsQuery.data ?? []}
- domainDetailsLoading={
- expandedIPDomainDetailsQuery.isLoading &&
- !expandedIPDomainDetailsQuery.data
- }
- associatedDomainsIcon="link"
- labels={{
- proxyTraffic: t("proxyTraffic"),
- associatedDomains: t("associatedDomains"),
- conn: t("conn"),
- }}
- showFullProxyChains
- disableNestedInteractions
- showIPLookupDetails
- />
- ) : null}
- </div>
- </DrawerContent>
- </Drawer>
-
- {/* Pagination Footer */}
- {totalPages > 0 && (
- <div className="p-3 sm:p-4 border-t border-border/50 bg-secondary/20">
- <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
- {/* Page size selector */}
- <div className="flex items-center gap-2">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="sm"
- className="h-8 gap-1.5 text-muted-foreground hover:text-foreground">
- <Rows3 className="h-4 w-4" />
- <span>
- {pageSize} / {t("page")}
- </span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {PAGE_SIZE_OPTIONS.map((size) => (
- <DropdownMenuItem
- key={size}
- onClick={() => handlePageSizeChange(size)}
- className={pageSize === size ? "bg-primary/10" : ""}>
- {size} / {t("page")}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
-
- {/* Pagination info and controls */}
- <div className="flex flex-col sm:flex-row items-center gap-1 sm:gap-3">
- <p className="text-xs sm:text-sm text-muted-foreground hidden sm:block whitespace-nowrap shrink-0">
- {t("showing")}{" "}
- {Math.min((currentPage - 1) * pageSize + 1, total)} -{" "}
- {Math.min(currentPage * pageSize, total)} {t("of")} {total}
- </p>
- <p className="text-xs text-muted-foreground sm:hidden whitespace-nowrap shrink-0">
- {Math.min((currentPage - 1) * pageSize + 1, total)}-
- {Math.min(currentPage * pageSize, total)} / {total}
- </p>
-
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8"
- onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
- disabled={currentPage === 1}>
- <ChevronLeft className="h-4 w-4" />
- </Button>
-
- {getPageNumbers().map((page, idx) =>
- page === "..." ? (
- <span
- key={`ellipsis-${idx}`}
- className="px-1 sm:px-2 text-muted-foreground text-xs">
- ...
- </span>
- ) : (
- <Button
- key={page}
- variant={currentPage === page ? "default" : "ghost"}
- size="sm"
- className="h-8 w-8 px-0 text-xs"
- onClick={() => setCurrentPage(page as number)}>
- {page}
- </Button>
- ),
- )}
-
- <Button
- variant="ghost"
- size="icon"
- className="h-8 w-8"
- onClick={() =>
- setCurrentPage((p) => Math.min(totalPages, p + 1))
- }
- disabled={currentPage === totalPages}>
- <ChevronRight className="h-4 w-4" />
- </Button>
- </div>
- </div>
- </div>
- </div>
- )}
- </div>
+ <IPStatsTable
+ ips={data}
+ loading={loading}
+ title={t("title")}
+ showHeader
+ pageSize={pageSize}
+ onPageSizeChange={setEffectivePageSize}
+ activeBackendId={activeBackendId}
+ timeRange={timeRange}
+ richExpand
+ mode="remote"
+ searchValue={search}
+ onSearchChange={setSearch}
+ sortKeyValue={sortKey}
+ sortOrderValue={sortOrder}
+ onSortChange={handleSortChange}
+ pageValue={currentPage}
+ totalValue={total}
+ onPageChange={setCurrentPage}
+ />
);
}