chore: publish current DataStack updates

Publish the current application, design, and Phase 1 deployment updates. Excludes ignored personal notes, local MCP config, and generated TypeScript build info.
This commit is contained in:
i vib committed 2026-10-23 19:56:38 -07:00
1 parent d39d9f92f9
commit fcc4f4db2d
88 files changed
+21248 -2213

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
import React from 'react';
interface AdminPageHeaderProps {
title: string;
subtitle?: string;
actions?: React.ReactNode;
}
export function AdminPageHeader({ title, subtitle, actions }: AdminPageHeaderProps) {
return (
<header className="mb-4 flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-base font-medium tracking-tight text-[var(--text)]">{title}</h1>
{subtitle && <p className="mt-0.5 text-xs text-[var(--text-muted)]">{subtitle}</p>}
</div>
{actions && <div className="flex items-center gap-2">{actions}</div>}
</header>
);
}
+38 -20
View File
@@ -1,26 +1,44 @@
import Link from 'next/link';
import React from 'react';
export const Footer: React.FC = () => {
interface FooterProps {
isAdmin?: boolean;
}
export const Footer: React.FC<FooterProps> = ({ isAdmin = false }) => {
return (
<footer className="shrink-0 h-[26px] bg-[var(--bg-activity)] border-t border-[var(--border)] px-3 sm:px-4 flex items-center justify-between text-[10px] text-[var(--text-dim)] select-none">
<div className="flex items-center gap-1.5 truncate min-w-0 pr-2">
<span className="font-semibold text-[var(--text-muted)] tracking-tight">DataStack</span>
<span className="text-[var(--border-strong)]">/</span>
<span className="font-mono text-[9px] truncate">
storage/data/&#123;clientId&#125;/&#123;YYYY-MM-DD&#125;.csv
</span>
</div>
<div className="flex items-center gap-2 font-mono text-[9.5px] shrink-0 ml-auto">
<span className="flex items-center gap-1">
<span className="w-1.5 h-1.5 bg-[var(--success)] inline-block" />
<span className="text-[var(--text-muted)]">:4000</span>
</span>
<span className="text-[var(--border-strong)]">•</span>
<span className="flex items-center gap-1">
<span className="w-1.5 h-1.5 bg-[var(--accent)] inline-block" />
<span className="text-[var(--text-muted)]">:3000</span>
</span>
</div>
<footer className="shrink-0 min-h-10 bg-[var(--bg-activity)] border-t border-[var(--border)] px-4 sm:px-6 py-2 flex flex-wrap items-center justify-between gap-2 text-[11px] text-[var(--text-dim)] select-none">
{isAdmin ? (
<>
<div className="flex items-center gap-1.5 truncate min-w-0 pr-2">
<span className="font-semibold text-[var(--text-muted)] tracking-tight">DataStack</span>
<span className="text-[var(--border-strong)]">/</span>
<span className="hidden sm:inline font-mono text-[10px] truncate">
storage/data/&#123;clientId&#125;/&#123;YYYY-MM-DD&#125;.csv
</span>
</div>
<div className="flex items-center gap-2 font-mono text-[10.5px] shrink-0 ml-auto">
<span className="flex items-center gap-1">
<span className="w-1.5 h-1.5 bg-[var(--success)] inline-block" />
<span className="text-[var(--text-muted)]">:4000</span>
</span>
<span className="text-[var(--border-strong)]">|</span>
<span className="flex items-center gap-1">
<span className="w-1.5 h-1.5 bg-[var(--accent)] inline-block" />
<span className="text-[var(--text-muted)]">:3000</span>
</span>
</div>
</>
) : (
<>
<span>DataStack · Self-hosted</span>
<nav aria-label="Footer navigation" className="flex items-center gap-5">
<Link href="#features" className="hover:text-[var(--text-muted)]">Features</Link>
<Link href="#sdk" className="hover:text-[var(--text-muted)]">SDK</Link>
<Link href="#about" className="hover:text-[var(--text-muted)]">About</Link>
</nav>
</>
)}
</footer>
);
};
+12 -6
View File
@@ -1,9 +1,10 @@
'use client';
import { cn } from '@/lib/utils';
import React, { useState } from 'react';
import { Footer } from './Footer';
import { Navbar } from './Navbar';
import { Sidebar } from './Sidebar';
import { Footer } from './Footer';
interface MainLayoutProps {
children: React.ReactNode;
@@ -17,24 +18,29 @@ export const MainLayout: React.FC<MainLayoutProps> = ({
const [sidebarOpen, setSidebarOpen] = useState(false);
return (
<div className="min-h-screen flex flex-col bg-[var(--bg-main)] text-[var(--text)] antialiased">
<div className="min-h-dvh flex flex-col bg-[var(--bg-main)] text-[var(--text)] antialiased">
<Navbar
showSidebarToggle={showSidebar}
onToggleSidebar={() => setSidebarOpen((prev) => !prev)}
/>
<div className="flex-1 flex min-h-0 overflow-hidden">
<div className="flex-1 flex min-h-0 min-w-0 overflow-hidden">
{showSidebar && (
<Sidebar
isOpen={sidebarOpen}
onClose={() => setSidebarOpen(false)}
/>
)}
<main className="flex-1 overflow-y-auto flex flex-col min-w-0">
<div className="flex-1 p-2 sm:p-3.5 max-w-[1360px] w-full mx-auto">
<main className="flex-1 min-h-0 overflow-y-auto flex flex-col min-w-0">
<div className={cn(
'flex-1 min-w-0 w-full mx-auto',
showSidebar
? 'max-w-[1600px] px-4 py-4 sm:px-6 sm:py-6 xl:px-8 xl:py-7'
: 'max-w-[var(--container-width)] px-6 py-0'
)}>
{children}
</div>
<Footer />
<Footer isAdmin={showSidebar} />
</main>
</div>
</div>
+62 -59
View File
@@ -1,10 +1,10 @@
'use client';
import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/Button';
import { Icon } from '@/components/ui/Icon';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Icon } from '@/components/ui/Icon';
import { Button } from '@/components/ui/Button';
import React, { useEffect, useState } from 'react';
interface NavbarProps {
onToggleSidebar?: () => void;
@@ -47,89 +47,92 @@ export const Navbar: React.FC<NavbarProps> = ({
const isVcon = pathname?.startsWith('/vcon');
return (
<header className="h-[38px] shrink-0 bg-[var(--bg-activity)] border-b border-[var(--border)] px-3 sm:px-4 flex items-center justify-between z-40 select-none">
<header className="h-14 shrink-0 bg-[var(--bg-activity)] border-b border-[var(--border)] px-4 sm:px-6 flex items-center justify-between gap-3 z-40 select-none">
{/* Left: Mobile hamburger + Brand */}
<div className="flex items-center gap-2">
<div className="flex items-center gap-3 min-w-0">
{showSidebarToggle && (
<button
onClick={onToggleSidebar}
className="md:hidden w-[26px] h-[26px] flex items-center justify-center text-[var(--text-muted)] hover:text-[var(--text)] border border-[var(--border)] bg-[var(--bg-elevated)] cursor-pointer"
className="lg:hidden w-9 h-9 shrink-0 flex items-center justify-center text-[var(--text-muted)] hover:text-[var(--text)] border border-[var(--border)] bg-[var(--bg-elevated)] cursor-pointer"
aria-label="Toggle Navigation"
>
<Icon name="Menu" size={13} />
</button>
)}
<Link href="/" className="flex items-center gap-1.5">
<div className="w-[17px] h-[17px] bg-[var(--accent)] text-[var(--text-on-accent)] flex items-center justify-center text-[9.5px] font-bold">
DS
</div>
<span className="text-[12px] font-semibold text-[var(--text)] tracking-tight">
<Link href="/" className="flex items-center gap-2 min-w-0 text-[14px] font-medium">
<span className="grid h-4 w-4 shrink-0 place-items-center bg-[var(--accent)]">
<span className="h-1.5 w-1.5 bg-[var(--bg)]" />
</span>
<span className="truncate text-[var(--text)]">
DataStack
</span>
<span className="hidden sm:inline text-[9px] text-[var(--text-dim)] font-mono border border-[var(--border)] px-1 py-0.2">
v2.4
</span>
{isVcon && (
<span className="hidden lg:inline text-[11px] text-[var(--text-dim)] font-mono border border-[var(--border)] px-1.5 py-1">
v2.4
</span>
)}
</Link>
</div>
{/* Middle: Links */}
<nav className="hidden sm:flex items-center gap-1 text-[11px]">
<Link
href="/"
className={`px-2.5 py-1 transition-colors border-b-2 ${
pathname === '/'
? 'border-[var(--accent)] text-[var(--text)] font-medium'
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'
}`}
>
Overview
</Link>
<Link
href="/vcon/dashboard"
className={`px-2.5 py-1 transition-colors border-b-2 flex items-center gap-1.5 ${
isVcon
? 'border-[var(--accent)] text-[var(--text)] font-medium'
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'
}`}
>
<span>Admin Console</span>
<span className="w-1.5 h-1.5 bg-[var(--success)] shrink-0" />
</Link>
<Link
href="/vcon/export"
className={`px-2.5 py-1 transition-colors border-b-2 ${
pathname === '/vcon/export'
? 'border-[var(--accent)] text-[var(--text)] font-medium'
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'
}`}
>
CSV Exporter
</Link>
<nav className="hidden sm:flex items-center gap-6 text-[13px]">
{isVcon ? (
<>
<Link href="/" className="text-[var(--text-muted)] hover:text-[var(--text)]">
Overview
</Link>
<Link
href="/vcon/dashboard"
className="px-3 py-2 transition-colors border-b-2 flex items-center gap-2 border-[var(--accent)] text-[var(--text)] font-medium"
>
<span>Admin Console</span>
<span className="w-1.5 h-1.5 bg-[var(--success)] shrink-0" />
</Link>
<Link
href="/vcon/export"
className={`px-3 py-2 transition-colors border-b-2 ${
pathname === '/vcon/export'
? 'border-[var(--accent)] text-[var(--text)] font-medium'
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'
}`}
>
CSV Exporter
</Link>
</>
) : (
<>
<Link href="#features" className="text-[var(--text-muted)] hover:text-[var(--text)]">Features</Link>
<Link href="#sdk" className="text-[var(--text-muted)] hover:text-[var(--text)]">SDK</Link>
<Link href="#about" className="text-[var(--text-muted)] hover:text-[var(--text)]">About</Link>
</>
)}
</nav>
{/* Right: Port Badges + Theme Toggle + Console Action */}
<div className="flex items-center gap-1.5">
<div className="hidden lg:flex items-center gap-1.5 text-[9.5px] text-[var(--text-dim)] font-mono border border-[var(--border)] px-1.5 py-0.5 bg-[var(--bg-main)]">
<span className="w-1.5 h-1.5 bg-[var(--success)] inline-block" />
<span>:4000</span>
<span className="text-[var(--border-strong)]">|</span>
<span className="w-1.5 h-1.5 bg-[var(--accent)] inline-block" />
<span>:3000</span>
</div>
{/* Right: Admin runtime indicators or public feature action */}
<div className="flex items-center gap-2 shrink-0">
{isVcon && (
<div className="hidden xl:flex items-center gap-2 text-[11px] text-[var(--text-dim)] font-mono border border-[var(--border)] px-2.5 py-1.5 bg-[var(--bg-main)]">
<span className="w-1.5 h-1.5 bg-[var(--success)] inline-block" />
<span>:4000</span>
<span className="text-[var(--border-strong)]">|</span>
<span className="w-1.5 h-1.5 bg-[var(--accent)] inline-block" />
<span>:3000</span>
</div>
)}
<button
onClick={toggleTheme}
aria-label="Toggle Theme"
className="w-[26px] h-[26px] flex items-center justify-center border border-[var(--border)] bg-[var(--bg-elevated)] text-[var(--text-muted)] hover:text-[var(--text)] cursor-pointer"
className="w-9 h-9 flex items-center justify-center border border-[var(--border)] bg-[var(--bg-elevated)] text-[var(--text-muted)] hover:text-[var(--text)] cursor-pointer"
>
<Icon name={theme === 'dark' ? 'Sun' : 'Moon'} size={12} />
</button>
{!isVcon && (
<Link href="/vcon/dashboard">
<Button size="xs" variant="primary" icon="Terminal">
/vcon/
<Link href="#sdk">
<Button size="sm" variant="primary">
Read the SDK guide
</Button>
</Link>
)}
+59 -28
View File
@@ -1,10 +1,10 @@
'use client';
import React from 'react';
import { Icon } from '@/components/ui/Icon';
import { cn } from '@/lib/utils';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '@/lib/utils';
import { Icon } from '@/components/ui/Icon';
import React, { useEffect, useState } from 'react';
interface SidebarProps {
isOpen?: boolean;
@@ -19,29 +19,42 @@ export const Sidebar: React.FC<SidebarProps> = ({
const navigation = [
{
group: 'Core Telemetry',
group: 'Monitoring',
items: [
{ name: 'Dashboard', href: '/vcon/dashboard', icon: 'LayoutDashboard' },
{ name: 'Live Data Sync', href: '/vcon/data', icon: 'Activity', badge: 'Live' },
{ name: 'CSV Exporter', href: '/vcon/export', icon: 'Download' },
],
},
{
group: 'Management',
group: 'Data',
items: [
{ name: 'CSV Exporter', href: '/vcon/export', icon: 'Download' },
{ name: 'CSV Storage & Disk', href: '/vcon/storage', icon: 'HardDrive' },
],
},
{
group: 'Administration',
items: [
{ name: 'Client SDKs', href: '/vcon/clients', icon: 'Key' },
{ name: 'CSV Storage & Disk', href: '/vcon/storage', icon: 'HardDrive' },
{ name: 'Engine Settings', href: '/vcon/settings', icon: 'Sliders' },
],
},
{
group: 'Integration',
group: 'Developer Tools',
items: [
{ name: 'Python SDK Guide', href: '/vcon/sdk', icon: 'FileCode2' },
{ name: 'Live Simulator', href: '/vcon/simulator', icon: 'Play' },
],
},
];
const activeGroup = navigation.find((section) =>
section.items.some((item) => item.href === pathname)
)?.group;
const [openGroup, setOpenGroup] = useState(activeGroup ?? navigation[0].group);
useEffect(() => {
if (activeGroup) setOpenGroup(activeGroup);
}, [activeGroup]);
return (
<>
@@ -49,28 +62,28 @@ export const Sidebar: React.FC<SidebarProps> = ({
{isOpen && (
<div
onClick={onClose}
className="fixed inset-0 z-40 bg-black/60 md:hidden backdrop-blur-[1px]"
className="fixed inset-x-0 top-14 bottom-0 z-40 bg-black/50 lg:hidden"
/>
)}
{/* Sidebar Container */}
<aside
className={cn(
'fixed inset-y-0 left-0 z-50 md:static w-[210px] shrink-0 bg-[var(--bg-sidebar)] border-r border-[var(--border)] flex flex-col transition-transform duration-150 ease-in-out md:translate-x-0',
'fixed left-0 top-14 bottom-0 z-50 w-[264px] shrink-0 overflow-hidden bg-[var(--bg-sidebar)] border-r border-[var(--border)] flex flex-col transition-transform duration-150 ease-in-out lg:static lg:w-[264px] lg:translate-x-0',
isOpen ? 'translate-x-0' : '-translate-x-full'
)}
>
{/* Top Header */}
<div className="h-[38px] px-3 flex items-center justify-between border-b border-[var(--border)] bg-[var(--bg-activity)] shrink-0">
<div className="flex items-center gap-1.5 min-w-0">
<div className="h-[52px] px-4 flex items-center justify-between border-b border-[var(--border)] bg-[var(--bg-activity)] shrink-0">
<div className="flex items-center gap-2 min-w-0">
<span className="w-1.5 h-1.5 bg-[var(--accent)] shrink-0" />
<span className="text-[10.5px] font-semibold text-[var(--text)] tracking-wider uppercase truncate">
<span className="text-[12px] font-semibold text-[var(--text)] uppercase truncate">
VCON ADMIN
</span>
</div>
<button
onClick={onClose}
className="md:hidden text-[var(--text-dim)] hover:text-[var(--text)] p-1 cursor-pointer"
className="lg:hidden text-[var(--text-dim)] hover:text-[var(--text)] p-1 cursor-pointer"
aria-label="Close menu"
>
<Icon name="X" size={13} />
@@ -78,13 +91,29 @@ export const Sidebar: React.FC<SidebarProps> = ({
</div>
{/* Navigation items */}
<div className="flex-1 overflow-y-auto p-1.5 flex flex-col gap-2">
{navigation.map((section, idx) => (
<div key={idx} className="flex flex-col gap-0.5">
<span className="text-[9px] font-semibold text-[var(--text-dim)] uppercase tracking-wider px-2 py-0.5">
{section.group}
</span>
<div className="flex flex-col gap-0.5">
<nav aria-label="Admin navigation" className="flex-1 min-h-0 overflow-y-auto p-2.5 flex flex-col">
{navigation.map((section) => {
const isExpanded = openGroup === section.group;
const groupId = `nav-${section.group.toLowerCase().replaceAll(' ', '-')}`;
return (
<div key={section.group} className="border-b border-[var(--border)] last:border-b-0">
<button
type="button"
aria-expanded={isExpanded}
aria-controls={groupId}
onClick={() => setOpenGroup(isExpanded ? '' : section.group)}
className="w-full min-h-[42px] px-3 flex items-center justify-between gap-2 text-left text-[12px] font-medium text-[var(--text-muted)] hover:text-[var(--text)] transition-colors cursor-pointer"
>
<span className="truncate">{section.group}</span>
<Icon
name="ChevronDown"
size={12}
className={cn('transition-transform', isExpanded && 'rotate-180')}
/>
</button>
{isExpanded && (
<div id={groupId} className="pb-1.5 flex flex-col gap-1">
{section.items.map((item) => {
const isActive = pathname === item.href;
return (
@@ -93,7 +122,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
href={item.href}
onClick={onClose}
className={cn(
'flex items-center justify-between px-2 py-1 text-[11px] transition-colors border',
'flex min-h-10 min-w-0 items-center justify-between gap-2 px-3 py-2 text-[13px] transition-colors border',
isActive
? 'bg-[var(--accent-soft)] text-[var(--accent-hover)] font-medium border-[var(--accent)]'
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)] hover:bg-[var(--bg-hover)]'
@@ -102,26 +131,28 @@ export const Sidebar: React.FC<SidebarProps> = ({
<div className="flex items-center gap-2 min-w-0">
<Icon
name={item.icon}
size={12}
size={16}
className={isActive ? 'text-[var(--accent)]' : 'text-[var(--text-dim)]'}
/>
<span className="truncate">{item.name}</span>
</div>
{item.badge && (
<span className="text-[8px] px-1 py-0.2 bg-[var(--success-soft)] text-[var(--success)] font-mono border border-[var(--success)] shrink-0">
<span className="text-[10px] px-1.5 py-0.5 bg-[var(--success-soft)] text-[var(--success)] font-mono border border-[var(--success)] shrink-0">
{item.badge}
</span>
)}
</Link>
);
})}
</div>
)}
</div>
</div>
))}
</div>
);
})}
</nav>
{/* Footer info */}
<div className="p-2 border-t border-[var(--border)] bg-[var(--bg-main)] text-[9.5px] text-[var(--text-dim)] font-mono flex flex-col gap-1 shrink-0">
<div className="p-3 border-t border-[var(--border)] bg-[var(--bg-main)] text-[11px] text-[var(--text-dim)] font-mono flex flex-col gap-1.5 shrink-0">
<div className="flex items-center justify-between">
<span>Buffer Worker</span>
<span className="text-[var(--success)] flex items-center gap-1 font-semibold">
+180
View File
@@ -0,0 +1,180 @@
'use client';
import { Button } from '@/components/ui/Button';
import { FormSwitch } from '@/components/ui/Form';
import { Input } from '@/components/ui/Input';
import { ArrowRight } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
function safeNextPath() {
const value = new URLSearchParams(window.location.search).get('next');
return value && value.startsWith('/') && !value.startsWith('//') && value !== '/vcon/login'
? value
: '/vcon/dashboard';
}
export function AdminLogin() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [remember, setRemember] = useState(true);
const [showPassword, setShowPassword] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const [theme, setTheme] = useState<'dark' | 'light'>('dark');
useEffect(() => {
const savedTheme = localStorage.getItem('datastack-theme');
const initialTheme = savedTheme === 'light' ? 'light' : 'dark';
setTheme(initialTheme);
document.documentElement.classList.toggle('light', initialTheme === 'light');
document.documentElement.classList.toggle('dark', initialTheme === 'dark');
}, []);
const toggleTheme = () => {
const nextTheme = theme === 'dark' ? 'light' : 'dark';
setTheme(nextTheme);
localStorage.setItem('datastack-theme', nextTheme);
document.documentElement.classList.toggle('light', nextTheme === 'light');
document.documentElement.classList.toggle('dark', nextTheme === 'dark');
};
const submit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setErrorMessage('');
setIsSubmitting(true);
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, remember }),
});
const body = await response.json();
if (!response.ok) throw new Error(body.error || 'Sign in failed.');
router.replace(safeNextPath());
router.refresh();
} catch (submitError) {
setErrorMessage(submitError instanceof Error ? submitError.message : 'Unable to sign in.');
setIsSubmitting(false);
}
};
return (
<main className="relative grid min-h-dvh place-items-center bg-[var(--bg)] p-4 text-[var(--text)] sm:p-6">
<Button
type="button"
variant="icon"
size="icon"
icon={theme === 'dark' ? 'Sun' : 'Moon'}
aria-label="Toggle theme"
title="Toggle theme"
className="fixed right-4 top-4 z-10 h-7 w-7 border border-[var(--border)] text-[var(--text-muted)]"
onClick={toggleTheme}
/>
<section className="z-0 w-full max-w-xs border border-[var(--border)] bg-[var(--surface)]">
<header className="flex flex-col gap-3.5 border-b border-[var(--border)] px-5 pb-4 pt-5">
<Link href="/" className="flex items-center gap-2 text-[13px] font-medium text-[var(--text)]">
<span className="grid h-3.5 w-3.5 place-items-center bg-[var(--accent)]" aria-hidden="true">
<span className="h-1.5 w-1.5 bg-[var(--bg)]" />
</span>
DataStack
<span className="ml-1 border border-[var(--border-strong)] px-1 py-px text-[9px] tracking-wider text-[var(--text-faint)]">CONSOLE</span>
</Link>
<div>
<h1 className="text-[15px] font-medium tracking-tight text-[var(--text)]">Sign in</h1>
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Access your admin console</p>
</div>
</header>
<form onSubmit={submit} className="flex flex-col gap-3 px-5 py-4">
{errorMessage && (
<div role="alert" className="flex items-start gap-2 border border-[var(--border-strong)] bg-[var(--surface-2)] px-2.5 py-2 text-xs leading-relaxed text-[var(--text-muted)]">
<span className="mt-1 h-1.5 w-1.5 shrink-0 bg-[var(--text-muted)]" aria-hidden="true" />
<span>{errorMessage}</span>
</div>
)}
<Input
label="Email"
type="email"
autoComplete="username"
placeholder="admin@example.com"
value={email}
onChange={(event) => setEmail(event.target.value)}
compact
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
required
/>
<div className="flex flex-col gap-1">
<label htmlFor="admin-password" className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Password</label>
<div className="relative">
<Input
id="admin-password"
type={showPassword ? 'text' : 'password'}
autoComplete="current-password"
placeholder="Enter password"
value={password}
onChange={(event) => setPassword(event.target.value)}
compact
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 pr-10 text-[12.5px] focus:border-[var(--border-strong)]"
required
/>
<Button
type="button"
variant="icon"
size="icon"
icon={showPassword ? 'EyeOff' : 'Eye'}
aria-label={showPassword ? 'Hide password' : 'Show password'}
title={showPassword ? 'Hide password' : 'Show password'}
className="absolute right-0 top-0 h-8 w-8 border-l border-[var(--border)] text-[var(--text-faint)]"
onClick={() => setShowPassword((current) => !current)}
/>
</div>
</div>
<div className="flex items-center justify-between gap-2">
<FormSwitch label="Remember me" checked={remember} onChange={setRemember} />
<span className="shrink-0 text-[11px] text-[var(--text-faint)]">Server-managed access</span>
</div>
<Button
type="submit"
variant="primary"
size="sm"
icon="ArrowRight"
iconPosition="right"
loading={isSubmitting}
disabled={isSubmitting}
className="mt-1 h-[34px] w-full justify-center text-[12.5px]"
>
Sign in
</Button>
<div className="my-0.5 flex items-center gap-2.5 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
<span className="h-px flex-1 bg-[var(--border)]" />
Admin access
<span className="h-px flex-1 bg-[var(--border)]" />
</div>
<p className="text-center text-[11px] leading-relaxed text-[var(--text-faint)]">
Credentials are configured by the server operator.
</p>
</form>
<footer className="flex items-center justify-between border-t border-[var(--border)] px-5 py-2.5 text-[10.5px] text-[var(--text-faint)]">
<span><span className="mr-1.5 inline-block h-1 w-1 bg-[var(--accent)] align-middle" />Protected session</span>
<Link href="/" className="text-[var(--text-muted)] hover:text-[var(--text)]">Home <ArrowRight className="inline h-3 w-3" aria-hidden="true" /></Link>
</footer>
</section>
<footer className="fixed bottom-3 left-0 right-0 flex items-center justify-center gap-2 text-[10.5px] text-[var(--text-faint)]">
<span>DataStack</span>
<span className="text-[var(--border-strong)]">·</span>
<span>Self-hosted</span>
</footer>
</main>
);
}
+58
View File
@@ -0,0 +1,58 @@
'use client';
import { Pill } from '@/components/ui/Pill';
import { Search } from 'lucide-react';
import type { ClientStatusFilter } from './clients/types';
interface ClientsFiltersProps {
search: string;
onSearchChange: (value: string) => void;
status: ClientStatusFilter;
onStatusChange: (status: ClientStatusFilter) => void;
counts: Record<ClientStatusFilter, number>;
}
const FILTERS: { key: ClientStatusFilter; label: string }[] = [
{ key: 'all', label: 'All' },
{ key: 'online', label: 'Online' },
{ key: 'offline', label: 'Offline' },
{ key: 'pending', label: 'Pending' },
];
export function ClientsFilters({
search,
onSearchChange,
status,
onStatusChange,
counts,
}: ClientsFiltersProps) {
return (
<div className="mb-3 flex flex-wrap items-center gap-2">
<div className="flex h-8 w-full flex-1 items-center gap-1.5 border border-[var(--border)] bg-[var(--surface)] px-2.5 sm:max-w-xs">
<Search className="h-3.5 w-3.5 shrink-0 text-[var(--text-faint)]" aria-hidden="true" />
<input
type="search"
aria-label="Search clients"
value={search}
onChange={(event) => onSearchChange(event.target.value)}
placeholder="Search by name or client ID"
className="min-w-0 flex-1 bg-transparent text-xs text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]"
/>
</div>
<div className="ml-auto flex min-w-0 gap-1 overflow-x-auto" role="group" aria-label="Filter clients by status">
{FILTERS.map((filter) => (
<Pill
key={filter.key}
active={status === filter.key}
onClick={() => onStatusChange(filter.key)}
>
{filter.label}
<span className="text-[10px] text-[var(--text-faint)]">
{counts[filter.key].toLocaleString()}
</span>
</Pill>
))}
</div>
</div>
);
}
+475
View File
@@ -0,0 +1,475 @@
'use client';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Input, Textarea } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import {
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
import { useCallback, useEffect, useMemo, useState } from 'react';
interface Client {
clientId: string;
name: string;
rateLimit: number;
status: 'active' | 'revoked';
totalEvents: number;
lastActive?: string;
createdAt: string;
}
interface ClientCredentials extends Client {
secret: string;
token: string;
}
type ClientFilter = 'all' | 'online' | 'offline' | 'pending';
function isOnline(client: Client) {
return Boolean(
client.status === 'active' &&
client.lastActive &&
Date.now() - new Date(client.lastActive).getTime() < 60_000
);
}
function isPending(client: Client) {
return client.status === 'active' && !client.lastActive;
}
function relativeTime(timestamp?: string) {
if (!timestamp) return 'Never';
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - new Date(timestamp).getTime()) / 1000));
if (elapsedSeconds < 10) return 'Just now';
if (elapsedSeconds < 60) return `${elapsedSeconds}s ago`;
if (elapsedSeconds < 3600) return `${Math.floor(elapsedSeconds / 60)}m ago`;
if (elapsedSeconds < 86_400) return `${Math.floor(elapsedSeconds / 3600)}h ago`;
return `${Math.floor(elapsedSeconds / 86_400)}d ago`;
}
export function ClientsManager() {
const { success, error, warning } = useToast();
const [clients, setClients] = useState<Client[]>([]);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [search, setSearch] = useState('');
const [filter, setFilter] = useState<ClientFilter>('all');
const [createModalOpen, setCreateModalOpen] = useState(false);
const [credentialsModalOpen, setCredentialsModalOpen] = useState(false);
const [selectedClient, setSelectedClient] = useState<ClientCredentials | null>(null);
const [newClientId, setNewClientId] = useState('');
const [newClientName, setNewClientName] = useState('');
const [newRateLimit, setNewRateLimit] = useState('100');
const [submitting, setSubmitting] = useState(false);
const fetchClients = useCallback(async () => {
try {
const response = await fetch('/api/clients');
if (!response.ok) throw new Error('Unable to load clients');
const data = await response.json();
setClients(data.clients || []);
setLoadError('');
} catch (fetchError) {
setLoadError(fetchError instanceof Error ? fetchError.message : 'Unable to load clients');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchClients();
}, [fetchClients]);
const onlineCount = clients.filter(isOnline).length;
const pendingCount = clients.filter(isPending).length;
const offlineCount = clients.length - onlineCount - pendingCount;
const eventCount = clients.reduce((sum, client) => sum + client.totalEvents, 0);
const visibleClients = useMemo(() => {
const query = search.trim().toLowerCase();
return clients.filter((client) => {
const matchesSearch =
!query ||
client.clientId.toLowerCase().includes(query) ||
client.name.toLowerCase().includes(query);
const matchesFilter =
filter === 'all' ||
(filter === 'online' && isOnline(client)) ||
(filter === 'offline' && !isOnline(client) && !isPending(client)) ||
(filter === 'pending' && isPending(client));
return matchesSearch && matchesFilter;
});
}, [clients, filter, search]);
const handleCreateClient = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!newClientId.trim() || !newClientName.trim()) {
error('Validation error', 'Client ID and client name are required.');
return;
}
setSubmitting(true);
try {
const response = await fetch('/api/clients', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: newClientId.trim(),
name: newClientName.trim(),
rateLimit: Number(newRateLimit) || 100,
}),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Client registration failed');
setSelectedClient(data.client);
setCreateModalOpen(false);
setCredentialsModalOpen(true);
setNewClientId('');
setNewClientName('');
setNewRateLimit('100');
success('Client registered', `${data.client.clientId} is ready to connect.`);
await fetchClients();
} catch (submitError) {
error('Registration failed', submitError instanceof Error ? submitError.message : 'Unknown error');
} finally {
setSubmitting(false);
}
};
const handleToggleStatus = async (client: Client) => {
const status = client.status === 'active' ? 'revoked' : 'active';
if (status === 'revoked' && !window.confirm(`Revoke access for ${client.clientId}?`)) return;
try {
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to update client status');
warning('Client status updated', `${client.clientId} is now ${status}.`);
await fetchClients();
} catch (updateError) {
error('Status update failed', updateError instanceof Error ? updateError.message : 'Unknown error');
}
};
const handleRotateKey = async (client: Client) => {
if (!window.confirm(`Rotate credentials for ${client.clientId}? Existing credentials will stop working.`)) return;
try {
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'regenerate_token' }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to rotate client credentials');
setSelectedClient(data.client);
setCredentialsModalOpen(true);
success('Credentials rotated', `New credentials issued for ${client.clientId}.`);
await fetchClients();
} catch (rotateError) {
error('Credential rotation failed', rotateError instanceof Error ? rotateError.message : 'Unknown error');
}
};
const copyToClipboard = async (value: string, label: string) => {
try {
await navigator.clipboard.writeText(value);
success('Copied', `${label} copied to clipboard.`);
} catch {
error('Copy failed', 'Clipboard access is unavailable in this browser.');
}
};
const filters: { id: ClientFilter; label: string; count: number }[] = [
{ id: 'all', label: 'All', count: clients.length },
{ id: 'online', label: 'Online', count: onlineCount },
{ id: 'offline', label: 'Offline', count: offlineCount },
{ id: 'pending', label: 'Pending', count: pendingCount },
];
return (
<section className="mx-auto flex w-full max-w-[var(--container-width)] flex-col gap-4">
<nav aria-label="Breadcrumb" className="flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
<span>Console</span>
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
<span aria-current="page" className="text-[var(--text)]">Clients</span>
</nav>
<header className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-base font-medium tracking-tight text-[var(--text)]">Clients</h1>
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Registered SDK clients and their API access</p>
</div>
<Button type="button" variant="primary" size="sm" icon="Plus" onClick={() => setCreateModalOpen(true)}>
New client
</Button>
</header>
<Card compact className="!p-0">
<div className="grid grid-cols-2 gap-px bg-[var(--border)] lg:grid-cols-4">
<StatCell label="Total clients" value={clients.length.toLocaleString()} />
<StatCell label="Online now" value={onlineCount.toLocaleString()} status="online" />
<StatCell label="Offline" value={offlineCount.toLocaleString()} status="offline" />
<StatCell label="Pending setup" value={pendingCount.toLocaleString()} status="pending" />
</div>
</Card>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<Input
compact
aria-label="Search clients"
placeholder="Search by name or client ID"
icon="Search"
value={search}
onChange={(event) => setSearch(event.target.value)}
className="bg-[var(--surface)] sm:max-w-xs"
/>
<div className="flex min-w-0 gap-1 overflow-x-auto sm:ml-auto" role="group" aria-label="Filter clients by status">
{filters.map((item) => (
<Button
key={item.id}
type="button"
size="xs"
variant="secondary"
aria-pressed={filter === item.id}
className={filter === item.id ? 'border-[var(--border-strong)] bg-[var(--surface-2)] text-[var(--text)]' : 'text-[var(--text-muted)]'}
onClick={() => setFilter(item.id)}
>
{item.label}<span className="text-[var(--text-faint)]">{item.count}</span>
</Button>
))}
</div>
</div>
<TableWrap>
<Table className="min-w-[760px] text-xs">
<TableHeader>
<TableRow>
<TableHead>Client</TableHead>
<TableHead>API key</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Events</TableHead>
<TableHead>Last seen</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableEmpty colSpan={6} message="Loading clients..." />
) : loadError ? (
<TableEmpty colSpan={6} message={loadError} />
) : visibleClients.length === 0 ? (
<TableEmpty colSpan={6} message={search || filter !== 'all' ? 'No clients match these filters.' : 'No registered SDK clients yet.'} />
) : (
visibleClients.map((client) => (
<TableRow key={client.clientId}>
<TableCell>
<div className="flex min-w-0 items-center gap-2.5">
<span className={`h-1.5 w-1.5 shrink-0 ${client.status === 'active' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
<div className="min-w-0">
<div className="truncate text-[var(--text)]">{client.name}</div>
<div className="truncate font-mono text-[11px] text-[var(--text-faint)]">{client.clientId}</div>
</div>
</div>
</TableCell>
<TableCell className="font-mono text-[var(--text-muted)]" title="Secret keys are hidden. Rotate credentials to issue a new key.">
sec_••••••••
</TableCell>
<TableCell>
<span className="inline-flex items-center gap-1.5 text-[var(--text-muted)]">
<span className={`h-1.5 w-1.5 ${client.status === 'active' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
{client.status}
</span>
</TableCell>
<TableCell className="text-right font-mono text-[var(--text)]">
{client.totalEvents.toLocaleString()}
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--text-muted)]">
{relativeTime(client.lastActive)}
</TableCell>
<TableCell className="text-right">
<div className="inline-flex items-center gap-1">
<Button
type="button"
variant="icon"
size="icon"
icon="Activity"
className="h-7 w-7 border border-[var(--border)]"
title={`View events for ${client.clientId}`}
aria-label={`View events for ${client.clientId}`}
onClick={() => window.location.assign(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
/>
<Button
type="button"
variant="icon"
size="icon"
icon="RotateCw"
className="h-7 w-7 border border-[var(--border)]"
title={`Rotate key for ${client.clientId}`}
aria-label={`Rotate key for ${client.clientId}`}
onClick={() => handleRotateKey(client)}
/>
<Button
type="button"
variant="icon"
size="icon"
icon={client.status === 'active' ? 'ShieldOff' : 'ShieldCheck'}
className="h-7 w-7 border border-[var(--border)]"
title={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
aria-label={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
onClick={() => handleToggleStatus(client)}
/>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableWrap>
<Modal
isOpen={createModalOpen}
onClose={() => setCreateModalOpen(false)}
title="Create client"
footer={
<>
<Button type="button" variant="ghost" size="sm" onClick={() => setCreateModalOpen(false)}>
Cancel
</Button>
<Button type="submit" form="create-client-form" variant="primary" size="sm" loading={submitting}>
Create client
</Button>
</>
}
>
<form id="create-client-form" onSubmit={handleCreateClient} className="flex flex-col gap-3">
<Input
label="Client ID"
placeholder="e.g. py_order_service_04"
value={newClientId}
onChange={(event) => setNewClientId(event.target.value)}
required
/>
<Input
label="Client name"
placeholder="e.g. Order Service"
value={newClientName}
onChange={(event) => setNewClientName(event.target.value)}
required
/>
<Input
label="Rate limit (requests per second)"
type="number"
min="1"
max="5000"
value={newRateLimit}
onChange={(event) => setNewRateLimit(event.target.value)}
/>
</form>
</Modal>
<Modal
isOpen={credentialsModalOpen}
onClose={() => setCredentialsModalOpen(false)}
title={`Credentials: ${selectedClient?.clientId || ''}`}
description="Copy these credentials now. The secret key is only shown after creation or rotation."
footer={
<Button type="button" variant="secondary" size="sm" onClick={() => setCredentialsModalOpen(false)}>
Close
</Button>
}
>
{selectedClient && (
<div className="flex flex-col gap-3">
<CredentialField
label="Client ID"
value={selectedClient.clientId}
onCopy={() => copyToClipboard(selectedClient.clientId, 'Client ID')}
/>
<CredentialField
label="Client secret key"
value={selectedClient.secret}
onCopy={() => copyToClipboard(selectedClient.secret, 'Client secret key')}
/>
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<label htmlFor="client-token" className="text-xs uppercase text-[var(--text-faint)]">
JWT handshake bearer token
</label>
<Button
type="button"
variant="ghost"
size="xs"
icon="Copy"
onClick={() => copyToClipboard(selectedClient.token, 'JWT token')}
>
Copy
</Button>
</div>
<Textarea id="client-token" readOnly value={selectedClient.token} rows={4} className="font-mono text-xs text-[var(--accent)]" />
</div>
</div>
)}
</Modal>
</section>
);
}
function StatCell({
label,
value,
status,
}: {
label: string;
value: string;
status?: 'online' | 'offline' | 'pending';
}) {
return (
<div className="bg-[var(--surface)] px-4 py-3">
<div className="mb-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">{label}</div>
<div className="flex items-center gap-2 text-lg font-medium leading-none tracking-tight text-[var(--text)]">
{status && (
<span className={`h-1.5 w-1.5 ${status === 'online' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
)}
{value}
</div>
</div>
);
}
function CredentialField({
label,
value,
onCopy,
}: {
label: string;
value: string;
onCopy: () => void;
}) {
return (
<div className="flex flex-col gap-1.5">
<label className="text-xs uppercase text-[var(--text-faint)]">{label}</label>
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
<code className="min-w-0 truncate font-mono text-xs text-[var(--text)]">{value}</code>
<Button type="button" variant="icon" size="icon" icon="Copy" className="h-7 w-7" title={`Copy ${label}`} aria-label={`Copy ${label}`} onClick={onCopy} />
</div>
</div>
);
}
+196
View File
@@ -0,0 +1,196 @@
'use client';
import { Button } from '@/components/ui/Button';
import { CopyButton } from '@/components/ui/CopyButton';
import { Modal } from '@/components/ui/Modal';
import {
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
import { useState } from 'react';
import type { ClientCredentials, ClientItem } from './clients/types';
interface ClientsTableProps {
clients: ClientItem[];
now: number;
onStatusChange: () => Promise<void>;
}
function relativeTime(timestamp: string | undefined, now: number) {
if (!timestamp) return 'Never';
const seconds = Math.max(0, Math.floor((now - new Date(timestamp).getTime()) / 1000));
if (seconds < 10) return 'Just now';
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86_400) return `${Math.floor(seconds / 3600)}h ago`;
return `${Math.floor(seconds / 86_400)}d ago`;
}
export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps) {
const { success, error } = useToast();
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
const rotateKey = async (client: ClientItem) => {
if (!window.confirm(`Rotate credentials for ${client.clientId}? Existing credentials will stop working.`)) return;
try {
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'regenerate_token' }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to rotate credentials');
setCredentials(data.client);
success('Credentials rotated', `New credentials issued for ${client.clientId}.`);
await onStatusChange();
} catch (rotateError) {
error('Credential rotation failed', rotateError instanceof Error ? rotateError.message : 'Unknown error');
}
};
const toggleStatus = async (client: ClientItem) => {
const status = client.status === 'active' ? 'revoked' : 'active';
if (status === 'revoked' && !window.confirm(`Revoke access for ${client.clientId}?`)) return;
try {
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to update client status');
success('Client status updated', `${client.clientId} is now ${status}.`);
await onStatusChange();
} catch (statusError) {
error('Status update failed', statusError instanceof Error ? statusError.message : 'Unknown error');
}
};
return (
<>
<TableWrap>
<Table className="min-w-[760px] text-xs">
<TableHeader>
<TableRow>
<TableHead>Client</TableHead>
<TableHead>API key</TableHead>
<TableHead className="text-right">Events</TableHead>
<TableHead>Last seen</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{clients.length === 0 ? (
<TableEmpty colSpan={5} message="No clients match these filters." />
) : (
clients.map((client) => {
const online = client.status === 'active' && Boolean(client.lastActive) &&
now - new Date(client.lastActive!).getTime() < 60_000;
const pending = client.status === 'active' && !client.lastActive;
const label = pending ? 'pending' : online ? 'online' : 'offline';
const dotClass = online
? 'bg-[var(--accent)]'
: pending
? 'bg-[var(--warning)]'
: 'bg-[var(--text-faint)]';
return (
<TableRow key={client.clientId} className="border-b border-[var(--border)] last:border-b-0 hover:bg-[var(--surface-2)]">
<TableCell className="px-3.5 py-2.5">
<div className="flex min-w-0 items-center gap-2.5">
<span className={`h-1.5 w-1.5 shrink-0 ${dotClass}`} title={label} />
<div className="min-w-0 leading-tight">
<div className="truncate text-[12.5px] 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="px-3.5 py-2.5 font-mono text-[11.5px] text-[var(--text-muted)]" title="Secret keys are hidden. Rotate credentials to issue a new key.">
sec_••••••••
</TableCell>
<TableCell className="px-3.5 py-2.5 text-right font-mono text-[11.5px] text-[var(--text-muted)]">
{client.totalEvents.toLocaleString()}
</TableCell>
<TableCell className="px-3.5 py-2.5 font-mono text-[11.5px] text-[var(--text-muted)]">
{client.lastActive ? new Date(client.lastActive).toLocaleTimeString([], { hour12: false }) : '—'}
<span className="ml-1 font-sans text-[10.5px] text-[var(--text-faint)]">{relativeTime(client.lastActive, now)}</span>
</TableCell>
<TableCell className="px-3.5 py-2.5 text-right">
<div className="inline-flex gap-0.5">
<Button
type="button"
variant="icon"
size="icon"
icon="Activity"
className="h-[26px] w-[26px] border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
title={`View events for ${client.clientId}`}
aria-label={`View events for ${client.clientId}`}
onClick={() => window.location.assign(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
/>
<Button
type="button"
variant="icon"
size="icon"
icon="RefreshCw"
className="h-[26px] w-[26px] border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
title={`Rotate key for ${client.clientId}`}
aria-label={`Rotate key for ${client.clientId}`}
onClick={() => rotateKey(client)}
/>
<Button
type="button"
variant="icon"
size="icon"
icon={client.status === 'active' ? 'Trash2' : 'ShieldCheck'}
className={`h-[26px] w-[26px] border border-transparent ${client.status === 'active' ? 'hover:border-[var(--danger)] hover:text-[var(--danger)]' : 'hover:border-[var(--border)] hover:bg-[var(--surface-2)]'}`}
title={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
aria-label={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
onClick={() => toggleStatus(client)}
/>
</div>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</TableWrap>
<Modal
isOpen={Boolean(credentials)}
onClose={() => setCredentials(null)}
title={`Credentials: ${credentials?.clientId || ''}`}
description="Copy the new credentials now. The secret is only shown after rotation."
footer={<Button type="button" size="sm" onClick={() => setCredentials(null)}>Close</Button>}
>
{credentials && (
<div className="flex flex-col gap-3">
<Credential label="Client ID" value={credentials.clientId} />
<Credential label="Client secret key" value={credentials.secret} />
<Credential label="JWT token" value={credentials.token} />
</div>
)}
</Modal>
</>
);
}
function Credential({ label, value }: { label: string; value: string }) {
return (
<div className="flex flex-col gap-1.5">
<span className="text-xs uppercase text-[var(--text-faint)]">{label}</span>
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
<code className="min-w-0 break-all font-mono text-xs text-[var(--text)]">{value}</code>
<CopyButton value={value} />
</div>
</div>
);
}
+241
View File
@@ -0,0 +1,241 @@
'use client';
import { Button } from '@/components/ui/Button';
import { ClientList, type ClientListItem } from '@/components/ui/ClientList';
import { Panel } from '@/components/ui/Panel';
import { StatCard } from '@/components/ui/StatCard';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
TableWrap,
} from '@/components/ui/Table';
import Link from 'next/link';
import React, { useCallback, useEffect, useState } from 'react';
type EventItem = {
eventId: string;
clientId: string;
timestamp: string;
payload: string;
};
type DashboardMetrics = {
activeClients: number;
totalClients: number;
bufferStats: {
currentBufferSize: number;
totalFlushed: number;
};
storageStats: {
totalMB: string;
totalBytes: number;
totalFiles: number;
totalRows: number;
};
};
type StorageFile = {
clientId: string;
date: string;
filename: string;
sizeBytes: number;
linesCount: number;
};
export const DashboardOverview: React.FC = () => {
const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
const [events, setEvents] = useState<EventItem[]>([]);
const [clients, setClients] = useState<ClientListItem[]>([]);
const [files, setFiles] = useState<StorageFile[]>([]);
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' }),
]);
if (metricsResponse.ok) setMetrics(await metricsResponse.json());
if (eventsResponse.ok) {
const data = await eventsResponse.json();
setEvents(data.events ?? []);
}
if (storageResponse.ok) {
const data = await storageResponse.json();
setFiles(data.files ?? []);
}
if (clientsResponse.ok) {
const data = await clientsResponse.json();
setClients(data.clients ?? []);
}
} catch {
// Keep the last successful dashboard snapshot when one request fails.
} finally {
setIsRefreshing(false);
}
}, []);
useEffect(() => {
void refresh();
const interval = window.setInterval(() => void refresh(), 5000);
return () => window.clearInterval(interval);
}, [refresh]);
const today = new Date().toISOString().slice(0, 10);
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 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 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);
return (
<section className="flex w-full max-w-[var(--console-width)] flex-col gap-4">
<header className="flex flex-wrap items-center justify-between gap-4">
<div>
<nav aria-label="Breadcrumb" className="mb-1 flex items-center gap-2 text-[11px] text-[var(--text-faint)]">
<span>Console</span>
<span>/</span>
<span className="text-[var(--text)]">Dashboard</span>
</nav>
<h1 className="text-[17px] font-medium text-[var(--text)]">Dashboard</h1>
<p className="mt-0.5 text-[12px] text-[var(--text-muted)]">Last 24 hours · UTC</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="mr-2 inline-flex items-center gap-2 text-[10px] uppercase text-[var(--text-muted)]">
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />
{metrics ? `${metrics.bufferStats.currentBufferSize} buffered` : 'Connecting'}
</span>
<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="sm" variant="secondary" icon="Download">Quick export</Button>
</a>
<Link href="/vcon/clients">
<Button size="sm" variant="primary" icon="Plus">New client</Button>
</Link>
</div>
</header>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
<StatCard
label="Events today"
value={eventsToday.toLocaleString()}
meta={`${metrics?.bufferStats.currentBufferSize ?? 0} waiting in buffer`}
/>
<StatCard
label="Active clients"
value={`${activeClients} / ${totalClients}`}
meta="registered clients"
/>
<StatCard
label="Storage used"
value={storageValue}
unit={storageUnit}
meta="across stored CSV files"
/>
<StatCard
label="Stored rows"
value={totalRows.toLocaleString()}
meta={`${totalFiles} CSV files`}
/>
</div>
<div className="grid min-w-0 grid-cols-1 gap-3 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<Panel
title="Live ingestion"
meta={`${events.length} recent events`}
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-[600px] text-[11.5px]">
<TableHeader>
<TableRow>
<TableHead>Time</TableHead>
<TableHead>Client</TableHead>
<TableHead>Payload</TableHead>
<TableHead className="text-right">Size</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{events.map((event) => (
<TableRow key={event.eventId}>
<TableCell className="font-mono text-[11px] 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)]">
{event.clientId}
</TableCell>
<TableCell className="max-w-[420px] truncate font-mono text-[11px] text-[var(--text)]">
{event.payload}
</TableCell>
<TableCell className="text-right font-mono text-[11px] text-[var(--text-faint)]">
{new TextEncoder().encode(event.payload).length} B
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableWrap>
</Panel>
<div className="flex min-w-0 flex-col gap-3">
<Panel
title="Recent clients"
action={<Link href="/vcon/clients" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">All →</Link>}
>
<ClientList clients={clients} limit={4} />
</Panel>
<Panel
title="Storage"
meta={`${totalFiles} files`}
action={<a href="/api/export?clientId=all" download className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">Quick 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-3 px-4 py-2">
<div className="min-w-0">
<p className="truncate text-[12px] 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-[11px] text-[var(--text-muted)]">
{(file.sizeBytes / 1024).toFixed(1)} KB
</span>
</div>
))}
{files.length === 0 && (
<p className="px-4 py-5 text-[12px] text-[var(--text-faint)]">No CSV files yet.</p>
)}
</div>
</Panel>
</div>
</div>
</section>
);
};
export default DashboardOverview;
+353
View File
@@ -0,0 +1,353 @@
'use client';
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 {
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
TableWrap,
} from '@/components/ui/Table';
import { useCallback, useEffect, useState } from 'react';
interface StreamEvent {
clientId: string;
eventId: string;
timestamp: string;
payload: string;
status: 'stored' | 'buffered';
}
interface Client {
clientId: string;
name: string;
}
const PAGE_SIZE = 12;
export function DataBrowser() {
const [events, setEvents] = useState<StreamEvent[]>([]);
const [clients, setClients] = useState<Client[]>([]);
const [total, setTotal] = useState(0);
const [pageCount, setPageCount] = useState(1);
const [clientFilter, setClientFilter] = useState('all');
const [fromFilter, setFromFilter] = useState('');
const [toFilter, setToFilter] = useState('');
const [searchFilter, setSearchFilter] = useState('');
const [appliedFilters, setAppliedFilters] = useState({
clientId: 'all',
from: '',
to: '',
search: '',
});
const [page, setPage] = useState(1);
const [filtersReady, setFiltersReady] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const fetchEvents = useCallback(async () => {
try {
const params = new URLSearchParams({
clientId: appliedFilters.clientId,
from: appliedFilters.from,
to: appliedFilters.to,
search: appliedFilters.search,
page: String(page),
pageSize: String(PAGE_SIZE),
});
const response = await fetch(`/api/data?${params}`);
if (!response.ok) throw new Error('Unable to load events');
const data = await response.json();
setEvents(data.events || []);
setTotal(data.total || 0);
setPageCount(data.pageCount || 1);
setErrorMessage('');
} catch (error) {
setErrorMessage(error instanceof Error ? error.message : 'Unable to load events');
}
}, [appliedFilters, page]);
useEffect(() => {
fetch('/api/clients')
.then((response) => (response.ok ? response.json() : { clients: [] }))
.then((data) => setClients(data.clients || []))
.catch(() => setClients([]));
}, []);
useEffect(() => {
const clientId = new URLSearchParams(window.location.search).get('clientId');
if (clientId) {
setClientFilter(clientId);
setAppliedFilters((current) => ({ ...current, clientId }));
}
setFiltersReady(true);
}, []);
useEffect(() => {
if (!filtersReady) return;
fetchEvents();
}, [fetchEvents, filtersReady]);
const firstVisible = total === 0 ? 0 : (page - 1) * PAGE_SIZE + 1;
const lastVisible = Math.min(page * PAGE_SIZE, total);
const firstPage = Math.max(1, Math.min(page - 1, pageCount - 2));
const visiblePages = Array.from(
{ length: Math.min(3, pageCount) },
(_, index) => firstPage + index
);
const applyFilters = () => {
setAppliedFilters({
clientId: clientFilter,
from: fromFilter,
to: toFilter,
search: searchFilter,
});
setPage(1);
};
const resetFilters = () => {
setClientFilter('all');
setFromFilter('');
setToFilter('');
setSearchFilter('');
setAppliedFilters({ clientId: 'all', from: '', to: '', search: '' });
setPage(1);
};
const refresh = async () => {
setRefreshing(true);
await fetchEvents();
setRefreshing(false);
};
return (
<section className="mx-auto flex w-full max-w-[var(--console-width)] flex-col gap-4">
<header className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-base font-medium tracking-[-0.3px] text-[var(--text)]">Data</h1>
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Collected events across all clients</p>
</div>
<div className="flex items-center gap-2">
<Button
type="button"
variant="icon"
size="icon"
icon="RefreshCw"
className="h-8 w-8 border border-[var(--border)]"
title="Refresh events"
aria-label="Refresh events"
loading={refreshing}
onClick={refresh}
/>
<Button
type="button"
variant="primary"
size="sm"
icon="Download"
onClick={() => window.location.assign('/vcon/export')}
>
Export CSV
</Button>
</div>
</header>
<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-3">
<Select
label="Client"
compact
value={clientFilter}
onChange={(event) => setClientFilter(event.target.value)}
>
<option value="all">All clients</option>
{clients.map((client) => (
<option key={client.clientId} value={client.clientId}>
{client.name || client.clientId}
</option>
))}
</Select>
</div>
<div className="bg-[var(--surface)] p-3">
<Input
label="From"
compact
type="date"
value={fromFilter}
onChange={(event) => setFromFilter(event.target.value)}
/>
</div>
<div className="bg-[var(--surface)] p-3">
<Input
label="To"
compact
type="date"
value={toFilter}
onChange={(event) => setToFilter(event.target.value)}
/>
</div>
<div className="bg-[var(--surface)] p-3">
<Input
label="Search payload"
compact
placeholder="e.g. sensor, user_id"
icon="Search"
value={searchFilter}
onChange={(event) => setSearchFilter(event.target.value)}
/>
</div>
<div className="flex items-end justify-end gap-2 bg-[var(--surface)] p-3">
<Button type="button" size="xs" icon="X" onClick={resetFilters}>
Reset
</Button>
<Button type="button" size="xs" variant="primary" onClick={applyFilters}>
Apply
</Button>
</div>
</div>
</Card>
<Panel
title="Events"
meta={`${total.toLocaleString()} results · page ${page} of ${pageCount}`}
bodyClassName="overflow-hidden"
>
<TableWrap className="border-0">
<Table className="min-w-[760px] text-xs">
<TableHeader>
<TableRow>
<TableHead>Time</TableHead>
<TableHead>Client</TableHead>
<TableHead className="hidden sm:table-cell">Event ID</TableHead>
<TableHead>Payload</TableHead>
<TableHead className="hidden md:table-cell">Size</TableHead>
<TableHead className="text-right">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{errorMessage ? (
<TableEmpty colSpan={6} message={errorMessage} />
) : events.length === 0 ? (
<TableEmpty colSpan={6} message="No events match these filters." />
) : (
events.map((event) => (
<TableRow key={event.eventId}>
<TableCell className="font-mono text-[var(--text)]">
{new Date(event.timestamp).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})}
</TableCell>
<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-[var(--text)]">
{event.payload}
</TableCell>
<TableCell className="hidden font-mono 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-[var(--text-muted)]">
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />{event.status}
</span>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableWrap>
<footer className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border)] px-4 py-2.5">
<p className="text-xs text-[var(--text-muted)]">
Showing <strong className="font-medium text-[var(--text)]">{firstVisible}–{lastVisible}</strong> of{' '}
<strong className="font-medium text-[var(--text)]">{total.toLocaleString()}</strong> events
</p>
<nav className="flex items-center gap-1" aria-label="Event pages">
<Button
type="button"
variant="icon"
size="icon"
icon="ChevronLeft"
className="h-7 w-7 border border-[var(--border)]"
aria-label="Previous page"
disabled={page <= 1}
onClick={() => setPage((current) => Math.max(1, current - 1))}
/>
{firstPage > 1 && (
<>
<PageButton pageNumber={1} active={page === 1} onSelect={setPage} />
{firstPage > 2 && <span className="px-1 text-xs text-[var(--text-faint)]">…</span>}
</>
)}
{visiblePages.map((pageNumber) => (
<PageButton
key={pageNumber}
pageNumber={pageNumber}
active={page === pageNumber}
onSelect={setPage}
/>
))}
{firstPage + visiblePages.length - 1 < pageCount && (
<>
{firstPage + visiblePages.length < pageCount && (
<span className="px-1 text-xs text-[var(--text-faint)]">…</span>
)}
<PageButton
pageNumber={pageCount}
active={page === pageCount}
onSelect={setPage}
/>
</>
)}
<Button
type="button"
variant="icon"
size="icon"
icon="ChevronRight"
className="h-7 w-7 border border-[var(--border)]"
aria-label="Next page"
disabled={page >= pageCount}
onClick={() => setPage((current) => Math.min(pageCount, current + 1))}
/>
</nav>
</footer>
</Panel>
</section>
);
}
function PageButton({
pageNumber,
active,
onSelect,
}: {
pageNumber: number;
active: boolean;
onSelect: (page: number) => void;
}) {
return (
<button
type="button"
aria-current={active ? 'page' : undefined}
className={`grid h-7 min-w-7 place-items-center border px-2 text-xs transition-colors ${
active
? 'border-[var(--border-strong)] bg-[var(--surface-2)] text-[var(--text)]'
: 'border-[var(--border)] text-[var(--text-muted)] hover:bg-[var(--surface-2)] hover:text-[var(--text)]'
}`}
onClick={() => onSelect(pageNumber)}
>
{pageNumber}
</button>
);
}
+316
View File
@@ -0,0 +1,316 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { Button } from '@/components/ui/Button';
import { Input, Select } from '@/components/ui/Input';
import { Panel } from '@/components/ui/Panel';
import { Pill } from '@/components/ui/Pill';
import { StatStrip } from '@/components/ui/StatStrip';
import { useToast } from '@/components/ui/Toast';
import { Braces, FileText, Info } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
interface Client {
clientId: string;
name: string;
}
interface StorageFile {
clientId: string;
date: string;
filename: string;
sizeBytes: number;
linesCount: number;
modifiedAt: string;
}
type ExportFormat = 'csv' | 'json';
type RangePreset = 'today' | '7d' | '30d' | 'all' | 'custom';
function dateString(date: Date) {
return date.toISOString().slice(0, 10);
}
function formatBytes(bytes: number) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
}
function relativeTime(value: string, now: number) {
const elapsedSeconds = Math.max(0, Math.floor((now - new Date(value).getTime()) / 1000));
if (elapsedSeconds < 60) return `${elapsedSeconds}s ago`;
if (elapsedSeconds < 3600) return `${Math.floor(elapsedSeconds / 60)}m ago`;
if (elapsedSeconds < 86_400) return `${Math.floor(elapsedSeconds / 3600)}h ago`;
return `${Math.floor(elapsedSeconds / 86_400)}d ago`;
}
export function ExportWorkspace() {
const { error, info } = useToast();
const [clients, setClients] = useState<Client[]>([]);
const [files, setFiles] = useState<StorageFile[]>([]);
const [selectedClient, setSelectedClient] = useState('all');
const [fromDate, setFromDate] = useState('');
const [toDate, setToDate] = useState('');
const [format, setFormat] = useState<ExportFormat>('csv');
const [preset, setPreset] = useState<RangePreset>('today');
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [now, setNow] = useState(0);
useEffect(() => {
const today = dateString(new Date());
setFromDate(today);
setToDate(today);
Promise.all([
fetch('/api/clients').then(async (response) => {
if (!response.ok) throw new Error('Unable to load clients');
return response.json();
}),
fetch('/api/storage').then(async (response) => {
if (!response.ok) throw new Error('Unable to load stored files');
return response.json();
}),
])
.then(([clientData, storageData]) => {
setClients(clientData.clients || []);
setFiles(storageData.files || []);
setLoadError('');
})
.catch((fetchError) => {
setLoadError(fetchError instanceof Error ? fetchError.message : 'Unable to load export data');
})
.finally(() => setLoading(false));
}, []);
useEffect(() => {
const updateClock = () => setNow(Date.now());
updateClock();
const interval = setInterval(updateClock, 30_000);
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 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 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);
if (nextPreset === 'all') {
setFromDate('');
setToDate('');
return;
}
const today = new Date();
const start = new Date(today);
if (nextPreset === '7d') start.setDate(today.getDate() - 6);
if (nextPreset === '30d') start.setDate(today.getDate() - 29);
setFromDate(dateString(start));
setToDate(dateString(today));
};
const exportUrl = useMemo(() => {
const params = new URLSearchParams({ clientId: selectedClient, format });
if (fromDate) params.set('from', fromDate);
if (toDate) params.set('to', toDate);
return `/api/export?${params.toString()}`;
}, [format, fromDate, selectedClient, toDate]);
const downloadExport = () => {
if (fromDate && toDate && fromDate > toDate) {
error('Invalid date range', 'The start date must be on or before the end date.');
return;
}
window.location.assign(exportUrl);
info('Export started', `${format.toUpperCase()} download for ${preview.rows.toLocaleString()} rows.`);
};
const downloadFile = (file: StorageFile) => {
window.location.assign(
`/api/export?clientId=${encodeURIComponent(file.clientId)}&filename=${encodeURIComponent(file.filename)}`
);
};
const rangeChanged = (setter: (value: string) => void, value: string) => {
setter(value);
setPreset('custom');
};
const resetExport = () => {
setSelectedClient('all');
setFormat('csv');
setQuickRange('all');
};
return (
<section className="mx-auto w-full max-w-[var(--container-width)]">
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
<span>Console</span>
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
<span aria-current="page" className="text-[var(--text)]">Export</span>
</nav>
<AdminPageHeader title="Export" subtitle="Generate CSV or JSON exports from collected data" />
<StatStrip
items={[
{ label: 'Stored files', value: files.length.toLocaleString() },
{ label: 'Stored rows', value: stats.rows.toLocaleString() },
{ label: 'Storage used', value: formatBytes(stats.bytes) },
{ label: 'Clients', value: stats.clients.toLocaleString() },
]}
/>
<div className="grid grid-cols-1 items-start gap-3 xl:grid-cols-5">
<Panel title="Export builder" meta="Estimate updates on change" bodyClassName="flex flex-col gap-4 p-4" className="min-w-0 xl:col-span-3">
<div className="flex flex-wrap items-center gap-1">
<span className="mr-1.5 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Quick range</span>
{([
['today', 'Today'],
['7d', 'Last 7d'],
['30d', 'Last 30d'],
['all', 'All'],
] as const).map(([id, label]) => (
<Pill key={id} active={preset === id} onClick={() => setQuickRange(id)}>{label}</Pill>
))}
</div>
<div className="grid grid-cols-1 gap-px border border-[var(--border)] bg-[var(--border)] md:grid-cols-[1.2fr_1fr_1fr]">
<div className="min-w-0 bg-[var(--surface)] p-3">
<Select
label="Client"
compact
value={selectedClient}
onChange={(event) => setSelectedClient(event.target.value)}
className="border-0 bg-transparent px-0 focus:border-transparent"
>
<option value="all">All clients</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-3">
<Input label="From" compact type="date" value={fromDate} onChange={(event) => rangeChanged(setFromDate, event.target.value)} className="border-0 bg-transparent px-0 focus:border-transparent" />
</div>
<div className="min-w-0 bg-[var(--surface)] p-3">
<Input label="To" compact type="date" value={toDate} onChange={(event) => rangeChanged(setToDate, event.target.value)} className="border-0 bg-transparent px-0 focus:border-transparent" />
</div>
</div>
<fieldset className="flex flex-col gap-2">
<legend className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Format</legend>
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2" role="radiogroup" aria-label="Export format">
<FormatOption value="csv" selected={format === 'csv'} label="CSV" hint="Comma-separated values" onSelect={setFormat} />
<FormatOption value="json" selected={format === 'json'} label="JSON" hint="Structured array" onSelect={setFormat} />
</div>
</fieldset>
<div className="flex flex-col gap-2">
<span className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Preview</span>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 border border-l-2 border-[var(--border)] border-l-[var(--accent)] bg-[var(--surface-2)] px-3 py-2 font-mono text-xs text-[var(--text-muted)]">
<Info className="h-3.5 w-3.5 text-[var(--accent)]" aria-hidden="true" />
<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> source size</span>
<span aria-hidden="true">·</span>
<span><strong className="font-medium text-[var(--text)]">{preview.files}</strong> files</span>
</div>
{loadError && <p role="alert" className="text-xs text-[var(--text-muted)]">{loadError}</p>}
{fromDate && toDate && fromDate > toDate && (
<p role="alert" className="text-xs 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-2 border-t border-[var(--border)] pt-3">
<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>
</Panel>
<Panel
title="Recent exports"
action={<a href="/vcon/storage" className="text-xs text-[var(--text-muted)] hover:text-[var(--text)]">View all</a>}
bodyClassName="divide-y divide-[var(--border)]"
className="min-w-0 xl:col-span-2"
>
{loading ? (
<p className="px-4 py-5 text-xs text-[var(--text-faint)]">Loading stored files...</p>
) : sortedRecentFiles.length === 0 ? (
<p className="px-4 py-5 text-xs text-[var(--text-faint)]">No stored files available to export.</p>
) : (
sortedRecentFiles.map((file) => (
<div key={`${file.clientId}/${file.filename}`} className="flex items-center gap-2.5 px-3.5 py-2.5 transition-colors hover:bg-[var(--surface-2)]">
<span className="shrink-0 border border-[var(--border-strong)] px-1.5 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-xs text-[var(--text)]">{file.filename}</div>
<div className="mt-0.5 truncate text-[10.5px] text-[var(--text-faint)]">
{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)} />
</div>
))
)}
</Panel>
</div>
<p className="mt-2 text-[11px] text-[var(--text-faint)]">
Exports are generated from CSV files on disk · Estimates are approximate · Large downloads are streamed
</p>
</section>
);
}
function FormatOption({
value,
selected,
label,
hint,
onSelect,
}: {
value: ExportFormat;
selected: boolean;
label: string;
hint: string;
onSelect: (value: ExportFormat) => void;
}) {
const FormatIcon = value === 'csv' ? FileText : Braces;
return (
<button
type="button"
role="radio"
aria-checked={selected}
className={`flex min-w-0 items-center gap-2.5 border px-3 py-2.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-7 w-7 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.5 w-3.5" aria-hidden="true" />
</span>
<span className="min-w-0">
<span className="block text-xs font-medium leading-tight text-[var(--text)]">{label}</span>
<span className="mt-0.5 block truncate text-[10.5px] text-[var(--text-faint)]">{hint}</span>
</span>
</button>
);
}
+14 -54
View File
@@ -1,66 +1,26 @@
import { FeatureItem } from '@/components/ui/FeatureItem';
import { SectionHeading } from '@/components/ui/SectionHeading';
import React from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Icon } from '@/components/ui/Icon';
export const Features: React.FC = () => {
const items = [
{
icon: 'Zap',
title: 'Decoupled Runtime Split',
desc: 'Port 4000 WebSocket intake; Port 3000 Web & export.',
},
{
icon: 'HardDrive',
title: 'CSV File Persistence',
desc: 'Streams directly to rotated CSV files on disk (Zero DB inserts).',
},
{
icon: 'ShieldCheck',
title: 'JWT SDK Authentication',
desc: 'Signed tokens verify client IDs and rate limits on handshake.',
},
{
icon: 'Cpu',
title: 'In-Memory Buffer',
desc: 'Aggregates 500 records or 2000ms intervals before async disk flush.',
},
{
icon: 'CheckCheck',
title: 'Idempotency Dedup',
desc: 'Rejects duplicate clientId + eventId in 5-minute sliding TTL window.',
},
{
icon: 'FileCode2',
title: 'Python Client SDK',
desc: 'datastack-sdk package with auto-reconnection and batch streaming.',
},
{ icon: 'Activity', title: 'Realtime over WebSocket', description: 'Durable connections. No polling or repeated API calls.' },
{ icon: 'HardDrive', title: 'CSV-first storage', description: 'Compact per-day records that stay simple to export.' },
{ icon: 'ShieldCheck', title: 'Verified sources', description: 'Each registered client is checked before sending activity.' },
{ icon: 'Layers3', title: 'Buffered writes', description: 'Batch incoming events to keep collection steady.' },
{ icon: 'ChartNoAxesCombined', title: 'Live dashboard', description: 'Watch activity arrive and filter by source or content.' },
{ icon: 'Download', title: 'One-click export', description: 'Download the records you need without blocking the workflow.' },
];
return (
<div className="flex flex-col gap-1.5 py-1">
<div className="flex items-center justify-between border-b border-[var(--border)] pb-1">
<h2 className="text-[11px] font-semibold text-[var(--text)] uppercase tracking-wider">
Platform Architecture
</h2>
<span className="text-[9px] text-[var(--text-dim)] font-mono">6 SUBSYSTEMS</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-1.5">
{items.map((item, idx) => (
<Card key={idx} compact className="flex flex-col gap-0.5 p-2">
<CardHeader className="p-0 pb-0.5 mb-0 border-b-0 flex items-center gap-1.5">
<div className="p-0.5 bg-[var(--bg-main)] text-[var(--accent)] border border-[var(--border-strong)] shrink-0">
<Icon name={item.icon} size={11} />
</div>
<CardTitle className="text-[11px]">{item.title}</CardTitle>
</CardHeader>
<CardContent className="p-0 text-[10px] text-[var(--text-muted)] leading-tight">
{item.desc}
</CardContent>
</Card>
<section id="features" className="border-b border-[var(--border)] py-10">
<SectionHeading index="01" label="Features" title="Built for ingestion at scale." />
<div className="grid grid-cols-1 gap-px border border-[var(--border)] bg-[var(--border)] sm:grid-cols-2 lg:grid-cols-3">
{items.map((item) => (
<FeatureItem key={item.title} {...item} />
))}
</div>
</div>
</section>
);
};
+26 -85
View File
@@ -1,90 +1,31 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { ActivityPreview } from '@/components/ui/ActivityPreview';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Icon } from '@/components/ui/Icon';
import Link from 'next/link';
import React from 'react';
export const Hero: React.FC = () => {
const [copied, setCopied] = useState(false);
const handleCopy = () => {
navigator.clipboard.writeText('pip install ./sdk-python');
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<div className="flex flex-col gap-2.5 py-1">
{/* Title */}
<div className="flex flex-col gap-1">
<h1 className="text-[16px] sm:text-[18px] font-semibold tracking-tight text-[var(--text)]">
Realtime Data Collection Platform
</h1>
</div>
{/* Actions */}
<div className="flex flex-wrap items-center gap-1.5">
<Link href="/vcon/dashboard">
<Button size="xs" variant="primary" icon="Terminal">
Console (/vcon/)
</Button>
</Link>
<Link href="/vcon/data">
<Button size="xs" variant="secondary" icon="Activity">
Live Stream
</Button>
</Link>
<div className="flex items-center gap-1.5 border border-[var(--border)] bg-[var(--bg-elevated)] px-2 py-0.5 text-[10px] font-mono text-[var(--text)]">
<span className="text-[var(--text-dim)]">$</span>
<span>pip install ./sdk-python</span>
<button
onClick={handleCopy}
className="text-[var(--text-dim)] hover:text-[var(--text)] ml-0.5 cursor-pointer"
aria-label="Copy install command"
>
<Icon name={copied ? 'Check' : 'Copy'} size={11} />
</button>
</div>
</div>
{/* 4 Clean Metric Cards */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-1.5 pt-0.5">
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<div className="flex items-center justify-between text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">
<span>Ingestion</span>
<Icon name="Radio" size={11} className="text-[var(--accent)]" />
</div>
<span className="text-[12.5px] font-semibold text-[var(--text)] font-mono">:4000 (ws)</span>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<div className="flex items-center justify-between text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">
<span>Web & API</span>
<Icon name="LayoutDashboard" size={11} className="text-[var(--accent)]" />
</div>
<span className="text-[12.5px] font-semibold text-[var(--text)] font-mono">:3000 (http)</span>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<div className="flex items-center justify-between text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">
<span>Storage Engine</span>
<Icon name="HardDrive" size={11} className="text-[var(--accent)]" />
</div>
<span className="text-[12.5px] font-semibold text-[var(--text)] font-mono">Rotated CSV</span>
</Card>
<Card compact className="p-2 flex flex-col gap-0.5 bg-[var(--bg-elevated)]">
<div className="flex items-center justify-between text-[8.5px] uppercase tracking-wider text-[var(--text-dim)] font-medium">
<span>Buffer Limit</span>
<Icon name="Cpu" size={11} className="text-[var(--accent)]" />
</div>
<span className="text-[12.5px] font-semibold text-[var(--text)] font-mono">500 rows / 2s</span>
</Card>
</div>
export const Hero: React.FC = () => (
<section aria-labelledby="hero-title" className="border-b border-[var(--border)] py-10 sm:py-14">
<span className="mb-5 inline-flex items-center gap-2 border border-[var(--border-strong)] px-2.5 py-1 text-[11px] uppercase text-[var(--text-muted)]">
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />
Self-hosted event collection
</span>
<h1 id="hero-title" className="mb-4 max-w-[640px] text-[28px] font-medium leading-tight text-[var(--text)] sm:text-[36px]">
Realtime data collection,<br />
<span className="text-[var(--text-muted)]">without the operational clutter.</span>
</h1>
<p className="mb-6 max-w-[520px] text-[15px] leading-relaxed text-[var(--text-muted)]">
Keep activity organized, review the records that matter, and export them when you need them.
</p>
<div className="flex flex-wrap gap-2">
<Link href="#features">
<Button variant="primary" size="sm">Explore features</Button>
</Link>
<Link href="#sdk">
<Button variant="secondary" size="sm">Python SDK</Button>
</Link>
</div>
);
};
<ActivityPreview />
</section>
);
export default Hero;
+17
View File
@@ -0,0 +1,17 @@
import { Button } from '@/components/ui/Button';
import Link from 'next/link';
import React from 'react';
export const LandingAbout: React.FC = () => (
<section id="about" className="flex flex-wrap items-center justify-between gap-6 py-10">
<div>
<h2 className="mb-1 text-[20px] font-medium text-[var(--text)]">Ready to simplify your data workflow?</h2>
<p className="text-[13px] text-[var(--text-muted)]">Start with the SDK guide and make the workspace your own.</p>
</div>
<Link href="#sdk">
<Button variant="primary" size="sm">View Python SDK</Button>
</Link>
</section>
);
export default LandingAbout;
+132
View File
@@ -0,0 +1,132 @@
'use client';
import { Button } from '@/components/ui/Button';
import { CopyButton } from '@/components/ui/CopyButton';
import { Input, Textarea } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import { useToast } from '@/components/ui/Toast';
import { useState } from 'react';
import type { ClientCredentials } from './clients/types';
interface NewClientModalProps {
open: boolean;
onClose: () => void;
onCreated: () => Promise<void>;
}
export function NewClientModal({ open, onClose, onCreated }: NewClientModalProps) {
const { success, error } = useToast();
const [clientId, setClientId] = useState('');
const [name, setName] = useState('');
const [rateLimit, setRateLimit] = useState('100');
const [submitting, setSubmitting] = useState(false);
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
const createClient = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSubmitting(true);
try {
const response = await fetch('/api/clients', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: clientId.trim(), name: name.trim(), rateLimit: Number(rateLimit) || 100 }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Client registration failed');
setCredentials(data.client as ClientCredentials);
setClientId('');
setName('');
setRateLimit('100');
onClose();
success('Client registered', `${data.client.clientId} is ready to connect.`);
await onCreated();
} catch (createError) {
error('Registration failed', createError instanceof Error ? createError.message : 'Unknown error');
} finally {
setSubmitting(false);
}
};
return (
<>
<Modal
isOpen={open}
onClose={onClose}
title="Create client"
maxWidth="xs"
footer={
<>
<Button type="button" variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
<Button type="submit" form="new-client-form" variant="primary" size="sm" loading={submitting}>Create client</Button>
</>
}
>
<form id="new-client-form" onSubmit={createClient} className="flex flex-col gap-3.5">
<Input
compact
label="Client ID"
placeholder="e.g. py_order_service_04"
value={clientId}
onChange={(event) => setClientId(event.target.value)}
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
required
/>
<Input
compact
label="Client name"
placeholder="e.g. Order Service"
value={name}
onChange={(event) => setName(event.target.value)}
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
required
/>
<Input
compact
label="Rate limit (requests per second)"
type="number"
min="1"
max="5000"
value={rateLimit}
onChange={(event) => setRateLimit(event.target.value)}
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
/>
</form>
</Modal>
<Modal
isOpen={Boolean(credentials)}
onClose={() => setCredentials(null)}
title={`Credentials: ${credentials?.clientId || ''}`}
description="Copy these credentials now. The secret is only shown after creation."
footer={<Button type="button" size="sm" onClick={() => setCredentials(null)}>Close</Button>}
>
{credentials && (
<div className="flex flex-col gap-3">
<Credential label="Client ID" value={credentials.clientId} />
<Credential label="Client secret key" value={credentials.secret} />
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<label htmlFor="new-client-token" className="text-xs uppercase text-[var(--text-faint)]">JWT handshake bearer token</label>
<CopyButton value={credentials.token} />
</div>
<Textarea id="new-client-token" readOnly value={credentials.token} rows={4} className="font-mono text-xs text-[var(--accent)]" />
</div>
</div>
)}
</Modal>
</>
);
}
function Credential({ label, value }: { label: string; value: string }) {
return (
<div className="flex flex-col gap-1.5">
<span className="text-xs uppercase text-[var(--text-faint)]">{label}</span>
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
<code className="min-w-0 truncate font-mono text-xs text-[var(--text)]">{value}</code>
<CopyButton value={value} />
</div>
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import { CodeBlock } from '@/components/ui/CodeBlock';
import { SectionHeading } from '@/components/ui/SectionHeading';
import React from 'react';
export const SdkSection: React.FC = () => (
<section id="sdk" className="border-b border-[var(--border)] py-10">
<SectionHeading index="02" label="Python SDK" title="Drop in the SDK. Start streaming." />
<div className="grid grid-cols-1 gap-px border border-[var(--border)] bg-[var(--border)] md:grid-cols-2">
<CodeBlock>
<span className="text-[var(--text-faint)]"># Install the client</span>{'\n'}
<span className="text-[var(--text)]">pip install ./sdk-python</span>{'\n\n'}
<span className="text-[var(--text-faint)]"># Send an event</span>{'\n'}
<span className="text-[var(--text)]">from datastack_sdk import DataStackClient</span>{'\n\n'}
<span className="text-[var(--text)]">client = DataStackClient(</span>{'\n'}
{' '}server_url=<span className="text-[var(--accent)]">&quot;YOUR_SERVER_URL&quot;</span>,{'\n'}
{' '}token=<span className="text-[var(--accent)]">&quot;YOUR_CLIENT_TOKEN&quot;</span>,{'\n'}
<span className="text-[var(--text)]">)</span>{'\n\n'}
<span className="text-[var(--text)]">if client.connect():</span>{'\n'}
{' '}client.sync({'{'}<span className="text-[var(--accent)]">&quot;event&quot;</span>: <span className="text-[var(--accent)]">&quot;package_received&quot;</span>{'}'}){'\n'}
{' '}client.disconnect()
</CodeBlock>
<div className="bg-[var(--surface)] p-5 sm:p-6">
<p className="mb-2 text-[11px] uppercase text-[var(--text-faint)]">How it works</p>
<h3 className="mb-2 text-[14px] font-medium text-[var(--text)]">A small client. A clear workflow.</h3>
<p className="text-[12px] leading-relaxed text-[var(--text-muted)]">
Connect a Python source, send individual or batched events, then review and export activity from one workspace.
</p>
</div>
</div>
</section>
);
export default SdkSection;
+273
View File
@@ -0,0 +1,273 @@
'use client';
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 { useToast } from '@/components/ui/Toast';
import { useEffect, useMemo, useState } from 'react';
interface EditableSettings {
maxEventsPerSec: number;
maxPayloadSizeKb: number;
batchFlushThreshold: number;
batchFlushIntervalMs: number;
fileRotationMb: number;
enableIdempotency: boolean;
autoPruneDays: number;
}
interface PublicSettings extends EditableSettings {
serverPort: number;
webPort: number;
updatedAt: string;
}
const DEFAULT_SETTINGS: EditableSettings = {
maxEventsPerSec: 100,
maxPayloadSizeKb: 100,
batchFlushThreshold: 500,
batchFlushIntervalMs: 2000,
fileRotationMb: 100,
enableIdempotency: true,
autoPruneDays: 30,
};
const TABS = [
{ id: 'general', label: 'General' },
{ id: 'connections', label: 'Connections' },
{ id: 'storage', label: 'Storage' },
{ id: 'security', label: 'Security' },
{ id: 'notifications', label: 'Notifications' },
];
type TabId = (typeof TABS)[number]['id'];
export function SettingsWorkspace() {
const { success, error } = useToast();
const [settings, setSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
const [savedSettings, setSavedSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
const [activeTab, setActiveTab] = useState<TabId>('general');
const [jwtSecret, setJwtSecret] = useState('');
const [storagePath, setStoragePath] = useState('');
const [baseUrl, setBaseUrl] = useState('');
const [webSocketUrl, setWebSocketUrl] = useState('');
const [serverPort, setServerPort] = useState(4000);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
useEffect(() => {
setBaseUrl(window.location.origin);
setWebSocketUrl(`${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.hostname}:4000`);
Promise.all([
fetch('/api/settings').then(async (response) => {
if (!response.ok) throw new Error('Unable to load settings');
return response.json();
}),
fetch('/api/storage').then(async (response) => {
if (!response.ok) throw new Error('Unable to load storage information');
return response.json();
}),
])
.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),
};
setSettings(loaded);
setSavedSettings(loaded);
setServerPort(Number((settingsData.settings as PublicSettings).serverPort ?? 4000));
setStoragePath(String(storageData.stats?.storageDirectory ?? ''));
})
.catch((loadError) => {
error('Settings unavailable', loadError instanceof Error ? loadError.message : 'Unable to load settings');
})
.finally(() => setLoading(false));
}, [error]);
const isDirty = useMemo(
() => jwtSecret.trim().length > 0 || JSON.stringify(settings) !== JSON.stringify(savedSettings),
[jwtSecret, savedSettings, settings]
);
const updateNumber = (key: keyof EditableSettings, value: string) => {
setSettings((current) => ({ ...current, [key]: Number(value) || 0 }));
};
const saveSettings = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSaving(true);
try {
const response = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...settings,
...(jwtSecret.trim() ? { jwtSecret: jwtSecret.trim() } : {}),
}),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Settings update failed');
setSavedSettings(settings);
setJwtSecret('');
success('Settings saved', 'Supported runtime settings have been applied.');
} catch (saveError) {
error('Save failed', saveError instanceof Error ? saveError.message : 'Unable to save settings');
} finally {
setSaving(false);
}
};
const discardChanges = () => {
setSettings(savedSettings);
setJwtSecret('');
};
return (
<section className="mx-auto w-full max-w-[var(--container-width)]">
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
<span>Console</span>
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
<span aria-current="page" className="text-[var(--text)]">Settings</span>
</nav>
<header className="mb-4">
<h1 className="text-base font-medium tracking-tight text-[var(--text)]">Settings</h1>
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Configure your DataStack instance</p>
</header>
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
<form onSubmit={saveSettings}>
<div
id={`settings-panel-${activeTab}`}
role="tabpanel"
aria-labelledby={`settings-tab-${activeTab}`}
className="border border-t-0 border-[var(--border)] bg-[var(--surface)]"
>
{loading ? (
<p className="p-4 text-xs text-[var(--text-faint)]">Loading settings...</p>
) : (
<>
{activeTab === 'general' && (
<>
<SettingsGroup title="Identity">
<SettingsField label="Instance name" hint="Shown in dashboard headers and emails">
<Input compact value="DataStack" readOnly className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="Base URL" hint="Current browser origin">
<Input compact value={baseUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="Instance ID" hint="Instance identifier is not configured">
<Input compact value="Not configured" readOnly className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]" />
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Throughput">
<SettingsField label="Events per second" hint="Global cap; client limits may be lower">
<Input compact type="number" min="1" max="10000" value={settings.maxEventsPerSec} onChange={(event) => updateNumber('maxEventsPerSec', event.target.value)} />
</SettingsField>
<SettingsField label="Enable idempotency" hint="Reject duplicate clientId + eventId combinations">
<FormSwitch label="Deduplicate incoming events" checked={settings.enableIdempotency} onChange={(enableIdempotency) => setSettings((current) => ({ ...current, enableIdempotency }))} />
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'connections' && (
<>
<SettingsGroup title="WebSocket server">
<SettingsField label="Public WebSocket URL" hint="Clients connect through the configured host">
<Input compact value={webSocketUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="Socket port" hint="Express process 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" hint="Write buffered rows to CSV at this count">
<Input compact type="number" min="1" value={settings.batchFlushThreshold} onChange={(event) => updateNumber('batchFlushThreshold', event.target.value)} />
</SettingsField>
<SettingsField label="Flush interval" hint="Maximum time before buffered rows are written">
<div className="flex items-center gap-0">
<Input compact type="number" min="100" value={settings.batchFlushIntervalMs} onChange={(event) => updateNumber('batchFlushIntervalMs', event.target.value)} className="border-[var(--border)] font-mono" />
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">ms</span>
</div>
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'storage' && (
<>
<SettingsGroup title="CSV files">
<SettingsField label="Root path" hint="Current server storage directory">
<Input compact value={storagePath || 'Unavailable'} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="File rotation" hint="Files rotate daily and at the configured size limit">
<div className="flex items-center gap-0">
<Input compact type="number" min="1" value={settings.fileRotationMb} onChange={(event) => updateNumber('fileRotationMb', event.target.value)} className="border-[var(--border)] font-mono" />
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">MB</span>
</div>
</SettingsField>
<SettingsField label="Retention" hint="Retention value is stored; automatic pruning is not enabled">
<div className="flex items-center gap-0">
<Input compact type="number" min="1" max="365" value={settings.autoPruneDays} onChange={(event) => updateNumber('autoPruneDays', event.target.value)} className="border-[var(--border)] font-mono" />
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">days</span>
</div>
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Schema">
<SettingsField label="Row format" hint="Fixed CSV schema">
<Input compact value="clientId, eventId, timestamp, payload" readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'security' && (
<>
<SettingsGroup title="Authentication">
<SettingsField label="JWT secret" hint="Changing the secret invalidates existing client tokens">
<Input compact type="password" autoComplete="new-password" value={jwtSecret} onChange={(event) => setJwtSecret(event.target.value)} placeholder="Leave blank to keep the current secret" />
</SettingsField>
<SettingsField label="Payload size limit" hint="Maximum accepted event payload size">
<div className="flex items-center gap-0">
<Input compact type="number" min="1" max="5120" value={settings.maxPayloadSizeKb} onChange={(event) => updateNumber('maxPayloadSizeKb', event.target.value)} className="border-[var(--border)] font-mono" />
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">KB</span>
</div>
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Configuration">
<p className="text-xs leading-relaxed text-[var(--text-faint)]">Allowed origins and token expiration are controlled by deployment configuration and are not editable from this console.</p>
</SettingsGroup>
</>
)}
{activeTab === 'notifications' && (
<SettingsGroup title="Delivery">
<p className="text-xs leading-relaxed text-[var(--text-faint)]">Email and webhook notification delivery are not configured for this instance.</p>
</SettingsGroup>
)}
</>
)}
</div>
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-4 py-2.5">
<div className="flex flex-1 items-center gap-1.5 text-xs text-[var(--text-muted)]" role="status">
<span className={`h-1.5 w-1.5 ${isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'}`} />
{loading ? 'Loading settings' : isDirty ? 'Unsaved changes' : 'All changes 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 changes</Button>
</footer>
</form>
<p className="mt-3 text-[11px] text-[var(--text-faint)]">Some settings require a service restart to take effect.</p>
</section>
);
}
+16
View File
@@ -0,0 +1,16 @@
export interface ClientItem {
clientId: string;
name: string;
rateLimit: number;
status: "active" | "revoked";
totalEvents: number;
lastActive?: string;
createdAt: string;
}
export interface ClientCredentials extends ClientItem {
secret: string;
token: string;
}
export type ClientStatusFilter = "all" | "online" | "offline" | "pending";
+8
View File
@@ -0,0 +1,8 @@
export * from "./AdminLogin";
export * from "./ClientsFilters";
export * from "./ClientsManager";
export * from "./ClientsTable";
export * from "./DataBrowser";
export * from "./ExportWorkspace";
export * from "./NewClientModal";
export * from "./SettingsWorkspace";
+35
View File
@@ -0,0 +1,35 @@
import React from 'react';
const sampleRows = [
{ time: '14:28:01', source: 'Source A', payload: '{ metric: "temperature", value: 22.4 }', size: '42 B' },
{ time: '14:28:01', source: 'Source B', payload: '{ action: "package_received", count: 3 }', size: '38 B' },
{ time: '14:28:02', source: 'Source A', payload: '{ metric: "humidity", value: 61 }', size: '40 B' },
{ time: '14:28:02', source: 'Source C', payload: '{ status: "complete", duration_ms: 184 }', size: '44 B' },
];
export const ActivityPreview: React.FC = () => (
<section aria-label="Example activity" className="mt-8 overflow-hidden border border-[var(--border)] bg-[var(--surface)]">
<div className="flex items-center justify-between gap-3 border-b border-[var(--border)] px-3 py-2.5 sm:px-4">
<div className="flex items-center gap-2 text-[12px] text-[var(--text-muted)]">
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />
Example activity
</div>
<span className="text-[11px] text-[var(--text-faint)]">Sample records</span>
</div>
<div className="divide-y divide-[var(--border)]">
{sampleRows.map((row) => (
<div
key={`${row.time}-${row.source}-${row.payload}`}
className="grid grid-cols-[4.5rem_minmax(0,1fr)_3rem] items-center gap-x-3 px-3 py-2 font-mono text-[11px] sm:grid-cols-[5rem_6rem_minmax(0,1fr)_3.5rem] sm:px-4"
>
<span className="text-[var(--text-faint)]">{row.time}</span>
<span className="hidden text-[var(--accent)] sm:block">{row.source}</span>
<span className="truncate text-[var(--text)]">{row.payload}</span>
<span className="text-right text-[var(--text-faint)]">{row.size}</span>
</div>
))}
</div>
</section>
);
export default ActivityPreview;
+6 -6
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { cn } from '@/lib/utils';
import React from 'react';
import { Icon } from './Icon';
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
@@ -30,7 +30,7 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
const variantStyles = {
primary:
'bg-[var(--accent)] text-[var(--text-on-accent)] hover:bg-[var(--accent-hover)] border-[var(--accent)]',
'bg-[var(--text)] text-[var(--bg)] hover:opacity-90 border-[var(--text)]',
secondary:
'bg-[var(--bg-elevated)] text-[var(--text)] border-[var(--border-strong)] hover:bg-[var(--bg-hover)]',
ghost:
@@ -42,10 +42,10 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
};
const sizeStyles = {
default: 'h-[32px] px-[14px] text-[12.5px] gap-[7px]',
sm: 'h-[27px] px-[10px] text-[11.5px] gap-[5px]',
xs: 'h-[24px] px-[7px] text-[10.5px] gap-[4px]',
icon: 'w-[30px] h-[30px] p-0',
default: 'min-h-10 px-4 text-[13.5px] gap-2',
sm: 'h-9 px-3 text-[12.5px] gap-1.5',
xs: 'h-8 px-2.5 text-[12px] gap-1.5',
icon: 'w-9 h-9 p-0',
};
return (
+8 -8
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { cn } from '@/lib/utils';
import React from 'react';
export interface CardProps extends React.HTMLAttributes<HTMLDivElement> {
variant?: 'default' | 'subtle' | 'dashed' | 'active';
@@ -25,8 +25,8 @@ export const Card: React.FC<CardProps> = ({
className={cn(
'transition-colors',
variantStyles[variant],
compact ? 'p-2.5' : 'p-3.5 sm:p-4',
className
className,
compact ? 'p-4' : 'p-5 sm:p-6'
)}
{...props}
>
@@ -42,7 +42,7 @@ export const CardHeader: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({
}) => (
<div
className={cn(
'flex items-center justify-between gap-2.5 pb-2.5 mb-2.5 border-b border-[var(--border)]',
'flex items-center justify-between gap-3 pb-3 mb-3 border-b border-[var(--border)]',
className
)}
{...props}
@@ -56,7 +56,7 @@ export const CardTitle: React.FC<React.HTMLAttributes<HTMLHeadingElement>> = ({
children,
...props
}) => (
<h3 className={cn('text-[13px] font-semibold text-[var(--text)] leading-tight', className)} {...props}>
<h3 className={cn('text-[15px] font-semibold text-[var(--text)] leading-snug', className)} {...props}>
{children}
</h3>
);
@@ -66,7 +66,7 @@ export const CardDescription: React.FC<React.HTMLAttributes<HTMLParagraphElement
children,
...props
}) => (
<p className={cn('text-[11px] text-[var(--text-muted)] leading-normal', className)} {...props}>
<p className={cn('text-[13px] text-[var(--text-muted)] leading-relaxed', className)} {...props}>
{children}
</p>
);
@@ -76,7 +76,7 @@ export const CardContent: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({
children,
...props
}) => (
<div className={cn('text-[12px]', className)} {...props}>
<div className={cn('text-[14px]', className)} {...props}>
{children}
</div>
);
@@ -88,7 +88,7 @@ export const CardFooter: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({
}) => (
<div
className={cn(
'flex items-center justify-between gap-2 pt-2.5 mt-2.5 border-t border-[var(--border)] text-[11px]',
'flex items-center justify-between gap-3 pt-3 mt-3 border-t border-[var(--border)] text-[13px]',
className
)}
{...props}
+37
View File
@@ -0,0 +1,37 @@
import React from 'react';
export interface ClientListItem {
clientId: string;
name: string;
status: 'active' | 'revoked';
totalEvents: number;
}
interface ClientListProps {
clients: ClientListItem[];
limit?: number;
}
export const ClientList: React.FC<ClientListProps> = ({ clients, limit = 4 }) => (
<div className="divide-y divide-[var(--border)]">
{clients.slice(0, limit).map((client) => (
<div key={client.clientId} className="flex min-w-0 items-center justify-between gap-3 px-4 py-2">
<div className="flex min-w-0 items-center gap-2">
<span className={client.status === 'active' ? 'h-1.5 w-1.5 shrink-0 bg-[var(--accent)]' : 'h-1.5 w-1.5 shrink-0 bg-[var(--text-faint)]'} />
<div className="min-w-0">
<p className="truncate text-[12px] font-medium text-[var(--text)]">{client.name}</p>
<p className="truncate font-mono text-[10px] text-[var(--text-faint)]">{client.clientId}</p>
</div>
</div>
<span className="shrink-0 font-mono text-[11px] text-[var(--text-muted)]">
{client.totalEvents.toLocaleString()}
</span>
</div>
))}
{clients.length === 0 && (
<p className="px-4 py-5 text-[12px] text-[var(--text-faint)]">No registered clients.</p>
)}
</div>
);
export default ClientList;
+14
View File
@@ -0,0 +1,14 @@
import React from 'react';
interface CodeBlockProps {
children: React.ReactNode;
className?: string;
}
export const CodeBlock: React.FC<CodeBlockProps> = ({ children, className = '' }) => (
<pre className={`overflow-x-auto bg-[var(--surface)] p-4 font-mono text-[12px] leading-relaxed text-[var(--text-muted)] ${className}`}>
<code>{children}</code>
</pre>
);
export default CodeBlock;
+49
View File
@@ -0,0 +1,49 @@
'use client';
import { Check, Copy } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
type CopyState = 'idle' | 'copied' | 'failed';
export function CopyButton({ value }: { value: string }) {
const [state, setState] = useState<CopyState>('idle');
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current);
}, []);
const copyValue = async () => {
try {
await navigator.clipboard.writeText(value);
setState('copied');
} catch {
setState('failed');
}
if (timeoutRef.current) clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => setState('idle'), 1200);
};
const label = state === 'copied'
? 'Copied to clipboard'
: state === 'failed'
? 'Clipboard unavailable'
: 'Copy to clipboard';
return (
<button
type="button"
onClick={copyValue}
aria-label={label}
title={label}
className="grid h-5 w-5 shrink-0 place-items-center text-[var(--text-faint)] transition-colors hover:text-[var(--text)]"
>
{state === 'copied'
? <Check className="h-3 w-3" aria-hidden="true" />
: <Copy className="h-3 w-3" aria-hidden="true" />}
</button>
);
}
export default CopyButton;
+20
View File
@@ -0,0 +1,20 @@
import React from 'react';
import { Icon } from './Icon';
interface FeatureItemProps {
icon: string;
title: string;
description: string;
}
export const FeatureItem: React.FC<FeatureItemProps> = ({ icon, title, description }) => (
<article className="min-h-full bg-[var(--surface)] p-5">
<div className="mb-3 grid h-[22px] w-[22px] place-items-center border border-[var(--border-strong)] text-[var(--accent)]">
<Icon name={icon} size={13} />
</div>
<h3 className="mb-1 text-[13px] font-medium text-[var(--text)]">{title}</h3>
<p className="text-[12px] leading-relaxed text-[var(--text-muted)]">{description}</p>
</article>
);
export default FeatureItem;
+8 -8
View File
@@ -1,12 +1,12 @@
import React from 'react';
import { cn } from '@/lib/utils';
import React from 'react';
export const Form: React.FC<React.FormHTMLAttributes<HTMLFormElement>> = ({
className,
children,
...props
}) => (
<form className={cn('flex flex-col gap-3', className)} {...props}>
<form className={cn('flex flex-col gap-5', className)} {...props}>
{children}
</form>
);
@@ -16,7 +16,7 @@ export const FormField: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({
children,
...props
}) => (
<div className={cn('flex flex-col gap-1 w-full', className)} {...props}>
<div className={cn('flex flex-col gap-2 w-full', className)} {...props}>
{children}
</div>
);
@@ -26,7 +26,7 @@ export const FormRow: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({
children,
...props
}) => (
<div className={cn('grid grid-cols-1 sm:grid-cols-2 gap-3 w-full', className)} {...props}>
<div className={cn('grid grid-cols-1 sm:grid-cols-2 gap-4 w-full', className)} {...props}>
{children}
</div>
);
@@ -40,20 +40,20 @@ export const FormSwitch: React.FC<{
}> = ({ label, checked, onChange, description, disabled = false }) => (
<label
className={cn(
'flex items-center justify-between p-2.5 border border-[var(--border)] bg-[var(--bg-main)] cursor-pointer select-none transition-colors hover:bg-[var(--bg-hover)]',
'flex items-center justify-between gap-4 p-4 border border-[var(--border)] bg-[var(--bg-main)] cursor-pointer select-none transition-colors hover:bg-[var(--bg-hover)]',
disabled && 'opacity-50 cursor-not-allowed'
)}
>
<div className="flex flex-col">
<span className="text-[12px] font-medium text-[var(--text)]">{label}</span>
{description && <span className="text-[10.5px] text-[var(--text-dim)]">{description}</span>}
<span className="text-[14px] font-medium text-[var(--text)]">{label}</span>
{description && <span className="text-[12px] text-[var(--text-muted)]">{description}</span>}
</div>
<input
type="checkbox"
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
className="w-4 h-4 accent-[var(--accent)] cursor-pointer"
className="w-5 h-5 accent-[var(--accent)] cursor-pointer shrink-0"
/>
</label>
);
+10 -10
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { cn } from '@/lib/utils';
import React from 'react';
import { Icon } from './Icon';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
@@ -18,7 +18,7 @@ export const Input = React.forwardRef<HTMLInputElement, InputProps>(
{label && (
<label
htmlFor={inputId}
className="text-[10.5px] font-semibold text-[var(--text-muted)] uppercase tracking-wider"
className="text-[12px] font-medium text-[var(--text-muted)]"
>
{label}
</label>
@@ -34,7 +34,7 @@ export const Input = React.forwardRef<HTMLInputElement, InputProps>(
ref={ref}
className={cn(
'w-full bg-[var(--bg-main)] text-[var(--text)] border border-[var(--border-strong)] placeholder:text-[var(--text-dim)] transition-colors focus:outline-none focus:border-[var(--accent)] disabled:opacity-50 disabled:cursor-not-allowed',
compact ? 'h-[28px] px-2 text-[11px]' : 'h-[32px] px-2.5 text-[12px]',
compact ? 'h-9 px-3 text-[13px]' : 'h-10 px-3.5 text-[14px]',
icon && 'pl-8',
error && 'border-[var(--danger)]',
className
@@ -42,7 +42,7 @@ export const Input = React.forwardRef<HTMLInputElement, InputProps>(
{...props}
/>
</div>
{error && <span className="text-[10.5px] text-[var(--danger)]">{error}</span>}
{error && <span className="text-[12px] text-[var(--danger)]">{error}</span>}
</div>
);
}
@@ -64,7 +64,7 @@ export const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
{label && (
<label
htmlFor={textareaId}
className="text-[10.5px] font-semibold text-[var(--text-muted)] uppercase tracking-wider"
className="text-[12px] font-medium text-[var(--text-muted)]"
>
{label}
</label>
@@ -73,13 +73,13 @@ export const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
id={textareaId}
ref={ref}
className={cn(
'w-full bg-[var(--bg-main)] text-[var(--text)] border border-[var(--border-strong)] p-2.5 text-[12px] placeholder:text-[var(--text-dim)] focus:outline-none focus:border-[var(--accent)] min-h-[64px] resize-y font-mono',
'w-full bg-[var(--bg-main)] text-[var(--text)] border border-[var(--border-strong)] p-3.5 text-[14px] placeholder:text-[var(--text-dim)] focus:outline-none focus:border-[var(--accent)] min-h-[96px] resize-y font-mono',
error && 'border-[var(--danger)]',
className
)}
{...props}
/>
{error && <span className="text-[10.5px] text-[var(--danger)]">{error}</span>}
{error && <span className="text-[12px] text-[var(--danger)]">{error}</span>}
</div>
);
}
@@ -103,7 +103,7 @@ export const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
{label && (
<label
htmlFor={selectId}
className="text-[10.5px] font-semibold text-[var(--text-muted)] uppercase tracking-wider"
className="text-[12px] font-medium text-[var(--text-muted)]"
>
{label}
</label>
@@ -113,7 +113,7 @@ export const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
ref={ref}
className={cn(
'w-full bg-[var(--bg-main)] text-[var(--text)] border border-[var(--border-strong)] focus:outline-none focus:border-[var(--accent)] cursor-pointer',
compact ? 'h-[28px] px-1.5 text-[11px]' : 'h-[32px] px-2 text-[11.5px]',
compact ? 'h-9 px-2.5 text-[13px]' : 'h-10 px-3 text-[14px]',
error && 'border-[var(--danger)]',
className
)}
@@ -127,7 +127,7 @@ export const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
))
: children}
</select>
{error && <span className="text-[10.5px] text-[var(--danger)]">{error}</span>}
{error && <span className="text-[12px] text-[var(--danger)]">{error}</span>}
</div>
);
}
+15 -14
View File
@@ -1,7 +1,7 @@
import React, { useEffect } from 'react';
import { cn } from '@/lib/utils';
import { Icon } from './Icon';
import React, { useEffect } from 'react';
import { Button } from './Button';
import { Icon } from './Icon';
export interface ModalProps {
isOpen: boolean;
@@ -10,7 +10,7 @@ export interface ModalProps {
description?: string;
children: React.ReactNode;
footer?: React.ReactNode;
maxWidth?: 'sm' | 'md' | 'lg';
maxWidth?: 'xs' | 'sm' | 'md' | 'lg';
}
export const Modal: React.FC<ModalProps> = ({
@@ -41,24 +41,25 @@ export const Modal: React.FC<ModalProps> = ({
if (!isOpen) return null;
const maxWidthStyles = {
sm: 'max-w-[440px]',
md: 'max-w-[520px]',
lg: 'max-w-[640px]',
xs: 'max-w-[440px]',
sm: 'max-w-[480px]',
md: 'max-w-[640px]',
lg: 'max-w-[800px]',
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-3.5 bg-black/60 backdrop-blur-[1px]">
<div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-6 bg-black/60">
<div
className={cn(
'w-full bg-[var(--bg-elevated)] border border-[var(--border-strong)] text-[var(--text)] flex flex-col max-h-[min(84dvh,680px)] overflow-hidden animate-in fade-in zoom-in-95 duration-100',
'w-full bg-[var(--bg-elevated)] border border-[var(--border-strong)] text-[var(--text)] flex flex-col max-h-[calc(100dvh-1.5rem)] sm:max-h-[min(88dvh,800px)] overflow-hidden animate-in fade-in zoom-in-95 duration-150',
maxWidthStyles[maxWidth]
)}
>
<div className="flex items-start justify-between gap-3 p-3.5 sm:px-4 sm:py-3.5 border-b border-[var(--border)] shrink-0">
<div className="flex items-start justify-between gap-4 p-4 sm:px-6 sm:py-5 border-b border-[var(--border)] shrink-0">
<div className="min-w-0">
<h2 className="text-[14px] font-semibold text-[var(--text)] leading-tight">{title}</h2>
<h2 className="text-[18px] font-semibold text-[var(--text)] leading-snug">{title}</h2>
{description && (
<p className="text-[11px] text-[var(--text-muted)] mt-1">{description}</p>
<p className="text-[13px] text-[var(--text-muted)] mt-1.5">{description}</p>
)}
</div>
<Button
@@ -66,18 +67,18 @@ export const Modal: React.FC<ModalProps> = ({
variant="ghost"
onClick={onClose}
aria-label="Close dialog"
className="w-7 h-7 text-[var(--text-dim)] hover:text-[var(--text)]"
className="w-9 h-9 text-[var(--text-dim)] hover:text-[var(--text)]"
>
<Icon name="X" size={14} />
</Button>
</div>
<div className="p-3.5 sm:p-4 overflow-y-auto flex-1 text-[12px] flex flex-col gap-3">
<div className="p-4 sm:p-6 overflow-y-auto flex-1 text-[14px] flex flex-col gap-4">
{children}
</div>
{footer && (
<div className="flex items-center justify-end gap-2 p-3 sm:px-4 border-t border-[var(--border)] bg-[var(--bg-sidebar)] shrink-0">
<div className="flex flex-wrap items-center justify-end gap-2 p-4 sm:px-6 border-t border-[var(--border)] bg-[var(--bg-sidebar)] shrink-0">
{footer}
</div>
)}
+33
View File
@@ -0,0 +1,33 @@
import { cn } from '@/lib/utils';
import React from 'react';
interface PanelProps extends React.HTMLAttributes<HTMLElement> {
title: string;
action?: React.ReactNode;
meta?: string;
children: React.ReactNode;
bodyClassName?: string;
}
export const Panel: React.FC<PanelProps> = ({
title,
action,
meta,
children,
className,
bodyClassName,
...props
}) => (
<section className={cn('flex min-w-0 flex-col border border-[var(--border)] bg-[var(--surface)]', className)} {...props}>
<header className="flex min-h-11 items-center justify-between gap-3 border-b border-[var(--border)] px-4 py-2.5">
<h2 className="text-[12px] font-medium text-[var(--text)]">{title}</h2>
<div className="flex items-center gap-3">
{meta && <span className="text-[11px] text-[var(--text-faint)]">{meta}</span>}
{action}
</div>
</header>
<div className={cn('min-w-0', bodyClassName)}>{children}</div>
</section>
);
export default Panel;
+29
View File
@@ -0,0 +1,29 @@
import { cn } from '@/lib/utils';
import React from 'react';
export interface PillProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
active?: boolean;
}
export const Pill = React.forwardRef<HTMLButtonElement, PillProps>(
({ active = false, className, children, type = 'button', ...props }, ref) => (
<button
ref={ref}
type={type}
className={cn(
'inline-flex h-[26px] shrink-0 items-center gap-1.5 border px-2.5 text-[11.5px] transition-colors disabled:cursor-not-allowed disabled:opacity-50',
active
? 'border-[var(--border-strong)] bg-[var(--surface-2)] text-[var(--text)]'
: 'border-[var(--border)] bg-transparent text-[var(--text-muted)] hover:bg-[var(--surface-2)] hover:text-[var(--text)]',
className
)}
{...props}
>
{children}
</button>
)
);
Pill.displayName = 'Pill';
export default Pill;
+18
View File
@@ -0,0 +1,18 @@
import React from 'react';
interface SectionHeadingProps {
index: string;
label: string;
title: string;
}
export const SectionHeading: React.FC<SectionHeadingProps> = ({ index, label, title }) => (
<div className="mb-5 flex items-baseline justify-between gap-4">
<h2 className="text-[16px] font-medium text-[var(--text)]">{title}</h2>
<span className="shrink-0 text-[11px] uppercase text-[var(--text-faint)]">
{index} / {label}
</span>
</div>
);
export default SectionHeading;
+72
View File
@@ -0,0 +1,72 @@
import React from 'react';
export interface SettingsTabItem {
id: string;
label: string;
}
export function SettingsTabs({
items,
value,
onChange,
}: {
items: SettingsTabItem[];
value: string;
onChange: (value: string) => void;
}) {
return (
<div className="flex overflow-x-auto border-b border-[var(--border)]" role="tablist" aria-label="Settings categories">
{items.map((item) => (
<button
key={item.id}
id={`settings-tab-${item.id}`}
type="button"
role="tab"
aria-selected={value === item.id}
aria-controls={`settings-panel-${item.id}`}
className={`mb-[-1px] shrink-0 border-b-2 px-3.5 py-2.5 text-xs transition-colors ${value === item.id ? 'border-[var(--accent)] text-[var(--text)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'}`}
onClick={() => onChange(item.id)}
>
{item.label}
</button>
))}
</div>
);
}
export function SettingsGroup({
title,
children,
}: {
title: string;
children: React.ReactNode;
}) {
return (
<section className="border-b border-[var(--border)] p-4 last:border-b-0">
<h2 className="mb-3 flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
{title}
</h2>
<div className="flex flex-col">{children}</div>
</section>
);
}
export function SettingsField({
label,
hint,
children,
}: {
label: string;
hint?: string;
children: React.ReactNode;
}) {
return (
<div className="grid grid-cols-1 items-start gap-1.5 py-2 sm:grid-cols-[1fr_2fr] sm:gap-5">
<div className="min-w-0 pt-px">
<div className="text-[12.5px] leading-snug text-[var(--text)]">{label}</div>
{hint && <div className="mt-0.5 text-[11px] leading-normal text-[var(--text-faint)]">{hint}</div>}
</div>
<div className="min-w-0">{children}</div>
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import React from 'react';
import { Card } from './Card';
interface StatCardProps {
label: string;
value: string | number;
unit?: string;
meta: string;
}
export const StatCard: React.FC<StatCardProps> = ({ label, value, unit, meta }) => (
<Card compact className="bg-[var(--surface)]">
<div className="mb-1.5 text-[10px] uppercase text-[var(--text-faint)]">{label}</div>
<div className="text-[22px] font-medium leading-tight text-[var(--text)]">
{value}
{unit && <span className="ml-1 text-[11px] font-normal text-[var(--text-muted)]">{unit}</span>}
</div>
<div className="mt-2 text-[11px] text-[var(--text-muted)]">{meta}</div>
</Card>
);
export default StatCard;
+28
View File
@@ -0,0 +1,28 @@
import type { ReactNode } from 'react';
type Dot = 'ok' | 'off' | 'pending';
type Item = { label: string; value: ReactNode; dot?: Dot };
const DOT_CLASS: Record<Dot, string> = {
ok: 'bg-[var(--accent)]',
off: 'bg-[var(--text-faint)]',
pending: 'bg-[var(--warning)]',
};
export function StatStrip({ items }: { items: Item[] }) {
return (
<div className="mb-4 grid grid-cols-2 gap-px border border-[var(--border)] bg-[var(--border)] md:grid-cols-4">
{items.map((item) => (
<div key={item.label} className="bg-[var(--surface)] px-4 py-3">
<div className="mb-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
{item.label}
</div>
<div className="flex items-center gap-2 text-lg font-medium leading-none tracking-tight text-[var(--text)]">
{item.dot && <span aria-hidden="true" className={`h-1.5 w-1.5 ${DOT_CLASS[item.dot]}`} />}
{item.value}
</div>
</div>
))}
</div>
);
}
+6 -6
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { cn } from '@/lib/utils';
import React from 'react';
export const TableWrap: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({
className,
@@ -24,7 +24,7 @@ export const Table: React.FC<React.TableHTMLAttributes<HTMLTableElement>> = ({
}) => (
<table
className={cn(
'w-full min-w-[540px] border-collapse text-left text-[11px] whitespace-nowrap',
'w-full min-w-[680px] border-collapse text-left text-[13px] whitespace-nowrap',
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-[9.5px] font-semibold text-[var(--text-dim)] uppercase tracking-wider',
'bg-[var(--bg-sidebar)] border-b border-[var(--border)] text-[12px] font-medium text-[var(--text-muted)] uppercase',
className
)}
{...props}
@@ -76,7 +76,7 @@ export const TableHead: React.FC<React.ThHTMLAttributes<HTMLTableCellElement>> =
children,
...props
}) => (
<th className={cn('px-2.5 py-1.5 font-medium', className)} {...props}>
<th className={cn('px-3 py-2.5 font-medium', className)} {...props}>
{children}
</th>
);
@@ -86,7 +86,7 @@ export const TableCell: React.FC<React.TdHTMLAttributes<HTMLTableCellElement>> =
children,
...props
}) => (
<td className={cn('px-2.5 py-1.5 text-[var(--text-muted)] align-middle', className)} {...props}>
<td className={cn('px-3 py-2.5 text-[var(--text-muted)] align-middle', className)} {...props}>
{children}
</td>
);
@@ -98,7 +98,7 @@ export const TableEmpty: React.FC<{ colSpan: number; message?: string }> = ({
<tr>
<td
colSpan={colSpan}
className="px-3 py-6 text-center text-[10.5px] text-[var(--text-dim)] italic"
className="px-4 py-10 text-center text-[13px] text-[var(--text-dim)]"
>
{message}
</td>
+10 -10
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { cn } from '@/lib/utils';
import React from 'react';
interface TextProps extends React.HTMLAttributes<HTMLElement> {
as?: 'h1' | 'h2' | 'h3' | 'h4' | 'p' | 'span' | 'label' | 'code' | 'div';
@@ -15,15 +15,15 @@ export const Text: React.FC<TextProps> = ({
...props
}) => {
const variantStyles = {
h1: 'text-[18px] font-semibold tracking-tight text-[var(--text)]',
h2: 'text-[15px] font-semibold text-[var(--text)]',
h3: 'text-[13px] font-medium text-[var(--text)]',
body: 'text-[12.5px] font-normal text-[var(--text)]',
muted: 'text-[11.5px] font-normal text-[var(--text-muted)]',
dim: 'text-[10.5px] font-normal text-[var(--text-dim)]',
label: 'text-[11px] font-medium uppercase tracking-wider text-[var(--text-dim)]',
code: 'text-[11px] font-mono text-[var(--accent)] bg-[var(--bg-hover)] px-1.5 py-0.5 border border-[var(--border)]',
badge: 'text-[10px] font-medium px-1.5 py-0.5 border border-[var(--border)] text-[var(--text-muted)] inline-flex items-center gap-1',
h1: 'text-[24px] font-semibold text-[var(--text)]',
h2: 'text-[20px] font-semibold text-[var(--text)]',
h3: 'text-[17px] font-medium text-[var(--text)]',
body: 'text-[14px] font-normal text-[var(--text)]',
muted: 'text-[13px] font-normal text-[var(--text-muted)]',
dim: 'text-[12px] font-normal text-[var(--text-dim)]',
label: 'text-[12px] font-medium uppercase text-[var(--text-muted)]',
code: 'text-[12px] font-mono text-[var(--accent)] bg-[var(--bg-hover)] px-2 py-1 border border-[var(--border)]',
badge: 'text-[11.5px] font-medium px-2 py-1 border border-[var(--border)] text-[var(--text-muted)] inline-flex items-center gap-1',
};
return (
+5 -5
View File
@@ -1,7 +1,7 @@
'use client';
import React, { createContext, useContext, useState, useCallback } from 'react';
import { cn } from '@/lib/utils';
import React, { createContext, useCallback, useContext, useState } from 'react';
import { Icon } from './Icon';
export type ToastType = 'success' | 'error' | 'warning' | 'info';
@@ -53,7 +53,7 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre
return (
<ToastContext.Provider value={{ toast: addToast, success, error, warning, info }}>
{children}
<div className="fixed bottom-4 right-4 z-[9999] flex flex-col gap-2 max-w-[340px] pointer-events-none">
<div className="fixed bottom-4 left-4 right-4 sm:left-auto sm:right-6 sm:bottom-6 z-[9999] flex flex-col gap-2 max-w-[420px] pointer-events-none">
{toasts.map((t) => {
const typeBorder = {
success: 'border-l-[3px] border-l-[var(--success)]',
@@ -80,17 +80,17 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre
<div
key={t.id}
className={cn(
'pointer-events-auto flex items-start gap-2.5 p-3 bg-[var(--bg-elevated)] border border-[var(--border-strong)] text-[var(--text)] text-[12px] transition-all',
'pointer-events-auto flex items-start gap-3 p-4 bg-[var(--bg-elevated)] border border-[var(--border-strong)] text-[var(--text)] text-[13px] transition-all',
typeBorder
)}
>
<div className="mt-0.5 shrink-0">
<Icon name={typeIcon} size={14} color={iconColor} />
<Icon name={typeIcon} size={17} color={iconColor} />
</div>
<div className="flex-1 min-w-0">
<div className="font-medium text-[var(--text)] leading-tight">{t.title}</div>
{t.message && (
<div className="text-[11px] text-[var(--text-muted)] mt-0.5 leading-normal break-words">
<div className="text-[12px] text-[var(--text-muted)] mt-1 leading-normal break-words">
{t.message}
</div>
)}
+20 -9
View File
@@ -1,9 +1,20 @@
export * from './Button';
export * from './Input';
export * from './Card';
export * from './Modal';
export * from './Table';
export * from './Form';
export * from './Text';
export * from './Icon';
export * from './Toast';
export * from "./ActivityPreview";
export * from "./Button";
export * from "./Card";
export * from "./ClientList";
export * from "./CodeBlock";
export * from "./CopyButton";
export * from "./FeatureItem";
export * from "./Form";
export * from "./Icon";
export * from "./Input";
export * from "./Modal";
export * from "./Panel";
export * from "./Pill";
export * from "./SectionHeading";
export * from "./SettingsLayout";
export * from "./StatCard";
export * from "./StatStrip";
export * from "./Table";
export * from "./Text";
export * from "./Toast";