refactor: replace AdminPageHeader with PageShell

Migrate pages to PageShell, add global autofill styles, and update SDK/simulator page logic for server URL and state consistency.
This commit is contained in:
Team Dark Devil committed 2026-11-17 00:24:33 +06:00
1 parent fa4516b078
commit 81c5e4e2fd
24 files changed
+1238 -595

No files matched your search

+25 -16
View File
@@ -1,29 +1,38 @@
import { cn } from '@/lib/utils';
import Link from 'next/link';
import React from 'react';
interface AdminPageHeaderProps {
title: string;
actions?: React.ReactNode;
className?: string;
}
export function AdminPageHeader({ title, actions }: AdminPageHeaderProps) {
export function AdminPageHeader({ title, actions, className }: AdminPageHeaderProps) {
return (
<header className="mb-3 flex min-h-8 flex-wrap items-center justify-between gap-2 border-b border-[var(--border)] pb-2.5">
<div className="flex min-w-0 items-center gap-1.5">
<Link
href="/vcon/dashboard"
className="text-[11.5px] text-[var(--text-faint)] hover:text-[var(--text-muted)]"
>
Console
</Link>
<span className="text-[11px] text-[var(--border-strong)]" aria-hidden="true">
/
</span>
<h1 className="truncate text-[13.5px] font-medium tracking-tight text-[var(--text)]">
{title}
</h1>
<header
className={cn(
'-mx-3.5 mb-3 flex h-10 shrink-0 items-center border-b border-[var(--border)] bg-[var(--surface)] px-3.5 sm:-mx-5 sm:px-5',
className
)}
>
<div className="flex w-full max-w-[var(--console-width)] min-w-0 items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-1.5">
<Link
href="/vcon/dashboard"
className="text-[11.5px] text-[var(--text-faint)] hover:text-[var(--text-muted)]"
>
Console
</Link>
<span className="text-[11px] text-[var(--border-strong)]" aria-hidden="true">
/
</span>
<h1 className="truncate text-[13px] font-medium tracking-tight text-[var(--text)]">
{title}
</h1>
</div>
{actions && <div className="flex shrink-0 items-center gap-1.5">{actions}</div>}
</div>
{actions && <div className="flex items-center gap-1.5">{actions}</div>}
</header>
);
}
+1 -1
View File
@@ -29,7 +29,7 @@ export const MainLayout: React.FC<MainLayoutProps> = ({
onToggleSidebar={() => setSidebarOpen((prev) => !prev)}
/>
<main className="flex flex-1 min-w-0 flex-col">
<div className="w-full max-w-[var(--console-width)] flex-1 px-3.5 py-3 sm:px-5 sm:py-3.5">
<div className="w-full max-w-[var(--console-width)] flex-1 px-3.5 pb-4 pt-0 sm:px-5">
{children}
</div>
<Footer isAdmin={true} />
+33
View File
@@ -0,0 +1,33 @@
import { cn } from '@/lib/utils';
import React from 'react';
import { AdminPageHeader } from './AdminPageHeader';
interface PageShellProps {
title: string;
actions?: React.ReactNode;
children: React.ReactNode;
className?: string;
}
/**
* Single-Source-of-Truth Page Container for all /vcon/* Control Panel views.
* Guarantees that AdminPageHeader, StatStrip, Panels, Settings forms, and Tables
* share the exact same full-width container alignment and uniform vertical rhythm.
*/
export function PageShell({
title,
actions,
children,
className,
}: PageShellProps) {
return (
<section className={cn('flex w-full min-w-0 flex-col', className)}>
<AdminPageHeader title={title} actions={actions} className="mb-0" />
<div className="flex w-full max-w-[var(--console-width)] min-w-0 flex-col gap-3 pt-3 [&>.stat-strip]:mb-0">
{children}
</div>
</section>
);
}
export default PageShell;
+42 -6
View File
@@ -3,6 +3,7 @@
import { Button } from '@/components/ui/Button';
import { Icon } from '@/components/ui/Icon';
import { cn } from '@/lib/utils';
import { getCached, setCached } from '@/lib/vconCache';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import React, { useEffect, useState } from 'react';
@@ -12,6 +13,11 @@ interface SidebarProps {
onClose?: () => void;
}
interface CachedProfile {
email?: string;
role?: string;
}
const NAVIGATION_SECTIONS = [
{
group: 'Main',
@@ -41,6 +47,12 @@ export const Sidebar: React.FC<SidebarProps> = ({
const pathname = usePathname();
const [isSigningOut, setIsSigningOut] = useState(false);
const [theme, setTheme] = useState<'dark' | 'light'>('dark');
const [adminEmail, setAdminEmail] = useState<string>(
() => getCached<CachedProfile>('vcon:profile', {}).email || 'Admin'
);
const [adminRole, setAdminRole] = useState<string>(
() => getCached<CachedProfile>('vcon:profile', {}).role || 'Owner'
);
useEffect(() => {
const saved = localStorage.getItem('datastack-theme') as 'dark' | 'light' | null;
@@ -50,6 +62,28 @@ export const Sidebar: React.FC<SidebarProps> = ({
document.documentElement.classList.toggle('dark', initial === 'dark');
}, []);
useEffect(() => {
const cached = getCached<CachedProfile>('vcon:profile', {});
if (cached.email) {
setAdminEmail(cached.email);
if (cached.role) setAdminRole(cached.role);
}
fetch('/api/auth/profile', { credentials: 'include' })
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (data?.profile?.email) {
setCached('vcon:profile', data.profile);
setCached('vcon:profile-loaded', true);
setAdminEmail(data.profile.email);
setAdminRole(data.profile.role || 'Owner');
}
})
.catch(() => {
// Keep cached or default identity label if offline
});
}, [pathname]);
const toggleTheme = () => {
const nextTheme = theme === 'dark' ? 'light' : 'dark';
setTheme(nextTheme);
@@ -72,6 +106,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
}
};
const avatarInitial = adminEmail.trim().charAt(0).toUpperCase() || 'A';
return (
<>
{isOpen && (
@@ -87,7 +123,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
isOpen ? 'translate-x-0' : '-translate-x-full'
)}
>
{/* Brand Header */}
{/* Brand Header (h-10 = 40px, aligned pixel-for-pixel with AdminPageHeader) */}
<div className="flex h-10 shrink-0 items-center justify-between border-b border-[var(--border)] px-3">
<Link
href="/vcon/dashboard"
@@ -158,23 +194,23 @@ export const Sidebar: React.FC<SidebarProps> = ({
))}
</nav>
{/* Bottom Dock: Identity + Theme Toggle + Sign Out */}
{/* Bottom Dock: Live Admin Identity + Theme Toggle + Sign Out */}
<div className="flex shrink-0 items-center gap-1 border-t border-[var(--border)] bg-[var(--bg)] px-2.5 py-2">
<Link
href="/vcon/profile"
onClick={onClose}
className="flex flex-1 min-w-0 items-center gap-2 hover:opacity-90"
title="Admin Profile"
title={`Admin Profile (${adminEmail})`}
>
<div className="grid h-6 w-6 shrink-0 place-items-center border border-[var(--border-strong)] bg-[var(--surface-3)] text-[10.5px] font-medium text-[var(--text)]">
A
{avatarInitial}
</div>
<div className="min-w-0 flex-1 leading-tight">
<div className="truncate text-[11px] font-medium text-[var(--text)]">
Admin
{adminEmail}
</div>
<div className="truncate text-[9px] uppercase tracking-wider text-[var(--text-faint)]">
Owner
{adminRole}
</div>
</div>
</Link>
+1 -2
View File
@@ -27,7 +27,7 @@ export function ClientsFilters({
counts,
}: ClientsFiltersProps) {
return (
<div className="mb-2.5 flex flex-wrap items-center gap-2">
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-[var(--border)] bg-[var(--surface)] px-3 py-2">
<div className="w-full flex-1 sm:max-w-xs">
<Input
compact
@@ -37,7 +37,6 @@ export function ClientsFilters({
value={search}
onChange={(event) => onSearchChange(event.target.value)}
placeholder="Search client..."
className="bg-[var(--surface)]"
/>
</div>
<div className="ml-auto flex min-w-0 gap-1 overflow-x-auto" role="group" aria-label="Filter clients by status">
+16 -16
View File
@@ -5,14 +5,14 @@ import { CopyButton } from '@/components/ui/CopyButton';
import { Textarea } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import {
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
TableWrap,
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
import { useRouter } from 'next/navigation';
@@ -105,8 +105,8 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
return (
<>
<TableWrap>
<Table className="min-w-[680px] text-[11px]">
<TableWrap className="border-0 bg-transparent">
<Table>
<TableHeader>
<TableRow>
<TableHead>Client</TableHead>
@@ -137,20 +137,20 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
<div className="flex min-w-0 items-center gap-2">
<span className={`h-1.5 w-1.5 shrink-0 ${dotClass}`} title={label} />
<div className="min-w-0 leading-tight">
<div className="truncate text-[11.5px] text-[var(--text)]">{client.name}</div>
<div className="mt-0.5 truncate font-mono text-[10px] text-[var(--text-faint)]">{client.clientId}</div>
<div className="truncate font-medium text-[var(--text)]">{client.name}</div>
<div className="mt-0.5 truncate font-mono text-[10.5px] text-[var(--text-faint)]">{client.clientId}</div>
</div>
</div>
</TableCell>
<TableCell className="font-mono text-[11px]">
<TableCell className="font-mono">
sec_••••••••
</TableCell>
<TableCell className="text-right font-mono text-[11px] tabular-nums">
<TableCell className="text-right font-mono tabular-nums">
{client.totalEvents.toLocaleString()}
</TableCell>
<TableCell className="font-mono text-[11px] tabular-nums">
<TableCell className="font-mono tabular-nums">
{client.lastActive ? new Date(client.lastActive).toLocaleTimeString([], { hour12: false }) : '—'}
<span className="ml-1 font-sans text-[10px] text-[var(--text-faint)]">{relativeTime(client.lastActive, now)}</span>
<span className="ml-1.5 font-sans text-[10.5px] text-[var(--text-faint)]">{relativeTime(client.lastActive, now)}</span>
</TableCell>
<TableCell className="text-right">
<div className="inline-flex gap-0.5">
+119 -65
View File
@@ -1,18 +1,18 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { PageShell } from '@/components/layout/PageShell';
import { Button } from '@/components/ui/Button';
import { ClientList, type ClientListItem } from '@/components/ui/ClientList';
import { Panel } from '@/components/ui/Panel';
import { StatStrip } from '@/components/ui/StatStrip';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
TableWrap,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { getCached, setCached } from '@/lib/vconCache';
import Link from 'next/link';
@@ -49,21 +49,30 @@ type StorageFile = {
};
export const DashboardOverview: React.FC = () => {
const [metrics, setMetrics] = useState<DashboardMetrics | null>(() => getCached<DashboardMetrics | null>('vcon:metrics', null));
const [events, setEvents] = useState<EventItem[]>(() => getCached<EventItem[]>('vcon:dashboard-events', []));
const [clients, setClients] = useState<ClientListItem[]>(() => getCached<ClientListItem[]>('vcon:clients', []));
const [files, setFiles] = useState<StorageFile[]>(() => getCached<StorageFile[]>('vcon:storage-files', []));
const [metrics, setMetrics] = useState<DashboardMetrics | null>(() =>
getCached<DashboardMetrics | null>('vcon:metrics', null)
);
const [events, setEvents] = useState<EventItem[]>(() =>
getCached<EventItem[]>('vcon:dashboard-events', [])
);
const [clients, setClients] = useState<ClientListItem[]>(() =>
getCached<ClientListItem[]>('vcon:clients', [])
);
const [files, setFiles] = useState<StorageFile[]>(() =>
getCached<StorageFile[]>('vcon:storage-files', [])
);
const [isRefreshing, setIsRefreshing] = useState(false);
const refresh = useCallback(async () => {
setIsRefreshing(true);
try {
const [metricsResponse, eventsResponse, storageResponse, clientsResponse] = await Promise.all([
fetch('/api/metrics', { cache: 'no-store' }),
fetch('/api/events?limit=8', { cache: 'no-store' }),
fetch('/api/storage', { cache: 'no-store' }),
fetch('/api/clients', { cache: 'no-store' }),
]);
const [metricsResponse, eventsResponse, storageResponse, clientsResponse] =
await Promise.all([
fetch('/api/metrics', { cache: 'no-store' }),
fetch('/api/events?limit=8', { cache: 'no-store' }),
fetch('/api/storage', { cache: 'no-store' }),
fetch('/api/clients', { cache: 'no-store' }),
]);
if (metricsResponse.ok) {
const nextMetrics = await metricsResponse.json();
@@ -99,60 +108,79 @@ export const DashboardOverview: React.FC = () => {
const storedRecordsToday = files
.filter((file) => file.date === today)
.reduce((total, file) => total + file.linesCount, 0);
const eventsToday = storedRecordsToday + (metrics?.bufferStats.currentBufferSize ?? 0);
const activeClients = metrics?.activeClients ?? clients.filter((client) => client.status === 'active').length;
const eventsToday =
storedRecordsToday + (metrics?.bufferStats.currentBufferSize ?? 0);
const activeClients =
metrics?.activeClients ??
clients.filter((client) => client.status === 'active').length;
const totalClients = metrics?.totalClients ?? clients.length;
const totalStorage = metrics?.storageStats.totalMB ?? '0.00';
const totalStorageBytes = metrics?.storageStats.totalBytes ?? 0;
const storageValue = totalStorageBytes < 1024 * 1024
? String(Math.max(1, Math.round(totalStorageBytes / 1024)))
: totalStorage;
const storageValue =
totalStorageBytes < 1024 * 1024
? String(Math.max(1, Math.round(totalStorageBytes / 1024)))
: totalStorage;
const storageUnit = totalStorageBytes < 1024 * 1024 ? 'KB' : 'MB';
const totalFiles = metrics?.storageStats.totalFiles ?? files.length;
const totalRows = metrics?.storageStats.totalRows ?? files.reduce((sum, file) => sum + file.linesCount, 0);
const totalRows =
metrics?.storageStats.totalRows ??
files.reduce((sum, file) => sum + file.linesCount, 0);
return (
<section className="w-full">
<AdminPageHeader
title="Dashboard"
actions={
<>
<Button
size="icon"
variant="secondary"
icon="RefreshCw"
aria-label="Refresh dashboard"
title="Refresh dashboard"
loading={isRefreshing}
onClick={() => void refresh()}
/>
<a href="/api/export?clientId=all" download>
<Button size="xs" variant="secondary" icon="Download">Export</Button>
</a>
<Link href="/vcon/clients">
<Button size="xs" variant="primary" icon="Plus">New client</Button>
</Link>
</>
}
/>
<PageShell
title="Dashboard"
actions={
<>
<Button
size="icon"
variant="secondary"
icon="RefreshCw"
aria-label="Refresh dashboard"
title="Refresh dashboard"
loading={isRefreshing}
onClick={() => void refresh()}
/>
<a href="/api/export?clientId=all" download>
<Button size="xs" variant="secondary" icon="Download">
Export
</Button>
</a>
<Link href="/vcon/clients">
<Button size="xs" variant="primary" icon="Plus">
New client
</Button>
</Link>
</>
}
>
<StatStrip
items={[
{ label: 'Events today', value: eventsToday.toLocaleString() },
{ label: 'Active clients', value: `${activeClients} / ${totalClients}`, dot: activeClients > 0 ? 'ok' : 'off' },
{
label: 'Active clients',
value: `${activeClients} / ${totalClients}`,
dot: activeClients > 0 ? 'ok' : 'off',
},
{ label: 'Storage used', value: `${storageValue} ${storageUnit}` },
{ label: 'Stored rows', value: totalRows.toLocaleString() },
]}
/>
<div className="grid min-w-0 grid-cols-1 gap-2.5 lg:grid-cols-[minmax(0,1.85fr)_minmax(0,1fr)]">
<div className="grid min-w-0 grid-cols-1 gap-3 lg:grid-cols-[minmax(0,1.85fr)_minmax(0,1fr)]">
<Panel
title="Recent events"
meta={`${events.length}`}
action={<Link href="/vcon/data" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all →</Link>}
action={
<Link
href="/vcon/data"
className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]"
>
View all →
</Link>
}
>
<TableWrap className="border-0 bg-transparent">
<Table className="min-w-[560px] text-[11px]">
<Table>
<TableHeader>
<TableRow>
<TableHead>Time</TableHead>
@@ -164,16 +192,18 @@ export const DashboardOverview: React.FC = () => {
<TableBody>
{events.map((event) => (
<TableRow key={event.eventId}>
<TableCell className="font-mono text-[10.5px] tabular-nums text-[var(--text-faint)]">
{event.timestamp.includes('T') ? new Date(event.timestamp).toLocaleTimeString() : event.timestamp}
<TableCell className="font-mono tabular-nums text-[var(--text-faint)]">
{event.timestamp.includes('T')
? new Date(event.timestamp).toLocaleTimeString()
: event.timestamp}
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--accent)]">
<TableCell className="font-mono text-[var(--accent)]">
{event.clientId}
</TableCell>
<TableCell className="max-w-[380px] truncate font-mono text-[11px] text-[var(--text)]">
<TableCell className="max-w-[380px] truncate font-mono text-[var(--text)]">
{event.payload}
</TableCell>
<TableCell className="text-right font-mono text-[10.5px] tabular-nums text-[var(--text-faint)]">
<TableCell className="text-right font-mono tabular-nums text-[var(--text-faint)]">
{new TextEncoder().encode(event.payload).length} B
</TableCell>
</TableRow>
@@ -183,10 +213,17 @@ export const DashboardOverview: React.FC = () => {
</TableWrap>
</Panel>
<div className="flex min-w-0 flex-col gap-2.5">
<div className="flex min-w-0 flex-col gap-3">
<Panel
title="Clients"
action={<Link href="/vcon/clients" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">All →</Link>}
action={
<Link
href="/vcon/clients"
className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]"
>
All →
</Link>
}
>
<ClientList clients={clients} limit={4} />
</Panel>
@@ -194,14 +231,29 @@ export const DashboardOverview: React.FC = () => {
<Panel
title="Storage"
meta={`${totalFiles}`}
action={<a href="/api/export?clientId=all" download className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">Export ↓</a>}
action={
<a
href="/api/export?clientId=all"
download
className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]"
>
Export ↓
</a>
}
>
<div className="divide-y divide-[var(--border)]">
{files.slice(0, 3).map((file) => (
<div key={`${file.clientId}/${file.filename}`} className="flex items-center justify-between gap-2.5 px-3 py-1.5">
<div
key={`${file.clientId}/${file.filename}`}
className="flex items-center justify-between gap-2.5 px-3 py-1.5"
>
<div className="min-w-0">
<p className="truncate text-[11.5px] text-[var(--text)]">{file.filename}</p>
<p className="truncate font-mono text-[10px] text-[var(--text-faint)]">{file.clientId}</p>
<p className="truncate text-[11.5px] text-[var(--text)]">
{file.filename}
</p>
<p className="truncate font-mono text-[10px] text-[var(--text-faint)]">
{file.clientId}
</p>
</div>
<span className="shrink-0 font-mono text-[10.5px] tabular-nums text-[var(--text-muted)]">
{(file.sizeBytes / 1024).toFixed(1)} KB
@@ -209,13 +261,15 @@ export const DashboardOverview: React.FC = () => {
</div>
))}
{files.length === 0 && (
<p className="px-3 py-4 text-[11px] text-[var(--text-faint)]">No CSV files</p>
<p className="px-3 py-4 text-[11px] text-[var(--text-faint)]">
No CSV files
</p>
)}
</div>
</Panel>
</div>
</div>
</section>
</PageShell>
);
};
+50 -49
View File
@@ -1,20 +1,20 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { PageShell } from '@/components/layout/PageShell';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Input, Select } from '@/components/ui/Input';
import { Panel } from '@/components/ui/Panel';
import { Pill } from '@/components/ui/Pill';
import {
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
TableWrap,
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
@@ -132,35 +132,33 @@ export function DataBrowser() {
};
return (
<section className="w-full">
<AdminPageHeader
title="Events"
actions={
<>
<Button
type="button"
variant="secondary"
size="icon"
icon="RefreshCw"
title="Refresh events"
aria-label="Refresh events"
loading={refreshing}
onClick={refresh}
/>
<Button
type="button"
variant="primary"
size="xs"
icon="Download"
onClick={() => router.push('/vcon/export')}
>
Export CSV
</Button>
</>
}
/>
<Card compact className="mb-2.5 p-0">
<PageShell
title="Events"
actions={
<>
<Button
type="button"
variant="secondary"
size="icon"
icon="RefreshCw"
title="Refresh events"
aria-label="Refresh events"
loading={refreshing}
onClick={refresh}
/>
<Button
type="button"
variant="primary"
size="xs"
icon="Download"
onClick={() => router.push('/vcon/export')}
>
Export CSV
</Button>
</>
}
>
<Card compact className="p-0">
<div className="grid grid-cols-1 gap-px bg-[var(--border)] sm:grid-cols-2 lg:grid-cols-5">
<div className="bg-[var(--surface)] p-2.5">
<Select
@@ -221,8 +219,8 @@ export function DataBrowser() {
meta={`${total.toLocaleString()} · ${page}/${pageCount}`}
bodyClassName="overflow-hidden"
>
<TableWrap className="border-0">
<Table className="min-w-[680px] text-[11px]">
<TableWrap className="border-0 bg-transparent">
<Table>
<TableHeader>
<TableRow>
<TableHead>Time</TableHead>
@@ -241,7 +239,7 @@ export function DataBrowser() {
) : (
events.map((event) => (
<TableRow key={event.eventId}>
<TableCell className="font-mono text-[10.5px] tabular-nums text-[var(--text)]">
<TableCell className="font-mono tabular-nums text-[var(--text)]">
{new Date(event.timestamp).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
@@ -249,19 +247,22 @@ export function DataBrowser() {
hour12: false,
})}
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--accent)]">{event.clientId}</TableCell>
<TableCell className="hidden font-mono text-[10.5px] text-[var(--text-faint)] sm:table-cell">
<TableCell className="font-mono text-[var(--accent)]">
{event.clientId}
</TableCell>
<TableCell className="hidden font-mono text-[var(--text-faint)] sm:table-cell">
{event.eventId}
</TableCell>
<TableCell className="max-w-0 truncate font-mono text-[11px] text-[var(--text)]">
<TableCell className="max-w-0 truncate font-mono text-[var(--text)]">
{event.payload}
</TableCell>
<TableCell className="hidden font-mono text-[10.5px] tabular-nums md:table-cell">
<TableCell className="hidden font-mono tabular-nums md:table-cell">
{new TextEncoder().encode(event.payload).length} B
</TableCell>
<TableCell className="text-right">
<span className="inline-flex items-center gap-1.5 text-[10.5px] text-[var(--text-muted)]">
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />{event.status}
<span className="inline-flex items-center gap-1.5 text-[var(--text-muted)]">
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />
{event.status}
</span>
</TableCell>
</TableRow>
@@ -270,7 +271,7 @@ export function DataBrowser() {
</TableBody>
</Table>
</TableWrap>
<footer className="flex flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] px-3 py-2">
<footer className="flex flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] bg-[var(--surface-2)] px-3 py-2">
<p className="font-mono text-[11px] tabular-nums text-[var(--text-muted)]">
{firstVisible}–{lastVisible} of {total.toLocaleString()}
</p>
@@ -337,6 +338,6 @@ export function DataBrowser() {
</nav>
</footer>
</Panel>
</section>
</PageShell>
);
}
+199 -62
View File
@@ -1,6 +1,6 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { PageShell } from '@/components/layout/PageShell';
import { Button } from '@/components/ui/Button';
import { Input, Select } from '@/components/ui/Input';
import { Panel } from '@/components/ui/Panel';
@@ -50,14 +50,20 @@ function relativeTime(value: string, now: number) {
export function ExportWorkspace() {
const { error, info } = useToast();
const [clients, setClients] = useState<Client[]>(() => getCached<Client[]>('vcon:clients', []));
const [files, setFiles] = useState<StorageFile[]>(() => getCached<StorageFile[]>('vcon:storage-files', []));
const [clients, setClients] = useState<Client[]>(() =>
getCached<Client[]>('vcon:clients', [])
);
const [files, setFiles] = useState<StorageFile[]>(() =>
getCached<StorageFile[]>('vcon:storage-files', [])
);
const [selectedClient, setSelectedClient] = useState('all');
const [fromDate, setFromDate] = useState(() => dateString(new Date()));
const [toDate, setToDate] = useState(() => dateString(new Date()));
const [format, setFormat] = useState<ExportFormat>('csv');
const [preset, setPreset] = useState<RangePreset>('today');
const [loading, setLoading] = useState(() => getCached<StorageFile[]>('vcon:storage-files', []).length === 0);
const [loading, setLoading] = useState(
() => getCached<StorageFile[]>('vcon:storage-files', []).length === 0
);
const [loadError, setLoadError] = useState('');
const [now, setNow] = useState(() => Date.now());
@@ -79,7 +85,9 @@ export function ExportWorkspace() {
setLoadError('');
})
.catch((fetchError) => {
setLoadError(fetchError instanceof Error ? fetchError.message : 'Unable to load export data');
setLoadError(
fetchError instanceof Error ? fetchError.message : 'Unable to load export data'
);
})
.finally(() => setLoading(false));
}, []);
@@ -91,27 +99,45 @@ export function ExportWorkspace() {
return () => clearInterval(interval);
}, []);
const filteredFiles = useMemo(() => files.filter((file) =>
(selectedClient === 'all' || file.clientId === selectedClient) &&
(!fromDate || file.date >= fromDate) &&
(!toDate || file.date <= toDate)
), [files, fromDate, selectedClient, toDate]);
const filteredFiles = useMemo(
() =>
files.filter(
(file) =>
(selectedClient === 'all' || file.clientId === selectedClient) &&
(!fromDate || file.date >= fromDate) &&
(!toDate || file.date <= toDate)
),
[files, fromDate, selectedClient, toDate]
);
const preview = useMemo(() => ({
rows: filteredFiles.reduce((total, file) => total + file.linesCount, 0),
bytes: filteredFiles.reduce((total, file) => total + file.sizeBytes, 0),
files: filteredFiles.length,
}), [filteredFiles]);
const preview = useMemo(
() => ({
rows: filteredFiles.reduce((total, file) => total + file.linesCount, 0),
bytes: filteredFiles.reduce((total, file) => total + file.sizeBytes, 0),
files: filteredFiles.length,
}),
[filteredFiles]
);
const stats = useMemo(() => ({
rows: files.reduce((total, file) => total + file.linesCount, 0),
bytes: files.reduce((total, file) => total + file.sizeBytes, 0),
clients: new Set(files.map((file) => file.clientId)).size,
}), [files]);
const stats = useMemo(
() => ({
rows: files.reduce((total, file) => total + file.linesCount, 0),
bytes: files.reduce((total, file) => total + file.sizeBytes, 0),
clients: new Set(files.map((file) => file.clientId)).size,
}),
[files]
);
const sortedRecentFiles = useMemo(() => [...files]
.sort((left, right) => new Date(right.modifiedAt).getTime() - new Date(left.modifiedAt).getTime())
.slice(0, 6), [files]);
const sortedRecentFiles = useMemo(
() =>
[...files]
.sort(
(left, right) =>
new Date(right.modifiedAt).getTime() - new Date(left.modifiedAt).getTime()
)
.slice(0, 6),
[files]
);
const setQuickRange = (nextPreset: Exclude<RangePreset, 'custom'>) => {
setPreset(nextPreset);
@@ -142,7 +168,10 @@ export function ExportWorkspace() {
return;
}
window.location.assign(exportUrl);
info('Export started', `${format.toUpperCase()} download for ${preview.rows.toLocaleString()} rows.`);
info(
'Export started',
`${format.toUpperCase()} download for ${preview.rows.toLocaleString()} rows.`
);
};
const downloadFile = (file: StorageFile) => {
@@ -163,9 +192,7 @@ export function ExportWorkspace() {
};
return (
<section className="w-full">
<AdminPageHeader title="Export" />
<PageShell title="Export">
<StatStrip
items={[
{ label: 'Files', value: files.length.toLocaleString() },
@@ -175,17 +202,27 @@ export function ExportWorkspace() {
]}
/>
<div className="grid grid-cols-1 items-start gap-2.5 lg:grid-cols-5">
<Panel title="Export builder" bodyClassName="flex flex-col gap-3 p-3" className="min-w-0 lg:col-span-3">
<div className="grid grid-cols-1 items-start gap-3 lg:grid-cols-5">
<Panel
title="Export builder"
bodyClassName="flex flex-col gap-3 p-3"
className="min-w-0 lg:col-span-3"
>
<div className="flex flex-wrap items-center gap-1">
<span className="mr-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Range</span>
{([
['today', 'Today'],
['7d', '7d'],
['30d', '30d'],
['all', 'All'],
] as const).map(([id, label]) => (
<Pill key={id} active={preset === id} onClick={() => setQuickRange(id)}>{label}</Pill>
<span className="mr-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
Range
</span>
{(
[
['today', 'Today'],
['7d', '7d'],
['30d', '30d'],
['all', 'All'],
] as const
).map(([id, label]) => (
<Pill key={id} active={preset === id} onClick={() => setQuickRange(id)}>
{label}
</Pill>
))}
</div>
@@ -198,41 +235,102 @@ export function ExportWorkspace() {
onChange={(event) => setSelectedClient(event.target.value)}
>
<option value="all">All clients</option>
{clients.map((client) => <option key={client.clientId} value={client.clientId}>{client.name}</option>)}
{clients.map((client) => (
<option key={client.clientId} value={client.clientId}>
{client.name}
</option>
))}
</Select>
</div>
<div className="min-w-0 bg-[var(--surface)] p-2.5">
<Input label="From" compact type="date" value={fromDate} onChange={(event) => rangeChanged(setFromDate, event.target.value)} />
<Input
label="From"
compact
type="date"
value={fromDate}
onChange={(event) => rangeChanged(setFromDate, event.target.value)}
/>
</div>
<div className="min-w-0 bg-[var(--surface)] p-2.5">
<Input label="To" compact type="date" value={toDate} onChange={(event) => rangeChanged(setToDate, event.target.value)} />
<Input
label="To"
compact
type="date"
value={toDate}
onChange={(event) => rangeChanged(setToDate, event.target.value)}
/>
</div>
</div>
<fieldset className="flex flex-col gap-1.5">
<legend className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Format</legend>
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Export format">
<FormatOption value="csv" selected={format === 'csv'} label="CSV" onSelect={setFormat} />
<FormatOption value="json" selected={format === 'json'} label="JSON" onSelect={setFormat} />
<legend className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
Format
</legend>
<div
className="grid grid-cols-2 gap-2"
role="radiogroup"
aria-label="Export format"
>
<FormatOption
value="csv"
selected={format === 'csv'}
label="CSV"
onSelect={setFormat}
/>
<FormatOption
value="json"
selected={format === 'json'}
label="JSON"
onSelect={setFormat}
/>
</div>
</fieldset>
<div className="flex flex-col gap-1.5">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 border border-[var(--border)] bg-[var(--surface-2)] px-2.5 py-1.5 font-mono text-[11px] tabular-nums text-[var(--text-muted)]">
<span><strong className="font-medium text-[var(--text)]">{preview.rows.toLocaleString()}</strong> rows</span>
<span>
<strong className="font-medium text-[var(--text)]">
{preview.rows.toLocaleString()}
</strong>{' '}
rows
</span>
<span aria-hidden="true">·</span>
<span><strong className="font-medium text-[var(--text)]">~{formatBytes(preview.bytes)}</strong></span>
<span>
<strong className="font-medium text-[var(--text)]">
~{formatBytes(preview.bytes)}
</strong>
</span>
<span aria-hidden="true">·</span>
<span><strong className="font-medium text-[var(--text)]">{preview.files}</strong> files</span>
<span>
<strong className="font-medium text-[var(--text)]">
{preview.files}
</strong>{' '}
files
</span>
</div>
{loadError && <p role="alert" className="text-[11px] text-[var(--text-muted)]">{loadError}</p>}
{loadError && (
<p role="alert" className="text-[11px] text-[var(--text-muted)]">
{loadError}
</p>
)}
{fromDate && toDate && fromDate > toDate && (
<p role="alert" className="text-[11px] text-[var(--text-muted)]">Start date must be on or before end date.</p>
<p role="alert" className="text-[11px] text-[var(--text-muted)]">
Start date must be on or before end date.
</p>
)}
</div>
<div className="flex flex-wrap items-center justify-end gap-1.5 border-t border-[var(--border)] pt-2.5">
<Button type="button" size="xs" onClick={resetExport}>Reset</Button>
<Button type="button" variant="primary" size="xs" icon="Download" disabled={loading || Boolean(fromDate && toDate && fromDate > toDate)} onClick={downloadExport}>
<Button type="button" size="xs" onClick={resetExport}>
Reset
</Button>
<Button
type="button"
variant="primary"
size="xs"
icon="Download"
disabled={loading || Boolean(fromDate && toDate && fromDate > toDate)}
onClick={downloadExport}
>
Download {format.toUpperCase()}
</Button>
</div>
@@ -240,31 +338,60 @@ export function ExportWorkspace() {
<Panel
title="Files"
action={<Link href="/vcon/storage" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all</Link>}
action={
<Link
href="/vcon/storage"
className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]"
>
View all
</Link>
}
bodyClassName="divide-y divide-[var(--border)]"
className="min-w-0 lg:col-span-2"
>
{loading ? (
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">Loading...</p>
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">
Loading...
</p>
) : sortedRecentFiles.length === 0 ? (
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">No files</p>
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">
No files
</p>
) : (
sortedRecentFiles.map((file) => (
<div key={`${file.clientId}/${file.filename}`} className="flex items-center gap-2 px-3 py-2 transition-colors hover:bg-[var(--surface-2)]">
<span className="shrink-0 border border-[var(--border-strong)] px-1 py-0.5 font-mono text-[9px] uppercase tracking-wider text-[var(--text-muted)]">CSV</span>
<div
key={`${file.clientId}/${file.filename}`}
className="flex items-center gap-2 px-3 py-2 transition-colors hover:bg-[var(--surface-2)]"
>
<span className="shrink-0 border border-[var(--border-strong)] px-1 py-0.5 font-mono text-[9px] uppercase tracking-wider text-[var(--text-muted)]">
CSV
</span>
<div className="min-w-0 flex-1">
<div className="truncate font-mono text-[11.5px] text-[var(--text)]">{file.filename}</div>
<div className="truncate font-mono text-[11.5px] text-[var(--text)]">
{file.filename}
</div>
<div className="truncate text-[10px] tabular-nums text-[var(--text-faint)]">
{file.clientId} · {relativeTime(file.modifiedAt, now)} · {file.linesCount.toLocaleString()} rows · {formatBytes(file.sizeBytes)}
{file.clientId} · {relativeTime(file.modifiedAt, now)} ·{' '}
{file.linesCount.toLocaleString()} rows ·{' '}
{formatBytes(file.sizeBytes)}
</div>
</div>
<Button type="button" variant="icon" size="icon" icon="Download" className="h-6 w-6 shrink-0" aria-label={`Download ${file.filename}`} title={`Download ${file.filename}`} onClick={() => downloadFile(file)} />
<Button
type="button"
variant="icon"
size="icon"
icon="Download"
className="h-6 w-6 shrink-0"
aria-label={`Download ${file.filename}`}
title={`Download ${file.filename}`}
onClick={() => downloadFile(file)}
/>
</div>
))
)}
</Panel>
</div>
</section>
</PageShell>
);
}
@@ -286,10 +413,20 @@ function FormatOption({
type="button"
role="radio"
aria-checked={selected}
className={`flex min-w-0 items-center gap-2 border px-2.5 py-1.5 text-left transition-colors ${selected ? 'border-[var(--border-strong)] bg-[var(--surface-2)]' : 'border-[var(--border)] hover:border-[var(--border-strong)]'}`}
className={`flex min-w-0 items-center gap-2 border px-2.5 py-1.5 text-left transition-colors ${
selected
? 'border-[var(--border-strong)] bg-[var(--surface-2)]'
: 'border-[var(--border)] hover:border-[var(--border-strong)]'
}`}
onClick={() => onSelect(value)}
>
<span className={`grid h-6 w-6 shrink-0 place-items-center border ${selected ? 'border-[var(--border-strong)] text-[var(--accent)]' : 'border-[var(--border)] text-[var(--text-muted)]'}`}>
<span
className={`grid h-6 w-6 shrink-0 place-items-center border ${
selected
? 'border-[var(--border-strong)] text-[var(--accent)]'
: 'border-[var(--border)] text-[var(--text-muted)]'
}`}
>
<FormatIcon className="h-3 w-3" aria-hidden="true" />
</span>
<span className="text-[11.5px] font-medium text-[var(--text)]">{label}</span>
+114 -91
View File
@@ -1,9 +1,14 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { PageShell } from '@/components/layout/PageShell';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { SettingsField, SettingsGroup } from '@/components/ui/SettingsLayout';
import {
SettingsField,
SettingsFooter,
SettingsGroup,
SettingsPanel,
} from '@/components/ui/SettingsLayout';
import { StatStrip } from '@/components/ui/StatStrip';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
@@ -28,12 +33,18 @@ const DEFAULT_PROFILE: AdminProfileData = {
export function ProfileWorkspace() {
const { success, error } = useToast();
const [profile, setProfile] = useState<AdminProfileData>(() => getCached<AdminProfileData>('vcon:profile', DEFAULT_PROFILE));
const [email, setEmail] = useState(() => getCached<AdminProfileData>('vcon:profile', DEFAULT_PROFILE).email);
const [profile, setProfile] = useState<AdminProfileData>(() =>
getCached<AdminProfileData>('vcon:profile', DEFAULT_PROFILE)
);
const [email, setEmail] = useState(
() => getCached<AdminProfileData>('vcon:profile', DEFAULT_PROFILE).email
);
const [currentPassword, setCurrentPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [loading, setLoading] = useState(() => !getCached<boolean>('vcon:profile-loaded', false));
const [loading, setLoading] = useState(
() => !getCached<boolean>('vcon:profile-loaded', false)
);
const [saving, setSaving] = useState(false);
const [signingOut, setSigningOut] = useState(false);
@@ -93,7 +104,12 @@ export function ProfileWorkspace() {
setConfirmPassword('');
success('Profile updated', 'Administrator credentials updated.');
} catch (saveError) {
error('Update failed', saveError instanceof Error ? saveError.message : 'Unable to update profile');
error(
'Update failed',
saveError instanceof Error
? saveError.message
: 'Unable to update profile'
);
} finally {
setSaving(false);
}
@@ -115,30 +131,28 @@ export function ProfileWorkspace() {
};
return (
<section className="w-full">
<AdminPageHeader
title="Profile"
actions={
<>
<Link href="/vcon/settings">
<Button type="button" size="xs" variant="secondary" icon="Sliders">
Settings
</Button>
</Link>
<Button
type="button"
size="xs"
variant="danger"
icon="LogOut"
loading={signingOut}
onClick={handleSignOut}
>
Sign out
<PageShell
title="Profile"
actions={
<>
<Link href="/vcon/settings">
<Button type="button" size="xs" variant="secondary" icon="Sliders">
Settings
</Button>
</>
}
/>
</Link>
<Button
type="button"
size="xs"
variant="danger"
icon="LogOut"
loading={signingOut}
onClick={handleSignOut}
>
Sign out
</Button>
</>
}
>
<StatStrip
items={[
{ label: 'Administrator', value: profile.email },
@@ -147,72 +161,81 @@ export function ProfileWorkspace() {
{
label: 'Session Expires',
value: profile.sessionExpiresAt
? new Date(profile.sessionExpiresAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
? new Date(profile.sessionExpiresAt).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
hour12: false,
})
: 'Active',
},
]}
/>
<form onSubmit={handleSave} className="max-w-[780px] border border-[var(--border)] bg-[var(--surface)]">
<SettingsGroup title="Account identity">
<SettingsField label="Admin email">
<Input
compact
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
required
/>
</SettingsField>
<SettingsField label="Access role">
<Input
compact
value={profile.role}
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]"
/>
</SettingsField>
</SettingsGroup>
<form onSubmit={handleSave} className="w-full">
<SettingsPanel>
<SettingsGroup title="Account identity">
<SettingsField label="Admin email">
<Input
compact
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
required
/>
</SettingsField>
<SettingsField label="Access role">
<Input
compact
value={profile.role}
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]"
/>
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Security & password">
<SettingsField label="Current password">
<Input
compact
type="password"
autoComplete="current-password"
placeholder="Required to confirm changes"
value={currentPassword}
onChange={(event) => setCurrentPassword(event.target.value)}
required
/>
</SettingsField>
<SettingsField label="New password">
<Input
compact
type="password"
autoComplete="new-password"
placeholder="Leave blank to keep current"
value={newPassword}
onChange={(event) => setNewPassword(event.target.value)}
/>
</SettingsField>
<SettingsField label="Confirm new password">
<Input
compact
type="password"
autoComplete="new-password"
placeholder="Repeat new password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
/>
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Security & password">
<SettingsField label="Current password">
<Input
compact
type="password"
autoComplete="current-password"
placeholder="Required to confirm changes"
value={currentPassword}
onChange={(event) => setCurrentPassword(event.target.value)}
required
/>
</SettingsField>
<SettingsField label="New password">
<Input
compact
type="password"
autoComplete="new-password"
placeholder="Leave blank to keep current"
value={newPassword}
onChange={(event) => setNewPassword(event.target.value)}
/>
</SettingsField>
<SettingsField label="Confirm new password">
<Input
compact
type="password"
autoComplete="new-password"
placeholder="Repeat new password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
/>
</SettingsField>
</SettingsGroup>
<footer className="flex flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] bg-[var(--surface)] px-3 py-2">
<span className="text-[11px] text-[var(--text-muted)]">
{loading ? 'Loading profile...' : 'Confirm current password to update credentials'}
</span>
<div className="flex items-center gap-2">
<SettingsFooter
status={
<span>
{loading
? 'Loading profile...'
: 'Confirm current password to update credentials'}
</span>
}
>
<Button
type="button"
size="xs"
@@ -236,9 +259,9 @@ export function ProfileWorkspace() {
>
Update profile
</Button>
</div>
</footer>
</SettingsFooter>
</SettingsPanel>
</form>
</section>
</PageShell>
);
}
+337 -113
View File
@@ -1,10 +1,17 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { PageShell } from '@/components/layout/PageShell';
import { Button } from '@/components/ui/Button';
import { FormSwitch } from '@/components/ui/Form';
import { Input } from '@/components/ui/Input';
import { SettingsField, SettingsGroup, SettingsTabs } from '@/components/ui/SettingsLayout';
import {
SettingsField,
SettingsFooter,
SettingsGroup,
SettingsPanel,
SettingsTabs,
} from '@/components/ui/SettingsLayout';
import { StatStrip } from '@/components/ui/StatStrip';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import { useEffect, useMemo, useState } from 'react';
@@ -46,15 +53,25 @@ type TabId = (typeof TABS)[number]['id'];
export function SettingsWorkspace() {
const { success, error } = useToast();
const [settings, setSettings] = useState<EditableSettings>(() => getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS));
const [savedSettings, setSavedSettings] = useState<EditableSettings>(() => getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS));
const [settings, setSettings] = useState<EditableSettings>(() =>
getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS)
);
const [savedSettings, setSavedSettings] = useState<EditableSettings>(() =>
getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS)
);
const [activeTab, setActiveTab] = useState<TabId>('general');
const [jwtSecret, setJwtSecret] = useState('');
const [storagePath, setStoragePath] = useState(() => getCached<string>('vcon:storage-path', ''));
const [storagePath, setStoragePath] = useState(() =>
getCached<string>('vcon:storage-path', '')
);
const [baseUrl, setBaseUrl] = useState('');
const [webSocketUrl, setWebSocketUrl] = useState('');
const [serverPort, setServerPort] = useState(() => getCached<number>('vcon:server-port', 4000));
const [loading, setLoading] = useState(() => !getCached<boolean>('vcon:settings-loaded', false));
const [serverPort, setServerPort] = useState(() =>
getCached<number>('vcon:server-port', 4000)
);
const [loading, setLoading] = useState(
() => !getCached<boolean>('vcon:settings-loaded', false)
);
const [saving, setSaving] = useState(false);
useEffect(() => {
@@ -78,18 +95,49 @@ export function SettingsWorkspace() {
])
.then(([settingsData, storageData]) => {
const loaded: EditableSettings = {
maxEventsPerSec: Number(settingsData.settings.maxEventsPerSec ?? DEFAULT_SETTINGS.maxEventsPerSec),
maxPayloadSizeKb: Number(settingsData.settings.maxPayloadSizeKb ?? DEFAULT_SETTINGS.maxPayloadSizeKb),
batchFlushThreshold: Number(settingsData.settings.batchFlushThreshold ?? DEFAULT_SETTINGS.batchFlushThreshold),
batchFlushIntervalMs: Number(settingsData.settings.batchFlushIntervalMs ?? DEFAULT_SETTINGS.batchFlushIntervalMs),
fileRotationMb: Number(settingsData.settings.fileRotationMb ?? DEFAULT_SETTINGS.fileRotationMb),
enableIdempotency: Boolean(settingsData.settings.enableIdempotency ?? DEFAULT_SETTINGS.enableIdempotency),
autoPruneDays: Number(settingsData.settings.autoPruneDays ?? DEFAULT_SETTINGS.autoPruneDays),
maxEventsPerSec: Number(
settingsData.settings.maxEventsPerSec ??
DEFAULT_SETTINGS.maxEventsPerSec
),
maxPayloadSizeKb: Number(
settingsData.settings.maxPayloadSizeKb ??
DEFAULT_SETTINGS.maxPayloadSizeKb
),
batchFlushThreshold: Number(
settingsData.settings.batchFlushThreshold ??
DEFAULT_SETTINGS.batchFlushThreshold
),
batchFlushIntervalMs: Number(
settingsData.settings.batchFlushIntervalMs ??
DEFAULT_SETTINGS.batchFlushIntervalMs
),
fileRotationMb: Number(
settingsData.settings.fileRotationMb ??
DEFAULT_SETTINGS.fileRotationMb
),
enableIdempotency: Boolean(
settingsData.settings.enableIdempotency ??
DEFAULT_SETTINGS.enableIdempotency
),
autoPruneDays: Number(
settingsData.settings.autoPruneDays ??
DEFAULT_SETTINGS.autoPruneDays
),
};
setSettings(setCached('vcon:settings', loaded));
setSavedSettings(loaded);
setServerPort(setCached('vcon:server-port', Number((settingsData.settings as PublicSettings).serverPort ?? 4000)));
setStoragePath(setCached('vcon:storage-path', String(storageData.stats?.storageDirectory ?? '')));
setServerPort(
setCached(
'vcon:server-port',
Number((settingsData.settings as PublicSettings).serverPort ?? 4000)
)
);
setStoragePath(
setCached(
'vcon:storage-path',
String(storageData.stats?.storageDirectory ?? '')
)
);
setCached('vcon:settings-loaded', true);
})
.catch(() => {
@@ -99,7 +147,9 @@ export function SettingsWorkspace() {
}, [error]);
const isDirty = useMemo(
() => jwtSecret.trim().length > 0 || JSON.stringify(settings) !== JSON.stringify(savedSettings),
() =>
jwtSecret.trim().length > 0 ||
JSON.stringify(settings) !== JSON.stringify(savedSettings),
[jwtSecret, savedSettings, settings]
);
@@ -110,13 +160,37 @@ export function SettingsWorkspace() {
const saveSettings = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const normalized: EditableSettings = {
maxEventsPerSec: Math.max(1, Math.min(10000, settings.maxEventsPerSec || DEFAULT_SETTINGS.maxEventsPerSec)),
maxPayloadSizeKb: Math.max(1, Math.min(5120, settings.maxPayloadSizeKb || DEFAULT_SETTINGS.maxPayloadSizeKb)),
batchFlushThreshold: Math.max(1, settings.batchFlushThreshold || DEFAULT_SETTINGS.batchFlushThreshold),
batchFlushIntervalMs: Math.max(100, settings.batchFlushIntervalMs || DEFAULT_SETTINGS.batchFlushIntervalMs),
fileRotationMb: Math.max(1, settings.fileRotationMb || DEFAULT_SETTINGS.fileRotationMb),
maxEventsPerSec: Math.max(
1,
Math.min(
10000,
settings.maxEventsPerSec || DEFAULT_SETTINGS.maxEventsPerSec
)
),
maxPayloadSizeKb: Math.max(
1,
Math.min(
5120,
settings.maxPayloadSizeKb || DEFAULT_SETTINGS.maxPayloadSizeKb
)
),
batchFlushThreshold: Math.max(
1,
settings.batchFlushThreshold || DEFAULT_SETTINGS.batchFlushThreshold
),
batchFlushIntervalMs: Math.max(
100,
settings.batchFlushIntervalMs || DEFAULT_SETTINGS.batchFlushIntervalMs
),
fileRotationMb: Math.max(
1,
settings.fileRotationMb || DEFAULT_SETTINGS.fileRotationMb
),
enableIdempotency: settings.enableIdempotency,
autoPruneDays: Math.max(1, Math.min(365, settings.autoPruneDays || DEFAULT_SETTINGS.autoPruneDays)),
autoPruneDays: Math.max(
1,
Math.min(365, settings.autoPruneDays || DEFAULT_SETTINGS.autoPruneDays)
),
};
setSaving(true);
try {
@@ -135,7 +209,12 @@ export function SettingsWorkspace() {
setJwtSecret('');
success('Settings saved', 'Runtime settings updated.');
} catch (saveError) {
error('Save failed', saveError instanceof Error ? saveError.message : 'Unable to save settings');
error(
'Save failed',
saveError instanceof Error
? saveError.message
: 'Unable to save settings'
);
} finally {
setSaving(false);
}
@@ -147,106 +226,251 @@ export function SettingsWorkspace() {
};
return (
<section className="w-full">
<AdminPageHeader title="Settings" />
<PageShell title="Settings">
<StatStrip
items={[
{ label: 'Instance', value: 'DataStack', dot: 'ok' },
{ label: 'Rate limit', value: `${settings.maxEventsPerSec} / sec` },
{
label: 'Batch flush',
value: `${settings.batchFlushThreshold} / ${settings.batchFlushIntervalMs}ms`,
},
{
label: 'CSV rotation',
value: `${settings.fileRotationMb}MB · ${settings.autoPruneDays}d`,
},
]}
/>
<div className="max-w-[780px]">
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
<div className="w-full">
<SettingsTabs
items={TABS}
value={activeTab}
onChange={(tab) => setActiveTab(tab as TabId)}
/>
<form onSubmit={saveSettings}>
<div
<form onSubmit={saveSettings} className="w-full">
<SettingsPanel
id={`settings-panel-${activeTab}`}
role="tabpanel"
aria-labelledby={`settings-tab-${activeTab}`}
className="border border-t-0 border-[var(--border)] bg-[var(--surface)]"
>
<>
{activeTab === 'general' && (
<>
<SettingsGroup title="Identity">
<SettingsField label="Instance name">
<Input compact value="DataStack" readOnly className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="Base URL">
<Input compact value={baseUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]" />
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Throughput">
<SettingsField label="Events per second">
<Input compact type="number" min="1" max="10000" value={settings.maxEventsPerSec} onChange={(event) => updateNumber('maxEventsPerSec', event.target.value)} />
</SettingsField>
<SettingsField label="Idempotency">
<FormSwitch label="Deduplicate events" checked={settings.enableIdempotency} onChange={(enableIdempotency) => setSettings((current) => ({ ...current, enableIdempotency }))} />
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'connections' && (
<>
<SettingsGroup title="WebSocket server">
<SettingsField label="WebSocket URL">
<Input compact value={webSocketUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="Socket port">
<Input compact type="number" value={serverPort} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[var(--text-muted)]" />
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Event buffer">
<SettingsField label="Batch flush threshold">
<Input compact type="number" min="1" value={settings.batchFlushThreshold} onChange={(event) => updateNumber('batchFlushThreshold', event.target.value)} />
</SettingsField>
<SettingsField label="Flush interval">
<Input compact type="number" min="100" suffix="ms" value={settings.batchFlushIntervalMs} onChange={(event) => updateNumber('batchFlushIntervalMs', event.target.value)} className="font-mono" />
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'storage' && (
<>
<SettingsGroup title="CSV files">
<SettingsField label="Root path">
<Input compact value={storagePath || 'Unavailable'} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="File rotation">
<Input compact type="number" min="1" suffix="MB" value={settings.fileRotationMb} onChange={(event) => updateNumber('fileRotationMb', event.target.value)} className="font-mono" />
</SettingsField>
<SettingsField label="Retention">
<Input compact type="number" min="1" max="365" suffix="days" value={settings.autoPruneDays} onChange={(event) => updateNumber('autoPruneDays', event.target.value)} className="font-mono" />
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Schema">
<SettingsField label="Row format">
<Input compact value="clientId, eventId, timestamp, payload" readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]" />
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'security' && (
<SettingsGroup title="Authentication">
<SettingsField label="JWT secret">
<Input compact type="password" autoComplete="new-password" value={jwtSecret} onChange={(event) => setJwtSecret(event.target.value)} placeholder="New secret..." />
{activeTab === 'general' && (
<>
<SettingsGroup title="Identity">
<SettingsField label="Instance name">
<Input
compact
value="DataStack"
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]"
/>
</SettingsField>
<SettingsField label="Payload size limit">
<Input compact type="number" min="1" max="5120" suffix="KB" value={settings.maxPayloadSizeKb} onChange={(event) => updateNumber('maxPayloadSizeKb', event.target.value)} className="font-mono" />
<SettingsField label="Base URL">
<Input
compact
value={baseUrl}
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]"
/>
</SettingsField>
</SettingsGroup>
)}
</>
</div>
<SettingsGroup title="Throughput">
<SettingsField label="Events per second">
<Input
compact
type="number"
min="1"
max="10000"
value={settings.maxEventsPerSec}
onChange={(event) =>
updateNumber('maxEventsPerSec', event.target.value)
}
/>
</SettingsField>
<SettingsField label="Idempotency">
<FormSwitch
label="Deduplicate events"
checked={settings.enableIdempotency}
onChange={(enableIdempotency) =>
setSettings((current) => ({
...current,
enableIdempotency,
}))
}
/>
</SettingsField>
</SettingsGroup>
</>
)}
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-3 py-2">
<div className="flex flex-1 items-center gap-1.5 text-[11px] text-[var(--text-muted)]" role="status">
<span className={`h-1.5 w-1.5 ${isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'}`} />
{loading ? 'Loading' : isDirty ? 'Unsaved' : 'Saved'}
</div>
<Button type="button" size="xs" disabled={!isDirty || saving} onClick={discardChanges}>Discard</Button>
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save</Button>
</footer>
{activeTab === 'connections' && (
<>
<SettingsGroup title="WebSocket server">
<SettingsField label="WebSocket URL">
<Input
compact
value={webSocketUrl}
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]"
/>
</SettingsField>
<SettingsField label="Socket port">
<Input
compact
type="number"
value={serverPort}
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[var(--text-muted)]"
/>
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Event buffer">
<SettingsField label="Batch flush threshold">
<Input
compact
type="number"
min="1"
value={settings.batchFlushThreshold}
onChange={(event) =>
updateNumber('batchFlushThreshold', event.target.value)
}
/>
</SettingsField>
<SettingsField label="Flush interval">
<Input
compact
type="number"
min="100"
suffix="ms"
value={settings.batchFlushIntervalMs}
onChange={(event) =>
updateNumber('batchFlushIntervalMs', event.target.value)
}
className="font-mono"
/>
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'storage' && (
<>
<SettingsGroup title="CSV files">
<SettingsField label="Root path">
<Input
compact
value={storagePath || 'Unavailable'}
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]"
/>
</SettingsField>
<SettingsField label="File rotation">
<Input
compact
type="number"
min="1"
suffix="MB"
value={settings.fileRotationMb}
onChange={(event) =>
updateNumber('fileRotationMb', event.target.value)
}
className="font-mono"
/>
</SettingsField>
<SettingsField label="Retention">
<Input
compact
type="number"
min="1"
max="365"
suffix="days"
value={settings.autoPruneDays}
onChange={(event) =>
updateNumber('autoPruneDays', event.target.value)
}
className="font-mono"
/>
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Schema">
<SettingsField label="Row format">
<Input
compact
value="clientId, eventId, timestamp, payload"
readOnly
className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]"
/>
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'security' && (
<SettingsGroup title="Authentication">
<SettingsField label="JWT secret">
<Input
compact
type="password"
autoComplete="new-password"
value={jwtSecret}
onChange={(event) => setJwtSecret(event.target.value)}
placeholder="New secret..."
/>
</SettingsField>
<SettingsField label="Payload size limit">
<Input
compact
type="number"
min="1"
max="5120"
suffix="KB"
value={settings.maxPayloadSizeKb}
onChange={(event) =>
updateNumber('maxPayloadSizeKb', event.target.value)
}
className="font-mono"
/>
</SettingsField>
</SettingsGroup>
)}
<SettingsFooter
status={
<>
<span
className={`h-1.5 w-1.5 ${
isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'
}`}
/>
<span>
{loading ? 'Loading' : isDirty ? 'Unsaved changes' : 'Saved'}
</span>
</>
}
>
<Button
type="button"
size="xs"
disabled={!isDirty || saving}
onClick={discardChanges}
>
Discard
</Button>
<Button
type="submit"
variant="primary"
size="xs"
icon="Save"
loading={saving}
disabled={loading || !isDirty}
>
Save
</Button>
</SettingsFooter>
</SettingsPanel>
</form>
</div>
</section>
</PageShell>
);
}
+45 -9
View File
@@ -1,3 +1,4 @@
import { cn } from '@/lib/utils';
import React from 'react';
export interface SettingsTabItem {
@@ -16,7 +17,7 @@ export function SettingsTabs({
}) {
return (
<div
className="flex overflow-x-auto overflow-y-hidden border-b border-[var(--border)] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
className="flex w-full overflow-x-auto overflow-y-hidden border border-b-0 border-[var(--border)] bg-[var(--surface-2)] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
role="tablist"
aria-label="Settings categories"
>
@@ -28,10 +29,10 @@ export function SettingsTabs({
role="tab"
aria-selected={value === item.id}
aria-controls={`settings-panel-${item.id}`}
className={`shrink-0 border-b-2 px-3 py-1.5 text-[11.5px] transition-colors cursor-pointer whitespace-nowrap ${
className={`shrink-0 border-b-2 border-r border-r-[var(--border)] px-3.5 py-2 text-[11.5px] transition-colors cursor-pointer whitespace-nowrap ${
value === item.id
? 'border-[var(--accent)] text-[var(--text)] font-medium'
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'
? 'border-b-[var(--accent)] bg-[var(--surface)] text-[var(--text)] font-medium'
: 'border-b-transparent text-[var(--text-muted)] hover:bg-[var(--surface)] hover:text-[var(--text)]'
}`}
onClick={() => onChange(item.id)}
>
@@ -42,6 +43,24 @@ export function SettingsTabs({
);
}
export function SettingsPanel({
children,
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn(
'w-full border border-[var(--border)] bg-[var(--surface)]',
className
)}
{...props}
>
{children}
</div>
);
}
export function SettingsGroup({
title,
children,
@@ -50,11 +69,11 @@ export function SettingsGroup({
children: React.ReactNode;
}) {
return (
<section className="border-b border-[var(--border)] p-3 last:border-b-0">
<h2 className="mb-2 flex items-center gap-1.5 text-[9.5px] uppercase tracking-wider text-[var(--text-faint)]">
<section className="border-b border-[var(--border)] p-3.5 last:border-b-0">
<h2 className="mb-2.5 flex items-center gap-1.5 text-[9.5px] font-medium uppercase tracking-wider text-[var(--text-faint)]">
{title}
</h2>
<div className="flex flex-col gap-1">{children}</div>
<div className="flex flex-col gap-1.5">{children}</div>
</section>
);
}
@@ -67,11 +86,28 @@ export function SettingsField({
children: React.ReactNode;
}) {
return (
<div className="grid grid-cols-1 items-center gap-1.5 py-1.5 sm:grid-cols-[180px_minmax(0,380px)] sm:justify-between sm:gap-4">
<div className="grid grid-cols-1 items-center gap-1.5 py-1 sm:grid-cols-[220px_minmax(0,520px)] sm:justify-start sm:gap-6">
<div className="min-w-0">
<div className="text-[11.5px] leading-snug text-[var(--text)]">{label}</div>
</div>
<div className="min-w-0">{children}</div>
<div className="min-w-0 w-full">{children}</div>
</div>
);
}
export function SettingsFooter({
status,
children,
}: {
status?: React.ReactNode;
children: React.ReactNode;
}) {
return (
<footer className="flex w-full flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] bg-[var(--surface-2)] px-3.5 py-2">
<div className="flex items-center gap-1.5 text-[11px] text-[var(--text-muted)]" role="status">
{status}
</div>
<div className="flex items-center gap-1.5">{children}</div>
</footer>
);
}
+13 -7
View File
@@ -1,3 +1,4 @@
import { cn } from '@/lib/utils';
import type { ReactNode } from 'react';
type Dot = 'ok' | 'off' | 'pending';
@@ -9,17 +10,22 @@ const DOT_CLASS: Record<Dot, string> = {
pending: 'bg-[var(--warning)]',
};
export function StatStrip({ items }: { items: Item[] }) {
export function StatStrip({ items, className }: { items: Item[]; className?: string }) {
return (
<div className="mb-3 grid grid-cols-2 gap-px border border-[var(--border)] bg-[var(--border)] md:grid-cols-4">
<div
className={cn(
'stat-strip mb-3 grid w-full grid-cols-2 gap-px border border-[var(--border)] bg-[var(--border)] md:grid-cols-4',
className
)}
>
{items.map((item) => (
<div key={item.label} className="bg-[var(--surface)] px-3 py-2">
<div className="mb-0.5 text-[9.5px] uppercase tracking-wider text-[var(--text-faint)]">
<div key={item.label} className="min-w-0 bg-[var(--surface)] px-3 py-2">
<div className="mb-0.5 truncate text-[9.5px] uppercase tracking-wider text-[var(--text-faint)]">
{item.label}
</div>
<div className="flex items-center gap-1.5 font-mono text-[15px] font-medium leading-tight tracking-tight tabular-nums text-[var(--text)]">
{item.dot && <span aria-hidden="true" className={`h-1.5 w-1.5 ${DOT_CLASS[item.dot]}`} />}
{item.value}
<div className="flex min-w-0 items-center gap-1.5 font-mono text-[15px] font-medium leading-tight tracking-tight tabular-nums text-[var(--text)]">
{item.dot && <span aria-hidden="true" className={`h-1.5 w-1.5 shrink-0 ${DOT_CLASS[item.dot]}`} />}
<span className="truncate">{item.value}</span>
</div>
</div>
))}
+4 -4
View File
@@ -8,7 +8,7 @@ export const TableWrap: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({
}) => (
<div
className={cn(
'w-full overflow-x-auto border border-[var(--border)] bg-[var(--bg-elevated)]',
'w-full overflow-x-auto border border-[var(--border)] bg-[var(--surface)]',
className
)}
{...props}
@@ -40,7 +40,7 @@ export const TableHeader: React.FC<React.HTMLAttributes<HTMLTableSectionElement>
}) => (
<thead
className={cn(
'bg-[var(--bg-sidebar)] border-b border-[var(--border)] text-[10px] font-medium tracking-wider text-[var(--text-muted)] uppercase',
'border-b border-[var(--border)] bg-[var(--surface-2)] text-[10px] font-medium uppercase tracking-wider text-[var(--text-muted)]',
className
)}
{...props}
@@ -62,7 +62,7 @@ export const TableRow: React.FC<React.HTMLAttributes<HTMLTableRowElement>> = ({
}) => (
<tr
className={cn(
'transition-colors hover:bg-[var(--bg-hover)] text-[var(--text)]',
'text-[var(--text)] transition-colors hover:bg-[var(--bg-hover)]',
className
)}
{...props}
@@ -86,7 +86,7 @@ export const TableCell: React.FC<React.TdHTMLAttributes<HTMLTableCellElement>> =
children,
...props
}) => (
<td className={cn('px-3 py-1.5 text-[var(--text-muted)] align-middle', className)} {...props}>
<td className={cn('px-3 py-1.5 align-middle text-[var(--text-muted)]', className)} {...props}>
{children}
</td>
);