Initial Upload
Some checks failed
CI / Lint & Typecheck (push) Has been cancelled
CI / Test (routes) (push) Has been cancelled
CI / Test (security) (push) Has been cancelled
CI / Test (services) (push) Has been cancelled
CI / Test (unit) (push) Has been cancelled
CI / Test (integration) (push) Has been cancelled
CI / Test Coverage (push) Has been cancelled
CI / Build (push) Has been cancelled
22
apps/web/components.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/styles/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"registries": {}
|
||||
}
|
||||
38
apps/web/index.html
Normal file
@@ -0,0 +1,38 @@
|
||||
<!doctype html>
|
||||
<html lang="en" class="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
|
||||
<!-- Branding -->
|
||||
<title>Tracearr</title>
|
||||
<meta name="description" content="Streaming access manager for Plex and Jellyfin. Detect account sharing with impossible travel, simultaneous locations, and device velocity rules." />
|
||||
|
||||
<!-- Favicon & Icons -->
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
|
||||
<!-- PWA -->
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<meta name="theme-color" content="#0B1A2E" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="Tracearr" />
|
||||
|
||||
<!-- Font: Inter -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap" rel="stylesheet" />
|
||||
|
||||
<!-- Open Graph -->
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:title" content="Tracearr - Streaming Access Manager" />
|
||||
<meta property="og:description" content="Detect account sharing across Plex and Jellyfin servers." />
|
||||
<meta property="og:image" content="/images/square-with-name.png" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
73
apps/web/package.json
Normal file
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"name": "@tracearr/web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "eslint src/",
|
||||
"lint:fix": "eslint src/ --fix",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"clean": "rm -rf dist .turbo"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.0.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-collapsible": "^1.1.12",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.15",
|
||||
"@radix-ui/react-label": "^2.1.7",
|
||||
"@radix-ui/react-popover": "^1.1.15",
|
||||
"@radix-ui/react-progress": "^1.1.7",
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-select": "^2.1.15",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.12",
|
||||
"@radix-ui/react-toast": "^1.2.14",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@tanstack/react-query": "^5.60.0",
|
||||
"@tanstack/react-table": "^8.21.0",
|
||||
"@tracearr/shared": "workspace:*",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"highcharts": "^12.0.0",
|
||||
"highcharts-react-official": "^3.2.1",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.500.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react": "^19.0.0",
|
||||
"react-day-picker": "^9.12.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-hook-form": "^7.55.0",
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-leaflet-heatmap-layer-v3": "3.0.3-beta-1",
|
||||
"react-router": "^7.0.0",
|
||||
"socket.io-client": "^4.8.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"zod": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.0.0",
|
||||
"@types/leaflet": "^1.9.16",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.4.0",
|
||||
"postcss": "^8.5.0",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^5.7.0",
|
||||
"vite": "^7.0.0",
|
||||
"vitest": "^4.0.0"
|
||||
}
|
||||
}
|
||||
5
apps/web/postcss.config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
export default {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
};
|
||||
BIN
apps/web/public/apple-touch-icon-transparent.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
apps/web/public/apple-touch-icon.png
Normal file
|
After Width: | Height: | Size: 32 KiB |
BIN
apps/web/public/favicon-96x96.png
Normal file
|
After Width: | Height: | Size: 9.4 KiB |
BIN
apps/web/public/favicon.ico
Normal file
|
After Width: | Height: | Size: 954 B |
23
apps/web/public/favicon.svg
Normal file
@@ -0,0 +1,23 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
|
||||
<!-- Background shield shape -->
|
||||
<path d="M32 4L8 14v18c0 14 10 24 24 28 14-4 24-14 24-28V14L32 4z" fill="#0B1A2E"/>
|
||||
<!-- Inner shield -->
|
||||
<path d="M32 8L12 16v14c0 12 8.5 20.5 20 24 11.5-3.5 20-12 20-24V16L32 8z" fill="#162840"/>
|
||||
<!-- T-path stylized -->
|
||||
<path d="M22 24h20v4H34v16h-4V28H22v-4z" fill="#18D1E7"/>
|
||||
<!-- Radar arcs -->
|
||||
<path d="M32 20a16 16 0 0 1 11.3 4.7" stroke="#18D1E7" stroke-width="2" stroke-linecap="round" fill="none" opacity="0.6"/>
|
||||
<path d="M32 16a20 20 0 0 1 14.1 5.9" stroke="#18D1E7" stroke-width="2" stroke-linecap="round" fill="none" opacity="0.4"/>
|
||||
<path d="M32 12a24 24 0 0 1 17 7" stroke="#18D1E7" stroke-width="2" stroke-linecap="round" fill="none" opacity="0.2"/>
|
||||
<!-- Glow effect -->
|
||||
<defs>
|
||||
<filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
|
||||
<feGaussianBlur stdDeviation="1" result="blur"/>
|
||||
<feMerge>
|
||||
<feMergeNode in="blur"/>
|
||||
<feMergeNode in="SourceGraphic"/>
|
||||
</feMerge>
|
||||
</filter>
|
||||
</defs>
|
||||
<path d="M22 24h20v4H34v16h-4V28H22v-4z" fill="#18D1E7" filter="url(#glow)"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
BIN
apps/web/public/images/banner.png
Normal file
|
After Width: | Height: | Size: 1.7 MiB |
BIN
apps/web/public/images/servers/emby.png
Normal file
|
After Width: | Height: | Size: 85 KiB |
BIN
apps/web/public/images/servers/jellyfin.png
Normal file
|
After Width: | Height: | Size: 68 KiB |
BIN
apps/web/public/images/servers/plex.png
Normal file
|
After Width: | Height: | Size: 74 KiB |
BIN
apps/web/public/images/square-with-name.png
Normal file
|
After Width: | Height: | Size: 1017 KiB |
BIN
apps/web/public/images/square.png
Normal file
|
After Width: | Height: | Size: 965 KiB |
BIN
apps/web/public/logo-transparent.png
Normal file
|
After Width: | Height: | Size: 510 KiB |
24
apps/web/public/site.webmanifest
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "Tracearr",
|
||||
"short_name": "Tracearr",
|
||||
"description": "Streaming access manager for Plex and Jellyfin",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/web-app-manifest-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
},
|
||||
{
|
||||
"src": "/web-app-manifest-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
],
|
||||
"theme_color": "#0B1A2E",
|
||||
"background_color": "#050A12",
|
||||
"display": "standalone",
|
||||
"start_url": "/",
|
||||
"scope": "/"
|
||||
}
|
||||
BIN
apps/web/public/web-app-manifest-192x192-transparent.png
Normal file
|
After Width: | Height: | Size: 28 KiB |
BIN
apps/web/public/web-app-manifest-192x192.png
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
apps/web/public/web-app-manifest-512x512-transparent.png
Normal file
|
After Width: | Height: | Size: 170 KiB |
BIN
apps/web/public/web-app-manifest-512x512.png
Normal file
|
After Width: | Height: | Size: 329 KiB |
66
apps/web/src/App.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import { Routes, Route, Navigate } from 'react-router';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { Layout } from '@/components/layout/Layout';
|
||||
import { ProtectedRoute } from '@/components/auth/ProtectedRoute';
|
||||
import { Login } from '@/pages/Login';
|
||||
import { PlexCallback } from '@/pages/PlexCallback';
|
||||
import { Setup } from '@/pages/Setup';
|
||||
import { Dashboard } from '@/pages/Dashboard';
|
||||
import { Map } from '@/pages/Map';
|
||||
import { StatsActivity, StatsLibrary, StatsUsers } from '@/pages/stats';
|
||||
import { Users } from '@/pages/Users';
|
||||
import { UserDetail } from '@/pages/UserDetail';
|
||||
import { Rules } from '@/pages/Rules';
|
||||
import { Violations } from '@/pages/Violations';
|
||||
import { Settings } from '@/pages/Settings';
|
||||
import { Debug } from '@/pages/Debug';
|
||||
import { NotFound } from '@/pages/NotFound';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<>
|
||||
<Routes>
|
||||
{/* Public routes */}
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/auth/plex-callback" element={<PlexCallback />} />
|
||||
<Route path="/setup" element={<Setup />} />
|
||||
|
||||
{/* Protected routes */}
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<Layout />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="map" element={<Map />} />
|
||||
|
||||
{/* Stats routes */}
|
||||
<Route path="stats" element={<Navigate to="/stats/activity" replace />} />
|
||||
<Route path="stats/activity" element={<StatsActivity />} />
|
||||
<Route path="stats/library" element={<StatsLibrary />} />
|
||||
<Route path="stats/users" element={<StatsUsers />} />
|
||||
|
||||
{/* Other routes */}
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="users/:id" element={<UserDetail />} />
|
||||
<Route path="rules" element={<Rules />} />
|
||||
<Route path="violations" element={<Violations />} />
|
||||
<Route path="settings/*" element={<Settings />} />
|
||||
|
||||
{/* Hidden debug page (owner only) */}
|
||||
<Route path="debug" element={<Debug />} />
|
||||
|
||||
{/* Legacy redirects */}
|
||||
<Route path="analytics" element={<Navigate to="/stats/activity" replace />} />
|
||||
<Route path="activity" element={<Navigate to="/stats/activity" replace />} />
|
||||
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
<Toaster />
|
||||
</>
|
||||
);
|
||||
}
|
||||
354
apps/web/src/components/auth/PlexServerSelector.tsx
Normal file
@@ -0,0 +1,354 @@
|
||||
/* eslint-disable @typescript-eslint/no-redundant-type-constituents -- eslint can't resolve @tracearr/shared types but TS compiles fine */
|
||||
import { useState } from 'react';
|
||||
import { Monitor, Wifi, Globe, Check, X, Loader2, ChevronDown, ChevronRight } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { PlexDiscoveredServer, PlexDiscoveredConnection } from '@tracearr/shared';
|
||||
import type { PlexServerInfo, PlexServerConnection } from '@/lib/api';
|
||||
|
||||
/**
|
||||
* Props for PlexServerSelector component
|
||||
*
|
||||
* Two modes:
|
||||
* 1. Discovery mode (Settings): servers with tested connections, uses recommendedUri
|
||||
* 2. Signup mode (Login): servers without testing, user picks any connection
|
||||
*/
|
||||
export interface PlexServerSelectorProps {
|
||||
/**
|
||||
* Servers to display - can be either discovered (with testing) or basic (signup flow)
|
||||
*/
|
||||
servers: PlexDiscoveredServer[] | PlexServerInfo[];
|
||||
|
||||
/**
|
||||
* Called when user selects a server
|
||||
* @param serverUri - The selected connection URI
|
||||
* @param serverName - The server name
|
||||
* @param clientIdentifier - The server's unique identifier
|
||||
*/
|
||||
onSelect: (serverUri: string, serverName: string, clientIdentifier: string) => void;
|
||||
|
||||
/**
|
||||
* Whether a connection attempt is in progress
|
||||
*/
|
||||
connecting?: boolean;
|
||||
|
||||
/**
|
||||
* Name of server currently being connected to
|
||||
*/
|
||||
connectingToServer?: string | null;
|
||||
|
||||
/**
|
||||
* Called when user clicks cancel/back
|
||||
*/
|
||||
onCancel?: () => void;
|
||||
|
||||
/**
|
||||
* Show cancel button (default true)
|
||||
*/
|
||||
showCancel?: boolean;
|
||||
|
||||
/**
|
||||
* Additional className for the container
|
||||
*/
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard to check if a server has discovery info (tested connections)
|
||||
*/
|
||||
function isDiscoveredServer(server: PlexDiscoveredServer | PlexServerInfo): server is PlexDiscoveredServer {
|
||||
return 'recommendedUri' in server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard to check if a connection has test results
|
||||
*/
|
||||
function isDiscoveredConnection(conn: PlexDiscoveredConnection | PlexServerConnection): conn is PlexDiscoveredConnection {
|
||||
return 'reachable' in conn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format latency for display
|
||||
*/
|
||||
function formatLatency(ms: number | null): string {
|
||||
if (ms === null) return '';
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
return `${(ms / 1000).toFixed(1)}s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* PlexServerSelector - Displays Plex servers grouped by server with connection options
|
||||
*
|
||||
* Used in two contexts:
|
||||
* 1. Settings page: Shows tested connections with reachability status and auto-selects best
|
||||
* 2. Login page: Shows all connections for user selection during signup
|
||||
*/
|
||||
export function PlexServerSelector({
|
||||
servers,
|
||||
onSelect,
|
||||
connecting = false,
|
||||
connectingToServer = null,
|
||||
onCancel,
|
||||
showCancel = true,
|
||||
className,
|
||||
}: PlexServerSelectorProps) {
|
||||
// Track which servers have expanded connection lists
|
||||
const [expandedServers, setExpandedServers] = useState<Set<string>>(new Set());
|
||||
|
||||
const toggleExpanded = (clientIdentifier: string) => {
|
||||
setExpandedServers(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(clientIdentifier)) {
|
||||
next.delete(clientIdentifier);
|
||||
} else {
|
||||
next.add(clientIdentifier);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleQuickConnect = (server: PlexDiscoveredServer | PlexServerInfo) => {
|
||||
// For discovered servers, use recommended URI; for basic, use first connection
|
||||
const uri = isDiscoveredServer(server)
|
||||
? server.recommendedUri
|
||||
: server.connections[0]?.uri;
|
||||
|
||||
if (!uri) return;
|
||||
|
||||
onSelect(uri, server.name, server.clientIdentifier);
|
||||
};
|
||||
|
||||
const handleConnectionSelect = (
|
||||
server: PlexDiscoveredServer | PlexServerInfo,
|
||||
connection: PlexDiscoveredConnection | PlexServerConnection
|
||||
) => {
|
||||
onSelect(connection.uri, server.name, server.clientIdentifier);
|
||||
};
|
||||
|
||||
if (servers.length === 0) {
|
||||
return (
|
||||
<div className={cn('text-center py-8 text-muted-foreground', className)}>
|
||||
<Monitor className="mx-auto h-12 w-12 mb-3 opacity-50" />
|
||||
<p>No Plex servers found</p>
|
||||
<p className="text-sm mt-1">Make sure you own at least one Plex server</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('space-y-3', className)}>
|
||||
{servers.map((server) => {
|
||||
const clientId = server.clientIdentifier;
|
||||
const isExpanded = expandedServers.has(clientId);
|
||||
const isDiscovered = isDiscoveredServer(server);
|
||||
const hasRecommended = isDiscovered && server.recommendedUri;
|
||||
const isConnecting = connectingToServer === server.name;
|
||||
|
||||
// For discovered servers, find recommended connection
|
||||
const recommendedConn = isDiscovered
|
||||
? server.connections.find(c => c.uri === server.recommendedUri)
|
||||
: null;
|
||||
|
||||
// Count reachable connections for discovered servers
|
||||
const reachableCount = isDiscovered
|
||||
? server.connections.filter(c => c.reachable).length
|
||||
: server.connections.length;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={clientId}
|
||||
className="rounded-lg border bg-card p-4"
|
||||
>
|
||||
{/* Server Header */}
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
|
||||
<Monitor className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h3 className="font-medium truncate">{server.name}</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{server.platform} • v{server.version}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Connect Button */}
|
||||
{hasRecommended && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleQuickConnect(server)}
|
||||
disabled={connecting}
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-1" />
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
'Connect'
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* No recommended - need to select manually */}
|
||||
{isDiscovered && !hasRecommended && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
No reachable connections
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Recommended Connection Preview (for discovered servers) */}
|
||||
{recommendedConn && isDiscoveredConnection(recommendedConn) && (
|
||||
<div className="mt-3 flex items-center gap-2 text-sm">
|
||||
<Check className="h-4 w-4 text-green-500" />
|
||||
<span className="text-muted-foreground">
|
||||
{recommendedConn.local ? 'Local' : 'Remote'}: {recommendedConn.address}:{recommendedConn.port}
|
||||
</span>
|
||||
{recommendedConn.latencyMs !== null && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
({formatLatency(recommendedConn.latencyMs)})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Connection Count & Expand Toggle */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleExpanded(clientId)}
|
||||
className="mt-3 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3" />
|
||||
)}
|
||||
{reachableCount} of {server.connections.length} connections
|
||||
{isDiscovered ? ' reachable' : ' available'}
|
||||
</button>
|
||||
|
||||
{/* Expanded Connection List */}
|
||||
{isExpanded && (
|
||||
<div className="mt-3 space-y-1.5 pl-2 border-l-2 border-muted">
|
||||
{server.connections.map((conn) => {
|
||||
const isDiscoveredConn = isDiscoveredConnection(conn);
|
||||
const isReachable = isDiscoveredConn ? conn.reachable : true;
|
||||
const isRecommended = isDiscovered && conn.uri === server.recommendedUri;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={conn.uri}
|
||||
type="button"
|
||||
onClick={() => isReachable && handleConnectionSelect(server, conn)}
|
||||
disabled={connecting || !isReachable}
|
||||
className={cn(
|
||||
'w-full flex items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm transition-colors',
|
||||
isReachable
|
||||
? 'hover:bg-muted cursor-pointer'
|
||||
: 'opacity-50 cursor-not-allowed',
|
||||
isRecommended && 'bg-muted/50 ring-1 ring-primary/20'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{/* Reachability indicator */}
|
||||
{isDiscoveredConn ? (
|
||||
conn.reachable ? (
|
||||
<Check className="h-3.5 w-3.5 flex-shrink-0 text-green-500" />
|
||||
) : (
|
||||
<X className="h-3.5 w-3.5 flex-shrink-0 text-red-500" />
|
||||
)
|
||||
) : conn.local ? (
|
||||
<Wifi className="h-3.5 w-3.5 flex-shrink-0 text-green-500" />
|
||||
) : (
|
||||
<Globe className="h-3.5 w-3.5 flex-shrink-0 text-blue-500" />
|
||||
)}
|
||||
|
||||
{/* Connection details */}
|
||||
<span className="truncate">
|
||||
{conn.local ? 'Local' : 'Remote'}: {conn.address}:{conn.port}
|
||||
</span>
|
||||
|
||||
{/* Recommended badge */}
|
||||
{isRecommended && (
|
||||
<span className="flex-shrink-0 text-xs text-primary font-medium">
|
||||
Recommended
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Latency */}
|
||||
{isDiscoveredConn && conn.reachable && conn.latencyMs !== null && (
|
||||
<span className="flex-shrink-0 text-xs text-muted-foreground">
|
||||
{formatLatency(conn.latencyMs)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* For non-discovered servers (signup flow), show simple connection buttons if no expand */}
|
||||
{!isDiscovered && !isExpanded && (
|
||||
<div className="mt-3 space-y-1.5">
|
||||
{server.connections.slice(0, 2).map((conn) => (
|
||||
<Button
|
||||
key={conn.uri}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full justify-between"
|
||||
onClick={() => handleConnectionSelect(server, conn)}
|
||||
disabled={connecting}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{conn.local ? (
|
||||
<Wifi className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Globe className="h-3 w-3 text-blue-500" />
|
||||
)}
|
||||
<span className="text-xs">
|
||||
{conn.local ? 'Local' : 'Remote'}: {conn.address}:{conn.port}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
))}
|
||||
{server.connections.length > 2 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleExpanded(clientId)}
|
||||
className="w-full text-xs text-muted-foreground hover:text-foreground py-1"
|
||||
>
|
||||
+{server.connections.length - 2} more connections
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Connecting status */}
|
||||
{connectingToServer && (
|
||||
<div className="flex items-center justify-center gap-2 py-3 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Connecting to {connectingToServer}...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Cancel button */}
|
||||
{showCancel && onCancel && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
onClick={onCancel}
|
||||
disabled={connecting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
33
apps/web/src/components/auth/ProtectedRoute.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Navigate, useLocation } from 'react-router';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps routes that require authentication.
|
||||
* Redirects to /login if user is not authenticated.
|
||||
*/
|
||||
export function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
const { isAuthenticated, isLoading } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
// Show loading spinner while checking auth status
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Redirect to login if not authenticated
|
||||
if (!isAuthenticated) {
|
||||
// Save the attempted URL for redirecting after login
|
||||
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
83
apps/web/src/components/brand/Logo.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface LogoProps {
|
||||
size?: 'sm' | 'md' | 'lg' | 'xl';
|
||||
showText?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const sizes = {
|
||||
sm: { icon: 'h-6 w-6', text: 'text-lg' },
|
||||
md: { icon: 'h-8 w-8', text: 'text-xl' },
|
||||
lg: { icon: 'h-12 w-12', text: 'text-3xl' },
|
||||
xl: { icon: 'h-16 w-16', text: 'text-4xl' },
|
||||
};
|
||||
|
||||
export function Logo({ size = 'md', showText = true, className }: LogoProps) {
|
||||
const { icon, text } = sizes[size];
|
||||
|
||||
return (
|
||||
<div className={cn('flex items-center gap-2', className)}>
|
||||
<LogoIcon className={icon} />
|
||||
{showText && (
|
||||
<span className={cn('font-bold tracking-tight', text)}>Tracearr</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface LogoIconProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function LogoIcon({ className }: LogoIconProps) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 64 64"
|
||||
fill="none"
|
||||
className={cn('shrink-0', className)}
|
||||
>
|
||||
{/* Background shield shape */}
|
||||
<path
|
||||
d="M32 4L8 14v18c0 14 10 24 24 28 14-4 24-14 24-28V14L32 4z"
|
||||
className="fill-blue-core"
|
||||
/>
|
||||
{/* Inner shield */}
|
||||
<path
|
||||
d="M32 8L12 16v14c0 12 8.5 20.5 20 24 11.5-3.5 20-12 20-24V16L32 8z"
|
||||
className="fill-blue-steel"
|
||||
/>
|
||||
{/* T-path stylized */}
|
||||
<path
|
||||
d="M22 24h20v4H34v16h-4V28H22v-4z"
|
||||
className="fill-cyan-core"
|
||||
/>
|
||||
{/* Radar arcs */}
|
||||
<path
|
||||
d="M32 20a16 16 0 0 1 11.3 4.7"
|
||||
className="stroke-cyan-core"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
fill="none"
|
||||
opacity="0.6"
|
||||
/>
|
||||
<path
|
||||
d="M32 16a20 20 0 0 1 14.1 5.9"
|
||||
className="stroke-cyan-core"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
fill="none"
|
||||
opacity="0.4"
|
||||
/>
|
||||
<path
|
||||
d="M32 12a24 24 0 0 1 17 7"
|
||||
className="stroke-cyan-core"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
fill="none"
|
||||
opacity="0.2"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
250
apps/web/src/components/charts/ConcurrentChart.tsx
Normal file
@@ -0,0 +1,250 @@
|
||||
import { useMemo } from 'react';
|
||||
import Highcharts from 'highcharts';
|
||||
import HighchartsReact from 'highcharts-react-official';
|
||||
import { ChartSkeleton } from '@/components/ui/skeleton';
|
||||
|
||||
interface ConcurrentData {
|
||||
hour: string;
|
||||
total: number;
|
||||
direct: number;
|
||||
transcode: number;
|
||||
}
|
||||
|
||||
interface ConcurrentChartProps {
|
||||
data: ConcurrentData[] | undefined;
|
||||
isLoading?: boolean;
|
||||
height?: number;
|
||||
period?: 'day' | 'week' | 'month' | 'year' | 'all' | 'custom';
|
||||
}
|
||||
|
||||
export function ConcurrentChart({ data, isLoading, height = 250, period = 'month' }: ConcurrentChartProps) {
|
||||
const options = useMemo<Highcharts.Options>(() => {
|
||||
if (!data || data.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// Find the peak total for highlighting
|
||||
const maxValue = Math.max(...data.map((d) => d.total));
|
||||
|
||||
return {
|
||||
chart: {
|
||||
type: 'area',
|
||||
height,
|
||||
backgroundColor: 'transparent',
|
||||
style: {
|
||||
fontFamily: 'inherit',
|
||||
},
|
||||
reflow: true,
|
||||
},
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
credits: {
|
||||
enabled: false,
|
||||
},
|
||||
legend: {
|
||||
enabled: true,
|
||||
align: 'right',
|
||||
verticalAlign: 'top',
|
||||
floating: true,
|
||||
itemStyle: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
fontWeight: 'normal',
|
||||
fontSize: '11px',
|
||||
},
|
||||
itemHoverStyle: {
|
||||
color: 'hsl(var(--foreground))',
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
categories: data.map((d) => d.hour),
|
||||
// Calculate appropriate number of labels based on period
|
||||
// Week: 7 labels (one per day), Month: ~10, Year: 12
|
||||
tickPositions: (() => {
|
||||
const numLabels = period === 'week' || period === 'day' ? 7 : period === 'month' ? 10 : 12;
|
||||
const actualLabels = Math.min(numLabels, data.length);
|
||||
return Array.from({ length: actualLabels }, (_, i) =>
|
||||
Math.floor(i * (data.length - 1) / (actualLabels - 1 || 1))
|
||||
);
|
||||
})(),
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
},
|
||||
formatter: function () {
|
||||
// this.value could be index (number) or category string depending on Highcharts version
|
||||
const categories = this.axis.categories;
|
||||
const categoryValue = typeof this.value === 'number'
|
||||
? categories[this.value]
|
||||
: this.value;
|
||||
if (!categoryValue) return '';
|
||||
const date = new Date(categoryValue);
|
||||
if (isNaN(date.getTime())) return '';
|
||||
if (period === 'year') {
|
||||
// Short month name for yearly view (Dec, Jan, Feb)
|
||||
return date.toLocaleDateString('en-US', { month: 'short' });
|
||||
}
|
||||
// M/D format for week/month views
|
||||
return `${date.getMonth() + 1}/${date.getDate()}`;
|
||||
},
|
||||
},
|
||||
lineColor: 'hsl(var(--border))',
|
||||
tickColor: 'hsl(var(--border))',
|
||||
},
|
||||
yAxis: {
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
},
|
||||
},
|
||||
gridLineColor: 'hsl(var(--border))',
|
||||
min: 0,
|
||||
allowDecimals: false,
|
||||
plotLines: [
|
||||
{
|
||||
value: maxValue,
|
||||
color: 'hsl(var(--destructive))',
|
||||
dashStyle: 'Dash',
|
||||
width: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
plotOptions: {
|
||||
area: {
|
||||
stacking: 'normal',
|
||||
marker: {
|
||||
enabled: false,
|
||||
states: {
|
||||
hover: {
|
||||
enabled: true,
|
||||
radius: 4,
|
||||
},
|
||||
},
|
||||
},
|
||||
lineWidth: 2,
|
||||
states: {
|
||||
hover: {
|
||||
lineWidth: 2,
|
||||
},
|
||||
},
|
||||
threshold: null,
|
||||
},
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'hsl(var(--popover))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
style: {
|
||||
color: 'hsl(var(--popover-foreground))',
|
||||
},
|
||||
shared: true,
|
||||
formatter: function () {
|
||||
const points = this.points || [];
|
||||
// With categories, this.x is the index. Use the category value from points[0].key
|
||||
const categoryValue = points[0]?.key as string | undefined;
|
||||
const date = categoryValue ? new Date(categoryValue) : null;
|
||||
const dateStr = date && !isNaN(date.getTime())
|
||||
? `${date.toLocaleDateString()} ${date.getHours()}:00`
|
||||
: 'Unknown';
|
||||
let html = `<b>${dateStr}</b>`;
|
||||
|
||||
// Calculate total from stacked values
|
||||
let total = 0;
|
||||
points.forEach((point) => {
|
||||
total += point.y || 0;
|
||||
html += `<br/><span style="color:${point.color}">●</span> ${point.series.name}: ${point.y}`;
|
||||
});
|
||||
html += `<br/><b>Total: ${total}</b>`;
|
||||
|
||||
return html;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'area',
|
||||
name: 'Direct Play',
|
||||
data: data.map((d) => d.direct),
|
||||
color: 'hsl(var(--chart-2))',
|
||||
fillColor: {
|
||||
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
|
||||
stops: [
|
||||
[0, 'hsl(var(--chart-2) / 0.4)'],
|
||||
[1, 'hsl(var(--chart-2) / 0.1)'],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'area',
|
||||
name: 'Transcode',
|
||||
data: data.map((d) => d.transcode),
|
||||
color: 'hsl(var(--chart-4))',
|
||||
fillColor: {
|
||||
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
|
||||
stops: [
|
||||
[0, 'hsl(var(--chart-4) / 0.4)'],
|
||||
[1, 'hsl(var(--chart-4) / 0.1)'],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
responsive: {
|
||||
rules: [
|
||||
{
|
||||
condition: {
|
||||
maxWidth: 400,
|
||||
},
|
||||
chartOptions: {
|
||||
legend: {
|
||||
floating: false,
|
||||
align: 'center',
|
||||
verticalAlign: 'bottom',
|
||||
itemStyle: {
|
||||
fontSize: '10px',
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '9px',
|
||||
},
|
||||
},
|
||||
},
|
||||
yAxis: {
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '9px',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}, [data, height, period]);
|
||||
|
||||
if (isLoading) {
|
||||
return <ChartSkeleton height={height} />;
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-center rounded-lg border border-dashed text-muted-foreground"
|
||||
style={{ height }}
|
||||
>
|
||||
No concurrent stream data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<HighchartsReact
|
||||
highcharts={Highcharts}
|
||||
options={options}
|
||||
containerProps={{ style: { width: '100%', height: '100%' } }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
136
apps/web/src/components/charts/DayOfWeekChart.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
import { useMemo } from 'react';
|
||||
import Highcharts from 'highcharts';
|
||||
import HighchartsReact from 'highcharts-react-official';
|
||||
import { ChartSkeleton } from '@/components/ui/skeleton';
|
||||
|
||||
interface DayOfWeekData {
|
||||
day: number;
|
||||
name: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface DayOfWeekChartProps {
|
||||
data: DayOfWeekData[] | undefined;
|
||||
isLoading?: boolean;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
export function DayOfWeekChart({ data, isLoading, height = 250 }: DayOfWeekChartProps) {
|
||||
const options = useMemo<Highcharts.Options>(() => {
|
||||
if (!data || data.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
chart: {
|
||||
type: 'column',
|
||||
height,
|
||||
backgroundColor: 'transparent',
|
||||
style: {
|
||||
fontFamily: 'inherit',
|
||||
},
|
||||
reflow: true,
|
||||
},
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
credits: {
|
||||
enabled: false,
|
||||
},
|
||||
legend: {
|
||||
enabled: false,
|
||||
},
|
||||
xAxis: {
|
||||
categories: data.map((d) => d.name),
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
},
|
||||
},
|
||||
lineColor: 'hsl(var(--border))',
|
||||
tickColor: 'hsl(var(--border))',
|
||||
},
|
||||
yAxis: {
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
},
|
||||
},
|
||||
gridLineColor: 'hsl(var(--border))',
|
||||
min: 0,
|
||||
},
|
||||
plotOptions: {
|
||||
column: {
|
||||
borderRadius: 4,
|
||||
color: 'hsl(var(--primary))',
|
||||
states: {
|
||||
hover: {
|
||||
color: 'hsl(var(--primary) / 0.8)',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'hsl(var(--popover))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
style: {
|
||||
color: 'hsl(var(--popover-foreground))',
|
||||
},
|
||||
formatter: function () {
|
||||
return `<b>${this.x}</b><br/>Plays: ${this.y}`;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'column',
|
||||
name: 'Plays',
|
||||
data: data.map((d) => d.count),
|
||||
},
|
||||
],
|
||||
responsive: {
|
||||
rules: [
|
||||
{
|
||||
condition: {
|
||||
maxWidth: 400,
|
||||
},
|
||||
chartOptions: {
|
||||
xAxis: {
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '9px',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}, [data, height]);
|
||||
|
||||
if (isLoading) {
|
||||
return <ChartSkeleton height={height} />;
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-center rounded-lg border border-dashed text-muted-foreground"
|
||||
style={{ height }}
|
||||
>
|
||||
No data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<HighchartsReact
|
||||
highcharts={Highcharts}
|
||||
options={options}
|
||||
containerProps={{ style: { width: '100%', height: '100%' } }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
147
apps/web/src/components/charts/HourOfDayChart.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
import { useMemo } from 'react';
|
||||
import Highcharts from 'highcharts';
|
||||
import HighchartsReact from 'highcharts-react-official';
|
||||
import { ChartSkeleton } from '@/components/ui/skeleton';
|
||||
|
||||
interface HourOfDayData {
|
||||
hour: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface HourOfDayChartProps {
|
||||
data: HourOfDayData[] | undefined;
|
||||
isLoading?: boolean;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
export function HourOfDayChart({ data, isLoading, height = 250 }: HourOfDayChartProps) {
|
||||
const options = useMemo<Highcharts.Options>(() => {
|
||||
if (!data || data.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// Format hour labels (12am, 1am, ... 11pm)
|
||||
const formatHour = (hour: number): string => {
|
||||
if (hour === 0) return '12am';
|
||||
if (hour === 12) return '12pm';
|
||||
return hour < 12 ? `${hour}am` : `${hour - 12}pm`;
|
||||
};
|
||||
|
||||
return {
|
||||
chart: {
|
||||
type: 'column',
|
||||
height,
|
||||
backgroundColor: 'transparent',
|
||||
style: {
|
||||
fontFamily: 'inherit',
|
||||
},
|
||||
reflow: true,
|
||||
},
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
credits: {
|
||||
enabled: false,
|
||||
},
|
||||
legend: {
|
||||
enabled: false,
|
||||
},
|
||||
xAxis: {
|
||||
categories: data.map((d) => formatHour(d.hour)),
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
fontSize: '10px',
|
||||
},
|
||||
rotation: -45,
|
||||
},
|
||||
lineColor: 'hsl(var(--border))',
|
||||
tickColor: 'hsl(var(--border))',
|
||||
},
|
||||
yAxis: {
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
},
|
||||
},
|
||||
gridLineColor: 'hsl(var(--border))',
|
||||
min: 0,
|
||||
},
|
||||
plotOptions: {
|
||||
column: {
|
||||
borderRadius: 2,
|
||||
color: 'hsl(var(--chart-2))',
|
||||
pointPadding: 0.1,
|
||||
groupPadding: 0.1,
|
||||
states: {
|
||||
hover: {
|
||||
color: 'hsl(var(--chart-2) / 0.8)',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'hsl(var(--popover))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
style: {
|
||||
color: 'hsl(var(--popover-foreground))',
|
||||
},
|
||||
formatter: function () {
|
||||
return `<b>${this.x}</b><br/>Plays: ${this.y}`;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'column',
|
||||
name: 'Plays',
|
||||
data: data.map((d) => d.count),
|
||||
},
|
||||
],
|
||||
responsive: {
|
||||
rules: [
|
||||
{
|
||||
condition: {
|
||||
maxWidth: 400,
|
||||
},
|
||||
chartOptions: {
|
||||
xAxis: {
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '8px',
|
||||
},
|
||||
rotation: -60,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}, [data, height]);
|
||||
|
||||
if (isLoading) {
|
||||
return <ChartSkeleton height={height} />;
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-center rounded-lg border border-dashed text-muted-foreground"
|
||||
style={{ height }}
|
||||
>
|
||||
No data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<HighchartsReact
|
||||
highcharts={Highcharts}
|
||||
options={options}
|
||||
containerProps={{ style: { width: '100%', height: '100%' } }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
133
apps/web/src/components/charts/PlatformChart.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import { useMemo } from 'react';
|
||||
import Highcharts from 'highcharts';
|
||||
import HighchartsReact from 'highcharts-react-official';
|
||||
import { ChartSkeleton } from '@/components/ui/skeleton';
|
||||
|
||||
interface PlatformData {
|
||||
name: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface PlatformChartProps {
|
||||
data: PlatformData[] | undefined;
|
||||
isLoading?: boolean;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
const COLORS = [
|
||||
'hsl(var(--primary))',
|
||||
'hsl(221, 83%, 53%)', // Blue
|
||||
'hsl(142, 76%, 36%)', // Green
|
||||
'hsl(38, 92%, 50%)', // Yellow/Orange
|
||||
'hsl(262, 83%, 58%)', // Purple
|
||||
'hsl(340, 82%, 52%)', // Pink
|
||||
];
|
||||
|
||||
export function PlatformChart({ data, isLoading, height = 200 }: PlatformChartProps) {
|
||||
const options = useMemo<Highcharts.Options>(() => {
|
||||
if (!data || data.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
chart: {
|
||||
type: 'pie',
|
||||
height,
|
||||
backgroundColor: 'transparent',
|
||||
style: {
|
||||
fontFamily: 'inherit',
|
||||
},
|
||||
reflow: true,
|
||||
},
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
credits: {
|
||||
enabled: false,
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'hsl(var(--popover))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
style: {
|
||||
color: 'hsl(var(--popover-foreground))',
|
||||
},
|
||||
pointFormat: '<b>{point.y}</b> plays ({point.percentage:.1f}%)',
|
||||
},
|
||||
plotOptions: {
|
||||
pie: {
|
||||
innerSize: '60%',
|
||||
borderWidth: 0,
|
||||
dataLabels: {
|
||||
enabled: false,
|
||||
},
|
||||
showInLegend: true,
|
||||
colors: COLORS,
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
align: 'right',
|
||||
verticalAlign: 'middle',
|
||||
layout: 'vertical',
|
||||
itemStyle: {
|
||||
color: 'hsl(var(--foreground))',
|
||||
},
|
||||
itemHoverStyle: {
|
||||
color: 'hsl(var(--primary))',
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'pie',
|
||||
name: 'Platform',
|
||||
data: data.map((d, i) => ({
|
||||
name: d.name,
|
||||
y: d.count,
|
||||
color: COLORS[i % COLORS.length],
|
||||
})),
|
||||
},
|
||||
],
|
||||
responsive: {
|
||||
rules: [
|
||||
{
|
||||
condition: {
|
||||
maxWidth: 400,
|
||||
},
|
||||
chartOptions: {
|
||||
legend: {
|
||||
align: 'center',
|
||||
verticalAlign: 'bottom',
|
||||
layout: 'horizontal',
|
||||
itemStyle: {
|
||||
fontSize: '10px',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}, [data, height]);
|
||||
|
||||
if (isLoading) {
|
||||
return <ChartSkeleton height={height} />;
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-center rounded-lg border border-dashed text-muted-foreground"
|
||||
style={{ height }}
|
||||
>
|
||||
No platform data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<HighchartsReact
|
||||
highcharts={Highcharts}
|
||||
options={options}
|
||||
containerProps={{ style: { width: '100%', height: '100%' } }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
181
apps/web/src/components/charts/PlaysChart.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
import { useMemo } from 'react';
|
||||
import Highcharts from 'highcharts';
|
||||
import HighchartsReact from 'highcharts-react-official';
|
||||
import type { PlayStats } from '@tracearr/shared';
|
||||
import { ChartSkeleton } from '@/components/ui/skeleton';
|
||||
|
||||
interface PlaysChartProps {
|
||||
data: PlayStats[] | undefined;
|
||||
isLoading?: boolean;
|
||||
height?: number;
|
||||
period?: 'day' | 'week' | 'month' | 'year' | 'all' | 'custom';
|
||||
}
|
||||
|
||||
export function PlaysChart({ data, isLoading, height = 200, period = 'month' }: PlaysChartProps) {
|
||||
const options = useMemo<Highcharts.Options>(() => {
|
||||
if (!data || data.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
chart: {
|
||||
type: 'area',
|
||||
height,
|
||||
backgroundColor: 'transparent',
|
||||
style: {
|
||||
fontFamily: 'inherit',
|
||||
},
|
||||
reflow: true,
|
||||
},
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
credits: {
|
||||
enabled: false,
|
||||
},
|
||||
legend: {
|
||||
enabled: false,
|
||||
},
|
||||
xAxis: {
|
||||
categories: data.map((d) => d.date),
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
},
|
||||
formatter: function () {
|
||||
// this.value could be index (number) or category string depending on Highcharts version
|
||||
const categories = this.axis.categories;
|
||||
const categoryValue = typeof this.value === 'number'
|
||||
? categories[this.value]
|
||||
: this.value;
|
||||
if (!categoryValue) return '';
|
||||
const date = new Date(categoryValue);
|
||||
if (isNaN(date.getTime())) return '';
|
||||
if (period === 'year') {
|
||||
// Short month name for yearly view (Dec, Jan, Feb)
|
||||
return date.toLocaleDateString('en-US', { month: 'short' });
|
||||
}
|
||||
// M/D format for week/month views
|
||||
return `${date.getMonth() + 1}/${date.getDate()}`;
|
||||
},
|
||||
step: Math.ceil(data.length / 12), // Show ~12 labels
|
||||
},
|
||||
lineColor: 'hsl(var(--border))',
|
||||
tickColor: 'hsl(var(--border))',
|
||||
},
|
||||
yAxis: {
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
},
|
||||
},
|
||||
gridLineColor: 'hsl(var(--border))',
|
||||
min: 0,
|
||||
},
|
||||
plotOptions: {
|
||||
area: {
|
||||
fillColor: {
|
||||
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
|
||||
stops: [
|
||||
[0, 'hsl(var(--primary) / 0.3)'],
|
||||
[1, 'hsl(var(--primary) / 0.05)'],
|
||||
],
|
||||
},
|
||||
marker: {
|
||||
enabled: false,
|
||||
states: {
|
||||
hover: {
|
||||
enabled: true,
|
||||
radius: 4,
|
||||
},
|
||||
},
|
||||
},
|
||||
lineWidth: 2,
|
||||
lineColor: 'hsl(var(--primary))',
|
||||
states: {
|
||||
hover: {
|
||||
lineWidth: 2,
|
||||
},
|
||||
},
|
||||
threshold: null,
|
||||
},
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'hsl(var(--popover))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
style: {
|
||||
color: 'hsl(var(--popover-foreground))',
|
||||
},
|
||||
formatter: function () {
|
||||
// With categories, this.x is the index. Use this.point.category for the actual value
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const categoryValue = (this as any).point?.category as string | undefined;
|
||||
const date = categoryValue ? new Date(categoryValue) : null;
|
||||
const dateStr = date && !isNaN(date.getTime())
|
||||
? date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
|
||||
: 'Unknown';
|
||||
return `<b>${dateStr}</b><br/>Plays: ${this.y}`;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'area',
|
||||
name: 'Plays',
|
||||
data: data.map((d) => d.count),
|
||||
},
|
||||
],
|
||||
responsive: {
|
||||
rules: [
|
||||
{
|
||||
condition: {
|
||||
maxWidth: 400,
|
||||
},
|
||||
chartOptions: {
|
||||
xAxis: {
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '9px',
|
||||
},
|
||||
step: Math.ceil(data.length / 6),
|
||||
},
|
||||
},
|
||||
yAxis: {
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '9px',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}, [data, height, period]);
|
||||
|
||||
if (isLoading) {
|
||||
return <ChartSkeleton height={height} />;
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-center rounded-lg border border-dashed text-muted-foreground"
|
||||
style={{ height }}
|
||||
>
|
||||
No play data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<HighchartsReact
|
||||
highcharts={Highcharts}
|
||||
options={options}
|
||||
containerProps={{ style: { width: '100%', height: '100%' } }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
138
apps/web/src/components/charts/QualityChart.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
import { useMemo } from 'react';
|
||||
import Highcharts from 'highcharts';
|
||||
import HighchartsReact from 'highcharts-react-official';
|
||||
import { ChartSkeleton } from '@/components/ui/skeleton';
|
||||
|
||||
interface QualityData {
|
||||
directPlay: number;
|
||||
transcode: number;
|
||||
total: number;
|
||||
directPlayPercent: number;
|
||||
transcodePercent: number;
|
||||
}
|
||||
|
||||
interface QualityChartProps {
|
||||
data: QualityData | undefined;
|
||||
isLoading?: boolean;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
const COLORS = {
|
||||
directPlay: 'hsl(142, 76%, 36%)', // Green
|
||||
transcode: 'hsl(38, 92%, 50%)', // Orange
|
||||
};
|
||||
|
||||
export function QualityChart({ data, isLoading, height = 250 }: QualityChartProps) {
|
||||
const options = useMemo<Highcharts.Options>(() => {
|
||||
if (!data || data.total === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
chart: {
|
||||
type: 'pie',
|
||||
height,
|
||||
backgroundColor: 'transparent',
|
||||
style: {
|
||||
fontFamily: 'inherit',
|
||||
},
|
||||
reflow: true,
|
||||
},
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
credits: {
|
||||
enabled: false,
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'hsl(var(--popover))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
style: {
|
||||
color: 'hsl(var(--popover-foreground))',
|
||||
},
|
||||
pointFormat: '<b>{point.y}</b> plays ({point.percentage:.1f}%)',
|
||||
},
|
||||
plotOptions: {
|
||||
pie: {
|
||||
innerSize: '60%',
|
||||
borderWidth: 0,
|
||||
dataLabels: {
|
||||
enabled: false,
|
||||
},
|
||||
showInLegend: true,
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
align: 'right',
|
||||
verticalAlign: 'middle',
|
||||
layout: 'vertical',
|
||||
itemStyle: {
|
||||
color: 'hsl(var(--foreground))',
|
||||
},
|
||||
itemHoverStyle: {
|
||||
color: 'hsl(var(--primary))',
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'pie',
|
||||
name: 'Quality',
|
||||
data: [
|
||||
{
|
||||
name: 'Direct Play',
|
||||
y: data.directPlay,
|
||||
color: COLORS.directPlay,
|
||||
},
|
||||
{
|
||||
name: 'Transcode',
|
||||
y: data.transcode,
|
||||
color: COLORS.transcode,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
responsive: {
|
||||
rules: [
|
||||
{
|
||||
condition: {
|
||||
maxWidth: 400,
|
||||
},
|
||||
chartOptions: {
|
||||
legend: {
|
||||
align: 'center',
|
||||
verticalAlign: 'bottom',
|
||||
layout: 'horizontal',
|
||||
itemStyle: {
|
||||
fontSize: '10px',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}, [data, height]);
|
||||
|
||||
if (isLoading) {
|
||||
return <ChartSkeleton height={height} />;
|
||||
}
|
||||
|
||||
if (!data || data.total === 0) {
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-center rounded-lg border border-dashed text-muted-foreground"
|
||||
style={{ height }}
|
||||
>
|
||||
No quality data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<HighchartsReact
|
||||
highcharts={Highcharts}
|
||||
options={options}
|
||||
containerProps={{ style: { width: '100%', height: '100%' } }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
350
apps/web/src/components/charts/ServerResourceCharts.tsx
Normal file
@@ -0,0 +1,350 @@
|
||||
import { useMemo } from 'react';
|
||||
import Highcharts from 'highcharts';
|
||||
import HighchartsReact from 'highcharts-react-official';
|
||||
import type { ServerResourceDataPoint } from '@tracearr/shared';
|
||||
import { ChartSkeleton } from '@/components/ui/skeleton';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Cpu, MemoryStick } from 'lucide-react';
|
||||
|
||||
// Colors matching Plex's style
|
||||
const COLORS = {
|
||||
process: '#00b4e4', // Plex-style cyan for "Plex Media Server"
|
||||
system: '#cc7b9f', // Pink/purple for "System"
|
||||
processGradientStart: 'rgba(0, 180, 228, 0.3)',
|
||||
processGradientEnd: 'rgba(0, 180, 228, 0.05)',
|
||||
systemGradientStart: 'rgba(204, 123, 159, 0.3)',
|
||||
systemGradientEnd: 'rgba(204, 123, 159, 0.05)',
|
||||
};
|
||||
|
||||
interface ServerResourceChartsProps {
|
||||
data: ServerResourceDataPoint[] | undefined;
|
||||
isLoading?: boolean;
|
||||
averages?: {
|
||||
hostCpu: number;
|
||||
processCpu: number;
|
||||
hostMemory: number;
|
||||
processMemory: number;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface ResourceChartProps {
|
||||
title: string;
|
||||
icon: React.ReactNode;
|
||||
data: ServerResourceDataPoint[] | undefined;
|
||||
processKey: 'processCpuUtilization' | 'processMemoryUtilization';
|
||||
hostKey: 'hostCpuUtilization' | 'hostMemoryUtilization';
|
||||
processAvg?: number;
|
||||
hostAvg?: number;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
// Static x-axis labels (7 ticks at 20s intervals over 2 minutes)
|
||||
const X_LABELS: Record<number, string> = {
|
||||
[-120]: '2m',
|
||||
[-100]: '1m 40s',
|
||||
[-80]: '1m 20s',
|
||||
[-60]: '1m',
|
||||
[-40]: '40s',
|
||||
[-20]: '20s',
|
||||
[0]: 'NOW',
|
||||
};
|
||||
|
||||
/**
|
||||
* Single resource chart (CPU or RAM)
|
||||
*/
|
||||
function ResourceChart({
|
||||
title,
|
||||
icon,
|
||||
data,
|
||||
processKey,
|
||||
hostKey,
|
||||
processAvg,
|
||||
hostAvg,
|
||||
isLoading,
|
||||
}: ResourceChartProps) {
|
||||
const chartOptions = useMemo<Highcharts.Options>(() => {
|
||||
if (!data || data.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// Map data points to x positions in -120 to 0 range
|
||||
// Data is sorted oldest first, spread across the 2-minute window
|
||||
const processData: [number, number][] = [];
|
||||
const hostData: [number, number][] = [];
|
||||
|
||||
const n = data.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const point = data[i];
|
||||
if (!point) continue;
|
||||
// Spread points from -120 (oldest) to 0 (newest)
|
||||
const x = n === 1 ? 0 : -120 + (i * 120) / (n - 1);
|
||||
processData.push([x, point[processKey]]);
|
||||
hostData.push([x, point[hostKey]]);
|
||||
}
|
||||
|
||||
// Calculate dynamic Y-axis max (round up to nearest 10, min 20)
|
||||
const allValues = [...processData, ...hostData].map(([, y]) => y);
|
||||
const maxValue = Math.max(...allValues, 0);
|
||||
const yMax = Math.max(20, Math.ceil(maxValue / 10) * 10);
|
||||
|
||||
return {
|
||||
chart: {
|
||||
type: 'area',
|
||||
height: 180,
|
||||
backgroundColor: 'transparent',
|
||||
style: {
|
||||
fontFamily: 'inherit',
|
||||
},
|
||||
spacing: [10, 10, 15, 10],
|
||||
reflow: true,
|
||||
},
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
credits: {
|
||||
enabled: false,
|
||||
},
|
||||
legend: {
|
||||
enabled: true,
|
||||
align: 'left',
|
||||
verticalAlign: 'top',
|
||||
floating: false,
|
||||
itemStyle: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
fontWeight: 'normal',
|
||||
fontSize: '11px',
|
||||
},
|
||||
itemHoverStyle: {
|
||||
color: 'hsl(var(--foreground))',
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
type: 'linear',
|
||||
min: -120,
|
||||
max: 0,
|
||||
tickInterval: 20,
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
fontSize: '10px',
|
||||
},
|
||||
formatter: function () {
|
||||
return X_LABELS[this.value as number] || '';
|
||||
},
|
||||
},
|
||||
lineColor: 'hsl(var(--border))',
|
||||
tickColor: 'hsl(var(--border))',
|
||||
},
|
||||
yAxis: {
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
fontSize: '10px',
|
||||
},
|
||||
format: '{value}%',
|
||||
},
|
||||
gridLineColor: 'hsl(var(--border) / 0.5)',
|
||||
min: 0,
|
||||
max: yMax,
|
||||
tickInterval: yMax <= 20 ? 5 : 10,
|
||||
},
|
||||
plotOptions: {
|
||||
area: {
|
||||
marker: {
|
||||
enabled: false,
|
||||
states: {
|
||||
hover: {
|
||||
enabled: true,
|
||||
radius: 3,
|
||||
},
|
||||
},
|
||||
},
|
||||
lineWidth: 2,
|
||||
states: {
|
||||
hover: {
|
||||
lineWidth: 2,
|
||||
},
|
||||
},
|
||||
threshold: null,
|
||||
connectNulls: false, // Don't connect across null values
|
||||
},
|
||||
},
|
||||
tooltip: {
|
||||
shared: true,
|
||||
backgroundColor: 'hsl(var(--popover))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
style: {
|
||||
color: 'hsl(var(--popover-foreground))',
|
||||
fontSize: '11px',
|
||||
},
|
||||
formatter: function () {
|
||||
const points = this.points || [];
|
||||
let html = '';
|
||||
for (const point of points) {
|
||||
if (point.y !== null) {
|
||||
const color = point.series.color;
|
||||
html += `<span style="color:${color}">●</span> ${point.series.name}: <b>${Math.round(point.y as number)}%</b><br/>`;
|
||||
}
|
||||
}
|
||||
return html;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'area',
|
||||
name: 'Plex Media Server',
|
||||
data: processData,
|
||||
color: COLORS.process,
|
||||
fillColor: {
|
||||
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
|
||||
stops: [
|
||||
[0, COLORS.processGradientStart],
|
||||
[1, COLORS.processGradientEnd],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'area',
|
||||
name: 'System',
|
||||
data: hostData,
|
||||
color: COLORS.system,
|
||||
fillColor: {
|
||||
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
|
||||
stops: [
|
||||
[0, COLORS.systemGradientStart],
|
||||
[1, COLORS.systemGradientEnd],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
responsive: {
|
||||
rules: [
|
||||
{
|
||||
condition: {
|
||||
maxWidth: 400,
|
||||
},
|
||||
chartOptions: {
|
||||
legend: {
|
||||
align: 'center',
|
||||
layout: 'horizontal',
|
||||
itemStyle: {
|
||||
fontSize: '10px',
|
||||
},
|
||||
},
|
||||
xAxis: {
|
||||
tickInterval: 40,
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '9px',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}, [data, processKey, hostKey]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-medium">
|
||||
{icon}
|
||||
{title}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ChartSkeleton height={180} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-medium">
|
||||
{icon}
|
||||
{title}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div
|
||||
className="flex items-center justify-center rounded-lg border border-dashed text-muted-foreground text-sm"
|
||||
style={{ height: 180 }}
|
||||
>
|
||||
No data available
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center justify-between text-sm font-medium">
|
||||
<span className="flex items-center gap-2">
|
||||
{icon}
|
||||
{title}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pb-2">
|
||||
<HighchartsReact
|
||||
highcharts={Highcharts}
|
||||
options={chartOptions}
|
||||
containerProps={{ style: { width: '100%', height: '100%' } }}
|
||||
/>
|
||||
{/* Averages row */}
|
||||
<div className="flex justify-end gap-4 text-xs text-muted-foreground mt-1 pr-2">
|
||||
<span>
|
||||
<span style={{ color: COLORS.process }}>●</span> Avg:{' '}
|
||||
<span className="font-medium text-foreground">{processAvg ?? '—'}%</span>
|
||||
</span>
|
||||
<span>
|
||||
<span style={{ color: COLORS.system }}>●</span> Avg:{' '}
|
||||
<span className="font-medium text-foreground">{hostAvg ?? '—'}%</span>
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Server resource monitoring charts (CPU + RAM)
|
||||
* Displays real-time server resource utilization matching Plex's dashboard style
|
||||
*/
|
||||
export function ServerResourceCharts({ data, isLoading, averages }: ServerResourceChartsProps) {
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<ResourceChart
|
||||
title="CPU"
|
||||
icon={<Cpu className="h-4 w-4" />}
|
||||
data={data}
|
||||
processKey="processCpuUtilization"
|
||||
hostKey="hostCpuUtilization"
|
||||
processAvg={averages?.processCpu}
|
||||
hostAvg={averages?.hostCpu}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
<ResourceChart
|
||||
title="RAM"
|
||||
icon={<MemoryStick className="h-4 w-4" />}
|
||||
data={data}
|
||||
processKey="processMemoryUtilization"
|
||||
hostKey="hostMemoryUtilization"
|
||||
processAvg={averages?.processMemory}
|
||||
hostAvg={averages?.hostMemory}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
137
apps/web/src/components/charts/TopListChart.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import { useMemo } from 'react';
|
||||
import Highcharts from 'highcharts';
|
||||
import HighchartsReact from 'highcharts-react-official';
|
||||
import { ChartSkeleton } from '@/components/ui/skeleton';
|
||||
|
||||
interface TopListItem {
|
||||
name: string;
|
||||
value: number;
|
||||
subtitle?: string;
|
||||
}
|
||||
|
||||
interface TopListChartProps {
|
||||
data: TopListItem[] | undefined;
|
||||
isLoading?: boolean;
|
||||
height?: number;
|
||||
valueLabel?: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export function TopListChart({
|
||||
data,
|
||||
isLoading,
|
||||
height = 250,
|
||||
valueLabel = 'Value',
|
||||
color = 'hsl(var(--primary))',
|
||||
}: TopListChartProps) {
|
||||
const options = useMemo<Highcharts.Options>(() => {
|
||||
if (!data || data.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// Take top 10
|
||||
const top10 = data.slice(0, 10);
|
||||
|
||||
return {
|
||||
chart: {
|
||||
type: 'bar',
|
||||
height,
|
||||
backgroundColor: 'transparent',
|
||||
style: {
|
||||
fontFamily: 'inherit',
|
||||
},
|
||||
},
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
credits: {
|
||||
enabled: false,
|
||||
},
|
||||
legend: {
|
||||
enabled: false,
|
||||
},
|
||||
xAxis: {
|
||||
categories: top10.map((d) => d.name),
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
fontSize: '11px',
|
||||
},
|
||||
},
|
||||
lineColor: 'hsl(var(--border))',
|
||||
tickColor: 'hsl(var(--border))',
|
||||
},
|
||||
yAxis: {
|
||||
title: {
|
||||
text: undefined,
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
},
|
||||
},
|
||||
gridLineColor: 'hsl(var(--border))',
|
||||
min: 0,
|
||||
},
|
||||
plotOptions: {
|
||||
bar: {
|
||||
borderRadius: 4,
|
||||
color: color,
|
||||
dataLabels: {
|
||||
enabled: true,
|
||||
style: {
|
||||
color: 'hsl(var(--muted-foreground))',
|
||||
textOutline: 'none',
|
||||
fontWeight: 'normal',
|
||||
},
|
||||
},
|
||||
states: {
|
||||
hover: {
|
||||
color: color.replace(')', ' / 0.8)').replace('hsl', 'hsl'),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: 'hsl(var(--popover))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
style: {
|
||||
color: 'hsl(var(--popover-foreground))',
|
||||
},
|
||||
formatter: function () {
|
||||
const xValue = String(this.x);
|
||||
const item = top10.find((d) => d.name === xValue);
|
||||
let tooltip = `<b>${xValue}</b><br/>${valueLabel}: ${this.y}`;
|
||||
if (item?.subtitle) {
|
||||
tooltip += `<br/><span style="font-size: 10px; color: hsl(var(--muted-foreground))">${item.subtitle}</span>`;
|
||||
}
|
||||
return tooltip;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'bar',
|
||||
name: valueLabel,
|
||||
data: top10.map((d) => d.value),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [data, height, valueLabel, color]);
|
||||
|
||||
if (isLoading) {
|
||||
return <ChartSkeleton height={height} />;
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-center rounded-lg border border-dashed text-muted-foreground"
|
||||
style={{ height }}
|
||||
>
|
||||
No data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <HighchartsReact highcharts={Highcharts} options={options} />;
|
||||
}
|
||||
7
apps/web/src/components/charts/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export { PlaysChart } from './PlaysChart';
|
||||
export { PlatformChart } from './PlatformChart';
|
||||
export { DayOfWeekChart } from './DayOfWeekChart';
|
||||
export { HourOfDayChart } from './HourOfDayChart';
|
||||
export { QualityChart } from './QualityChart';
|
||||
export { TopListChart } from './TopListChart';
|
||||
export { ConcurrentChart } from './ConcurrentChart';
|
||||
48
apps/web/src/components/icons/MediaServerIcon.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { Server } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// Import server type from shared
|
||||
import type { ServerType } from '@tracearr/shared';
|
||||
|
||||
interface MediaServerIconProps {
|
||||
/** Server type: 'plex', 'jellyfin', or 'emby' */
|
||||
type: ServerType;
|
||||
/** CSS class name for sizing (e.g., "h-4 w-4") */
|
||||
className?: string;
|
||||
/** Alt text for accessibility */
|
||||
alt?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the appropriate icon for a media server type.
|
||||
* Falls back to generic Server icon if type is unknown.
|
||||
*/
|
||||
export function MediaServerIcon({ type, className, alt }: MediaServerIconProps) {
|
||||
const iconPath = getIconPath(type);
|
||||
|
||||
if (!iconPath) {
|
||||
// Fallback to generic server icon
|
||||
return <Server className={className} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
src={iconPath}
|
||||
alt={alt ?? `${type} server`}
|
||||
className={cn('object-contain', className)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function getIconPath(type: ServerType): string | null {
|
||||
switch (type) {
|
||||
case 'plex':
|
||||
return '/images/servers/plex.png';
|
||||
case 'jellyfin':
|
||||
return '/images/servers/jellyfin.png';
|
||||
case 'emby':
|
||||
return '/images/servers/emby.png';
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
116
apps/web/src/components/layout/AppSidebar.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
import { NavLink, useLocation } from 'react-router';
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
useSidebar,
|
||||
} from '@/components/ui/sidebar';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import { Logo } from '@/components/brand/Logo';
|
||||
import { ServerSelector } from './ServerSelector';
|
||||
import { navigation, isNavGroup, type NavItem, type NavGroup } from './nav-data';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function NavMenuItem({ item }: { item: NavItem }) {
|
||||
const { setOpenMobile } = useSidebar();
|
||||
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild>
|
||||
<NavLink
|
||||
to={item.href}
|
||||
end={item.href === '/'}
|
||||
onClick={() => setOpenMobile(false)}
|
||||
className={({ isActive }) =>
|
||||
cn(isActive && 'bg-sidebar-accent text-sidebar-accent-foreground')
|
||||
}
|
||||
>
|
||||
<item.icon className="size-4" />
|
||||
<span>{item.name}</span>
|
||||
</NavLink>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
function NavMenuGroup({ group }: { group: NavGroup }) {
|
||||
const location = useLocation();
|
||||
const { setOpenMobile } = useSidebar();
|
||||
const isActive = group.children.some((child) =>
|
||||
location.pathname.startsWith(child.href)
|
||||
);
|
||||
|
||||
return (
|
||||
<Collapsible defaultOpen={isActive} className="group/collapsible">
|
||||
<SidebarMenuItem>
|
||||
<CollapsibleTrigger asChild>
|
||||
<SidebarMenuButton className={cn(isActive && 'font-medium')}>
|
||||
<group.icon className="size-4" />
|
||||
<span>{group.name}</span>
|
||||
<ChevronRight className="ml-auto size-4 transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
|
||||
</SidebarMenuButton>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<SidebarMenuSub>
|
||||
{group.children.map((child) => (
|
||||
<SidebarMenuSubItem key={child.href}>
|
||||
<SidebarMenuSubButton asChild>
|
||||
<NavLink
|
||||
to={child.href}
|
||||
onClick={() => setOpenMobile(false)}
|
||||
className={({ isActive }) =>
|
||||
cn(isActive && 'bg-sidebar-accent text-sidebar-accent-foreground')
|
||||
}
|
||||
>
|
||||
<child.icon className="size-4" />
|
||||
<span>{child.name}</span>
|
||||
</NavLink>
|
||||
</SidebarMenuSubButton>
|
||||
</SidebarMenuSubItem>
|
||||
))}
|
||||
</SidebarMenuSub>
|
||||
</CollapsibleContent>
|
||||
</SidebarMenuItem>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
export function AppSidebar() {
|
||||
return (
|
||||
<Sidebar>
|
||||
<SidebarHeader className="border-b p-0">
|
||||
<div className="flex h-14 items-center px-4">
|
||||
<Logo size="md" />
|
||||
</div>
|
||||
<ServerSelector />
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
<SidebarGroup>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{navigation.map((entry) => {
|
||||
if (isNavGroup(entry)) {
|
||||
return <NavMenuGroup key={entry.name} group={entry} />;
|
||||
}
|
||||
return <NavMenuItem key={entry.href} item={entry} />;
|
||||
})}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
76
apps/web/src/components/layout/Header.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { LogOut, Settings } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { ModeToggle } from '@/components/ui/mode-toggle';
|
||||
import { SidebarTrigger } from '@/components/ui/sidebar';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
|
||||
export function Header() {
|
||||
const { user, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleLogout = async () => {
|
||||
await logout();
|
||||
};
|
||||
|
||||
const initials = user?.username
|
||||
? user.username.slice(0, 2).toUpperCase()
|
||||
: 'U';
|
||||
|
||||
return (
|
||||
<header className="flex h-16 shrink-0 items-center gap-2 border-b px-4">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="mr-2 h-4" />
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<ModeToggle />
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="rounded-full">
|
||||
<Avatar className="h-8 w-8">
|
||||
{user?.thumbUrl && (
|
||||
<AvatarImage src={user.thumbUrl} alt={user.username} />
|
||||
)}
|
||||
<AvatarFallback className="bg-primary/10 text-primary text-xs">
|
||||
{initials}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<DropdownMenuLabel>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-sm font-medium">{user?.username}</p>
|
||||
{user?.email && (
|
||||
<p className="text-xs text-muted-foreground">{user.email}</p>
|
||||
)}
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => navigate('/settings')}>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout} className="text-destructive focus:text-destructive">
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Sign out
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
21
apps/web/src/components/layout/Layout.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Outlet } from 'react-router';
|
||||
import { SidebarProvider, SidebarInset } from '@/components/ui/sidebar';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { AppSidebar } from './AppSidebar';
|
||||
import { Header } from './Header';
|
||||
|
||||
export function Layout() {
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppSidebar />
|
||||
<SidebarInset>
|
||||
<Header />
|
||||
<ScrollArea className="flex-1">
|
||||
<main className="p-6">
|
||||
<Outlet />
|
||||
</main>
|
||||
</ScrollArea>
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
59
apps/web/src/components/layout/ServerSelector.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import { useServer } from '@/hooks/useServer';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { MediaServerIcon } from '@/components/icons/MediaServerIcon';
|
||||
|
||||
export function ServerSelector() {
|
||||
const { servers, selectedServerId, selectServer, isLoading, isFetching } = useServer();
|
||||
|
||||
// Show skeleton while loading initially or refetching with no cached data
|
||||
if (isLoading || (servers.length === 0 && isFetching)) {
|
||||
return (
|
||||
<div className="px-4 py-2">
|
||||
<Skeleton className="h-9 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// No servers available
|
||||
if (servers.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only show selector if there are multiple servers
|
||||
if (servers.length === 1) {
|
||||
const server = servers[0]!;
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-4 py-2 text-sm text-muted-foreground">
|
||||
<MediaServerIcon type={server.type} className="h-4 w-4" />
|
||||
<span className="truncate font-medium">{server.name}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 py-2">
|
||||
<Select value={selectedServerId ?? undefined} onValueChange={selectServer}>
|
||||
<SelectTrigger className="h-9 w-full">
|
||||
<SelectValue placeholder="Select server" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{servers.map((server) => (
|
||||
<SelectItem key={server.id} value={server.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
<MediaServerIcon type={server.type} className="h-4 w-4 shrink-0" />
|
||||
<span className="truncate">{server.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
48
apps/web/src/components/layout/nav-data.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Map,
|
||||
BarChart3,
|
||||
Users,
|
||||
Shield,
|
||||
AlertTriangle,
|
||||
Settings,
|
||||
TrendingUp,
|
||||
Film,
|
||||
UserCircle,
|
||||
} from 'lucide-react';
|
||||
|
||||
export interface NavItem {
|
||||
name: string;
|
||||
href: string;
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
}
|
||||
|
||||
export interface NavGroup {
|
||||
name: string;
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
children: NavItem[];
|
||||
}
|
||||
|
||||
export type NavEntry = NavItem | NavGroup;
|
||||
|
||||
export function isNavGroup(entry: NavEntry): entry is NavGroup {
|
||||
return 'children' in entry;
|
||||
}
|
||||
|
||||
export const navigation: NavEntry[] = [
|
||||
{ name: 'Dashboard', href: '/', icon: LayoutDashboard },
|
||||
{ name: 'Map', href: '/map', icon: Map },
|
||||
{
|
||||
name: 'Stats',
|
||||
icon: BarChart3,
|
||||
children: [
|
||||
{ name: 'Activity', href: '/stats/activity', icon: TrendingUp },
|
||||
{ name: 'Library', href: '/stats/library', icon: Film },
|
||||
{ name: 'Users', href: '/stats/users', icon: UserCircle },
|
||||
],
|
||||
},
|
||||
{ name: 'Users', href: '/users', icon: Users },
|
||||
{ name: 'Rules', href: '/rules', icon: Shield },
|
||||
{ name: 'Violations', href: '/violations', icon: AlertTriangle },
|
||||
{ name: 'Settings', href: '/settings', icon: Settings },
|
||||
];
|
||||
299
apps/web/src/components/map/StreamCard.tsx
Normal file
@@ -0,0 +1,299 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { MapContainer, TileLayer, Marker, Popup, useMap } from 'react-leaflet';
|
||||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import type { ActiveSession, LocationStats } from '@tracearr/shared';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ActiveSessionBadge } from '@/components/sessions/ActiveSessionBadge';
|
||||
import { useTheme } from '@/components/theme-provider';
|
||||
import { User, MapPin } from 'lucide-react';
|
||||
import { getAvatarUrl } from '@/components/users/utils';
|
||||
|
||||
// Fix for default marker icons in Leaflet with bundlers
|
||||
delete (L.Icon.Default.prototype as { _getIconUrl?: () => void })._getIconUrl;
|
||||
L.Icon.Default.mergeOptions({
|
||||
iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
|
||||
iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
|
||||
shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
|
||||
});
|
||||
|
||||
// Custom marker icon for active sessions
|
||||
const activeSessionIcon = L.divIcon({
|
||||
className: 'stream-marker',
|
||||
html: `<div class="relative">
|
||||
<div class="absolute -inset-1 animate-ping rounded-full bg-green-500/50"></div>
|
||||
<div class="relative h-4 w-4 rounded-full bg-green-500 border-2 border-white shadow-lg"></div>
|
||||
</div>`,
|
||||
iconSize: [16, 16],
|
||||
iconAnchor: [8, 8],
|
||||
popupAnchor: [0, -10],
|
||||
});
|
||||
|
||||
// Location marker icon
|
||||
const locationIcon = L.divIcon({
|
||||
className: 'location-marker',
|
||||
html: `<div class="h-3 w-3 rounded-full bg-blue-500 border-2 border-white shadow-md"></div>`,
|
||||
iconSize: [12, 12],
|
||||
iconAnchor: [6, 6],
|
||||
popupAnchor: [0, -8],
|
||||
});
|
||||
|
||||
// Format media title based on type
|
||||
function formatMediaTitle(session: ActiveSession): { primary: string; secondary: string | null } {
|
||||
const { mediaType, mediaTitle, grandparentTitle, seasonNumber, episodeNumber, year } = session;
|
||||
|
||||
if (mediaType === 'episode' && grandparentTitle) {
|
||||
const seasonEp = seasonNumber && episodeNumber
|
||||
? `S${String(seasonNumber).padStart(2, '0')}E${String(episodeNumber).padStart(2, '0')}`
|
||||
: null;
|
||||
return {
|
||||
primary: grandparentTitle,
|
||||
secondary: seasonEp ? `${seasonEp} · ${mediaTitle}` : mediaTitle,
|
||||
};
|
||||
}
|
||||
|
||||
if (mediaType === 'movie') {
|
||||
return { primary: mediaTitle, secondary: year ? `${year}` : null };
|
||||
}
|
||||
|
||||
return { primary: mediaTitle, secondary: null };
|
||||
}
|
||||
|
||||
// Custom styles for popup and z-index fixes
|
||||
const popupStyles = `
|
||||
/* Ensure map container doesn't overlap sidebars/modals */
|
||||
.leaflet-container {
|
||||
z-index: 0 !important;
|
||||
}
|
||||
.leaflet-pane {
|
||||
z-index: 1 !important;
|
||||
}
|
||||
.leaflet-tile-pane {
|
||||
z-index: 1 !important;
|
||||
}
|
||||
.leaflet-overlay-pane {
|
||||
z-index: 2 !important;
|
||||
}
|
||||
.leaflet-marker-pane {
|
||||
z-index: 3 !important;
|
||||
}
|
||||
.leaflet-tooltip-pane {
|
||||
z-index: 4 !important;
|
||||
}
|
||||
.leaflet-popup-pane {
|
||||
z-index: 5 !important;
|
||||
}
|
||||
.leaflet-control {
|
||||
z-index: 10 !important;
|
||||
}
|
||||
.leaflet-popup-content-wrapper {
|
||||
background: hsl(var(--card));
|
||||
border: 1px solid hsl(var(--border));
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.4);
|
||||
padding: 0;
|
||||
}
|
||||
.leaflet-popup-content {
|
||||
margin: 0 !important;
|
||||
min-width: 220px;
|
||||
max-width: 280px;
|
||||
}
|
||||
.leaflet-popup-tip {
|
||||
background: hsl(var(--card));
|
||||
border: 1px solid hsl(var(--border));
|
||||
border-top: none;
|
||||
border-right: none;
|
||||
}
|
||||
.leaflet-popup-close-button {
|
||||
color: hsl(var(--muted-foreground)) !important;
|
||||
font-size: 18px !important;
|
||||
padding: 4px 8px !important;
|
||||
}
|
||||
.leaflet-popup-close-button:hover {
|
||||
color: hsl(var(--foreground)) !important;
|
||||
}
|
||||
`;
|
||||
|
||||
interface StreamCardProps {
|
||||
sessions?: ActiveSession[];
|
||||
locations?: LocationStats[];
|
||||
className?: string;
|
||||
height?: number | string;
|
||||
}
|
||||
|
||||
// Component to fit bounds when data changes
|
||||
function MapBoundsUpdater({
|
||||
sessions,
|
||||
locations,
|
||||
}: {
|
||||
sessions?: ActiveSession[];
|
||||
locations?: LocationStats[];
|
||||
}) {
|
||||
const map = useMap();
|
||||
|
||||
useEffect(() => {
|
||||
const points: [number, number][] = [];
|
||||
|
||||
sessions?.forEach((s) => {
|
||||
if (s.geoLat && s.geoLon) {
|
||||
points.push([s.geoLat, s.geoLon]);
|
||||
}
|
||||
});
|
||||
|
||||
locations?.forEach((l) => {
|
||||
if (l.lat && l.lon) {
|
||||
points.push([l.lat, l.lon]);
|
||||
}
|
||||
});
|
||||
|
||||
if (points.length > 0) {
|
||||
const bounds = L.latLngBounds(points);
|
||||
map.fitBounds(bounds, { padding: [50, 50], maxZoom: 10 });
|
||||
}
|
||||
}, [sessions, locations, map]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Map tile URLs for different themes
|
||||
const TILE_URLS = {
|
||||
dark: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',
|
||||
light: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',
|
||||
};
|
||||
|
||||
export function StreamCard({
|
||||
sessions,
|
||||
locations,
|
||||
className,
|
||||
height = 300,
|
||||
}: StreamCardProps) {
|
||||
const hasData =
|
||||
(sessions?.some((s) => s.geoLat && s.geoLon)) ||
|
||||
(locations?.some((l) => l.lat && l.lon));
|
||||
const { theme } = useTheme();
|
||||
const resolvedTheme = theme === 'system'
|
||||
? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
|
||||
: theme;
|
||||
const tileUrl = TILE_URLS[resolvedTheme];
|
||||
|
||||
return (
|
||||
<div className={cn('relative overflow-hidden rounded-lg', className)} style={{ height }}>
|
||||
<style>{popupStyles}</style>
|
||||
<MapContainer
|
||||
center={[20, 0]}
|
||||
zoom={2}
|
||||
className="h-full w-full"
|
||||
scrollWheelZoom={true}
|
||||
zoomControl={true}
|
||||
>
|
||||
<TileLayer
|
||||
key={resolvedTheme}
|
||||
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
|
||||
url={tileUrl}
|
||||
/>
|
||||
|
||||
<MapBoundsUpdater sessions={sessions} locations={locations} />
|
||||
|
||||
{/* Active session markers */}
|
||||
{sessions?.map((session) => {
|
||||
if (!session.geoLat || !session.geoLon) return null;
|
||||
|
||||
const avatarUrl = getAvatarUrl(session.serverId, session.user.thumbUrl, 32);
|
||||
const { primary: mediaTitle, secondary: mediaSubtitle } = formatMediaTitle(session);
|
||||
|
||||
return (
|
||||
<Marker
|
||||
key={session.id}
|
||||
position={[session.geoLat, session.geoLon]}
|
||||
icon={activeSessionIcon}
|
||||
>
|
||||
<Popup>
|
||||
<div className="p-2.5 text-foreground min-w-[180px]">
|
||||
{/* Media title */}
|
||||
<h4 className="font-semibold text-sm leading-snug">{mediaTitle}</h4>
|
||||
|
||||
{/* Subtitle + status on same line */}
|
||||
<div className="flex items-center gap-2 mt-0.5">
|
||||
{mediaSubtitle && (
|
||||
<span className="text-xs text-muted-foreground truncate">{mediaSubtitle}</span>
|
||||
)}
|
||||
<ActiveSessionBadge state={session.state} className="text-[10px] px-1.5 py-0" />
|
||||
</div>
|
||||
|
||||
{/* User - clickable */}
|
||||
<Link
|
||||
to={`/users/${session.user.id}`}
|
||||
className="flex items-center gap-2 mt-2 py-1 transition-opacity hover:opacity-80"
|
||||
>
|
||||
<div className="flex h-5 w-5 items-center justify-center rounded-full bg-muted overflow-hidden flex-shrink-0">
|
||||
{avatarUrl ? (
|
||||
<img src={avatarUrl} alt={session.user.username} className="h-5 w-5 object-cover" />
|
||||
) : (
|
||||
<User className="h-3 w-3 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs font-medium">
|
||||
{session.user.identityName ?? session.user.username}
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
{/* Meta info */}
|
||||
<div className="flex items-center gap-2 mt-1 text-[11px] text-muted-foreground">
|
||||
{(session.geoCity || session.geoCountry) && (
|
||||
<>
|
||||
<MapPin className="h-3 w-3 flex-shrink-0" />
|
||||
<span className="truncate">{session.geoCity || session.geoCountry}</span>
|
||||
</>
|
||||
)}
|
||||
{(session.product || session.platform) && (
|
||||
<>
|
||||
<span className="text-border">·</span>
|
||||
<span className="truncate">{session.product || session.platform}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Popup>
|
||||
</Marker>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Location stats markers */}
|
||||
{locations?.map((location, idx) => {
|
||||
if (!location.lat || !location.lon) return null;
|
||||
|
||||
return (
|
||||
<Marker
|
||||
key={`${location.city}-${location.country}-${idx}`}
|
||||
position={[location.lat, location.lon]}
|
||||
icon={locationIcon}
|
||||
>
|
||||
<Popup>
|
||||
<div className="p-3 text-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<MapPin className="h-4 w-4 text-blue-500" />
|
||||
<div>
|
||||
<p className="font-semibold">{location.city || 'Unknown'}</p>
|
||||
<p className="text-xs text-muted-foreground">{location.country}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 flex items-center justify-between text-sm border-t border-border pt-2">
|
||||
<span className="text-muted-foreground">Total streams</span>
|
||||
<span className="font-medium">{location.count}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Popup>
|
||||
</Marker>
|
||||
);
|
||||
})}
|
||||
</MapContainer>
|
||||
|
||||
{!hasData && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/50">
|
||||
<p className="text-sm text-muted-foreground">No location data available</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
233
apps/web/src/components/map/StreamMap.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { MapContainer, TileLayer, useMap, ZoomControl, CircleMarker, Popup } from 'react-leaflet';
|
||||
import { HeatmapLayer } from 'react-leaflet-heatmap-layer-v3';
|
||||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import type { LocationStats } from '@tracearr/shared';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useTheme } from '@/components/theme-provider';
|
||||
|
||||
export type MapViewMode = 'heatmap' | 'circles';
|
||||
|
||||
// Custom styles for dark theme, zoom control, and z-index fixes
|
||||
const mapStyles = `
|
||||
/* Ensure map container doesn't overlap sidebars/modals */
|
||||
.leaflet-container {
|
||||
z-index: 0 !important;
|
||||
}
|
||||
.leaflet-pane {
|
||||
z-index: 1 !important;
|
||||
}
|
||||
.leaflet-tile-pane {
|
||||
z-index: 1 !important;
|
||||
}
|
||||
.leaflet-overlay-pane {
|
||||
z-index: 2 !important;
|
||||
}
|
||||
.leaflet-marker-pane {
|
||||
z-index: 3 !important;
|
||||
}
|
||||
.leaflet-tooltip-pane {
|
||||
z-index: 4 !important;
|
||||
}
|
||||
.leaflet-popup-pane {
|
||||
z-index: 5 !important;
|
||||
}
|
||||
.leaflet-control {
|
||||
z-index: 10 !important;
|
||||
}
|
||||
.leaflet-control-zoom {
|
||||
border: 1px solid hsl(var(--border)) !important;
|
||||
border-radius: 0.5rem !important;
|
||||
overflow: hidden;
|
||||
}
|
||||
.leaflet-control-zoom a {
|
||||
background: hsl(var(--card)) !important;
|
||||
color: hsl(var(--foreground)) !important;
|
||||
border-bottom: 1px solid hsl(var(--border)) !important;
|
||||
}
|
||||
.leaflet-control-zoom a:hover {
|
||||
background: hsl(var(--muted)) !important;
|
||||
}
|
||||
.leaflet-control-zoom a:last-child {
|
||||
border-bottom: none !important;
|
||||
}
|
||||
`;
|
||||
|
||||
interface StreamMapProps {
|
||||
locations: LocationStats[];
|
||||
className?: string;
|
||||
isLoading?: boolean;
|
||||
viewMode?: MapViewMode;
|
||||
}
|
||||
|
||||
// Heatmap configuration optimized for streaming location data
|
||||
const HEATMAP_CONFIG = {
|
||||
// Gradient: dark cyan base → bright cyan → white hotspots
|
||||
// Designed for dark map tiles with good contrast
|
||||
gradient: {
|
||||
0.0: 'rgba(14, 116, 144, 0)', // cyan-700 transparent (fade from nothing)
|
||||
0.2: 'rgba(14, 116, 144, 0.8)', // cyan-700
|
||||
0.4: '#0891b2', // cyan-600
|
||||
0.6: '#06b6d4', // cyan-500
|
||||
0.8: '#22d3ee', // cyan-400
|
||||
0.95: '#67e8f9', // cyan-300
|
||||
1.0: '#ffffff', // white for hotspots
|
||||
},
|
||||
// Radius: larger for world view, heatmap auto-adjusts with zoom
|
||||
radius: 30,
|
||||
// Blur: soft edges for smooth transitions
|
||||
blur: 20,
|
||||
// minOpacity: ensure even low-activity areas are visible
|
||||
minOpacity: 0.4,
|
||||
// maxZoom: heatmap intensity calculation stops scaling at this zoom
|
||||
maxZoom: 12,
|
||||
};
|
||||
|
||||
// Circle markers layer component
|
||||
function CircleMarkersLayer({ locations }: { locations: LocationStats[] }) {
|
||||
const maxCount = useMemo(() => Math.max(...locations.map((l) => l.count), 1), [locations]);
|
||||
|
||||
// Calculate radius based on count (scaled logarithmically)
|
||||
const getRadius = (count: number) => {
|
||||
const minRadius = 6;
|
||||
const maxRadius = 25;
|
||||
const scale = Math.log(count + 1) / Math.log(maxCount + 1);
|
||||
return minRadius + scale * (maxRadius - minRadius);
|
||||
};
|
||||
|
||||
// Get opacity based on count
|
||||
const getOpacity = (count: number) => {
|
||||
const minOpacity = 0.4;
|
||||
const maxOpacity = 0.8;
|
||||
const scale = count / maxCount;
|
||||
return minOpacity + scale * (maxOpacity - minOpacity);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{locations
|
||||
.filter((l) => l.lat && l.lon)
|
||||
.map((location, index) => (
|
||||
<CircleMarker
|
||||
key={`${location.lat}-${location.lon}-${index}`}
|
||||
center={[location.lat, location.lon]}
|
||||
radius={getRadius(location.count)}
|
||||
pathOptions={{
|
||||
color: '#06b6d4', // cyan-500
|
||||
fillColor: '#22d3ee', // cyan-400
|
||||
fillOpacity: getOpacity(location.count),
|
||||
weight: 1,
|
||||
}}
|
||||
>
|
||||
<Popup>
|
||||
<div className="text-sm">
|
||||
<div className="font-semibold">
|
||||
{location.city ? `${location.city}, ` : ''}
|
||||
{location.country || 'Unknown'}
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{location.count.toLocaleString()} stream{location.count !== 1 ? 's' : ''}
|
||||
</div>
|
||||
</div>
|
||||
</Popup>
|
||||
</CircleMarker>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Component to fit bounds when data changes
|
||||
function MapBoundsUpdater({ locations, isLoading }: { locations: LocationStats[]; isLoading?: boolean }) {
|
||||
const map = useMap();
|
||||
|
||||
useEffect(() => {
|
||||
// Don't update bounds while loading - prevents zoom reset during filter changes
|
||||
if (isLoading) return;
|
||||
|
||||
const points: [number, number][] = locations
|
||||
.filter((l) => l.lat && l.lon)
|
||||
.map((l) => [l.lat, l.lon]);
|
||||
|
||||
if (points.length > 0) {
|
||||
const bounds = L.latLngBounds(points);
|
||||
map.fitBounds(bounds, { padding: [50, 50], maxZoom: 8 });
|
||||
}
|
||||
// Note: Don't zoom out when no data - preserve current view during filter transitions
|
||||
}, [locations, map, isLoading]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Map tile URLs for different themes
|
||||
const TILE_URLS = {
|
||||
dark: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',
|
||||
light: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',
|
||||
};
|
||||
|
||||
export function StreamMap({ locations, className, isLoading, viewMode = 'heatmap' }: StreamMapProps) {
|
||||
const hasData = locations.length > 0;
|
||||
const { theme } = useTheme();
|
||||
const resolvedTheme = theme === 'system'
|
||||
? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
|
||||
: theme;
|
||||
const tileUrl = TILE_URLS[resolvedTheme];
|
||||
|
||||
return (
|
||||
<div className={cn('relative h-full w-full', className)}>
|
||||
<style>{mapStyles}</style>
|
||||
<MapContainer
|
||||
center={[20, 0]}
|
||||
zoom={2}
|
||||
className="h-full w-full"
|
||||
scrollWheelZoom={true}
|
||||
zoomControl={false}
|
||||
>
|
||||
<TileLayer
|
||||
key={resolvedTheme}
|
||||
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
|
||||
url={tileUrl}
|
||||
/>
|
||||
<ZoomControl position="bottomright" />
|
||||
|
||||
<MapBoundsUpdater locations={locations} isLoading={isLoading} />
|
||||
|
||||
{/* Visualization layer - heatmap or circles */}
|
||||
{hasData && viewMode === 'heatmap' && (
|
||||
<HeatmapLayer
|
||||
points={locations.filter((l) => l.lat && l.lon)}
|
||||
latitudeExtractor={(l: LocationStats) => l.lat}
|
||||
longitudeExtractor={(l: LocationStats) => l.lon}
|
||||
// Logarithmic intensity: prevents high-count locations from dominating
|
||||
intensityExtractor={(l: LocationStats) => Math.log10(l.count + 1)}
|
||||
gradient={HEATMAP_CONFIG.gradient}
|
||||
radius={HEATMAP_CONFIG.radius}
|
||||
blur={HEATMAP_CONFIG.blur}
|
||||
minOpacity={HEATMAP_CONFIG.minOpacity}
|
||||
maxZoom={HEATMAP_CONFIG.maxZoom}
|
||||
// Dynamic max based on log scale
|
||||
max={Math.log10(Math.max(...locations.map((l) => l.count), 1) + 1)}
|
||||
/>
|
||||
)}
|
||||
{hasData && viewMode === 'circles' && <CircleMarkersLayer locations={locations} />}
|
||||
</MapContainer>
|
||||
|
||||
{/* Loading overlay */}
|
||||
{isLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/50 backdrop-blur-sm">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||
Loading map data...
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No data message */}
|
||||
{!isLoading && !hasData && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/50">
|
||||
<p className="text-sm text-muted-foreground">No location data for current filters</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
2
apps/web/src/components/map/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { StreamCard } from './StreamCard';
|
||||
export { StreamMap, type MapViewMode } from './StreamMap';
|
||||
128
apps/web/src/components/media/MediaCard.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
import { Film, Tv, Music } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface MediaCardProps {
|
||||
title: string;
|
||||
type: string;
|
||||
showTitle?: string | null;
|
||||
year?: number | null;
|
||||
playCount: number;
|
||||
watchTimeHours: number;
|
||||
thumbPath?: string | null;
|
||||
serverId?: string | null;
|
||||
rank?: number;
|
||||
className?: string;
|
||||
/** For TV shows (aggregated series), number of unique episodes watched */
|
||||
episodeCount?: number;
|
||||
}
|
||||
|
||||
function MediaIcon({ type, className }: { type: string; className?: string }) {
|
||||
switch (type) {
|
||||
case 'movie':
|
||||
return <Film className={className} />;
|
||||
case 'episode':
|
||||
return <Tv className={className} />;
|
||||
case 'track':
|
||||
return <Music className={className} />;
|
||||
default:
|
||||
return <Film className={className} />;
|
||||
}
|
||||
}
|
||||
|
||||
function getImageUrl(serverId: string | null | undefined, thumbPath: string | null | undefined, width = 300, height = 450) {
|
||||
if (!serverId || !thumbPath) return null;
|
||||
return `/api/v1/images/proxy?server=${serverId}&url=${encodeURIComponent(thumbPath)}&width=${width}&height=${height}&fallback=poster`;
|
||||
}
|
||||
|
||||
export function MediaCard({
|
||||
title,
|
||||
type,
|
||||
showTitle,
|
||||
year,
|
||||
playCount,
|
||||
watchTimeHours,
|
||||
thumbPath,
|
||||
serverId,
|
||||
rank,
|
||||
className,
|
||||
episodeCount,
|
||||
}: MediaCardProps) {
|
||||
const imageUrl = getImageUrl(serverId, thumbPath, 300, 450);
|
||||
const bgImageUrl = getImageUrl(serverId, thumbPath, 800, 400);
|
||||
// For individual episodes: showTitle is series name, title is episode name
|
||||
// For aggregated shows: title is series name (no showTitle), episodeCount indicates it's aggregated
|
||||
const displayTitle = type === 'episode' && showTitle ? showTitle : title;
|
||||
const subtitle = episodeCount
|
||||
? `${episodeCount} episodes • ${year || ''}`
|
||||
: type === 'episode'
|
||||
? title
|
||||
: year
|
||||
? `(${year})`
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group relative animate-fade-in-up overflow-hidden rounded-xl border bg-card transition-all duration-300 hover:shadow-lg hover:shadow-primary/10',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{/* Background with blur */}
|
||||
<div
|
||||
className="absolute inset-0 bg-cover bg-center opacity-30 blur-xl transition-opacity group-hover:opacity-40"
|
||||
style={{
|
||||
backgroundImage: bgImageUrl ? `url(${bgImageUrl})` : undefined,
|
||||
backgroundColor: bgImageUrl ? undefined : 'hsl(var(--muted))',
|
||||
}}
|
||||
/>
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-card via-card/80 to-transparent" />
|
||||
|
||||
{/* Content */}
|
||||
<div className="relative flex gap-4 p-4">
|
||||
{/* Poster */}
|
||||
<div className="relative h-36 w-24 shrink-0 overflow-hidden rounded-lg bg-muted shadow-lg transition-transform group-hover:scale-105">
|
||||
{imageUrl ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={displayTitle}
|
||||
className="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<MediaIcon type={type} className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{rank && (
|
||||
<div className="absolute -left-1 -top-1 flex h-7 w-7 items-center justify-center rounded-full bg-primary text-xs font-bold text-primary-foreground shadow-md">
|
||||
#{rank}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="flex flex-1 flex-col justify-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<MediaIcon type={type} className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
{type}
|
||||
</span>
|
||||
</div>
|
||||
<h3 className="mt-1 text-lg font-semibold leading-tight">{displayTitle}</h3>
|
||||
{subtitle && (
|
||||
<p className="text-sm text-muted-foreground">{subtitle}</p>
|
||||
)}
|
||||
<div className="mt-3 flex items-center gap-4 text-sm">
|
||||
<div>
|
||||
<span className="font-semibold text-primary">{playCount.toLocaleString()}</span>
|
||||
<span className="ml-1 text-muted-foreground">plays</span>
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{watchTimeHours.toLocaleString()}h watched
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
109
apps/web/src/components/media/MediaCardSmall.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import { Film, Tv, Music } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface MediaCardSmallProps {
|
||||
title: string;
|
||||
type: string;
|
||||
showTitle?: string | null;
|
||||
year?: number | null;
|
||||
playCount: number;
|
||||
thumbPath?: string | null;
|
||||
serverId?: string | null;
|
||||
rank?: number;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
/** For TV shows (aggregated series), number of unique episodes watched */
|
||||
episodeCount?: number;
|
||||
}
|
||||
|
||||
function MediaIcon({ type, className }: { type: string; className?: string }) {
|
||||
switch (type) {
|
||||
case 'movie':
|
||||
return <Film className={className} />;
|
||||
case 'episode':
|
||||
return <Tv className={className} />;
|
||||
case 'track':
|
||||
return <Music className={className} />;
|
||||
default:
|
||||
return <Film className={className} />;
|
||||
}
|
||||
}
|
||||
|
||||
function getImageUrl(serverId: string | null | undefined, thumbPath: string | null | undefined, width = 150, height = 225) {
|
||||
if (!serverId || !thumbPath) return null;
|
||||
return `/api/v1/images/proxy?server=${serverId}&url=${encodeURIComponent(thumbPath)}&width=${width}&height=${height}&fallback=poster`;
|
||||
}
|
||||
|
||||
export function MediaCardSmall({
|
||||
title,
|
||||
type,
|
||||
showTitle,
|
||||
year,
|
||||
playCount,
|
||||
thumbPath,
|
||||
serverId,
|
||||
rank,
|
||||
className,
|
||||
style,
|
||||
episodeCount,
|
||||
}: MediaCardSmallProps) {
|
||||
const imageUrl = getImageUrl(serverId, thumbPath);
|
||||
// For individual episodes: showTitle is series name, title is episode name
|
||||
// For aggregated shows: title is series name (no showTitle), episodeCount indicates it's aggregated
|
||||
const displayTitle = type === 'episode' && showTitle ? showTitle : title;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group relative animate-fade-in overflow-hidden rounded-lg border bg-card transition-all duration-300 hover:scale-[1.03] hover:border-primary/50 hover:shadow-lg hover:shadow-primary/10',
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
>
|
||||
{/* Poster */}
|
||||
<div className="relative aspect-[2/3] overflow-hidden bg-muted">
|
||||
{imageUrl ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={displayTitle}
|
||||
className="h-full w-full object-cover transition-transform group-hover:scale-105"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<MediaIcon type={type} className="h-12 w-12 text-muted-foreground/50" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rank badge */}
|
||||
{rank && (
|
||||
<div className="absolute left-2 top-2 flex h-6 w-6 items-center justify-center rounded-full bg-black/70 text-xs font-bold text-white">
|
||||
{rank}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Hover overlay with play count */}
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold text-white">{playCount}</div>
|
||||
<div className="text-xs text-white/80">plays</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="p-3">
|
||||
<h4 className="truncate text-sm font-medium" title={displayTitle}>
|
||||
{displayTitle}
|
||||
</h4>
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
{episodeCount
|
||||
? `${episodeCount} eps`
|
||||
: type === 'episode'
|
||||
? title
|
||||
: year || type}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
2
apps/web/src/components/media/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { MediaCard } from './MediaCard';
|
||||
export { MediaCardSmall } from './MediaCardSmall';
|
||||
30
apps/web/src/components/sessions/ActiveSessionBadge.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import type { SessionState } from '@tracearr/shared';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Play, Pause, Square } from 'lucide-react';
|
||||
|
||||
interface ActiveSessionBadgeProps {
|
||||
state: SessionState;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const stateConfig: Record<
|
||||
SessionState,
|
||||
{ variant: 'success' | 'warning' | 'secondary'; label: string; icon: typeof Play }
|
||||
> = {
|
||||
playing: { variant: 'success', label: 'Playing', icon: Play },
|
||||
paused: { variant: 'warning', label: 'Paused', icon: Pause },
|
||||
stopped: { variant: 'secondary', label: 'Stopped', icon: Square },
|
||||
};
|
||||
|
||||
export function ActiveSessionBadge({ state, className }: ActiveSessionBadgeProps) {
|
||||
const config = stateConfig[state];
|
||||
const Icon = config.icon;
|
||||
|
||||
return (
|
||||
<Badge variant={config.variant} className={cn('gap-1', className)}>
|
||||
<Icon className="h-3 w-3" />
|
||||
{config.label}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
253
apps/web/src/components/sessions/NowPlayingCard.tsx
Normal file
@@ -0,0 +1,253 @@
|
||||
import { useState } from 'react';
|
||||
import { Monitor, Smartphone, Tablet, Tv, Play, Pause, Zap, Server, X } from 'lucide-react';
|
||||
import { getAvatarUrl } from '@/components/users/utils';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useEstimatedProgress } from '@/hooks/useEstimatedProgress';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { TerminateSessionDialog } from './TerminateSessionDialog';
|
||||
import type { ActiveSession } from '@tracearr/shared';
|
||||
|
||||
interface NowPlayingCardProps {
|
||||
session: ActiveSession;
|
||||
}
|
||||
|
||||
// Get device icon based on platform/device info
|
||||
function DeviceIcon({ session, className }: { session: ActiveSession; className?: string }) {
|
||||
const platform = session.platform?.toLowerCase() ?? '';
|
||||
const device = session.device?.toLowerCase() ?? '';
|
||||
const product = session.product?.toLowerCase() ?? '';
|
||||
|
||||
if (platform.includes('ios') || device.includes('iphone') || platform.includes('android')) {
|
||||
return <Smartphone className={className} />;
|
||||
}
|
||||
if (device.includes('ipad') || platform.includes('tablet')) {
|
||||
return <Tablet className={className} />;
|
||||
}
|
||||
if (
|
||||
platform.includes('tv') ||
|
||||
device.includes('tv') ||
|
||||
product.includes('tv') ||
|
||||
device.includes('roku') ||
|
||||
device.includes('firestick') ||
|
||||
device.includes('chromecast') ||
|
||||
device.includes('apple tv') ||
|
||||
device.includes('shield')
|
||||
) {
|
||||
return <Tv className={className} />;
|
||||
}
|
||||
return <Monitor className={className} />;
|
||||
}
|
||||
|
||||
// Format duration for display
|
||||
function formatDuration(ms: number | null): string {
|
||||
if (!ms) return '--:--';
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
const secs = seconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
|
||||
}
|
||||
return `${minutes}:${secs.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// Get display title for media
|
||||
function getMediaDisplay(session: ActiveSession): { title: string; subtitle: string | null } {
|
||||
if (session.mediaType === 'episode' && session.grandparentTitle) {
|
||||
// TV Show episode
|
||||
const episodeInfo =
|
||||
session.seasonNumber && session.episodeNumber
|
||||
? `S${session.seasonNumber.toString().padStart(2, '0')}E${session.episodeNumber.toString().padStart(2, '0')}`
|
||||
: '';
|
||||
return {
|
||||
title: session.grandparentTitle,
|
||||
subtitle: episodeInfo ? `${episodeInfo} · ${session.mediaTitle}` : session.mediaTitle,
|
||||
};
|
||||
}
|
||||
// Movie or music
|
||||
return {
|
||||
title: session.mediaTitle,
|
||||
subtitle: session.year ? `${session.year}` : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function NowPlayingCard({ session }: NowPlayingCardProps) {
|
||||
const { title, subtitle } = getMediaDisplay(session);
|
||||
const { user } = useAuth();
|
||||
const [showTerminateDialog, setShowTerminateDialog] = useState(false);
|
||||
|
||||
// Only admin/owner can terminate sessions
|
||||
const canTerminate = user?.role === 'admin' || user?.role === 'owner';
|
||||
|
||||
// Use estimated progress for smooth updates between SSE/poll events
|
||||
const { estimatedProgressMs, progressPercent } = useEstimatedProgress(session);
|
||||
|
||||
// Time remaining based on estimated progress
|
||||
const remaining =
|
||||
session.totalDurationMs && estimatedProgressMs
|
||||
? session.totalDurationMs - estimatedProgressMs
|
||||
: null;
|
||||
|
||||
// Build poster URL using image proxy
|
||||
const posterUrl = session.thumbPath
|
||||
? `/api/v1/images/proxy?server=${session.serverId}&url=${encodeURIComponent(session.thumbPath)}&width=200&height=300`
|
||||
: null;
|
||||
|
||||
// User avatar URL (proxied for Jellyfin/Emby)
|
||||
const avatarUrl = getAvatarUrl(session.serverId, session.user.thumbUrl, 28) ?? undefined;
|
||||
|
||||
const isPaused = session.state === 'paused';
|
||||
|
||||
return (
|
||||
<div className="group relative animate-fade-in overflow-hidden rounded-xl border bg-card transition-all duration-300 hover:scale-[1.02] hover:shadow-lg hover:shadow-primary/10">
|
||||
{/* Background with poster blur */}
|
||||
{posterUrl && (
|
||||
<div
|
||||
className="absolute inset-0 bg-cover bg-center opacity-20 blur-xl"
|
||||
style={{ backgroundImage: `url(${posterUrl})` }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Content */}
|
||||
<div className="relative flex gap-4 p-4">
|
||||
{/* Poster */}
|
||||
<div className="relative h-28 w-20 flex-shrink-0 overflow-hidden rounded-lg bg-muted shadow-lg">
|
||||
{posterUrl ? (
|
||||
<img
|
||||
src={posterUrl}
|
||||
alt={title}
|
||||
className="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<Server className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Play/Pause indicator overlay */}
|
||||
<div
|
||||
className={cn(
|
||||
'absolute inset-0 flex items-center justify-center bg-black/50 transition-opacity',
|
||||
isPaused ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
)}
|
||||
>
|
||||
{isPaused ? (
|
||||
<Pause className="h-8 w-8 text-white" />
|
||||
) : (
|
||||
<Play className="h-8 w-8 text-white" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="flex min-w-0 flex-1 flex-col justify-between">
|
||||
{/* Top row: User and badges */}
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-7 w-7 border-2 border-background shadow">
|
||||
<AvatarImage src={avatarUrl} alt={session.user.username} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{session.user.username.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-sm font-medium">
|
||||
{session.user.identityName ?? session.user.username}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
{/* Quality badge */}
|
||||
<Badge
|
||||
variant={session.isTranscode ? 'secondary' : 'default'}
|
||||
className={cn(
|
||||
'text-xs',
|
||||
!session.isTranscode && 'bg-green-600 hover:bg-green-700'
|
||||
)}
|
||||
>
|
||||
{session.isTranscode ? (
|
||||
<>
|
||||
<Zap className="mr-1 h-3 w-3" />
|
||||
Transcode
|
||||
</>
|
||||
) : (
|
||||
'Direct'
|
||||
)}
|
||||
</Badge>
|
||||
|
||||
{/* Device icon */}
|
||||
<div className="flex h-6 w-6 items-center justify-center rounded-md bg-muted">
|
||||
<DeviceIcon session={session} className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
{/* Terminate button - admin/owner only */}
|
||||
{canTerminate && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setShowTerminateDialog(true);
|
||||
}}
|
||||
title="Terminate stream"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Middle: Title */}
|
||||
<div className="mt-2">
|
||||
<h3 className="truncate text-sm font-semibold leading-tight">{title}</h3>
|
||||
{subtitle && (
|
||||
<p className="mt-0.5 truncate text-xs text-muted-foreground">{subtitle}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Bottom: Progress */}
|
||||
<div className="mt-3 space-y-1">
|
||||
<Progress value={progressPercent} className="h-1.5" />
|
||||
<div className="flex justify-between text-[10px] text-muted-foreground">
|
||||
<span>{formatDuration(estimatedProgressMs)}</span>
|
||||
<span>
|
||||
{isPaused ? (
|
||||
<span className="font-medium text-yellow-500">Paused</span>
|
||||
) : remaining ? (
|
||||
`-${formatDuration(remaining)}`
|
||||
) : (
|
||||
formatDuration(session.totalDurationMs)
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Location/Quality footer */}
|
||||
<div className="relative flex items-center justify-between border-t bg-muted/50 px-4 py-2 text-xs text-muted-foreground">
|
||||
<span className="truncate">
|
||||
{session.geoCity && session.geoCountry
|
||||
? `${session.geoCity}, ${session.geoCountry}`
|
||||
: session.geoCountry ?? 'Unknown location'}
|
||||
</span>
|
||||
<span className="flex-shrink-0">{session.quality ?? 'Unknown quality'}</span>
|
||||
</div>
|
||||
|
||||
{/* Terminate confirmation dialog */}
|
||||
<TerminateSessionDialog
|
||||
open={showTerminateDialog}
|
||||
onOpenChange={setShowTerminateDialog}
|
||||
sessionId={session.id}
|
||||
mediaTitle={title}
|
||||
username={session.user.username}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
97
apps/web/src/components/sessions/TerminateSessionDialog.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useTerminateSession } from '@/hooks/queries';
|
||||
|
||||
interface TerminateSessionDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
sessionId: string;
|
||||
mediaTitle: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirmation dialog for terminating a streaming session
|
||||
* Includes optional reason field that is shown to the user
|
||||
*/
|
||||
export function TerminateSessionDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
sessionId,
|
||||
mediaTitle,
|
||||
username,
|
||||
}: TerminateSessionDialogProps) {
|
||||
const [reason, setReason] = useState('');
|
||||
const terminateSession = useTerminateSession();
|
||||
|
||||
const handleTerminate = () => {
|
||||
terminateSession.mutate(
|
||||
{ sessionId, reason: reason.trim() || undefined },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setReason('');
|
||||
onOpenChange(false);
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (!newOpen) {
|
||||
setReason('');
|
||||
}
|
||||
onOpenChange(newOpen);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Terminate Stream</DialogTitle>
|
||||
<DialogDescription>
|
||||
Stop “{mediaTitle}” for @{username}?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="reason">Message to user (optional)</Label>
|
||||
<Input
|
||||
id="reason"
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
placeholder="e.g., Please don't share your account"
|
||||
maxLength={500}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This message will be shown to them during playback
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={terminateSession.isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleTerminate}
|
||||
disabled={terminateSession.isPending}
|
||||
>
|
||||
{terminateSession.isPending ? 'Terminating...' : 'Kill Stream'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
1
apps/web/src/components/sessions/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { NowPlayingCard } from './NowPlayingCard';
|
||||
196
apps/web/src/components/settings/NotificationRoutingMatrix.tsx
Normal file
@@ -0,0 +1,196 @@
|
||||
import { Info } from 'lucide-react';
|
||||
import type { NotificationChannelRouting, NotificationEventType } from '@tracearr/shared';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import { useChannelRouting, useUpdateChannelRouting } from '@/hooks/queries';
|
||||
|
||||
// Display names and descriptions for event types
|
||||
const EVENT_CONFIG: Record<
|
||||
NotificationEventType,
|
||||
{ name: string; description: string }
|
||||
> = {
|
||||
violation_detected: {
|
||||
name: 'Rule Violation',
|
||||
description: 'A user triggered a rule violation (e.g., concurrent streams, impossible travel)',
|
||||
},
|
||||
new_device: {
|
||||
name: 'New Device',
|
||||
description: 'A user logged in from a new device for the first time',
|
||||
},
|
||||
trust_score_changed: {
|
||||
name: 'Trust Score Changed',
|
||||
description: "A user's trust score changed significantly",
|
||||
},
|
||||
stream_started: {
|
||||
name: 'Stream Started',
|
||||
description: 'A user started watching content',
|
||||
},
|
||||
stream_stopped: {
|
||||
name: 'Stream Stopped',
|
||||
description: 'A user stopped watching content',
|
||||
},
|
||||
concurrent_streams: {
|
||||
name: 'Concurrent Streams',
|
||||
description: 'Multiple streams detected from the same user',
|
||||
},
|
||||
server_down: {
|
||||
name: 'Server Offline',
|
||||
description: 'A media server became unreachable',
|
||||
},
|
||||
server_up: {
|
||||
name: 'Server Online',
|
||||
description: 'A media server came back online',
|
||||
},
|
||||
};
|
||||
|
||||
// Order of events in the table (security first, then streams, then server)
|
||||
const EVENT_ORDER: NotificationEventType[] = [
|
||||
'violation_detected',
|
||||
'new_device',
|
||||
'trust_score_changed',
|
||||
'stream_started',
|
||||
'stream_stopped',
|
||||
'concurrent_streams',
|
||||
'server_down',
|
||||
'server_up',
|
||||
];
|
||||
|
||||
interface NotificationRoutingMatrixProps {
|
||||
discordConfigured: boolean;
|
||||
webhookConfigured: boolean;
|
||||
}
|
||||
|
||||
export function NotificationRoutingMatrix({
|
||||
discordConfigured,
|
||||
webhookConfigured,
|
||||
}: NotificationRoutingMatrixProps) {
|
||||
const { data: routingData, isLoading } = useChannelRouting();
|
||||
const updateRouting = useUpdateChannelRouting();
|
||||
|
||||
// Build a map for quick lookup
|
||||
const routingMap = new Map<NotificationEventType, NotificationChannelRouting>();
|
||||
routingData?.forEach((r) => routingMap.set(r.eventType, r));
|
||||
|
||||
const handleToggle = (
|
||||
eventType: NotificationEventType,
|
||||
channel: 'discord' | 'webhook' | 'webToast',
|
||||
checked: boolean
|
||||
) => {
|
||||
updateRouting.mutate({
|
||||
eventType,
|
||||
...(channel === 'discord' && { discordEnabled: checked }),
|
||||
...(channel === 'webhook' && { webhookEnabled: checked }),
|
||||
...(channel === 'webToast' && { webToastEnabled: checked }),
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{EVENT_ORDER.map((eventType) => (
|
||||
<Skeleton key={eventType} className="h-10 w-full" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className="space-y-4">
|
||||
{/* Table */}
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/50">
|
||||
<TableRow>
|
||||
<TableHead className="py-3 px-4">Event</TableHead>
|
||||
<TableHead className="text-center py-3 px-4 w-24">Web</TableHead>
|
||||
{discordConfigured && (
|
||||
<TableHead className="text-center py-3 px-4 w-24">Discord</TableHead>
|
||||
)}
|
||||
{webhookConfigured && (
|
||||
<TableHead className="text-center py-3 px-4 w-24">Webhook</TableHead>
|
||||
)}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{EVENT_ORDER.map((eventType) => {
|
||||
const routing = routingMap.get(eventType);
|
||||
const config = EVENT_CONFIG[eventType];
|
||||
|
||||
return (
|
||||
<TableRow key={eventType}>
|
||||
<TableCell className="py-3 px-4">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="text-sm cursor-help border-b border-dotted border-muted-foreground/50">
|
||||
{config.name}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" className="max-w-xs">
|
||||
<p>{config.description}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TableCell>
|
||||
<TableCell className="py-3 px-4 text-center">
|
||||
<Checkbox
|
||||
checked={routing?.webToastEnabled ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
handleToggle(eventType, 'webToast', checked === true)
|
||||
}
|
||||
disabled={updateRouting.isPending}
|
||||
/>
|
||||
</TableCell>
|
||||
{discordConfigured && (
|
||||
<TableCell className="py-3 px-4 text-center">
|
||||
<Checkbox
|
||||
checked={routing?.discordEnabled ?? false}
|
||||
onCheckedChange={(checked) =>
|
||||
handleToggle(eventType, 'discord', checked === true)
|
||||
}
|
||||
disabled={updateRouting.isPending}
|
||||
/>
|
||||
</TableCell>
|
||||
)}
|
||||
{webhookConfigured && (
|
||||
<TableCell className="py-3 px-4 text-center">
|
||||
<Checkbox
|
||||
checked={routing?.webhookEnabled ?? false}
|
||||
onCheckedChange={(checked) =>
|
||||
handleToggle(eventType, 'webhook', checked === true)
|
||||
}
|
||||
disabled={updateRouting.isPending}
|
||||
/>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{/* Info about notification channels */}
|
||||
<div className="flex items-start gap-2 text-sm text-muted-foreground">
|
||||
<Info className="h-4 w-4 mt-0.5 shrink-0" />
|
||||
<span>
|
||||
<strong>Web</strong> shows toast notifications in this browser. Push notifications are configured per-device in the mobile app.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
67
apps/web/src/components/theme-provider.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
type Theme = 'dark' | 'light' | 'system';
|
||||
|
||||
interface ThemeProviderProps {
|
||||
children: React.ReactNode;
|
||||
defaultTheme?: Theme;
|
||||
storageKey?: string;
|
||||
}
|
||||
|
||||
interface ThemeProviderState {
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
}
|
||||
|
||||
const initialState: ThemeProviderState = {
|
||||
theme: 'system',
|
||||
setTheme: () => null,
|
||||
};
|
||||
|
||||
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
defaultTheme = 'dark',
|
||||
storageKey = 'tracearr-theme',
|
||||
...props
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setTheme] = useState<Theme>(
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
root.classList.remove('light', 'dark');
|
||||
|
||||
if (theme === 'system') {
|
||||
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
root.classList.add(systemTheme);
|
||||
return;
|
||||
}
|
||||
|
||||
root.classList.add(theme);
|
||||
}, [theme]);
|
||||
|
||||
const value = {
|
||||
theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
localStorage.setItem(storageKey, theme);
|
||||
setTheme(theme);
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider {...props} value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeProviderContext);
|
||||
if (context === undefined) throw new Error('useTheme must be used within a ThemeProvider');
|
||||
return context;
|
||||
};
|
||||
157
apps/web/src/components/ui/alert-dialog.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function AlertDialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
data-slot="alert-dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn("text-lg font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Action
|
||||
className={cn(buttonVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
className={cn(buttonVariants({ variant: "outline" }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
}
|
||||
58
apps/web/src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const alertVariants = cva(
|
||||
'relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-background text-foreground',
|
||||
destructive:
|
||||
'border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const Alert = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
|
||||
>(({ className, variant, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
role="alert"
|
||||
className={cn(alertVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Alert.displayName = 'Alert';
|
||||
|
||||
const AlertTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h5
|
||||
ref={ref}
|
||||
className={cn('mb-1 font-medium leading-none tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertTitle.displayName = 'AlertTitle';
|
||||
|
||||
const AlertDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('text-sm [&_p]:leading-relaxed', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDescription.displayName = 'AlertDescription';
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription };
|
||||
48
apps/web/src/components/ui/avatar.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import * as React from "react"
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Avatar = React.forwardRef<
|
||||
React.ComponentRef<typeof AvatarPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AvatarPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Avatar.displayName = AvatarPrimitive.Root.displayName
|
||||
|
||||
const AvatarImage = React.forwardRef<
|
||||
React.ComponentRef<typeof AvatarPrimitive.Image>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AvatarPrimitive.Image
|
||||
ref={ref}
|
||||
className={cn("aspect-square h-full w-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AvatarImage.displayName = AvatarPrimitive.Image.displayName
|
||||
|
||||
const AvatarFallback = React.forwardRef<
|
||||
React.ComponentRef<typeof AvatarPrimitive.Fallback>,
|
||||
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AvatarPrimitive.Fallback
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full items-center justify-center rounded-full bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
|
||||
|
||||
export { Avatar, AvatarImage, AvatarFallback }
|
||||
35
apps/web/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary text-primary-foreground',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground',
|
||||
destructive: 'border-transparent bg-destructive text-destructive-foreground',
|
||||
outline: 'text-foreground',
|
||||
success: 'border-transparent bg-green-500/15 text-green-600 dark:text-green-400',
|
||||
warning: 'border-transparent bg-yellow-500/15 text-yellow-600 dark:text-yellow-400',
|
||||
danger: 'border-transparent bg-red-500/15 text-red-600 dark:text-red-400',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return (
|
||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
60
apps/web/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 dark:hover:text-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50 dark:hover:text-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
216
apps/web/src/components/ui/calendar.tsx
Normal file
@@ -0,0 +1,216 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import { DayPicker, getDefaultClassNames, type DayButton } from "react-day-picker"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) =>
|
||||
date.toLocaleString("default", { month: "short" }),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"flex gap-4 flex-col md:flex-row relative",
|
||||
defaultClassNames.months
|
||||
),
|
||||
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute bg-popover inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
|
||||
defaultClassNames.weekday
|
||||
),
|
||||
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"select-none w-(--cell-size)",
|
||||
defaultClassNames.week_number_header
|
||||
),
|
||||
week_number: cn(
|
||||
"text-[0.8rem] select-none text-muted-foreground",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"relative w-full h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
|
||||
props.showWeekNumber
|
||||
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
|
||||
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"rounded-l-md bg-accent",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return (
|
||||
<div
|
||||
data-slot="calendar"
|
||||
ref={rootRef as React.Ref<HTMLDivElement>}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return (
|
||||
<ChevronRightIcon
|
||||
className={cn("size-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
className,
|
||||
day,
|
||||
modifiers,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toLocaleDateString()}
|
||||
data-selected-single={
|
||||
modifiers.selected &&
|
||||
!modifiers.range_start &&
|
||||
!modifiers.range_end &&
|
||||
!modifiers.range_middle
|
||||
}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
55
apps/web/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('rounded-lg border bg-card text-card-foreground shadow-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
Card.displayName = 'Card';
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardHeader.displayName = 'CardHeader';
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn('text-2xl font-semibold leading-none tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
CardTitle.displayName = 'CardTitle';
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
CardDescription.displayName = 'CardDescription';
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardContent.displayName = 'CardContent';
|
||||
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardFooter.displayName = 'CardFooter';
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
|
||||
30
apps/web/src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
31
apps/web/src/components/ui/collapsible.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleTrigger
|
||||
data-slot="collapsible-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleContent
|
||||
data-slot="collapsible-content"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
59
apps/web/src/components/ui/confirm-dialog.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
|
||||
interface ConfirmDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
description: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
onConfirm: () => void;
|
||||
isLoading?: boolean;
|
||||
variant?: 'destructive' | 'default';
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
confirmLabel = 'Confirm',
|
||||
cancelLabel = 'Cancel',
|
||||
onConfirm,
|
||||
isLoading = false,
|
||||
variant = 'destructive',
|
||||
}: ConfirmDialogProps) {
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{description}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{cancelLabel}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={onConfirm}
|
||||
disabled={isLoading}
|
||||
className={
|
||||
variant === 'destructive'
|
||||
? 'bg-destructive text-destructive-foreground hover:bg-destructive/90'
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{isLoading ? `${confirmLabel.replace(/e$/, '')}ing...` : confirmLabel}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
225
apps/web/src/components/ui/data-table.tsx
Normal file
@@ -0,0 +1,225 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import {
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
getPaginationRowModel,
|
||||
getFilteredRowModel,
|
||||
useReactTable,
|
||||
type ColumnDef,
|
||||
type SortingState,
|
||||
type PaginationState,
|
||||
type FilterFn,
|
||||
} from '@tanstack/react-table';
|
||||
import { ChevronDown, ChevronUp, ChevronsUpDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[];
|
||||
data: TData[];
|
||||
pageSize?: number;
|
||||
onRowClick?: (row: TData) => void;
|
||||
emptyMessage?: string;
|
||||
className?: string;
|
||||
// Server-side pagination props
|
||||
pageCount?: number;
|
||||
page?: number;
|
||||
onPageChange?: (page: number) => void;
|
||||
isLoading?: boolean;
|
||||
// Filtering props
|
||||
filterColumn?: string;
|
||||
filterValue?: string;
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
columns,
|
||||
data,
|
||||
pageSize = 10,
|
||||
onRowClick,
|
||||
emptyMessage = 'No results found.',
|
||||
className,
|
||||
pageCount,
|
||||
page,
|
||||
onPageChange,
|
||||
isLoading,
|
||||
filterColumn,
|
||||
filterValue,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: page ? page - 1 : 0,
|
||||
pageSize,
|
||||
});
|
||||
|
||||
const isServerPaginated = pageCount !== undefined && onPageChange !== undefined;
|
||||
|
||||
// Custom filter function that searches in the specified column
|
||||
const globalFilterFn: FilterFn<TData> = useMemo(() => {
|
||||
return (row, _columnId, filterValue: string) => {
|
||||
if (!filterColumn || !filterValue) return true;
|
||||
const cellValue = row.getValue(filterColumn);
|
||||
if (cellValue == null) return false;
|
||||
return String(cellValue).toLowerCase().includes(filterValue.toLowerCase());
|
||||
};
|
||||
}, [filterColumn]);
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getPaginationRowModel: isServerPaginated ? undefined : getPaginationRowModel(),
|
||||
globalFilterFn,
|
||||
onSortingChange: setSorting,
|
||||
onPaginationChange: setPagination,
|
||||
manualPagination: isServerPaginated,
|
||||
pageCount: isServerPaginated ? pageCount : undefined,
|
||||
state: {
|
||||
sorting,
|
||||
globalFilter: filterValue ?? '',
|
||||
pagination: isServerPaginated ? { pageIndex: (page ?? 1) - 1, pageSize } : pagination,
|
||||
},
|
||||
});
|
||||
|
||||
const handlePageChange = (newPage: number) => {
|
||||
if (isServerPaginated && onPageChange) {
|
||||
onPageChange(newPage);
|
||||
}
|
||||
};
|
||||
|
||||
const currentPage = isServerPaginated ? page : pagination.pageIndex + 1;
|
||||
const totalPages = isServerPaginated ? pageCount : table.getPageCount();
|
||||
const canPreviousPage = isServerPaginated
|
||||
? (page ?? 1) > 1
|
||||
: table.getCanPreviousPage();
|
||||
const canNextPage = isServerPaginated
|
||||
? (page ?? 1) < (pageCount ?? 1)
|
||||
: table.getCanNextPage();
|
||||
|
||||
return (
|
||||
<div className={cn('space-y-4', className)}>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/50">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead key={header.id} className="px-4 py-3">
|
||||
{header.isPlaceholder ? null : (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-2',
|
||||
header.column.getCanSort() &&
|
||||
'cursor-pointer select-none hover:text-foreground'
|
||||
)}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
{header.column.getCanSort() && (
|
||||
<span className="ml-1">
|
||||
{header.column.getIsSorted() === 'asc' ? (
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
) : header.column.getIsSorted() === 'desc' ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronsUpDown className="h-4 w-4 opacity-50" />
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length}
|
||||
className="py-10 text-center text-muted-foreground"
|
||||
>
|
||||
Loading...
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : table.getRowModel().rows.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
className={cn(onRowClick && 'cursor-pointer')}
|
||||
onClick={() => onRowClick?.(row.original)}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id} className="px-4 py-3">
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length}
|
||||
className="py-10 text-center text-muted-foreground"
|
||||
>
|
||||
{emptyMessage}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Page {currentPage ?? 1} of {totalPages}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (isServerPaginated) {
|
||||
handlePageChange((page ?? 1) - 1);
|
||||
} else {
|
||||
table.previousPage();
|
||||
}
|
||||
}}
|
||||
disabled={!canPreviousPage}
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (isServerPaginated) {
|
||||
handlePageChange((page ?? 1) + 1);
|
||||
} else {
|
||||
table.nextPage();
|
||||
}
|
||||
}}
|
||||
disabled={!canNextPage}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
119
apps/web/src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ComponentRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-[9998] bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ComponentRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-[9999] grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
const DialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col space-y-1.5 text-center sm:text-left',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogHeader.displayName = 'DialogHeader';
|
||||
|
||||
const DialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogFooter.displayName = 'DialogFooter';
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ComponentRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'text-lg font-semibold leading-none tracking-tight',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ComponentRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
179
apps/web/src/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
import * as React from 'react';
|
||||
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
|
||||
import { Check, ChevronRight, Circle } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const DropdownMenu = DropdownMenuPrimitive.Root;
|
||||
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
|
||||
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
|
||||
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
|
||||
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
|
||||
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
|
||||
|
||||
const DropdownMenuSubTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.SubTrigger>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean;
|
||||
}
|
||||
>(({ className, inset, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent',
|
||||
inset && 'pl-8',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRight className="ml-auto h-4 w-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
));
|
||||
DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
|
||||
|
||||
const DropdownMenuSubContent = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.SubContent>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
|
||||
|
||||
const DropdownMenuContent = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
));
|
||||
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
|
||||
|
||||
const DropdownMenuItem = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
inset && 'pl-8',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
|
||||
|
||||
const DropdownMenuCheckboxItem = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.CheckboxItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
|
||||
>(({ className, children, checked, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
));
|
||||
DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
|
||||
|
||||
const DropdownMenuRadioItem = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.RadioItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<Circle className="h-2 w-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
));
|
||||
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
|
||||
|
||||
const DropdownMenuLabel = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean;
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn('px-2 py-1.5 text-sm font-semibold', inset && 'pl-8', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
|
||||
|
||||
const DropdownMenuSeparator = React.forwardRef<
|
||||
React.ComponentRef<typeof DropdownMenuPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn('-mx-1 my-1 h-px bg-muted', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
|
||||
|
||||
const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span className={cn('ml-auto text-xs tracking-widest opacity-60', className)} {...props} />
|
||||
);
|
||||
};
|
||||
DropdownMenuShortcut.displayName = 'DropdownMenuShortcut';
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuRadioGroup,
|
||||
};
|
||||
40
apps/web/src/components/ui/empty-state.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface EmptyStateProps {
|
||||
icon?: LucideIcon;
|
||||
title: string;
|
||||
description?: string;
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function EmptyState({
|
||||
icon: Icon,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
className,
|
||||
}: EmptyStateProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center py-12 text-center',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{Icon && (
|
||||
<div className="rounded-full bg-muted p-4">
|
||||
<Icon className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<h3 className="mt-4 text-lg font-semibold">{title}</h3>
|
||||
{description && (
|
||||
<p className="mt-2 max-w-md text-sm text-muted-foreground">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
{children && <div className="mt-6">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
24
apps/web/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Input.displayName = 'Input';
|
||||
|
||||
export { Input };
|
||||
23
apps/web/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import * as React from 'react';
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const labelVariants = cva(
|
||||
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
|
||||
);
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ComponentRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
||||
VariantProps<typeof labelVariants>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(labelVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Label.displayName = LabelPrimitive.Root.displayName;
|
||||
|
||||
export { Label };
|
||||
42
apps/web/src/components/ui/loading-spinner.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface LoadingSpinnerProps {
|
||||
className?: string;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
}
|
||||
|
||||
const sizeClasses = {
|
||||
sm: 'h-4 w-4',
|
||||
md: 'h-6 w-6',
|
||||
lg: 'h-8 w-8',
|
||||
};
|
||||
|
||||
export function LoadingSpinner({ className, size = 'md' }: LoadingSpinnerProps) {
|
||||
return (
|
||||
<Loader2
|
||||
className={cn('animate-spin text-muted-foreground', sizeClasses[size], className)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface LoadingOverlayProps {
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export function LoadingOverlay({ message = 'Loading...' }: LoadingOverlayProps) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-12">
|
||||
<LoadingSpinner size="lg" />
|
||||
<p className="text-sm text-muted-foreground">{message}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PageLoadingSpinner() {
|
||||
return (
|
||||
<div className="flex min-h-[400px] items-center justify-center">
|
||||
<LoadingSpinner size="lg" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
30
apps/web/src/components/ui/mode-toggle.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Moon, Sun } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { useTheme } from '@/components/theme-provider';
|
||||
|
||||
export function ModeToggle() {
|
||||
const { setTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Sun className="h-5 w-5 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
||||
<Moon className="absolute h-5 w-5 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setTheme('light')}>Light</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme('dark')}>Dark</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme('system')}>System</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
127
apps/web/src/components/ui/pagination.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
MoreHorizontalIcon,
|
||||
} from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants, type Button } from "@/components/ui/button"
|
||||
|
||||
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
|
||||
return (
|
||||
<nav
|
||||
role="navigation"
|
||||
aria-label="pagination"
|
||||
data-slot="pagination"
|
||||
className={cn("mx-auto flex w-full justify-center", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="pagination-content"
|
||||
className={cn("flex flex-row items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
|
||||
return <li data-slot="pagination-item" {...props} />
|
||||
}
|
||||
|
||||
type PaginationLinkProps = {
|
||||
isActive?: boolean
|
||||
} & Pick<React.ComponentProps<typeof Button>, "size"> &
|
||||
React.ComponentProps<"a">
|
||||
|
||||
function PaginationLink({
|
||||
className,
|
||||
isActive,
|
||||
size = "icon",
|
||||
...props
|
||||
}: PaginationLinkProps) {
|
||||
return (
|
||||
<a
|
||||
aria-current={isActive ? "page" : undefined}
|
||||
data-slot="pagination-link"
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
buttonVariants({
|
||||
variant: isActive ? "outline" : "ghost",
|
||||
size,
|
||||
}),
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationPrevious({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PaginationLink>) {
|
||||
return (
|
||||
<PaginationLink
|
||||
aria-label="Go to previous page"
|
||||
size="default"
|
||||
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
<span className="hidden sm:block">Previous</span>
|
||||
</PaginationLink>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationNext({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PaginationLink>) {
|
||||
return (
|
||||
<PaginationLink
|
||||
aria-label="Go to next page"
|
||||
size="default"
|
||||
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
|
||||
{...props}
|
||||
>
|
||||
<span className="hidden sm:block">Next</span>
|
||||
<ChevronRightIcon />
|
||||
</PaginationLink>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationEllipsis({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
data-slot="pagination-ellipsis"
|
||||
className={cn("flex size-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontalIcon className="size-4" />
|
||||
<span className="sr-only">More pages</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationLink,
|
||||
PaginationItem,
|
||||
PaginationPrevious,
|
||||
PaginationNext,
|
||||
PaginationEllipsis,
|
||||
}
|
||||
46
apps/web/src/components/ui/popover.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
26
apps/web/src/components/ui/progress.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import * as React from 'react';
|
||||
import * as ProgressPrimitive from '@radix-ui/react-progress';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Progress = React.forwardRef<
|
||||
React.ComponentRef<typeof ProgressPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
|
||||
>(({ className, value, ...props }, ref) => (
|
||||
<ProgressPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative h-2 w-full overflow-hidden rounded-full bg-primary/20',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
className="h-full w-full flex-1 bg-primary transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
));
|
||||
Progress.displayName = ProgressPrimitive.Root.displayName;
|
||||
|
||||
export { Progress };
|
||||
58
apps/web/src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
157
apps/web/src/components/ui/select.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
import * as React from 'react';
|
||||
import * as SelectPrimitive from '@radix-ui/react-select';
|
||||
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Select = SelectPrimitive.Root;
|
||||
|
||||
const SelectGroup = SelectPrimitive.Group;
|
||||
|
||||
const SelectValue = SelectPrimitive.Value;
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
));
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex cursor-default items-center justify-center py-1',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
));
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex cursor-default items-center justify-center py-1',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
));
|
||||
SelectScrollDownButton.displayName =
|
||||
SelectPrimitive.ScrollDownButton.displayName;
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = 'popper', ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative z-[10000] max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
'p-1',
|
||||
position === 'popper' &&
|
||||
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]'
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
));
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName;
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn('py-1.5 pl-8 pr-2 text-sm font-semibold', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName;
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
));
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName;
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ComponentRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn('-mx-1 my-1 h-px bg-muted', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
};
|
||||
26
apps/web/src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
139
apps/web/src/components/ui/sheet.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
727
apps/web/src/components/ui/sidebar.tsx
Normal file
@@ -0,0 +1,727 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
interface SidebarContextProps {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}) {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer text-sidebar-foreground hidden md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-label"
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-action"
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-button"
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip) {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
asChild = false,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-action"
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
asChild = false,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-sub-button"
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
61
apps/web/src/components/ui/skeleton.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SkeletonProps extends React.HTMLAttributes<HTMLDivElement> {}
|
||||
|
||||
export function Skeleton({ className, ...props }: SkeletonProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn('animate-pulse rounded-md bg-muted', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Card skeleton for dashboard stats
|
||||
export function StatsCardSkeleton() {
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-4 rounded-full" />
|
||||
</div>
|
||||
<Skeleton className="mt-4 h-8 w-16" />
|
||||
<Skeleton className="mt-2 h-3 w-32" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Table row skeleton
|
||||
export function TableRowSkeleton({ columns = 5 }: { columns?: number }) {
|
||||
return (
|
||||
<tr className="border-b">
|
||||
{Array.from({ length: columns }).map((_, i) => (
|
||||
<td key={i} className="p-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
// List item skeleton
|
||||
export function ListItemSkeleton() {
|
||||
return (
|
||||
<div className="flex items-center gap-4 p-4">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-1/3" />
|
||||
<Skeleton className="h-3 w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Chart skeleton
|
||||
export function ChartSkeleton({ height = 200 }: { height?: number }) {
|
||||
return (
|
||||
<div className="w-full" style={{ height }}>
|
||||
<Skeleton className="h-full w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
38
apps/web/src/components/ui/sonner.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react"
|
||||
import { useTheme } from "@/components/theme-provider"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
26
apps/web/src/components/ui/switch.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import * as React from 'react';
|
||||
import * as SwitchPrimitives from '@radix-ui/react-switch';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Switch = React.forwardRef<
|
||||
React.ComponentRef<typeof SwitchPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitives.Root
|
||||
className={cn(
|
||||
'peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<SwitchPrimitives.Thumb
|
||||
className={cn(
|
||||
'pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0'
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitives.Root>
|
||||
));
|
||||
Switch.displayName = SwitchPrimitives.Root.displayName;
|
||||
|
||||
export { Switch };
|
||||
114
apps/web/src/components/ui/table.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("text-muted-foreground mt-4 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
}
|
||||
52
apps/web/src/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import * as React from 'react';
|
||||
import * as TabsPrimitive from '@radix-ui/react-tabs';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Tabs = TabsPrimitive.Root;
|
||||
|
||||
const TabsList = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsList.displayName = TabsPrimitive.List.displayName;
|
||||
|
||||
const TabsTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
|
||||
|
||||
const TabsContent = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsContent.displayName = TabsPrimitive.Content.displayName;
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
130
apps/web/src/components/ui/time-range-picker.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import * as React from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { CalendarIcon } from 'lucide-react';
|
||||
import type { DateRange } from 'react-day-picker';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
|
||||
export type TimeRangePeriod = 'day' | 'week' | 'month' | 'year' | 'all' | 'custom';
|
||||
|
||||
export interface TimeRangeValue {
|
||||
period: TimeRangePeriod;
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
}
|
||||
|
||||
interface TimeRangePickerProps {
|
||||
value: TimeRangeValue;
|
||||
onChange: (value: TimeRangeValue) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const PRESETS: { value: TimeRangePeriod; label: string }[] = [
|
||||
{ value: 'week', label: '7d' },
|
||||
{ value: 'month', label: '30d' },
|
||||
{ value: 'year', label: '1y' },
|
||||
{ value: 'all', label: 'All' },
|
||||
];
|
||||
|
||||
export function TimeRangePicker({ value, onChange, className }: TimeRangePickerProps) {
|
||||
const [isOpen, setIsOpen] = React.useState(false);
|
||||
const [tempRange, setTempRange] = React.useState<DateRange | undefined>(() => {
|
||||
if (value.startDate && value.endDate) {
|
||||
return { from: value.startDate, to: value.endDate };
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const handlePresetClick = (period: TimeRangePeriod) => {
|
||||
onChange({ period, startDate: undefined, endDate: undefined });
|
||||
};
|
||||
|
||||
const handleCustomApply = () => {
|
||||
if (tempRange?.from && tempRange?.to) {
|
||||
onChange({
|
||||
period: 'custom',
|
||||
startDate: tempRange.from,
|
||||
endDate: tempRange.to,
|
||||
});
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDateRange = () => {
|
||||
if (value.startDate && value.endDate) {
|
||||
return `${format(value.startDate, 'MMM d')} - ${format(value.endDate, 'MMM d, yyyy')}`;
|
||||
}
|
||||
return 'Custom';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn('inline-flex items-center gap-1 rounded-lg bg-muted p-1', className)}>
|
||||
{/* Preset buttons */}
|
||||
{PRESETS.map((preset) => (
|
||||
<button
|
||||
key={preset.value}
|
||||
onClick={() => handlePresetClick(preset.value)}
|
||||
className={cn(
|
||||
'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
|
||||
value.period === preset.value
|
||||
? 'bg-background text-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
{preset.label}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* Custom date range picker */}
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
|
||||
value.period === 'custom'
|
||||
? 'bg-background text-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="h-3.5 w-3.5" />
|
||||
<span>{value.period === 'custom' ? formatDateRange() : 'Custom'}</span>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="z-[1100] w-auto p-0" align="end">
|
||||
<div className="p-3">
|
||||
<Calendar
|
||||
mode="range"
|
||||
defaultMonth={tempRange?.from}
|
||||
selected={tempRange}
|
||||
onSelect={setTempRange}
|
||||
numberOfMonths={2}
|
||||
disabled={{ after: new Date() }}
|
||||
/>
|
||||
<div className="flex items-center justify-end gap-2 border-t pt-3 mt-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setTempRange(undefined);
|
||||
setIsOpen(false);
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleCustomApply}
|
||||
disabled={!tempRange?.from || !tempRange?.to}
|
||||
>
|
||||
Apply
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
27
apps/web/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import * as React from 'react';
|
||||
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider;
|
||||
|
||||
const Tooltip = TooltipPrimitive.Root;
|
||||
|
||||
const TooltipTrigger = TooltipPrimitive.Trigger;
|
||||
|
||||
const TooltipContent = React.forwardRef<
|
||||
React.ComponentRef<typeof TooltipPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<TooltipPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||
96
apps/web/src/components/users/EditUserNameDialog.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useUpdateUserIdentity } from '@/hooks/queries';
|
||||
|
||||
interface EditUserNameDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
userId: string;
|
||||
currentName: string | null;
|
||||
username: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dialog for editing a user's display name (identity name)
|
||||
* Only accessible to owners
|
||||
*/
|
||||
export function EditUserNameDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
userId,
|
||||
currentName,
|
||||
username,
|
||||
}: EditUserNameDialogProps) {
|
||||
const [name, setName] = useState(currentName ?? '');
|
||||
const mutation = useUpdateUserIdentity();
|
||||
|
||||
// Reset form when dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setName(currentName ?? '');
|
||||
}
|
||||
}, [open, currentName]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
mutation.mutate(
|
||||
{ id: userId, name: name.trim() || null },
|
||||
{ onSuccess: () => onOpenChange(false) }
|
||||
);
|
||||
};
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
if (!newOpen) {
|
||||
setName(currentName ?? '');
|
||||
}
|
||||
onOpenChange(newOpen);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Display Name</DialogTitle>
|
||||
<DialogDescription>
|
||||
Set a custom display name. Leave empty to use server username (@{username}).
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="displayName">Display Name</Label>
|
||||
<Input
|
||||
id="displayName"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={username}
|
||||
maxLength={255}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={mutation.isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
{mutation.isPending ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
36
apps/web/src/components/users/TrustScoreBadge.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface TrustScoreBadgeProps {
|
||||
score: number;
|
||||
showLabel?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function getTrustLevel(score: number): {
|
||||
variant: 'success' | 'warning' | 'danger';
|
||||
label: string;
|
||||
} {
|
||||
if (score >= 80) {
|
||||
return { variant: 'success', label: 'Trusted' };
|
||||
}
|
||||
if (score >= 50) {
|
||||
return { variant: 'warning', label: 'Caution' };
|
||||
}
|
||||
return { variant: 'danger', label: 'Untrusted' };
|
||||
}
|
||||
|
||||
export function TrustScoreBadge({
|
||||
score,
|
||||
showLabel = false,
|
||||
className,
|
||||
}: TrustScoreBadgeProps) {
|
||||
const { variant, label } = getTrustLevel(score);
|
||||
|
||||
return (
|
||||
<Badge variant={variant} className={cn('gap-1', className)}>
|
||||
<span className="font-mono">{score}</span>
|
||||
{showLabel && <span>· {label}</span>}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
120
apps/web/src/components/users/UserCard.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
import { Link } from 'react-router';
|
||||
import { User, Trophy } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { getAvatarUrl, getTrustScoreColor, getTrustScoreBg, MEDALS } from './utils';
|
||||
|
||||
interface UserCardProps {
|
||||
userId: string;
|
||||
username: string;
|
||||
identityName?: string | null;
|
||||
thumbUrl?: string | null;
|
||||
serverId?: string | null;
|
||||
trustScore: number;
|
||||
playCount: number;
|
||||
watchTimeHours: number;
|
||||
topMediaType?: string | null;
|
||||
topContent?: string | null;
|
||||
rank: 1 | 2 | 3;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
export function UserCard({
|
||||
userId,
|
||||
username,
|
||||
identityName,
|
||||
thumbUrl,
|
||||
serverId,
|
||||
trustScore,
|
||||
playCount,
|
||||
watchTimeHours,
|
||||
topContent,
|
||||
rank,
|
||||
className,
|
||||
style,
|
||||
}: UserCardProps) {
|
||||
const displayName = identityName ?? username;
|
||||
const avatarUrl = getAvatarUrl(serverId, thumbUrl);
|
||||
const medal = MEDALS[rank];
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={`/users/${userId}`}
|
||||
className={cn(
|
||||
'group relative flex flex-col items-center rounded-xl border bg-card p-6 text-center transition-all duration-300 hover:scale-[1.02] hover:border-primary/50 hover:shadow-lg hover:shadow-primary/10',
|
||||
'animate-fade-in-up',
|
||||
className
|
||||
)}
|
||||
style={{
|
||||
...style,
|
||||
animationDelay: rank === 1 ? '0ms' : rank === 2 ? '100ms' : '200ms',
|
||||
}}
|
||||
>
|
||||
{/* Subtle gradient background based on medal */}
|
||||
<div
|
||||
className={cn(
|
||||
'pointer-events-none absolute inset-0 rounded-xl bg-gradient-to-b opacity-50 transition-opacity group-hover:opacity-70',
|
||||
medal.bgColor
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Medal */}
|
||||
<div className="relative z-10 absolute -top-3 text-3xl drop-shadow-md">{medal.emoji}</div>
|
||||
|
||||
{/* Avatar */}
|
||||
<div
|
||||
className={cn(
|
||||
'relative z-10 mt-4 overflow-hidden rounded-full bg-gradient-to-br shadow-lg ring-2 ring-background',
|
||||
medal.color,
|
||||
medal.size
|
||||
)}
|
||||
>
|
||||
<div className="absolute inset-0.5 overflow-hidden rounded-full bg-card">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
src={avatarUrl}
|
||||
alt={displayName}
|
||||
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-110"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center bg-muted">
|
||||
<User className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Name */}
|
||||
<h3 className="relative z-10 mt-4 w-full px-2 text-center text-base font-semibold line-clamp-2 break-words">{displayName}</h3>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="relative z-10 mt-2 flex items-center gap-4 text-sm">
|
||||
<div>
|
||||
<span className="font-semibold text-primary">{playCount.toLocaleString()}</span>
|
||||
<span className="ml-1 text-muted-foreground">plays</span>
|
||||
</div>
|
||||
<div className="text-muted-foreground">{watchTimeHours.toLocaleString()}h</div>
|
||||
</div>
|
||||
|
||||
{/* Trust Score */}
|
||||
<div
|
||||
className={cn(
|
||||
'relative z-10 mt-3 flex w-24 items-center justify-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium',
|
||||
getTrustScoreBg(trustScore),
|
||||
getTrustScoreColor(trustScore)
|
||||
)}
|
||||
>
|
||||
<Trophy className="h-3 w-3 shrink-0" />
|
||||
<span>Trust: {trustScore}%</span>
|
||||
</div>
|
||||
|
||||
{/* Top Content */}
|
||||
{topContent && (
|
||||
<p className="relative z-10 mt-2 w-full px-2 text-center text-xs text-muted-foreground truncate">
|
||||
Loves: <span className="font-medium">{topContent}</span>
|
||||
</p>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
313
apps/web/src/components/users/UserDevicesCard.tsx
Normal file
@@ -0,0 +1,313 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import {
|
||||
Monitor,
|
||||
Smartphone,
|
||||
Tablet,
|
||||
Tv,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Laptop,
|
||||
HardDrive,
|
||||
MapPin,
|
||||
} from 'lucide-react';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import type { UserDevice } from '@tracearr/shared';
|
||||
|
||||
interface UserDevicesCardProps {
|
||||
devices: UserDevice[];
|
||||
isLoading?: boolean;
|
||||
totalSessions?: number;
|
||||
}
|
||||
|
||||
const INITIAL_DISPLAY_COUNT = 5;
|
||||
|
||||
function getDeviceIcon(device: UserDevice) {
|
||||
const deviceType = device.device?.toLowerCase() ?? '';
|
||||
const platform = device.platform?.toLowerCase() ?? '';
|
||||
const product = device.product?.toLowerCase() ?? '';
|
||||
|
||||
// Check for TV/streaming devices
|
||||
if (
|
||||
deviceType.includes('tv') ||
|
||||
platform.includes('tv') ||
|
||||
product.includes('tv') ||
|
||||
product.includes('roku') ||
|
||||
product.includes('fire') ||
|
||||
product.includes('chromecast') ||
|
||||
product.includes('shield')
|
||||
) {
|
||||
return Tv;
|
||||
}
|
||||
|
||||
// Check for tablets
|
||||
if (
|
||||
deviceType.includes('ipad') ||
|
||||
deviceType.includes('tablet') ||
|
||||
platform.includes('ipad')
|
||||
) {
|
||||
return Tablet;
|
||||
}
|
||||
|
||||
// Check for phones
|
||||
if (
|
||||
deviceType.includes('iphone') ||
|
||||
deviceType.includes('phone') ||
|
||||
deviceType.includes('android') ||
|
||||
platform.includes('ios') ||
|
||||
platform.includes('android')
|
||||
) {
|
||||
return Smartphone;
|
||||
}
|
||||
|
||||
// Check for laptops/desktops
|
||||
if (
|
||||
deviceType.includes('mac') ||
|
||||
platform.includes('macos') ||
|
||||
platform.includes('windows') ||
|
||||
platform.includes('linux')
|
||||
) {
|
||||
return Laptop;
|
||||
}
|
||||
|
||||
// Check for web browsers
|
||||
if (
|
||||
product.includes('web') ||
|
||||
product.includes('browser') ||
|
||||
product.includes('chrome') ||
|
||||
product.includes('firefox') ||
|
||||
product.includes('safari')
|
||||
) {
|
||||
return Monitor;
|
||||
}
|
||||
|
||||
// Default
|
||||
return HardDrive;
|
||||
}
|
||||
|
||||
function getDeviceDisplayName(device: UserDevice): string {
|
||||
// Prefer playerName if available
|
||||
if (device.playerName) {
|
||||
return device.playerName;
|
||||
}
|
||||
|
||||
// Build from product + device
|
||||
const parts: string[] = [];
|
||||
if (device.product) {
|
||||
parts.push(device.product);
|
||||
}
|
||||
if (device.device && !parts.some(p => p.toLowerCase().includes(device.device!.toLowerCase()))) {
|
||||
parts.push(device.device);
|
||||
}
|
||||
|
||||
if (parts.length > 0) {
|
||||
return parts.join(' - ');
|
||||
}
|
||||
|
||||
// Fall back to platform or unknown
|
||||
return device.platform ?? 'Unknown Device';
|
||||
}
|
||||
|
||||
function formatLocationShort(loc: { city: string | null; region: string | null; country: string | null }): string {
|
||||
if (loc.city && loc.region) {
|
||||
return `${loc.city}, ${loc.region}`;
|
||||
}
|
||||
if (loc.city && loc.country) {
|
||||
return `${loc.city}, ${loc.country}`;
|
||||
}
|
||||
return loc.city ?? loc.country ?? 'Unknown';
|
||||
}
|
||||
|
||||
export function UserDevicesCard({
|
||||
devices,
|
||||
isLoading,
|
||||
totalSessions = 0,
|
||||
}: UserDevicesCardProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Monitor className="h-5 w-5" />
|
||||
Devices
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<div key={i} className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="h-8 w-8 rounded-full" />
|
||||
<div>
|
||||
<Skeleton className="h-4 w-36" />
|
||||
<Skeleton className="mt-1 h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="h-5 w-12" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (devices.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Monitor className="h-5 w-5" />
|
||||
Devices
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">No device data available</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const displayedDevices = isExpanded
|
||||
? devices
|
||||
: devices.slice(0, INITIAL_DISPLAY_COUNT);
|
||||
const hasMore = devices.length > INITIAL_DISPLAY_COUNT;
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Monitor className="h-5 w-5" />
|
||||
Devices
|
||||
</div>
|
||||
<Badge variant="secondary" className="font-normal">
|
||||
{devices.length} unique
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{displayedDevices.map((device, index) => {
|
||||
const deviceKey = `${device.deviceId ?? index}-${device.playerName ?? ''}-${device.product ?? ''}`;
|
||||
const percentage = totalSessions > 0
|
||||
? Math.round((device.sessionCount / totalSessions) * 100)
|
||||
: 0;
|
||||
const DeviceIcon = getDeviceIcon(device);
|
||||
const displayName = getDeviceDisplayName(device);
|
||||
const locations = device.locations ?? [];
|
||||
const hasMultipleLocations = locations.length > 1;
|
||||
const primaryLocation = locations[0];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={deviceKey}
|
||||
className="flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50"
|
||||
>
|
||||
{/* Device Icon */}
|
||||
<div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-primary/10">
|
||||
<DeviceIcon className="h-4 w-4 text-primary" />
|
||||
</div>
|
||||
|
||||
{/* Device Info */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="truncate font-medium">{displayName}</p>
|
||||
{device.platform && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{device.platform}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{device.sessionCount} session{device.sessionCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<span>·</span>
|
||||
<span>
|
||||
{formatDistanceToNow(new Date(device.lastSeenAt), { addSuffix: true })}
|
||||
</span>
|
||||
{primaryLocation && (
|
||||
<>
|
||||
<span>·</span>
|
||||
{hasMultipleLocations ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="flex cursor-help items-center gap-1 text-yellow-500">
|
||||
<MapPin className="h-3 w-3" />
|
||||
{locations.length} locations
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" className="max-w-xs">
|
||||
<div className="space-y-1">
|
||||
{locations.map((loc, locIndex) => (
|
||||
<div
|
||||
key={locIndex}
|
||||
className="flex items-center justify-between gap-4 text-xs"
|
||||
>
|
||||
<span>{formatLocationShort(loc)}</span>
|
||||
<span className="tabular-nums text-muted-foreground">
|
||||
{loc.sessionCount}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span className="flex items-center gap-1">
|
||||
<MapPin className="h-3 w-3" />
|
||||
{formatLocationShort(primaryLocation)}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Usage Percentage */}
|
||||
<Badge variant="outline" className="flex-shrink-0 font-mono">
|
||||
{percentage}%
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{hasMore && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="mt-3 w-full"
|
||||
onClick={() => { setIsExpanded(!isExpanded); }}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<ChevronUp className="mr-2 h-4 w-4" />
|
||||
Show Less
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronDown className="mr-2 h-4 w-4" />
|
||||
View All ({devices.length - INITIAL_DISPLAY_COUNT} more)
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
163
apps/web/src/components/users/UserLocationsCard.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { MapPin, ChevronDown, ChevronUp, Globe } from 'lucide-react';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import type { UserLocation } from '@tracearr/shared';
|
||||
|
||||
interface UserLocationsCardProps {
|
||||
locations: UserLocation[];
|
||||
isLoading?: boolean;
|
||||
totalSessions?: number;
|
||||
}
|
||||
|
||||
const INITIAL_DISPLAY_COUNT = 5;
|
||||
|
||||
export function UserLocationsCard({
|
||||
locations,
|
||||
isLoading,
|
||||
totalSessions = 0,
|
||||
}: UserLocationsCardProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<MapPin className="h-5 w-5" />
|
||||
Locations
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<div key={i} className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="h-4 w-4" />
|
||||
<div>
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<Skeleton className="mt-1 h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="h-5 w-12" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (locations.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<MapPin className="h-5 w-5" />
|
||||
Locations
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">No location data available</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const displayedLocations = isExpanded
|
||||
? locations
|
||||
: locations.slice(0, INITIAL_DISPLAY_COUNT);
|
||||
const hasMore = locations.length > INITIAL_DISPLAY_COUNT;
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<MapPin className="h-5 w-5" />
|
||||
Locations
|
||||
</div>
|
||||
<Badge variant="secondary" className="font-normal">
|
||||
{locations.length} unique
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{displayedLocations.map((location) => {
|
||||
const locationKey = `${location.city ?? 'unknown'}-${location.country ?? 'unknown'}-${location.lat}-${location.lon}`;
|
||||
const percentage = totalSessions > 0
|
||||
? Math.round((location.sessionCount / totalSessions) * 100)
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={locationKey}
|
||||
className="flex items-center justify-between rounded-lg border p-3 transition-colors hover:bg-muted/50"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
|
||||
<Globe className="h-4 w-4 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{location.city ?? 'Unknown City'}
|
||||
{location.region && (
|
||||
<span className="text-muted-foreground">, {location.region}</span>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>{location.country ?? 'Unknown'}</span>
|
||||
<span>·</span>
|
||||
<span>
|
||||
{location.sessionCount} session{location.sessionCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<span>·</span>
|
||||
<span>
|
||||
{formatDistanceToNow(new Date(location.lastSeenAt), { addSuffix: true })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{percentage}%
|
||||
</Badge>
|
||||
{location.ipAddresses.length > 1 && (
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{location.ipAddresses.length} IPs
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{hasMore && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="mt-3 w-full"
|
||||
onClick={() => { setIsExpanded(!isExpanded); }}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<ChevronUp className="mr-2 h-4 w-4" />
|
||||
Show Less
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronDown className="mr-2 h-4 w-4" />
|
||||
View All ({locations.length - INITIAL_DISPLAY_COUNT} more)
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
99
apps/web/src/components/users/UserRow.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { Link } from 'react-router';
|
||||
import { User, Trophy, ChevronRight } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { getAvatarUrl, getTrustScoreColor } from './utils';
|
||||
|
||||
interface UserRowProps {
|
||||
userId: string;
|
||||
username: string;
|
||||
identityName?: string | null;
|
||||
thumbUrl?: string | null;
|
||||
serverId?: string | null;
|
||||
trustScore: number;
|
||||
playCount: number;
|
||||
watchTimeHours: number;
|
||||
topContent?: string | null;
|
||||
rank: number;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
export function UserRow({
|
||||
userId,
|
||||
username,
|
||||
identityName,
|
||||
thumbUrl,
|
||||
serverId,
|
||||
trustScore,
|
||||
playCount,
|
||||
watchTimeHours,
|
||||
topContent,
|
||||
rank,
|
||||
className,
|
||||
style,
|
||||
}: UserRowProps) {
|
||||
const displayName = identityName ?? username;
|
||||
const avatarUrl = getAvatarUrl(serverId, thumbUrl, 40);
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={`/users/${userId}`}
|
||||
className={cn(
|
||||
'group flex animate-fade-in-up items-center gap-4 rounded-lg border bg-card p-3 transition-all duration-200 hover:border-primary/50 hover:bg-accent hover:shadow-md',
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
>
|
||||
{/* Rank */}
|
||||
<div className="w-8 text-center text-lg font-bold text-muted-foreground">#{rank}</div>
|
||||
|
||||
{/* Avatar */}
|
||||
<div className="h-10 w-10 shrink-0 overflow-hidden rounded-full bg-muted ring-2 ring-background">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
src={avatarUrl}
|
||||
alt={displayName}
|
||||
className="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<User className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Name & Top Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="truncate font-medium">{displayName}</p>
|
||||
{topContent && (
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
Loves: <span className="font-medium">{topContent}</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="hidden sm:flex items-center gap-6 text-sm">
|
||||
<div className="text-right">
|
||||
<span className="font-semibold">{playCount.toLocaleString()}</span>
|
||||
<span className="ml-1 text-muted-foreground">plays</span>
|
||||
</div>
|
||||
<div className="w-16 text-right text-muted-foreground">{watchTimeHours.toLocaleString()}h</div>
|
||||
<div className={cn('flex w-20 items-center gap-1 text-right', getTrustScoreColor(trustScore))}>
|
||||
<Trophy className="h-3.5 w-3.5" />
|
||||
<span className="font-medium">{trustScore}%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mobile Stats */}
|
||||
<div className="flex sm:hidden items-center gap-3 text-xs">
|
||||
<span className="font-semibold">{playCount}</span>
|
||||
<span className={cn('font-medium', getTrustScoreColor(trustScore))}>{trustScore}%</span>
|
||||
</div>
|
||||
|
||||
{/* Arrow */}
|
||||
<ChevronRight className="h-5 w-5 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
2
apps/web/src/components/users/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { UserCard } from './UserCard';
|
||||
export { UserRow } from './UserRow';
|
||||
46
apps/web/src/components/users/utils.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Shared utilities for user components
|
||||
*/
|
||||
|
||||
/**
|
||||
* Generate proxied avatar URL for user thumbnails
|
||||
*/
|
||||
export function getAvatarUrl(
|
||||
serverId: string | null | undefined,
|
||||
thumbUrl: string | null | undefined,
|
||||
size = 100
|
||||
): string | null {
|
||||
if (!thumbUrl) return null;
|
||||
// If thumbUrl is already a full URL (e.g., from Plex.tv), use it directly
|
||||
if (thumbUrl.startsWith('http')) return thumbUrl;
|
||||
// Otherwise, proxy through our server
|
||||
if (!serverId) return null;
|
||||
return `/api/v1/images/proxy?server=${serverId}&url=${encodeURIComponent(thumbUrl)}&width=${size}&height=${size}&fallback=avatar`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get text color class based on trust score
|
||||
*/
|
||||
export function getTrustScoreColor(score: number): string {
|
||||
if (score >= 80) return 'text-green-500';
|
||||
if (score >= 50) return 'text-yellow-500';
|
||||
return 'text-red-500';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get background color class based on trust score
|
||||
*/
|
||||
export function getTrustScoreBg(score: number): string {
|
||||
if (score >= 80) return 'bg-green-500/20';
|
||||
if (score >= 50) return 'bg-yellow-500/20';
|
||||
return 'bg-red-500/20';
|
||||
}
|
||||
|
||||
/**
|
||||
* Medal configuration for podium ranks
|
||||
*/
|
||||
export const MEDALS = {
|
||||
1: { emoji: '🥇', color: 'from-yellow-400 to-yellow-600', bgColor: 'from-yellow-500/10 to-yellow-600/5', size: 'h-20 w-20' },
|
||||
2: { emoji: '🥈', color: 'from-gray-300 to-gray-500', bgColor: 'from-gray-400/10 to-gray-500/5', size: 'h-16 w-16' },
|
||||
3: { emoji: '🥉', color: 'from-amber-600 to-amber-800', bgColor: 'from-amber-500/10 to-amber-600/5', size: 'h-16 w-16' },
|
||||
} as const;
|
||||
23
apps/web/src/components/violations/SeverityBadge.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import type { ViolationSeverity } from '@tracearr/shared';
|
||||
import { SEVERITY_LEVELS } from '@tracearr/shared';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SeverityBadgeProps {
|
||||
severity: ViolationSeverity;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const severityVariants: Record<ViolationSeverity, 'success' | 'warning' | 'danger'> = {
|
||||
low: 'success',
|
||||
warning: 'warning',
|
||||
high: 'danger',
|
||||
};
|
||||
|
||||
export function SeverityBadge({ severity, className }: SeverityBadgeProps) {
|
||||
return (
|
||||
<Badge variant={severityVariants[severity]} className={cn(className)}>
|
||||
{SEVERITY_LEVELS[severity].label}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
558
apps/web/src/components/violations/ViolationDetailDialog.tsx
Normal file
@@ -0,0 +1,558 @@
|
||||
import { formatDistanceToNow, format } from 'date-fns';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { SeverityBadge } from '@/components/violations/SeverityBadge';
|
||||
import { getAvatarUrl } from '@/components/users/utils';
|
||||
import { getViolationDescription, getViolationDetails } from '@/utils/violationDescription';
|
||||
import { useSettings } from '@/hooks/queries';
|
||||
import type { ViolationWithDetails } from '@tracearr/shared';
|
||||
import {
|
||||
User,
|
||||
AlertTriangle,
|
||||
Check,
|
||||
X,
|
||||
MapPin,
|
||||
Users,
|
||||
Zap,
|
||||
Shield,
|
||||
Globe,
|
||||
Clock,
|
||||
Film,
|
||||
Monitor,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
} from 'lucide-react';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
|
||||
const ruleIcons: Record<string, React.ReactNode> = {
|
||||
impossible_travel: <MapPin className="h-4 w-4" />,
|
||||
simultaneous_locations: <Users className="h-4 w-4" />,
|
||||
device_velocity: <Zap className="h-4 w-4" />,
|
||||
concurrent_streams: <Shield className="h-4 w-4" />,
|
||||
geo_restriction: <Globe className="h-4 w-4" />,
|
||||
};
|
||||
|
||||
interface ViolationDetailDialogProps {
|
||||
violation: ViolationWithDetails | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onAcknowledge: (id: string) => void;
|
||||
onDismiss: (id: string) => void;
|
||||
isAcknowledging?: boolean;
|
||||
isDismissing?: boolean;
|
||||
}
|
||||
|
||||
export function ViolationDetailDialog({
|
||||
violation,
|
||||
open,
|
||||
onOpenChange,
|
||||
onAcknowledge,
|
||||
onDismiss,
|
||||
isAcknowledging = false,
|
||||
isDismissing = false,
|
||||
}: ViolationDetailDialogProps) {
|
||||
const { data: settings } = useSettings();
|
||||
const unitSystem = settings?.unitSystem ?? 'metric';
|
||||
|
||||
if (!violation) return null;
|
||||
|
||||
const avatarUrl = getAvatarUrl(violation.user.serverId, violation.user.thumbUrl, 80);
|
||||
const description = getViolationDescription(violation, unitSystem);
|
||||
const details = getViolationDetails(violation, unitSystem);
|
||||
const ruleIcon = ruleIcons[violation.rule.type] ?? <AlertTriangle className="h-4 w-4" />;
|
||||
const isPending = !violation.acknowledgedAt;
|
||||
|
||||
// Helper function to check if a value has been seen before
|
||||
const isValueSeenBefore = (
|
||||
value: string | null | undefined,
|
||||
history: string[]
|
||||
): boolean => {
|
||||
if (!value) return false;
|
||||
return history.includes(value);
|
||||
};
|
||||
|
||||
// Helper function to check if location has been seen before
|
||||
const isLocationSeenBefore = (
|
||||
city: string | null,
|
||||
country: string | null,
|
||||
history: Array<{ city: string | null; country: string | null; ip: string }>
|
||||
): boolean => {
|
||||
if (!city && !country) return false;
|
||||
return history.some(
|
||||
(loc) => loc.city === city && loc.country === country
|
||||
);
|
||||
};
|
||||
|
||||
// Collect all sessions for comparison
|
||||
// Include triggering session first, then related sessions (excluding duplicates)
|
||||
const allSessions: NonNullable<typeof violation.session>[] = (() => {
|
||||
const sessions: NonNullable<typeof violation.session>[] = [];
|
||||
const seenIds = new Set<string>();
|
||||
|
||||
// Add triggering session first if it exists
|
||||
if (violation.session) {
|
||||
sessions.push(violation.session);
|
||||
seenIds.add(violation.session.id);
|
||||
}
|
||||
|
||||
// Add related sessions, excluding the triggering session if it appears
|
||||
if (violation.relatedSessions) {
|
||||
for (const session of violation.relatedSessions) {
|
||||
if (!seenIds.has(session.id)) {
|
||||
sessions.push(session);
|
||||
seenIds.add(session.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sessions;
|
||||
})();
|
||||
|
||||
// Analyze for suspicious patterns
|
||||
const analysis = allSessions.length > 1 ? {
|
||||
uniqueIPs: new Set(allSessions.map((s) => s.ipAddress)).size,
|
||||
uniqueDevices: new Set(
|
||||
allSessions
|
||||
.map((s) => s.deviceId || s.device)
|
||||
.filter((d): d is string => !!d)
|
||||
).size,
|
||||
uniqueLocations: new Set(
|
||||
allSessions
|
||||
.map((s) => `${s.geoCity || ''}-${s.geoCountry || ''}`)
|
||||
.filter((l) => l !== '-')
|
||||
).size,
|
||||
newIPs: allSessions.filter((s) =>
|
||||
!isValueSeenBefore(s.ipAddress, violation.userHistory?.previousIPs || [])
|
||||
).length,
|
||||
newDevices: allSessions.filter((s) =>
|
||||
!isValueSeenBefore(
|
||||
s.deviceId || s.device,
|
||||
violation.userHistory?.previousDevices || []
|
||||
)
|
||||
).length,
|
||||
newLocations: allSessions.filter((s) =>
|
||||
!isLocationSeenBefore(
|
||||
s.geoCity,
|
||||
s.geoCountry,
|
||||
violation.userHistory?.previousLocations || []
|
||||
)
|
||||
).length,
|
||||
} : null;
|
||||
|
||||
const handleAcknowledge = () => {
|
||||
onAcknowledge(violation.id);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleDismiss = () => {
|
||||
onDismiss(violation.id);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Violation Details</DialogTitle>
|
||||
<DialogDescription>
|
||||
Detailed information about this rule violation
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* User Information */}
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted shrink-0">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
src={avatarUrl}
|
||||
alt={violation.user.identityName ?? violation.user.username}
|
||||
className="h-16 w-16 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<User className="h-8 w-8 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-lg truncate">{violation.user.identityName ?? violation.user.username}</h3>
|
||||
<p className="text-sm text-muted-foreground truncate">
|
||||
@{violation.user.username}
|
||||
{violation.server?.name && ` • ${violation.server.name}`}
|
||||
</p>
|
||||
</div>
|
||||
<SeverityBadge severity={violation.severity} />
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Rule Information */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded bg-muted">
|
||||
{ruleIcon}
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{violation.rule.name}</p>
|
||||
<p className="text-xs text-muted-foreground capitalize">
|
||||
{violation.rule.type.replace(/_/g, ' ')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Violation Description */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium text-muted-foreground">Description</h4>
|
||||
<p className="text-sm">{description}</p>
|
||||
</div>
|
||||
|
||||
{/* Stream Comparison - Side by side analysis */}
|
||||
{allSessions.length > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="text-sm font-medium text-muted-foreground flex items-center gap-2">
|
||||
<Film className="h-4 w-4" />
|
||||
Stream Comparison
|
||||
{allSessions.length > 1 && (
|
||||
<span className="text-xs bg-muted px-2 py-0.5 rounded">
|
||||
{allSessions.length} streams
|
||||
</span>
|
||||
)}
|
||||
</h4>
|
||||
{analysis && (
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
{analysis.uniqueIPs > 1 && (
|
||||
<span className="bg-yellow-500/20 text-yellow-600 px-2 py-0.5 rounded">
|
||||
{analysis.uniqueIPs} IPs
|
||||
</span>
|
||||
)}
|
||||
{analysis.uniqueDevices > 1 && (
|
||||
<span className="bg-orange-500/20 text-orange-600 px-2 py-0.5 rounded">
|
||||
{analysis.uniqueDevices} Devices
|
||||
</span>
|
||||
)}
|
||||
{analysis.uniqueLocations > 1 && (
|
||||
<span className="bg-red-500/20 text-red-600 px-2 py-0.5 rounded">
|
||||
{analysis.uniqueLocations} Locations
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Comparison Table */}
|
||||
<div className="overflow-x-auto">
|
||||
<div className="min-w-full space-y-2">
|
||||
{allSessions.map((session, idx) => {
|
||||
const isNewIP = !isValueSeenBefore(
|
||||
session.ipAddress,
|
||||
violation.userHistory?.previousIPs || []
|
||||
);
|
||||
const isNewDevice = !isValueSeenBefore(
|
||||
session.deviceId || session.device,
|
||||
violation.userHistory?.previousDevices || []
|
||||
);
|
||||
const isNewLocation = !isLocationSeenBefore(
|
||||
session.geoCity,
|
||||
session.geoCountry,
|
||||
violation.userHistory?.previousLocations || []
|
||||
);
|
||||
const isTriggering = idx === 0 && violation.session?.id === session.id;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={session.id}
|
||||
className={`border rounded-lg p-3 ${
|
||||
isTriggering ? 'bg-muted/30 border-primary/50' : 'bg-background'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<p className="text-xs font-medium text-muted-foreground">
|
||||
{isTriggering ? 'Triggering Stream' : `Stream #${idx + 1}`}
|
||||
</p>
|
||||
{isTriggering && (
|
||||
<span className="text-xs bg-primary/20 text-primary px-1.5 py-0.5 rounded">
|
||||
Primary
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm font-medium truncate">
|
||||
{session.mediaTitle}
|
||||
{session.grandparentTitle && (
|
||||
<span className="text-muted-foreground">
|
||||
{' '}• {session.grandparentTitle}
|
||||
</span>
|
||||
)}
|
||||
{session.seasonNumber && session.episodeNumber && (
|
||||
<span className="text-muted-foreground">
|
||||
{' '}• S{session.seasonNumber}E{session.episodeNumber}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground capitalize">
|
||||
{session.mediaType}
|
||||
{session.quality && ` • ${session.quality}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Comparison Grid */}
|
||||
<div className="grid grid-cols-2 gap-3 text-xs">
|
||||
{/* IP Address */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<p className="text-muted-foreground">IP Address</p>
|
||||
{isNewIP ? (
|
||||
<AlertCircle className="h-3 w-3 text-yellow-600" />
|
||||
) : (
|
||||
<CheckCircle2 className="h-3 w-3 text-green-600" />
|
||||
)}
|
||||
</div>
|
||||
<p className="font-mono font-medium">{session.ipAddress}</p>
|
||||
{isNewIP && (
|
||||
<p className="text-yellow-600 text-[10px] mt-0.5">⚠️ First time seen</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Location */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<p className="text-muted-foreground">Location</p>
|
||||
{isNewLocation ? (
|
||||
<AlertCircle className="h-3 w-3 text-red-600" />
|
||||
) : (
|
||||
<CheckCircle2 className="h-3 w-3 text-green-600" />
|
||||
)}
|
||||
</div>
|
||||
<p className="font-medium">
|
||||
{session.geoCity && `${session.geoCity}, `}
|
||||
{session.geoRegion && `${session.geoRegion}, `}
|
||||
{session.geoCountry || 'Unknown'}
|
||||
</p>
|
||||
{isNewLocation && (
|
||||
<p className="text-red-600 text-[10px] mt-0.5">⚠️ First time seen</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Device */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<p className="text-muted-foreground">Device</p>
|
||||
{isNewDevice ? (
|
||||
<AlertCircle className="h-3 w-3 text-orange-600" />
|
||||
) : (
|
||||
<CheckCircle2 className="h-3 w-3 text-green-600" />
|
||||
)}
|
||||
</div>
|
||||
<p className="font-medium">
|
||||
{session.device || session.deviceId || 'Unknown'}
|
||||
{session.playerName && ` (${session.playerName})`}
|
||||
</p>
|
||||
{isNewDevice && (
|
||||
<p className="text-orange-600 text-[10px] mt-0.5">⚠️ First time seen</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Platform */}
|
||||
<div>
|
||||
<p className="text-muted-foreground mb-1">Platform</p>
|
||||
<p className="font-medium">
|
||||
{session.platform || 'Unknown'}
|
||||
{session.product && ` • ${session.product}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground mt-2">
|
||||
Started {formatDistanceToNow(new Date(session.startedAt), { addSuffix: true })}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Location Information - Only show if comparison view is NOT shown (info is already in comparison view) */}
|
||||
{allSessions.length === 0 &&
|
||||
violation.session &&
|
||||
!violation.relatedSessions?.length &&
|
||||
(violation.session.ipAddress || violation.session.geoCity || violation.session.geoCountry) && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium text-muted-foreground flex items-center gap-2">
|
||||
<MapPin className="h-4 w-4" />
|
||||
Location
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{violation.session.ipAddress && (
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">IP Address</p>
|
||||
<p className="text-sm font-medium font-mono">{violation.session.ipAddress}</p>
|
||||
</div>
|
||||
)}
|
||||
{(violation.session.geoCity || violation.session.geoCountry) && (
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">Location</p>
|
||||
<p className="text-sm font-medium">
|
||||
{violation.session.geoCity && `${violation.session.geoCity}, `}
|
||||
{violation.session.geoRegion && `${violation.session.geoRegion}, `}
|
||||
{violation.session.geoCountry || 'Unknown'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{violation.session.geoLat && violation.session.geoLon && (
|
||||
<div className="col-span-2">
|
||||
<p className="text-xs text-muted-foreground mb-1">Coordinates</p>
|
||||
<p className="text-sm font-medium font-mono">
|
||||
{violation.session.geoLat.toFixed(4)}, {violation.session.geoLon.toFixed(4)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Device Information - Only show if comparison view is NOT shown (info is already in comparison view) */}
|
||||
{allSessions.length === 0 &&
|
||||
violation.session &&
|
||||
!violation.relatedSessions?.length &&
|
||||
(violation.session.playerName || violation.session.device || violation.session.platform) && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium text-muted-foreground flex items-center gap-2">
|
||||
<Monitor className="h-4 w-4" />
|
||||
Device & Platform
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{violation.session.playerName && (
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">Player</p>
|
||||
<p className="text-sm font-medium">{violation.session.playerName}</p>
|
||||
</div>
|
||||
)}
|
||||
{violation.session.device && (
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">Device</p>
|
||||
<p className="text-sm font-medium">{violation.session.device}</p>
|
||||
</div>
|
||||
)}
|
||||
{violation.session.platform && (
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">Platform</p>
|
||||
<p className="text-sm font-medium">{violation.session.platform}</p>
|
||||
</div>
|
||||
)}
|
||||
{violation.session.product && (
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">Product</p>
|
||||
<p className="text-sm font-medium">{violation.session.product}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Additional Violation Details */}
|
||||
{Object.keys(details).length > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium text-muted-foreground">Violation Details</h4>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{Object.entries(details).map(([key, value]) => {
|
||||
// Handle array values (like locations or IP addresses)
|
||||
if (Array.isArray(value)) {
|
||||
return (
|
||||
<div key={key} className="col-span-2">
|
||||
<p className="text-xs text-muted-foreground mb-1">{key}</p>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{value.map((item, idx) => (
|
||||
<span
|
||||
key={idx}
|
||||
className="inline-flex items-center rounded-md bg-muted px-2 py-1 text-xs font-medium"
|
||||
>
|
||||
{String(item)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div key={key}>
|
||||
<p className="text-xs text-muted-foreground mb-1">{key}</p>
|
||||
<p className="text-sm font-medium">{String(value)}</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Timestamp */}
|
||||
<Separator />
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Clock className="h-4 w-4" />
|
||||
<span>
|
||||
Created {formatDistanceToNow(new Date(violation.createdAt), { addSuffix: true })}
|
||||
</span>
|
||||
<span className="mx-2">•</span>
|
||||
<span>{format(new Date(violation.createdAt), 'PPpp')}</span>
|
||||
</div>
|
||||
|
||||
{violation.acknowledgedAt && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
<span>
|
||||
Acknowledged {formatDistanceToNow(new Date(violation.acknowledgedAt), { addSuffix: true })}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex-row justify-end gap-2 sm:justify-end">
|
||||
{isPending && (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={handleAcknowledge}
|
||||
disabled={isAcknowledging}
|
||||
>
|
||||
<Check className="mr-2 h-4 w-4" />
|
||||
{isAcknowledging ? 'Acknowledging...' : 'Acknowledge'}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDismiss}
|
||||
disabled={isDismissing}
|
||||
>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
{isDismissing ? 'Dismissing...' : 'Dismiss'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
11
apps/web/src/hooks/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
// Auth
|
||||
export { AuthProvider, useAuth, useRequireAuth } from './useAuth';
|
||||
|
||||
// Socket
|
||||
export { SocketProvider, useSocket } from './useSocket';
|
||||
|
||||
// Progress estimation
|
||||
export { useEstimatedProgress } from './useEstimatedProgress';
|
||||
|
||||
// React Query hooks
|
||||
export * from './queries';
|
||||
73
apps/web/src/hooks/queries/index.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
// Stats hooks
|
||||
export {
|
||||
useDashboardStats,
|
||||
usePlaysStats,
|
||||
useUserStats,
|
||||
useLocationStats,
|
||||
usePlaysByDayOfWeek,
|
||||
usePlaysByHourOfDay,
|
||||
usePlatformStats,
|
||||
useQualityStats,
|
||||
useTopUsers,
|
||||
useTopContent,
|
||||
useConcurrentStats,
|
||||
type LocationStatsFilters,
|
||||
type StatsTimeRange,
|
||||
} from './useStats';
|
||||
|
||||
// Session hooks
|
||||
export { useSessions, useActiveSessions, useSession } from './useSessions';
|
||||
export { useTerminateSession } from './useTerminateSession';
|
||||
|
||||
// User hooks
|
||||
export {
|
||||
useUsers,
|
||||
useUser,
|
||||
useUserFull,
|
||||
useUserSessions,
|
||||
useUpdateUser,
|
||||
useUpdateUserIdentity,
|
||||
useUserLocations,
|
||||
useUserDevices,
|
||||
useUserTerminations,
|
||||
} from './useUsers';
|
||||
|
||||
// Rule hooks
|
||||
export {
|
||||
useRules,
|
||||
useCreateRule,
|
||||
useUpdateRule,
|
||||
useDeleteRule,
|
||||
useToggleRule,
|
||||
} from './useRules';
|
||||
|
||||
// Violation hooks
|
||||
export {
|
||||
useViolations,
|
||||
useAcknowledgeViolation,
|
||||
useDismissViolation,
|
||||
} from './useViolations';
|
||||
|
||||
// Server hooks
|
||||
export {
|
||||
useServers,
|
||||
useCreateServer,
|
||||
useDeleteServer,
|
||||
useSyncServer,
|
||||
} from './useServers';
|
||||
|
||||
// Settings hooks
|
||||
export { useSettings, useUpdateSettings } from './useSettings';
|
||||
|
||||
// Channel Routing hooks
|
||||
export { useChannelRouting, useUpdateChannelRouting } from './useChannelRouting';
|
||||
|
||||
// Mobile hooks
|
||||
export {
|
||||
useMobileConfig,
|
||||
useEnableMobile,
|
||||
useDisableMobile,
|
||||
useGeneratePairToken,
|
||||
useRevokeSession,
|
||||
useRevokeMobileSessions,
|
||||
} from './useMobile';
|
||||
61
apps/web/src/hooks/queries/useChannelRouting.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import type { NotificationChannelRouting, NotificationEventType } from '@tracearr/shared';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
export function useChannelRouting() {
|
||||
return useQuery({
|
||||
queryKey: ['channelRouting'],
|
||||
queryFn: api.channelRouting.getAll,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateChannelRouting() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
eventType,
|
||||
...data
|
||||
}: {
|
||||
eventType: NotificationEventType;
|
||||
discordEnabled?: boolean;
|
||||
webhookEnabled?: boolean;
|
||||
webToastEnabled?: boolean;
|
||||
}) => api.channelRouting.update(eventType, data),
|
||||
onMutate: async ({ eventType, discordEnabled, webhookEnabled, webToastEnabled }) => {
|
||||
// Cancel outgoing refetches
|
||||
await queryClient.cancelQueries({ queryKey: ['channelRouting'] });
|
||||
|
||||
// Snapshot the previous value
|
||||
const previousRouting = queryClient.getQueryData<NotificationChannelRouting[]>(['channelRouting']);
|
||||
|
||||
// Optimistically update
|
||||
queryClient.setQueryData<NotificationChannelRouting[]>(['channelRouting'], (old) => {
|
||||
if (!old) return old;
|
||||
return old.map((routing) => {
|
||||
if (routing.eventType !== eventType) return routing;
|
||||
return {
|
||||
...routing,
|
||||
...(discordEnabled !== undefined && { discordEnabled }),
|
||||
...(webhookEnabled !== undefined && { webhookEnabled }),
|
||||
...(webToastEnabled !== undefined && { webToastEnabled }),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
return { previousRouting };
|
||||
},
|
||||
onError: (err, _variables, context) => {
|
||||
// Rollback on error
|
||||
if (context?.previousRouting) {
|
||||
queryClient.setQueryData(['channelRouting'], context.previousRouting);
|
||||
}
|
||||
toast.error('Failed to Update Routing', { description: err.message });
|
||||
},
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['channelRouting'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
93
apps/web/src/hooks/queries/useMobile.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import type { MobileConfig } from '@tracearr/shared';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
export function useMobileConfig() {
|
||||
return useQuery({
|
||||
queryKey: ['mobile', 'config'],
|
||||
queryFn: api.mobile.get,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useEnableMobile() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: api.mobile.enable,
|
||||
onSuccess: (data) => {
|
||||
queryClient.setQueryData<MobileConfig>(['mobile', 'config'], data);
|
||||
toast.success('Mobile Access Enabled', { description: 'Scan the QR code with the Tracearr mobile app to connect.' });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error('Failed to Enable Mobile Access', { description: err.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDisableMobile() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: api.mobile.disable,
|
||||
onSuccess: () => {
|
||||
queryClient.setQueryData<MobileConfig>(['mobile', 'config'], (old) => {
|
||||
if (!old) return old;
|
||||
return { ...old, isEnabled: false, token: null, sessions: [] };
|
||||
});
|
||||
toast.success('Mobile Access Disabled', { description: 'All mobile sessions have been revoked.' });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error('Failed to Disable Mobile Access', { description: err.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useGeneratePairToken() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: api.mobile.generatePairToken,
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['mobile', 'config'] });
|
||||
toast.success('Pair Token Generated', { description: 'Scan the QR code with your mobile device to pair.' });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error('Failed to Generate Pair Token', { description: err.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useRevokeSession() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (sessionId: string) => api.mobile.revokeSession(sessionId),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['mobile', 'config'] });
|
||||
toast.success('Device Removed', { description: 'The device has been disconnected.' });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error('Failed to Remove Device', { description: err.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useRevokeMobileSessions() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: api.mobile.revokeSessions,
|
||||
onSuccess: (data) => {
|
||||
queryClient.setQueryData<MobileConfig>(['mobile', 'config'], (old) => {
|
||||
if (!old) return old;
|
||||
return { ...old, sessions: [] };
|
||||
});
|
||||
toast.success('Sessions Revoked', { description: `${data.revokedCount} mobile session(s) have been revoked.` });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error('Failed to Revoke Sessions', { description: err.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
94
apps/web/src/hooks/queries/useRules.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import type { Rule } from '@tracearr/shared';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
export function useRules() {
|
||||
return useQuery({
|
||||
queryKey: ['rules', 'list'],
|
||||
queryFn: api.rules.list,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateRule() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: Omit<Rule, 'id' | 'createdAt' | 'updatedAt'>) =>
|
||||
api.rules.create(data),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['rules', 'list'] });
|
||||
toast.success('Rule Created', { description: 'The rule has been created successfully.' });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to Create Rule', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateRule() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, data }: { id: string; data: Partial<Rule> }) =>
|
||||
api.rules.update(id, data),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['rules', 'list'] });
|
||||
toast.success('Rule Updated', { description: 'The rule has been updated successfully.' });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to Update Rule', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteRule() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.rules.delete(id),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['rules', 'list'] });
|
||||
toast.success('Rule Deleted', { description: 'The rule has been deleted successfully.' });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to Delete Rule', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useToggleRule() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, isActive }: { id: string; isActive: boolean }) =>
|
||||
api.rules.update(id, { isActive }),
|
||||
onMutate: async ({ id, isActive }) => {
|
||||
// Cancel outgoing refetches
|
||||
await queryClient.cancelQueries({ queryKey: ['rules', 'list'] });
|
||||
|
||||
// Snapshot the previous value
|
||||
const previousRules = queryClient.getQueryData<Rule[]>(['rules', 'list']);
|
||||
|
||||
// Optimistically update to the new value
|
||||
queryClient.setQueryData<Rule[]>(['rules', 'list'], (old) => {
|
||||
if (!old) return [];
|
||||
return old.map((rule) =>
|
||||
rule.id === id ? { ...rule, isActive } : rule
|
||||
);
|
||||
});
|
||||
|
||||
return { previousRules };
|
||||
},
|
||||
onError: (err, variables, context) => {
|
||||
// Rollback on error
|
||||
if (context?.previousRules) {
|
||||
queryClient.setQueryData(['rules', 'list'], context.previousRules);
|
||||
}
|
||||
},
|
||||
onSettled: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['rules', 'list'] });
|
||||
},
|
||||
});
|
||||
}
|
||||