Skip to content

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

feat: Add interactive device, IP, and domain statistics with dedicated tables and backend collection.

luolei09cee248d3ed
diff --git a/apps/collector/src/api.ts b/apps/collector/src/api.ts
index 67baa8d..95a5f38 100644
--- a/apps/collector/src/api.ts
+++ b/apps/collector/src/api.ts
@@ -344,6 +344,36 @@ export class APIServer {
);
});
+ // Get device statistics for a specific backend
+ app.get('/api/stats/devices', async (request, reply) => {
+ const backendId = getBackendId(request);
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+ const { limit, start, end } = request.query as { limit?: string; start?: string; end?: string };
+ return this.db.getDevices(backendId, parseInt(limit || '50'), start, end);
+ });
+
+ app.get('/api/stats/devices/domains', async (request, reply) => {
+ const backendId = getBackendId(request);
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+ const { sourceIP } = request.query as { sourceIP: string };
+ if (!sourceIP) return [];
+ return this.db.getDeviceDomains(backendId, sourceIP);
+ });
+
+ app.get('/api/stats/devices/ips', async (request, reply) => {
+ const backendId = getBackendId(request);
+ if (backendId === null) {
+ return reply.status(404).send({ error: 'No backend specified or active' });
+ }
+ const { sourceIP } = request.query as { sourceIP: string };
+ if (!sourceIP) return [];
+ return this.db.getDeviceIPs(backendId, sourceIP);
+ });
+
// Get hourly statistics for a specific backend
app.get('/api/stats/hourly', async (request, reply) => {
const backendId = getBackendId(request);
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index bf1f74a..3745386 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -21,6 +21,7 @@ interface TrafficUpdate {
rulePayload: string;
upload: number;
download: number;
+ sourceIP?: string;
}
interface GeoIPResult {
@@ -257,6 +258,7 @@ interface TrackedConnection {
lastDownload: number;
totalUpload: number;
totalDownload: number;
+ sourceIP?: string;
}
export function createCollector(
@@ -338,6 +340,7 @@ export function createCollector(
const metadata = conn.metadata || {};
const domain = metadata.host || metadata.sniffHost || "";
const ip = metadata.destinationIP || "";
+ const sourceIP = metadata.sourceIP || "";
const chains = Array.isArray(conn.chains) ? conn.chains : ["DIRECT"];
const rule = conn.rule || "Match";
const rulePayload = conn.rulePayload || "";
@@ -357,6 +360,7 @@ export function createCollector(
lastDownload: conn.download,
totalUpload: conn.upload,
totalDownload: conn.download,
+ sourceIP,
});
// Record initial traffic for new connection (add to batch buffer)
@@ -370,6 +374,7 @@ export function createCollector(
rulePayload,
upload: conn.upload,
download: conn.download,
+ sourceIP,
});
realtimeStore.recordTraffic(
id,
@@ -438,6 +443,7 @@ export function createCollector(
rulePayload: existing.rulePayload || "",
upload: uploadDelta,
download: downloadDelta,
+ sourceIP: existing.sourceIP,
});
realtimeStore.recordTraffic(
id,
diff --git a/apps/collector/src/db.ts b/apps/collector/src/db.ts
index 5825414..e6e77a7 100644
--- a/apps/collector/src/db.ts
+++ b/apps/collector/src/db.ts
@@ -1,7 +1,7 @@
import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
-import type { Connection, DomainStats, IPStats, HourlyStats, DailyStats, ProxyStats, RuleStats, ProxyTrafficStats } from '@clashmaster/shared';
+import type { Connection, DomainStats, IPStats, HourlyStats, DailyStats, ProxyStats, RuleStats, ProxyTrafficStats, DeviceStats } from '@clashmaster/shared';
// Retention config stored in database (doesn't include cleanupInterval)
interface DatabaseRetentionConfig {
connectionLogsDays: number;
@@ -18,6 +18,7 @@ export interface TrafficUpdate {
rulePayload: string;
upload: number;
download: number;
+ sourceIP?: string;
}
export interface BackendConfig {
@@ -169,6 +170,52 @@ export class StatsDatabase {
);
`);
+ // Device statistics per backend
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS device_stats (
+ backend_id INTEGER NOT NULL,
+ source_ip TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, source_ip),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `);
+
+ // Device×domain traffic aggregation
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS device_domain_stats (
+ backend_id INTEGER NOT NULL,
+ source_ip TEXT NOT NULL,
+ domain TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, source_ip, domain),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `);
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_device_domain_source_ip ON device_domain_stats(backend_id, source_ip);`);
+
+ // Device×IP traffic aggregation
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS device_ip_stats (
+ backend_id INTEGER NOT NULL,
+ source_ip TEXT NOT NULL,
+ ip TEXT NOT NULL,
+ total_upload INTEGER DEFAULT 0,
+ total_download INTEGER DEFAULT 0,
+ total_connections INTEGER DEFAULT 0,
+ last_seen DATETIME,
+ PRIMARY KEY (backend_id, source_ip, ip),
+ FOREIGN KEY (backend_id) REFERENCES backend_configs(id) ON DELETE CASCADE
+ );
+ `);
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_device_ip_source_ip ON device_ip_stats(backend_id, source_ip);`);
+
// Hourly aggregation per backend
this.db.exec(`
CREATE TABLE IF NOT EXISTS hourly_stats (
@@ -968,6 +1015,9 @@ export class StatsDatabase {
const minuteMap = new Map<string, { upload: number; download: number; connections: number }>();
const domainProxyMap = new Map<string, { domain: string; chain: string; upload: number; download: number; count: number }>();
const ipProxyMap = new Map<string, { ip: string; chain: string; upload: number; download: number; count: number; domains: Set<string> }>();
+ const deviceMap = new Map<string, { sourceIP: string; upload: number; download: number; count: number }>();
+ const deviceDomainMap = new Map<string, { sourceIP: string; domain: string; upload: number; download: number; count: number }>();
+ const deviceIPMap = new Map<string, { sourceIP: string; ip: string; upload: number; download: number; count: number }>();
for (const update of updates) {
if (update.upload === 0 && update.download === 0) continue;
@@ -1122,6 +1172,48 @@ export class StatsDatabase {
}
ipProxyMap.set(ipPKey, { ip: update.ip, chain: proxyChain, upload: update.upload, download: update.download, count: 1, domains });
}
+
+ // Aggregate device stats
+ if (update.sourceIP) {
+ const sourceIP = update.sourceIP;
+
+ // Device stats
+ const deviceKey = sourceIP;
+ const existingDevice = deviceMap.get(deviceKey);
+ if (existingDevice) {
+ existingDevice.upload += update.upload;
+ existingDevice.download += update.download;
+ existingDevice.count++;
+ } else {
+ deviceMap.set(deviceKey, { sourceIP, upload: update.upload, download: update.download, count: 1 });
+ }
+
+ // Device domain stats
+ if (update.domain) {
+ const deviceDomainKey = `${sourceIP}:${update.domain}`;
+ const existingDeviceDomain = deviceDomainMap.get(deviceDomainKey);
+ if (existingDeviceDomain) {
+ existingDeviceDomain.upload += update.upload;
+ existingDeviceDomain.download += update.download;
+ existingDeviceDomain.count++;
+ } else {
+ deviceDomainMap.set(deviceDomainKey, { sourceIP, domain: update.domain, upload: update.upload, download: update.download, count: 1 });
+ }
+ }
+
+ // Device IP stats
+ if (update.ip) {
+ const deviceIPKey = `${sourceIP}:${update.ip}`;
+ const existingDeviceIP = deviceIPMap.get(deviceIPKey);
+ if (existingDeviceIP) {
+ existingDeviceIP.upload += update.upload;
+ existingDeviceIP.download += update.download;
+ existingDeviceIP.count++;
+ } else {
+ deviceIPMap.set(deviceIPKey, { sourceIP, ip: update.ip, upload: update.upload, download: update.download, count: 1 });
+ }
+ }
+ }
}
// Execute batch upserts in a single transaction
@@ -1446,6 +1538,73 @@ export class StatsDatabase {
}
}
}
+ // Device stats
+ const deviceStmt = this.db.prepare(`
+ INSERT INTO device_stats (backend_id, source_ip, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @sourceIP, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, source_ip) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+
+ for (const [key, data] of deviceMap) {
+ deviceStmt.run({
+ backendId,
+ sourceIP: data.sourceIP,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
+ });
+ }
+
+ // Device domain stats
+ const deviceDomainStmt = this.db.prepare(`
+ INSERT INTO device_domain_stats (backend_id, source_ip, domain, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @sourceIP, @domain, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, source_ip, domain) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+
+ for (const [key, data] of deviceDomainMap) {
+ deviceDomainStmt.run({
+ backendId,
+ sourceIP: data.sourceIP,
+ domain: data.domain,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
+ });
+ }
+
+ // Device IP stats
+ const deviceIPStmt = this.db.prepare(`
+ INSERT INTO device_ip_stats (backend_id, source_ip, ip, total_upload, total_download, total_connections, last_seen)
+ VALUES (@backendId, @sourceIP, @ip, @upload, @download, @count, @timestamp)
+ ON CONFLICT(backend_id, source_ip, ip) DO UPDATE SET
+ total_upload = total_upload + @upload,
+ total_download = total_download + @download,
+ total_connections = total_connections + @count,
+ last_seen = @timestamp
+ `);
+
+ for (const [key, data] of deviceIPMap) {
+ deviceIPStmt.run({
+ backendId,
+ sourceIP: data.sourceIP,
+ ip: data.ip,
+ upload: data.upload,
+ download: data.download,
+ count: data.count,
+ timestamp
+ });
+ }
});
transaction();
@@ -1735,6 +1894,94 @@ export class StatsDatabase {
tx();
}
+ // Get device stats for a specific backend
+ getDevices(backendId: number, limit = 50, start?: string, end?: string): DeviceStats[] {
+ let query = `
+ SELECT source_ip as sourceIP,
+ total_upload as totalUpload, total_download as totalDownload,
+ total_connections as totalConnections, last_seen as lastSeen
+ FROM device_stats
+ WHERE backend_id = ?
+ `;
+ const params: any[] = [backendId];
+
+ if (start && end) {
+ // If time range provided, use minute_stats to filter (approximate) or adjust query if we had time-series device data
+ // For now we return all stats as device_stats is aggregated totals
+ }
+
+ query += ` ORDER BY (total_upload + total_download) DESC LIMIT ?`;
+ params.push(limit);
+
+ const stmt = this.db.prepare(query);
+ return stmt.all(...params) as DeviceStats[];
+ }
+
+ // Get domain breakdown for a specific device
+ getDeviceDomains(backendId: number, sourceIP: string): DomainStats[] {
+ const stmt = this.db.prepare(`
+ SELECT
+ d.domain,
+ d.total_upload as totalUpload,
+ d.total_download as totalDownload,
+ d.total_connections as totalConnections,
+ d.last_seen as lastSeen,
+ g.ips
+ FROM device_domain_stats d
+ LEFT JOIN domain_stats g ON d.domain = g.domain AND d.backend_id = g.backend_id
+ WHERE d.backend_id = ? AND d.source_ip = ?
+ ORDER BY (d.total_upload + d.total_download) DESC
+ LIMIT 100
+ `);
+ const result = stmt.all(backendId, sourceIP) as any[];
+ return result.map(r => ({
+ ...r,
+ ips: r.ips ? r.ips.split(',') : [],
+ rules: [],
+ chains: []
+ }));
+ }
+
+ // Get IP breakdown for a specific device
+ getDeviceIPs(backendId: number, sourceIP: string): IPStats[] {
+ const stmt = this.db.prepare(`
+ SELECT
+ d.ip,
+ d.total_upload as totalUpload,
+ d.total_download as totalDownload,
+ d.total_connections as totalConnections,
+ d.last_seen as lastSeen,
+ i.domains,
+ COALESCE(i.asn, g.asn) as asn,
+ CASE
+ WHEN g.country IS NOT NULL THEN
+ json_array(
+ g.country,
+ COALESCE(g.country_name, g.country),
+ COALESCE(g.city, ''),
+ COALESCE(g.as_name, '')
+ )
+ WHEN i.geoip IS NOT NULL THEN
+ json(i.geoip)
+ ELSE
+ NULL
+ END as geoIP
+ FROM device_ip_stats d
+ LEFT JOIN ip_stats i ON d.ip = i.ip AND d.backend_id = i.backend_id
+ LEFT JOIN geoip_cache g ON d.ip = g.ip
+ WHERE d.backend_id = ? AND d.source_ip = ?
+ ORDER BY (d.total_upload + d.total_download) DESC
+ LIMIT 100
+ `);
+ const result = stmt.all(backendId, sourceIP) as any[];
+ return result.map(r => ({
+ ...r,
+ domains: r.domains ? r.domains.split(',') : [],
+ geoIP: r.geoIP ? JSON.parse(r.geoIP).filter(Boolean) : undefined,
+ asn: r.asn || undefined,
+ }));
+ }
+
// Get top domains for a specific backend
getTopDomains(backendId: number, limit = 10): DomainStats[] {
return this.getDomainStats(backendId, limit);
@@ -2539,6 +2786,11 @@ export class StatsDatabase {
this.db.prepare(`DELETE FROM domain_proxy_stats WHERE backend_id = ?`).run(backendId);
this.db.prepare(`DELETE FROM ip_proxy_stats WHERE backend_id = ?`).run(backendId);
+ // Clear device stats
+ this.db.prepare(`DELETE FROM device_stats WHERE backend_id = ?`).run(backendId);
+ this.db.prepare(`DELETE FROM device_domain_stats WHERE backend_id = ?`).run(backendId);
+ this.db.prepare(`DELETE FROM device_ip_stats WHERE backend_id = ?`).run(backendId);
+
// Clear hourly stats (used for today traffic)
this.db.prepare(`DELETE FROM hourly_stats WHERE backend_id = ?`).run(backendId);
} else {
@@ -2589,6 +2841,11 @@ export class StatsDatabase {
this.db.prepare(`DELETE FROM domain_proxy_stats`).run();
this.db.prepare(`DELETE FROM ip_proxy_stats`).run();
+ // Clear device stats
+ this.db.prepare(`DELETE FROM device_stats`).run();
+ this.db.prepare(`DELETE FROM device_domain_stats`).run();
+ this.db.prepare(`DELETE FROM device_ip_stats`).run();
+
// Clear hourly stats (used for today traffic)
this.db.prepare(`DELETE FROM hourly_stats`).run();
} else {
@@ -2844,6 +3101,9 @@ export class StatsDatabase {
this.db.prepare(`DELETE FROM minute_stats WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM domain_proxy_stats WHERE backend_id = ?`).run(id);
this.db.prepare(`DELETE FROM ip_proxy_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM device_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM device_domain_stats WHERE backend_id = ?`).run(id);
+ this.db.prepare(`DELETE FROM device_ip_stats WHERE backend_id = ?`).run(id);
this.db.exec('COMMIT');
} catch (error) {
this.db.exec('ROLLBACK');
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsx
index 0c78934..1ecfa2d 100644
--- a/apps/web/app/[locale]/page.tsx
+++ b/apps/web/app/[locale]/page.tsx
@@ -28,6 +28,7 @@ import { OverviewTab } from "@/components/overview";
import { TopDomainsChart } from "@/components/top-domains-chart";
import { ProxyStatsChart } from "@/components/proxy-stats-chart";
import { InteractiveProxyStats } from "@/components/interactive-proxy-stats";
+import { InteractiveDeviceStats } from "@/components/interactive-device-stats";
import { InteractiveRuleStats } from "@/components/interactive-rule-stats";
import { RuleChainChart } from "@/components/rule-chain-chart";
import { WorldTrafficMap } from "@/components/world-traffic-map";
@@ -58,7 +59,7 @@ import {
type Backend,
} from "@/lib/api";
import { cn } from "@/lib/utils";
-import type { StatsSummary, CountryStats } from "@clashmaster/shared";
+import type { StatsSummary, CountryStats, DeviceStats } from "@clashmaster/shared";
function formatTimeAgo(date: Date, t: any): string {
const now = new Date();
@@ -77,6 +78,7 @@ const NAV_ITEMS = [
{ id: "overview", label: "overview" },
{ id: "domains", label: "domains" },
{ id: "countries", label: "countries" },
+ { id: "devices", label: "devices" },
{ id: "proxies", label: "proxies" },
{ id: "rules", label: "rules" },
];
@@ -193,6 +195,48 @@ const RulesContent = memo(function RulesContent({
);
});
+const DevicesContent = memo(function DevicesContent({
+ activeBackendId,
+}: {
+ activeBackendId?: number;
+}) {
+ const [deviceStats, setDeviceStats] = useState<DeviceStats[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ const fetchDevices = async () => {
+ setLoading(true);
+ try {
+ const data = await api.getDevices(activeBackendId);
+ setDeviceStats(data);
+ } catch (err) {
+ console.error("Failed to fetch device stats:", err);
+ setDeviceStats([]);
+ } finally {
+ setLoading(false);
+ }
+ };
+ fetchDevices();
+ }, [activeBackendId]);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center p-12">
+ <RefreshCw className="w-6 h-6 animate-spin text-muted-foreground" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <InteractiveDeviceStats
+ data={deviceStats}
+ activeBackendId={activeBackendId}
+ />
+ </div>
+ );
+});
+
const NetworkContent = memo(function NetworkContent() {
const t = useTranslations("network");
return (
@@ -349,6 +393,8 @@ export default function DashboardPage() {
);
case "rules":
return <RulesContent data={data} activeBackendId={activeBackend?.id} />;
+ case "devices":
+ return <DevicesContent activeBackendId={activeBackend?.id} />;
case "network":
return <NetworkContent />;
default:
diff --git a/apps/web/components/interactive-device-stats.tsx b/apps/web/components/interactive-device-stats.tsx
new file mode 100644
index 0000000..d17ae31
--- /dev/null
+++ b/apps/web/components/interactive-device-stats.tsx
@@ -0,0 +1,273 @@
+"use client";
+
+import { useState, useCallback, useMemo, useEffect } from "react";
+import { Loader2, BarChart3, Link2, Smartphone, Monitor, Tablet, HelpCircle } from "lucide-react";
+import { useTranslations } from "next-intl";
+import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip, BarChart, Bar, XAxis, YAxis, Cell as BarCell, LabelList } from "recharts";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { formatBytes, formatNumber } from "@/lib/utils";
+import { cn } from "@/lib/utils";
+import { api } from "@/lib/api";
+import { Favicon } from "@/components/favicon";
+import { DomainStatsTable, IPStatsTable } from "@/components/stats-tables";
+import { COLORS } from "@/lib/stats-utils";
+import type { DeviceStats, DomainStats, IPStats } from "@clashmaster/shared";
+
+interface InteractiveDeviceStatsProps {
+ data: DeviceStats[];
+ activeBackendId?: number;
+}
+
+
+
+function renderCustomBarLabel(props: any) {
+ const { x, y, width, value, height } = props;
+ return (
+ <text x={x + width + 6} y={y + height / 2} fill="currentColor" fontSize={11} dominantBaseline="central" textAnchor="start" style={{ fontVariantNumeric: "tabular-nums" }}>
+ {formatBytes(value, 0)}
+ </text>
+ );
+}
+
+export function InteractiveDeviceStats({ data, activeBackendId }: InteractiveDeviceStatsProps) {
+ const t = useTranslations("devices");
+ const domainsT = useTranslations("domains");
+
+ const [selectedDevice, setSelectedDevice] = useState<string | null>(null);
+ const [deviceDomains, setDeviceDomains] = useState<DomainStats[]>([]);
+ const [deviceIPs, setDeviceIPs] = useState<IPStats[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [activeTab, setActiveTab] = useState("domains");
+ const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);
+
+ useEffect(() => {
+ const media = window.matchMedia("(min-width: 640px)");
+ const update = () => setShowDomainBarLabels(media.matches);
+ update();
+ media.addEventListener("change", update);
+ return () => media.removeEventListener("change", update);
+ }, []);
+
+ const chartData = useMemo(() => {
+ if (!data) return [];
+ return data.map((device, index) => ({
+ name: device.sourceIP,
+ rawName: device.sourceIP,
+ value: device.totalDownload + device.totalUpload,
+ download: device.totalDownload,
+ upload: device.totalUpload,
+ connections: device.totalConnections,
+ color: COLORS[index % COLORS.length],
+ rank: index,
+ }));
+ }, [data]);
+
+ const totalTraffic = useMemo(() => chartData.reduce((sum, item) => sum + item.value, 0), [chartData]);
+ const topDevices = useMemo(() => [...chartData].sort((a, b) => b.value - a.value).slice(0, 4), [chartData]);
+ const maxTotal = useMemo(() => chartData.length ? Math.max(...chartData.map(d => d.value)) : 1, [chartData]);
+
+ const loadDeviceDetails = useCallback(async (sourceIP: string) => {
+ setLoading(true);
+ try {
+ const [domains, ips] = await Promise.all([
+ api.getDeviceDomains(sourceIP, activeBackendId),
+ api.getDeviceIPs(sourceIP, activeBackendId),
+ ]);
+ setDeviceDomains(domains);
+ setDeviceIPs(ips);
+ } catch (err) {
+ console.error(`Failed to load details for ${sourceIP}:`, err);
+ setDeviceDomains([]);
+ setDeviceIPs([]);
+ } finally {
+ setLoading(false);
+ }
+ }, [activeBackendId]);
+
+ useEffect(() => {
+ if (chartData.length > 0 && !selectedDevice) {
+ const firstDevice = chartData[0].rawName;
+ setSelectedDevice(firstDevice);
+ loadDeviceDetails(firstDevice);
+ }
+ }, [chartData, selectedDevice, loadDeviceDetails]);
+
+ const handleDeviceClick = useCallback((rawName: string) => {
+ if (selectedDevice !== rawName) {
+ setSelectedDevice(rawName);
+ loadDeviceDetails(rawName);
+ }
+ }, [selectedDevice, loadDeviceDetails]);
+
+ const selectedDeviceData = useMemo(() => chartData.find(d => d.rawName === selectedDevice), [chartData, selectedDevice]);
+
+ const domainChartData = useMemo(() => {
+ return [...deviceDomains]
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
+ .slice(0, 10)
+ .map((d, i) => ({
+ name: d.domain.length > 25 ? d.domain.slice(0, 22) + "..." : d.domain,
+ fullName: d.domain,
+ total: d.totalDownload + d.totalUpload,
+ download: d.totalDownload,
+ upload: d.totalUpload,
+ connections: d.totalConnections,
+ color: COLORS[i % COLORS.length],
+ }));
+ }, [deviceDomains]);
+
+ if (chartData.length === 0) {
+ return (
+ <Card>
+ <CardContent className="p-12 text-center text-muted-foreground">
+ <Smartphone className="w-8 h-8 mx-auto mb-2 opacity-50" />
+ <p>{t("noData")}</p>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
+ {/* Pie Chart */}
+ <Card className="lg:col-span-3">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">{t("title")}</CardTitle>
+ </CardHeader>
+ <CardContent className="pt-2 pb-4">
+ <div className="h-[165px] w-full">
+ <ResponsiveContainer width="100%" height="100%">
+ <PieChart>
+ <Pie data={chartData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={2} dataKey="value">
+ {chartData.map((entry, index) => (<Cell key={`cell-${index}`} fill={entry.color} />))}
+ </Pie>
+ <RechartsTooltip content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const item = payload[0].payload;
+ return (<div className="bg-background border border-border p-3 rounded-lg shadow-lg"><p className="font-medium text-sm mb-1">{item.name}</p><p className="text-xs text-muted-foreground">{formatBytes(item.value)}</p></div>);
+ }
+ return null;
+ }} />
+ </PieChart>
+ </ResponsiveContainer>
+ </div>
+ {topDevices.length > 0 && (
+ <div className="mt-2">
+ <p className="text-[10px] text-muted-foreground uppercase tracking-wider text-center">Top 4</p>
+ <div className="mt-1 space-y-1.5">
+ {topDevices.map((item, idx) => {
+ const rankBadgeClass = idx === 0 ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300" : idx === 1 ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300" : idx === 2 ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300" : "bg-muted text-muted-foreground";
+ return (
+ <div key={item.rawName} title={item.name} className="flex items-center gap-1.5 min-w-0">
+ <span className={cn("w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0", rankBadgeClass)}>
+ {idx + 1}
+ </span>
+ <div className="px-1.5 py-0.5 rounded-md text-[10px] font-medium text-white/90 truncate min-w-0 max-w-full flex items-center gap-1" style={{ backgroundColor: item.color }}>
+ <span className="truncate">{item.name}</span>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ {/* Device List */}
+ <Card className="lg:col-span-4">
+ <CardHeader className="pb-2"><CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">{t("title")}</CardTitle></CardHeader>
+ <CardContent className="p-3">
+ <ScrollArea className="h-[280px] pr-3">
+ <div className="space-y-2">
+ {chartData.map((item) => {
+ const percentage = totalTraffic > 0 ? (item.value / totalTraffic) * 100 : 0;
+ const barPercent = (item.value / maxTotal) * 100;
+ const isSelected = selectedDevice === item.rawName;
+ const badgeColor = item.rank === 0 ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" : item.rank === 1 ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300" : item.rank === 2 ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" : "bg-muted text-muted-foreground";
+ return (
+ <button key={item.rawName} onClick={() => handleDeviceClick(item.rawName)} className={cn("w-full p-2.5 rounded-xl border text-left transition-all duration-200", isSelected ? "border-primary bg-primary/5 ring-1 ring-primary/20" : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30")}>
+ <div className="flex items-center gap-2 mb-1.5">
+ <span className={cn("w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0", badgeColor)}>{item.rank + 1}</span>
+ <span className="flex-1 text-sm font-medium truncate" title={item.name}>{item.name}</span>
+ <span className="text-sm font-bold tabular-nums shrink-0">{formatBytes(item.value)}</span>
+ </div>
+ <div className="pl-7 space-y-1">
+ <div className="h-1.5 rounded-full bg-muted overflow-hidden flex">
+ <div className="h-full bg-blue-500 dark:bg-blue-400" style={{ width: `${(item.download / item.value) * barPercent}%` }} />
+ <div className="h-full bg-purple-500 dark:bg-purple-400" style={{ width: `${(item.upload / item.value) * barPercent}%` }} />
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-1 text-xs text-muted-foreground">
+ <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
+ <span className="text-blue-500 dark:text-blue-400">↓ {formatBytes(item.download)}</span>
+ <span className="text-purple-500 dark:text-purple-400">↑ {formatBytes(item.upload)}</span>
+ <span className="flex items-center gap-1 tabular-nums"><Link2 className="w-3 h-3" />{formatNumber(item.connections)}</span>
+ </div>
+ <span className="tabular-nums">{percentage.toFixed(1)}%</span>
+ </div>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ </ScrollArea>
+ </CardContent>
+ </Card>
+
+ {/* Top Domains Chart */}
+ <Card className="lg:col-span-5">
+ <CardHeader className="pb-2">
+ <div className="flex items-center justify-between">
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2"><BarChart3 className="h-4 w-4" />{domainsT("title")}</CardTitle>
+ {selectedDeviceData && (<span className="text-xs text-muted-foreground">{selectedDeviceData.name}</span>)}
+ </div>
+ </CardHeader>
+ <CardContent className="pt-0">
+ {loading ? (<div className="h-[280px] flex items-center justify-center"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>
+ ) : domainChartData.length === 0 ? (<div className="h-[280px] flex items-center justify-center text-muted-foreground text-sm">{domainsT("noData")}</div>
+ ) : (
+ <div className="h-[280px] w-full">
+ <ResponsiveContainer width="100%" height="100%">
+ <BarChart data={domainChartData} layout="vertical" margin={{ left: 0, right: showDomainBarLabels ? 60 : 10, top: 5, bottom: 5 }}>
+ <XAxis type="number" hide />
+ <YAxis type="category" dataKey="name" width={100} tick={{ fontSize: 11 }} tickLine={false} axisLine={false} />
+ <RechartsTooltip content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const item = payload[0].payload;
+ return (<div className="bg-background border border-border p-3 rounded-lg shadow-lg min-w-[160px]"><div className="flex items-center gap-2 mb-2 pb-2 border-b border-border/50"><Favicon domain={item.fullName} size="sm" /><span className="font-medium text-sm truncate max-w-[180px]" title={item.fullName}>{item.fullName}</span></div><div className="space-y-2 text-xs"><div className="flex justify-between items-center"><span className="text-muted-foreground">Total</span><span className="font-semibold">{formatBytes(item.total)}</span></div><div className="flex justify-between items-center"><span className="text-blue-500">Download</span><span>{formatBytes(item.download)}</span></div><div className="flex justify-between items-center"><span className="text-purple-500">Upload</span><span>{formatBytes(item.upload)}</span></div><div className="flex justify-between items-center pt-1 border-t border-border/50"><span className="text-emerald-500">Connections</span><span>{formatNumber(item.connections)}</span></div></div></div>);
+ }
+ return null;
+ }} cursor={{ fill: "rgba(128, 128, 128, 0.1)" }} />
+ <Bar dataKey="total" radius={[0, 4, 4, 0]} maxBarSize={24}>
+ {domainChartData.map((entry, index) => (<BarCell key={`cell-${index}`} fill={entry.color} />))}
+ {showDomainBarLabels && (<LabelList dataKey="total" position="right" content={renderCustomBarLabel} />)}
+ </Bar>
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+
+ {/* Bottom: Tabs with shared table components */}
+ {selectedDevice && (
+ <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
+ <TabsList className="glass">
+ <TabsTrigger value="domains">{domainsT("domainList")}</TabsTrigger>
+ <TabsTrigger value="ips">IP Addresses</TabsTrigger>
+ </TabsList>
+ <TabsContent value="domains" className="mt-4">
+ <DomainStatsTable domains={deviceDomains} loading={loading} />
+ </TabsContent>
+ <TabsContent value="ips" className="mt-4">
+ <IPStatsTable ips={deviceIPs} loading={loading} />
+ </TabsContent>
+ </Tabs>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/components/interactive-proxy-stats.tsx b/apps/web/components/interactive-proxy-stats.tsx
index 3b970bd..b5a772e 100644
--- a/apps/web/components/interactive-proxy-stats.tsx
+++ b/apps/web/components/interactive-proxy-stats.tsx
@@ -1,25 +1,18 @@
"use client";
import { useState, useCallback, useMemo, useEffect } from "react";
-import { Server, ChevronLeft, ChevronRight, Loader2, BarChart3, Link2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, Waypoints, ChevronDown, ChevronUp } from "lucide-react";
+import { Loader2, BarChart3, Link2, Waypoints } from "lucide-react";
import { useTranslations } from "next-intl";
-import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip } from "recharts";
-import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Cell as BarCell, LabelList } from "recharts";
+import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip, BarChart, Bar, XAxis, YAxis, Cell as BarCell, LabelList } from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-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 } from "@/lib/api";
import { Favicon } from "@/components/favicon";
+import { DomainStatsTable, IPStatsTable } from "@/components/stats-tables";
+import { COLORS } from "@/lib/stats-utils";
import type { ProxyStats, DomainStats, IPStats } from "@clashmaster/shared";
interface InteractiveProxyStatsProps {
@@ -27,43 +20,11 @@ interface InteractiveProxyStatsProps {
activeBackendId?: number;
}
-const COLORS = [
- "#3B82F6", "#8B5CF6", "#06B6D4", "#10B981", "#F59E0B",
- "#EF4444", "#EC4899", "#6366F1", "#14B8A6", "#F97316",
-];
-
-const CHART_COLORS = [
- "#3B82F6", "#8B5CF6", "#06B6D4", "#10B981", "#F59E0B",
- "#EF4444", "#EC4899", "#6366F1", "#14B8A6", "#F97316",
-];
-
-const PAGE_SIZE_OPTIONS = [10, 20, 50] as const;
-type PageSize = typeof PAGE_SIZE_OPTIONS[number];
-
-// Generate gradient based on IP - same as DomainsTable
-const getIPGradient = (ip: string) => {
- const colors = [
- "from-emerald-500 to-teal-400",
- "from-blue-500 to-cyan-400",
- "from-violet-500 to-purple-400",
- "from-orange-500 to-amber-400",
- "from-rose-500 to-pink-400",
- ];
- let hash = 0;
- for (let i = 0; i < ip.length; i++) {
- hash = ip.charCodeAt(i) + ((hash << 5) - hash);
- }
- return colors[Math.abs(hash) % colors.length];
-};
-
-// Keep original proxy name - preserve emojis and special characters
function simplifyProxyName(name: string): string {
if (!name) return "DIRECT";
- // Keep original name with emojis, just trim whitespace
return name.trim();
}
-// Get emoji for proxy
function getProxyEmoji(name: string): string {
if (name.includes("🇺🇸")) return "🇺🇸";
if (name.includes("🇯🇵")) return "🇯🇵";
@@ -75,67 +36,10 @@ function getProxyEmoji(name: string): string {
return "🌐";
}
-// 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 getDomainColor = (domain: string) => {
- let hash = 0;
- for (let i = 0; i < domain.length; i++) {
- hash = domain.charCodeAt(i) + ((hash << 5) - hash);
- }
- return ICON_COLORS[Math.abs(hash) % ICON_COLORS.length];
-};
-
-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];
-};
-
-// Country flag emoji mapping
-const COUNTRY_FLAGS: Record<string, string> = {
- US: "🇺🇸", CN: "🇨🇳", JP: "🇯🇵", SG: "🇸🇬", HK: "🇭🇰",
- TW: "🇹🇼", KR: "🇰🇷", GB: "🇬🇧", DE: "🇩🇪", FR: "🇫🇷",
- NL: "🇳🇱", CA: "🇨🇦", AU: "🇦🇺", IN: "🇮🇳", BR: "🇧🇷",
- RU: "🇷🇺", SE: "🇸🇪", CH: "🇨🇭", IL: "🇮🇱", ID: "🇮🇩",
- LOCAL: "🏠",
-};
-
-function getCountryFlag(country: string): string {
- return COUNTRY_FLAGS[country] || COUNTRY_FLAGS[country.toUpperCase()] || "🌐";
-}
-
-// Custom label renderer for bar chart
function renderCustomBarLabel(props: any) {
const { x, y, width, value, height } = props;
return (
- <text
- x={x + width + 6}
- y={y + height / 2}
- fill="currentColor"
- fontSize={11}
- dominantBaseline="central"
- textAnchor="start"
- style={{ fontVariantNumeric: "tabular-nums" }}
- >
+ <text x={x + width + 6} y={y + height / 2} fill="currentColor" fontSize={11} dominantBaseline="central" textAnchor="start" style={{ fontVariantNumeric: "tabular-nums" }}>
{formatBytes(value, 0)}
</text>
);
@@ -144,33 +48,14 @@ function renderCustomBarLabel(props: any) {
export function InteractiveProxyStats({ data, activeBackendId }: InteractiveProxyStatsProps) {
const t = useTranslations("proxies");
const domainsT = useTranslations("domains");
- const ipsT = useTranslations("ips");
const [selectedProxy, setSelectedProxy] = useState<string | null>(null);
const [proxyDomains, setProxyDomains] = useState<DomainStats[]>([]);
const [proxyIPs, setProxyIPs] = useState<IPStats[]>([]);
const [loading, setLoading] = useState(false);
const [activeTab, setActiveTab] = useState("domains");
-
- // Pagination states
- const [domainPage, setDomainPage] = useState(1);
- const [domainPageSize, setDomainPageSize] = useState<PageSize>(10);
- const [domainSearch, setDomainSearch] = useState("");
- const [ipPage, setIpPage] = useState(1);
- const [ipPageSize, setIpPageSize] = useState<PageSize>(10);
- const [ipSearch, setIpSearch] = useState("");
const [showDomainBarLabels, setShowDomainBarLabels] = useState(true);
- // 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);
-
useEffect(() => {
const media = window.matchMedia("(min-width: 640px)");
const update = () => setShowDomainBarLabels(media.matches);
@@ -194,71 +79,10 @@ export function InteractiveProxyStats({ data, activeBackendId }: InteractiveProx
}));
}, [data]);
- const totalTraffic = useMemo(() => {
- return chartData.reduce((sum, item) => sum + item.value, 0);
- }, [chartData]);
-
- const topProxies = useMemo(
- () => [...chartData].sort((a, b) => b.value - a.value).slice(0, 4),
- [chartData]
- );
-
- const maxTotal = useMemo(() => {
- if (!chartData.length) return 1;
- return Math.max(...chartData.map(p => p.value));
- }, [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) => {
- setExpandedDomain(expandedDomain === domain ? null : domain);
- };
-
- const toggleExpandIP = (ip: string) => {
- setExpandedIP(expandedIP === ip ? null : ip);
- };
-
- // 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" />
- );
- };
+ const totalTraffic = useMemo(() => chartData.reduce((sum, item) => sum + item.value, 0), [chartData]);
+ const topProxies = useMemo(() => [...chartData].sort((a, b) => b.value - a.value).slice(0, 4), [chartData]);
+ const maxTotal = useMemo(() => chartData.length ? Math.max(...chartData.map(p => p.value)) : 1, [chartData]);
- // Load proxy details
const loadProxyDetails = useCallback(async (chain: string) => {
setLoading(true);
try {
@@ -268,11 +92,6 @@ export function InteractiveProxyStats({ data, activeBackendId }: InteractiveProx
]);
setProxyDomains(domains);
setProxyIPs(ips);
- // Reset pagination
- setDomainPage(1);
- setIpPage(1);
- setDomainSearch("");
- setIpSearch("");
} catch (err) {
console.error(`Failed to load details for ${chain}:`, err);
setProxyDomains([]);
@@ -282,7 +101,6 @@ export function InteractiveProxyStats({ data, activeBackendId }: InteractiveProx
}
}, [activeBackendId]);
- // Default select first proxy when data loads
useEffect(() => {
if (chartData.length > 0 && !selectedProxy) {
const firstProxy = chartData[0].rawName;
@@ -291,119 +109,36 @@ export function InteractiveProxyStats({ data, activeBackendId }: InteractiveProx
}
}, [chartData, selectedProxy, loadProxyDetails]);
- const handleProxyClick = useCallback((chain: string) => {
- if (selectedProxy !== chain) {
- setSelectedProxy(chain);
- loadProxyDetails(chain);
+ const handleProxyClick = useCallback((rawName: string) => {
+ if (selectedProxy !== rawName) {
+ setSelectedProxy(rawName);
+ loadProxyDetails(rawName);
}
}, [selectedProxy, loadProxyDetails]);
- const selectedProxyData = useMemo(() => {
- return chartData.find(p => p.rawName === selectedProxy);
- }, [chartData, selectedProxy]);
-
- // Filter, sort and paginate domains
- const filteredDomains = useMemo(() => {
- let result = proxyDomains;
- if (domainSearch) {
- result = proxyDomains.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;
- });
- }, [proxyDomains, domainSearch, domainSortKey, domainSortOrder]);
-
- const paginatedDomains = useMemo(() => {
- const start = (domainPage - 1) * domainPageSize;
- return filteredDomains.slice(start, start + domainPageSize);
- }, [filteredDomains, domainPage, domainPageSize]);
-
- const domainTotalPages = Math.ceil(filteredDomains.length / domainPageSize);
+ const selectedProxyData = useMemo(() => chartData.find(d => d.rawName === selectedProxy), [chartData, selectedProxy]);
- // Filter, sort and paginate IPs
- const filteredIPs = useMemo(() => {
- let result = proxyIPs;
- if (ipSearch) {
- result = proxyIPs.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;
- });
- }, [proxyIPs, ipSearch, ipSortKey, ipSortOrder]);
-
- const paginatedIPs = useMemo(() => {
- const start = (ipPage - 1) * ipPageSize;
- return filteredIPs.slice(start, start + ipPageSize);
- }, [filteredIPs, ipPage, ipPageSize]);
-
- const ipTotalPages = Math.ceil(filteredIPs.length / ipPageSize);
-
- // Chart data
const domainChartData = useMemo(() => {
- if (!proxyDomains?.length) return [];
- return proxyDomains
+ return [...proxyDomains]
+ .sort((a, b) => (b.totalDownload + b.totalUpload) - (a.totalDownload + a.totalUpload))
.slice(0, 10)
- .map((domain, index) => ({
- name: domain.domain.length > 15 ? domain.domain.slice(0, 15) + "..." : domain.domain,
- fullDomain: domain.domain,
- total: domain.totalDownload + domain.totalUpload,
- download: domain.totalDownload,
- upload: domain.totalUpload,
- connections: domain.totalConnections,
- color: CHART_COLORS[index % CHART_COLORS.length],
+ .map((d, i) => ({
+ name: d.domain.length > 25 ? d.domain.slice(0, 22) + "..." : d.domain,
+ fullName: d.domain,
+ total: d.totalDownload + d.totalUpload,
+ download: d.totalDownload,
+ upload: d.totalUpload,
+ connections: d.totalConnections,
+ color: COLORS[i % COLORS.length],
}));
}, [proxyDomains]);
- 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 (chartData.length === 0) {
return (
<Card>
<CardContent className="p-12 text-center text-muted-foreground">
- {t("noData")}
+ <Waypoints className="w-8 h-8 mx-auto mb-2 opacity-50" />
+ <p>{t("noData")}</p>
</CardContent>
</Card>
);
@@ -411,85 +146,36 @@ export function InteractiveProxyStats({ data, activeBackendId }: InteractiveProx
return (
<div className="space-y-6">
- {/* Top Section: Three Column Layout */}
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
- {/* Left: Pie Chart (3 columns) */}
+ {/* Pie Chart */}
<Card className="lg:col-span-3">
<CardHeader className="pb-2">
- <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
- {t("distribution")}
- </CardTitle>
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">{t("title")}</CardTitle>
</CardHeader>
<CardContent className="pt-2 pb-4">
<div className="h-[165px] w-full">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
- <Pie
- data={chartData}
- cx="50%"
- cy="50%"
- innerRadius={50}
- outerRadius={80}
- paddingAngle={2}
- dataKey="value">
- {chartData.map((entry, index) => (
- <Cell key={`cell-${index}`} fill={entry.color} />
- ))}
+ <Pie data={chartData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={2} dataKey="value">
+ {chartData.map((entry, index) => (<Cell key={`cell-${index}`} fill={entry.color} />))}
</Pie>
- <RechartsTooltip
- content={({ active, payload }) => {
- if (active && payload && payload.length) {
- const item = payload[0].payload;
- return (
- <div className="bg-background border border-border p-3 rounded-lg shadow-lg">
- <p className="font-medium text-sm mb-1">{item.name}</p>
- <p className="text-xs text-muted-foreground">{formatBytes(item.value)}</p>
- </div>
- );
- }
- return null;
- }}
- />
+ <RechartsTooltip content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const item = payload[0].payload;
+ return (<div className="bg-background border border-border p-3 rounded-lg shadow-lg"><p className="font-medium text-sm mb-1">{item.emoji} {item.name}</p><p className="text-xs text-muted-foreground">{formatBytes(item.value)}</p></div>);
+ }
+ return null;
+ }} />
</PieChart>
</ResponsiveContainer>
</div>
{topProxies.length > 0 && (
<div className="mt-2">
- <p className="text-[10px] text-muted-foreground uppercase tracking-wider text-center">
- Top 4
- </p>
+ <p className="text-[10px] text-muted-foreground uppercase tracking-wider text-center">Top 4</p>
<div className="mt-1 space-y-1.5">
{topProxies.map((item, idx) => {
- const rankBadgeClass = idx === 0
- ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300"
- : idx === 1
- ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"
- : idx === 2
- ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300"
- : "bg-muted text-muted-foreground";
-
- return (
- <div
- key={item.rawName}
- title={item.name}
- className="flex items-center gap-1.5 min-w-0"
- >
- <span
- className={cn(
- "w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0",
- rankBadgeClass
- )}
- >
- {idx + 1}
- </span>
- <span
- className="px-1.5 py-0.5 rounded-md text-[10px] font-medium text-white/90 truncate min-w-0"
- style={{ backgroundColor: item.color }}
- >
- {item.name}
- </span>
- </div>
- );
+ const rankBadgeClass = idx === 0 ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300" : idx === 1 ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300" : idx === 2 ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300" : "bg-muted text-muted-foreground";
+ return (<div key={item.rawName} title={item.name} className="flex items-center gap-1.5 min-w-0"><span className={cn("w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0", rankBadgeClass)}>{idx + 1}</span><span className="px-1.5 py-0.5 rounded-md text-[10px] font-medium text-white/90 truncate min-w-0" style={{ backgroundColor: item.color }}>{item.emoji} {item.name}</span></div>);
})}
</div>
</div>
@@ -497,905 +183,95 @@ export function InteractiveProxyStats({ data, activeBackendId }: InteractiveProx
</CardContent>
</Card>
- {/* Middle: Proxy List (4 columns) - Style like TopProxiesSimple */}
+ {/* Proxy List */}
<Card className="lg:col-span-4">
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
- {t("proxyNodes")}
- </CardTitle>
- </CardHeader>
+ <CardHeader className="pb-2"><CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">{t("title")}</CardTitle></CardHeader>
<CardContent className="p-3">
<ScrollArea className="h-[280px] pr-3">
<div className="space-y-2">
{chartData.map((item) => {
- const percentage = totalTraffic > 0 ? (item.value / totalTraffic) * 100 : 0;
- const barPercent = (item.value / maxTotal) * 100;
- const isSelected = selectedProxy === item.rawName;
-
- // Badge color based on rank like TopProxiesSimple
- const badgeColor = item.rank === 0
- ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400"
- : item.rank === 1
- ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"
- : item.rank === 2
- ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400"
- : "bg-muted text-muted-foreground";
-
- return (
- <button
- key={item.rawName}
- onClick={() => handleProxyClick(item.rawName)}
- className={cn(
- "w-full p-2.5 rounded-xl border text-left transition-all duration-200",
- isSelected
- ? "border-primary bg-primary/5 ring-1 ring-primary/20"
- : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30"
- )}>
- {/* Row 1: Rank + Name + Total */}
- <div className="flex items-center gap-2 mb-1.5">
- <span className={cn(
- "w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0",
- badgeColor
- )}>
- {item.rank + 1}
- </span>
-
- <span className="flex-1 text-sm font-medium truncate" title={item.name}>
- {item.name}
- </span>
-
- <span className="text-sm font-bold tabular-nums shrink-0">
- {formatBytes(item.value)}
- </span>
- </div>
-
- {/* Row 2: Progress bar + Stats */}
- <div className="pl-7 space-y-1">
- {/* Progress bar - dual color like TopProxiesSimple */}
- <div className="h-1.5 rounded-full bg-muted overflow-hidden flex">
- <div
- className="h-full bg-blue-500 dark:bg-blue-400"
- style={{ width: `${(item.download / item.value) * barPercent}%` }}
- />
- <div
- className="h-full bg-purple-500 dark:bg-purple-400"
- style={{ width: `${(item.upload / item.value) * barPercent}%` }}
- />
+ const percentage = totalTraffic > 0 ? (item.value / totalTraffic) * 100 : 0;
+ const barPercent = (item.value / maxTotal) * 100;
+ const isSelected = selectedProxy === item.rawName;
+ const badgeColor = item.rank === 0 ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" : item.rank === 1 ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300" : item.rank === 2 ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" : "bg-muted text-muted-foreground";
+ return (
+ <button key={item.rawName} onClick={() => handleProxyClick(item.rawName)} className={cn("w-full p-2.5 rounded-xl border text-left transition-all duration-200", isSelected ? "border-primary bg-primary/5 ring-1 ring-primary/20" : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30")}>
+ <div className="flex items-center gap-2 mb-1.5">
+ <span className={cn("w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0", badgeColor)}>{item.rank + 1}</span>
+ <span className="text-sm shrink-0">{item.emoji}</span>
+ <span className="flex-1 text-sm font-medium truncate" title={item.name}>{item.name}</span>
+ <span className="text-sm font-bold tabular-nums shrink-0">{formatBytes(item.value)}</span>
</div>
- {/* Stats */}
- <div className="flex flex-wrap items-center justify-between gap-1 text-xs text-muted-foreground">
- <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
- <span className="text-blue-500 dark:text-blue-400">↓ {formatBytes(item.download)}</span>
- <span className="text-purple-500 dark:text-purple-400">↑ {formatBytes(item.upload)}</span>
- <span className="flex items-center gap-1 tabular-nums">
- <Link2 className="w-3 h-3" />
- {formatNumber(item.connections)}
- </span>
+ <div className="pl-7 space-y-1">
+ <div className="h-1.5 rounded-full bg-muted overflow-hidden flex">
+ <div className="h-full bg-blue-500 dark:bg-blue-400" style={{ width: `${(item.download / item.value) * barPercent}%` }} />
+ <div className="h-full bg-purple-500 dark:bg-purple-400" style={{ width: `${(item.upload / item.value) * barPercent}%` }} />
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-1 text-xs text-muted-foreground">
+ <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
+ <span className="text-blue-500 dark:text-blue-400">↓ {formatBytes(item.download)}</span>
+ <span className="text-purple-500 dark:text-purple-400">↑ {formatBytes(item.upload)}</span>
+ <span className="flex items-center gap-1 tabular-nums"><Link2 className="w-3 h-3" />{formatNumber(item.connections)}</span>
+ </div>
+ <span className="tabular-nums">{percentage.toFixed(1)}%</span>
</div>
- <span className="tabular-nums">{percentage.toFixed(1)}%</span>
</div>
- </div>
- </button>
- );
- })}
+ </button>
+ );
+ })}
</div>
</ScrollArea>
</CardContent>
</Card>
- {/* Right: Top Domains Chart (5 columns) */}
+ {/* Top Domains Chart */}
<Card className="lg:col-span-5">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
- <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2">
- <BarChart3 className="h-4 w-4" />
- {t("topDomains")}
- </CardTitle>
- {selectedProxyData && (
- <span className="text-xs text-muted-foreground">
- {selectedProxyData.name}
- </span>
- )}
+ <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2"><BarChart3 className="h-4 w-4" />{domainsT("title")}</CardTitle>
+ {selectedProxyData && (<span className="text-xs text-muted-foreground">{selectedProxyData.emoji} {selectedProxyData.name}</span>)}
</div>
</CardHeader>
- <CardContent>
- {loading ? (
- <div className="flex items-center justify-center py-8 h-[280px]">
- <div className="h-5 w-5 border-2 border-primary/30 border-t-primary rounded-full animate-spin" />
- </div>
- ) : domainChartData.length === 0 ? (
- <div className="text-center py-8 text-muted-foreground h-[280px] flex items-center justify-center">
- {domainsT("noResults")}
- </div>
+ <CardContent className="pt-0">
+ {loading ? (<div className="h-[280px] flex items-center justify-center"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>
+ ) : domainChartData.length === 0 ? (<div className="h-[280px] flex items-center justify-center text-muted-foreground text-sm">{domainsT("noData")}</div>
) : (
- <div className="h-[280px] w-full min-w-0 overflow-hidden sm:overflow-visible">
+ <div className="h-[280px] w-full">
<ResponsiveContainer width="100%" height="100%">
- <BarChart
- data={domainChartData}
- layout="vertical"
- margin={{ top: 5, right: showDomainBarLabels ? 50 : 10, left: 5, bottom: 5 }}
- >
- <CartesianGrid
- strokeDasharray="3 3"
- stroke="#888888"
- opacity={0.2}
- horizontal={false}
- />
- <XAxis
- type="number"
- tickFormatter={(value) => formatBytes(value, 0)}
- tick={{ fill: "#888888", fontSize: 10 }}
- tickLine={false}
- axisLine={false}
- />
- <YAxis
- type="category"
- dataKey="name"
- width={90}
- tick={{ fontSize: 10, fill: "currentColor" }}
- tickLine={false}
- axisLine={false}
- />
- <RechartsTooltip
- content={({ active, payload }) => {
- if (active && payload && payload.length) {
- const item = payload[0].payload;
- return (
- <div className="bg-background border border-border p-3 rounded-lg shadow-lg min-w-[200px] max-w-[90vw] sm:min-w-[280px]">
- <div className="flex items-center gap-2 mb-3">
- <Favicon domain={item.fullDomain} size="sm" />
- <span className="font-medium text-sm text-foreground truncate max-w-[200px]">
- {item.fullDomain}
- </span>
- </div>
- <div className="space-y-2 text-xs">
- <div className="flex justify-between items-center">
- <span className="text-muted-foreground">Total Traffic</span>
- <span className="font-semibold text-foreground">{formatBytes(item.total)}</span>
- </div>
- <div className="flex justify-between items-center">
- <span className="text-blue-500">Download</span>
- <span className="text-foreground">{formatBytes(item.download)}</span>
- </div>
- <div className="flex justify-between items-center">
- <span className="text-purple-500">Upload</span>
- <span className="text-foreground">{formatBytes(item.upload)}</span>
- </div>
- <div className="flex justify-between items-center pt-1 border-t border-border/50">
- <span className="text-emerald-500">Connections</span>
- <span className="text-foreground">{formatNumber(item.connections)}</span>
- </div>
- </div>
- </div>
- );
- }
- return null;
- }}
- cursor={{ fill: "rgba(128, 128, 128, 0.1)" }}
- />
- <Bar
- dataKey="total"
- radius={[0, 4, 4, 0]}
- maxBarSize={24}
- >
- {domainChartData.map((entry, index) => (
- <BarCell key={`cell-${index}`} fill={entry.color} />
- ))}
- {showDomainBarLabels && (
- <LabelList
- dataKey="total"
- position="right"
- content={renderCustomBarLabel}
- />
- )}
- </Bar>
- </BarChart>
- </ResponsiveContainer>
- </div>
+ <BarChart data={domainChartData} layout="vertical" margin={{ left: 0, right: showDomainBarLabels ? 60 : 10, top: 5, bottom: 5 }}>
+ <XAxis type="number" hide />
+ <YAxis type="category" dataKey="name" width={100} tick={{ fontSize: 11 }} tickLine={false} axisLine={false} />
+ <RechartsTooltip content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const item = payload[0].payload;
+ return (<div className="bg-background border border-border p-3 rounded-lg shadow-lg min-w-[160px]"><div className="flex items-center gap-2 mb-2 pb-2 border-b border-border/50"><Favicon domain={item.fullName} size="sm" /><span className="font-medium text-sm truncate max-w-[180px]" title={item.fullName}>{item.fullName}</span></div><div className="space-y-2 text-xs"><div className="flex justify-between items-center"><span className="text-muted-foreground">Total</span><span className="font-semibold">{formatBytes(item.total)}</span></div><div className="flex justify-between items-center"><span className="text-blue-500">Download</span><span>{formatBytes(item.download)}</span></div><div className="flex justify-between items-center"><span className="text-purple-500">Upload</span><span>{formatBytes(item.upload)}</span></div><div className="flex justify-between items-center pt-1 border-t border-border/50"><span className="text-emerald-500">Connections</span><span>{formatNumber(item.connections)}</span></div></div></div>);
+ }
+ return null;
+ }} cursor={{ fill: "rgba(128, 128, 128, 0.1)" }} />
+ <Bar dataKey="total" radius={[0, 4, 4, 0]} maxBarSize={24}>
+ {domainChartData.map((entry, index) => (<BarCell key={`cell-${index}`} fill={entry.color} />))}
+ {showDomainBarLabels && (<LabelList dataKey="total" position="right" content={renderCustomBarLabel} />)}
+ </Bar>
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
)}
</CardContent>
</Card>
</div>
- {/* Bottom Section: Domain List & IP Addresses with pagination */}
+ {/* Bottom: Tabs with shared table components */}
{selectedProxy && (
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
- {/* Simplified Tabs - no icons, no counts, like Domains page */}
<TabsList className="glass">
- <TabsTrigger value="domains">
- {domainsT("domainList")}
- </TabsTrigger>
- <TabsTrigger value="ips">
- {ipsT("ipList")}
- </TabsTrigger>
+ <TabsTrigger value="domains">{domainsT("domainList")}</TabsTrigger>
+ <TabsTrigger value="ips">IP Addresses</TabsTrigger>
</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 ? (
- <div className="flex items-center justify-center py-12">
- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
- </div>
- ) : filteredDomains.length === 0 ? (
- <div className="text-center py-12 text-muted-foreground">
- {domainSearch ? domainsT("noResults") : "No domains found"}
- </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-4 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 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-2 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">
- {(() => {
- const totalDomainTraffic = filteredDomains.reduce(
- (sum, d) => sum + d.totalDownload + d.totalUpload, 0
- );
- return paginatedDomains.map((domain, index) => {
- const domainTraffic = domain.totalDownload + domain.totalUpload;
- const percent = totalDomainTraffic > 0 ? (domainTraffic / totalDomainTraffic) * 100 : 0;
- const isExpanded = expandedDomain === 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",
- isExpanded && "bg-secondary/10"
- )}
- style={{ animationDelay: `${index * 50}ms` }}
- onClick={() => toggleExpandDomain(domain.domain)}
- >
- {/* Domain with Favicon */}
- <div className="col-span-4 flex items-center gap-3 min-w-0">
- <Favicon domain={domain.domain} size="sm" className="shrink-0" />
- <span className="font-medium text-sm truncate" title={domain.domain}>
- {domain.domain}
- </span>
- </div>
-
- {/* Download */}
- <div className="col-span-2 text-right tabular-nums text-sm">
- <span className="text-blue-500">{formatBytes(domain.totalDownload)}</span>
- </div>
-
- {/* Upload */}
- <div className="col-span-2 text-right tabular-nums text-sm">
- <span className="text-purple-500">{formatBytes(domain.totalUpload)}</span>
- </div>
-
- {/* Connections */}
- <div className="col-span-2 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",
- isExpanded
- ? "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}
- {isExpanded ? (
- <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",
- isExpanded && "bg-secondary/10"
- )}
- onClick={() => toggleExpandDomain(domain.domain)}
- >
- {/* Top: Favicon + Domain + Expand */}
- <div className="flex items-center gap-2.5 mb-2">
- <Favicon domain={domain.domain} size="sm" className="shrink-0" />
- <span className="font-medium text-sm truncate flex-1" title={domain.domain}>
- {domain.domain}
- </span>
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isExpanded
- ? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground"
- )}
- onClick={(e) => {
- e.stopPropagation();
- toggleExpandDomain(domain.domain);
- }}
- >
- <Server className="h-3 w-3" />
- {domain.ips.length}
- {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
- </Button>
- </div>
-
- {/* Bottom: Stats row */}
- <div className="flex items-center justify-between text-xs pl-[30px]">
- <span className="text-blue-500 tabular-nums">↓ {formatBytes(domain.totalDownload)}</span>
- <span className="text-purple-500 tabular-nums">↑ {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: Associated IPs */}
- {isExpanded && (
- <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
- <div className="pt-3">
- {/* Associated IPs */}
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Globe className="h-3 w-3" />
- {domainsT("associatedIPs")}
- </p>
- <div className="flex flex-wrap gap-2">
- {domain.ips.map((ip) => {
- const gradient = getIPGradient(ip);
- return (
- <div
- key={ip}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md bg-gradient-to-br ${gradient} flex items-center justify-center shrink-0`}>
- <Server className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />
- </div>
- <code className="text-xs font-mono break-all">{ip}</code>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
- )}
- </div>
- );
- });
- })()}
- </div>
-
- {/* 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>{domainPageSize} / {domainsT("page")}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {PAGE_SIZE_OPTIONS.map((size) => (
- <DropdownMenuItem
- key={size}
- onClick={() => {
- setDomainPageSize(size);
- setDomainPage(1);
- }}
- className={domainPageSize === size ? "bg-primary/10" : ""}
- >
- {size} / {domainsT("page")}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <span className="text-sm text-muted-foreground">
- {domainsT("total")} {filteredDomains.length}
- </span>
- </div>
- <div className="flex items-center gap-2">
- <p className="text-xs text-muted-foreground">
- {(domainPage - 1) * domainPageSize + 1}-{Math.min(domainPage * domainPageSize, 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={proxyDomains} loading={loading} />
</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 ? (
- <div className="flex items-center justify-center py-12">
- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
- </div>
- ) : filteredIPs.length === 0 ? (
- <div className="text-center py-12 text-muted-foreground">
- {ipSearch ? ipsT("noResults") : "No IPs found"}
- </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("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-2 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">
- {(() => {
- const totalIPTraffic = filteredIPs.reduce(
- (sum, ip) => sum + ip.totalDownload + ip.totalUpload, 0
- );
- return paginatedIPs.map((ip, index) => {
- const ipTraffic = ip.totalDownload + ip.totalUpload;
- const percent = totalIPTraffic > 0 ? (ipTraffic / totalIPTraffic) * 100 : 0;
- const isExpanded = expandedIP === ip.ip;
- const ipColor = getIPColor(ip.ip);
-
- 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",
- isExpanded && "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>
-
- {/* Location */}
- <div className="col-span-2 flex items-center gap-1.5 min-w-0">
- {ip.geoIP && ip.geoIP.length > 0 ? (
- <>
- <span className="text-sm shrink-0" title={ip.geoIP[1] || ip.geoIP[0]}>
- {getCountryFlag(ip.geoIP[0])}
- </span>
- <span className="text-xs truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
- </>
- ) : (
- <span className="text-xs text-muted-foreground">-</span>
- )}
- </div>
-
- {/* Download */}
- <div className="col-span-2 text-right tabular-nums text-sm">
- <span className="text-blue-500">{formatBytes(ip.totalDownload)}</span>
- </div>
-
- {/* Upload */}
- <div className="col-span-1 text-right tabular-nums text-sm">
- <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-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",
- isExpanded
- ? "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}
- {isExpanded ? (
- <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",
- isExpanded && "bg-secondary/10"
- )}
- onClick={() => toggleExpandIP(ip.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>
- {ip.geoIP && ip.geoIP.length > 0 && (
- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
- <span className="text-sm">{getCountryFlag(ip.geoIP[0])}</span>
- <span className="truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
- </div>
- )}
- </div>
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-7 px-2 gap-1 text-xs font-medium shrink-0",
- isExpanded
- ? "bg-primary/10 text-primary"
- : "bg-secondary/50 text-muted-foreground"
- )}
- onClick={(e) => {
- e.stopPropagation();
- toggleExpandIP(ip.ip);
- }}
- >
- <Link2 className="h-3 w-3" />
- {ip.domains.length}
- {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
- </Button>
- </div>
-
- {/* Bottom: Stats row */}
- <div className="flex items-center justify-between text-xs pl-[30px]">
- <span className="text-blue-500 tabular-nums">↓ {formatBytes(ip.totalDownload)}</span>
- <span className="text-purple-500 tabular-nums">↑ {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: Associated Domains */}
- {isExpanded && (
- <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
- <div className="pt-3">
- {/* Associated Domains */}
- <div className="px-1">
- <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
- <Link2 className="h-3 w-3" />
- {ipsT("associatedDomains")}
- </p>
- <div className="flex flex-wrap gap-2">
- {ip.domains.map((domain) => {
- const domainColor = getDomainColor(domain);
- return (
- <div
- key={domain}
- className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
- >
- <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md ${domainColor.bg} ${domainColor.text} flex items-center justify-center shrink-0`}>
- <Globe className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
- </div>
- <span className="text-xs font-medium truncate max-w-[180px] sm:max-w-[200px]">{domain}</span>
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
- )}
- </div>
- );
- });
- })()}
- </div>
-
- {/* 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>{ipPageSize} / {ipsT("page")}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {PAGE_SIZE_OPTIONS.map((size) => (
- <DropdownMenuItem
- key={size}
- onClick={() => {
- setIpPageSize(size);
- setIpPage(1);
- }}
- className={ipPageSize === size ? "bg-primary/10" : ""}
- >
- {size} / {ipsT("page")}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <span className="text-sm text-muted-foreground">
- {ipsT("total")} {filteredIPs.length}
- </span>
- </div>
- <div className="flex items-center gap-2">
- <p className="text-xs text-muted-foreground">
- {(ipPage - 1) * ipPageSize + 1}-{Math.min(ipPage * ipPageSize, 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={proxyIPs} loading={loading} />
</TabsContent>
</Tabs>
)}
diff --git a/apps/web/components/navigation.tsx b/apps/web/components/navigation.tsx
index 032c74c..6fde914 100644
--- a/apps/web/components/navigation.tsx
+++ b/apps/web/components/navigation.tsx
@@ -13,6 +13,7 @@ import {
Info,
ExternalLink,
ArrowUpCircle,
+ Smartphone,
RefreshCw,
X,
} from "lucide-react";
@@ -43,6 +44,7 @@ const NAV_ITEMS = [
{ id: "rules", icon: Route },
{ id: "domains", icon: Globe },
{ id: "countries", icon: MapPin },
+ { id: "devices", icon: Smartphone },
{ id: "proxies", icon: Server },
];
diff --git a/apps/web/components/stats-tables/domain-stats-table.tsx b/apps/web/components/stats-tables/domain-stats-table.tsx
new file mode 100644
index 0000000..148fc4d
--- /dev/null
+++ b/apps/web/components/stats-tables/domain-stats-table.tsx
@@ -0,0 +1,426 @@
+"use client";
+
+import { useState, useMemo } from "react";
+import { ChevronLeft, ChevronRight, Loader2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, ChevronDown, ChevronUp, Server } from "lucide-react";
+import { useTranslations } from "next-intl";
+import { Card, CardContent } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { formatBytes, formatNumber } from "@/lib/utils";
+import { cn } from "@/lib/utils";
+import { Favicon } from "@/components/favicon";
+import {
+ PAGE_SIZE_OPTIONS,
+ getIPGradient,
+ getPageNumbers,
+ type PageSize,
+ type DomainSortKey,
+ type SortOrder,
+} from "@/lib/stats-utils";
+import type { DomainStats } from "@clashmaster/shared";
+
+interface DomainStatsTableProps {
+ domains: DomainStats[];
+ loading?: boolean;
+ title?: string;
+ showHeader?: boolean;
+}
+
+export function DomainStatsTable({
+ domains,
+ loading = false,
+ title,
+ showHeader = true,
+}: DomainStatsTableProps) {
+ const t = useTranslations("domains");
+
+ const [page, setPage] = useState(1);
+ const [pageSize, setPageSize] = useState<PageSize>(10);
+ const [search, setSearch] = useState("");
+ const [sortKey, setSortKey] = useState<DomainSortKey>("totalDownload");
+ const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
+ const [expandedDomain, setExpandedDomain] = useState<string | null>(null);
+
+ // Sort handler
+ const handleSort = (key: DomainSortKey) => {
+ if (sortKey === key) {
+ setSortOrder(sortOrder === "asc" ? "desc" : "asc");
+ } else {
+ setSortKey(key);
+ setSortOrder("desc");
+ }
+ setPage(1);
+ };
+
+ // Toggle expand
+ const toggleExpand = (domain: string) => {
+ setExpandedDomain(expandedDomain === domain ? null : domain);
+ };
+
+ // Sort icon component
+ const SortIcon = ({ column }: { column: DomainSortKey }) => {
+ 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" />
+ );
+ };
+
+ // Filter and sort
+ const filteredDomains = useMemo(() => {
+ let result = [...domains];
+ if (search) {
+ const lower = search.toLowerCase();
+ result = result.filter(d => d.domain.toLowerCase().includes(lower));
+ }
+ result.sort((a, b) => {
+ const aVal = a[sortKey] ?? "";
+ const bVal = b[sortKey] ?? "";
+ if (sortOrder === "asc") {
+ return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
+ }
+ return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
+ });
+ return result;
+ }, [domains, search, sortKey, sortOrder]);
+
+ // Paginate
+ const paginatedDomains = useMemo(() => {
+ const start = (page - 1) * pageSize;
+ return filteredDomains.slice(start, start + pageSize);
+ }, [filteredDomains, page, pageSize]);
+
+ const totalPages = Math.ceil(filteredDomains.length / pageSize);
+
+ return (
+ <Card>
+ {/* Header with search */}
+ {showHeader && (
+ <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>
+ <p className="text-sm text-muted-foreground">
+ {filteredDomains.length} {t("domainsCount")}
+ </p>
+ </div>
+ <div className="relative">
+ <Input
+ placeholder={t("search")}
+ value={search}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setPage(1);
+ }}
+ className="h-9 w-full sm:w-[240px] bg-secondary/50 border-0"
+ />
+ </div>
+ </div>
+ </div>
+ )}
+
+ <CardContent className="p-0">
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+ ) : filteredDomains.length === 0 ? (
+ <div className="text-center py-12 text-muted-foreground">
+ {search ? t("noResults") : t("noData")}
+ </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-4 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 justify-end cursor-pointer hover:text-foreground transition-colors"
+ onClick={() => handleSort("totalDownload")}
+ >
+ {t("download")}
+ <SortIcon column="totalDownload" />
+ </div>
+ <div
+ className="col-span-2 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-2 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-2 flex items-center justify-end">
+ {t("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: t("domain") },
+ { key: "totalDownload" as DomainSortKey, label: t("download") },
+ { key: "totalUpload" as DomainSortKey, label: t("upload") },
+ { key: "totalConnections" as DomainSortKey, 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>
+
+ {/* Domain List */}
+ <div className="divide-y divide-border/30">
+ {paginatedDomains.map((domain, index) => {
+ const isExpanded = expandedDomain === 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",
+ isExpanded && "bg-secondary/10"
+ )}
+ style={{ animationDelay: `${index * 50}ms` }}
+ onClick={() => toggleExpand(domain.domain)}
+ >
+ {/* Domain with Favicon */}
+ <div className="col-span-4 flex items-center gap-3 min-w-0">
+ <Favicon domain={domain.domain} size="sm" className="shrink-0" />
+ <span className="font-medium text-sm truncate" title={domain.domain}>
+ {domain.domain}
+ </span>
+ </div>
+
+ {/* Download */}
+ <div className="col-span-2 text-right tabular-nums text-sm">
+ <span className="text-blue-500">{formatBytes(domain.totalDownload)}</span>
+ </div>
+
+ {/* Upload */}
+ <div className="col-span-2 text-right tabular-nums text-sm">
+ <span className="text-purple-500">{formatBytes(domain.totalUpload)}</span>
+ </div>
+
+ {/* Connections */}
+ <div className="col-span-2 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",
+ isExpanded
+ ? "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 || 0}
+ {isExpanded ? (
+ <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",
+ isExpanded && "bg-secondary/10"
+ )}
+ onClick={() => toggleExpand(domain.domain)}
+ >
+ {/* Top: Favicon + Domain + Expand */}
+ <div className="flex items-center gap-2.5 mb-2">
+ <Favicon domain={domain.domain} size="sm" className="shrink-0" />
+ <span className="font-medium text-sm truncate flex-1" title={domain.domain}>
+ {domain.domain}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-7 px-2 gap-1 text-xs font-medium shrink-0",
+ isExpanded
+ ? "bg-primary/10 text-primary"
+ : "bg-secondary/50 text-muted-foreground"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpand(domain.domain);
+ }}
+ >
+ <Server className="h-3 w-3" />
+ {domain.ips?.length || 0}
+ {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
+ </Button>
+ </div>
+
+ {/* Bottom: Stats row */}
+ <div className="flex items-center justify-between text-xs pl-[30px]">
+ <span className="text-blue-500 tabular-nums">↓ {formatBytes(domain.totalDownload)}</span>
+ <span className="text-purple-500 tabular-nums">↑ {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>
+ </div>
+ </div>
+
+ {/* Expanded Details: Associated IPs */}
+ {isExpanded && domain.ips && domain.ips.length > 0 && (
+ <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
+ <div className="pt-3">
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {t("associatedIPs")}
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {domain.ips.map((ip) => {
+ const gradient = getIPGradient(ip);
+ return (
+ <div
+ key={ip}
+ className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
+ >
+ <div className={`w-5 h-5 sm:w-6 sm:h-6 rounded-md bg-gradient-to-br ${gradient} flex items-center justify-center shrink-0`}>
+ <Server className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />
+ </div>
+ <code className="text-xs font-mono break-all">{ip}</code>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ {/* 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>{pageSize} / {t("page")}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {PAGE_SIZE_OPTIONS.map((size) => (
+ <DropdownMenuItem
+ key={size}
+ onClick={() => {
+ setPageSize(size);
+ setPage(1);
+ }}
+ className={pageSize === size ? "bg-primary/10" : ""}
+ >
+ {size} / {t("page")}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <span className="text-sm text-muted-foreground">
+ {t("total")} {filteredDomains.length}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <p className="text-xs text-muted-foreground">
+ {(page - 1) * pageSize + 1}-{Math.min(page * pageSize, filteredDomains.length)} / {filteredDomains.length}
+ </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}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ {getPageNumbers(page, totalPages).map((p, idx) => (
+ p === '...' ? (
+ <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">...</span>
+ ) : (
+ <Button
+ key={p}
+ variant={page === p ? "default" : "ghost"}
+ size="sm"
+ className="h-8 w-8 px-0 text-xs"
+ onClick={() => setPage(p as number)}
+ >
+ {p}
+ </Button>
+ )
+ ))}
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => setPage(p => Math.min(totalPages, p + 1))}
+ disabled={page === totalPages}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/apps/web/components/stats-tables/index.ts b/apps/web/components/stats-tables/index.ts
new file mode 100644
index 0000000..793d7aa
--- /dev/null
+++ b/apps/web/components/stats-tables/index.ts
@@ -0,0 +1,2 @@
+export { DomainStatsTable } from "./domain-stats-table";
+export { IPStatsTable } from "./ip-stats-table";
diff --git a/apps/web/components/stats-tables/ip-stats-table.tsx b/apps/web/components/stats-tables/ip-stats-table.tsx
new file mode 100644
index 0000000..636e903
--- /dev/null
+++ b/apps/web/components/stats-tables/ip-stats-table.tsx
@@ -0,0 +1,443 @@
+"use client";
+
+import { useState, useMemo } from "react";
+import { ChevronLeft, ChevronRight, Loader2, Rows3, ArrowUpDown, ArrowDown, ArrowUp, Globe, ChevronDown, ChevronUp, Server } from "lucide-react";
+import { useTranslations } from "next-intl";
+import { Card, CardContent } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { formatBytes, formatNumber } from "@/lib/utils";
+import { cn } from "@/lib/utils";
+import { Favicon } from "@/components/favicon";
+import {
+ PAGE_SIZE_OPTIONS,
+ getIPGradient,
+ getCountryFlag,
+ getPageNumbers,
+ type PageSize,
+ type IPSortKey,
+ type SortOrder,
+} from "@/lib/stats-utils";
+import type { IPStats } from "@clashmaster/shared";
+
+interface IPStatsTableProps {
+ ips: IPStats[];
+ loading?: boolean;
+ title?: string;
+ showHeader?: boolean;
+}
+
+export function IPStatsTable({
+ ips,
+ loading = false,
+ title,
+ showHeader = true,
+}: IPStatsTableProps) {
+ const t = useTranslations("ips");
+
+ const [page, setPage] = useState(1);
+ const [pageSize, setPageSize] = useState<PageSize>(10);
+ const [search, setSearch] = useState("");
+ const [sortKey, setSortKey] = useState<IPSortKey>("totalDownload");
+ const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
+ const [expandedIP, setExpandedIP] = useState<string | null>(null);
+
+ // Sort handler
+ const handleSort = (key: IPSortKey) => {
+ if (sortKey === key) {
+ setSortOrder(sortOrder === "asc" ? "desc" : "asc");
+ } else {
+ setSortKey(key);
+ setSortOrder("desc");
+ }
+ setPage(1);
+ };
+
+ // Toggle expand
+ const toggleExpand = (ip: string) => {
+ setExpandedIP(expandedIP === ip ? null : ip);
+ };
+
+ // Sort icon component
+ const SortIcon = ({ column }: { column: IPSortKey }) => {
+ 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" />
+ );
+ };
+
+ // Filter and sort
+ const filteredIPs = useMemo(() => {
+ let result = [...ips];
+ if (search) {
+ const lower = search.toLowerCase();
+ result = result.filter(ip => ip.ip.toLowerCase().includes(lower));
+ }
+ result.sort((a, b) => {
+ const aVal = a[sortKey] ?? "";
+ const bVal = b[sortKey] ?? "";
+ if (sortOrder === "asc") {
+ return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
+ }
+ return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
+ });
+ return result;
+ }, [ips, search, sortKey, sortOrder]);
+
+ // Paginate
+ const paginatedIPs = useMemo(() => {
+ const start = (page - 1) * pageSize;
+ return filteredIPs.slice(start, start + pageSize);
+ }, [filteredIPs, page, pageSize]);
+
+ const totalPages = Math.ceil(filteredIPs.length / pageSize);
+
+ return (
+ <Card>
+ {/* Header with search */}
+ {showHeader && (
+ <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("associatedIPs")}</h3>
+ <p className="text-sm text-muted-foreground">
+ {filteredIPs.length} {t("ipsCount")}
+ </p>
+ </div>
+ <div className="relative">
+ <Input
+ placeholder={t("search")}
+ value={search}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setPage(1);
+ }}
+ className="h-9 w-full sm:w-[240px] bg-secondary/50 border-0"
+ />
+ </div>
+ </div>
+ </div>
+ )}
+
+ <CardContent className="p-0">
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+ ) : filteredIPs.length === 0 ? (
+ <div className="text-center py-12 text-muted-foreground">
+ {search ? t("noResults") : t("noData")}
+ </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("ip")}
+ <SortIcon column="ip" />
+ </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-2 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-2 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 IPSortKey, label: t("ip") },
+ { key: "totalDownload" as IPSortKey, label: t("download") },
+ { key: "totalUpload" as IPSortKey, label: t("upload") },
+ { key: "totalConnections" as IPSortKey, 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>
+
+ {/* IP List */}
+ <div className="divide-y divide-border/30">
+ {paginatedIPs.map((ip) => {
+ const isExpanded = expandedIP === ip.ip;
+
+ 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",
+ isExpanded && "bg-secondary/10"
+ )}
+ onClick={() => toggleExpand(ip.ip)}
+ >
+ {/* IP Address */}
+ <div className="col-span-3 flex items-center gap-3 min-w-0">
+ <div className={`w-5 h-5 rounded-md bg-gradient-to-br ${getIPGradient(ip.ip)} flex items-center justify-center shrink-0`}>
+ <Server className="w-3 h-3 text-white" />
+ </div>
+ <code className="font-mono text-sm truncate">{ip.ip}</code>
+ </div>
+
+ {/* Location */}
+ <div className="col-span-2 flex items-center gap-1.5 min-w-0">
+ {ip.geoIP && ip.geoIP.length > 0 ? (
+ <>
+ <span className="text-sm shrink-0" title={ip.geoIP[1] || ip.geoIP[0]}>
+ {getCountryFlag(ip.geoIP[0])}
+ </span>
+ <span className="text-xs truncate">{ip.geoIP[1] || ip.geoIP[0]}</span>
+ </>
+ ) : (
+ <span className="text-xs text-muted-foreground">-</span>
+ )}
+ </div>
+
+ {/* Download */}
+ <div className="col-span-2 text-right tabular-nums text-sm">
+ <span className="text-blue-500">{formatBytes(ip.totalDownload)}</span>
+ </div>
+
+ {/* Upload */}
+ <div className="col-span-2 text-right tabular-nums text-sm">
+ <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>
+
+ {/* Domain 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",
+ isExpanded
+ ? "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);
+ }}
+ >
+ <Globe className="h-3 w-3" />
+ {ip.domains?.length || 0}
+ {isExpanded ? (
+ <ChevronUp className="h-3 w-3 ml-0.5" />
+ ) : (
+ <ChevronDown className="h-3 w-3 ml-0.5" />
+ )}
+ </Button>
+ </div>
+ </div>
+
+ {/* Mobile Row */}
+ <div
+ className={cn(
+ "sm:hidden px-4 py-3 hover:bg-secondary/20 transition-colors cursor-pointer",
+ isExpanded && "bg-secondary/10"
+ )}
+ onClick={() => toggleExpand(ip.ip)}
+ >
+ {/* Top: IP Address + Location + Expand */}
+ <div className="flex items-center gap-2.5 mb-2">
+ <div className={`w-5 h-5 rounded-md bg-gradient-to-br ${getIPGradient(ip.ip)} flex items-center justify-center shrink-0`}>
+ <Server className="w-2.5 h-2.5 text-white" />
+ </div>
+ <code className="font-mono text-sm flex-1 truncate">{ip.ip}</code>
+ {ip.geoIP && ip.geoIP.length > 0 && (
+ <span className="text-sm shrink-0" title={ip.geoIP[1] || ip.geoIP[0]}>
+ {getCountryFlag(ip.geoIP[0])}
+ </span>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-7 px-2 gap-1 text-xs font-medium shrink-0",
+ isExpanded
+ ? "bg-primary/10 text-primary"
+ : "bg-secondary/50 text-muted-foreground"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpand(ip.ip);
+ }}
+ >
+ <Globe className="h-3 w-3" />
+ {ip.domains?.length || 0}
+ {isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
+ </Button>
+ </div>
+
+ {/* Bottom: Stats row */}
+ <div className="flex items-center justify-between text-xs pl-[30px]">
+ <span className="text-blue-500 tabular-nums">↓ {formatBytes(ip.totalDownload)}</span>
+ <span className="text-purple-500 tabular-nums">↑ {formatBytes(ip.totalUpload)}</span>
+ <span className="px-2 py-0.5 rounded-full bg-secondary text-muted-foreground font-medium">
+ {formatNumber(ip.totalConnections)} {t("conn")}
+ </span>
+ </div>
+ </div>
+
+ {/* Expanded Details: Associated Domains */}
+ {isExpanded && ip.domains && ip.domains.length > 0 && (
+ <div className="px-4 sm:px-5 pb-4 bg-secondary/5">
+ <div className="pt-3">
+ <div className="px-1">
+ <p className="text-xs font-medium text-muted-foreground mb-2.5 flex items-center gap-1.5">
+ <Globe className="h-3 w-3" />
+ {t("associatedDomains")}
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {ip.domains.map((domain) => (
+ <div
+ key={domain}
+ className="flex items-center gap-2 px-2.5 py-1.5 sm:px-3 sm:py-2 rounded-lg bg-card border border-border/50 hover:border-primary/30 hover:shadow-sm transition-all"
+ >
+ <Favicon domain={domain} size="sm" />
+ <span className="text-xs truncate max-w-[200px]">{domain}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ {/* 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>{pageSize} / {t("page")}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {PAGE_SIZE_OPTIONS.map((size) => (
+ <DropdownMenuItem
+ key={size}
+ onClick={() => {
+ setPageSize(size);
+ setPage(1);
+ }}
+ className={pageSize === size ? "bg-primary/10" : ""}
+ >
+ {size} / {t("page")}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <span className="text-sm text-muted-foreground">
+ {t("total")} {filteredIPs.length}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <p className="text-xs text-muted-foreground">
+ {(page - 1) * pageSize + 1}-{Math.min(page * pageSize, filteredIPs.length)} / {filteredIPs.length}
+ </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}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ {getPageNumbers(page, totalPages).map((p, idx) => (
+ p === '...' ? (
+ <span key={`ellipsis-${idx}`} className="px-1 text-muted-foreground text-xs">...</span>
+ ) : (
+ <Button
+ key={p}
+ variant={page === p ? "default" : "ghost"}
+ size="sm"
+ className="h-8 w-8 px-0 text-xs"
+ onClick={() => setPage(p as number)}
+ >
+ {p}
+ </Button>
+ )
+ ))}
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8"
+ onClick={() => setPage(p => Math.min(totalPages, p + 1))}
+ disabled={page === totalPages}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts
index d2fc50d..96d186a 100644
--- a/apps/web/lib/api.ts
+++ b/apps/web/lib/api.ts
@@ -9,6 +9,7 @@ import type {
DailyStats,
TrafficTrendPoint,
ProxyTrafficStats,
+ DeviceStats,
} from "@clashmaster/shared";
type RuntimeConfig = {
@@ -245,6 +246,22 @@ export const api = {
buildUrl(`${API_BASE}/stats/proxies/ips`, { chain, backendId })
),
+ // Device stats APIs
+ getDevices: (backendId?: number, limit = 50, range?: TimeRange) =>
+ fetchJson<DeviceStats[]>(
+ buildUrl(`${API_BASE}/stats/devices`, { backendId, limit, start: range?.start, end: range?.end })
+ ),
+
+ getDeviceDomains: (sourceIP: string, backendId?: number) =>
+ fetchJson<DomainStats[]>(
+ buildUrl(`${API_BASE}/stats/devices/domains`, { sourceIP, backendId })
+ ),
+
+ getDeviceIPs: (sourceIP: string, backendId?: number) =>
+ fetchJson<IPStats[]>(
+ buildUrl(`${API_BASE}/stats/devices/ips`, { sourceIP, backendId })
+ ),
+
getRuleDomains: (rule: string, backendId?: number) =>
fetchJson<DomainStats[]>(
buildUrl(`${API_BASE}/stats/rules/domains`, { rule, backendId })
diff --git a/apps/web/lib/stats-utils.ts b/apps/web/lib/stats-utils.ts
new file mode 100644
index 0000000..8af2e43
--- /dev/null
+++ b/apps/web/lib/stats-utils.ts
@@ -0,0 +1,117 @@
+/**
+ * Shared utility functions for stats tables (used by Proxies, Devices, Rules)
+ */
+
+// Chart color palette
+export const COLORS = [
+ "#3B82F6", "#8B5CF6", "#06B6D4", "#10B981", "#F59E0B",
+ "#EF4444", "#EC4899", "#6366F1", "#14B8A6", "#F97316",
+];
+
+// Pagination options
+export const PAGE_SIZE_OPTIONS = [10, 20, 50] as const;
+export type PageSize = typeof PAGE_SIZE_OPTIONS[number];
+
+// Sort order type
+export type SortOrder = "asc" | "desc";
+
+// Domain sort keys
+export type DomainSortKey = "domain" | "totalDownload" | "totalUpload" | "totalConnections";
+
+// IP sort keys
+export type IPSortKey = "ip" | "totalDownload" | "totalUpload" | "totalConnections";
+
+// Color palette for icons
+export 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" },
+];
+
+// Country flag emoji mapping (comprehensive)
+const COUNTRY_FLAGS: Record<string, string> = {
+ CN: "🇨🇳", US: "🇺🇸", JP: "🇯🇵", KR: "🇰🇷", SG: "🇸🇬", HK: "🇭🇰", TW: "🇹🇼", DE: "🇩🇪",
+ UK: "🇬🇧", GB: "🇬🇧", FR: "🇫🇷", AU: "🇦🇺", CA: "🇨🇦", RU: "🇷🇺", IN: "🇮🇳", BR: "🇧🇷",
+ NL: "🇳🇱", IT: "🇮🇹", ES: "🇪🇸", SE: "🇸🇪", NO: "🇳🇴", FI: "🇫🇮", DK: "🇩🇰", CH: "🇨🇭",
+ AT: "🇦🇹", BE: "🇧🇪", PL: "🇵🇱", CZ: "🇨🇿", PT: "🇵🇹", GR: "🇬🇷", IE: "🇮🇪", RO: "🇷🇴",
+ HU: "🇭🇺", NZ: "🇳🇿", ZA: "🇿🇦", MX: "🇲🇽", AR: "🇦🇷", CL: "🇨🇱", CO: "🇨🇴", PE: "🇵🇪",
+ VE: "🇻🇪", ID: "🇮🇩", MY: "🇲🇾", TH: "🇹🇭", VN: "🇻🇳", PH: "🇵🇭", PK: "🇵🇰", BD: "🇧🇩",
+ EG: "🇪🇬", NG: "🇳🇬", KE: "🇰🇪", AE: "🇦🇪", SA: "🇸🇦", IL: "🇮🇱", TR: "🇹🇷", UA: "🇺🇦",
+ // Chinese names
+ "中国": "🇨🇳", "美国": "🇺🇸", "日本": "🇯🇵", "韩国": "🇰🇷", "新加坡": "🇸🇬",
+ "香港": "🇭🇰", "台湾": "🇹🇼", "德国": "🇩🇪", "英国": "🇬🇧", "法国": "🇫🇷",
+ "澳大利亚": "🇦🇺", "加拿大": "🇨🇦", "俄罗斯": "🇷🇺", "印度": "🇮🇳", "荷兰": "🇳🇱",
+ LOCAL: "🏠",
+};
+
+/**
+ * Get country flag emoji from country code or name
+ */
+export function getCountryFlag(country: string): string {
+ return COUNTRY_FLAGS[country] || COUNTRY_FLAGS[country.toUpperCase()] || "🌐";
+}
+
+/**
+ * Generate gradient class for IP address display
+ */
+export function getIPGradient(ip: string): string {
+ const gradients = [
+ "from-blue-500 to-cyan-400",
+ "from-violet-500 to-purple-400",
+ "from-emerald-500 to-teal-400",
+ "from-amber-500 to-orange-400",
+ "from-rose-500 to-pink-400",
+ "from-indigo-500 to-blue-400",
+ ];
+ let hash = 0;
+ for (let i = 0; i < ip.length; i++) {
+ hash = ip.charCodeAt(i) + ((hash << 5) - hash);
+ }
+ return gradients[Math.abs(hash) % gradients.length];
+}
+
+/**
+ * Get color for domain icon
+ */
+export function getDomainColor(domain: string) {
+ let hash = 0;
+ for (let i = 0; i < domain.length; i++) {
+ hash = domain.charCodeAt(i) + ((hash << 5) - hash);
+ }
+ return ICON_COLORS[Math.abs(hash) % ICON_COLORS.length];
+}
+
+/**
+ * Get color for IP icon
+ */
+export function 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];
+}
+
+/**
+ * Generate pagination page numbers with ellipsis
+ */
+export function getPageNumbers(currentPage: number, totalPages: number): (number | "...")[] {
+ const pages: (number | "...")[] = [];
+ if (totalPages <= 5) {
+ for (let i = 1; i <= totalPages; i++) pages.push(i);
+ } else {
+ if (currentPage <= 3) {
+ pages.push(1, 2, 3, 4, "...", totalPages);
+ } else if (currentPage >= totalPages - 2) {
+ pages.push(1, "...", totalPages - 3, totalPages - 2, totalPages - 1, totalPages);
+ } else {
+ pages.push(1, "...", currentPage - 1, currentPage, currentPage + 1, "...", totalPages);
+ }
+ }
+ return pages;
+}
diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json
index 3b58e5e..85b0712 100644
--- a/apps/web/messages/en.json
+++ b/apps/web/messages/en.json
@@ -7,6 +7,7 @@
"overview": "Overview",
"domains": "Domains",
"countries": "Regions",
+ "devices": "Devices",
"proxies": "Proxies",
"rules": "Rules",
"network": "Network",
@@ -98,6 +99,7 @@
"associatedIPs": "Associated IP Addresses",
"search": "Search domains...",
"noResults": "No domains found",
+ "noData": "No domain data available",
"connections": "connections",
"lastSeen": "Last seen",
"topDomainsByTraffic": "Top Domains by Traffic",
@@ -166,6 +168,15 @@
"noData": "No data",
"viewAll": "Back to all proxies"
},
+ "devices": {
+ "title": "Devices",
+ "distribution": "Device Traffic Distribution",
+ "noData": "No device data available",
+ "connections": "connections",
+ "total": "Total",
+ "download": "Download",
+ "upload": "Upload"
+ },
"rules": {
"title": "Rules",
"distribution": "Rule Traffic Distribution",
diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.json
index b0307ec..e4b6b1f 100644
--- a/apps/web/messages/zh.json
+++ b/apps/web/messages/zh.json
@@ -7,6 +7,7 @@
"overview": "概览",
"domains": "域名",
"countries": "地区",
+ "devices": "设备",
"proxies": "代理",
"rules": "规则",
"network": "网络",
@@ -97,6 +98,7 @@
"associatedIPs": "关联 IP 地址",
"search": "搜索域名...",
"noResults": "未找到域名",
+ "noData": "暂无域名数据",
"connections": "连接",
"lastSeen": "最后访问",
"topDomainsByTraffic": "按流量排序的热门域名",
@@ -165,6 +167,15 @@
"noData": "暂无数据",
"viewAll": "返回全部节点"
},
+ "devices": {
+ "title": "设备",
+ "distribution": "设备流量分布",
+ "noData": "暂无设备数据",
+ "connections": "连接",
+ "total": "总计",
+ "download": "下载",
+ "upload": "上传"
+ },
"rules": {
"title": "规则",
"distribution": "规则流量分布",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 2e1f5ce..68b7f53 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -97,6 +97,14 @@ export interface ProxyStats {
lastSeen: string;
}
+export interface DeviceStats {
+ sourceIP: string;
+ totalUpload: number;
+ totalDownload: number;
+ totalConnections: number;
+ lastSeen: string;
+}
+
export interface RuleStats {
rule: string;
finalProxy: string;