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
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
This commit is contained in:
66
apps/web/src/App.tsx
Normal file
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
162
apps/web/src/hooks/queries/useServers.ts
Normal file
162
apps/web/src/hooks/queries/useServers.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { SERVER_STATS_CONFIG, type ServerResourceDataPoint } from '@tracearr/shared';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
import { useRef, useCallback } from 'react';
|
||||
|
||||
export function useServers() {
|
||||
return useQuery({
|
||||
queryKey: ['servers', 'list'],
|
||||
queryFn: api.servers.list,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateServer() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: { name: string; type: string; url: string; token: string }) =>
|
||||
api.servers.create(data),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['servers', 'list'] });
|
||||
toast.success('Server Added', { description: 'The server has been added successfully.' });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to Add Server', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteServer() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.servers.delete(id),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['servers', 'list'] });
|
||||
toast.success('Server Removed', { description: 'The server has been removed successfully.' });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to Remove Server', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSyncServer() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.servers.sync(id),
|
||||
onSuccess: (data) => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['servers', 'list'] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['users', 'list'] });
|
||||
|
||||
// Show detailed results
|
||||
const parts: string[] = [];
|
||||
if (data.usersAdded > 0) parts.push(`${data.usersAdded} users added`);
|
||||
if (data.usersUpdated > 0) parts.push(`${data.usersUpdated} users updated`);
|
||||
if (data.librariesSynced > 0) parts.push(`${data.librariesSynced} libraries`);
|
||||
if (data.errors.length > 0) parts.push(`${data.errors.length} errors`);
|
||||
|
||||
const description = parts.length > 0
|
||||
? parts.join(', ')
|
||||
: 'No changes detected';
|
||||
|
||||
if (data.errors.length > 0) {
|
||||
toast.warning(data.success ? 'Sync Completed with Errors' : 'Sync Completed with Errors', { description });
|
||||
// Log errors to console for debugging
|
||||
console.error('Sync errors:', data.errors);
|
||||
} else {
|
||||
toast.success('Server Synced', { description });
|
||||
}
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Sync Failed', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for fetching server resource statistics with fixed 2-minute window
|
||||
* Polls every 10 seconds, displays last 2 minutes of data (12 points)
|
||||
* X-axis is static (2m → NOW), data slides through as new points arrive
|
||||
*
|
||||
* @param serverId - Server ID to fetch stats for
|
||||
* @param enabled - Whether polling is enabled (typically tied to component mount)
|
||||
*/
|
||||
export function useServerStatistics(serverId: string | undefined, enabled: boolean = true) {
|
||||
// Accumulate data points across polls, keyed by timestamp for deduplication
|
||||
const dataMapRef = useRef<Map<number, ServerResourceDataPoint>>(new Map());
|
||||
|
||||
// Merge new data with existing, keep most recent DATA_POINTS
|
||||
const mergeData = useCallback((newData: ServerResourceDataPoint[]) => {
|
||||
const map = dataMapRef.current;
|
||||
|
||||
// Add/update data points
|
||||
for (const point of newData) {
|
||||
map.set(point.at, point);
|
||||
}
|
||||
|
||||
// Sort by timestamp descending (newest first), keep DATA_POINTS
|
||||
const sorted = Array.from(map.values())
|
||||
.sort((a, b) => b.at - a.at)
|
||||
.slice(0, SERVER_STATS_CONFIG.DATA_POINTS);
|
||||
|
||||
// Rebuild map with only kept points
|
||||
dataMapRef.current = new Map(sorted.map((p) => [p.at, p]));
|
||||
|
||||
// Return in ascending order (oldest first) for chart rendering
|
||||
return sorted.reverse();
|
||||
}, []);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['servers', 'statistics', serverId],
|
||||
queryFn: async () => {
|
||||
if (!serverId) throw new Error('Server ID required');
|
||||
const response = await api.servers.statistics(serverId);
|
||||
// Merge with accumulated data
|
||||
const mergedData = mergeData(response.data);
|
||||
return {
|
||||
...response,
|
||||
data: mergedData,
|
||||
};
|
||||
},
|
||||
enabled: enabled && !!serverId,
|
||||
// Poll every 10 seconds
|
||||
refetchInterval: SERVER_STATS_CONFIG.POLL_INTERVAL_SECONDS * 1000,
|
||||
// Don't poll when tab is hidden
|
||||
refetchIntervalInBackground: false,
|
||||
// Don't refetch on window focus (we have interval polling)
|
||||
refetchOnWindowFocus: false,
|
||||
// Keep previous data while fetching new
|
||||
placeholderData: (prev) => prev,
|
||||
// Data is fresh until next poll
|
||||
staleTime: (SERVER_STATS_CONFIG.POLL_INTERVAL_SECONDS * 1000) - 500,
|
||||
});
|
||||
|
||||
// Calculate averages from windowed data
|
||||
const dataPoints = query.data?.data as ServerResourceDataPoint[] | undefined;
|
||||
const dataLength = dataPoints?.length ?? 0;
|
||||
const averages = dataPoints && dataLength > 0
|
||||
? {
|
||||
hostCpu: Math.round(
|
||||
dataPoints.reduce((sum: number, p) => sum + p.hostCpuUtilization, 0) / dataLength
|
||||
),
|
||||
processCpu: Math.round(
|
||||
dataPoints.reduce((sum: number, p) => sum + p.processCpuUtilization, 0) / dataLength
|
||||
),
|
||||
hostMemory: Math.round(
|
||||
dataPoints.reduce((sum: number, p) => sum + p.hostMemoryUtilization, 0) / dataLength
|
||||
),
|
||||
processMemory: Math.round(
|
||||
dataPoints.reduce((sum: number, p) => sum + p.processMemoryUtilization, 0) / dataLength
|
||||
),
|
||||
}
|
||||
: null;
|
||||
|
||||
return {
|
||||
...query,
|
||||
averages,
|
||||
};
|
||||
}
|
||||
37
apps/web/src/hooks/queries/useSessions.ts
Normal file
37
apps/web/src/hooks/queries/useSessions.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import '@tracearr/shared';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
interface SessionsParams {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
userId?: string;
|
||||
serverId?: string;
|
||||
state?: string;
|
||||
}
|
||||
|
||||
export function useSessions(params: SessionsParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: ['sessions', 'list', params],
|
||||
queryFn: () => api.sessions.list(params),
|
||||
staleTime: 1000 * 30, // 30 seconds
|
||||
});
|
||||
}
|
||||
|
||||
export function useActiveSessions(serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['sessions', 'active', serverId],
|
||||
queryFn: () => api.sessions.getActive(serverId ?? undefined),
|
||||
staleTime: 1000 * 15, // 15 seconds
|
||||
refetchInterval: 1000 * 30, // 30 seconds
|
||||
});
|
||||
}
|
||||
|
||||
export function useSession(id: string) {
|
||||
return useQuery({
|
||||
queryKey: ['sessions', 'detail', id],
|
||||
queryFn: () => api.sessions.get(id),
|
||||
enabled: !!id,
|
||||
staleTime: 1000 * 60, // 1 minute
|
||||
});
|
||||
}
|
||||
46
apps/web/src/hooks/queries/useSettings.ts
Normal file
46
apps/web/src/hooks/queries/useSettings.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import type { Settings } from '@tracearr/shared';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
export function useSettings() {
|
||||
return useQuery({
|
||||
queryKey: ['settings'],
|
||||
queryFn: api.settings.get,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateSettings() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: Partial<Settings>) => api.settings.update(data),
|
||||
onMutate: async (newSettings) => {
|
||||
// Cancel outgoing refetches
|
||||
await queryClient.cancelQueries({ queryKey: ['settings'] });
|
||||
|
||||
// Snapshot the previous value
|
||||
const previousSettings = queryClient.getQueryData<Settings>(['settings']);
|
||||
|
||||
// Optimistically update to the new value
|
||||
queryClient.setQueryData<Settings>(['settings'], (old) => {
|
||||
if (!old) return old;
|
||||
return { ...old, ...newSettings };
|
||||
});
|
||||
|
||||
return { previousSettings };
|
||||
},
|
||||
onError: (err, newSettings, context) => {
|
||||
// Rollback on error
|
||||
if (context?.previousSettings) {
|
||||
queryClient.setQueryData(['settings'], context.previousSettings);
|
||||
}
|
||||
toast.error('Failed to Update Settings', { description: (err).message });
|
||||
},
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['settings'] });
|
||||
toast.success('Settings Updated', { description: 'Your settings have been saved.' });
|
||||
},
|
||||
});
|
||||
}
|
||||
102
apps/web/src/hooks/queries/useStats.ts
Normal file
102
apps/web/src/hooks/queries/useStats.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import '@tracearr/shared';
|
||||
import { api, type StatsTimeRange } from '@/lib/api';
|
||||
|
||||
// Re-export for backwards compatibility and convenience
|
||||
export type { StatsTimeRange };
|
||||
|
||||
export function useDashboardStats(serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'dashboard', serverId],
|
||||
queryFn: () => api.stats.dashboard(serverId ?? undefined),
|
||||
staleTime: 1000 * 30, // 30 seconds
|
||||
refetchInterval: 1000 * 60, // 1 minute
|
||||
});
|
||||
}
|
||||
|
||||
export function usePlaysStats(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'plays', timeRange, serverId],
|
||||
queryFn: () => api.stats.plays(timeRange ?? { period: 'week' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserStats(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'users', timeRange, serverId],
|
||||
queryFn: () => api.stats.users(timeRange ?? { period: 'month' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export interface LocationStatsFilters {
|
||||
timeRange?: StatsTimeRange;
|
||||
serverUserId?: string;
|
||||
serverId?: string;
|
||||
mediaType?: 'movie' | 'episode' | 'track';
|
||||
}
|
||||
|
||||
export function useLocationStats(filters?: LocationStatsFilters) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'locations', filters],
|
||||
queryFn: () => api.stats.locations(filters),
|
||||
staleTime: 1000 * 60, // 1 minute
|
||||
});
|
||||
}
|
||||
|
||||
export function usePlaysByDayOfWeek(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'plays-by-dayofweek', timeRange, serverId],
|
||||
queryFn: () => api.stats.playsByDayOfWeek(timeRange ?? { period: 'month' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function usePlaysByHourOfDay(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'plays-by-hourofday', timeRange, serverId],
|
||||
queryFn: () => api.stats.playsByHourOfDay(timeRange ?? { period: 'month' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function usePlatformStats(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'platforms', timeRange, serverId],
|
||||
queryFn: () => api.stats.platforms(timeRange ?? { period: 'month' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useQualityStats(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'quality', timeRange, serverId],
|
||||
queryFn: () => api.stats.quality(timeRange ?? { period: 'month' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useTopUsers(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'top-users', timeRange, serverId],
|
||||
queryFn: () => api.stats.topUsers(timeRange ?? { period: 'month' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useTopContent(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'top-content', timeRange, serverId],
|
||||
queryFn: () => api.stats.topContent(timeRange ?? { period: 'month' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useConcurrentStats(timeRange?: StatsTimeRange, serverId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['stats', 'concurrent', timeRange, serverId],
|
||||
queryFn: () => api.stats.concurrent(timeRange ?? { period: 'month' }, serverId ?? undefined),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
23
apps/web/src/hooks/queries/useTerminateSession.ts
Normal file
23
apps/web/src/hooks/queries/useTerminateSession.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
/**
|
||||
* Mutation hook for terminating an active streaming session
|
||||
* Invalidates active sessions cache on success
|
||||
*/
|
||||
export function useTerminateSession() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ sessionId, reason }: { sessionId: string; reason?: string }) =>
|
||||
api.sessions.terminate(sessionId, reason),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['sessions', 'active'] });
|
||||
toast.success('Stream Terminated', { description: 'The playback session has been stopped.' });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to Terminate', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
102
apps/web/src/hooks/queries/useUsers.ts
Normal file
102
apps/web/src/hooks/queries/useUsers.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
export function useUsers(params: { page?: number; pageSize?: number; serverId?: string } = {}) {
|
||||
return useQuery({
|
||||
queryKey: ['users', 'list', params],
|
||||
queryFn: () => api.users.list(params),
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useUser(id: string) {
|
||||
return useQuery({
|
||||
queryKey: ['users', 'detail', id],
|
||||
queryFn: () => api.users.get(id),
|
||||
enabled: !!id,
|
||||
staleTime: 1000 * 60, // 1 minute
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate endpoint that fetches all user data in one request.
|
||||
* Use this for the UserDetail page instead of multiple separate queries.
|
||||
* Reduces 6 API calls to 1, significantly improving load time.
|
||||
*/
|
||||
export function useUserFull(id: string) {
|
||||
return useQuery({
|
||||
queryKey: ['users', 'full', id],
|
||||
queryFn: () => api.users.getFull(id),
|
||||
enabled: !!id,
|
||||
staleTime: 1000 * 60, // 1 minute
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserSessions(id: string, params: { page?: number; pageSize?: number } = {}) {
|
||||
return useQuery({
|
||||
queryKey: ['users', 'sessions', id, params],
|
||||
queryFn: () => api.users.sessions(id, params),
|
||||
enabled: !!id,
|
||||
staleTime: 1000 * 60, // 1 minute
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateUser() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, data }: { id: string; data: { trustScore?: number } }) =>
|
||||
api.users.update(id, data),
|
||||
onSuccess: (data, variables) => {
|
||||
// Update user in cache
|
||||
queryClient.setQueryData(['users', 'detail', variables.id], data);
|
||||
// Invalidate users list
|
||||
void queryClient.invalidateQueries({ queryKey: ['users', 'list'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateUserIdentity() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, name }: { id: string; name: string | null }) =>
|
||||
api.users.updateIdentity(id, { name }),
|
||||
onSuccess: (_, variables) => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['users', 'full', variables.id] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['users', 'list'] });
|
||||
toast.success('Display Name Updated');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to Update', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserLocations(id: string) {
|
||||
return useQuery({
|
||||
queryKey: ['users', 'locations', id],
|
||||
queryFn: () => api.users.locations(id),
|
||||
enabled: !!id,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserDevices(id: string) {
|
||||
return useQuery({
|
||||
queryKey: ['users', 'devices', id],
|
||||
queryFn: () => api.users.devices(id),
|
||||
enabled: !!id,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserTerminations(id: string, params: { page?: number; pageSize?: number } = {}) {
|
||||
return useQuery({
|
||||
queryKey: ['users', 'terminations', id, params],
|
||||
queryFn: () => api.users.terminations(id, params),
|
||||
enabled: !!id,
|
||||
staleTime: 1000 * 60, // 1 minute
|
||||
});
|
||||
}
|
||||
83
apps/web/src/hooks/queries/useViolations.ts
Normal file
83
apps/web/src/hooks/queries/useViolations.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import type { ViolationWithDetails, PaginatedResponse, ViolationSeverity } from '@tracearr/shared';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
interface ViolationsParams {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
userId?: string;
|
||||
severity?: ViolationSeverity;
|
||||
acknowledged?: boolean;
|
||||
serverId?: string;
|
||||
}
|
||||
|
||||
export function useViolations(params: ViolationsParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: ['violations', 'list', params],
|
||||
queryFn: () => api.violations.list(params),
|
||||
staleTime: 1000 * 30, // 30 seconds
|
||||
});
|
||||
}
|
||||
|
||||
export function useAcknowledgeViolation() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.violations.acknowledge(id),
|
||||
onMutate: async (id) => {
|
||||
// Optimistic update
|
||||
await queryClient.cancelQueries({ queryKey: ['violations', 'list'] });
|
||||
|
||||
const previousData = queryClient.getQueriesData<PaginatedResponse<ViolationWithDetails>>({
|
||||
queryKey: ['violations', 'list'],
|
||||
});
|
||||
|
||||
// Update all matching queries
|
||||
queryClient.setQueriesData<PaginatedResponse<ViolationWithDetails>>(
|
||||
{ queryKey: ['violations', 'list'] },
|
||||
(old) => {
|
||||
if (!old) return old;
|
||||
return {
|
||||
...old,
|
||||
data: old.data.map((v) =>
|
||||
v.id === id ? { ...v, acknowledgedAt: new Date() } : v
|
||||
),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
return { previousData };
|
||||
},
|
||||
onError: (err, id, context) => {
|
||||
// Rollback on error
|
||||
if (context?.previousData) {
|
||||
for (const [queryKey, data] of context.previousData) {
|
||||
queryClient.setQueryData(queryKey, data);
|
||||
}
|
||||
}
|
||||
toast.error('Failed to Acknowledge', { description: (err).message });
|
||||
},
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['violations'] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['stats', 'dashboard'] });
|
||||
toast.success('Violation Acknowledged', { description: 'The violation has been marked as acknowledged.' });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDismissViolation() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.violations.dismiss(id),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['violations'] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['stats', 'dashboard'] });
|
||||
toast.success('Violation Dismissed', { description: 'The violation has been dismissed.' });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error('Failed to Dismiss', { description: error.message });
|
||||
},
|
||||
});
|
||||
}
|
||||
19
apps/web/src/hooks/use-mobile.ts
Normal file
19
apps/web/src/hooks/use-mobile.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
}
|
||||
174
apps/web/src/hooks/useAuth.tsx
Normal file
174
apps/web/src/hooks/useAuth.tsx
Normal file
@@ -0,0 +1,174 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useEffect,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import type { AuthUser } from '@tracearr/shared';
|
||||
import { api, tokenStorage, AUTH_STATE_CHANGE_EVENT } from '@/lib/api';
|
||||
|
||||
interface UserProfile extends AuthUser {
|
||||
email: string | null;
|
||||
thumbUrl: string | null;
|
||||
trustScore: number;
|
||||
hasPassword?: boolean;
|
||||
hasPlexLinked?: boolean;
|
||||
}
|
||||
|
||||
interface AuthContextValue {
|
||||
user: UserProfile | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
logout: () => Promise<void>;
|
||||
refetch: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const {
|
||||
data: userData,
|
||||
isLoading,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: ['auth', 'me'],
|
||||
queryFn: async () => {
|
||||
// Don't even try if no token
|
||||
if (!tokenStorage.getAccessToken()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const user = await api.auth.me();
|
||||
// Return full user profile including thumbUrl
|
||||
return {
|
||||
userId: user.userId ?? user.id ?? '',
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
serverIds: user.serverIds ?? (user.serverId ? [user.serverId] : []),
|
||||
email: user.email ?? null,
|
||||
thumbUrl: user.thumbnail ?? user.thumbUrl ?? null,
|
||||
trustScore: user.aggregateTrustScore ?? user.trustScore ?? 100,
|
||||
hasPassword: user.hasPassword,
|
||||
hasPlexLinked: user.hasPlexLinked,
|
||||
} as UserProfile;
|
||||
} catch {
|
||||
// Don't clear tokens on network errors (e.g., server restart)
|
||||
// The API layer already clears tokens on real auth failures (401 + failed refresh)
|
||||
// Just return null to indicate "not currently authenticated"
|
||||
return null;
|
||||
}
|
||||
},
|
||||
// Retry configuration following AWS best practices:
|
||||
// - 3 retries (industry standard)
|
||||
// - Exponential backoff with full jitter to prevent thundering herd
|
||||
// - Cap at 10s to prevent excessively long waits
|
||||
// - Only retry on network errors, not on 4xx auth errors (handled by API layer)
|
||||
retry: (failureCount, error) => {
|
||||
// Don't retry on auth errors (4xx) - API layer handles token refresh
|
||||
// Only retry on network errors (TypeError: fetch failed, etc.)
|
||||
if (error instanceof Error && error.message.includes('401')) return false;
|
||||
if (error instanceof Error && error.message.includes('403')) return false;
|
||||
return failureCount < 3;
|
||||
},
|
||||
// Full jitter: random(0, min(cap, base * 2^attempt))
|
||||
// This spreads out retries to prevent all clients hitting server at once
|
||||
retryDelay: (attemptIndex) => {
|
||||
const baseDelay = 1000;
|
||||
const maxDelay = 10000;
|
||||
const exponentialDelay = Math.min(maxDelay, baseDelay * 2 ** attemptIndex);
|
||||
// Full jitter - random value between 0 and the exponential delay
|
||||
return Math.random() * exponentialDelay;
|
||||
},
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
// Auto-refetch when network reconnects (handles stale tabs)
|
||||
refetchOnReconnect: true,
|
||||
// Refetch when window regains focus (handles stale tabs)
|
||||
refetchOnWindowFocus: true,
|
||||
});
|
||||
|
||||
// Listen for auth state changes (e.g., token cleared due to failed refresh)
|
||||
useEffect(() => {
|
||||
const handleAuthChange = () => {
|
||||
// Immediately clear auth data and redirect to login
|
||||
queryClient.setQueryData(['auth', 'me'], null);
|
||||
queryClient.clear();
|
||||
window.location.href = '/login';
|
||||
};
|
||||
|
||||
window.addEventListener(AUTH_STATE_CHANGE_EVENT, handleAuthChange);
|
||||
return () => window.removeEventListener(AUTH_STATE_CHANGE_EVENT, handleAuthChange);
|
||||
}, [queryClient]);
|
||||
|
||||
const logoutMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
try {
|
||||
await api.auth.logout();
|
||||
} catch {
|
||||
// Ignore API errors - we're logging out anyway
|
||||
} finally {
|
||||
// Use silent mode to avoid double-redirect (we handle redirect in onSettled)
|
||||
tokenStorage.clearTokens(true);
|
||||
}
|
||||
},
|
||||
onSettled: () => {
|
||||
// Always redirect, whether success or failure
|
||||
queryClient.setQueryData(['auth', 'me'], null);
|
||||
queryClient.clear();
|
||||
window.location.href = '/login';
|
||||
},
|
||||
});
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await logoutMutation.mutateAsync();
|
||||
}, [logoutMutation]);
|
||||
|
||||
// Optimistic authentication pattern (industry standard):
|
||||
// - If we have tokens in localStorage, assume authenticated until tokens are cleared
|
||||
// - Tokens only get cleared on explicit 401/403 from the server
|
||||
// - This prevents "logout" during temporary server unavailability (restarts, network issues)
|
||||
// See: https://github.com/TanStack/query/discussions/1547
|
||||
const hasTokens = !!tokenStorage.getAccessToken();
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({
|
||||
user: userData ?? null,
|
||||
isLoading,
|
||||
// Optimistic: authenticated if we have tokens (server might just be temporarily down)
|
||||
// Only false when tokens are explicitly cleared (logout or 401/403 rejection)
|
||||
isAuthenticated: hasTokens,
|
||||
logout,
|
||||
refetch,
|
||||
}),
|
||||
[userData, isLoading, hasTokens, logout, refetch]
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth(): AuthContextValue {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
// Hook for protected routes
|
||||
export function useRequireAuth(): AuthContextValue {
|
||||
const auth = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
// isAuthenticated is now token-based (optimistic auth)
|
||||
// So this only triggers when tokens don't exist (never logged in, or explicitly logged out)
|
||||
if (!auth.isAuthenticated) {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}, [auth.isAuthenticated]);
|
||||
|
||||
return auth;
|
||||
}
|
||||
76
apps/web/src/hooks/useEstimatedProgress.ts
Normal file
76
apps/web/src/hooks/useEstimatedProgress.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import type { ActiveSession } from '@tracearr/shared';
|
||||
|
||||
/**
|
||||
* Hook that estimates playback progress client-side for smooth UI updates.
|
||||
*
|
||||
* When state is "playing", progress increments every second based on elapsed time.
|
||||
* When state is "paused" or "stopped", progress stays at last known value.
|
||||
*
|
||||
* Resets estimation when:
|
||||
* - Session ID changes
|
||||
* - Server-side progressMs changes (new data from SSE/poll)
|
||||
* - State changes
|
||||
*
|
||||
* @param session - The active session to estimate progress for
|
||||
* @returns Object with estimated progressMs and progress percentage
|
||||
*/
|
||||
export function useEstimatedProgress(session: ActiveSession) {
|
||||
const [estimatedProgressMs, setEstimatedProgressMs] = useState(session.progressMs ?? 0);
|
||||
|
||||
// Track the last known server values to detect changes
|
||||
const lastServerProgress = useRef(session.progressMs);
|
||||
const lastSessionId = useRef(session.id);
|
||||
const lastState = useRef(session.state);
|
||||
const estimationStartTime = useRef(Date.now());
|
||||
const estimationStartProgress = useRef(session.progressMs ?? 0);
|
||||
|
||||
// Reset estimation when server data changes
|
||||
useEffect(() => {
|
||||
const serverProgressChanged = session.progressMs !== lastServerProgress.current;
|
||||
const sessionChanged = session.id !== lastSessionId.current;
|
||||
const stateChanged = session.state !== lastState.current;
|
||||
|
||||
if (sessionChanged || serverProgressChanged || stateChanged) {
|
||||
// Reset to server value
|
||||
const newProgress = session.progressMs ?? 0;
|
||||
setEstimatedProgressMs(newProgress);
|
||||
|
||||
// Update refs
|
||||
lastServerProgress.current = session.progressMs;
|
||||
lastSessionId.current = session.id;
|
||||
lastState.current = session.state;
|
||||
estimationStartTime.current = Date.now();
|
||||
estimationStartProgress.current = newProgress;
|
||||
}
|
||||
}, [session.id, session.progressMs, session.state]);
|
||||
|
||||
// Tick progress when playing
|
||||
useEffect(() => {
|
||||
if (session.state !== 'playing') {
|
||||
return;
|
||||
}
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
const elapsedMs = Date.now() - estimationStartTime.current;
|
||||
const estimated = estimationStartProgress.current + elapsedMs;
|
||||
|
||||
// Cap at total duration if available
|
||||
const maxProgress = session.totalDurationMs ?? Infinity;
|
||||
setEstimatedProgressMs(Math.min(estimated, maxProgress));
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(intervalId);
|
||||
}, [session.state, session.totalDurationMs]);
|
||||
|
||||
// Calculate percentage
|
||||
const progressPercent = session.totalDurationMs
|
||||
? Math.min((estimatedProgressMs / session.totalDurationMs) * 100, 100)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
estimatedProgressMs,
|
||||
progressPercent,
|
||||
isEstimating: session.state === 'playing',
|
||||
};
|
||||
}
|
||||
142
apps/web/src/hooks/useServer.tsx
Normal file
142
apps/web/src/hooks/useServer.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useEffect,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type { Server } from '@tracearr/shared';
|
||||
import { api } from '@/lib/api';
|
||||
import { useAuth } from './useAuth';
|
||||
|
||||
// Local storage key for persisting selected server
|
||||
const SELECTED_SERVER_KEY = 'tracearr_selected_server';
|
||||
|
||||
interface ServerContextValue {
|
||||
servers: Server[];
|
||||
selectedServer: Server | null;
|
||||
selectedServerId: string | null;
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
selectServer: (serverId: string) => void;
|
||||
refetch: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
const ServerContext = createContext<ServerContextValue | null>(null);
|
||||
|
||||
export function ServerProvider({ children }: { children: ReactNode }) {
|
||||
const { isAuthenticated, user } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const [selectedServerId, setSelectedServerId] = useState<string | null>(() => {
|
||||
// Initialize from localStorage
|
||||
return localStorage.getItem(SELECTED_SERVER_KEY);
|
||||
});
|
||||
|
||||
// Fetch available servers (only when authenticated)
|
||||
const {
|
||||
data: servers = [],
|
||||
isLoading,
|
||||
isFetching,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: ['servers'],
|
||||
queryFn: () => api.servers.list(),
|
||||
enabled: isAuthenticated,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
|
||||
// Filter servers by user's accessible serverIds (non-owners only see assigned servers)
|
||||
const accessibleServers = useMemo(() => {
|
||||
if (!user) return [];
|
||||
if (user.role === 'owner') return servers;
|
||||
return servers.filter((s) => user.serverIds.includes(s.id));
|
||||
}, [servers, user]);
|
||||
|
||||
// Validate and auto-select server when servers load
|
||||
useEffect(() => {
|
||||
// Don't do anything while still loading servers or waiting for user data
|
||||
// This prevents clearing selection before we have the full picture
|
||||
if (isLoading || !user) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (accessibleServers.length === 0) {
|
||||
// No servers available after loading, clear selection
|
||||
if (selectedServerId) {
|
||||
setSelectedServerId(null);
|
||||
localStorage.removeItem(SELECTED_SERVER_KEY);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// If selected server is not in accessible list, select first available
|
||||
const currentServerValid = selectedServerId && accessibleServers.some((s) => s.id === selectedServerId);
|
||||
if (!currentServerValid) {
|
||||
const firstServer = accessibleServers[0];
|
||||
if (firstServer) {
|
||||
setSelectedServerId(firstServer.id);
|
||||
localStorage.setItem(SELECTED_SERVER_KEY, firstServer.id);
|
||||
}
|
||||
}
|
||||
}, [accessibleServers, selectedServerId, isLoading, user]);
|
||||
|
||||
// Clear selection on logout
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
setSelectedServerId(null);
|
||||
localStorage.removeItem(SELECTED_SERVER_KEY);
|
||||
}
|
||||
}, [isAuthenticated]);
|
||||
|
||||
const selectServer = useCallback((serverId: string) => {
|
||||
setSelectedServerId(serverId);
|
||||
localStorage.setItem(SELECTED_SERVER_KEY, serverId);
|
||||
// Invalidate server-dependent queries to force refetch with new server context
|
||||
// We exclude 'servers' query as that's not server-dependent
|
||||
void queryClient.invalidateQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey[0];
|
||||
// Keep server list, invalidate everything else that may be server-specific
|
||||
return key !== 'servers';
|
||||
},
|
||||
});
|
||||
}, [queryClient]);
|
||||
|
||||
// Get the full server object for the selected ID
|
||||
const selectedServer = useMemo(() => {
|
||||
if (!selectedServerId) return null;
|
||||
return accessibleServers.find((s) => s.id === selectedServerId) ?? null;
|
||||
}, [accessibleServers, selectedServerId]);
|
||||
|
||||
const value = useMemo<ServerContextValue>(
|
||||
() => ({
|
||||
servers: accessibleServers,
|
||||
selectedServer,
|
||||
selectedServerId,
|
||||
isLoading,
|
||||
isFetching,
|
||||
selectServer,
|
||||
refetch,
|
||||
}),
|
||||
[accessibleServers, selectedServer, selectedServerId, isLoading, isFetching, selectServer, refetch]
|
||||
);
|
||||
|
||||
return <ServerContext.Provider value={value}>{children}</ServerContext.Provider>;
|
||||
}
|
||||
|
||||
export function useServer(): ServerContextValue {
|
||||
const context = useContext(ServerContext);
|
||||
if (!context) {
|
||||
throw new Error('useServer must be used within a ServerProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
// Convenience hook to get just the selected server ID (common use case)
|
||||
export function useSelectedServerId(): string | null {
|
||||
const { selectedServerId } = useServer();
|
||||
return selectedServerId;
|
||||
}
|
||||
196
apps/web/src/hooks/useSocket.tsx
Normal file
196
apps/web/src/hooks/useSocket.tsx
Normal file
@@ -0,0 +1,196 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import type {
|
||||
ServerToClientEvents,
|
||||
ClientToServerEvents,
|
||||
ActiveSession,
|
||||
ViolationWithDetails,
|
||||
DashboardStats,
|
||||
NotificationChannelRouting,
|
||||
NotificationEventType,
|
||||
} from '@tracearr/shared';
|
||||
import { WS_EVENTS } from '@tracearr/shared';
|
||||
import { useAuth } from './useAuth';
|
||||
import { toast } from 'sonner';
|
||||
import { tokenStorage } from '@/lib/api';
|
||||
import { useChannelRouting } from './queries';
|
||||
|
||||
type TypedSocket = Socket<ServerToClientEvents, ClientToServerEvents>;
|
||||
|
||||
interface SocketContextValue {
|
||||
socket: TypedSocket | null;
|
||||
isConnected: boolean;
|
||||
subscribeSessions: () => void;
|
||||
unsubscribeSessions: () => void;
|
||||
}
|
||||
|
||||
const SocketContext = createContext<SocketContextValue | null>(null);
|
||||
|
||||
export function SocketProvider({ children }: { children: ReactNode }) {
|
||||
const { isAuthenticated } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const [socket, setSocket] = useState<TypedSocket | null>(null);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
|
||||
// Get channel routing for web toast preferences
|
||||
const { data: routingData } = useChannelRouting();
|
||||
|
||||
// Build a ref to the routing map for access in event handlers
|
||||
const routingMapRef = useRef<Map<NotificationEventType, NotificationChannelRouting>>(new Map());
|
||||
|
||||
// Update the ref when routing data changes
|
||||
useEffect(() => {
|
||||
const newMap = new Map<NotificationEventType, NotificationChannelRouting>();
|
||||
routingData?.forEach((r) => newMap.set(r.eventType, r));
|
||||
routingMapRef.current = newMap;
|
||||
}, [routingData]);
|
||||
|
||||
// Helper to check if web toast is enabled for an event type
|
||||
const isWebToastEnabled = useCallback((eventType: NotificationEventType): boolean => {
|
||||
const routing = routingMapRef.current.get(eventType);
|
||||
// Default to true if routing not yet loaded
|
||||
return routing?.webToastEnabled ?? true;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
if (socket) {
|
||||
socket.disconnect();
|
||||
setSocket(null);
|
||||
setIsConnected(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Get JWT token for authentication
|
||||
const token = tokenStorage.getAccessToken();
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create socket connection with auth token
|
||||
const newSocket: TypedSocket = io({
|
||||
path: '/socket.io',
|
||||
withCredentials: true,
|
||||
autoConnect: true,
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000,
|
||||
auth: {
|
||||
token,
|
||||
},
|
||||
});
|
||||
|
||||
newSocket.on('connect', () => {
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
newSocket.on('disconnect', () => {
|
||||
setIsConnected(false);
|
||||
});
|
||||
|
||||
newSocket.on('connect_error', (error) => {
|
||||
console.error('[Socket] Connection error:', error);
|
||||
});
|
||||
|
||||
// Handle real-time events
|
||||
// Note: Since users can filter by server, we invalidate all matching query patterns
|
||||
// and let react-query refetch with the appropriate server filter
|
||||
newSocket.on(WS_EVENTS.SESSION_STARTED as 'session:started', (session: ActiveSession) => {
|
||||
// Invalidate all active sessions queries (regardless of server filter)
|
||||
void queryClient.invalidateQueries({ queryKey: ['sessions', 'active'] });
|
||||
// Invalidate dashboard stats and session history
|
||||
void queryClient.invalidateQueries({ queryKey: ['stats', 'dashboard'] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['sessions', 'list'] });
|
||||
|
||||
// Show toast if web notifications are enabled for stream_started
|
||||
if (isWebToastEnabled('stream_started')) {
|
||||
toast.info('New Stream Started', {
|
||||
description: `${session.user.identityName ?? session.user.username} is watching ${session.mediaTitle}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
newSocket.on(WS_EVENTS.SESSION_STOPPED as 'session:stopped', (_sessionId: string) => {
|
||||
// Invalidate all active sessions queries (regardless of server filter)
|
||||
void queryClient.invalidateQueries({ queryKey: ['sessions', 'active'] });
|
||||
// Invalidate dashboard stats and session history (stopped session now has duration)
|
||||
void queryClient.invalidateQueries({ queryKey: ['stats', 'dashboard'] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['sessions', 'list'] });
|
||||
});
|
||||
|
||||
newSocket.on(WS_EVENTS.SESSION_UPDATED as 'session:updated', (_session: ActiveSession) => {
|
||||
// Invalidate all active sessions queries (regardless of server filter)
|
||||
void queryClient.invalidateQueries({ queryKey: ['sessions', 'active'] });
|
||||
});
|
||||
|
||||
newSocket.on(WS_EVENTS.VIOLATION_NEW as 'violation:new', (violation: ViolationWithDetails) => {
|
||||
// Invalidate violations query
|
||||
void queryClient.invalidateQueries({ queryKey: ['violations'] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['stats', 'dashboard'] });
|
||||
|
||||
// Show toast notification if web notifications are enabled for violation_detected
|
||||
if (isWebToastEnabled('violation_detected')) {
|
||||
const toastFn = violation.severity === 'high' ? toast.error : toast.warning;
|
||||
toastFn(`New Violation: ${violation.rule.name}`, {
|
||||
description: `${violation.user.identityName ?? violation.user.username} triggered ${violation.rule.type}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
newSocket.on(WS_EVENTS.STATS_UPDATED as 'stats:updated', (_stats: DashboardStats) => {
|
||||
// Invalidate all dashboard stats queries (they now have server-specific cache keys)
|
||||
void queryClient.invalidateQueries({ queryKey: ['stats', 'dashboard'] });
|
||||
});
|
||||
|
||||
setSocket(newSocket);
|
||||
|
||||
return () => {
|
||||
newSocket.disconnect();
|
||||
};
|
||||
}, [isAuthenticated, queryClient, isWebToastEnabled]);
|
||||
|
||||
const subscribeSessions = useCallback(() => {
|
||||
if (socket && isConnected) {
|
||||
socket.emit('subscribe:sessions');
|
||||
}
|
||||
}, [socket, isConnected]);
|
||||
|
||||
const unsubscribeSessions = useCallback(() => {
|
||||
if (socket && isConnected) {
|
||||
socket.emit('unsubscribe:sessions');
|
||||
}
|
||||
}, [socket, isConnected]);
|
||||
|
||||
const value = useMemo<SocketContextValue>(
|
||||
() => ({
|
||||
socket,
|
||||
isConnected,
|
||||
subscribeSessions,
|
||||
unsubscribeSessions,
|
||||
}),
|
||||
[socket, isConnected, subscribeSessions, unsubscribeSessions]
|
||||
);
|
||||
|
||||
return (
|
||||
<SocketContext.Provider value={value}>{children}</SocketContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSocket(): SocketContextValue {
|
||||
const context = useContext(SocketContext);
|
||||
if (!context) {
|
||||
throw new Error('useSocket must be used within a SocketProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
76
apps/web/src/hooks/useTimeRange.ts
Normal file
76
apps/web/src/hooks/useTimeRange.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import type { TimeRangePeriod, TimeRangeValue } from '@/components/ui/time-range-picker';
|
||||
|
||||
const DEFAULT_PERIOD: TimeRangePeriod = 'month';
|
||||
|
||||
function parseDate(dateStr: string | null): Date | undefined {
|
||||
if (!dateStr) return undefined;
|
||||
const date = new Date(dateStr);
|
||||
return isNaN(date.getTime()) ? undefined : date;
|
||||
}
|
||||
|
||||
function formatDateParam(date: Date | undefined): string | undefined {
|
||||
if (!date) return undefined;
|
||||
return date.toISOString().split('T')[0]; // YYYY-MM-DD
|
||||
}
|
||||
|
||||
export function useTimeRange() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const value = useMemo<TimeRangeValue>(() => {
|
||||
const period = (searchParams.get('period') as TimeRangePeriod) || DEFAULT_PERIOD;
|
||||
|
||||
if (period === 'custom') {
|
||||
const startDate = parseDate(searchParams.get('from'));
|
||||
const endDate = parseDate(searchParams.get('to'));
|
||||
|
||||
// If custom period but missing dates, fall back to default
|
||||
if (!startDate || !endDate) {
|
||||
return { period: DEFAULT_PERIOD };
|
||||
}
|
||||
|
||||
return { period, startDate, endDate };
|
||||
}
|
||||
|
||||
return { period };
|
||||
}, [searchParams]);
|
||||
|
||||
const setValue = useCallback(
|
||||
(newValue: TimeRangeValue) => {
|
||||
setSearchParams(
|
||||
(prev) => {
|
||||
const params = new URLSearchParams(prev);
|
||||
|
||||
params.set('period', newValue.period);
|
||||
|
||||
if (newValue.period === 'custom' && newValue.startDate && newValue.endDate) {
|
||||
params.set('from', formatDateParam(newValue.startDate)!);
|
||||
params.set('to', formatDateParam(newValue.endDate)!);
|
||||
} else {
|
||||
params.delete('from');
|
||||
params.delete('to');
|
||||
}
|
||||
|
||||
return params;
|
||||
},
|
||||
{ replace: true }
|
||||
);
|
||||
},
|
||||
[setSearchParams]
|
||||
);
|
||||
|
||||
// Helper to get API params for backend calls
|
||||
const apiParams = useMemo(() => {
|
||||
if (value.period === 'custom' && value.startDate && value.endDate) {
|
||||
return {
|
||||
period: value.period,
|
||||
startDate: value.startDate.toISOString(),
|
||||
endDate: value.endDate.toISOString(),
|
||||
};
|
||||
}
|
||||
return { period: value.period };
|
||||
}, [value]);
|
||||
|
||||
return { value, setValue, apiParams };
|
||||
}
|
||||
668
apps/web/src/lib/api.ts
Normal file
668
apps/web/src/lib/api.ts
Normal file
@@ -0,0 +1,668 @@
|
||||
import type {
|
||||
Server,
|
||||
User,
|
||||
UserRole,
|
||||
ServerUserWithIdentity,
|
||||
ServerUserDetail,
|
||||
ServerUserFullDetail,
|
||||
Session,
|
||||
SessionWithDetails,
|
||||
ActiveSession,
|
||||
Rule,
|
||||
Violation,
|
||||
ViolationWithDetails,
|
||||
DashboardStats,
|
||||
PlayStats,
|
||||
UserStats,
|
||||
TopUserStats,
|
||||
LocationStatsResponse,
|
||||
UserLocation,
|
||||
UserDevice,
|
||||
Settings,
|
||||
PaginatedResponse,
|
||||
MobileConfig,
|
||||
TerminationLogWithDetails,
|
||||
PlexDiscoveredServer,
|
||||
PlexDiscoveredConnection,
|
||||
PlexAvailableServersResponse,
|
||||
NotificationChannelRouting,
|
||||
NotificationEventType,
|
||||
} from '@tracearr/shared';
|
||||
|
||||
// Re-export shared types needed by frontend components
|
||||
export type { PlexDiscoveredServer, PlexDiscoveredConnection, PlexAvailableServersResponse };
|
||||
import { API_BASE_PATH } from '@tracearr/shared';
|
||||
|
||||
// Stats time range parameters
|
||||
export interface StatsTimeRange {
|
||||
period: 'day' | 'week' | 'month' | 'year' | 'all' | 'custom';
|
||||
startDate?: string; // ISO date string
|
||||
endDate?: string; // ISO date string
|
||||
}
|
||||
|
||||
// Types for Plex server selection during signup (from check-pin endpoint)
|
||||
export interface PlexServerConnection {
|
||||
uri: string;
|
||||
local: boolean;
|
||||
address: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
export interface PlexServerInfo {
|
||||
name: string;
|
||||
platform: string;
|
||||
version: string;
|
||||
clientIdentifier: string;
|
||||
connections: PlexServerConnection[];
|
||||
}
|
||||
|
||||
export interface PlexCheckPinResponse {
|
||||
authorized: boolean;
|
||||
message?: string;
|
||||
// If returning user (auto-connect)
|
||||
accessToken?: string;
|
||||
refreshToken?: string;
|
||||
user?: User;
|
||||
// If new user (needs server selection)
|
||||
needsServerSelection?: boolean;
|
||||
servers?: PlexServerInfo[];
|
||||
tempToken?: string;
|
||||
}
|
||||
|
||||
// Token storage keys
|
||||
const ACCESS_TOKEN_KEY = 'tracearr_access_token';
|
||||
const REFRESH_TOKEN_KEY = 'tracearr_refresh_token';
|
||||
|
||||
// Event for auth state changes (logout, token cleared, etc.)
|
||||
export const AUTH_STATE_CHANGE_EVENT = 'tracearr:auth-state-change';
|
||||
|
||||
// Token management utilities
|
||||
export const tokenStorage = {
|
||||
getAccessToken: (): string | null => localStorage.getItem(ACCESS_TOKEN_KEY),
|
||||
getRefreshToken: (): string | null => localStorage.getItem(REFRESH_TOKEN_KEY),
|
||||
setTokens: (accessToken: string, refreshToken: string) => {
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
|
||||
},
|
||||
/**
|
||||
* Clear tokens from storage
|
||||
* @param silent - If true, don't dispatch auth change event (used for intentional logout)
|
||||
*/
|
||||
clearTokens: (silent = false) => {
|
||||
localStorage.removeItem(ACCESS_TOKEN_KEY);
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||
// Dispatch event so auth context can react immediately (unless silent)
|
||||
if (!silent) {
|
||||
window.dispatchEvent(new CustomEvent(AUTH_STATE_CHANGE_EVENT, { detail: { type: 'logout' } }));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
class ApiClient {
|
||||
private baseUrl: string;
|
||||
private isRefreshing = false;
|
||||
private refreshPromise: Promise<boolean> | null = null;
|
||||
|
||||
constructor(baseUrl: string = API_BASE_PATH) {
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to refresh the access token using the refresh token
|
||||
* Returns true if refresh succeeded, false otherwise
|
||||
*/
|
||||
private async refreshAccessToken(): Promise<boolean> {
|
||||
const refreshToken = tokenStorage.getRefreshToken();
|
||||
if (!refreshToken) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Only clear tokens on explicit auth rejection (401/403)
|
||||
// Don't clear on server errors (500, 502, 503) - server might be restarting
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
tokenStorage.clearTokens();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (data.accessToken && data.refreshToken) {
|
||||
tokenStorage.setTokens(data.accessToken, data.refreshToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch {
|
||||
// Network error (server down, timeout, etc.)
|
||||
// DON'T clear tokens - they might still be valid when server comes back
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle token refresh with deduplication
|
||||
* Multiple concurrent 401s will share the same refresh attempt
|
||||
*/
|
||||
private async handleTokenRefresh(): Promise<boolean> {
|
||||
if (this.isRefreshing) {
|
||||
return this.refreshPromise!;
|
||||
}
|
||||
|
||||
this.isRefreshing = true;
|
||||
this.refreshPromise = this.refreshAccessToken().finally(() => {
|
||||
this.isRefreshing = false;
|
||||
this.refreshPromise = null;
|
||||
});
|
||||
|
||||
return this.refreshPromise;
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
isRetry = false
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
...(options.headers as Record<string, string>),
|
||||
};
|
||||
|
||||
// Only set Content-Type for requests with a body
|
||||
if (options.body) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
// Add Authorization header if we have a token
|
||||
const token = tokenStorage.getAccessToken();
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseUrl}${path}`, {
|
||||
...options,
|
||||
credentials: 'include',
|
||||
headers,
|
||||
});
|
||||
|
||||
// Handle 401 with automatic token refresh (skip for auth endpoints to avoid loops)
|
||||
// Note: /auth/me is NOT in this list - it SHOULD trigger token refresh on 401
|
||||
const noRetryPaths = ['/auth/login', '/auth/signup', '/auth/refresh', '/auth/logout', '/auth/plex/check-pin', '/auth/callback'];
|
||||
const shouldRetry = !noRetryPaths.some(p => path.startsWith(p));
|
||||
if (response.status === 401 && !isRetry && shouldRetry) {
|
||||
const refreshed = await this.handleTokenRefresh();
|
||||
if (refreshed) {
|
||||
// Retry the original request with new token
|
||||
return this.request<T>(path, options, true);
|
||||
}
|
||||
// Refresh failed - tokens already cleared by refreshAccessToken() if it was a real auth failure
|
||||
// Don't clear here - might just be a network error (server restarting)
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({}));
|
||||
throw new Error(error.message ?? `Request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
// Handle empty responses (204 No Content) or responses without JSON
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (response.status === 204 || !contentType?.includes('application/json')) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Setup - check if Tracearr needs initial configuration
|
||||
setup = {
|
||||
status: () => this.request<{
|
||||
needsSetup: boolean;
|
||||
hasServers: boolean;
|
||||
hasJellyfinServers: boolean;
|
||||
hasPasswordAuth: boolean;
|
||||
primaryAuthMethod: 'jellyfin' | 'local';
|
||||
}>('/setup/status'),
|
||||
};
|
||||
|
||||
// Auth
|
||||
auth = {
|
||||
me: () => this.request<{
|
||||
userId: string;
|
||||
username: string;
|
||||
email: string | null;
|
||||
thumbnail: string | null;
|
||||
role: UserRole;
|
||||
aggregateTrustScore: number;
|
||||
serverIds: string[];
|
||||
hasPassword?: boolean;
|
||||
hasPlexLinked?: boolean;
|
||||
// Fallback fields for backwards compatibility
|
||||
id?: string;
|
||||
serverId?: string;
|
||||
thumbUrl?: string | null;
|
||||
trustScore?: number;
|
||||
}>('/auth/me'),
|
||||
logout: () => this.request<void>('/auth/logout', { method: 'POST' }),
|
||||
|
||||
// Local account signup (email for login, username for display)
|
||||
signup: (data: { email: string; username: string; password: string }) =>
|
||||
this.request<{ accessToken: string; refreshToken: string; user: User }>('/auth/signup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
// Local account login (uses email)
|
||||
loginLocal: (data: { email: string; password: string }) =>
|
||||
this.request<{ accessToken: string; refreshToken: string; user: User }>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ type: 'local', ...data }),
|
||||
}),
|
||||
|
||||
// Plex OAuth - Step 1: Get PIN
|
||||
loginPlex: (forwardUrl?: string) =>
|
||||
this.request<{ pinId: string; authUrl: string }>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ type: 'plex', forwardUrl }),
|
||||
}),
|
||||
|
||||
// Plex OAuth - Step 2: Check PIN and get servers
|
||||
checkPlexPin: (pinId: string) =>
|
||||
this.request<PlexCheckPinResponse>('/auth/plex/check-pin', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ pinId }),
|
||||
}),
|
||||
|
||||
// Jellyfin Admin Login - Authenticate with Jellyfin username/password
|
||||
loginJellyfin: (data: { username: string; password: string }) =>
|
||||
this.request<{ accessToken: string; refreshToken: string; user: User }>('/auth/jellyfin/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
// Plex OAuth - Step 3: Connect with selected server (only for setup)
|
||||
connectPlexServer: (data: { tempToken: string; serverUri: string; serverName: string; clientIdentifier?: string }) =>
|
||||
this.request<{ accessToken: string; refreshToken: string; user: User }>('/auth/plex/connect', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
// Get available Plex servers (authenticated - for adding additional servers)
|
||||
getAvailablePlexServers: () =>
|
||||
this.request<PlexAvailableServersResponse>('/auth/plex/available-servers'),
|
||||
|
||||
// Add an additional Plex server (authenticated - owner only)
|
||||
addPlexServer: (data: { serverUri: string; serverName: string; clientIdentifier: string }) =>
|
||||
this.request<{ server: Server; usersAdded: number; librariesSynced: number }>('/auth/plex/add-server', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
// Jellyfin server connection with API key (requires auth)
|
||||
connectJellyfinWithApiKey: (data: {
|
||||
serverUrl: string;
|
||||
serverName: string;
|
||||
apiKey: string;
|
||||
}) =>
|
||||
this.request<{
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
user: User;
|
||||
}>('/auth/jellyfin/connect-api-key', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
// Emby server connection with API key (requires auth)
|
||||
connectEmbyWithApiKey: (data: {
|
||||
serverUrl: string;
|
||||
serverName: string;
|
||||
apiKey: string;
|
||||
}) =>
|
||||
this.request<{
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
user: User;
|
||||
}>('/auth/emby/connect-api-key', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
// Legacy callback (deprecated, kept for compatibility)
|
||||
checkPlexCallback: (data: {
|
||||
pinId: string;
|
||||
serverUrl: string;
|
||||
serverName: string;
|
||||
}) =>
|
||||
this.request<{
|
||||
authorized: boolean;
|
||||
message?: string;
|
||||
accessToken?: string;
|
||||
refreshToken?: string;
|
||||
user?: User;
|
||||
}>('/auth/callback', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
};
|
||||
|
||||
// Servers
|
||||
servers = {
|
||||
list: async () => {
|
||||
const response = await this.request<{ data: Server[] }>('/servers');
|
||||
return response.data;
|
||||
},
|
||||
create: (data: { name: string; type: string; url: string; token: string }) =>
|
||||
this.request<Server>('/servers', { method: 'POST', body: JSON.stringify(data) }),
|
||||
delete: (id: string) => this.request<void>(`/servers/${id}`, { method: 'DELETE' }),
|
||||
sync: (id: string) =>
|
||||
this.request<{
|
||||
success: boolean;
|
||||
usersAdded: number;
|
||||
usersUpdated: number;
|
||||
librariesSynced: number;
|
||||
errors: string[];
|
||||
syncedAt: string;
|
||||
}>(`/servers/${id}/sync`, { method: 'POST', body: JSON.stringify({}) }),
|
||||
statistics: (id: string) =>
|
||||
this.request<{
|
||||
serverId: string;
|
||||
data: {
|
||||
at: number;
|
||||
timespan: number;
|
||||
hostCpuUtilization: number;
|
||||
processCpuUtilization: number;
|
||||
hostMemoryUtilization: number;
|
||||
processMemoryUtilization: number;
|
||||
}[];
|
||||
fetchedAt: string;
|
||||
}>(`/servers/${id}/statistics`),
|
||||
};
|
||||
|
||||
// Users
|
||||
users = {
|
||||
list: (params?: { page?: number; pageSize?: number; serverId?: string }) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.page) searchParams.set('page', String(params.page));
|
||||
if (params?.pageSize) searchParams.set('pageSize', String(params.pageSize));
|
||||
if (params?.serverId) searchParams.set('serverId', params.serverId);
|
||||
return this.request<PaginatedResponse<ServerUserWithIdentity>>(`/users?${searchParams.toString()}`);
|
||||
},
|
||||
get: (id: string) => this.request<ServerUserDetail>(`/users/${id}`),
|
||||
getFull: (id: string) => this.request<ServerUserFullDetail>(`/users/${id}/full`),
|
||||
update: (id: string, data: { trustScore?: number }) =>
|
||||
this.request<ServerUserWithIdentity>(`/users/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
|
||||
updateIdentity: (id: string, data: { name: string | null }) =>
|
||||
this.request<{ success: boolean; name: string | null }>(`/users/${id}/identity`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
sessions: (id: string, params?: { page?: number; pageSize?: number }) => {
|
||||
const query = new URLSearchParams(params as Record<string, string>).toString();
|
||||
return this.request<PaginatedResponse<Session>>(`/users/${id}/sessions?${query}`);
|
||||
},
|
||||
locations: async (id: string) => {
|
||||
const response = await this.request<{ data: UserLocation[] }>(`/users/${id}/locations`);
|
||||
return response.data;
|
||||
},
|
||||
devices: async (id: string) => {
|
||||
const response = await this.request<{ data: UserDevice[] }>(`/users/${id}/devices`);
|
||||
return response.data;
|
||||
},
|
||||
terminations: (id: string, params?: { page?: number; pageSize?: number }) => {
|
||||
const query = new URLSearchParams(params as Record<string, string>).toString();
|
||||
return this.request<PaginatedResponse<TerminationLogWithDetails>>(`/users/${id}/terminations?${query}`);
|
||||
},
|
||||
};
|
||||
|
||||
// Sessions
|
||||
sessions = {
|
||||
list: (params?: { page?: number; pageSize?: number; userId?: string; serverId?: string }) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.page) searchParams.set('page', String(params.page));
|
||||
if (params?.pageSize) searchParams.set('pageSize', String(params.pageSize));
|
||||
if (params?.userId) searchParams.set('userId', params.userId);
|
||||
if (params?.serverId) searchParams.set('serverId', params.serverId);
|
||||
return this.request<PaginatedResponse<SessionWithDetails>>(`/sessions?${searchParams.toString()}`);
|
||||
},
|
||||
getActive: async (serverId?: string) => {
|
||||
const params = new URLSearchParams();
|
||||
if (serverId) params.set('serverId', serverId);
|
||||
const query = params.toString();
|
||||
const response = await this.request<{ data: ActiveSession[] }>(`/sessions/active${query ? `?${query}` : ''}`);
|
||||
return response.data;
|
||||
},
|
||||
get: (id: string) => this.request<Session>(`/sessions/${id}`),
|
||||
terminate: (id: string, reason?: string) =>
|
||||
this.request<{ success: boolean; terminationLogId: string; message: string }>(
|
||||
`/sessions/${id}/terminate`,
|
||||
{ method: 'POST', body: JSON.stringify({ reason }) }
|
||||
),
|
||||
};
|
||||
|
||||
// Rules
|
||||
rules = {
|
||||
list: async () => {
|
||||
const response = await this.request<{ data: Rule[] }>('/rules');
|
||||
return response.data;
|
||||
},
|
||||
create: (data: Omit<Rule, 'id' | 'createdAt' | 'updatedAt'>) =>
|
||||
this.request<Rule>('/rules', { method: 'POST', body: JSON.stringify(data) }),
|
||||
update: (id: string, data: Partial<Rule>) =>
|
||||
this.request<Rule>(`/rules/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
|
||||
delete: (id: string) => this.request<void>(`/rules/${id}`, { method: 'DELETE' }),
|
||||
};
|
||||
|
||||
// Violations
|
||||
violations = {
|
||||
list: (params?: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
userId?: string;
|
||||
severity?: string;
|
||||
acknowledged?: boolean;
|
||||
serverId?: string;
|
||||
}) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.page) searchParams.set('page', String(params.page));
|
||||
if (params?.pageSize) searchParams.set('pageSize', String(params.pageSize));
|
||||
if (params?.userId) searchParams.set('userId', params.userId);
|
||||
if (params?.severity) searchParams.set('severity', params.severity);
|
||||
if (params?.acknowledged !== undefined) searchParams.set('acknowledged', String(params.acknowledged));
|
||||
if (params?.serverId) searchParams.set('serverId', params.serverId);
|
||||
return this.request<PaginatedResponse<ViolationWithDetails>>(`/violations?${searchParams.toString()}`);
|
||||
},
|
||||
acknowledge: (id: string) =>
|
||||
this.request<Violation>(`/violations/${id}`, { method: 'PATCH' }),
|
||||
dismiss: (id: string) => this.request<void>(`/violations/${id}`, { method: 'DELETE' }),
|
||||
};
|
||||
|
||||
// Stats - helper to build stats query params
|
||||
private buildStatsParams(timeRange?: StatsTimeRange, serverId?: string): URLSearchParams {
|
||||
const params = new URLSearchParams();
|
||||
if (timeRange?.period) params.set('period', timeRange.period);
|
||||
if (timeRange?.startDate) params.set('startDate', timeRange.startDate);
|
||||
if (timeRange?.endDate) params.set('endDate', timeRange.endDate);
|
||||
if (serverId) params.set('serverId', serverId);
|
||||
return params;
|
||||
}
|
||||
|
||||
stats = {
|
||||
dashboard: (serverId?: string) => {
|
||||
const params = new URLSearchParams();
|
||||
if (serverId) params.set('serverId', serverId);
|
||||
const query = params.toString();
|
||||
return this.request<DashboardStats>(`/stats/dashboard${query ? `?${query}` : ''}`);
|
||||
},
|
||||
plays: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'week' }, serverId);
|
||||
const response = await this.request<{ data: PlayStats[] }>(`/stats/plays?${params.toString()}`);
|
||||
return response.data;
|
||||
},
|
||||
users: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'month' }, serverId);
|
||||
const response = await this.request<{ data: UserStats[] }>(`/stats/users?${params.toString()}`);
|
||||
return response.data;
|
||||
},
|
||||
locations: async (params?: {
|
||||
timeRange?: StatsTimeRange;
|
||||
serverUserId?: string;
|
||||
serverId?: string;
|
||||
mediaType?: 'movie' | 'episode' | 'track';
|
||||
}) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.timeRange?.period) searchParams.set('period', params.timeRange.period);
|
||||
if (params?.timeRange?.startDate) searchParams.set('startDate', params.timeRange.startDate);
|
||||
if (params?.timeRange?.endDate) searchParams.set('endDate', params.timeRange.endDate);
|
||||
if (params?.serverUserId) searchParams.set('serverUserId', params.serverUserId);
|
||||
if (params?.serverId) searchParams.set('serverId', params.serverId);
|
||||
if (params?.mediaType) searchParams.set('mediaType', params.mediaType);
|
||||
const query = searchParams.toString();
|
||||
return this.request<LocationStatsResponse>(`/stats/locations${query ? `?${query}` : ''}`);
|
||||
},
|
||||
playsByDayOfWeek: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'month' }, serverId);
|
||||
const response = await this.request<{ data: { day: number; name: string; count: number }[] }>(
|
||||
`/stats/plays-by-dayofweek?${params.toString()}`
|
||||
);
|
||||
return response.data;
|
||||
},
|
||||
playsByHourOfDay: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'month' }, serverId);
|
||||
const response = await this.request<{ data: { hour: number; count: number }[] }>(
|
||||
`/stats/plays-by-hourofday?${params.toString()}`
|
||||
);
|
||||
return response.data;
|
||||
},
|
||||
platforms: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'month' }, serverId);
|
||||
const response = await this.request<{ data: { platform: string | null; count: number }[] }>(
|
||||
`/stats/platforms?${params.toString()}`
|
||||
);
|
||||
return response.data;
|
||||
},
|
||||
quality: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'month' }, serverId);
|
||||
return this.request<{
|
||||
directPlay: number;
|
||||
transcode: number;
|
||||
total: number;
|
||||
directPlayPercent: number;
|
||||
transcodePercent: number;
|
||||
}>(`/stats/quality?${params.toString()}`);
|
||||
},
|
||||
topUsers: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'month' }, serverId);
|
||||
const response = await this.request<{ data: TopUserStats[] }>(`/stats/top-users?${params.toString()}`);
|
||||
return response.data;
|
||||
},
|
||||
topContent: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'month' }, serverId);
|
||||
const response = await this.request<{
|
||||
movies: {
|
||||
title: string;
|
||||
type: 'movie';
|
||||
year: number | null;
|
||||
playCount: number;
|
||||
watchTimeHours: number;
|
||||
thumbPath: string | null;
|
||||
serverId: string | null;
|
||||
ratingKey: string | null;
|
||||
}[];
|
||||
shows: {
|
||||
title: string;
|
||||
type: 'episode';
|
||||
year: number | null;
|
||||
playCount: number;
|
||||
episodeCount: number;
|
||||
watchTimeHours: number;
|
||||
thumbPath: string | null;
|
||||
serverId: string | null;
|
||||
ratingKey: string | null;
|
||||
}[];
|
||||
}>(`/stats/top-content?${params.toString()}`);
|
||||
return response;
|
||||
},
|
||||
concurrent: async (timeRange?: StatsTimeRange, serverId?: string) => {
|
||||
const params = this.buildStatsParams(timeRange ?? { period: 'month' }, serverId);
|
||||
const response = await this.request<{
|
||||
data: { hour: string; total: number; direct: number; transcode: number }[];
|
||||
}>(`/stats/concurrent?${params.toString()}`);
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
|
||||
// Settings
|
||||
settings = {
|
||||
get: () => this.request<Settings>('/settings'),
|
||||
update: (data: Partial<Settings>) =>
|
||||
this.request<Settings>('/settings', { method: 'PATCH', body: JSON.stringify(data) }),
|
||||
};
|
||||
|
||||
// Channel Routing
|
||||
channelRouting = {
|
||||
getAll: () => this.request<NotificationChannelRouting[]>('/settings/notifications/routing'),
|
||||
update: (
|
||||
eventType: NotificationEventType,
|
||||
data: { discordEnabled?: boolean; webhookEnabled?: boolean }
|
||||
) =>
|
||||
this.request<NotificationChannelRouting>(`/settings/notifications/routing/${eventType}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
};
|
||||
|
||||
// Import
|
||||
import = {
|
||||
tautulli: {
|
||||
test: (url: string, apiKey: string) =>
|
||||
this.request<{ success: boolean; message: string; users?: number; historyRecords?: number }>(
|
||||
'/import/tautulli/test',
|
||||
{ method: 'POST', body: JSON.stringify({ url, apiKey }) }
|
||||
),
|
||||
start: (serverId: string) =>
|
||||
this.request<{ status: string; jobId?: string; message: string }>(
|
||||
'/import/tautulli',
|
||||
{ method: 'POST', body: JSON.stringify({ serverId }) }
|
||||
),
|
||||
getActive: (serverId: string) =>
|
||||
this.request<{
|
||||
active: boolean;
|
||||
jobId?: string;
|
||||
state?: string;
|
||||
progress?: number | object;
|
||||
createdAt?: number;
|
||||
}>(`/import/tautulli/active/${serverId}`),
|
||||
getStatus: (jobId: string) =>
|
||||
this.request<{
|
||||
jobId: string;
|
||||
state: string;
|
||||
progress: number | object | null;
|
||||
result?: { success: boolean; imported: number; skipped: number; errors: number; message: string };
|
||||
failedReason?: string;
|
||||
createdAt?: number;
|
||||
finishedAt?: number;
|
||||
}>(`/import/tautulli/${jobId}`),
|
||||
},
|
||||
};
|
||||
|
||||
// Mobile access
|
||||
mobile = {
|
||||
get: () => this.request<MobileConfig>('/mobile'),
|
||||
enable: () => this.request<MobileConfig>('/mobile/enable', { method: 'POST', body: '{}' }),
|
||||
disable: () => this.request<{ success: boolean }>('/mobile/disable', { method: 'POST', body: '{}' }),
|
||||
generatePairToken: () =>
|
||||
this.request<{ token: string; expiresAt: string }>('/mobile/pair-token', { method: 'POST', body: '{}' }),
|
||||
revokeSession: (id: string) =>
|
||||
this.request<{ success: boolean }>(`/mobile/sessions/${id}`, { method: 'DELETE' }),
|
||||
revokeSessions: () =>
|
||||
this.request<{ success: boolean; revokedCount: number }>('/mobile/sessions', { method: 'DELETE' }),
|
||||
};
|
||||
}
|
||||
|
||||
export const api = new ApiClient();
|
||||
6
apps/web/src/lib/utils.ts
Normal file
6
apps/web/src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
48
apps/web/src/main.tsx
Normal file
48
apps/web/src/main.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { AuthProvider } from '@/hooks/useAuth';
|
||||
import { ServerProvider } from '@/hooks/useServer';
|
||||
import { SocketProvider } from '@/hooks/useSocket';
|
||||
import { ThemeProvider } from '@/components/theme-provider';
|
||||
import { App } from './App';
|
||||
import './styles/globals.css';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 1000 * 60,
|
||||
// Retry failed queries with exponential backoff
|
||||
retry: 3,
|
||||
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 10000),
|
||||
// Auto-refetch when reconnecting or window regains focus
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const root = document.getElementById('root');
|
||||
|
||||
if (!root) {
|
||||
throw new Error('Root element not found');
|
||||
}
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<ThemeProvider defaultTheme="dark" storageKey="tracearr-theme">
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<ServerProvider>
|
||||
<SocketProvider>
|
||||
<App />
|
||||
</SocketProvider>
|
||||
</ServerProvider>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</ThemeProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
166
apps/web/src/pages/Dashboard.tsx
Normal file
166
apps/web/src/pages/Dashboard.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import { Play, Clock, AlertTriangle, Tv, MapPin, Calendar, Users } from 'lucide-react';
|
||||
import { MediaServerIcon } from '@/components/icons/MediaServerIcon';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { NowPlayingCard } from '@/components/sessions';
|
||||
import { StreamCard } from '@/components/map';
|
||||
import { ServerResourceCharts } from '@/components/charts/ServerResourceCharts';
|
||||
import { useDashboardStats, useActiveSessions } from '@/hooks/queries';
|
||||
import { useServerStatistics } from '@/hooks/queries/useServers';
|
||||
import { useServer } from '@/hooks/useServer';
|
||||
|
||||
export function Dashboard() {
|
||||
const { selectedServerId, selectedServer } = useServer();
|
||||
const { data: stats, isLoading: statsLoading } = useDashboardStats(selectedServerId);
|
||||
const { data: sessions } = useActiveSessions(selectedServerId);
|
||||
|
||||
// Only show server resource stats for Plex servers
|
||||
const isPlexServer = selectedServer?.type === 'plex';
|
||||
|
||||
// Poll server statistics only when viewing a Plex server
|
||||
const {
|
||||
data: serverStats,
|
||||
isLoading: statsChartLoading,
|
||||
averages,
|
||||
} = useServerStatistics(selectedServerId ?? undefined, isPlexServer);
|
||||
|
||||
const activeCount = sessions?.length ?? 0;
|
||||
const hasActiveStreams = activeCount > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Today Stats Section */}
|
||||
<section>
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<Calendar className="h-5 w-5 text-primary" />
|
||||
<h2 className="text-lg font-semibold">Today</h2>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{/* Alerts */}
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-between py-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Alerts</p>
|
||||
{statsLoading ? (
|
||||
<Skeleton className="h-7 w-12 mt-1" />
|
||||
) : (
|
||||
<div className="text-2xl font-bold">{stats?.alertsLast24h ?? 0}</div>
|
||||
)}
|
||||
</div>
|
||||
<AlertTriangle className="h-5 w-5 text-muted-foreground" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Plays */}
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-between py-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Plays</p>
|
||||
{statsLoading ? (
|
||||
<Skeleton className="h-7 w-12 mt-1" />
|
||||
) : (
|
||||
<div className="text-2xl font-bold">{stats?.todayPlays ?? 0}</div>
|
||||
)}
|
||||
</div>
|
||||
<Play className="h-5 w-5 text-muted-foreground" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Watch Time */}
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-between py-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Watch Time</p>
|
||||
{statsLoading ? (
|
||||
<Skeleton className="h-7 w-12 mt-1" />
|
||||
) : (
|
||||
<div className="text-2xl font-bold">
|
||||
{stats?.watchTimeHours ?? 0}
|
||||
<span className="text-lg font-normal text-muted-foreground">h</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Clock className="h-5 w-5 text-muted-foreground" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Active Users */}
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-between py-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Active Users</p>
|
||||
{statsLoading ? (
|
||||
<Skeleton className="h-7 w-12 mt-1" />
|
||||
) : (
|
||||
<div className="text-2xl font-bold">{stats?.activeUsersToday ?? 0}</div>
|
||||
)}
|
||||
</div>
|
||||
<Users className="h-5 w-5 text-muted-foreground" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Now Playing Section */}
|
||||
<section>
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<Tv className="h-5 w-5 text-primary" />
|
||||
<h2 className="text-lg font-semibold">Now Playing</h2>
|
||||
{hasActiveStreams && (
|
||||
<span className="rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
|
||||
{activeCount} {activeCount === 1 ? 'stream' : 'streams'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!sessions || sessions.length === 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<div className="rounded-full bg-muted p-4">
|
||||
<Tv className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 className="mt-4 font-semibold">No active streams</h3>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Active streams will appear here when users start watching
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{sessions.map((session) => (
|
||||
<NowPlayingCard key={session.id} session={session} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Stream Map - only show when there are active streams */}
|
||||
{hasActiveStreams && (
|
||||
<section>
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<MapPin className="h-5 w-5 text-primary" />
|
||||
<h2 className="text-lg font-semibold">Stream Locations</h2>
|
||||
</div>
|
||||
<Card className="overflow-hidden">
|
||||
<StreamCard sessions={sessions} height={320} />
|
||||
</Card>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Server Resource Stats (Plex only) */}
|
||||
{isPlexServer && (
|
||||
<section>
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<MediaServerIcon type="plex" className="h-5 w-5" />
|
||||
<h2 className="text-lg font-semibold">Server Resources</h2>
|
||||
</div>
|
||||
<ServerResourceCharts
|
||||
data={serverStats?.data}
|
||||
isLoading={statsChartLoading}
|
||||
averages={averages}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
325
apps/web/src/pages/Debug.tsx
Normal file
325
apps/web/src/pages/Debug.tsx
Normal file
@@ -0,0 +1,325 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
AlertTriangle,
|
||||
Trash2,
|
||||
RotateCcw,
|
||||
Database,
|
||||
Server,
|
||||
Users,
|
||||
Film,
|
||||
Shield,
|
||||
RefreshCw,
|
||||
Info,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { tokenStorage } from '@/lib/api';
|
||||
import { API_BASE_PATH } from '@tracearr/shared';
|
||||
|
||||
interface DebugStats {
|
||||
counts: {
|
||||
sessions: number;
|
||||
violations: number;
|
||||
users: number;
|
||||
servers: number;
|
||||
rules: number;
|
||||
};
|
||||
database: {
|
||||
size: string;
|
||||
tables: { table_name: string; total_size: string }[];
|
||||
};
|
||||
}
|
||||
|
||||
interface EnvInfo {
|
||||
nodeVersion: string;
|
||||
platform: string;
|
||||
arch: string;
|
||||
uptime: number;
|
||||
memoryUsage: {
|
||||
heapUsed: string;
|
||||
heapTotal: string;
|
||||
rss: string;
|
||||
};
|
||||
env: Record<string, string>;
|
||||
}
|
||||
|
||||
// Simple fetch helper for debug endpoints
|
||||
async function debugFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const token = tokenStorage.getAccessToken();
|
||||
const headers: Record<string, string> = {
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
// Only set Content-Type for requests with a body
|
||||
if (options.body) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
// Merge additional headers if provided as a plain object
|
||||
if (options.headers && typeof options.headers === 'object' && !Array.isArray(options.headers)) {
|
||||
Object.assign(headers, options.headers);
|
||||
}
|
||||
const res = await fetch(`${API_BASE_PATH}/debug${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export function Debug() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const stats = useQuery({
|
||||
queryKey: ['debug', 'stats'],
|
||||
queryFn: () => debugFetch<DebugStats>('/stats'),
|
||||
});
|
||||
|
||||
const envInfo = useQuery({
|
||||
queryKey: ['debug', 'env'],
|
||||
queryFn: () => debugFetch<EnvInfo>('/env'),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: async ({ action, isPost }: { action: string; isPost?: boolean }) => {
|
||||
return debugFetch(`/${action}`, { method: isPost ? 'POST' : 'DELETE' });
|
||||
},
|
||||
onSuccess: (_data, variables) => {
|
||||
// Factory reset: clear tokens and redirect to login
|
||||
if (variables.action === 'reset') {
|
||||
tokenStorage.clearTokens(true);
|
||||
window.location.href = '/login';
|
||||
return;
|
||||
}
|
||||
void queryClient.invalidateQueries();
|
||||
},
|
||||
});
|
||||
|
||||
const handleDelete = (action: string, description: string, isPost = false) => {
|
||||
if (window.confirm(`${description}\n\nThis cannot be undone. Continue?`)) {
|
||||
deleteMutation.mutate({ action, isPost });
|
||||
}
|
||||
};
|
||||
|
||||
const formatUptime = (seconds: number) => {
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
const mins = Math.floor((seconds % 3600) / 60);
|
||||
if (days > 0) return `${days}d ${hours}h ${mins}m`;
|
||||
if (hours > 0) return `${hours}h ${mins}m`;
|
||||
return `${mins}m`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-destructive/10">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Debug Tools</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Administrative utilities for troubleshooting and data management
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats Overview */}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<Film className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-2xl font-bold">{stats.data?.counts.sessions ?? '-'}</p>
|
||||
<p className="text-xs text-muted-foreground">Sessions</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<Shield className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-2xl font-bold">{stats.data?.counts.violations ?? '-'}</p>
|
||||
<p className="text-xs text-muted-foreground">Violations</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<Users className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-2xl font-bold">{stats.data?.counts.users ?? '-'}</p>
|
||||
<p className="text-xs text-muted-foreground">Users</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<Server className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-2xl font-bold">{stats.data?.counts.servers ?? '-'}</p>
|
||||
<p className="text-xs text-muted-foreground">Servers</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-3 p-4">
|
||||
<Database className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-2xl font-bold">{stats.data?.database.size ?? '-'}</p>
|
||||
<p className="text-xs text-muted-foreground">DB Size</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
{/* Environment Info */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
Environment
|
||||
</CardTitle>
|
||||
<CardDescription>Server runtime information</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{envInfo.data && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-2 text-sm">
|
||||
<div className="text-muted-foreground">Node.js</div>
|
||||
<div className="font-mono">{envInfo.data.nodeVersion}</div>
|
||||
<div className="text-muted-foreground">Platform</div>
|
||||
<div className="font-mono">{envInfo.data.platform}/{envInfo.data.arch}</div>
|
||||
<div className="text-muted-foreground">Uptime</div>
|
||||
<div className="font-mono">{formatUptime(envInfo.data.uptime)}</div>
|
||||
<div className="text-muted-foreground">Heap Used</div>
|
||||
<div className="font-mono">{envInfo.data.memoryUsage.heapUsed}</div>
|
||||
<div className="text-muted-foreground">RSS</div>
|
||||
<div className="font-mono">{envInfo.data.memoryUsage.rss}</div>
|
||||
</div>
|
||||
<div className="border-t pt-3">
|
||||
<p className="mb-2 text-sm font-medium">Environment Variables</p>
|
||||
<div className="grid grid-cols-2 gap-2 text-sm">
|
||||
{Object.entries(envInfo.data.env).map(([key, value]) => (
|
||||
<div key={key} className="contents">
|
||||
<div className="truncate text-muted-foreground">{key}</div>
|
||||
<div className="font-mono text-xs">{value}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Table Sizes */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
Table Sizes
|
||||
</CardTitle>
|
||||
<CardDescription>Database storage by table</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{stats.data?.database.tables.map((table) => (
|
||||
<div key={table.table_name} className="flex items-center justify-between text-sm">
|
||||
<span className="font-mono text-muted-foreground">{table.table_name}</span>
|
||||
<span className="font-mono">{table.total_size}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Trash2 className="h-5 w-5" />
|
||||
Data Management
|
||||
</CardTitle>
|
||||
<CardDescription>Clear data or reset the application</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Utility Actions */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleDelete('refresh-aggregates', 'Refresh TimescaleDB aggregates', true)}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Refresh Aggregates
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => queryClient.invalidateQueries()}
|
||||
>
|
||||
<RotateCcw className="mr-2 h-4 w-4" />
|
||||
Clear Query Cache
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-4">
|
||||
<p className="mb-3 text-sm font-medium text-muted-foreground">Destructive Actions</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleDelete('violations', 'Delete all violation records')}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Clear Violations
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleDelete('rules', 'Delete all detection rules and violations')}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Clear Rules
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-destructive/50 text-destructive hover:bg-destructive/10"
|
||||
onClick={() => handleDelete('sessions', 'Delete all session history and violations')}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Clear Sessions
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-destructive/50 text-destructive hover:bg-destructive/10"
|
||||
onClick={() => handleDelete('users', 'Delete all non-owner users and their data')}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Clear Users
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-destructive/50 text-destructive hover:bg-destructive/10"
|
||||
onClick={() => handleDelete('servers', 'Delete all servers (cascades to users, sessions, violations)')}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Clear Servers
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-4">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => handleDelete('reset', 'FACTORY RESET: Delete everything except your owner account. You will need to set up the app again.', true)}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
<AlertTriangle className="mr-2 h-4 w-4" />
|
||||
Factory Reset
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
592
apps/web/src/pages/Login.tsx
Normal file
592
apps/web/src/pages/Login.tsx
Normal file
@@ -0,0 +1,592 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router';
|
||||
import { Loader2, ExternalLink, User, KeyRound } from 'lucide-react';
|
||||
import { MediaServerIcon } from '@/components/icons/MediaServerIcon';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { toast } from 'sonner';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { api, tokenStorage, type PlexServerInfo } from '@/lib/api';
|
||||
import { LogoIcon } from '@/components/brand/Logo';
|
||||
import { PlexServerSelector } from '@/components/auth/PlexServerSelector';
|
||||
|
||||
// Plex brand color
|
||||
const PLEX_COLOR = 'bg-[#E5A00D] hover:bg-[#C88A0B]';
|
||||
|
||||
type AuthStep = 'initial' | 'plex-waiting' | 'server-select';
|
||||
|
||||
export function Login() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { isAuthenticated, isLoading: authLoading, refetch } = useAuth();
|
||||
|
||||
// Setup status - default to false (Sign In mode) since most users are returning
|
||||
const [setupLoading, setSetupLoading] = useState(true);
|
||||
const [needsSetup, setNeedsSetup] = useState(false);
|
||||
const [hasPasswordAuth, setHasPasswordAuth] = useState(false);
|
||||
const [hasJellyfinServers, setHasJellyfinServers] = useState(false);
|
||||
|
||||
// Auth form state - which form to show (jellyfin or local)
|
||||
// Default to Jellyfin if Jellyfin servers exist, otherwise default to local
|
||||
const [showJellyfinForm, setShowJellyfinForm] = useState(true);
|
||||
|
||||
// Auth flow state
|
||||
const [authStep, setAuthStep] = useState<AuthStep>('initial');
|
||||
const [plexAuthUrl, setPlexAuthUrl] = useState<string | null>(null);
|
||||
const [plexServers, setPlexServers] = useState<PlexServerInfo[]>([]);
|
||||
const [plexTempToken, setPlexTempToken] = useState<string | null>(null);
|
||||
const [connectingToServer, setConnectingToServer] = useState<string | null>(null);
|
||||
const [plexPopup, setPlexPopup] = useState<ReturnType<typeof window.open>>(null);
|
||||
|
||||
// Local auth state
|
||||
const [localLoading, setLocalLoading] = useState(false);
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
|
||||
// Jellyfin auth state
|
||||
const [jellyfinLoading, setJellyfinLoading] = useState(false);
|
||||
const [jellyfinUsername, setJellyfinUsername] = useState('');
|
||||
const [jellyfinPassword, setJellyfinPassword] = useState('');
|
||||
|
||||
// Check setup status on mount with retry logic for server restarts
|
||||
useEffect(() => {
|
||||
async function checkSetup() {
|
||||
const maxRetries = 3;
|
||||
const delays = [0, 1000, 2000]; // immediate, 1s, 2s
|
||||
|
||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||
try {
|
||||
if (attempt > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
||||
}
|
||||
const status = await api.setup.status();
|
||||
setNeedsSetup(status.needsSetup);
|
||||
setHasPasswordAuth(status.hasPasswordAuth);
|
||||
setHasJellyfinServers(status.hasJellyfinServers);
|
||||
// Use the configured primary auth method
|
||||
setShowJellyfinForm(status.primaryAuthMethod === 'jellyfin');
|
||||
setSetupLoading(false);
|
||||
return; // Success - exit retry loop
|
||||
} catch {
|
||||
// Continue to next retry attempt
|
||||
}
|
||||
}
|
||||
|
||||
// All retries failed - server is unavailable
|
||||
// Default to Sign In mode (needsSetup: false) since most users are returning users
|
||||
// If they actually need setup, the server will tell them when it comes back
|
||||
setNeedsSetup(false);
|
||||
setSetupLoading(false);
|
||||
}
|
||||
void checkSetup();
|
||||
}, []);
|
||||
|
||||
// Redirect if already authenticated
|
||||
useEffect(() => {
|
||||
if (!authLoading && isAuthenticated) {
|
||||
const redirectTo = searchParams.get('redirect') || '/';
|
||||
void navigate(redirectTo, { replace: true });
|
||||
}
|
||||
}, [isAuthenticated, authLoading, navigate, searchParams]);
|
||||
|
||||
// Close Plex popup helper
|
||||
const closePlexPopup = () => {
|
||||
if (plexPopup && !plexPopup.closed) {
|
||||
plexPopup.close();
|
||||
}
|
||||
setPlexPopup(null);
|
||||
};
|
||||
|
||||
// Poll for Plex PIN claim
|
||||
const pollPlexPin = async (pinId: string) => {
|
||||
try {
|
||||
const result = await api.auth.checkPlexPin(pinId);
|
||||
|
||||
if (!result.authorized) {
|
||||
// Still waiting for PIN claim, continue polling
|
||||
setTimeout(() => void pollPlexPin(pinId), 2000);
|
||||
return;
|
||||
}
|
||||
|
||||
// PIN claimed - close the popup
|
||||
closePlexPopup();
|
||||
|
||||
// Check what we got back
|
||||
if (result.needsServerSelection && result.servers && result.tempToken) {
|
||||
// New user - needs to select a server
|
||||
setPlexServers(result.servers);
|
||||
setPlexTempToken(result.tempToken);
|
||||
setAuthStep('server-select');
|
||||
} else if (result.accessToken && result.refreshToken) {
|
||||
// User authenticated (returning or no servers)
|
||||
tokenStorage.setTokens(result.accessToken, result.refreshToken);
|
||||
void refetch();
|
||||
toast.success('Success', { description: 'Logged in successfully!' });
|
||||
void navigate('/');
|
||||
}
|
||||
} catch (error) {
|
||||
resetPlexAuth();
|
||||
toast.error('Authentication failed', {
|
||||
description: error instanceof Error ? error.message : 'Plex authentication failed',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Start Plex OAuth flow
|
||||
const handlePlexLogin = async () => {
|
||||
setAuthStep('plex-waiting');
|
||||
|
||||
// Open popup to blank page first (same origin) - helps with cross-origin close
|
||||
const popup = window.open('about:blank', 'plex_auth', 'width=600,height=700,popup=yes');
|
||||
setPlexPopup(popup);
|
||||
|
||||
try {
|
||||
// Pass callback URL so Plex redirects back to our domain after auth
|
||||
const callbackUrl = `${window.location.origin}/auth/plex-callback`;
|
||||
const result = await api.auth.loginPlex(callbackUrl);
|
||||
setPlexAuthUrl(result.authUrl);
|
||||
|
||||
// Navigate popup to Plex auth
|
||||
if (popup && !popup.closed) {
|
||||
popup.location.href = result.authUrl;
|
||||
}
|
||||
|
||||
// Start polling
|
||||
void pollPlexPin(result.pinId);
|
||||
} catch (error) {
|
||||
closePlexPopup();
|
||||
setAuthStep('initial');
|
||||
toast.error('Error', {
|
||||
description: error instanceof Error ? error.message : 'Failed to start Plex login',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Connect to selected Plex server
|
||||
const handlePlexServerSelect = async (serverUri: string, serverName: string, clientIdentifier: string) => {
|
||||
if (!plexTempToken) return;
|
||||
|
||||
setConnectingToServer(serverName);
|
||||
|
||||
try {
|
||||
const result = await api.auth.connectPlexServer({
|
||||
tempToken: plexTempToken,
|
||||
serverUri,
|
||||
serverName,
|
||||
clientIdentifier,
|
||||
});
|
||||
|
||||
if (result.accessToken && result.refreshToken) {
|
||||
tokenStorage.setTokens(result.accessToken, result.refreshToken);
|
||||
void refetch();
|
||||
toast.success('Success', { description: `Connected to ${serverName}` });
|
||||
void navigate('/');
|
||||
}
|
||||
} catch (error) {
|
||||
setConnectingToServer(null);
|
||||
toast.error('Connection failed', {
|
||||
description: error instanceof Error ? error.message : 'Failed to connect to server',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Reset Plex auth state
|
||||
const resetPlexAuth = () => {
|
||||
// Close popup if still open
|
||||
if (plexPopup && !plexPopup.closed) {
|
||||
plexPopup.close();
|
||||
}
|
||||
setPlexPopup(null);
|
||||
setAuthStep('initial');
|
||||
setPlexAuthUrl(null);
|
||||
setPlexServers([]);
|
||||
setPlexTempToken(null);
|
||||
setConnectingToServer(null);
|
||||
};
|
||||
|
||||
// Handle local signup
|
||||
const handleLocalSignup = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLocalLoading(true);
|
||||
|
||||
try {
|
||||
const result = await api.auth.signup({
|
||||
email: email.trim(),
|
||||
username: username.trim(),
|
||||
password,
|
||||
});
|
||||
|
||||
if (result.accessToken && result.refreshToken) {
|
||||
tokenStorage.setTokens(result.accessToken, result.refreshToken);
|
||||
void refetch();
|
||||
toast.success('Success', { description: 'Account created successfully!' });
|
||||
void navigate('/');
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error('Signup failed', {
|
||||
description: error instanceof Error ? error.message : 'Failed to create account',
|
||||
});
|
||||
} finally {
|
||||
setLocalLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle local login
|
||||
const handleLocalLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLocalLoading(true);
|
||||
|
||||
try {
|
||||
const result = await api.auth.loginLocal({
|
||||
email: email.trim(),
|
||||
password,
|
||||
});
|
||||
|
||||
if (result.accessToken && result.refreshToken) {
|
||||
tokenStorage.setTokens(result.accessToken, result.refreshToken);
|
||||
void refetch();
|
||||
toast.success('Success', { description: 'Logged in successfully!' });
|
||||
void navigate('/');
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error('Login failed', {
|
||||
description: error instanceof Error ? error.message : 'Invalid email or password',
|
||||
});
|
||||
} finally {
|
||||
setLocalLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle Jellyfin login
|
||||
const handleJellyfinLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setJellyfinLoading(true);
|
||||
|
||||
try {
|
||||
const result = await api.auth.loginJellyfin({
|
||||
username: jellyfinUsername.trim(),
|
||||
password: jellyfinPassword,
|
||||
});
|
||||
|
||||
if (result.accessToken && result.refreshToken) {
|
||||
tokenStorage.setTokens(result.accessToken, result.refreshToken);
|
||||
setJellyfinUsername('');
|
||||
setJellyfinPassword('');
|
||||
void refetch();
|
||||
toast.success('Success', { description: 'Logged in successfully!' });
|
||||
void navigate('/');
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error('Login failed', {
|
||||
description: error instanceof Error ? error.message : 'Invalid username or password, or user is not an administrator',
|
||||
});
|
||||
} finally {
|
||||
setJellyfinLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Show loading while checking auth/setup status
|
||||
if (authLoading || setupLoading) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center gap-4">
|
||||
<LogoIcon className="h-16 w-16 animate-pulse" />
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Server selection step (only during Plex signup)
|
||||
if (authStep === 'server-select' && plexServers.length > 0) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-background p-4">
|
||||
<div className="mb-8 flex flex-col items-center text-center">
|
||||
<LogoIcon className="h-20 w-20 mb-4" />
|
||||
<h1 className="text-4xl font-bold tracking-tight">Tracearr</h1>
|
||||
<p className="mt-2 text-muted-foreground">Select your Plex server</p>
|
||||
</div>
|
||||
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle>Select Server</CardTitle>
|
||||
<CardDescription>
|
||||
Choose which Plex Media Server to monitor
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<PlexServerSelector
|
||||
servers={plexServers}
|
||||
onSelect={handlePlexServerSelect}
|
||||
connecting={connectingToServer !== null}
|
||||
connectingToServer={connectingToServer}
|
||||
onCancel={resetPlexAuth}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center bg-background p-4">
|
||||
<div className="mb-8 flex flex-col items-center text-center">
|
||||
<LogoIcon className="h-20 w-20 mb-4" />
|
||||
<h1 className="text-4xl font-bold tracking-tight">Tracearr</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{needsSetup
|
||||
? 'Create your account to get started'
|
||||
: 'Sign in to your account'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle>{needsSetup ? 'Create Account' : 'Sign In'}</CardTitle>
|
||||
<CardDescription>
|
||||
{needsSetup
|
||||
? 'Create an account to manage your media servers'
|
||||
: 'Sign in to access your dashboard'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Plex OAuth Section */}
|
||||
{authStep === 'plex-waiting' ? (
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-lg bg-muted/50 p-4 text-center">
|
||||
<Loader2 className="mx-auto h-8 w-8 animate-spin text-[#E5A00D] mb-3" />
|
||||
<p className="text-sm font-medium">Waiting for Plex authorization...</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Complete sign-in in the popup window
|
||||
</p>
|
||||
{plexAuthUrl && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="sm"
|
||||
onClick={() => window.open(plexAuthUrl, '_blank')}
|
||||
className="gap-1 h-auto p-0 mt-2"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
Reopen Plex Login
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="ghost" className="w-full" onClick={resetPlexAuth}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Plex Login Button - Always Available */}
|
||||
<Button
|
||||
className={`w-full ${PLEX_COLOR} text-white`}
|
||||
onClick={handlePlexLogin}
|
||||
>
|
||||
<MediaServerIcon type="plex" className="mr-2 h-4 w-4" />
|
||||
{needsSetup ? 'Sign up with Plex' : 'Sign in with Plex'}
|
||||
</Button>
|
||||
|
||||
{/* Divider between Plex and other auth methods */}
|
||||
{(hasJellyfinServers || hasPasswordAuth || needsSetup) && (
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-card px-2 text-muted-foreground">or</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Conditional Auth Forms - Show only one at a time with transition */}
|
||||
{(hasJellyfinServers || hasPasswordAuth || needsSetup) && (
|
||||
<div className="relative min-h-[200px]">
|
||||
{/* Jellyfin Admin Login Form */}
|
||||
{showJellyfinForm && hasJellyfinServers && (
|
||||
<div
|
||||
key="jellyfin-form"
|
||||
className="animate-in fade-in-0 slide-in-from-bottom-2 duration-300"
|
||||
>
|
||||
<form onSubmit={handleJellyfinLogin} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="jellyfin-username">Jellyfin Username</Label>
|
||||
<Input
|
||||
id="jellyfin-username"
|
||||
type="text"
|
||||
placeholder="Your Jellyfin username"
|
||||
value={jellyfinUsername}
|
||||
onChange={(e) => setJellyfinUsername(e.target.value)}
|
||||
required
|
||||
disabled={jellyfinLoading}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="jellyfin-password">Jellyfin Password</Label>
|
||||
<Input
|
||||
id="jellyfin-password"
|
||||
type="password"
|
||||
placeholder="Your Jellyfin password"
|
||||
value={jellyfinPassword}
|
||||
onChange={(e) => setJellyfinPassword(e.target.value)}
|
||||
required
|
||||
disabled={jellyfinLoading}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Must be an administrator on a configured Jellyfin server
|
||||
</p>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={jellyfinLoading}>
|
||||
{jellyfinLoading ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<MediaServerIcon type="jellyfin" className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Sign in with Jellyfin
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Toggle button to switch to local auth */}
|
||||
{hasPasswordAuth && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
className="mt-4 w-full text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
onClick={() => setShowJellyfinForm(false)}
|
||||
>
|
||||
Use local account instead
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Local Auth Form */}
|
||||
{!showJellyfinForm && (hasPasswordAuth || needsSetup) && (
|
||||
<div
|
||||
key="local-form"
|
||||
className="animate-in fade-in-0 slide-in-from-bottom-2 duration-300"
|
||||
>
|
||||
{needsSetup ? (
|
||||
<form onSubmit={handleLocalSignup} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="your@email.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Display Name</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
placeholder="Choose a display name"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={50}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="At least 8 characters"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
minLength={8}
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={localLoading}>
|
||||
{localLoading ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Create Account
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={handleLocalLogin} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="your@email.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Your password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={localLoading}>
|
||||
{localLoading ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{/* Toggle button to switch to Jellyfin auth */}
|
||||
{hasJellyfinServers && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
className="mt-4 w-full text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
onClick={() => setShowJellyfinForm(true)}
|
||||
>
|
||||
Use Jellyfin account instead
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<p className="mt-6 text-center text-xs text-muted-foreground">
|
||||
{needsSetup ? (
|
||||
<>
|
||||
After creating your account, you'll add your
|
||||
<br />
|
||||
Plex or Jellyfin servers from Settings.
|
||||
</>
|
||||
) : (
|
||||
'Tracearr • Stream access management'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
228
apps/web/src/pages/Map.tsx
Normal file
228
apps/web/src/pages/Map.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { StreamMap } from '@/components/map';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { TimeRangePicker } from '@/components/ui/time-range-picker';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { X, Flame, CircleDot } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useLocationStats } from '@/hooks/queries';
|
||||
import { useServer } from '@/hooks/useServer';
|
||||
import { useTimeRange } from '@/hooks/useTimeRange';
|
||||
|
||||
const MEDIA_TYPES = [
|
||||
{ value: 'movie', label: 'Movies' },
|
||||
{ value: 'episode', label: 'TV' },
|
||||
{ value: 'track', label: 'Music' },
|
||||
] as const;
|
||||
|
||||
export function Map() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { value: timeRange, setValue: setTimeRange } = useTimeRange();
|
||||
const { selectedServerId } = useServer();
|
||||
|
||||
// Parse filters from URL, use selected server from context
|
||||
const filters = useMemo(() => {
|
||||
const serverUserId = searchParams.get('serverUserId');
|
||||
const mediaType = searchParams.get('mediaType') as 'movie' | 'episode' | 'track' | null;
|
||||
const viewMode = (searchParams.get('view') as 'heatmap' | 'circles') || 'heatmap';
|
||||
|
||||
return {
|
||||
serverUserId: serverUserId || undefined,
|
||||
serverId: selectedServerId || undefined,
|
||||
mediaType: mediaType || undefined,
|
||||
viewMode,
|
||||
};
|
||||
}, [searchParams, selectedServerId]);
|
||||
|
||||
// Build API params including time range
|
||||
const apiParams = useMemo(() => ({
|
||||
timeRange: {
|
||||
period: timeRange.period,
|
||||
startDate: timeRange.startDate?.toISOString(),
|
||||
endDate: timeRange.endDate?.toISOString(),
|
||||
},
|
||||
serverUserId: filters.serverUserId,
|
||||
serverId: filters.serverId,
|
||||
mediaType: filters.mediaType,
|
||||
}), [timeRange, filters]);
|
||||
|
||||
// Fetch data - includes available filter options based on current filters
|
||||
const { data: locationData, isLoading: locationsLoading } = useLocationStats(apiParams);
|
||||
|
||||
const locations = locationData?.data ?? [];
|
||||
const summary = locationData?.summary;
|
||||
const availableFilters = locationData?.availableFilters;
|
||||
|
||||
// Dynamic filter options from the response
|
||||
const users = availableFilters?.users ?? [];
|
||||
const mediaTypes = availableFilters?.mediaTypes ?? [];
|
||||
|
||||
// Get selected filter labels for display
|
||||
const selectedUser = users.find(u => u.id === filters.serverUserId);
|
||||
const selectedMediaType = MEDIA_TYPES.find(m => m.value === filters.mediaType);
|
||||
|
||||
// Filter MEDIA_TYPES to only show available options
|
||||
const availableMediaTypeOptions = MEDIA_TYPES.filter(m => mediaTypes.includes(m.value));
|
||||
|
||||
// Update a single filter
|
||||
const setFilter = (key: string, value: string | null) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
if (value) {
|
||||
params.set(key, value);
|
||||
} else {
|
||||
params.delete(key);
|
||||
}
|
||||
setSearchParams(params, { replace: true });
|
||||
};
|
||||
|
||||
// Set view mode
|
||||
const setViewMode = (mode: 'heatmap' | 'circles') => {
|
||||
setFilter('view', mode === 'heatmap' ? null : mode);
|
||||
};
|
||||
|
||||
// Clear all filters (except time range which has its own controls)
|
||||
const clearFilters = () => {
|
||||
const params = new URLSearchParams();
|
||||
// Preserve time range params
|
||||
if (searchParams.get('period')) params.set('period', searchParams.get('period')!);
|
||||
if (searchParams.get('from')) params.set('from', searchParams.get('from')!);
|
||||
if (searchParams.get('to')) params.set('to', searchParams.get('to')!);
|
||||
setSearchParams(params, { replace: true });
|
||||
};
|
||||
|
||||
// Check if any non-time filters are active
|
||||
const hasFilters = filters.serverUserId || filters.mediaType;
|
||||
|
||||
// Build summary text
|
||||
const summaryContext = useMemo(() => {
|
||||
const parts: string[] = [];
|
||||
if (selectedUser) parts.push(selectedUser.identityName ?? selectedUser.username);
|
||||
if (selectedMediaType) parts.push(selectedMediaType.label);
|
||||
return parts.join(' · ') || 'All activity';
|
||||
}, [selectedUser, selectedMediaType]);
|
||||
|
||||
return (
|
||||
<div className="-m-6 flex h-[calc(100vh-4rem)] flex-col">
|
||||
{/* Filter bar */}
|
||||
<div className="relative z-20 flex items-center gap-3 border-b bg-card/50 px-4 py-2 backdrop-blur">
|
||||
{/* Time range picker */}
|
||||
<TimeRangePicker value={timeRange} onChange={setTimeRange} />
|
||||
|
||||
<div className="h-4 w-px bg-border" />
|
||||
|
||||
{/* User filter */}
|
||||
<Select
|
||||
value={filters.serverUserId ?? '_all'}
|
||||
onValueChange={(v) => setFilter('serverUserId', v === '_all' ? null : v)}
|
||||
>
|
||||
<SelectTrigger className="w-[140px] h-8 text-sm">
|
||||
<SelectValue placeholder="All users" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="_all">All users</SelectItem>
|
||||
{users.map((user) => (
|
||||
<SelectItem key={user.id} value={user.id}>
|
||||
{user.identityName ?? user.username}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* Media type filter */}
|
||||
<Select
|
||||
value={filters.mediaType ?? '_all'}
|
||||
onValueChange={(v) => setFilter('mediaType', v === '_all' ? null : v)}
|
||||
>
|
||||
<SelectTrigger className="w-[100px] h-8 text-sm">
|
||||
<SelectValue placeholder="All types" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="_all">All types</SelectItem>
|
||||
{availableMediaTypeOptions.map((m) => (
|
||||
<SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{hasFilters && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={clearFilters}
|
||||
className="h-8 px-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="h-4 w-px bg-border" />
|
||||
|
||||
{/* View mode toggle */}
|
||||
<div className="flex h-8 rounded-md border bg-muted/50 p-0.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setViewMode('heatmap')}
|
||||
className={cn(
|
||||
'h-7 px-2.5 gap-1.5 text-xs rounded-sm',
|
||||
filters.viewMode === 'heatmap'
|
||||
? 'bg-background shadow-sm text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground hover:bg-transparent'
|
||||
)}
|
||||
>
|
||||
<Flame className="h-3.5 w-3.5" />
|
||||
<span className="hidden sm:inline">Heatmap</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setViewMode('circles')}
|
||||
className={cn(
|
||||
'h-7 px-2.5 gap-1.5 text-xs rounded-sm',
|
||||
filters.viewMode === 'circles'
|
||||
? 'bg-background shadow-sm text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground hover:bg-transparent'
|
||||
)}
|
||||
>
|
||||
<CircleDot className="h-3.5 w-3.5" />
|
||||
<span className="hidden sm:inline">Circles</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Summary stats - right side */}
|
||||
<div className="ml-auto flex items-center gap-4 text-sm">
|
||||
<div className="text-muted-foreground">
|
||||
{summaryContext}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div>
|
||||
<span className="font-semibold tabular-nums">{summary?.totalStreams ?? 0}</span>
|
||||
<span className="ml-1 text-muted-foreground">streams</span>
|
||||
</div>
|
||||
<div className="h-4 w-px bg-border" />
|
||||
<div>
|
||||
<span className="font-semibold tabular-nums">{summary?.uniqueLocations ?? 0}</span>
|
||||
<span className="ml-1 text-muted-foreground">locations</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Map */}
|
||||
<div className="relative flex-1">
|
||||
<StreamMap
|
||||
locations={locations}
|
||||
isLoading={locationsLoading}
|
||||
viewMode={filters.viewMode}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
14
apps/web/src/pages/NotFound.tsx
Normal file
14
apps/web/src/pages/NotFound.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Link } from 'react-router';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export function NotFound() {
|
||||
return (
|
||||
<div className="flex min-h-[50vh] flex-col items-center justify-center space-y-4">
|
||||
<h1 className="text-4xl font-bold">404</h1>
|
||||
<p className="text-muted-foreground">Page not found</p>
|
||||
<Button asChild>
|
||||
<Link to="/">Go Home</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user