feat: Add Wild Central web app (Central-only UI)

Extract Central pages from the wild-cloud web app into a standalone
React app for Wild Central. Includes:

- Central overview, DNS, DHCP, Firewall, VPN, Ingress, CrowdSec pages
- Simplified sidebar with Central-only navigation
- Branding updated to "Wild Central"
- All Cloud-specific pages, components, hooks, and API services removed
- TypeScript type-check and production build pass

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-09 04:10:43 +00:00
parent 5defc27f63
commit 735f3fcb05
121 changed files with 18347 additions and 0 deletions

View File

@@ -0,0 +1,134 @@
import { NavLink } from 'react-router';
import { Sun, Moon, Monitor, Shield, Lock, Network, ShieldAlert, Router, Cloud, Wifi, Server } from 'lucide-react';
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
useSidebar,
} from './ui/sidebar';
import { useTheme } from '../contexts/ThemeContext';
export function AppSidebar() {
const { theme, setTheme } = useTheme();
const { state } = useSidebar();
const cycleTheme = () => {
if (theme === 'light') {
setTheme('dark');
} else if (theme === 'dark') {
setTheme('system');
} else {
setTheme('light');
}
};
const getThemeIcon = () => {
switch (theme) {
case 'light':
return <Sun className="h-4 w-4" />;
case 'dark':
return <Moon className="h-4 w-4" />;
default:
return <Monitor className="h-4 w-4" />;
}
};
const getThemeLabel = () => {
switch (theme) {
case 'light':
return 'Light mode';
case 'dark':
return 'Dark mode';
default:
return 'System theme';
}
};
const centralItems = [
{ to: '/central', icon: Server, label: 'Overview', end: true },
{ to: '/central/cloudflare', icon: Cloud, label: 'Cloudflare' },
{ to: '/central/dns', icon: Router, label: 'DNS' },
{ to: '/central/ingress', icon: Network, label: 'Ingress Proxy' },
{ to: '/central/firewall', icon: Shield, label: 'Firewall' },
{ to: '/central/vpn', icon: Lock, label: 'VPN' },
{ to: '/central/crowdsec', icon: ShieldAlert, label: 'CrowdSec' },
{ to: '/central/dhcp', icon: Wifi, label: 'DHCP' },
];
return (
<Sidebar variant="sidebar" collapsible="icon">
<SidebarHeader>
<div className="flex items-center justify-center pb-2">
<div className="p-1 bg-primary/10 rounded-lg">
<Server className="h-6 w-6 text-primary" />
</div>
<div className="overflow-hidden transition-all duration-200 ease-linear ml-2 max-w-[200px] opacity-100 group-data-[collapsible=icon]:ml-0 group-data-[collapsible=icon]:max-w-0 group-data-[collapsible=icon]:opacity-0">
<h2 className="text-lg font-bold text-foreground whitespace-nowrap">Wild Central</h2>
</div>
</div>
</SidebarHeader>
<SidebarContent>
{state === 'collapsed' ? (
<SidebarMenu>
{centralItems.map(({ to, icon: Icon, label, end }) => (
<SidebarMenuItem key={to}>
<NavLink to={to} end={end}>
{({ isActive }) => (
<SidebarMenuButton isActive={isActive} tooltip={label}>
<Icon className="h-4 w-4" />
<span>{label}</span>
</SidebarMenuButton>
)}
</NavLink>
</SidebarMenuItem>
))}
</SidebarMenu>
) : (
<SidebarGroup>
<SidebarGroupLabel>Central</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{centralItems.map(({ to, icon: Icon, label, end }) => (
<SidebarMenuItem key={to}>
<NavLink to={to} end={end}>
{({ isActive }) => (
<SidebarMenuButton isActive={isActive}>
<Icon className="h-4 w-4" />
<span className="truncate">{label}</span>
</SidebarMenuButton>
)}
</NavLink>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
)}
</SidebarContent>
<SidebarFooter>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
onClick={cycleTheme}
tooltip={`Current: ${getThemeLabel()}. Click to cycle themes.`}
>
{getThemeIcon()}
<span>{getThemeLabel()}</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
<SidebarRail/>
</Sidebar>
);
}

View File

@@ -0,0 +1,219 @@
import { useState, useEffect } from 'react';
import { Card } from './ui/card';
import { Button } from './ui/button';
import { Input, Label } from './ui';
import { Alert, AlertDescription } from './ui/alert';
import { HardDrive, Settings, CheckCircle, BookOpen, ExternalLink, Loader2, AlertCircle, Mail, Edit2, Check, X, RotateCw } from 'lucide-react';
import { Badge } from './ui/badge';
import { useCentralStatus } from '../hooks/useCentralStatus';
import { useConfig } from '../hooks';
import { usePageHelp } from '../hooks/usePageHelp';
export function CentralComponent() {
const { data: centralStatus, isLoading: statusLoading, error: statusError, restart: restartDaemon, isRestarting: isDaemonRestarting } = useCentralStatus();
const { config: globalConfig, updateConfig: updateGlobalConfig, isUpdating } = useConfig();
const [editingOperator, setEditingOperator] = useState(false);
const [operatorEmail, setOperatorEmail] = useState('');
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const showSuccess = (msg: string) => {
setSuccessMessage(msg);
setErrorMessage(null);
setTimeout(() => setSuccessMessage(null), 5000);
};
const showError = (msg: string) => {
setErrorMessage(msg);
setSuccessMessage(null);
setTimeout(() => setErrorMessage(null), 8000);
};
useEffect(() => {
if (globalConfig?.operator?.email) {
setOperatorEmail(globalConfig.operator.email);
}
}, [globalConfig]);
const handleOperatorSave = async () => {
if (!globalConfig || !operatorEmail) return;
try {
await updateGlobalConfig({
...globalConfig,
operator: { ...globalConfig.operator, email: operatorEmail },
});
setEditingOperator(false);
showSuccess('Operator email saved');
} catch (err) {
showError(`Failed to save operator: ${err instanceof Error ? err.message : String(err)}`);
}
};
const handleOperatorCancel = () => {
setOperatorEmail(globalConfig?.operator?.email || '');
setEditingOperator(false);
};
usePageHelp({
title: 'What is the Central Service?',
description: (
<>
<p className="mb-3 leading-relaxed">
The Central Service is the "brain" of your personal cloud. It acts as the main coordinator that manages
all the different services running on your network. Think of it like the control tower at an airport -
it keeps track of what's happening, routes traffic between services, and ensures everything works together smoothly.
</p>
<p className="text-sm">
This service handles configuration management, service discovery, and provides the web interface you're using right now.
</p>
</>
),
icon: <BookOpen className="h-6 w-6 text-blue-600 dark:text-blue-400" />,
color: 'bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/20 dark:to-indigo-950/20',
actions: (
<Button
variant="outline"
size="sm"
className="text-blue-700 border-blue-300 hover:bg-blue-100 dark:text-blue-300 dark:border-blue-700 dark:hover:bg-blue-900/20"
>
<ExternalLink className="h-4 w-4 mr-2" />
Learn more about service orchestration
</Button>
),
});
if (statusError) {
return (
<Card className="p-8 text-center">
<AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
<h3 className="text-lg font-medium mb-2">Error Loading Central Status</h3>
<p className="text-muted-foreground mb-4">
{(statusError as Error)?.message || 'An error occurred'}
</p>
<Button onClick={() => window.location.reload()}>Reload Page</Button>
</Card>
);
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h2 className="text-3xl font-bold tracking-tight">Wild Central</h2>
<p className="text-muted-foreground">Manage your Wild Central server</p>
</div>
{centralStatus && (
<Badge variant="success" className="gap-1">
<CheckCircle className="h-3 w-3" />
{centralStatus.status === 'running' ? 'Running' : centralStatus.status}
</Badge>
)}
</div>
{centralStatus?.pendingRestart && (
<div className="flex items-center justify-between gap-3 rounded-md border border-amber-300 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-700 px-4 py-3 text-sm text-amber-800 dark:text-amber-300">
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4 shrink-0" />
<span>Configuration changed restart Wild Central for changes to take effect.</span>
</div>
<Button
size="sm"
variant="outline"
className="shrink-0 border-amber-400 text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/30"
onClick={restartDaemon}
disabled={isDaemonRestarting}
>
{isDaemonRestarting ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <RotateCw className="h-3 w-3 mr-1" />}
{isDaemonRestarting ? 'Restarting...' : 'Restart Now'}
</Button>
</div>
)}
{successMessage && (
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
</Alert>
)}
{errorMessage && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{errorMessage}</AlertDescription>
</Alert>
)}
{statusLoading ? (
<Card className="p-6">
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
</Card>
) : (
<Card className="p-4 border-l-4 border-l-blue-500">
<div className="flex items-start gap-3">
<Settings className="h-5 w-5 text-blue-500 mt-0.5" />
<div className="flex-1">
<div className="text-sm text-muted-foreground mb-1">Version</div>
<div className="font-medium font-mono">{centralStatus?.version || 'Unknown'}</div>
</div>
</div>
<div className="flex items-start gap-3">
<HardDrive className="h-5 w-5 text-indigo-500 mt-0.5" />
<div className="flex-1">
<div className="text-sm text-muted-foreground mb-1">Data Directory</div>
<div className="font-medium font-mono text-sm break-all">
{centralStatus?.dataDir || '/var/lib/wild-central'}
</div>
</div>
</div>
</Card>
)}
<Card className="p-4 border-l-4 border-l-amber-500">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<Mail className="h-5 w-5 text-amber-500" />
<div className="text-sm text-muted-foreground">Operator Email</div>
</div>
{!editingOperator && (
<Button variant="ghost" size="sm" onClick={() => setEditingOperator(true)} disabled={isUpdating}>
<Edit2 className="h-4 w-4" />
</Button>
)}
</div>
{editingOperator ? (
<div className="space-y-3">
<div>
<Label htmlFor="operator-email">Email</Label>
<Input
id="operator-email"
type="email"
value={operatorEmail}
onChange={(e) => setOperatorEmail(e.target.value)}
placeholder="email@example.com"
className="mt-1"
/>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" size="sm" onClick={handleOperatorCancel} disabled={isUpdating}>
<X className="h-4 w-4 mr-1" />Cancel
</Button>
<Button size="sm" onClick={handleOperatorSave} disabled={isUpdating || !operatorEmail}>
{isUpdating ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <Check className="h-4 w-4 mr-1" />}
Save
</Button>
</div>
</div>
) : (
<div className="font-medium font-mono text-sm ml-7">
{globalConfig?.operator?.email || (
<span className="text-muted-foreground italic">Not configured</span>
)}
</div>
)}
</Card>
</div>
);
}

View File

@@ -0,0 +1,426 @@
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input, Label } from './ui';
import { Alert, AlertDescription } from './ui/alert';
import {
Cloud, CheckCircle, XCircle, AlertCircle, Loader2, Edit2,
RefreshCw, ExternalLink, BookOpen, Globe, Key, Shield, Check, X, KeyRound,
} from 'lucide-react';
import { Badge } from './ui/badge';
import { useCloudflare } from '../hooks/useCloudflare';
import { useConfig } from '../hooks';
import { useDdns } from '../hooks/useDdns';
import { useCert } from '../hooks/useCert';
import { secretsApi } from '../services/api';
import { usePageHelp } from '../hooks/usePageHelp';
export function CloudflareComponent() {
const { verification, isLoading: isVerifying, refetch: reverify } = useCloudflare();
const { config: globalConfig, updateConfig: updateGlobalConfig, isUpdating } = useConfig();
const { status: ddnsStatus } = useDdns();
const { status: certStatus, isLoading: certLoading, provision: provisionCert, isProvisioning, provisionError } = useCert();
const queryClient = useQueryClient();
const { data: globalSecrets } = useQuery({
queryKey: ['globalSecrets'],
queryFn: () => secretsApi.get(),
});
const updateSecretsMutation = useMutation({
mutationFn: (values: Record<string, unknown>) => secretsApi.update(values),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['globalSecrets'] });
queryClient.invalidateQueries({ queryKey: ['cloudflare', 'verify'] });
setEditingToken(false);
setTokenValue('');
showSuccess('Cloudflare API token saved');
},
onError: (err) => {
showError(String(err));
},
});
const cfTokenIsSet = !!(globalSecrets as Record<string, unknown> | undefined)
&& !!(globalSecrets as { cloudflare?: { apiToken?: string } })?.cloudflare?.apiToken;
const [editingToken, setEditingToken] = useState(false);
const [tokenValue, setTokenValue] = useState('');
const [editingDomain, setEditingDomain] = useState(false);
const [domainInput, setDomainInput] = useState('');
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const showSuccess = (msg: string) => {
setSuccessMessage(msg);
setErrorMessage(null);
setTimeout(() => setSuccessMessage(null), 5000);
};
const showError = (msg: string) => {
setErrorMessage(msg);
setSuccessMessage(null);
setTimeout(() => setErrorMessage(null), 8000);
};
usePageHelp({
title: 'Why Cloudflare?',
description: (
<>
<p className="mb-3 leading-relaxed">
Wild Cloud uses Cloudflare to manage DNS records and provision TLS certificates for your domains.
A Cloudflare API token enables three key features: <strong>Dynamic DNS</strong> keeps your domain
pointed at your changing public IP, <strong>TLS certificates</strong> are provisioned via
Let's Encrypt DNS-01 challenges, and <strong>ExternalDNS</strong> automatically creates DNS records
when you deploy apps.
</p>
<p className="text-sm">
Create an API token in your Cloudflare dashboard with <strong>Zone:DNS:Edit</strong> and{' '}
<strong>Zone:Zone:Read</strong> permissions, scoped to your domain's zone.
</p>
</>
),
icon: <BookOpen className="h-6 w-6 text-orange-600 dark:text-orange-400" />,
color: 'bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-950/20 dark:to-amber-950/20',
actions: (
<a
href="https://developers.cloudflare.com/fundamentals/api/get-started/create-token/"
target="_blank"
rel="noopener noreferrer"
>
<Button
variant="outline"
size="sm"
className="text-orange-700 border-orange-300 hover:bg-orange-100 dark:text-orange-300 dark:border-orange-700 dark:hover:bg-orange-900/20"
>
<ExternalLink className="h-4 w-4 mr-2" />
Create a Cloudflare API token
</Button>
</a>
),
});
return (
<div className="space-y-6">
{/* Page Header */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-3xl font-bold tracking-tight">Cloudflare</h2>
<p className="text-muted-foreground">Manage your Cloudflare integration for DNS and TLS</p>
</div>
{verification?.tokenValid && (
<Badge variant="success" className="gap-1">
<CheckCircle className="h-3 w-3" />
Connected
</Badge>
)}
</div>
{/* Alerts */}
{successMessage && (
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
</Alert>
)}
{errorMessage && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{errorMessage}</AlertDescription>
</Alert>
)}
{/* API Token Card */}
<Card className="p-4 border-l-4 border-l-orange-500">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<Key className="h-5 w-5 text-orange-500" />
<div className="font-medium">API Token</div>
</div>
{!editingToken && (
<Button variant="outline" size="sm" onClick={() => setEditingToken(true)} className="gap-1">
<Edit2 className="h-3 w-3" />
{cfTokenIsSet ? 'Update' : 'Set'}
</Button>
)}
</div>
{!editingToken && (
cfTokenIsSet
? <p className="text-sm text-green-600 dark:text-green-400 ml-7">Configured</p>
: <p className="text-sm text-muted-foreground ml-7">Not set required for DNS and TLS features</p>
)}
{editingToken && (
<div className="space-y-2 ml-7">
<Input
type="password"
placeholder="Cloudflare API token..."
value={tokenValue}
onChange={(e) => setTokenValue(e.target.value)}
/>
<div className="flex gap-2">
<Button
size="sm"
onClick={() => updateSecretsMutation.mutate({ cloudflare: { apiToken: tokenValue } })}
disabled={updateSecretsMutation.isPending || !tokenValue}
>
{updateSecretsMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
Save
</Button>
<Button variant="outline" size="sm" onClick={() => { setEditingToken(false); setTokenValue(''); }}>
Cancel
</Button>
</div>
</div>
)}
</Card>
{/* Central Domain & TLS Card */}
<Card className="p-4 border-l-4 border-l-green-500">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<Globe className="h-5 w-5 text-green-500" />
<div className="font-medium">Central Domain</div>
</div>
<div className="flex items-center gap-2">
{certStatus?.cert?.exists && (
<Badge variant="success" className="gap-1">
<Shield className="h-3 w-3" />
TLS
</Badge>
)}
{!editingDomain && (
<Button variant="ghost" size="sm" onClick={() => {
setDomainInput(globalConfig?.cloud?.central?.domain || '');
setEditingDomain(true);
}} disabled={isUpdating}>
<Edit2 className="h-4 w-4" />
</Button>
)}
</div>
</div>
{editingDomain ? (
<div className="space-y-3 ml-7">
<div>
<Label htmlFor="central-domain">Domain</Label>
<Input
id="central-domain"
value={domainInput}
onChange={(e) => setDomainInput(e.target.value)}
placeholder="central.example.com"
className="mt-1 font-mono"
/>
<p className="text-xs text-muted-foreground mt-1">
Must resolve to this server (via internal DNS or VPN).
</p>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" size="sm" onClick={() => setEditingDomain(false)} disabled={isUpdating}>
<X className="h-4 w-4 mr-1" />Cancel
</Button>
<Button size="sm" onClick={async () => {
if (!globalConfig) return;
try {
await updateGlobalConfig({
...globalConfig,
cloud: {
...globalConfig.cloud,
central: { domain: domainInput },
},
});
setEditingDomain(false);
showSuccess('Central domain saved');
} catch (err) {
showError(`Failed to save domain: ${err instanceof Error ? err.message : String(err)}`);
}
}} disabled={isUpdating}>
{isUpdating ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <Check className="h-4 w-4 mr-1" />}
Save
</Button>
</div>
</div>
) : (
<div className="space-y-3">
<div className="font-mono text-sm ml-7">
{globalConfig?.cloud?.central?.domain ? (
<a
href={`https://${globalConfig.cloud.central.domain}`}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
{globalConfig.cloud.central.domain}
</a>
) : (
<span className="text-muted-foreground italic">Not configured</span>
)}
</div>
{globalConfig?.cloud?.central?.domain && (
<div className="ml-7 space-y-2">
{certLoading ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : certStatus?.cert?.exists ? (
<div className="text-sm space-y-1">
<div className="flex items-center gap-2 text-green-600 dark:text-green-400">
<Shield className="h-4 w-4" />
<span>Valid TLS certificate</span>
</div>
<div className="text-xs text-muted-foreground">
Expires in {certStatus.cert.daysLeft} days
{certStatus.cert.issuerCN && <> &middot; {certStatus.cert.issuerCN}</>}
</div>
</div>
) : (
<div className="space-y-2">
<div className="flex items-center gap-2 text-amber-600 dark:text-amber-400 text-sm">
<KeyRound className="h-4 w-4" />
<span>No TLS certificate</span>
</div>
<Button
size="sm"
onClick={async () => {
try { await provisionCert(); } catch { /* error shown below */ }
}}
disabled={isProvisioning}
className="gap-1"
>
{isProvisioning ? <Loader2 className="h-3 w-3 animate-spin" /> : <Shield className="h-3 w-3" />}
{isProvisioning ? 'Provisioning...' : 'Provision TLS Certificate'}
</Button>
{provisionError && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription className="text-xs">{(provisionError as Error).message}</AlertDescription>
</Alert>
)}
</div>
)}
</div>
)}
</div>
)}
</Card>
{/* Verification Checklist Card */}
<Card className="p-4 border-l-4 border-l-blue-500">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<Shield className="h-5 w-5 text-blue-500" />
<div className="font-medium">Token Verification</div>
</div>
<Button
variant="outline"
size="sm"
onClick={() => reverify()}
disabled={isVerifying}
className="gap-1"
>
{isVerifying ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
Verify
</Button>
</div>
{isVerifying && !verification ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground ml-7">
<Loader2 className="h-4 w-4 animate-spin" />
Verifying token...
</div>
) : (
<div className="space-y-2 ml-7">
{/* Token configured */}
<div className="flex items-center gap-2 text-sm">
{verification?.tokenConfigured
? <CheckCircle className="h-4 w-4 text-green-500" />
: <XCircle className="h-4 w-4 text-muted-foreground" />}
<span>Token configured</span>
</div>
{/* Token valid */}
{verification?.tokenConfigured && (
<div className="flex items-center gap-2 text-sm">
{verification?.tokenValid
? <CheckCircle className="h-4 w-4 text-green-500" />
: <XCircle className="h-4 w-4 text-red-500" />}
<span>Token valid{verification?.tokenStatus ? ` (${verification.tokenStatus})` : ''}</span>
</div>
)}
{/* Accessible zones */}
{verification?.tokenValid && verification.zones && verification.zones.length > 0 && (
<div className="flex items-start gap-2 text-sm">
<CheckCircle className="h-4 w-4 text-green-500 mt-0.5" />
<div>
<span>Accessible zones: </span>
<span className="inline-flex flex-wrap gap-1 mt-1">
{verification.zones.map((zone) => (
<span key={zone.id} className="font-mono bg-muted px-2 py-0.5 rounded text-xs">
{zone.name}
</span>
))}
</span>
</div>
</div>
)}
{/* Error */}
{verification?.error && (
<div className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
<AlertCircle className="h-4 w-4" />
<span>{verification.error}</span>
</div>
)}
</div>
)}
</Card>
{/* Feature Status Card */}
<Card className="p-4 border-l-4 border-l-green-500">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<Globe className="h-5 w-5 text-green-500" />
<div className="font-medium">Features Using This Token</div>
</div>
</div>
<CardContent className="p-0 ml-7">
<div className="space-y-3">
{/* DDNS */}
<div className="flex items-center justify-between text-sm">
<div className="flex items-center gap-2">
<Cloud className="h-4 w-4 text-muted-foreground" />
<span>Dynamic DNS</span>
</div>
{ddnsStatus?.enabled
? <Badge variant="success" className="text-xs">Active</Badge>
: <Badge variant="secondary" className="text-xs">Disabled</Badge>}
</div>
{/* TLS Certificates */}
<div className="flex items-center justify-between text-sm">
<div className="flex items-center gap-2">
<Shield className="h-4 w-4 text-muted-foreground" />
<span>TLS Certificate</span>
</div>
{certStatus?.cert?.exists
? <Badge variant="success" className="text-xs">
Valid ({certStatus.cert.daysLeft}d left)
</Badge>
: certStatus?.configured
? <Badge variant="secondary" className="text-xs">Not provisioned</Badge>
: <Badge variant="secondary" className="text-xs">Not configured</Badge>}
</div>
{/* ExternalDNS note */}
<div className="flex items-center justify-between text-sm">
<div className="flex items-center gap-2">
<Globe className="h-4 w-4 text-muted-foreground" />
<span>ExternalDNS</span>
</div>
<span className="text-xs text-muted-foreground">Per-instance</span>
</div>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,49 @@
import { useState } from 'react';
import { Copy, Check } from 'lucide-react';
import { Button } from './ui/button';
interface CopyButtonProps {
content: string;
label?: string;
variant?: 'default' | 'outline' | 'secondary' | 'ghost';
disabled?: boolean;
}
export function CopyButton({
content,
label = 'Copy',
variant = 'outline',
disabled = false,
}: CopyButtonProps) {
const [copied, setCopied] = useState(false);
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy:', error);
}
};
return (
<Button
onClick={handleCopy}
variant={variant}
disabled={disabled}
>
{copied ? (
<>
<Check className="h-4 w-4" />
Copied
</>
) : (
<>
<Copy className="h-4 w-4" />
{label}
</>
)}
</Button>
);
}

View File

@@ -0,0 +1,760 @@
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Alert, AlertDescription } from './ui/alert';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import {
ShieldAlert, Loader2, AlertCircle, CheckCircle, Ban, X, Trash2,
BookOpen, Shield, Activity, Zap, RefreshCw, Globe,
} from 'lucide-react';
import { Badge } from './ui/badge';
// Instance provisioning removed — Central-only mode
import { useCrowdSec } from '../hooks/useCrowdSec';
import type { AddDecisionRequest, CrowdSecAlert } from '../services/api/networking';
type Timescale = '1h' | '6h' | '24h' | '7d';
const TIMESCALES: { key: Timescale; label: string; ms: number; bucketMs: number }[] = [
{ key: '1h', label: '1h', ms: 60 * 60 * 1000, bucketMs: 5 * 60 * 1000 },
{ key: '6h', label: '6h', ms: 6 * 60 * 60 * 1000, bucketMs: 30 * 60 * 1000 },
{ key: '24h', label: '24h', ms: 24 * 60 * 60 * 1000, bucketMs: 2 * 60 * 60 * 1000 },
{ key: '7d', label: '7d', ms: 7 * 24 * 60 * 60 * 1000, bucketMs: 24 * 60 * 60 * 1000 },
];
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
function formatBucketLabel(ts: number, scale: Timescale): string {
const d = new Date(ts);
if (scale === '7d') return d.toLocaleDateString(undefined, { timeZone: tz, weekday: 'short', month: 'short', day: 'numeric' });
return d.toLocaleTimeString(undefined, { timeZone: tz, hour: '2-digit', minute: '2-digit', hour12: false });
}
function binAlerts(alerts: CrowdSecAlert[], scale: Timescale) {
const cfg = TIMESCALES.find(t => t.key === scale)!;
const now = Date.now();
// Align start to a clean bucket boundary so labels fall on round times
const rawStart = now - cfg.ms;
const alignedStart = Math.floor(rawStart / cfg.bucketMs) * cfg.bucketMs;
const numBuckets = Math.ceil((now - alignedStart) / cfg.bucketMs);
const buckets = Array.from({ length: numBuckets }, (_, i) => ({
label: formatBucketLabel(alignedStart + i * cfg.bucketMs, scale),
detections: 0,
}));
for (const a of alerts) {
const t = new Date(a.createdAt).getTime();
if (t < alignedStart) continue;
const idx = Math.floor((t - alignedStart) / cfg.bucketMs);
if (idx >= 0 && idx < numBuckets) buckets[idx].detections++;
}
return buckets;
}
function formatRelativeTime(isoString?: string): string {
if (!isoString) return 'unknown';
const diff = Date.now() - new Date(isoString).getTime();
const minutes = Math.floor(diff / 60000);
if (minutes < 1) return 'just now';
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
function scenarioHubUrl(scenario: string): string | null {
if (!scenario) return null;
const parts = scenario.split('/');
// Only link hub scenarios in author/name format (e.g. crowdsecurity/http-probing-classb)
// CAPI category labels (http:scan, ssh:bruteforce) have no individual hub pages
if (parts.length === 2 && parts[0] !== 'custom') {
return `https://app.crowdsec.net/hub/author/${parts[0]}/configurations/name/${parts[1]}`;
}
return null;
}
const KNOWN_ABBREV = new Set(['ssh', 'http', 'https', 'tcp', 'udp', 'ftp', 'ip', 'dns', 'tls', 'dos', 'ddos', 'bf']);
function titleCaseScenario(s: string): string {
return s.replace(/[:\-_]/g, ' ').split(' ').filter(Boolean).map(w =>
KNOWN_ABBREV.has(w.toLowerCase()) ? w.toUpperCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
).join(' ');
}
function friendlyReason(reason: string): string {
if (!reason) return 'Community blocklist';
const map: Record<string, string> = {
'crowdsecurity/http-scan-classb': 'HTTP Scanner',
'crowdsecurity/ssh-slow-bruteforce': 'SSH Brute Force (slow)',
'crowdsecurity/ssh-bf': 'SSH Brute Force',
'crowdsecurity/ssh-bruteforce': 'SSH Brute Force',
'crowdsecurity/http-dos': 'HTTP DoS',
'crowdsecurity/http-bruteforce': 'HTTP Brute Force',
'crowdsecurity/http-exploit': 'HTTP Exploit',
'crowdsecurity/http-crawl': 'HTTP Crawler',
'crowdsecurity/http-bad-user-agent': 'Bad User Agent',
'crowdsecurity/iptables-scan-multi_ports': 'Port Scanner',
};
if (map[reason]) return map[reason];
const short = reason.includes('/') ? reason.split('/').slice(1).join(' ') : reason;
return titleCaseScenario(short);
}
function parseDuration(dur?: string): string {
if (!dur) return '';
// Go duration: "164h1m31s" → "6d 20h"
const h = dur.match(/(\d+)h/);
const m = dur.match(/(\d+)m/);
const hours = h ? parseInt(h[1]) : 0;
const mins = m ? parseInt(m[1]) : 0;
if (hours >= 24) {
const days = Math.floor(hours / 24);
const rem = hours % 24;
return rem > 0 ? `${days}d ${rem}h` : `${days}d`;
}
if (hours > 0) return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
return `${mins}m`;
}
interface BlockFormValues {
ip: string;
type: 'ban' | 'allow';
duration: string;
reason: string;
}
export function CrowdSecComponent() {
const instances: string[] = [];
const {
status,
isLoadingStatus,
summary,
isLoadingSummary,
alerts,
isLoadingAlerts,
refetchAlerts,
graphAlerts,
isLoadingGraphAlerts,
decisions,
addDecision,
isAddingDecision,
addDecisionError,
deleteDecision,
deleteBouncer,
deleteMachine,
provision,
isProvisioning,
} = useCrowdSec();
const [provisionResults, setProvisionResults] = useState<Record<string, { ok: boolean; message: string }>>({});
const [provisioningInstance, setProvisioningInstance] = useState<string | null>(null);
const [blockSuccess, setBlockSuccess] = useState<string | null>(null);
const [timescale, setTimescale] = useState<Timescale>('24h');
const { register, handleSubmit, reset, setValue, watch, formState: { errors } } = useForm<BlockFormValues>({
defaultValues: { ip: '', type: 'ban', duration: '24h', reason: 'manual' },
});
const selectedType = watch('type');
function handleProvision(instanceName: string) {
setProvisioningInstance(instanceName);
provision(instanceName, {
onSuccess: (data) => {
setProvisionResults((prev) => ({ ...prev, [instanceName]: { ok: true, message: data.message } }));
setProvisioningInstance(null);
},
onError: (err) => {
setProvisionResults((prev) => ({ ...prev, [instanceName]: { ok: false, message: (err as Error).message } }));
setProvisioningInstance(null);
},
});
}
function onBlockSubmit(values: BlockFormValues) {
setBlockSuccess(null);
const req: AddDecisionRequest = { ip: values.ip, type: values.type, reason: values.reason, duration: values.duration };
addDecision(req, {
onSuccess: (data) => {
setBlockSuccess(data.message);
reset();
},
});
}
const sortedReasons = summary
? Object.entries(summary.byReason).sort(([, a], [, b]) => b - a)
: [];
return (
<div className="space-y-6">
<div className="flex items-center gap-4 mb-6">
<div className="p-2 bg-primary/10 rounded-lg">
<ShieldAlert className="h-6 w-6 text-primary" />
</div>
<div>
<h2 className="text-2xl font-semibold">CrowdSec</h2>
<p className="text-muted-foreground">Collaborative intrusion detection protecting your infrastructure with community threat intelligence</p>
</div>
</div>
{/* Educational card */}
<Card className="bg-gradient-to-br from-cyan-50 to-blue-50 dark:from-cyan-900/20 dark:to-blue-900/20 border-cyan-200 dark:border-cyan-800">
<CardContent className="pt-4">
<div className="flex gap-3">
<BookOpen className="h-5 w-5 text-cyan-600 dark:text-cyan-400 shrink-0 mt-0.5" />
<div className="space-y-1 text-sm text-cyan-900 dark:text-cyan-100">
<p>
<strong>CrowdSec</strong> analyzes logs from your k8s clusters, detects attacks, and shares threat
intelligence with the community. Wild Central runs the <strong>LAPI</strong> the hub that agents
report to and that bouncers query for the live blocklist. Your cluster contributes to and benefits
from a shared blocklist of millions of known malicious IPs.
</p>
</div>
</div>
</CardContent>
</Card>
{/* LAPI Status */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Shield className="h-4 w-4 text-muted-foreground" />
<CardTitle>LAPI Status</CardTitle>
</div>
{isLoadingStatus ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : (
<Badge variant={status?.active ? 'success' : 'warning'} className="gap-1">
{status?.active && <CheckCircle className="h-3 w-3" />}
{status?.active ? 'Running' : 'Stopped'}
</Badge>
)}
</div>
</CardHeader>
<CardContent className="space-y-3">
{!status?.active && !isLoadingStatus && (
<p className="text-sm text-muted-foreground">
CrowdSec is not running on Wild Central. Install it with{' '}
<code className="font-mono text-xs bg-muted px-1 rounded">apt install crowdsec crowdsec-firewall-bouncer</code>
{' '}or reinstall wild-cloud-central.
</p>
)}
{status?.active && (
<>
<div className="flex items-center justify-between py-2 px-3 rounded bg-muted">
<div className="flex items-center gap-2 text-sm">
<Shield className="h-4 w-4 text-muted-foreground" />
<span>Perimeter firewall enforcement</span>
<span className="text-xs text-muted-foreground">(nftables on Wild Central)</span>
</div>
<Badge variant={status.firewallBouncer ? 'success' : 'warning'} className="gap-1">
{status.firewallBouncer && <CheckCircle className="h-3 w-3" />}
{status.firewallBouncer ? 'Active' : 'Stopped'}
</Badge>
</div>
{!status.firewallBouncer && (
<p className="text-xs text-muted-foreground">
Install the firewall bouncer to block threats at the perimeter:{' '}
<code className="font-mono bg-muted px-1 rounded">apt install crowdsec-firewall-bouncer</code>
</p>
)}
<p className="text-xs text-muted-foreground">
{status.machines.length > 0 && `${status.machines.length} k8s agent${status.machines.length !== 1 ? 's' : ''} reporting. `}
{status.bouncers.length > 0 && `${status.bouncers.length} enforcement point${status.bouncers.length !== 1 ? 's' : ''} active.`}
</p>
</>
)}
</CardContent>
</Card>
{status?.active && (
<>
{/* Active Protection Summary */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Activity className="h-4 w-4 text-muted-foreground" />
<CardTitle>Active Protection</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
IPs currently blocked by the community blocklist (CAPI) and local decisions, enforced by your bouncers.
</p>
{isLoadingSummary ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />Loading ban statistics
</div>
) : summary ? (
<div className="space-y-3">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Ban className="h-5 w-5 text-red-500" />
<span className="text-2xl font-bold">{summary.total.toLocaleString()}</span>
</div>
<span className="text-sm text-muted-foreground">IPs blocked right now</span>
</div>
{sortedReasons.length > 0 && (
<div className="space-y-1.5">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">By threat type</p>
{sortedReasons.slice(0, 8).map(([reason, count]) => {
const pct = Math.round((count / summary.total) * 100);
return (
<div key={reason} className="flex items-center gap-2 text-sm">
<div className="flex-1 flex items-center gap-2">
<div
className="h-1.5 bg-red-400 rounded"
style={{ width: `${Math.max(pct, 2)}%`, maxWidth: '60%' }}
/>
{scenarioHubUrl(reason) ? (
<a href={scenarioHubUrl(reason)!} target="_blank" rel="noopener noreferrer" className="text-muted-foreground hover:text-foreground hover:underline">
{friendlyReason(reason)}
</a>
) : (
<span className="text-muted-foreground">{friendlyReason(reason)}</span>
)}
</div>
<span className="font-mono text-xs tabular-nums">{count.toLocaleString()}</span>
<span className="text-xs text-muted-foreground w-8 text-right">{pct}%</span>
</div>
);
})}
{sortedReasons.length > 8 && (
<p className="text-xs text-muted-foreground">+{sortedReasons.length - 8} more categories</p>
)}
</div>
)}
</div>
) : null}
</CardContent>
</Card>
{/* Detections Over Time */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Activity className="h-4 w-4 text-muted-foreground" />
<CardTitle>Detections Over Time</CardTitle>
</div>
<div className="flex gap-1">
{TIMESCALES.map(t => (
<Button
key={t.key}
variant={timescale === t.key ? 'default' : 'ghost'}
size="sm"
className="h-7 px-2 text-xs"
onClick={() => setTimescale(t.key)}
>
{t.label}
</Button>
))}
</div>
</div>
</CardHeader>
<CardContent>
{isLoadingGraphAlerts ? (
<div className="flex items-center justify-center h-40 gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />Loading
</div>
) : (
<ResponsiveContainer width="100%" height={160}>
<BarChart data={binAlerts(graphAlerts, timescale)} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis dataKey="label" tick={{ fontSize: 10 }} interval="preserveStartEnd" className="fill-muted-foreground" />
<YAxis allowDecimals={false} tick={{ fontSize: 10 }} className="fill-muted-foreground" />
<Tooltip
contentStyle={{ fontSize: 12 }}
formatter={(v) => [v, 'detections']}
/>
<Bar dataKey="detections" fill="#ef4444" radius={[2, 2, 0, 0]} />
</BarChart>
</ResponsiveContainer>
)}
</CardContent>
</Card>
{/* Recent Alert Feed */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Activity className="h-4 w-4 text-muted-foreground" />
<CardTitle>Recent Detections</CardTitle>
</div>
<Button variant="ghost" size="sm" onClick={() => refetchAlerts()} className="h-7 gap-1.5 text-xs">
<RefreshCw className="h-3 w-3" />Refresh
</Button>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-3">
Attack events detected by your k8s agents and reported to this LAPI. Each event results in a ban
that is shared with the CrowdSec community.
</p>
{isLoadingAlerts ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />Loading
</div>
) : alerts.length === 0 ? (
<div className="text-center py-6">
<Shield className="h-10 w-10 text-muted-foreground mx-auto mb-2" />
<p className="text-sm text-muted-foreground">No detections yet.</p>
<p className="text-xs text-muted-foreground mt-1">
Events appear here when k8s agents detect and report attacks. The community blocklist
(CAPI) is already protecting you even before local detections.
</p>
</div>
) : (
<div className="space-y-1 max-h-72 overflow-y-auto">
<div className="grid grid-cols-[1fr_auto_auto_auto] gap-x-3 text-xs text-muted-foreground font-medium px-2 pb-1">
<span>Source IP</span>
<span>Threat</span>
<span>Agent</span>
<span>When</span>
</div>
{alerts.map((alert) => (
<div key={alert.id} className="grid grid-cols-[1fr_auto_auto_auto] gap-x-3 items-center py-1.5 px-2 bg-muted rounded text-sm">
<div className="flex items-center gap-1.5 min-w-0">
<span className="font-mono text-xs truncate">{alert.sourceIP || '—'}</span>
{alert.country && (
<span className="text-xs text-muted-foreground flex items-center gap-0.5 shrink-0">
<Globe className="h-3 w-3" />{alert.country}
</span>
)}
</div>
{scenarioHubUrl(alert.scenario) ? (
<a href={scenarioHubUrl(alert.scenario)!} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground whitespace-nowrap hover:text-foreground hover:underline">
{friendlyReason(alert.scenario)}
</a>
) : (
<span className="text-xs text-muted-foreground whitespace-nowrap">{friendlyReason(alert.scenario)}</span>
)}
<span className="text-xs font-mono text-muted-foreground whitespace-nowrap">{alert.machineId?.replace(/^wc-/, '') ?? '—'}</span>
<span className="text-xs text-muted-foreground whitespace-nowrap">{formatRelativeTime(alert.createdAt)}</span>
</div>
))}
</div>
)}
</CardContent>
</Card>
{/* Manual Decisions: Block / Allow */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Ban className="h-4 w-4 text-muted-foreground" />
<CardTitle>Block or Allow an IP</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">
Manually ban an IP (e.g. an attacker you've identified) or add a local allowlist entry
to prevent a legitimate IP from being blocked by the community list.
</p>
<form onSubmit={handleSubmit(onBlockSubmit)} className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<div>
<Label htmlFor="ip">IP Address</Label>
<Input
id="ip"
placeholder="1.2.3.4"
className="mt-1 font-mono"
{...register('ip', {
required: 'Required',
pattern: { value: /^[\d.:/a-fA-F]+$/, message: 'Invalid IP' },
})}
/>
{errors.ip && <p className="text-xs text-red-600 mt-1">{errors.ip.message}</p>}
</div>
<div>
<Label htmlFor="reason">Reason</Label>
<Input
id="reason"
placeholder="manual"
className="mt-1"
{...register('reason')}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label>Action</Label>
<Select value={selectedType} onValueChange={(v) => setValue('type', v as 'ban' | 'allow')}>
<SelectTrigger className="mt-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ban">Ban (block)</SelectItem>
<SelectItem value="allow">Allow (whitelist)</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label>Duration</Label>
<Select defaultValue="24h" onValueChange={(v) => setValue('duration', v)}>
<SelectTrigger className="mt-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1h">1 hour</SelectItem>
<SelectItem value="24h">24 hours</SelectItem>
<SelectItem value="168h">7 days</SelectItem>
<SelectItem value="720h">30 days</SelectItem>
<SelectItem value="8760h">1 year</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{blockSuccess && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription className="text-xs">{blockSuccess}</AlertDescription>
</Alert>
)}
{addDecisionError && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription className="text-xs">{(addDecisionError as Error).message}</AlertDescription>
</Alert>
)}
<Button type="submit" size="sm" disabled={isAddingDecision} className="gap-2">
{isAddingDecision ? <Loader2 className="h-4 w-4 animate-spin" /> : <Ban className="h-4 w-4" />}
{selectedType === 'allow' ? 'Add to Allowlist' : 'Block IP'}
</Button>
</form>
{/* Local decisions list */}
{decisions.length > 0 && (
<div className="border-t pt-3 space-y-2">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Active local decisions</p>
<div className="space-y-1 max-h-48 overflow-y-auto">
{decisions.map((d) => (
<div key={d.id} className="flex items-center justify-between py-1.5 px-2 bg-muted rounded text-xs">
<div className="flex items-center gap-2 min-w-0">
{d.type === 'allow'
? <CheckCircle className="h-3 w-3 text-green-500 shrink-0" />
: <Ban className="h-3 w-3 text-red-500 shrink-0" />
}
<span className="font-mono truncate">{d.value}</span>
<Badge variant="outline" className="text-xs h-4 shrink-0">{d.type}</Badge>
<span className="text-muted-foreground truncate">{friendlyReason(d.reason)}</span>
</div>
<div className="flex items-center gap-2 shrink-0">
{d.duration && (
<span className="text-muted-foreground">{parseDuration(d.duration)}</span>
)}
<Button
variant="ghost"
size="sm"
className="h-5 w-5 p-0 text-muted-foreground hover:text-red-500"
onClick={() => deleteDecision(d.id)}
>
<X className="h-3 w-3" />
</Button>
</div>
</div>
))}
</div>
</div>
)}
</CardContent>
</Card>
{/* Registered Agents */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Zap className="h-4 w-4 text-muted-foreground" />
<CardTitle>Registered Agents</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
<strong>Agents</strong> are CrowdSec engines running inside your k8s clusters. They analyze
logs, detect threats, and report to this LAPI. Each provisioned Wild Cloud instance registers
one agent here.
</p>
{status.machines.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-3">No agents registered. Provision an instance below.</p>
) : (
<div className="space-y-2">
{status.machines.map((m) => (
<div key={m.machineId} className="flex items-center justify-between py-2 px-3 bg-muted rounded">
<div className="space-y-0.5">
<div className="flex items-center gap-2">
<span className="font-mono text-sm">{m.machineId}</span>
<Badge variant={m.isValidated ? 'default' : 'secondary'} className="text-xs h-4">
{m.isValidated ? 'validated' : 'pending'}
</Badge>
</div>
<div className="flex items-center gap-3 text-xs text-muted-foreground">
{m.last_heartbeat && <span>heartbeat {formatRelativeTime(m.last_heartbeat)}</span>}
{m.version && <span>{m.version}</span>}
{m.ipAddress && <span className="font-mono">{m.ipAddress}</span>}
</div>
</div>
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0 text-muted-foreground hover:text-red-500"
onClick={() => deleteMachine(m.machineId)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
</CardContent>
</Card>
{/* Registered Bouncers */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Shield className="h-4 w-4 text-muted-foreground" />
<CardTitle>Registered Bouncers</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
<strong>Bouncers</strong> enforce the blocklist. Wild Central's nftables bouncer blocks at
the network perimeter. Each k8s cluster also runs a Traefik bouncer as a second layer.
</p>
{status.bouncers.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-3">No bouncers registered. Provision an instance to add them.</p>
) : (
<div className="space-y-2">
{status.bouncers.map((b) => {
const isFirewallBouncer = b.type === 'crowdsec-firewall-bouncer';
return (
<div key={b.name} className="flex items-center justify-between py-2 px-3 bg-muted rounded">
<div className="space-y-0.5">
<div className="flex items-center gap-2">
<span className="font-mono text-sm truncate max-w-64">{b.name}</span>
<Badge variant={b.revoked ? 'secondary' : 'default'} className="text-xs h-4">
{b.revoked ? 'revoked' : 'active'}
</Badge>
{isFirewallBouncer && (
<Badge variant="outline" className="text-xs h-4 border-orange-400 text-orange-600 dark:text-orange-400">
perimeter
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground">
{isFirewallBouncer ? 'Crowdsec Firewall Bouncer' : b.type?.replace(/-/g, ' ') || ''}
</p>
</div>
{!isFirewallBouncer && (
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0 text-muted-foreground hover:text-red-500"
onClick={() => deleteBouncer(b.name)}
>
<Trash2 className="h-3 w-3" />
</Button>
)}
</div>
);
})}
</div>
)}
</CardContent>
</Card>
{/* Provision Instances */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Zap className="h-4 w-4 text-muted-foreground" />
<CardTitle>Provision Instances</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
<strong>Provisioning</strong> connects a Wild Cloud instance's CrowdSec agent to this LAPI —
generating credentials, registering agent and bouncer, and writing the LAPI URL into the
instance's app config. After provisioning, redeploy the CrowdSec app on the instance.
Safe to re-run.
</p>
<div className="space-y-2">
{instances.length === 0 ? (
<p className="text-sm text-muted-foreground">No instances found.</p>
) : (
instances.map((instanceName) => {
const agentName = `wc-${instanceName}`;
const bouncerName = `wc-bouncer-${instanceName}`;
const agent = status.machines.find((m) => m.machineId === agentName);
const bouncer = status.bouncers.find((b) => b.name === bouncerName);
const isActive = provisioningInstance === instanceName;
const result = provisionResults[instanceName];
return (
<div key={instanceName} className="rounded border p-3 space-y-2">
<div className="flex items-center justify-between">
<span className="font-mono text-sm font-medium">{instanceName}</span>
<Button
size="sm"
variant={agent ? 'outline' : 'default'}
onClick={() => handleProvision(instanceName)}
disabled={isProvisioning || isActive}
className="gap-2 h-7"
>
{isActive
? <><Loader2 className="h-3 w-3 animate-spin" />Provisioning</>
: agent
? <><Zap className="h-3 w-3" />Re-provision</>
: <><Zap className="h-3 w-3" />Provision</>
}
</Button>
</div>
<div className="flex items-center gap-4 text-xs">
<div className="flex items-center gap-1.5">
<span className="text-muted-foreground">Agent:</span>
{agent ? (
<Badge variant={agent.isValidated ? 'default' : 'secondary'} className="text-xs h-4">
{agent.isValidated ? 'validated' : 'pending'}
{agent.last_heartbeat && ` · ${formatRelativeTime(agent.last_heartbeat)}`}
</Badge>
) : (
<span className="text-muted-foreground italic">not provisioned</span>
)}
</div>
<div className="flex items-center gap-1.5">
<span className="text-muted-foreground">Bouncer:</span>
{bouncer ? (
<Badge variant={bouncer.revoked ? 'secondary' : 'default'} className="text-xs h-4">
{bouncer.revoked ? 'revoked' : 'active'}
</Badge>
) : (
<span className="text-muted-foreground italic">not provisioned</span>
)}
</div>
</div>
{result && (
<Alert variant={result.ok ? 'default' : 'error'} className="py-2">
{result.ok ? <CheckCircle className="h-3 w-3" /> : <AlertCircle className="h-3 w-3" />}
<AlertDescription className="text-xs">{result.message}</AlertDescription>
</Alert>
)}
</div>
);
})
)}
</div>
</CardContent>
</Card>
</>
)}
</div>
);
}

View File

@@ -0,0 +1,280 @@
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input, Label } from './ui';
import { Textarea } from './ui/textarea';
import { Alert, AlertDescription } from './ui/alert';
import { Globe, Loader2, AlertCircle, CheckCircle, XCircle, RefreshCw, Edit2 } from 'lucide-react';
import { Badge } from './ui/badge';
import { useConfig } from '../hooks';
import { useDdns } from '../hooks/useDdns';
import { secretsApi } from '../services/api';
import type { DdnsRecordStatus } from '../services/api/networking';
export function DdnsComponent() {
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
const { status: ddnsStatus, isLoadingStatus: isDdnsLoading, trigger: triggerDdns, isTriggering: isDdnsTriggering } = useDdns();
const queryClient = useQueryClient();
const { data: globalSecrets } = useQuery({
queryKey: ['globalSecrets'],
queryFn: () => secretsApi.get(),
});
const updateSecretsMutation = useMutation({
mutationFn: (values: Record<string, unknown>) => secretsApi.update(values),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['globalSecrets'] });
setEditingToken(false);
setTokenValue('');
},
});
const cfTokenIsSet = !!(globalSecrets as Record<string, unknown> | undefined)
&& !!(globalSecrets as { ddns?: { cloudflare?: { apiToken?: string } } })?.ddns?.cloudflare?.apiToken;
const [editingDdnsConfig, setEditingDdnsConfig] = useState(false);
const [ddnsConfigForm, setDdnsConfigForm] = useState({ enabled: false, records: '', intervalMinutes: 5 });
const [editingToken, setEditingToken] = useState(false);
const [tokenValue, setTokenValue] = useState('');
const handleDdnsConfigEdit = () => {
setDdnsConfigForm({
enabled: globalConfig?.cloud?.ddns?.enabled ?? false,
records: (globalConfig?.cloud?.ddns?.records ?? []).join('\n'),
intervalMinutes: globalConfig?.cloud?.ddns?.intervalMinutes ?? 5,
});
setEditingDdnsConfig(true);
};
const handleDdnsConfigSave = async () => {
if (!globalConfig) return;
const records = ddnsConfigForm.records.split('\n').map(r => r.trim()).filter(Boolean);
await updateConfig({
...globalConfig,
cloud: {
...globalConfig.cloud,
ddns: {
enabled: ddnsConfigForm.enabled,
provider: 'cloudflare',
records,
intervalMinutes: ddnsConfigForm.intervalMinutes,
},
},
});
setEditingDdnsConfig(false);
};
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<div className="p-2 bg-primary/10 rounded-lg">
<Globe className="h-6 w-6 text-primary" />
</div>
<div>
<h2 className="text-2xl font-semibold">Dynamic DNS</h2>
<p className="text-muted-foreground">Keeps your Cloudflare A records pointed at your current public IP</p>
</div>
</div>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Status</CardTitle>
{isDdnsLoading ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : ddnsStatus?.enabled ? (
<Badge variant="success" className="gap-1">
<CheckCircle className="h-3 w-3" />
Active
</Badge>
) : (
<Badge variant="secondary">Disabled</Badge>
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
{ddnsStatus?.enabled && (
<div className="space-y-3">
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-muted-foreground">Public IP</span>
<div className="font-mono font-medium mt-0.5">{ddnsStatus.currentIP || '—'}</div>
</div>
<div>
<span className="text-muted-foreground">Last checked</span>
<div className="font-mono mt-0.5">
{ddnsStatus.lastChecked ? new Date(ddnsStatus.lastChecked).toLocaleTimeString() : '—'}
</div>
</div>
</div>
{ddnsStatus.lastError && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription className="text-xs">{ddnsStatus.lastError}</AlertDescription>
</Alert>
)}
<Button
variant="outline"
size="sm"
onClick={() => triggerDdns()}
disabled={isDdnsTriggering}
className="gap-2"
>
{isDdnsTriggering ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
Check Now
</Button>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Configuration</CardTitle>
{!editingDdnsConfig && (
<Button variant="outline" size="sm" onClick={handleDdnsConfigEdit} className="gap-1">
<Edit2 className="h-3 w-3" />
Edit
</Button>
)}
</div>
</CardHeader>
<CardContent>
{editingDdnsConfig ? (
<div className="space-y-3">
<div className="flex items-center gap-2">
<input
type="checkbox"
id="ddns-enabled"
checked={ddnsConfigForm.enabled}
onChange={e => setDdnsConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
/>
<Label htmlFor="ddns-enabled">Enabled</Label>
</div>
<div>
<Label>A Records (one per line)</Label>
<Textarea
value={ddnsConfigForm.records}
onChange={e => setDdnsConfigForm(prev => ({ ...prev, records: e.target.value }))}
placeholder={'cloud.example.com\ncloud2.example.com'}
className="text-sm h-20 mt-1 font-mono"
/>
</div>
<div>
<Label>Check interval (minutes)</Label>
<Input
type="number"
value={ddnsConfigForm.intervalMinutes}
onChange={e => setDdnsConfigForm(prev => ({ ...prev, intervalMinutes: parseInt(e.target.value) || 5 }))}
className="h-9 mt-1 w-24"
min={1}
/>
</div>
<div className="flex gap-2">
<Button size="sm" onClick={handleDdnsConfigSave} disabled={isUpdating}>
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
Save
</Button>
<Button variant="outline" size="sm" onClick={() => setEditingDdnsConfig(false)}>
Cancel
</Button>
</div>
</div>
) : (
<div className="space-y-2 text-sm">
<div className="flex items-center gap-2">
<span className="text-muted-foreground">Status:</span>
<span>{globalConfig?.cloud?.ddns?.enabled ? 'Enabled' : 'Disabled'}</span>
</div>
{globalConfig?.cloud?.ddns?.records?.length ? (
<div>
<span className="text-muted-foreground">Records:</span>
<div className="mt-1 space-y-1">
{globalConfig.cloud.ddns.records.map(r => {
const rs: DdnsRecordStatus | undefined = ddnsStatus?.records?.find(s => s.name === r);
return (
<div key={r} className="flex items-center gap-2 text-xs">
{rs?.ok ? (
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
) : rs && !rs.ok ? (
<XCircle className="h-3.5 w-3.5 text-red-500 shrink-0" />
) : null}
<span className="font-mono bg-muted px-2 py-0.5 rounded">{r}</span>
{rs?.ok && rs.ip && (
<span className="text-muted-foreground font-mono">{rs.ip}</span>
)}
{rs && !rs.ok && rs.error && (
<span className="text-red-500 truncate" title={rs.error}>{rs.error}</span>
)}
</div>
);
})}
</div>
</div>
) : (
<div className="text-muted-foreground text-xs">No A records configured</div>
)}
{(globalConfig?.cloud?.ddns?.intervalMinutes ?? 0) > 0 && (
<div className="text-muted-foreground text-xs">
Checks every {globalConfig!.cloud!.ddns!.intervalMinutes} min
</div>
)}
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Cloudflare API Token</CardTitle>
{!editingToken && (
<Button variant="outline" size="sm" onClick={() => setEditingToken(true)} className="gap-1">
<Edit2 className="h-3 w-3" />
{cfTokenIsSet ? 'Update' : 'Set'}
</Button>
)}
</div>
</CardHeader>
<CardContent>
{cfTokenIsSet ? (
<p className="text-sm text-green-600 dark:text-green-400">Configured</p>
) : (
<p className="text-sm text-muted-foreground">Not set required for DDNS to work</p>
)}
{editingToken && (
<div className="mt-3 space-y-2">
<Input
type="password"
placeholder="Cloudflare API token..."
value={tokenValue}
onChange={(e) => setTokenValue(e.target.value)}
/>
<div className="flex gap-2">
<Button
size="sm"
onClick={() => updateSecretsMutation.mutate({ ddns: { cloudflare: { apiToken: tokenValue } } })}
disabled={updateSecretsMutation.isPending || !tokenValue}
>
{updateSecretsMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
Save
</Button>
<Button
variant="outline"
size="sm"
onClick={() => { setEditingToken(false); setTokenValue(''); }}
>
Cancel
</Button>
</div>
{updateSecretsMutation.isError && (
<p className="text-xs text-red-500">{String(updateSecretsMutation.error)}</p>
)}
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,350 @@
import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input, Label } from './ui';
import { Alert, AlertDescription } from './ui/alert';
import { Wifi, Loader2, Edit2, Check, X, Trash2, Plus, RotateCw, CheckCircle, AlertCircle } from 'lucide-react';
import { Badge } from './ui/badge';
import { useConfig } from '../hooks';
import { useDhcp } from '../hooks/useDhcp';
import { useDnsmasq } from '../hooks/useDnsmasq';
import type { DhcpStaticLease } from '../services/api/networking';
export function DhcpComponent() {
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
const { leases, isLoadingLeases, refetchLeases, addStatic, isAddingStatic, deleteStatic } = useDhcp();
const { generateConfig: generateDnsConfig } = useDnsmasq();
const [editingDhcpConfig, setEditingDhcpConfig] = useState(false);
const [dhcpConfigForm, setDhcpConfigForm] = useState({ enabled: false, rangeStart: '', rangeEnd: '', leaseTime: '24h', gateway: '' });
const [showAddLease, setShowAddLease] = useState(false);
const [newLease, setNewLease] = useState<DhcpStaticLease>({ mac: '', ip: '', hostname: '' });
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const showSuccess = (msg: string) => {
setSuccessMessage(msg);
setErrorMessage(null);
setTimeout(() => setSuccessMessage(null), 5000);
};
const showError = (msg: string) => {
setErrorMessage(msg);
setSuccessMessage(null);
setTimeout(() => setErrorMessage(null), 8000);
};
const handleDhcpConfigEdit = () => {
setDhcpConfigForm({
enabled: globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ?? false,
rangeStart: globalConfig?.cloud?.dnsmasq?.dhcp?.rangeStart ?? '',
rangeEnd: globalConfig?.cloud?.dnsmasq?.dhcp?.rangeEnd ?? '',
leaseTime: globalConfig?.cloud?.dnsmasq?.dhcp?.leaseTime ?? '24h',
gateway: globalConfig?.cloud?.dnsmasq?.dhcp?.gateway ?? '',
});
setEditingDhcpConfig(true);
};
const handleDhcpConfigSave = async () => {
if (!globalConfig) return;
try {
await updateConfig({
...globalConfig,
cloud: {
...globalConfig.cloud,
dnsmasq: {
...globalConfig.cloud?.dnsmasq,
dhcp: {
enabled: dhcpConfigForm.enabled,
rangeStart: dhcpConfigForm.rangeStart,
rangeEnd: dhcpConfigForm.rangeEnd,
leaseTime: dhcpConfigForm.leaseTime,
gateway: dhcpConfigForm.gateway || undefined,
},
},
},
});
setEditingDhcpConfig(false);
if (dhcpConfigForm.enabled) {
generateDnsConfig(true);
}
showSuccess(dhcpConfigForm.enabled ? 'DHCP configuration saved and applied' : 'DHCP disabled');
} catch (e) {
showError(`Failed to save DHCP config: ${e instanceof Error ? e.message : String(e)}`);
}
};
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<div className="p-2 bg-primary/10 rounded-lg">
<Wifi className="h-6 w-6 text-primary" />
</div>
<div>
<h2 className="text-2xl font-semibold">DHCP</h2>
<p className="text-muted-foreground">Assigns IP addresses to devices on your local network</p>
</div>
</div>
{successMessage && (
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
</Alert>
)}
{errorMessage && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{errorMessage}</AlertDescription>
</Alert>
)}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Configuration</CardTitle>
<div className="flex items-center gap-2">
<Badge variant={globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? 'success' : 'secondary'} className="gap-1">
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled && <CheckCircle className="h-3 w-3" />}
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? 'Enabled' : 'Disabled'}
</Badge>
{!editingDhcpConfig && (
<Button variant="outline" size="sm" onClick={handleDhcpConfigEdit} className="gap-1 h-7 text-xs">
<Edit2 className="h-3 w-3" />
Configure
</Button>
)}
</div>
</div>
</CardHeader>
<CardContent className="space-y-3">
{editingDhcpConfig ? (
<div className="space-y-3">
<div className="flex items-center gap-2">
<input
type="checkbox"
id="dhcp-enabled"
checked={dhcpConfigForm.enabled}
onChange={e => setDhcpConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
/>
<Label htmlFor="dhcp-enabled">Enable DHCP server</Label>
</div>
{dhcpConfigForm.enabled && (
<>
<div className="grid grid-cols-2 gap-3">
<div>
<Label htmlFor="dhcp-range-start">Range Start</Label>
<Input
id="dhcp-range-start"
value={dhcpConfigForm.rangeStart}
onChange={e => setDhcpConfigForm(prev => ({ ...prev, rangeStart: e.target.value }))}
placeholder="192.168.8.100"
className="mt-1 font-mono text-sm"
/>
</div>
<div>
<Label htmlFor="dhcp-range-end">Range End</Label>
<Input
id="dhcp-range-end"
value={dhcpConfigForm.rangeEnd}
onChange={e => setDhcpConfigForm(prev => ({ ...prev, rangeEnd: e.target.value }))}
placeholder="192.168.8.200"
className="mt-1 font-mono text-sm"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label htmlFor="dhcp-lease-time">Lease Time</Label>
<Input
id="dhcp-lease-time"
value={dhcpConfigForm.leaseTime}
onChange={e => setDhcpConfigForm(prev => ({ ...prev, leaseTime: e.target.value }))}
placeholder="24h"
className="mt-1 font-mono text-sm"
/>
</div>
<div>
<Label htmlFor="dhcp-gateway">Gateway (optional)</Label>
<Input
id="dhcp-gateway"
value={dhcpConfigForm.gateway}
onChange={e => setDhcpConfigForm(prev => ({ ...prev, gateway: e.target.value }))}
placeholder="192.168.8.1"
className="mt-1 font-mono text-sm"
/>
</div>
</div>
</>
)}
<div className="flex gap-2">
<Button size="sm" onClick={handleDhcpConfigSave} disabled={isUpdating}>
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
Save
</Button>
<Button variant="outline" size="sm" onClick={() => setEditingDhcpConfig(false)}>
Cancel
</Button>
</div>
</div>
) : (
<div className="space-y-2 text-sm">
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? (
<>
<div className="flex items-center gap-4">
<div>
<span className="text-muted-foreground">Range: </span>
<span className="font-mono">
{globalConfig.cloud.dnsmasq.dhcp.rangeStart} {globalConfig.cloud.dnsmasq.dhcp.rangeEnd}
</span>
</div>
<div>
<span className="text-muted-foreground">Lease: </span>
<span className="font-mono">{globalConfig.cloud.dnsmasq.dhcp.leaseTime || '24h'}</span>
</div>
</div>
{globalConfig.cloud.dnsmasq.dhcp.gateway && (
<div>
<span className="text-muted-foreground">Gateway: </span>
<span className="font-mono">{globalConfig.cloud.dnsmasq.dhcp.gateway}</span>
</div>
)}
</>
) : (
<p className="text-muted-foreground text-xs">DHCP is disabled. Enable it to assign IPs to LAN devices.</p>
)}
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Leases</CardTitle>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => refetchLeases()} className="gap-1">
<RotateCw className="h-3 w-3" />
Refresh
</Button>
<Button size="sm" onClick={() => setShowAddLease(!showAddLease)} className="gap-1">
<Plus className="h-3 w-3" />
Static
</Button>
</div>
</div>
</CardHeader>
<CardContent className="space-y-3">
{showAddLease && (
<Card className="p-3 border-dashed">
<div className="grid grid-cols-3 gap-2 mb-2">
<div>
<Label htmlFor="lease-mac" className="text-xs">MAC Address</Label>
<Input
id="lease-mac"
value={newLease.mac}
onChange={(e) => setNewLease(l => ({ ...l, mac: e.target.value }))}
placeholder="aa:bb:cc:dd:ee:ff"
className="mt-1 font-mono text-xs"
/>
</div>
<div>
<Label htmlFor="lease-ip" className="text-xs">IP Address</Label>
<Input
id="lease-ip"
value={newLease.ip}
onChange={(e) => setNewLease(l => ({ ...l, ip: e.target.value }))}
placeholder="192.168.8.10"
className="mt-1 font-mono text-xs"
/>
</div>
<div>
<Label htmlFor="lease-hostname" className="text-xs">Hostname (optional)</Label>
<Input
id="lease-hostname"
value={newLease.hostname ?? ''}
onChange={(e) => setNewLease(l => ({ ...l, hostname: e.target.value }))}
placeholder="node1"
className="mt-1 text-xs"
/>
</div>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" size="sm" onClick={() => setShowAddLease(false)}>
<X className="h-3 w-3 mr-1" />Cancel
</Button>
<Button
size="sm"
disabled={!newLease.mac || !newLease.ip || isAddingStatic}
onClick={() => {
addStatic(newLease, {
onSuccess: () => {
showSuccess(`Static lease added for ${newLease.ip}`);
setShowAddLease(false);
setNewLease({ mac: '', ip: '', hostname: '' });
},
onError: (e: Error) => {
showError(`Failed to add lease: ${e.message}`);
},
});
}}
>
{isAddingStatic ? <Loader2 className="h-3 w-3 mr-1 animate-spin" /> : <Check className="h-3 w-3 mr-1" />}
Add
</Button>
</div>
</Card>
)}
{isLoadingLeases ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : leases.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">
No active leases. DHCP must be enabled in config.
</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-xs">
<thead>
<tr className="text-muted-foreground border-b">
<th className="text-left pb-1">MAC</th>
<th className="text-left pb-1">IP</th>
<th className="text-left pb-1">Hostname</th>
<th className="text-left pb-1">Expires</th>
<th className="pb-1" />
</tr>
</thead>
<tbody>
{leases.map((lease) => (
<tr key={lease.mac} className="border-b last:border-0">
<td className="py-1 font-mono">{lease.mac}</td>
<td className="py-1 font-mono">{lease.ip}</td>
<td className="py-1">{lease.hostname || '—'}</td>
<td className="py-1 text-muted-foreground">
{lease.expiry ? new Date(lease.expiry).toLocaleString() : '—'}
</td>
<td className="py-1">
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-muted-foreground hover:text-red-500"
onClick={() => deleteStatic(lease.mac, {
onSuccess: () => showSuccess(`Lease for ${lease.mac} deleted`),
onError: (e: Error) => showError(`Failed to delete lease: ${e.message}`),
})}
>
<Trash2 className="h-3 w-3" />
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,484 @@
import { useState } from 'react';
import { NavLink } from 'react-router';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input, Label } from './ui';
import { Textarea } from './ui/textarea';
import { Alert, AlertDescription } from './ui/alert';
import {
Router, Globe, Loader2, AlertCircle, CheckCircle, XCircle,
Play, RotateCw, Copy, ChevronDown, ChevronUp, Edit2,
RefreshCw, ExternalLink, TestTube2,
} from 'lucide-react';
import { Badge } from './ui/badge';
import { useConfig } from '../hooks';
import { useCloudflare } from '../hooks/useCloudflare';
import { useDnsmasq } from '../hooks/useDnsmasq';
import { useDdns } from '../hooks/useDdns';
import { apiService } from '../services/api-legacy';
import type { DdnsRecordStatus } from '../services/api/networking';
export function DnsComponent() {
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
// ── LAN DNS (dnsmasq) ──
const {
status: dnsStatus,
isLoadingStatus: isDnsStatusLoading,
config: dnsConfig,
fetchConfig: fetchDnsConfig,
generateConfig: generateDnsConfig,
isGenerating: isDnsGenerating,
generateData: dnsGenerateData,
restart: restartDns,
isRestarting: isDnsRestarting,
restartData: dnsRestartData,
generateError: dnsGenerateError,
restartError: dnsRestartError,
} = useDnsmasq();
const [showDnsAdvanced, setShowDnsAdvanced] = useState(false);
const [editedDnsConfig, setEditedDnsConfig] = useState('');
const [originalDnsConfig, setOriginalDnsConfig] = useState('');
const [copiedDnsIp, setCopiedDnsIp] = useState(false);
const isDnsRunning = dnsStatus?.status === 'active';
const dnsIp = dnsStatus?.ip;
const handleCopyDnsIp = () => {
if (dnsIp) {
navigator.clipboard.writeText(dnsIp);
setCopiedDnsIp(true);
setTimeout(() => setCopiedDnsIp(false), 2000);
}
};
const handleShowDnsAdvanced = async () => {
if (!showDnsAdvanced) {
const result = await fetchDnsConfig();
const content = result.data?.content || dnsConfig?.content || '';
setEditedDnsConfig(content);
setOriginalDnsConfig(content);
}
setShowDnsAdvanced(!showDnsAdvanced);
};
const handleSaveDnsConfig = async () => {
try {
await apiService.writeDnsmasqConfig(editedDnsConfig);
fetchDnsConfig();
} catch (error) {
console.error('Failed to save config:', error);
}
};
const handleSaveAndRestartDns = async () => {
try {
await apiService.writeDnsmasqConfig(editedDnsConfig);
await apiService.restartDnsmasq();
fetchDnsConfig();
} catch (error) {
console.error('Failed to save config and restart:', error);
}
};
// ── Dynamic DNS ──
const { status: ddnsStatus, isLoadingStatus: isDdnsLoading, trigger: triggerDdns, isTriggering: isDdnsTriggering } = useDdns();
const { verification: cfVerification } = useCloudflare();
const [editingDdnsConfig, setEditingDdnsConfig] = useState(false);
const [ddnsConfigForm, setDdnsConfigForm] = useState({ enabled: false, records: '', intervalMinutes: 5 });
const handleDdnsConfigEdit = () => {
setDdnsConfigForm({
enabled: globalConfig?.cloud?.ddns?.enabled ?? false,
records: (globalConfig?.cloud?.ddns?.records ?? []).join('\n'),
intervalMinutes: globalConfig?.cloud?.ddns?.intervalMinutes ?? 5,
});
setEditingDdnsConfig(true);
};
const handleDdnsConfigSave = async () => {
if (!globalConfig) return;
const records = ddnsConfigForm.records.split('\n').map(r => r.trim()).filter(Boolean);
await updateConfig({
...globalConfig,
cloud: {
...globalConfig.cloud,
ddns: {
enabled: ddnsConfigForm.enabled,
provider: 'cloudflare',
records,
intervalMinutes: ddnsConfigForm.intervalMinutes,
},
},
});
setEditingDdnsConfig(false);
};
// ── DNS Lookup ──
const [lookupDomain, setLookupDomain] = useState('');
const [lookupTesting, setLookupTesting] = useState<'external' | 'internal' | null>(null);
const [lookupResult, setLookupResult] = useState<{ type: string; success: boolean; message: string } | null>(null);
const handleLookup = async (type: 'external' | 'internal') => {
const domain = lookupDomain.trim();
if (!domain) return;
setLookupTesting(type);
setLookupResult(null);
try {
if (type === 'external') {
const response = await fetch(`https://cloudflare-dns.com/dns-query?name=${domain}&type=A`, {
headers: { accept: 'application/dns-json' },
});
const data = await response.json();
if (data.Status === 0 && data.Answer?.length > 0) {
const aRecord = data.Answer.find((a: { type: number; data: string }) => a.type === 1);
const ip = aRecord ? aRecord.data : data.Answer[data.Answer.length - 1].data;
setLookupResult({ type: 'External', success: true, message: `Resolves to ${ip}` });
} else {
setLookupResult({ type: 'External', success: false, message: 'No public DNS record found' });
}
} else {
const response = await fetch(`/api/v1/network/resolve?domain=${domain}`);
const data = await response.json();
if (data.success && data.ip) {
setLookupResult({ type: 'LAN', success: true, message: `Resolves to ${data.ip}` });
} else {
setLookupResult({ type: 'LAN', success: false, message: data.error || 'Not resolved on LAN' });
}
}
} catch {
setLookupResult({ type: type === 'external' ? 'External' : 'LAN', success: false, message: 'Lookup failed' });
} finally {
setLookupTesting(null);
}
};
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<div className="p-2 bg-primary/10 rounded-lg">
<Globe className="h-6 w-6 text-primary" />
</div>
<div>
<h2 className="text-2xl font-semibold">DNS</h2>
<p className="text-muted-foreground">LAN name resolution and public DNS record management</p>
</div>
</div>
{/* ── LAN DNS ── */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Router className="h-5 w-5 text-muted-foreground" />
<CardTitle>LAN DNS</CardTitle>
</div>
<Badge variant={isDnsRunning ? 'success' : 'warning'} className="gap-1">
{isDnsStatusLoading ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : isDnsRunning ? (
<CheckCircle className="h-3 w-3" />
) : null}
{isDnsStatusLoading ? 'Checking...' : isDnsRunning ? 'Running' : 'Stopped'}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between p-3 bg-muted/30 rounded-lg">
<div>
<div className="text-xs text-muted-foreground mb-0.5">Set as primary DNS in your router</div>
<code className="text-lg font-mono font-bold">{dnsIp || 'Auto-detecting...'}</code>
</div>
<Button variant="outline" size="sm" onClick={handleCopyDnsIp} disabled={!dnsIp} className="gap-2">
<Copy className="h-4 w-4" />
{copiedDnsIp ? 'Copied!' : 'Copy'}
</Button>
</div>
{globalConfig?.cloud?.router?.ip && (
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
Router: <span className="font-mono">{globalConfig.cloud.router.ip}</span>
</span>
<Button
variant="ghost"
size="sm"
onClick={() => window.open(`http://${globalConfig?.cloud?.router?.ip}`, '_blank')}
className="gap-1 text-xs"
>
<ExternalLink className="h-3 w-3" />
Open Admin
</Button>
</div>
)}
<div className="flex gap-2">
{!isDnsRunning ? (
<Button onClick={() => generateDnsConfig(true)} disabled={isDnsGenerating} className="gap-2">
{isDnsGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
Start DNS
</Button>
) : (
<Button onClick={() => restartDns()} disabled={isDnsRestarting} variant="outline" className="gap-2">
{isDnsRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
Restart
</Button>
)}
<Button onClick={handleShowDnsAdvanced} variant="outline" className="gap-2">
{showDnsAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
Advanced
</Button>
</div>
{(dnsGenerateData || dnsRestartData) && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>{dnsGenerateData?.message || dnsRestartData?.message}</AlertDescription>
</Alert>
)}
{(dnsGenerateError || dnsRestartError) && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{(dnsGenerateError || dnsRestartError)?.toString()}</AlertDescription>
</Alert>
)}
{showDnsAdvanced && (
<div className="border-t pt-4 space-y-3">
<span className="text-sm font-medium">Config file</span>
<Textarea
value={editedDnsConfig}
onChange={(e) => setEditedDnsConfig(e.target.value)}
className="font-mono text-xs min-h-[300px]"
placeholder="# dnsmasq configuration"
/>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={handleSaveDnsConfig} className="gap-2">
Save
</Button>
<Button size="sm" onClick={handleSaveAndRestartDns} className="gap-2">
Save & Restart
</Button>
<Button variant="ghost" size="sm" onClick={() => setEditedDnsConfig(originalDnsConfig)} disabled={editedDnsConfig === originalDnsConfig} className="gap-2">
Reset
</Button>
</div>
</div>
)}
</CardContent>
</Card>
{/* ── Dynamic DNS ── */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Globe className="h-5 w-5 text-muted-foreground" />
<CardTitle>Dynamic DNS</CardTitle>
</div>
{isDdnsLoading ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : ddnsStatus?.enabled ? (
<Badge variant="success" className="gap-1">
<CheckCircle className="h-3 w-3" />
Active
</Badge>
) : (
<Badge variant="secondary">Disabled</Badge>
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
{ddnsStatus?.enabled && (
<div className="space-y-3">
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-muted-foreground">Public IP</span>
<div className="font-mono font-medium mt-0.5">{ddnsStatus.currentIP || '—'}</div>
</div>
<div>
<span className="text-muted-foreground">Last checked</span>
<div className="font-mono mt-0.5">
{ddnsStatus.lastChecked ? new Date(ddnsStatus.lastChecked).toLocaleTimeString() : '—'}
</div>
</div>
</div>
{ddnsStatus.lastError && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription className="text-xs">{ddnsStatus.lastError}</AlertDescription>
</Alert>
)}
<Button
variant="outline"
size="sm"
onClick={() => triggerDdns()}
disabled={isDdnsTriggering}
className="gap-2"
>
{isDdnsTriggering ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
Check Now
</Button>
</div>
)}
<div className={ddnsStatus?.enabled ? 'border-t pt-4' : ''}>
<div className="flex items-center justify-between mb-3">
<span className="text-sm font-medium">A Records</span>
{!editingDdnsConfig && (
<Button variant="outline" size="sm" onClick={handleDdnsConfigEdit} className="gap-1">
<Edit2 className="h-3 w-3" />
Edit
</Button>
)}
</div>
{editingDdnsConfig ? (
<div className="space-y-3">
<div className="flex items-center gap-2">
<input
type="checkbox"
id="ddns-enabled"
checked={ddnsConfigForm.enabled}
onChange={e => setDdnsConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
/>
<Label htmlFor="ddns-enabled">Enabled</Label>
</div>
<div>
<Label>Domains (one per line)</Label>
<Textarea
value={ddnsConfigForm.records}
onChange={e => setDdnsConfigForm(prev => ({ ...prev, records: e.target.value }))}
placeholder={'cloud.example.com\nexample.org'}
className="text-sm h-24 mt-1 font-mono"
/>
</div>
<div>
<Label>Check interval (minutes)</Label>
<Input
type="number"
value={ddnsConfigForm.intervalMinutes}
onChange={e => setDdnsConfigForm(prev => ({ ...prev, intervalMinutes: parseInt(e.target.value) || 5 }))}
className="h-9 mt-1 w-24"
min={1}
/>
</div>
<div className="flex gap-2">
<Button size="sm" onClick={handleDdnsConfigSave} disabled={isUpdating}>
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
Save
</Button>
<Button variant="outline" size="sm" onClick={() => setEditingDdnsConfig(false)}>Cancel</Button>
</div>
</div>
) : (
<div className="space-y-1">
{(globalConfig?.cloud?.ddns?.records ?? []).length > 0 ? (
<>
{(globalConfig?.cloud?.ddns?.records ?? []).map(r => {
const rs: DdnsRecordStatus | undefined = ddnsStatus?.records?.find(s => s.name === r);
return (
<div key={r} className="flex items-center gap-2 text-xs">
{rs?.ok ? (
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
) : rs && !rs.ok ? (
<XCircle className="h-3.5 w-3.5 text-red-500 shrink-0" />
) : (
<div className="h-3.5 w-3.5 shrink-0" />
)}
<span className="font-mono bg-muted px-2 py-0.5 rounded">{r}</span>
{rs?.ok && rs.ip && <span className="text-muted-foreground font-mono">{rs.ip}</span>}
{rs && !rs.ok && rs.error && (
<span className="text-red-500 truncate" title={rs.error}>{rs.error}</span>
)}
</div>
);
})}
{(globalConfig?.cloud?.ddns?.intervalMinutes ?? 0) > 0 && (
<div className="text-muted-foreground text-xs pt-1">
Checks every {globalConfig!.cloud!.ddns!.intervalMinutes} min
</div>
)}
</>
) : (
<p className="text-xs text-muted-foreground">No records configured</p>
)}
</div>
)}
</div>
{cfVerification && !cfVerification.tokenConfigured && (
<div className="flex items-center gap-3 rounded-md border border-amber-300 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-700 px-4 py-3 text-sm text-amber-800 dark:text-amber-300">
<AlertCircle className="h-4 w-4 shrink-0" />
<span>
Cloudflare API token not configured. DDNS requires a valid token.{' '}
<NavLink to="/central/cloudflare" className="underline font-medium">Configure token</NavLink>
</span>
</div>
)}
</CardContent>
</Card>
{/* ── DNS Lookup ── */}
<Card>
<CardHeader>
<div className="flex items-center gap-3">
<TestTube2 className="h-5 w-5 text-muted-foreground" />
<CardTitle>DNS Lookup</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex gap-2">
<Input
placeholder="cloud.example.com"
value={lookupDomain}
onChange={e => { setLookupDomain(e.target.value); setLookupResult(null); }}
onKeyDown={e => e.key === 'Enter' && handleLookup('external')}
className="font-mono text-sm"
/>
<Button
variant="outline"
size="sm"
onClick={() => handleLookup('external')}
disabled={!lookupDomain.trim() || !!lookupTesting}
className="gap-1 shrink-0"
>
{lookupTesting === 'external' ? <Loader2 className="h-3 w-3 animate-spin" /> : <Globe className="h-3 w-3" />}
External
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleLookup('internal')}
disabled={!lookupDomain.trim() || !!lookupTesting}
className="gap-1 shrink-0"
>
{lookupTesting === 'internal' ? <Loader2 className="h-3 w-3 animate-spin" /> : <Router className="h-3 w-3" />}
LAN
</Button>
</div>
{lookupResult && (
<Alert className={lookupResult.success
? 'border-green-500 bg-green-50 dark:bg-green-950'
: 'border-amber-500 bg-amber-50 dark:bg-amber-950'
}>
{lookupResult.success
? <CheckCircle className="h-4 w-4 text-green-600" />
: <AlertCircle className="h-4 w-4 text-amber-600" />
}
<AlertDescription className={lookupResult.success
? 'text-green-800 dark:text-green-200'
: 'text-amber-800 dark:text-amber-200'
}>
<span className="font-medium">{lookupResult.type}: </span>
{lookupResult.message}
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,86 @@
import { Settings, RotateCcw, AlertCircle } from 'lucide-react';
import { useDnsmasq, useMessages } from '../hooks';
import { Message } from './Message';
import { Card, CardHeader, CardTitle, CardContent, Button } from './ui';
export const DnsmasqSection = () => {
const {
config: dnsmasqConfig,
generateConfig,
isGenerating,
generateError,
restart,
isRestarting,
restartError,
restartData
} = useDnsmasq();
const { messages, setMessage } = useMessages();
// Handle success/error messaging
if (generateError) {
setMessage('dnsmasq', `Failed to generate dnsmasq config: ${generateError.message}`, 'error');
} else if (dnsmasqConfig) {
setMessage('dnsmasq', 'Dnsmasq config generated successfully', 'success');
}
if (restartError) {
setMessage('dnsmasq', `Failed to restart dnsmasq: ${restartError.message}`, 'error');
} else if (restartData) {
setMessage('dnsmasq', `Dnsmasq restart: ${restartData.status}`, 'success');
}
return (
<Card>
<CardHeader>
<CardTitle>DNS/DHCP Management</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-2">
<Button onClick={() => generateConfig(false)} disabled={isGenerating} variant="outline">
<Settings className="mr-2 h-4 w-4" />
{isGenerating ? 'Generating...' : 'Generate Dnsmasq Config'}
</Button>
<Button onClick={() => restart()} disabled={isRestarting} variant="outline">
<RotateCcw className={`mr-2 h-4 w-4 ${isRestarting ? 'animate-spin' : ''}`} />
{isRestarting ? 'Restarting...' : 'Restart Dnsmasq'}
</Button>
</div>
{generateError && (
<div className="p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-md flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-red-600 mt-0.5" />
<div>
<p className="text-sm font-medium text-red-800 dark:text-red-200">Generation Error</p>
<p className="text-sm text-red-700 dark:text-red-300">{generateError.message}</p>
</div>
</div>
)}
{restartError && (
<div className="p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-md flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-red-600 mt-0.5" />
<div>
<p className="text-sm font-medium text-red-800 dark:text-red-200">Restart Error</p>
<p className="text-sm text-red-700 dark:text-red-300">{restartError.message}</p>
</div>
</div>
)}
{restartData && (
<div className="p-3 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-md">
<p className="text-sm text-green-800 dark:text-green-200">
Dnsmasq restart: {restartData.status}
</p>
</div>
)}
<Message message={messages.dnsmasq} />
{dnsmasqConfig && (
<pre className="p-4 bg-muted rounded-md text-sm overflow-auto max-h-96">
{dnsmasqConfig.content || JSON.stringify(dnsmasqConfig, null, 2)}
</pre>
)}
</CardContent>
</Card>
);
};

View File

@@ -0,0 +1,41 @@
import { Download } from 'lucide-react';
import { Button } from './ui/button';
interface DownloadButtonProps {
content: string;
filename: string;
label?: string;
variant?: 'default' | 'outline' | 'secondary' | 'ghost';
disabled?: boolean;
}
export function DownloadButton({
content,
filename,
label = 'Download',
variant = 'default',
disabled = false,
}: DownloadButtonProps) {
const handleDownload = () => {
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
return (
<Button
onClick={handleDownload}
variant={variant}
disabled={disabled}
>
<Download className="h-4 w-4" />
{label}
</Button>
);
}

View File

@@ -0,0 +1,167 @@
import React, { Component as ReactComponent } from 'react';
import type { ErrorInfo, ReactNode } from 'react';
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
import { Button } from './ui/button';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
interface Props {
children?: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: ErrorInfo) => void;
}
interface State {
hasError: boolean;
error?: Error;
errorInfo?: ErrorInfo;
}
export class ErrorBoundary extends ReactComponent<Props, State> {
public state: State = {
hasError: false,
};
public static getDerivedStateFromError(error: Error): State {
// Update state so the next render will show the fallback UI
return { hasError: true, error };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('ErrorBoundary caught an error:', error, errorInfo);
this.setState({
error,
errorInfo,
});
// Call optional error handler
if (this.props.onError) {
this.props.onError(error, errorInfo);
}
}
private handleReset = () => {
this.setState({ hasError: false, error: undefined, errorInfo: undefined });
};
private handleReload = () => {
window.location.reload();
};
public render() {
if (this.state.hasError) {
// If a custom fallback is provided, use it
if (this.props.fallback) {
return this.props.fallback;
}
// Default error UI
return <ErrorFallback
error={this.state.error}
errorInfo={this.state.errorInfo}
onReset={this.handleReset}
onReload={this.handleReload}
/>;
}
return this.props.children;
}
}
interface ErrorFallbackProps {
error?: Error;
errorInfo?: ErrorInfo;
onReset: () => void;
onReload: () => void;
}
export const ErrorFallback: React.FC<ErrorFallbackProps> = ({
error,
errorInfo,
onReset,
onReload
}) => {
const isDev = process.env.NODE_ENV === 'development';
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<Card className="w-full max-w-2xl">
<CardHeader>
<div className="flex items-center gap-3">
<div className="p-2 rounded-lg">
<AlertTriangle className="h-6 w-6 text-red-600 dark:text-red-400" />
</div>
<div>
<CardTitle className="text-red-800 dark:text-red-200">
Something went wrong
</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
The application encountered an unexpected error
</p>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
Don't worry, your data is safe. You can try the following options:
</p>
<div className="flex gap-2">
<Button onClick={onReset} variant="outline" size="sm">
<RefreshCw className="h-4 w-4 mr-2" />
Try Again
</Button>
<Button onClick={onReload} variant="outline" size="sm">
<Home className="h-4 w-4 mr-2" />
Reload Page
</Button>
</div>
</div>
{isDev && error && (
<div className="space-y-3">
<h4 className="text-sm font-medium text-red-800 dark:text-red-200">
Error Details (Development Mode)
</h4>
<div className="space-y-2">
<div>
<p className="text-xs font-medium text-muted-foreground">Error Message:</p>
<p className="text-xs bg-red-50 p-2 rounded border font-mono">
{error.message}
</p>
</div>
{error.stack && (
<div>
<p className="text-xs font-medium text-muted-foreground">Stack Trace:</p>
<pre className="text-xs p-2 rounded border overflow-auto max-h-40 font-mono">
{error.stack}
</pre>
</div>
)}
{errorInfo?.componentStack && (
<div>
<p className="text-xs font-medium text-muted-foreground">Component Stack:</p>
<pre className="text-xs p-2 rounded border overflow-auto max-h-40 font-mono">
{errorInfo.componentStack}
</pre>
</div>
)}
</div>
</div>
)}
{!isDev && (
<div className="p-3 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md">
<p className="text-sm text-blue-800 dark:text-blue-200">
If this problem persists, please contact support with details about what you were doing when the error occurred.
</p>
</div>
)}
</CardContent>
</Card>
</div>
);
};

View File

@@ -0,0 +1,530 @@
import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Alert, AlertDescription } from './ui/alert';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Shield, Loader2, AlertCircle, CheckCircle, Check, X, Plus, Trash2, BookOpen, ChevronDown, ChevronUp, Lock } from 'lucide-react';
import { Badge } from './ui/badge';
import { useConfig } from '../hooks';
import { useNftables } from '../hooks/useNftables';
import { useVpn } from '../hooks/useVpn';
type ExtraPort = { port: number; protocol?: string; label?: string };
const WELL_KNOWN_PORTS: Record<number, string> = {
22: 'SSH',
53: 'DNS',
67: 'DHCP Server',
68: 'DHCP Client',
80: 'HTTP',
443: 'HTTPS',
3389: 'RDP',
5353: 'mDNS',
5900: 'VNC',
8404: 'HAProxy Stats',
};
// Ports that are always included automatically
const AUTO_TCP_PORTS = [80, 443, 8404];
const AUTO_UDP_PORTS = [53, 67, 68];
interface PortEntry {
port: number;
protocol: string;
label: string;
source: 'auto' | 'haproxy-custom' | 'user';
}
export function FirewallComponent() {
const { config: globalConfig, updateConfig } = useConfig();
const { status: nftablesStatus, isLoadingStatus: isNftablesLoading, interfaces, refetchStatus } = useNftables();
const { config: vpnConfig } = useVpn();
const nftCfg = globalConfig?.cloud?.nftables;
const isEnabled = nftCfg?.enabled !== false;
const currentWan = nftCfg?.wanInterface ?? '';
const currentExtraPorts: ExtraPort[] = nftCfg?.extraPorts ?? [];
const customRoutes = globalConfig?.cloud?.haproxy?.customRoutes ?? [];
const [editingWan, setEditingWan] = useState(false);
const [wanValue, setWanValue] = useState('');
const [savingWan, setSavingWan] = useState(false);
const [togglingFirewall, setTogglingFirewall] = useState(false);
const [showAdvanced, setShowAdvanced] = useState(false);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [newPort, setNewPort] = useState('');
const [newProtocol, setNewProtocol] = useState('tcp');
const [newLabel, setNewLabel] = useState('');
const [portError, setPortError] = useState('');
const [savingPorts, setSavingPorts] = useState(false);
const showSuccess = (msg: string) => {
setSuccessMessage(msg);
setErrorMessage(null);
setTimeout(() => setSuccessMessage(null), 5000);
};
const showError = (msg: string) => {
setErrorMessage(msg);
setSuccessMessage(null);
setTimeout(() => setErrorMessage(null), 8000);
};
// Build unified port list from all sources
function buildPortList(): PortEntry[] {
const entries: PortEntry[] = [];
const seen = new Set<string>();
const addEntry = (port: number, protocol: string, label: string, source: PortEntry['source']) => {
const key = `${port}/${protocol}`;
if (!seen.has(key)) {
seen.add(key);
entries.push({ port, protocol, label, source });
}
};
// Auto TCP ports (HAProxy base)
for (const port of AUTO_TCP_PORTS) {
addEntry(port, 'tcp', WELL_KNOWN_PORTS[port] || '', 'auto');
}
// HAProxy custom route ports
for (const route of customRoutes) {
addEntry(route.port, 'tcp', `HAProxy: ${route.name}`, 'haproxy-custom');
}
// Auto UDP ports (DNS/DHCP)
for (const port of AUTO_UDP_PORTS) {
addEntry(port, 'udp', WELL_KNOWN_PORTS[port] || '', 'auto');
}
// VPN listen port (when enabled)
if (vpnConfig?.enabled && vpnConfig.listenPort) {
addEntry(vpnConfig.listenPort, 'udp', 'WireGuard VPN', 'auto');
}
// User extra ports
for (const ep of currentExtraPorts) {
const proto = ep.protocol || 'tcp';
addEntry(ep.port, proto, ep.label || WELL_KNOWN_PORTS[ep.port] || '', 'user');
}
return entries;
}
const allPorts = buildPortList();
const tcpPorts = allPorts.filter(p => p.protocol === 'tcp');
const udpPorts = allPorts.filter(p => p.protocol === 'udp');
async function saveNftConfig(patch: NonNullable<NonNullable<typeof globalConfig>['cloud']>['nftables']) {
if (!globalConfig) return;
await updateConfig({
...globalConfig,
cloud: {
...globalConfig.cloud,
nftables: { ...nftCfg, ...patch },
},
});
refetchStatus();
}
async function toggleFirewall() {
setTogglingFirewall(true);
try {
await saveNftConfig({ enabled: !isEnabled });
showSuccess(`Firewall ${isEnabled ? 'disabled' : 'enabled'}`);
} catch (e) {
showError(`Failed to toggle firewall: ${e instanceof Error ? e.message : String(e)}`);
}
setTogglingFirewall(false);
}
async function saveWan(value: string) {
setSavingWan(true);
try {
await saveNftConfig({ wanInterface: value || undefined });
showSuccess(value ? `WAN interface set to ${value}` : 'Strict mode disabled');
} catch (e) {
showError(`Failed to save WAN interface: ${e instanceof Error ? e.message : String(e)}`);
}
setSavingWan(false);
setEditingWan(false);
}
async function addPort() {
const port = parseInt(newPort, 10);
if (isNaN(port) || port < 1 || port > 65535) {
setPortError('Enter a valid port (165535)');
return;
}
if (currentExtraPorts.some((p) => p.port === port && (p.protocol || 'tcp') === newProtocol)) {
setPortError('Port/protocol already in list');
return;
}
setPortError('');
setSavingPorts(true);
try {
const entry: ExtraPort = { port, protocol: newProtocol };
if (newLabel.trim()) entry.label = newLabel.trim();
await saveNftConfig({ extraPorts: [...currentExtraPorts, entry] });
showSuccess(`Port ${port}/${newProtocol} added`);
setNewPort('');
setNewLabel('');
} catch (e) {
showError(`Failed to add port: ${e instanceof Error ? e.message : String(e)}`);
}
setSavingPorts(false);
}
async function removePort(port: number, protocol: string) {
try {
await saveNftConfig({
extraPorts: currentExtraPorts.filter(
(ep) => !(ep.port === port && (ep.protocol || 'tcp') === protocol)
),
});
showSuccess(`Port ${port}/${protocol} removed`);
} catch (e) {
showError(`Failed to remove port: ${e instanceof Error ? e.message : String(e)}`);
}
}
function renderPortRow(entry: PortEntry) {
const isAuto = entry.source !== 'user';
return (
<div
key={`${entry.port}/${entry.protocol}`}
className={`flex items-center gap-3 px-3 py-2 rounded-md ${isAuto ? 'bg-muted/50' : 'bg-muted'}`}
>
<span className="font-mono text-sm w-16">{entry.port}</span>
<span className="text-xs text-muted-foreground uppercase w-8">{entry.protocol}</span>
<span className="text-sm flex-1 truncate">
{entry.label}
</span>
{isAuto ? (
<span title="Managed automatically"><Lock className="h-3 w-3 text-muted-foreground shrink-0" /></span>
) : (
<button
onClick={() => removePort(entry.port, entry.protocol)}
className="text-muted-foreground hover:text-red-500 shrink-0"
title="Remove port"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
);
}
return (
<div className="space-y-6">
{/* Header with enable/disable toggle */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="p-2 bg-primary/10 rounded-lg">
<Shield className="h-6 w-6 text-primary" />
</div>
<div>
<h2 className="text-2xl font-semibold">Firewall</h2>
<p className="text-muted-foreground">nftables rules protecting Wild Central itself</p>
</div>
</div>
<div className="flex items-center gap-3">
<Badge variant={isEnabled ? 'success' : 'secondary'} className="gap-1">
{isEnabled && <CheckCircle className="h-3 w-3" />}
{isEnabled ? 'Enabled' : 'Disabled'}
</Badge>
<Button
variant="outline"
size="sm"
className="h-7 text-xs gap-1"
onClick={toggleFirewall}
disabled={togglingFirewall}
>
{togglingFirewall ? <Loader2 className="h-3 w-3 animate-spin" /> : null}
{isEnabled ? 'Disable' : 'Enable'}
</Button>
</div>
</div>
{/* Educational card */}
<Card className="bg-gradient-to-br from-cyan-50 to-blue-50 dark:from-cyan-900/20 dark:to-blue-900/20 border-cyan-200 dark:border-cyan-800">
<CardContent className="pt-4">
<div className="flex gap-3">
<BookOpen className="h-5 w-5 text-cyan-600 dark:text-cyan-400 shrink-0 mt-0.5" />
<div className="space-y-1 text-sm text-cyan-900 dark:text-cyan-100">
<p>
Wild Central uses <strong>nftables</strong> to protect itself. Rules are generated
automatically from your HAProxy ingress configuration the ports HAProxy listens
on are always allowed. The firewall is permissive by default; set a{' '}
<strong>WAN interface</strong> to enable strict filtering that drops anything not
explicitly listed. Make sure to add <strong>extra ports</strong> for any services
you need to reach directly (like SSH) before enabling strict mode.
</p>
</div>
</div>
</CardContent>
</Card>
{successMessage && (
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
</Alert>
)}
{errorMessage && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{errorMessage}</AlertDescription>
</Alert>
)}
{/* Allowed Ports */}
<Card className={!isEnabled ? 'opacity-50 pointer-events-none' : ''}>
<CardHeader>
<CardTitle>Allowed Ports</CardTitle>
</CardHeader>
<CardContent className="space-y-5">
<p className="text-sm text-muted-foreground">
All ports the firewall allows through. Ports managed by HAProxy and system services are
locked add your own with the form below.
</p>
{/* TCP ports */}
<div className="space-y-2">
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">TCP</h4>
<div className="space-y-1">
{tcpPorts.map(renderPortRow)}
</div>
</div>
{/* UDP ports */}
<div className="space-y-2">
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">UDP</h4>
<div className="space-y-1">
{udpPorts.map(renderPortRow)}
</div>
</div>
{/* Add port form */}
<div className="border-t pt-4 space-y-3">
<h4 className="text-sm font-medium">Add Port</h4>
<div className="flex flex-wrap gap-2 items-end">
<div>
<Label htmlFor="new-port" className="text-xs">Port</Label>
<Input
id="new-port"
value={newPort}
onChange={(e) => { setNewPort(e.target.value); setPortError(''); }}
onKeyDown={(e) => e.key === 'Enter' && addPort()}
placeholder="e.g. 22"
className="font-mono h-8 text-sm w-24 mt-1"
/>
</div>
<div>
<Label className="text-xs">Protocol</Label>
<Select value={newProtocol} onValueChange={setNewProtocol}>
<SelectTrigger className="h-8 text-sm w-20 mt-1 font-mono">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="tcp">TCP</SelectItem>
<SelectItem value="udp">UDP</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="new-label" className="text-xs">Label (optional)</Label>
<Input
id="new-label"
value={newLabel}
onChange={(e) => setNewLabel(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && addPort()}
placeholder="e.g. SSH"
className="h-8 text-sm w-32 mt-1"
/>
</div>
<Button
size="sm"
className="h-8 gap-1"
onClick={addPort}
disabled={savingPorts || !newPort}
>
{savingPorts ? <Loader2 className="h-3 w-3 animate-spin" /> : <Plus className="h-3 w-3" />}
Add
</Button>
{!currentExtraPorts.some((p) => p.port === 22) && (
<Button
size="sm"
variant="outline"
className="h-8 gap-1 text-xs"
onClick={() => { setNewPort('22'); setNewProtocol('tcp'); setNewLabel('SSH'); }}
>
<Plus className="h-3 w-3" />
Add SSH (22)
</Button>
)}
</div>
{portError && <p className="text-xs text-red-600">{portError}</p>}
</div>
</CardContent>
</Card>
{/* WAN Interface */}
<Card className={!isEnabled ? 'opacity-50 pointer-events-none' : ''}>
<CardHeader>
<CardTitle>WAN Interface</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">
Your <strong>WAN interface</strong> is the network port that faces the internet the
one your router sends traffic to. When set, the firewall drops all inbound connections
on that interface except for the ports listed above. Leave unset to keep the firewall
permissive (safe default while you're getting started).
</p>
{!editingWan ? (
<div className="flex items-center gap-3">
{currentWan ? (
<span className="font-mono bg-muted px-2 py-0.5 rounded text-sm">{currentWan}</span>
) : (
<span className="text-sm text-muted-foreground italic">
Not set — permissive mode (all inbound allowed)
</span>
)}
<Button
variant="outline"
size="sm"
className="h-7 text-xs gap-1"
onClick={() => { setWanValue(currentWan); setEditingWan(true); }}
>
{currentWan ? 'Change' : 'Enable strict mode'}
</Button>
{currentWan && (
<Button
variant="ghost"
size="sm"
className="h-7 text-xs gap-1 text-muted-foreground hover:text-red-500"
onClick={() => saveWan('')}
>
<Trash2 className="h-3 w-3" />
Disable
</Button>
)}
</div>
) : (
<div className="space-y-3">
{currentWan === '' && !currentExtraPorts.some((p) => p.port === 22) && (
<Alert variant="warning">
<AlertCircle className="h-4 w-4" />
<AlertDescription className="text-xs">
SSH (port 22) is not in your extra ports list. Enabling strict mode will
block SSH access to Wild Central.
</AlertDescription>
</Alert>
)}
<div className="space-y-1.5">
<Label className="text-xs">Select interface</Label>
{interfaces.length > 0 ? (
<Select value={wanValue} onValueChange={setWanValue}>
<SelectTrigger className="w-64 h-8 text-sm font-mono">
<SelectValue placeholder="Choose an interface…" />
</SelectTrigger>
<SelectContent>
{interfaces.map((iface) => (
<SelectItem key={iface.name} value={iface.name}>
<span className="font-mono">{iface.name}</span>
{iface.addresses.length > 0 && (
<span className="text-muted-foreground ml-2 text-xs">
{iface.addresses[0].split('/')[0]}
</span>
)}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Input
value={wanValue}
onChange={(e) => setWanValue(e.target.value)}
placeholder="e.g. eth0"
className="font-mono h-8 text-sm w-32"
/>
)}
<p className="text-xs text-muted-foreground">
Pick the interface that faces your router/internet. Typically the one with your
external IP address.
</p>
</div>
<div className="flex gap-2">
<Button
size="sm"
className="h-8 gap-1"
onClick={() => saveWan(wanValue)}
disabled={savingWan || !wanValue}
>
{savingWan ? <Loader2 className="h-3 w-3 animate-spin" /> : <Check className="h-3 w-3" />}
Save
</Button>
<Button
variant="outline"
size="sm"
className="h-8 gap-1"
onClick={() => setEditingWan(false)}
>
<X className="h-3 w-3" />Cancel
</Button>
</div>
</div>
)}
</CardContent>
</Card>
{/* Advanced: raw rules */}
<Card className={!isEnabled ? 'opacity-50' : ''}>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Active Ruleset</CardTitle>
<div className="flex items-center gap-2">
{isNftablesLoading ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : (
<Badge variant={nftablesStatus?.rules ? 'success' : isEnabled ? 'warning' : 'secondary'} className="gap-1">
{nftablesStatus?.rules && <CheckCircle className="h-3 w-3" />}
{nftablesStatus?.rules ? 'Active' : 'Not loaded'}
</Badge>
)}
<Button
variant="outline"
size="sm"
className="h-7 text-xs gap-1"
onClick={() => setShowAdvanced(!showAdvanced)}
>
{showAdvanced ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
Advanced
</Button>
</div>
</div>
</CardHeader>
{showAdvanced && (
<CardContent>
{nftablesStatus?.rules ? (
<pre className="bg-muted p-3 rounded-lg overflow-x-auto text-xs font-mono">
{nftablesStatus.rules}
</pre>
) : (
<p className="text-sm text-muted-foreground">
No rules loaded yet. Rules are generated when you apply an HAProxy configuration.
</p>
)}
</CardContent>
)}
</Card>
</div>
);
}

View File

@@ -0,0 +1,41 @@
import { useHelp } from '../contexts/HelpContext';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from './ui/sheet';
import { Card } from './ui/card';
export function HelpPanel() {
const { helpContent, isHelpOpen, setIsHelpOpen } = useHelp();
if (!helpContent) return null;
return (
<Sheet open={isHelpOpen} onOpenChange={setIsHelpOpen}>
<SheetContent className="w-full sm:max-w-lg overflow-y-auto p-6">
<SheetHeader className="mb-6">
<SheetTitle className="flex items-center gap-3">
{helpContent.icon && (
<div className={`p-2 rounded-lg ${helpContent.color || 'bg-primary/10'}`}>
{helpContent.icon}
</div>
)}
{helpContent.title}
</SheetTitle>
<SheetDescription className="sr-only">
Help information for {helpContent.title}
</SheetDescription>
</SheetHeader>
<div className="space-y-4">
<Card className={`p-4 ${helpContent.color || 'bg-muted/50'}`}>
<div className="prose dark:prose-invert max-w-none text-sm">
{helpContent.description}
</div>
</Card>
{helpContent.actions && (
<div className="flex gap-2 flex-wrap">
{helpContent.actions}
</div>
)}
</div>
</SheetContent>
</Sheet>
);
}

View File

@@ -0,0 +1,342 @@
import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input, Label } from './ui';
import { Alert, AlertDescription } from './ui/alert';
import { Textarea } from './ui/textarea';
import { Network, Loader2, AlertCircle, CheckCircle, Play, RotateCw, Plus, Trash2, X, Check, Activity, ChevronDown, ChevronUp } from 'lucide-react';
import { Badge } from './ui/badge';
import { useConfig } from '../hooks';
import { useHaproxy } from '../hooks/useHaproxy';
import type { HAProxyCustomRoute } from '../types';
import type { HaproxyInstanceRoute } from '../services/api/networking';
import { haproxyApi } from '../services/api/networking';
export function IngressProxyComponent() {
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
const {
status: haproxyStatus,
isLoadingStatus: isHaproxyLoading,
stats: haproxyStats,
isLoadingStats: isHaproxyStatsLoading,
generate: generateHaproxy,
isGenerating: isHaproxyGenerating,
generateData: haproxyGenerateData,
generateError: haproxyGenerateError,
restart: restartHaproxy,
isRestarting: isHaproxyRestarting,
} = useHaproxy();
const [showAddCustomRoute, setShowAddCustomRoute] = useState(false);
const [newCustomRoute, setNewCustomRoute] = useState<HAProxyCustomRoute>({ name: '', port: 0, backend: '' });
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [showAdvanced, setShowAdvanced] = useState(false);
const [advancedConfig, setAdvancedConfig] = useState('');
const [loadingAdvanced, setLoadingAdvanced] = useState(false);
const showSuccess = (msg: string) => {
setSuccessMessage(msg);
setErrorMessage(null);
setTimeout(() => setSuccessMessage(null), 5000);
};
const showError = (msg: string) => {
setErrorMessage(msg);
setSuccessMessage(null);
setTimeout(() => setErrorMessage(null), 8000);
};
const handleShowAdvanced = async () => {
if (!showAdvanced) {
setLoadingAdvanced(true);
try {
const result = await haproxyApi.getConfig();
setAdvancedConfig(result.content || '');
} catch {
setAdvancedConfig('# Could not load HAProxy config');
}
setLoadingAdvanced(false);
}
setShowAdvanced(!showAdvanced);
};
const handleAddCustomRoute = async () => {
if (!globalConfig || !newCustomRoute.name || !newCustomRoute.port || !newCustomRoute.backend) return;
try {
const existing = globalConfig.cloud?.haproxy?.customRoutes ?? [];
await updateConfig({
...globalConfig,
cloud: {
...globalConfig.cloud,
haproxy: {
...globalConfig.cloud?.haproxy,
customRoutes: [...existing, newCustomRoute],
},
},
});
setNewCustomRoute({ name: '', port: 0, backend: '' });
setShowAddCustomRoute(false);
generateHaproxy();
showSuccess(`Custom route "${newCustomRoute.name}" added`);
} catch (e) {
showError(`Failed to add route: ${e instanceof Error ? e.message : String(e)}`);
}
};
const handleDeleteCustomRoute = async (name: string) => {
if (!globalConfig) return;
try {
const updated = (globalConfig.cloud?.haproxy?.customRoutes ?? []).filter(r => r.name !== name);
await updateConfig({
...globalConfig,
cloud: {
...globalConfig.cloud,
haproxy: {
...globalConfig.cloud?.haproxy,
customRoutes: updated,
},
},
});
generateHaproxy();
showSuccess(`Custom route "${name}" removed`);
} catch (e) {
showError(`Failed to delete route: ${e instanceof Error ? e.message : String(e)}`);
}
};
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<div className="p-2 bg-primary/10 rounded-lg">
<Network className="h-6 w-6 text-primary" />
</div>
<div>
<h2 className="text-2xl font-semibold">Ingress Proxy</h2>
<p className="text-muted-foreground">Routes external traffic to your Wild Cloud instances by domain name (HAProxy)</p>
</div>
</div>
{successMessage && (
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
</Alert>
)}
{errorMessage && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{errorMessage}</AlertDescription>
</Alert>
)}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Instance Routes</CardTitle>
{isHaproxyLoading ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : (
<Badge variant={haproxyStatus?.status === 'active' ? 'success' : 'warning'} className="gap-1">
{haproxyStatus?.status === 'active' && <CheckCircle className="h-3 w-3" />}
{haproxyStatus?.status === 'active' ? 'Active' : haproxyStatus?.status ?? 'Stopped'}
</Badge>
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
{(() => {
const routes: HaproxyInstanceRoute[] = haproxyStatus?.routes ?? [];
return routes.length > 0 ? (
<div className="border rounded-lg divide-y text-sm">
{routes.map(r => (
<div key={r.name} className="px-3 py-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
<span className="font-mono text-xs">*.{r.domain}</span>
</div>
<span className="font-mono text-xs text-muted-foreground">{r.backendIP}</span>
</div>
{r.extraDomains && r.extraDomains.length > 0 && (
<div className="mt-1 ml-5 flex flex-wrap gap-1">
{r.extraDomains.map(d => (
<span key={d} className="font-mono text-xs text-muted-foreground bg-muted rounded px-1.5 py-0.5">
{d}
</span>
))}
</div>
)}
</div>
))}
</div>
) : (
<p className="text-xs text-muted-foreground">
No instances registered click Generate &amp; Apply to configure.
</p>
);
})()}
{haproxyGenerateData && (
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-700 dark:text-green-300">
{haproxyGenerateData.message}
</AlertDescription>
</Alert>
)}
{haproxyGenerateError && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{(haproxyGenerateError as Error).message}</AlertDescription>
</Alert>
)}
<div className="flex gap-2">
<Button onClick={() => generateHaproxy()} disabled={isHaproxyGenerating} className="gap-2">
{isHaproxyGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
Generate & Apply
</Button>
<Button variant="outline" onClick={() => restartHaproxy()} disabled={isHaproxyRestarting} className="gap-2">
{isHaproxyRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
Restart
</Button>
<Button variant="outline" onClick={handleShowAdvanced} disabled={loadingAdvanced} className="gap-2">
{loadingAdvanced ? <Loader2 className="h-4 w-4 animate-spin" /> : showAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
Advanced
</Button>
</div>
{showAdvanced && (
<div className="border-t pt-4 space-y-3">
<span className="text-sm font-medium">Generated config file</span>
<Textarea
value={advancedConfig}
readOnly
className="font-mono text-xs min-h-[300px]"
placeholder="# haproxy configuration"
/>
</div>
)}
</CardContent>
</Card>
{(haproxyStats.length > 0 || isHaproxyStatsLoading) && (
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Activity className="h-4 w-4 text-muted-foreground" />
<CardTitle>Backend Status</CardTitle>
</div>
</CardHeader>
<CardContent>
{isHaproxyStatsLoading ? (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />Loading
</div>
) : (
<div className="border rounded-lg divide-y text-sm">
{haproxyStats.map(s => (
<div key={s.name} className="flex items-center justify-between px-3 py-2">
<div className="flex items-center gap-2">
<Badge variant={s.status === 'UP' ? 'default' : 'secondary'} className="text-xs h-4">
{s.status}
</Badge>
<span className="font-mono text-xs">{s.name.replace(/^be_https?_/, '')}</span>
</div>
<div className="flex items-center gap-4 text-xs text-muted-foreground">
<span><span className="font-medium text-foreground">{s.activeConns}</span> active</span>
<span><span className="font-medium text-foreground">{s.rate}</span> /s <span className="text-muted-foreground/60">(peak {s.peakRate})</span></span>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Custom TCP Routes</CardTitle>
<Button size="sm" variant="outline" onClick={() => setShowAddCustomRoute(!showAddCustomRoute)} className="gap-1">
<Plus className="h-3 w-3" />
Add
</Button>
</div>
</CardHeader>
<CardContent className="space-y-3">
{showAddCustomRoute && (
<Card className="p-3 border-dashed">
<div className="grid grid-cols-3 gap-2 mb-2">
<div>
<Label className="text-xs">Name</Label>
<Input
value={newCustomRoute.name}
onChange={e => setNewCustomRoute(r => ({ ...r, name: e.target.value }))}
placeholder="e.g. civil_ssh"
className="mt-1 text-xs font-mono"
/>
</div>
<div>
<Label className="text-xs">Listen Port</Label>
<Input
type="number"
value={newCustomRoute.port || ''}
onChange={e => setNewCustomRoute(r => ({ ...r, port: parseInt(e.target.value) || 0 }))}
placeholder="2222"
className="mt-1 text-xs font-mono"
/>
</div>
<div>
<Label className="text-xs">Backend (host:port)</Label>
<Input
value={newCustomRoute.backend}
onChange={e => setNewCustomRoute(r => ({ ...r, backend: e.target.value }))}
placeholder="192.168.8.10:22"
className="mt-1 text-xs font-mono"
/>
</div>
</div>
<div className="flex gap-2 justify-end">
<Button variant="outline" size="sm" onClick={() => setShowAddCustomRoute(false)}>
<X className="h-3 w-3 mr-1" />Cancel
</Button>
<Button
size="sm"
onClick={handleAddCustomRoute}
disabled={!newCustomRoute.name || !newCustomRoute.port || !newCustomRoute.backend || isUpdating}
>
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <Check className="h-3 w-3 mr-1" />}
Add
</Button>
</div>
</Card>
)}
{(globalConfig?.cloud?.haproxy?.customRoutes ?? []).length === 0 ? (
<p className="text-xs text-muted-foreground">No custom routes configured.</p>
) : (
<div className="border rounded-lg divide-y text-xs">
{(globalConfig?.cloud?.haproxy?.customRoutes ?? []).map(r => (
<div key={r.name} className="flex items-center justify-between px-3 py-1.5">
<div className="flex items-center gap-3">
<span className="font-mono font-medium">{r.name}</span>
<span className="text-muted-foreground font-mono">:{r.port} {r.backend}</span>
</div>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-muted-foreground hover:text-red-500"
onClick={() => handleDeleteCustomRoute(r.name)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,259 @@
import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Textarea } from './ui/textarea';
import { Alert, AlertDescription } from './ui/alert';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from './ui/dialog';
import { Router, CheckCircle, ExternalLink, Loader2, AlertCircle, Play, RotateCw, Copy, ChevronDown, ChevronUp, Edit } from 'lucide-react';
import { Badge } from './ui/badge';
import { useConfig } from '../hooks';
import { useDnsmasq } from '../hooks/useDnsmasq';
import { apiService } from '../services/api-legacy';
export function LanDnsComponent() {
const { config: globalConfig } = useConfig();
const {
status: dnsStatus,
isLoadingStatus: isDnsStatusLoading,
config: dnsConfig,
fetchConfig: fetchDnsConfig,
generateConfig: generateDnsConfig,
isGenerating: isDnsGenerating,
generateData: dnsGenerateData,
restart: restartDns,
isRestarting: isDnsRestarting,
restartData: dnsRestartData,
generateError: dnsGenerateError,
restartError: dnsRestartError,
} = useDnsmasq();
const [showDnsAdvanced, setShowDnsAdvanced] = useState(false);
const [showDnsEditDialog, setShowDnsEditDialog] = useState(false);
const [editedDnsConfig, setEditedDnsConfig] = useState('');
const [copiedDnsIp, setCopiedDnsIp] = useState(false);
const isDnsRunning = dnsStatus?.status === 'active';
const dnsIp = dnsStatus?.ip;
const handleCopyDnsIp = () => {
if (dnsIp) {
navigator.clipboard.writeText(dnsIp);
setCopiedDnsIp(true);
setTimeout(() => setCopiedDnsIp(false), 2000);
}
};
const handleShowDnsAdvanced = () => {
if (!showDnsAdvanced && !dnsConfig) {
fetchDnsConfig();
}
setShowDnsAdvanced(!showDnsAdvanced);
};
const handleEditDnsConfig = () => {
if (dnsConfig?.content) {
setEditedDnsConfig(dnsConfig.content);
} else if (dnsGenerateData?.config || dnsGenerateData?.content) {
setEditedDnsConfig(dnsGenerateData.config || dnsGenerateData.content || '');
} else {
setEditedDnsConfig('');
}
setShowDnsEditDialog(true);
};
const handleSaveDnsConfig = async () => {
try {
await apiService.writeDnsmasqConfig(editedDnsConfig);
setShowDnsEditDialog(false);
fetchDnsConfig();
} catch (error) {
console.error('Failed to save config:', error);
}
};
const handleSaveAndRestartDns = async () => {
try {
await apiService.writeDnsmasqConfig(editedDnsConfig);
await apiService.restartDnsmasq();
setShowDnsEditDialog(false);
fetchDnsConfig();
} catch (error) {
console.error('Failed to save config and restart:', error);
}
};
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<div className="p-2 bg-primary/10 rounded-lg">
<Router className="h-6 w-6 text-primary" />
</div>
<div>
<h2 className="text-2xl font-semibold">LAN DNS</h2>
<p className="text-muted-foreground">Resolves Wild Cloud domains on your local network via dnsmasq</p>
</div>
</div>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>DNS Service</CardTitle>
<Badge variant={isDnsRunning ? 'success' : 'warning'} className="gap-1">
{isDnsStatusLoading ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : isDnsRunning ? (
<CheckCircle className="h-3 w-3" />
) : null}
{isDnsStatusLoading ? 'Checking...' : isDnsRunning ? 'Running' : 'Stopped'}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between p-4 bg-muted/30 rounded-lg">
<div>
<div className="text-sm text-muted-foreground">
Set this as the primary DNS server in your router
</div>
<code className="text-xl font-mono font-bold mt-1 inline-block">
{dnsIp || 'Auto-detecting...'}
</code>
</div>
<Button
variant="outline"
size="sm"
onClick={handleCopyDnsIp}
disabled={!dnsIp}
className="gap-2"
>
<Copy className="h-4 w-4" />
{copiedDnsIp ? 'Copied!' : 'Copy'}
</Button>
</div>
{globalConfig?.cloud?.router?.ip && (
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
Router: <span className="font-mono">{globalConfig.cloud.router.ip}</span>
</span>
<Button
variant="ghost"
size="sm"
onClick={() => window.open(`http://${globalConfig?.cloud?.router?.ip}`, '_blank')}
className="gap-1 text-xs"
>
<ExternalLink className="h-3 w-3" />
Open Admin
</Button>
</div>
)}
<div className="flex gap-2">
{!isDnsRunning ? (
<Button onClick={() => generateDnsConfig(true)} disabled={isDnsGenerating} className="gap-2">
{isDnsGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
Start DNS
</Button>
) : (
<Button onClick={() => restartDns()} disabled={isDnsRestarting} variant="outline" className="gap-2">
{isDnsRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
Restart
</Button>
)}
<Button onClick={handleShowDnsAdvanced} variant="outline" className="gap-2">
{showDnsAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
Advanced
</Button>
</div>
{(dnsGenerateData || dnsRestartData) && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
{dnsGenerateData?.message || dnsRestartData?.message}
</AlertDescription>
</Alert>
)}
{(dnsGenerateError || dnsRestartError) && (
<Alert variant="error">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
{(dnsGenerateError || dnsRestartError)?.toString()}
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
{showDnsAdvanced && (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Advanced DNS Configuration</CardTitle>
<Button variant="outline" size="sm" onClick={handleEditDnsConfig} className="gap-2">
<Edit className="h-4 w-4" />
Edit Config
</Button>
</div>
</CardHeader>
<CardContent>
<pre className="bg-muted p-4 rounded-lg overflow-x-auto text-xs font-mono">
{isDnsGenerating && !dnsConfig && !dnsGenerateData && (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
)}
{(dnsConfig?.content || dnsGenerateData?.config || dnsGenerateData?.content) && (
dnsConfig?.content || dnsGenerateData?.config || dnsGenerateData?.content
)}
{!isDnsGenerating && !dnsGenerateData && !dnsConfig && (
<div className="text-center p-8 text-sm text-muted-foreground">
<p>Configuration preview will appear here</p>
</div>
)}
</pre>
</CardContent>
</Card>
)}
<Dialog open={showDnsEditDialog} onOpenChange={setShowDnsEditDialog}>
<DialogContent className="max-w-4xl max-h-[80vh]">
<DialogHeader>
<DialogTitle>Edit DNS Configuration</DialogTitle>
<DialogDescription>
Modify the dnsmasq configuration. Changes will take effect after saving and restarting.
</DialogDescription>
</DialogHeader>
<div className="py-4">
<Textarea
value={editedDnsConfig}
onChange={(e) => setEditedDnsConfig(e.target.value)}
className="font-mono text-xs min-h-[400px]"
placeholder="# dnsmasq configuration"
/>
</div>
<DialogFooter className="gap-2">
<Button variant="outline" onClick={() => setShowDnsEditDialog(false)}>
Cancel
</Button>
<Button variant="outline" onClick={handleSaveDnsConfig}>
Save
</Button>
<Button onClick={handleSaveAndRestartDns}>
Save & Restart
</Button>
</DialogFooter>
<p className="text-xs text-muted-foreground text-center">
Save: Write config without restarting | Save & Restart: Write config and restart service
</p>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -0,0 +1,43 @@
import { AlertCircle, CheckCircle, Info } from 'lucide-react';
import type { Message as MessageType } from '../types';
import { cn } from '@/lib/utils';
interface MessageProps {
message?: MessageType;
}
export const Message = ({ message }: MessageProps) => {
if (!message) return null;
const getIcon = () => {
switch (message.type) {
case 'error':
return <AlertCircle className="h-4 w-4" />;
case 'success':
return <CheckCircle className="h-4 w-4" />;
default:
return <Info className="h-4 w-4" />;
}
};
const getVariantStyles = () => {
switch (message.type) {
case 'error':
return 'border-destructive/50 text-destructive bg-destructive/10';
case 'success':
return 'border-green-500/50 text-green-700 bg-green-50 dark:bg-green-950 dark:text-green-400';
default:
return 'border-blue-500/50 text-blue-700 bg-blue-50 dark:bg-blue-950 dark:text-blue-400';
}
};
return (
<div className={cn(
'flex items-center gap-2 p-3 rounded-md border text-sm',
getVariantStyles()
)}>
{getIcon()}
<span>{message.message}</span>
</div>
);
};

View File

@@ -0,0 +1,52 @@
import { Moon, Sun, Monitor } from 'lucide-react';
import { Button } from './ui/button';
import { useTheme } from '../contexts/ThemeContext';
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
const cycleTheme = () => {
if (theme === 'light') {
setTheme('dark');
} else if (theme === 'dark') {
setTheme('system');
} else {
setTheme('light');
}
};
const getIcon = () => {
switch (theme) {
case 'light':
return <Sun className="h-4 w-4" />;
case 'dark':
return <Moon className="h-4 w-4" />;
default:
return <Monitor className="h-4 w-4" />;
}
};
const getLabel = () => {
switch (theme) {
case 'light':
return 'Light mode';
case 'dark':
return 'Dark mode';
default:
return 'System theme';
}
};
return (
<Button
variant="ghost"
size="sm"
onClick={cycleTheme}
title={`Current: ${getLabel()}. Click to cycle themes.`}
className="gap-2"
>
{getIcon()}
<span className="text-xs font-medium">{getLabel()}</span>
</Button>
);
}

View File

@@ -0,0 +1,583 @@
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { Shield, Loader2, Edit2, Plus, Trash2, Copy, Check, CheckCircle, RefreshCw, KeyRound, Play, ChevronDown, ChevronUp } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Badge } from './ui/badge';
import { Alert, AlertDescription } from './ui/alert';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './ui/dialog';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from './ui/sheet';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from './ui/alert-dialog';
import { useVpn } from '../hooks/useVpn';
import { vpnApi, type VpnPeer, type VpnPeerConfig } from '../services/api/vpn';
interface ConfigFormValues {
enabled: boolean;
listenPort: number;
address: string;
endpoint: string;
dns: string;
lanCIDR: string;
}
function CopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
const handleCopy = async () => {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<Button variant="ghost" size="sm" onClick={handleCopy} className="h-7 w-7 p-0">
{copied ? <Check className="h-3.5 w-3.5 text-green-500" /> : <Copy className="h-3.5 w-3.5" />}
</Button>
);
}
export function VpnComponent() {
const {
status, isLoadingStatus,
config, isLoadingConfig,
peers, isLoadingPeers,
updateConfig, isUpdatingConfig,
generateKeypair, isGeneratingKeypair,
apply, isApplying, applyError,
addPeer, isAddingPeer, addPeerError,
deletePeer,
} = useVpn();
const [editingConfig, setEditingConfig] = useState(false);
const [confirmKeygen, setConfirmKeygen] = useState(false);
const [addPeerOpen, setAddPeerOpen] = useState(false);
const [newPeerName, setNewPeerName] = useState('');
const [peerConfigModal, setPeerConfigModal] = useState<VpnPeerConfig | null>(null);
const [loadingPeerConfig, setLoadingPeerConfig] = useState<string | null>(null);
const [deleteConfirmPeer, setDeleteConfirmPeer] = useState<VpnPeer | null>(null);
const [showAdvanced, setShowAdvanced] = useState(false);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const { register, handleSubmit, reset, formState: { errors } } = useForm<ConfigFormValues>();
const showSuccess = (msg: string) => {
setSuccessMessage(msg);
setTimeout(() => setSuccessMessage(null), 5000);
};
const showError = (msg: string) => {
setErrorMessage(msg);
setTimeout(() => setErrorMessage(null), 8000);
};
const handleEditConfig = () => {
reset({
enabled: config?.enabled ?? false,
listenPort: config?.listenPort ?? 51820,
address: config?.address ?? '10.8.0.1/24',
endpoint: config?.endpoint ?? '',
dns: config?.dns ?? '',
lanCIDR: config?.lanCIDR ?? '',
});
setEditingConfig(true);
};
const handleSaveConfig = async (values: ConfigFormValues) => {
try {
await updateConfig({ ...values, listenPort: Number(values.listenPort) });
setEditingConfig(false);
if (values.enabled) {
await apply();
showSuccess('Configuration saved and applied');
} else {
showSuccess('Configuration saved');
}
} catch (e) {
showError(`Save failed: ${e instanceof Error ? e.message : String(e)}`);
}
};
const handleGenerateKeypair = async () => {
setConfirmKeygen(false);
try {
await generateKeypair();
showSuccess('Server keypair generated — re-add all peers to update their configs');
} catch (e) {
showError(`Keygen failed: ${e instanceof Error ? e.message : String(e)}`);
}
};
const handleApply = async () => {
try {
await apply();
showSuccess('WireGuard interface applied');
} catch (e) {
showError(`Apply failed: ${e instanceof Error ? e.message : String(e)}`);
}
};
const handleAddPeer = async () => {
if (!newPeerName.trim()) return;
try {
await addPeer(newPeerName.trim());
setNewPeerName('');
setAddPeerOpen(false);
showSuccess(`Peer "${newPeerName.trim()}" added`);
} catch (e) {
showError(`Add peer failed: ${e instanceof Error ? e.message : String(e)}`);
}
};
const handleShowPeerConfig = async (peer: VpnPeer) => {
setLoadingPeerConfig(peer.id);
try {
const cfg = await vpnApi.getPeerConfig(peer.id);
setPeerConfigModal(cfg);
} catch (e) {
showError(`Failed to get peer config: ${e instanceof Error ? e.message : String(e)}`);
} finally {
setLoadingPeerConfig(null);
}
};
const handleDeletePeer = async () => {
if (!deleteConfirmPeer) return;
try {
await deletePeer(deleteConfirmPeer.id);
setDeleteConfirmPeer(null);
showSuccess(`Peer "${deleteConfirmPeer.name}" deleted`);
} catch (e) {
showError(`Delete failed: ${e instanceof Error ? e.message : String(e)}`);
}
};
if (isLoadingStatus && isLoadingConfig) {
return (
<div className="flex items-center justify-center h-48">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="space-y-6">
{/* Page header */}
<div className="flex items-center gap-4">
<div className="p-2 bg-primary/10 rounded-lg">
<Shield className="h-6 w-6 text-primary" />
</div>
<div>
<h2 className="text-2xl font-semibold">VPN</h2>
<p className="text-muted-foreground">WireGuard remote access to your Wild Cloud network</p>
</div>
</div>
{/* Alerts */}
{successMessage && (
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
<Check className="h-4 w-4 text-green-600" />
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
</Alert>
)}
{(errorMessage || applyError || addPeerError) && (
<Alert variant="error">
<AlertDescription>{errorMessage ?? String(applyError ?? addPeerError)}</AlertDescription>
</Alert>
)}
{/* Status card */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Status</CardTitle>
<div className="flex items-center gap-2">
<Badge variant={status?.running ? 'success' : config?.enabled ? 'warning' : 'secondary'} className="gap-1">
{status?.running && <CheckCircle className="h-3 w-3" />}
{status?.running ? 'Running' : 'Stopped'}
</Badge>
<Button
size="sm"
onClick={handleApply}
disabled={isApplying || !config?.enabled}
className="gap-1 h-7 text-xs"
>
{isApplying ? <Loader2 className="h-3 w-3 animate-spin" /> : <Play className="h-3 w-3" />}
Apply
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
<div>
<p className="text-muted-foreground">Interface</p>
<p className="font-mono">{status?.interface ?? 'wg0'}</p>
</div>
<div>
<p className="text-muted-foreground">Connected peers</p>
<p className="font-mono">{status?.peerCount ?? 0}</p>
</div>
<div>
<p className="text-muted-foreground">Listen port</p>
<p className="font-mono">{status?.listenPort ?? config?.listenPort ?? 51820}</p>
</div>
</div>
<div className="flex gap-2 pt-2">
<Button
variant="outline"
size="sm"
className="gap-1 h-7 text-xs"
onClick={() => setShowAdvanced(!showAdvanced)}
>
{showAdvanced ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
Advanced
</Button>
</div>
{showAdvanced && status?.rawOutput && (
<div className="border-t pt-3">
<span className="text-sm font-medium">WireGuard interface status</span>
<pre className="bg-muted p-3 rounded-lg overflow-x-auto text-xs font-mono mt-2">
{status.rawOutput}
</pre>
</div>
)}
</CardContent>
</Card>
{/* Server configuration card */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Server Configuration</CardTitle>
{!editingConfig && (
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setConfirmKeygen(true)}
disabled={isGeneratingKeypair}
className="gap-1 h-7 text-xs"
>
{isGeneratingKeypair ? <Loader2 className="h-3 w-3 animate-spin" /> : <KeyRound className="h-3 w-3" />}
Generate Keys
</Button>
<Button
variant="outline"
size="sm"
onClick={handleEditConfig}
className="gap-1 h-7 text-xs"
>
<Edit2 className="h-3 w-3" />
Configure
</Button>
</div>
)}
</div>
</CardHeader>
<CardContent>
{isLoadingConfig ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : editingConfig ? (
<form onSubmit={handleSubmit(handleSaveConfig)} className="space-y-3">
<div className="flex items-center gap-3">
<input
type="checkbox"
id="enabled"
{...register('enabled')}
className="h-4 w-4"
/>
<Label htmlFor="enabled">Enabled</Label>
</div>
<div>
<Label htmlFor="endpoint">Public Endpoint</Label>
<Input
id="endpoint"
{...register('endpoint')}
placeholder="vpn.example.com or 1.2.3.4"
className="mt-1"
/>
<p className="text-xs text-muted-foreground mt-1">
Public hostname or IP clients use to connect. Port appended automatically if omitted.
</p>
</div>
<div>
<Label htmlFor="listenPort">Listen Port</Label>
<Input
id="listenPort"
type="number"
{...register('listenPort', { required: 'Required', min: { value: 1, message: 'Invalid port' }, max: { value: 65535, message: 'Invalid port' } })}
className="mt-1"
/>
{errors.listenPort && <p className="text-sm text-red-600 mt-1">{errors.listenPort.message}</p>}
</div>
<div>
<Label htmlFor="address">Server VPN Address</Label>
<Input
id="address"
{...register('address', { required: 'Required' })}
placeholder="10.8.0.1/24"
className="mt-1 font-mono"
/>
{errors.address && <p className="text-sm text-red-600 mt-1">{errors.address.message}</p>}
</div>
<div>
<Label htmlFor="dns">DNS for Clients</Label>
<Input
id="dns"
{...register('dns')}
placeholder="10.8.0.1"
className="mt-1 font-mono"
/>
</div>
<div>
<Label htmlFor="lanCIDR">LAN CIDR (optional)</Label>
<Input
id="lanCIDR"
{...register('lanCIDR')}
placeholder="192.168.8.0/24"
className="mt-1 font-mono"
/>
<p className="text-xs text-muted-foreground mt-1">
Routes LAN traffic through the VPN and enables masquerade on the server.
</p>
</div>
<div className="flex gap-2 pt-2">
<Button type="submit" size="sm" disabled={isUpdatingConfig}>
{isUpdatingConfig && <Loader2 className="h-3 w-3 animate-spin mr-1" />}
Save
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => setEditingConfig(false)}>
Cancel
</Button>
</div>
</form>
) : (
<div className="space-y-3 text-sm">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div>
<p className="text-muted-foreground">Status</p>
<Badge variant={config?.enabled ? 'success' : 'secondary'} className="mt-0.5 gap-1">
{config?.enabled && <CheckCircle className="h-3 w-3" />}
{config?.enabled ? 'Enabled' : 'Disabled'}
</Badge>
</div>
<div>
<p className="text-muted-foreground">Public Endpoint</p>
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">
{config?.endpoint || <span className="text-muted-foreground italic">not set</span>}
</p>
</div>
<div>
<p className="text-muted-foreground">Listen Port</p>
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.listenPort ?? 51820}</p>
</div>
<div>
<p className="text-muted-foreground">VPN Subnet</p>
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.address || '—'}</p>
</div>
<div>
<p className="text-muted-foreground">DNS for Clients</p>
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.dns || '—'}</p>
</div>
<div>
<p className="text-muted-foreground">LAN CIDR</p>
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.lanCIDR || '—'}</p>
</div>
<div>
<p className="text-muted-foreground">Public Key</p>
<div className="flex items-center gap-1 mt-0.5">
<p className="font-mono bg-muted rounded px-2 py-1 truncate text-xs flex-1">
{config?.publicKey || <span className="italic">not generated</span>}
</p>
{config?.publicKey && <CopyButton text={config.publicKey} />}
</div>
</div>
</div>
{!config?.publicKey && (
<Alert>
<KeyRound className="h-4 w-4" />
<AlertDescription>
No server keypair yet. Click <strong>Generate Keys</strong> before adding peers.
</AlertDescription>
</Alert>
)}
</div>
)}
</CardContent>
</Card>
{/* Peers card */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Peers</CardTitle>
<Button
size="sm"
onClick={() => setAddPeerOpen(true)}
disabled={!config?.publicKey}
className="gap-1 h-7 text-xs"
>
<Plus className="h-3 w-3" />
Add Peer
</Button>
</div>
</CardHeader>
<CardContent>
{isLoadingPeers ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : peers.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<Shield className="h-10 w-10 mx-auto mb-2 opacity-30" />
<p className="text-sm">No peers yet. Add a peer to get started.</p>
</div>
) : (
<div className="divide-y">
{peers.map((peer) => (
<div key={peer.id} className="flex items-center justify-between py-3">
<div>
<p className="font-medium text-sm">{peer.name}</p>
<p className="text-xs text-muted-foreground font-mono">{peer.allowedIPs}</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="gap-1 h-7 text-xs"
disabled={loadingPeerConfig === peer.id}
onClick={() => handleShowPeerConfig(peer)}
>
{loadingPeerConfig === peer.id
? <Loader2 className="h-3 w-3 animate-spin" />
: <RefreshCw className="h-3 w-3" />}
Config
</Button>
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0 text-destructive hover:text-destructive"
onClick={() => setDeleteConfirmPeer(peer)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
{/* Add peer drawer */}
<Sheet open={addPeerOpen} onOpenChange={setAddPeerOpen}>
<SheetContent>
<SheetHeader>
<SheetTitle>Add Peer</SheetTitle>
</SheetHeader>
<div className="space-y-4 py-6">
<div>
<Label htmlFor="peerName">Peer Name</Label>
<Input
id="peerName"
value={newPeerName}
onChange={(e) => setNewPeerName(e.target.value)}
placeholder="e.g. my-phone, laptop"
className="mt-1"
onKeyDown={(e) => e.key === 'Enter' && handleAddPeer()}
/>
<p className="text-xs text-muted-foreground mt-1">
A VPN IP will be assigned automatically from the server subnet.
</p>
</div>
{addPeerError && (
<Alert variant="error">
<AlertDescription>{String(addPeerError)}</AlertDescription>
</Alert>
)}
</div>
<SheetFooter>
<Button onClick={handleAddPeer} disabled={isAddingPeer || !newPeerName.trim()}>
{isAddingPeer && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
Add Peer
</Button>
<Button variant="outline" onClick={() => setAddPeerOpen(false)}>Cancel</Button>
</SheetFooter>
</SheetContent>
</Sheet>
{/* Peer config modal */}
<Dialog open={!!peerConfigModal} onOpenChange={(open) => !open && setPeerConfigModal(null)}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>{peerConfigModal?.name} Client Config</DialogTitle>
</DialogHeader>
{peerConfigModal && (
<div className="space-y-4">
<div className="flex justify-center">
<QRCodeSVG value={peerConfigModal.config} size={220} />
</div>
<p className="text-xs text-center text-muted-foreground">
Scan with the WireGuard mobile app
</p>
<div className="relative">
<pre className="text-xs font-mono bg-muted rounded-md p-3 overflow-x-auto whitespace-pre-wrap break-all">
{peerConfigModal.config}
</pre>
<div className="absolute top-2 right-2">
<CopyButton text={peerConfigModal.config} />
</div>
</div>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setPeerConfigModal(null)}>Close</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Generate keypair confirmation */}
<AlertDialog open={confirmKeygen} onOpenChange={setConfirmKeygen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Regenerate Server Keypair?</AlertDialogTitle>
<AlertDialogDescription>
This will generate a new server private and public key. All existing peer configs
will become invalid you'll need to regenerate and redistribute them.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleGenerateKeypair}>Generate</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Delete peer confirmation */}
<AlertDialog open={!!deleteConfirmPeer} onOpenChange={(open) => !open && setDeleteConfirmPeer(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete peer "{deleteConfirmPeer?.name}"?</AlertDialogTitle>
<AlertDialogDescription>
This will remove the peer configuration. The peer will no longer be able to connect
after you apply the VPN config.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDeletePeer}>Delete</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -0,0 +1,11 @@
export { Message } from './Message';
export { DnsmasqSection } from './DnsmasqSection';
export { AppSidebar } from './AppSidebar';
export { ErrorBoundary, ErrorFallback } from './ErrorBoundary';
export { CentralComponent } from './CentralComponent';
export { CloudflareComponent } from './CloudflareComponent';
export { DnsComponent } from './DnsComponent';
export { DhcpComponent } from './DhcpComponent';
export { DownloadButton } from './DownloadButton';
export { CopyButton } from './CopyButton';
export { HelpPanel } from './HelpPanel';

View File

@@ -0,0 +1,194 @@
import * as React from "react"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } 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(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm"
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"group/alert-dialog-content 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 bg-background p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className
)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-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 sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
className
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
)
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}

View File

@@ -0,0 +1,76 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { X } from 'lucide-react';
const alertVariants = cva(
'relative w-full rounded-lg border p-4 [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg+div]:translate-y-[-3px] [&:has(svg)]:pl-11',
{
variants: {
variant: {
default: 'bg-background text-foreground border-border',
success: 'bg-green-50 text-green-900 border-green-200 dark:bg-green-950/20 dark:text-green-100 dark:border-green-800',
error: 'bg-red-50 text-red-900 border-red-200 dark:bg-red-950/20 dark:text-red-100 dark:border-red-800',
warning: 'bg-yellow-50 text-yellow-900 border-yellow-200 dark:bg-yellow-950/20 dark:text-yellow-100 dark:border-yellow-800',
info: 'bg-blue-50 text-blue-900 border-blue-200 dark:bg-blue-950/20 dark:text-blue-100 dark:border-blue-800',
},
},
defaultVariants: {
variant: 'default',
},
}
);
export interface AlertProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof alertVariants> {
onClose?: () => void;
}
const Alert = React.forwardRef<HTMLDivElement, AlertProps>(
({ className, variant, onClose, children, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={alertVariants({ variant, className })}
{...props}
>
{children}
{onClose && (
<button
onClick={onClose}
className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2"
aria-label="Close"
>
<X className="h-4 w-4" />
</button>
)}
</div>
)
);
Alert.displayName = 'Alert';
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={`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={`text-sm [&_p]:leading-relaxed ${className || ''}`}
{...props}
/>
));
AlertDescription.displayName = 'AlertDescription';
export { Alert, AlertTitle, AlertDescription };

View File

@@ -0,0 +1,50 @@
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 badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-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 transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
success:
"border-transparent bg-green-500 text-white [a&]:hover:bg-green-600 dark:bg-green-600 dark:[a&]:hover:bg-green-700",
warning:
"border-transparent bg-yellow-500 text-white [a&]:hover:bg-yellow-600 dark:bg-yellow-600 dark:[a&]:hover:bg-yellow-700",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,59 @@
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 shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs 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",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
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",
},
},
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 }

View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View 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 }

View 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 }

View File

@@ -0,0 +1,141 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="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 DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="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}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground 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 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,95 @@
import { useEffect, type ReactNode } from 'react';
interface DrawerProps {
open: boolean;
onClose: () => void;
title: string;
children: ReactNode;
footer?: ReactNode;
}
export function Drawer({ open, onClose, title, children, footer }: DrawerProps) {
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && open) {
onClose();
}
};
document.addEventListener('keydown', handleEscape);
return () => document.removeEventListener('keydown', handleEscape);
}, [open, onClose]);
useEffect(() => {
if (open) {
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = '';
}
return () => {
document.body.style.overflow = '';
};
}, [open]);
return (
<>
{/* Overlay with fade transition */}
<div
className={`
fixed inset-0 z-50
bg-black/50 backdrop-blur-sm
transition-opacity duration-300 ease-in-out
${open ? 'opacity-100' : 'opacity-0 pointer-events-none'}
`}
onClick={onClose}
aria-hidden="true"
/>
{/* Drawer panel with slide transition */}
<div
className={`
fixed inset-y-0 right-0 z-50
w-full max-w-md
transform transition-transform duration-300 ease-in-out
${open ? 'translate-x-0' : 'translate-x-full'}
`}
>
<div className="flex h-full flex-col bg-background shadow-xl">
{/* Header */}
<div className="border-b border-border px-6 py-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold text-foreground">{title}</h2>
<button
onClick={onClose}
className="rounded-md text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label="Close drawer"
>
<svg
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
strokeWidth={2}
stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto px-6 py-6">
{children}
</div>
{/* Footer */}
{footer && (
<div className="border-t border-border px-6 py-4">
{footer}
</div>
)}
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,97 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
interface EntityTileProps extends React.ComponentProps<"div"> {
icon?: React.ReactNode
title: string
version?: string
description?: React.ReactNode
statusIndicator?: React.ReactNode
onClick?: () => void
disabled?: boolean
loading?: boolean
tint?: string
}
function EntityTile({
icon,
title,
version,
description,
statusIndicator,
onClick,
disabled = false,
loading = false,
tint,
className,
children,
...props
}: EntityTileProps) {
const handleKeyDown = (e: React.KeyboardEvent) => {
if (disabled || !onClick) return
if (e.key === "Enter" || e.key === " ") {
e.preventDefault()
onClick()
}
}
return (
<div className="flex flex-col items-center w-full sm:w-[240px]">
<div
role={onClick ? "button" : undefined}
tabIndex={onClick && !disabled ? 0 : undefined}
onClick={!disabled && !loading ? onClick : undefined}
onKeyDown={onClick ? handleKeyDown : undefined}
aria-disabled={disabled || undefined}
className={cn(
"relative w-full aspect-square text-black border border-border/60 p-4 flex flex-col rounded-none",
"transition-all duration-200",
onClick && !disabled && !loading && [
"cursor-pointer",
"hover:shadow-md hover:border-primary/50",
"hover:scale-[1.02] hover:-translate-y-0.5",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
],
loading && "ring-2 ring-primary/60 scale-[0.97] brightness-95",
disabled && "opacity-50 pointer-events-none",
className
)}
{...props}
style={tint ? { backgroundColor: `${tint}FF` } : undefined}
>
{loading && (
<div className="absolute inset-0 bg-black/10 animate-pulse rounded-[inherit]" />
)}
<div className="flex flex-col gap-3 flex-1">
<div className="flex items-start gap-3">
{icon && (
<div className="h-10 w-10 rounded-lg bg-white/70 flex items-center justify-center overflow-hidden shrink-0">
{icon}
</div>
)}
<div className="flex-1 min-w-0">
<h4 className="font-medium truncate mb-1">{title}</h4>
{version && (
<Badge variant="outline" className="text-xs text-black/70 border-black/20">
{version}
</Badge>
)}
</div>
</div>
{description && (
<p className="text-sm text-black/60 line-clamp-2">{description}</p>
)}
</div>
{children}
</div>
<div className="flex justify-center mt-2 h-3">
{statusIndicator}
</div>
</div>
)
}
export { EntityTile }
export type { EntityTileProps }

View File

@@ -0,0 +1,167 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState } = useFormContext()
const formState = useFormState({ name: fieldContext.name })
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
)
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField()
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField()
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : props.children
if (!body) {
return null
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body}
</p>
)
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View File

@@ -0,0 +1,28 @@
export { Button, buttonVariants } from './button';
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } from './card';
export { Badge, badgeVariants } from './badge';
export { Alert, AlertTitle, AlertDescription } from './alert';
export { Input } from './input';
export { Label } from './label';
export { Textarea } from './textarea';
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
} from './dialog';
export {
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
} from './form';

View File

@@ -0,0 +1,26 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
ref={ref}
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-transparent dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] focus-visible:bg-transparent dark:focus-visible:bg-input/30",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
)
Input.displayName = 'Input'
export { Input }

View File

@@ -0,0 +1,22 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,158 @@
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.ElementRef<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.ElementRef<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.ElementRef<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.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 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.ElementRef<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.ElementRef<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.ElementRef<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,
}

View File

@@ -0,0 +1,28 @@
"use client"
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 }

View File

@@ -0,0 +1,137 @@
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,
}

View File

@@ -0,0 +1,727 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva } from "class-variance-authority"
import 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"
type 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 group-data-[collapsible=icon]:items-center group-data-[state=expanded]:px-2", 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
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,
}

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -0,0 +1,29 @@
import * as React from "react"
import * as SwitchPrimitive from "@radix-ui/react-switch"
import { cn } from "@/lib/utils"
function Switch({
className,
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitive.Root>
)
}
export { Switch }

View File

@@ -0,0 +1,64 @@
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
function Tabs({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function TabsList({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
className
)}
{...props}
/>
)
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent }

View File

@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

View File

@@ -0,0 +1,59 @@
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
)
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-primary text-primary-foreground 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 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }