chore(services): update components based on recent changes
Changes: services/frontend/src/features/dashboard/components/ChannelProfileDetail.tsx | 258 +++++++++++----------------------------------------------------------------- services/frontend/src/features/dashboard/components/ChannelSummaryList.tsx | 171 ++++++++------------------------------------------- services/frontend/src/features/dashboard/components/DashboardStats.tsx | 8 ++- services/frontend/src/features/dashboard/components/UserProfileDetail.tsx | 297 +++++++++++++--------------------------------------------------------------------------- services/frontend/src/features/dashboard/components/UserSummaryList.tsx | 204 +++++++++++------------------------------------------------- services/frontend/src/features/dashboard/hooks/useDashboard.ts | 203 +++++++++++++++--------------------------------------------- services/frontend/src/features/messages/components/MessageCard.tsx | 10 +-- services/frontend/src/shared/api/client.ts | 87 +++++++++++++++++++------- services/frontend/src/shared/hooks/useItemDetail.ts | 58 +++++++++++++++++ services/frontend/src/shared/hooks/usePaginatedList.ts | 105 +++++++++++++++++++++++++++++++
This commit is contained in:
@@ -1,16 +1,6 @@
|
||||
import { motion } from "framer-motion";
|
||||
import { AlertCircle, ArrowLeft, Hash, RefreshCw } from "lucide-react";
|
||||
import { Hash } from "lucide-react";
|
||||
import type { DashboardChannelDetail } from "../../../shared/api/client";
|
||||
import { cardItem, cardStagger } from "../../../shared/hooks/useFramerStagger";
|
||||
import { cn } from "../../../shared/lib/utils";
|
||||
import {
|
||||
Badge,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
Skeleton,
|
||||
} from "../../../shared/ui";
|
||||
import { ProfileDetail } from "../../../shared/ui";
|
||||
|
||||
interface ChannelProfileDetailProps {
|
||||
detail: DashboardChannelDetail | null;
|
||||
@@ -27,218 +17,40 @@ export function ChannelProfileDetail({
|
||||
onBack,
|
||||
onRefetch,
|
||||
}: ChannelProfileDetailProps) {
|
||||
if (!detail && !loading && !error) return null;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="grid gap-6"
|
||||
variants={cardStagger}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
>
|
||||
{/* Back button */}
|
||||
<motion.div variants={cardItem}>
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" /> Back to channels
|
||||
</button>
|
||||
</motion.div>
|
||||
|
||||
{/* Loading */}
|
||||
{loading && <DetailSkeleton />}
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<motion.div
|
||||
variants={cardItem}
|
||||
className="flex flex-col items-center gap-4 py-20 text-muted-foreground"
|
||||
>
|
||||
<AlertCircle className="h-10 w-10 text-destructive" />
|
||||
<p className="text-sm">{error}</p>
|
||||
<button
|
||||
onClick={onRefetch}
|
||||
className="inline-flex items-center gap-1.5 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" /> Retry
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{detail && !error && (
|
||||
<>
|
||||
{/* Channel header */}
|
||||
<motion.div variants={cardItem}>
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-full bg-muted ring-2 ring-border">
|
||||
<Hash className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-lg font-bold">
|
||||
#{detail.channel_name ?? detail.channel_id}
|
||||
</h2>
|
||||
<p className="mt-0.5 truncate font-mono text-xs text-muted-foreground">
|
||||
{detail.channel_id}
|
||||
</p>
|
||||
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
{detail.flagged_count > 0 && (
|
||||
<Badge variant="destructive">
|
||||
{detail.flagged_count} flagged
|
||||
</Badge>
|
||||
)}
|
||||
{detail.culture_summary && (
|
||||
<Badge variant="default">AI Profile</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Culture summary */}
|
||||
{detail.culture_summary && (
|
||||
<div className="mt-4 rounded-lg bg-muted/50 p-3">
|
||||
<p className="text-xs font-medium text-muted-foreground mb-1">
|
||||
AI Channel Summary
|
||||
</p>
|
||||
<p className="text-sm whitespace-pre-wrap">
|
||||
{detail.culture_summary}
|
||||
</p>
|
||||
{detail.last_analyzed_at && (
|
||||
<p className="mt-1 text-[11px] text-muted-foreground">
|
||||
Last analyzed:{" "}
|
||||
{new Date(detail.last_analyzed_at).toLocaleString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* Stats grid */}
|
||||
<motion.div variants={cardItem} className="grid gap-4 sm:grid-cols-3">
|
||||
<Card>
|
||||
<CardContent className="p-4 text-center">
|
||||
<p className="text-2xl font-bold text-primary">
|
||||
{detail.total_messages.toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Total Messages
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4 text-center">
|
||||
<p className="text-2xl font-bold text-emerald-600">
|
||||
{detail.clean_count.toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Clean</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4 text-center">
|
||||
<p
|
||||
className={cn(
|
||||
"text-2xl font-bold",
|
||||
detail.flagged_count > 0
|
||||
? "text-destructive"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{detail.flagged_count.toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Flagged</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* Recent messages */}
|
||||
<motion.div variants={cardItem}>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-primary">Recent Messages</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{detail.recent_messages.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No messages found.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2 max-h-80 overflow-y-auto">
|
||||
{detail.recent_messages.map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="rounded-lg border border-border p-3 text-sm"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<p className="line-clamp-2 flex-1 break-words text-xs text-foreground">
|
||||
{msg.content}
|
||||
</p>
|
||||
{msg.ai_status && (
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium",
|
||||
msg.ai_status === "flagged"
|
||||
? "bg-red-100 text-red-700"
|
||||
: msg.ai_status === "clean"
|
||||
? "bg-emerald-100 text-emerald-700"
|
||||
: msg.ai_status === "warn"
|
||||
? "bg-amber-100 text-amber-700"
|
||||
: "bg-muted text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{msg.ai_status}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 text-[10px] text-muted-foreground">
|
||||
{msg.username ?? "unknown"} ·{" "}
|
||||
{new Date(msg.created_at).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<Skeleton className="h-16 w-16 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-3 w-60" />
|
||||
<div className="flex gap-2 mt-2">
|
||||
<Skeleton className="h-5 w-20 rounded-full" />
|
||||
<Skeleton className="h-5 w-24 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="mt-4 h-20 w-full rounded-lg" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-4 text-center space-y-1">
|
||||
<Skeleton className="mx-auto h-7 w-16" />
|
||||
<Skeleton className="mx-auto h-3 w-20" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<ProfileDetail
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRetry={onRefetch}
|
||||
onBack={onBack}
|
||||
icon={<Hash className="h-8 w-8" />}
|
||||
title={detail ? `#${detail.channel_name ?? detail.channel_id}` : ""}
|
||||
subtitle={detail?.channel_id}
|
||||
summaryLabel="AI Channel Summary"
|
||||
summaryText={detail?.culture_summary ?? undefined}
|
||||
lastAnalyzedLabel={
|
||||
detail?.last_analyzed_at
|
||||
? `Last analyzed: ${new Date(detail.last_analyzed_at).toLocaleString()}`
|
||||
: undefined
|
||||
}
|
||||
stats={{
|
||||
totalLabel: "Total Messages",
|
||||
totalValue: detail?.total_messages ?? 0,
|
||||
cleanLabel: "Clean",
|
||||
cleanValue: detail?.clean_count ?? 0,
|
||||
flaggedLabel: "Flagged",
|
||||
flaggedValue: detail?.flagged_count ?? 0,
|
||||
}}
|
||||
messages={
|
||||
detail?.recent_messages.map((msg) => ({
|
||||
id: msg.id,
|
||||
content: msg.content,
|
||||
created_at: new Date(msg.created_at).toISOString(),
|
||||
ai_status: msg.ai_status,
|
||||
})) ?? []
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { motion } from "framer-motion";
|
||||
import { AlertCircle, Hash, Loader2, RefreshCw, Search } from "lucide-react";
|
||||
import { Hash } from "lucide-react";
|
||||
import type { DashboardChannel } from "../../../shared/api/client";
|
||||
import { cardItem, cardStagger } from "../../../shared/hooks/useFramerStagger";
|
||||
import { cn } from "../../../shared/lib/utils";
|
||||
import { Card, CardContent, Input, Skeleton } from "../../../shared/ui";
|
||||
import { SummaryList } from "../../../shared/ui";
|
||||
import type { SummaryItem } from "../../../shared/ui";
|
||||
|
||||
interface ChannelSummaryListProps {
|
||||
channels: DashboardChannel[];
|
||||
@@ -28,148 +26,31 @@ export function ChannelSummaryList({
|
||||
onRefetch,
|
||||
onSelectChannel,
|
||||
}: ChannelSummaryListProps) {
|
||||
const items: SummaryItem[] = channels.map((ch) => ({
|
||||
id: ch.channel_id,
|
||||
label: `#${ch.channel_name ?? ch.channel_id}`,
|
||||
subtitle: ch.flagged_count > 0 ? `${ch.flagged_count} flagged` : undefined,
|
||||
summaryText: ch.culture_summary ?? `${ch.total_messages} messages`,
|
||||
onClick: () => onSelectChannel(ch.channel_id),
|
||||
}));
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="grid gap-6"
|
||||
variants={cardStagger}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
>
|
||||
{/* Search bar */}
|
||||
<motion.div variants={cardItem} className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-primary" />
|
||||
<Input
|
||||
className="pl-9 rounded-full focus-visible:ring-primary"
|
||||
placeholder="Search by channel name or ID..."
|
||||
value={search}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
/>
|
||||
<SummaryList
|
||||
items={items}
|
||||
loading={loading}
|
||||
error={error}
|
||||
searchValue={search}
|
||||
onSearchChange={onSearchChange}
|
||||
onRetry={onRefetch}
|
||||
hasMore={hasMore}
|
||||
onLoadMore={onLoadMore}
|
||||
loadingMore={loading}
|
||||
renderIcon={() => (
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
|
||||
<Hash className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Error state */}
|
||||
{error && (
|
||||
<motion.div
|
||||
variants={cardItem}
|
||||
className="flex flex-col items-center gap-4 py-10 text-muted-foreground"
|
||||
>
|
||||
<AlertCircle className="h-10 w-10 text-destructive" />
|
||||
<p className="text-sm">{error}</p>
|
||||
<button
|
||||
onClick={onRefetch}
|
||||
className="inline-flex items-center gap-1.5 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" /> Retry
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Loading state */}
|
||||
{loading && channels.length === 0 && !error && <ChannelListSkeleton />}
|
||||
|
||||
{/* Empty state */}
|
||||
{!loading && !error && channels.length === 0 && (
|
||||
<motion.div
|
||||
variants={cardItem}
|
||||
className="flex flex-col items-center gap-4 py-20 text-muted-foreground"
|
||||
>
|
||||
<Hash className="h-10 w-10" />
|
||||
<p className="text-sm">No channels found.</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Channel cards */}
|
||||
{channels.length > 0 && (
|
||||
<motion.div variants={cardItem} className="grid gap-3 sm:grid-cols-2">
|
||||
{channels.map((ch) => (
|
||||
<button
|
||||
key={ch.channel_id}
|
||||
onClick={() => onSelectChannel(ch.channel_id)}
|
||||
className="group w-full text-left"
|
||||
>
|
||||
<Card className="transition-all hover:ring-1 hover:ring-primary/30 cursor-pointer">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Icon */}
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-muted">
|
||||
<Hash className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold">
|
||||
#{ch.channel_name ?? ch.channel_id}
|
||||
</span>
|
||||
{ch.flagged_count > 0 && (
|
||||
<span className="shrink-0 rounded-full bg-red-100 px-2 py-0.5 text-[10px] font-medium text-red-700">
|
||||
{ch.flagged_count} flagged
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{ch.culture_summary && (
|
||||
<p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
|
||||
{ch.culture_summary}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mt-1.5 flex items-center gap-3 text-[11px] text-muted-foreground">
|
||||
<span>{ch.total_messages} messages</span>
|
||||
{ch.last_message_at && (
|
||||
<span>
|
||||
Last{" "}
|
||||
{new Date(ch.last_message_at).toLocaleDateString()}
|
||||
</span>
|
||||
)}
|
||||
{ch.culture_summary && (
|
||||
<span className="text-emerald-600">AI Summary</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</button>
|
||||
))}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Load more */}
|
||||
{hasMore && (
|
||||
<motion.div variants={cardItem} className="flex justify-center">
|
||||
<button
|
||||
onClick={onLoadMore}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-2 rounded-xl border border-border px-6 py-2 text-sm font-medium hover:bg-accent transition-colors disabled:opacity-50"
|
||||
>
|
||||
{loading && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
{loading ? "Loading..." : "Load More"}
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
function ChannelListSkeleton() {
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<Skeleton className="h-3 w-full" />
|
||||
<Skeleton className="h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
emptyMessage="No channels found."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
Skeleton,
|
||||
StatusBadge,
|
||||
} from "../../../shared/ui";
|
||||
import { useDashboardStats } from "../hooks/useDashboard";
|
||||
import { useUIState } from "../../../shared/hooks/useUIState";
|
||||
@@ -189,7 +190,12 @@ export function DashboardStatsContent() {
|
||||
<CardTitle className="text-primary">Moderation Queue</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<StatusBadge status="pending" />
|
||||
<StatusBadge status="processing" />
|
||||
<StatusBadge status="error" />
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3 mt-4">
|
||||
<div className="rounded-xl border border-border bg-card p-4 text-center">
|
||||
<p className="text-2xl font-bold text-muted-foreground">
|
||||
{stats.moderation_overview.pending}
|
||||
|
||||
@@ -1,20 +1,6 @@
|
||||
import { motion } from "framer-motion";
|
||||
import { AlertCircle, ArrowLeft, RefreshCw, User } from "lucide-react";
|
||||
import { User } from "lucide-react";
|
||||
import type { DashboardUserDetail } from "../../../shared/api/client";
|
||||
import {
|
||||
cardItem,
|
||||
cardStagger,
|
||||
fadeSlideUp,
|
||||
} from "../../../shared/hooks/useFramerStagger";
|
||||
import { cn } from "../../../shared/lib/utils";
|
||||
import {
|
||||
Badge,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
Skeleton,
|
||||
} from "../../../shared/ui";
|
||||
import { ProfileDetail } from "../../../shared/ui";
|
||||
|
||||
interface UserProfileDetailProps {
|
||||
detail: DashboardUserDetail | null;
|
||||
@@ -31,247 +17,50 @@ export function UserProfileDetail({
|
||||
onBack,
|
||||
onRefetch,
|
||||
}: UserProfileDetailProps) {
|
||||
if (!detail && !loading && !error) return null;
|
||||
|
||||
const icon = detail?.avatar_url ? (
|
||||
<img
|
||||
src={detail.avatar_url}
|
||||
alt=""
|
||||
className="h-16 w-16 rounded-full object-cover ring-2 ring-border"
|
||||
/>
|
||||
) : (
|
||||
<User className="h-8 w-8" />
|
||||
);
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="grid gap-6"
|
||||
variants={cardStagger}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
>
|
||||
{/* Back button */}
|
||||
<motion.div variants={cardItem}>
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" /> Back to users
|
||||
</button>
|
||||
</motion.div>
|
||||
|
||||
{/* Loading */}
|
||||
{loading && <DetailSkeleton />}
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<motion.div
|
||||
variants={cardItem}
|
||||
className="flex flex-col items-center gap-4 py-20 text-muted-foreground"
|
||||
>
|
||||
<AlertCircle className="h-10 w-10 text-destructive" />
|
||||
<p className="text-sm">{error}</p>
|
||||
<button
|
||||
onClick={onRefetch}
|
||||
className="inline-flex items-center gap-1.5 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" /> Retry
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{detail && !error && (
|
||||
<>
|
||||
{/* Profile header */}
|
||||
<motion.div variants={cardItem}>
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
{/* Avatar */}
|
||||
<div className="shrink-0">
|
||||
{detail.avatar_url ? (
|
||||
<img
|
||||
src={detail.avatar_url}
|
||||
alt={detail.username ?? "User"}
|
||||
className="h-16 w-16 rounded-full object-cover ring-2 ring-border"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted ring-2 ring-border">
|
||||
<User className="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-lg font-bold">
|
||||
{detail.username ?? detail.user_id}
|
||||
</h2>
|
||||
<p className="mt-0.5 truncate font-mono text-xs text-muted-foreground">
|
||||
{detail.user_id}
|
||||
</p>
|
||||
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
{detail.trust_score !== null && (
|
||||
<Badge
|
||||
variant={
|
||||
detail.trust_score >= 80
|
||||
? "success"
|
||||
: detail.trust_score >= 50
|
||||
? "warning"
|
||||
: "destructive"
|
||||
}
|
||||
>
|
||||
Trust: {detail.trust_score}
|
||||
</Badge>
|
||||
)}
|
||||
{detail.total_infractions !== null &&
|
||||
detail.total_infractions > 0 && (
|
||||
<Badge variant="destructive">
|
||||
{detail.total_infractions} infractions
|
||||
</Badge>
|
||||
)}
|
||||
{detail.clean_message_streak !== null &&
|
||||
detail.clean_message_streak > 0 && (
|
||||
<Badge variant="success">
|
||||
Streak: {detail.clean_message_streak}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Profile summary */}
|
||||
{detail.profile_summary && (
|
||||
<div className="mt-4 rounded-lg bg-muted/50 p-3">
|
||||
<p className="text-xs font-medium text-muted-foreground mb-1">
|
||||
AI Profile Summary
|
||||
</p>
|
||||
<p className="text-sm whitespace-pre-wrap">
|
||||
{detail.profile_summary}
|
||||
</p>
|
||||
{detail.last_analyzed_at && (
|
||||
<p className="mt-1 text-[11px] text-muted-foreground">
|
||||
Last analyzed:{" "}
|
||||
{new Date(detail.last_analyzed_at).toLocaleString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* Stats grid */}
|
||||
<motion.div variants={cardItem} className="grid gap-4 sm:grid-cols-3">
|
||||
<Card>
|
||||
<CardContent className="p-4 text-center">
|
||||
<p className="text-2xl font-bold text-primary">
|
||||
{detail.total_messages.toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Total Messages
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4 text-center">
|
||||
<p className="text-2xl font-bold text-emerald-600">
|
||||
{detail.clean_count.toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Clean</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4 text-center">
|
||||
<p
|
||||
className={cn(
|
||||
"text-2xl font-bold",
|
||||
detail.flagged_count > 0
|
||||
? "text-destructive"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{detail.flagged_count.toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Flagged</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* Recent messages */}
|
||||
<motion.div variants={cardItem}>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-primary">Recent Messages</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{detail.recent_messages.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No messages found.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2 max-h-80 overflow-y-auto">
|
||||
{detail.recent_messages.map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="rounded-lg border border-border p-3 text-sm"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<p className="line-clamp-2 flex-1 break-words text-xs text-foreground">
|
||||
{msg.content}
|
||||
</p>
|
||||
{msg.ai_status && (
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium",
|
||||
msg.ai_status === "flagged"
|
||||
? "bg-red-100 text-red-700"
|
||||
: msg.ai_status === "clean"
|
||||
? "bg-emerald-100 text-emerald-700"
|
||||
: msg.ai_status === "warn"
|
||||
? "bg-amber-100 text-amber-700"
|
||||
: "bg-muted text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{msg.ai_status}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 text-[10px] text-muted-foreground">
|
||||
#{msg.channel_id} ·{" "}
|
||||
{new Date(msg.created_at).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<Skeleton className="h-16 w-16 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-3 w-60" />
|
||||
<div className="flex gap-2 mt-2">
|
||||
<Skeleton className="h-5 w-20 rounded-full" />
|
||||
<Skeleton className="h-5 w-24 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="mt-4 h-20 w-full rounded-lg" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-4 text-center space-y-1">
|
||||
<Skeleton className="mx-auto h-7 w-16" />
|
||||
<Skeleton className="mx-auto h-3 w-20" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<ProfileDetail
|
||||
loading={loading}
|
||||
error={error}
|
||||
onRetry={onRefetch}
|
||||
onBack={onBack}
|
||||
icon={icon}
|
||||
title={detail?.username ?? detail?.user_id ?? ""}
|
||||
subtitle={detail?.user_id}
|
||||
summaryLabel="AI Profile Summary"
|
||||
summaryText={detail?.profile_summary ?? undefined}
|
||||
lastAnalyzedLabel={
|
||||
detail?.last_analyzed_at
|
||||
? `Last analyzed: ${new Date(detail.last_analyzed_at).toLocaleString()}`
|
||||
: undefined
|
||||
}
|
||||
stats={{
|
||||
totalLabel: "Total Messages",
|
||||
totalValue: detail?.total_messages ?? 0,
|
||||
cleanLabel: "Clean",
|
||||
cleanValue: detail?.clean_count ?? 0,
|
||||
flaggedLabel: "Flagged",
|
||||
flaggedValue: detail?.flagged_count ?? 0,
|
||||
}}
|
||||
messages={
|
||||
detail?.recent_messages.map((msg) => ({
|
||||
id: msg.id,
|
||||
content: msg.content,
|
||||
created_at: new Date(msg.created_at).toISOString(),
|
||||
ai_status: msg.ai_status,
|
||||
})) ?? []
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
import { motion } from "framer-motion";
|
||||
import { AlertCircle, Loader2, RefreshCw, Search, User } from "lucide-react";
|
||||
import { User } from "lucide-react";
|
||||
import type { DashboardUser } from "../../../shared/api/client";
|
||||
import { cardItem, cardStagger } from "../../../shared/hooks/useFramerStagger";
|
||||
import { cn } from "../../../shared/lib/utils";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
Input,
|
||||
Skeleton,
|
||||
} from "../../../shared/ui";
|
||||
import { SummaryList } from "../../../shared/ui";
|
||||
import type { SummaryItem } from "../../../shared/ui";
|
||||
|
||||
interface UserSummaryListProps {
|
||||
users: DashboardUser[];
|
||||
@@ -35,163 +26,42 @@ export function UserSummaryList({
|
||||
onRefetch,
|
||||
onSelectUser,
|
||||
}: UserSummaryListProps) {
|
||||
const items: SummaryItem[] = users.map((u) => ({
|
||||
id: u.user_id,
|
||||
label: u.username ?? u.user_id,
|
||||
subtitle: u.trust_score !== null ? `Trust: ${u.trust_score}` : undefined,
|
||||
summaryText: u.profile_summary ?? `${u.total_messages} messages`,
|
||||
onClick: () => onSelectUser(u.user_id),
|
||||
}));
|
||||
|
||||
const avatarMap = new Map(users.map((u) => [u.user_id, u.avatar_url]));
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="grid gap-6"
|
||||
variants={cardStagger}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
>
|
||||
{/* Search bar */}
|
||||
<motion.div variants={cardItem} className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-primary" />
|
||||
<Input
|
||||
className="pl-9 rounded-full focus-visible:ring-primary"
|
||||
placeholder="Search by username or user ID..."
|
||||
value={search}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
<SummaryList
|
||||
items={items}
|
||||
loading={loading}
|
||||
error={error}
|
||||
searchValue={search}
|
||||
onSearchChange={onSearchChange}
|
||||
onRetry={onRefetch}
|
||||
hasMore={hasMore}
|
||||
onLoadMore={onLoadMore}
|
||||
loadingMore={loading}
|
||||
renderIcon={(item) => {
|
||||
const avatarUrl = avatarMap.get(item.id);
|
||||
return avatarUrl ? (
|
||||
<img
|
||||
src={avatarUrl}
|
||||
alt=""
|
||||
className="h-10 w-10 rounded-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Error state */}
|
||||
{error && (
|
||||
<motion.div
|
||||
variants={cardItem}
|
||||
className="flex flex-col items-center gap-4 py-10 text-muted-foreground"
|
||||
>
|
||||
<AlertCircle className="h-10 w-10 text-destructive" />
|
||||
<p className="text-sm">{error}</p>
|
||||
<button
|
||||
onClick={onRefetch}
|
||||
className="inline-flex items-center gap-1.5 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" /> Retry
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Loading state */}
|
||||
{loading && users.length === 0 && !error && <UserListSkeleton />}
|
||||
|
||||
{/* Empty state */}
|
||||
{!loading && !error && users.length === 0 && (
|
||||
<motion.div
|
||||
variants={cardItem}
|
||||
className="flex flex-col items-center gap-4 py-20 text-muted-foreground"
|
||||
>
|
||||
<User className="h-10 w-10" />
|
||||
<p className="text-sm">No users found.</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* User cards */}
|
||||
{users.length > 0 && (
|
||||
<motion.div variants={cardItem} className="grid gap-3 sm:grid-cols-2">
|
||||
{users.map((u) => (
|
||||
<button
|
||||
key={u.user_id}
|
||||
onClick={() => onSelectUser(u.user_id)}
|
||||
className="group w-full text-left"
|
||||
>
|
||||
<Card className="transition-all hover:ring-1 hover:ring-primary/30 cursor-pointer">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Avatar */}
|
||||
<div className="shrink-0">
|
||||
{u.avatar_url ? (
|
||||
<img
|
||||
src={u.avatar_url}
|
||||
alt={u.username ?? "User"}
|
||||
className="h-10 w-10 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
|
||||
<User className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold">
|
||||
{u.username ?? u.user_id}
|
||||
</span>
|
||||
{u.trust_score !== null && (
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium",
|
||||
u.trust_score >= 80
|
||||
? "bg-emerald-100 text-emerald-700"
|
||||
: u.trust_score >= 50
|
||||
? "bg-amber-100 text-amber-700"
|
||||
: "bg-red-100 text-red-700",
|
||||
)}
|
||||
>
|
||||
{u.trust_score}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{u.profile_summary && (
|
||||
<p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
|
||||
{u.profile_summary}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mt-1.5 flex items-center gap-3 text-[11px] text-muted-foreground">
|
||||
<span>{u.total_messages} messages</span>
|
||||
{u.flagged_count > 0 && (
|
||||
<span className="text-destructive">
|
||||
{u.flagged_count} flagged
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</button>
|
||||
))}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Load more */}
|
||||
{hasMore && (
|
||||
<motion.div variants={cardItem} className="flex justify-center">
|
||||
<button
|
||||
onClick={onLoadMore}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-2 rounded-xl border border-border px-6 py-2 text-sm font-medium hover:bg-accent transition-colors disabled:opacity-50"
|
||||
>
|
||||
{loading && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
{loading ? "Loading..." : "Load More"}
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
function UserListSkeleton() {
|
||||
return (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<Skeleton className="h-3 w-full" />
|
||||
<Skeleton className="h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
|
||||
<User className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
emptyMessage="No users found."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
listDashboardChannels,
|
||||
listDashboardUsers,
|
||||
} from "../../../shared/api/client";
|
||||
import { useItemDetail } from "../../../shared/hooks/useItemDetail";
|
||||
import { usePaginatedList } from "../../../shared/hooks/usePaginatedList";
|
||||
|
||||
const logger = console;
|
||||
|
||||
@@ -48,58 +50,25 @@ export function useDashboardStats() {
|
||||
* Fetch paginated user list with optional search.
|
||||
*/
|
||||
export function useDashboardUsers() {
|
||||
const [users, setUsers] = useState<DashboardUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [nextCursor, setNextCursor] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const fetchUsers = useCallback(
|
||||
async (cursor?: string) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await listDashboardUsers({
|
||||
limit: 20,
|
||||
cursor,
|
||||
search: search || undefined,
|
||||
});
|
||||
if (cursor) {
|
||||
setUsers((prev) => [...prev, ...result.data]);
|
||||
} else {
|
||||
setUsers(result.data);
|
||||
}
|
||||
setNextCursor(result.nextCursor);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : "Failed to load users";
|
||||
setError(msg);
|
||||
logger.error("[useDashboardUsers]", msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[search],
|
||||
const paginated = usePaginatedList(
|
||||
(params) =>
|
||||
listDashboardUsers({
|
||||
limit: params.limit,
|
||||
search: params.search,
|
||||
cursor: params.cursor,
|
||||
}).then((r) => ({ data: r.data, nextCursor: r.nextCursor })),
|
||||
"",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsers().catch(() => undefined);
|
||||
}, [fetchUsers]);
|
||||
|
||||
const loadMore = useCallback(() => {
|
||||
if (nextCursor && !loading) {
|
||||
fetchUsers(nextCursor).catch(() => undefined);
|
||||
}
|
||||
}, [nextCursor, loading, fetchUsers]);
|
||||
|
||||
return {
|
||||
users,
|
||||
loading,
|
||||
error,
|
||||
search,
|
||||
setSearch,
|
||||
loadMore,
|
||||
hasMore: !!nextCursor,
|
||||
refetch: () => fetchUsers().catch(() => undefined),
|
||||
users: paginated.data,
|
||||
loading: paginated.loading,
|
||||
error: paginated.error,
|
||||
search: paginated.search,
|
||||
setSearch: paginated.setSearch,
|
||||
loadMore: paginated.loadMore,
|
||||
hasMore: paginated.hasMore,
|
||||
refetch: paginated.refetch,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -107,92 +76,40 @@ export function useDashboardUsers() {
|
||||
* Fetch a single user detail by userId.
|
||||
*/
|
||||
export function useDashboardUserDetail(userId: string | null) {
|
||||
const [detail, setDetail] = useState<DashboardUserDetail | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { data, loading, error, refetch } = useItemDetail(
|
||||
(_guildId, entityId) => getDashboardUserDetail(entityId),
|
||||
"",
|
||||
userId,
|
||||
"user",
|
||||
);
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
if (!userId) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await getDashboardUserDetail(userId);
|
||||
if (!data) {
|
||||
setError("User not found");
|
||||
return;
|
||||
}
|
||||
setDetail(data);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : "Failed to load user detail";
|
||||
setError(msg);
|
||||
logger.error("[useDashboardUserDetail]", msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [userId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetch().catch(() => undefined);
|
||||
}, [fetch]);
|
||||
|
||||
return { detail, loading, error, refetch: fetch };
|
||||
return { detail: data, loading, error, refetch };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch paginated channel list with optional search.
|
||||
*/
|
||||
export function useDashboardChannels() {
|
||||
const [channels, setChannels] = useState<DashboardChannel[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [nextCursor, setNextCursor] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const fetchChannels = useCallback(
|
||||
async (cursor?: string) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await listDashboardChannels({
|
||||
limit: 20,
|
||||
search: search || undefined,
|
||||
});
|
||||
if (cursor) {
|
||||
setChannels((prev) => [...prev, ...result.data]);
|
||||
} else {
|
||||
setChannels(result.data);
|
||||
}
|
||||
setNextCursor(result.nextCursor);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : "Failed to load channels";
|
||||
setError(msg);
|
||||
logger.error("[useDashboardChannels]", msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[search],
|
||||
const paginated = usePaginatedList(
|
||||
(params) =>
|
||||
listDashboardChannels({
|
||||
limit: params.limit,
|
||||
search: params.search,
|
||||
guild_id: params.guildId,
|
||||
cursor: params.cursor,
|
||||
}).then((r) => ({ data: r.data, nextCursor: r.nextCursor })),
|
||||
"",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchChannels().catch(() => undefined);
|
||||
}, [fetchChannels]);
|
||||
|
||||
const loadMore = useCallback(() => {
|
||||
if (nextCursor && !loading) {
|
||||
fetchChannels(nextCursor).catch(() => undefined);
|
||||
}
|
||||
}, [nextCursor, loading, fetchChannels]);
|
||||
|
||||
return {
|
||||
channels,
|
||||
loading,
|
||||
error,
|
||||
search,
|
||||
setSearch,
|
||||
loadMore,
|
||||
hasMore: !!nextCursor,
|
||||
refetch: () => fetchChannels().catch(() => undefined),
|
||||
channels: paginated.data,
|
||||
loading: paginated.loading,
|
||||
error: paginated.error,
|
||||
search: paginated.search,
|
||||
setSearch: paginated.setSearch,
|
||||
loadMore: paginated.loadMore,
|
||||
hasMore: paginated.hasMore,
|
||||
refetch: paginated.refetch,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -200,34 +117,12 @@ export function useDashboardChannels() {
|
||||
* Fetch a single channel detail by channelId.
|
||||
*/
|
||||
export function useDashboardChannelDetail(channelId: string | null) {
|
||||
const [detail, setDetail] = useState<DashboardChannelDetail | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { data, loading, error, refetch } = useItemDetail(
|
||||
(_guildId, entityId) => getDashboardChannelDetail(entityId),
|
||||
"",
|
||||
channelId,
|
||||
"channel",
|
||||
);
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
if (!channelId) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await getDashboardChannelDetail(channelId);
|
||||
if (!data) {
|
||||
setError("Channel not found");
|
||||
return;
|
||||
}
|
||||
setDetail(data);
|
||||
} catch (e) {
|
||||
const msg =
|
||||
e instanceof Error ? e.message : "Failed to load channel detail";
|
||||
setError(msg);
|
||||
logger.error("[useDashboardChannelDetail]", msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [channelId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetch().catch(() => undefined);
|
||||
}, [fetch]);
|
||||
|
||||
return { detail, loading, error, refetch: fetch };
|
||||
return { detail: data, loading, error, refetch };
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { Fragment, useMemo, useState } from "react";
|
||||
import { parseMetadata } from "../../../entities/message/types";
|
||||
import type { MessageRecord } from "../../../shared/api/client";
|
||||
import { Badge, Button, Skeleton } from "../../../shared/ui";
|
||||
import { Badge, Button, Skeleton, StatusBadge } from "../../../shared/ui";
|
||||
|
||||
const CUSTOM_EMOJI_REGEX = /<(a)?:([a-zA-Z0-9_]+):(\d+)>/g;
|
||||
|
||||
@@ -194,15 +194,11 @@ function MessageRow({
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<Badge
|
||||
variant={aiVariant(aiStatus)}
|
||||
className="flex items-center gap-1 text-[10px] px-1.5 py-0"
|
||||
>
|
||||
<StatusBadge status={aiStatus} className="text-[10px] px-1.5 py-0">
|
||||
{aiStatus === "clean" && <CheckCircle2 className="h-3 w-3" />}
|
||||
{aiStatus === "flagged" && <AlertCircle className="h-3 w-3" />}
|
||||
{aiStatus === "error" && <AlertCircle className="h-3 w-3" />}
|
||||
{aiStatus}
|
||||
</Badge>
|
||||
</StatusBadge>
|
||||
{message.ai_severity && message.ai_severity !== "none" && (
|
||||
<Badge
|
||||
className={`text-[10px] px-1.5 py-0 ${severityColor(message.ai_severity)}`}
|
||||
|
||||
@@ -7,6 +7,8 @@ const logger = createLogger("api");
|
||||
|
||||
const BE_API_URL = import.meta.env.VITE_BE_API_URL || "http://localhost:3001";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 15000;
|
||||
|
||||
class ApiError extends Error {
|
||||
code: string;
|
||||
statusCode: number;
|
||||
@@ -19,9 +21,36 @@ class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const password = localStorage.getItem("admin-password");
|
||||
// Cache admin password in memory — read from localStorage once on first call
|
||||
let _cachedPassword: string | null = null;
|
||||
|
||||
function getAdminPassword(): string | null {
|
||||
if (_cachedPassword === null) {
|
||||
_cachedPassword = localStorage.getItem("admin-password");
|
||||
}
|
||||
return _cachedPassword;
|
||||
}
|
||||
|
||||
function buildSearchParams(
|
||||
params: Record<string, string | number | undefined | null>,
|
||||
): URLSearchParams {
|
||||
const sp = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value != null && value !== "") {
|
||||
sp.set(key, String(value));
|
||||
}
|
||||
}
|
||||
return sp;
|
||||
}
|
||||
|
||||
export async function request<T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
timeoutMs?: number,
|
||||
): Promise<T> {
|
||||
const password = getAdminPassword();
|
||||
const url = path.startsWith("http") ? path : `${BE_API_URL}${path}`;
|
||||
const signal = AbortSignal.timeout(timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
||||
logger.debug("Request", { method: init?.method ?? "GET", url });
|
||||
|
||||
const res = await fetch(url, {
|
||||
@@ -29,6 +58,7 @@ export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
"Content-Type": "application/json",
|
||||
...(password ? { "X-Admin-Password": password } : {}),
|
||||
},
|
||||
signal,
|
||||
...init,
|
||||
});
|
||||
|
||||
@@ -144,11 +174,11 @@ export function listMessages(params: {
|
||||
limit?: number;
|
||||
cursor?: string;
|
||||
}): Promise<PageResult<MessageRecord>> {
|
||||
const sp = new URLSearchParams({
|
||||
const sp = buildSearchParams({
|
||||
guildId: params.guildId,
|
||||
limit: String(params.limit ?? 100),
|
||||
...(params.channelId && { channelId: params.channelId }),
|
||||
...(params.cursor && { cursor: params.cursor }),
|
||||
limit: params.limit ?? 100,
|
||||
channelId: params.channelId,
|
||||
cursor: params.cursor,
|
||||
});
|
||||
return request<PageResult<MessageRecord>>(`/api/messages?${sp}`);
|
||||
}
|
||||
@@ -263,16 +293,21 @@ export interface VoiceRecording {
|
||||
uploaded_at: number | null;
|
||||
}
|
||||
|
||||
export interface VoiceRecordingListResponse {
|
||||
items: VoiceRecording[];
|
||||
nextCursor: string | null;
|
||||
hasMore: boolean;
|
||||
}
|
||||
|
||||
export function listRecordings(params?: {
|
||||
limit?: number;
|
||||
cursor?: string;
|
||||
}): Promise<{ items: VoiceRecording[]; nextCursor: string | null; hasMore: boolean }> {
|
||||
const sp = new URLSearchParams();
|
||||
sp.set("limit", String(params?.limit ?? 50));
|
||||
if (params?.cursor) sp.set("cursor", params.cursor);
|
||||
return request<{ items: VoiceRecording[]; nextCursor: string | null; hasMore: boolean }>(
|
||||
`/api/recordings?${sp}`,
|
||||
);
|
||||
}): Promise<VoiceRecordingListResponse> {
|
||||
const sp = buildSearchParams({
|
||||
limit: params?.limit ?? 50,
|
||||
cursor: params?.cursor,
|
||||
});
|
||||
return request<VoiceRecordingListResponse>(`/api/recordings?${sp}`);
|
||||
}
|
||||
|
||||
export function deleteRecording(id: string): Promise<void> {
|
||||
@@ -346,10 +381,11 @@ export function getDashboardStats(): Promise<DashboardStats> {
|
||||
export function listDashboardUsers(
|
||||
params: { limit?: number; cursor?: string; search?: string } = {},
|
||||
): Promise<{ data: DashboardUser[]; nextCursor: string | null }> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params.limit) sp.set("limit", String(params.limit));
|
||||
if (params.cursor) sp.set("cursor", params.cursor);
|
||||
if (params.search) sp.set("search", params.search);
|
||||
const sp = buildSearchParams({
|
||||
limit: params.limit,
|
||||
cursor: params.cursor,
|
||||
search: params.search,
|
||||
});
|
||||
return request<{ data: DashboardUser[]; nextCursor: string | null }>(
|
||||
`/api/dashboard/users?${sp}`,
|
||||
);
|
||||
@@ -387,12 +423,19 @@ export interface DashboardChannelDetail extends DashboardChannel {
|
||||
}
|
||||
|
||||
export function listDashboardChannels(
|
||||
params: { limit?: number; search?: string; guild_id?: string } = {},
|
||||
params: {
|
||||
limit?: number;
|
||||
search?: string;
|
||||
guild_id?: string;
|
||||
cursor?: string;
|
||||
} = {},
|
||||
): Promise<{ data: DashboardChannel[]; nextCursor: string | null }> {
|
||||
const sp = new URLSearchParams();
|
||||
if (params.limit) sp.set("limit", String(params.limit));
|
||||
if (params.search) sp.set("search", params.search);
|
||||
if (params.guild_id) sp.set("guild_id", params.guild_id);
|
||||
const sp = buildSearchParams({
|
||||
limit: params.limit,
|
||||
search: params.search,
|
||||
guild_id: params.guild_id,
|
||||
cursor: params.cursor,
|
||||
});
|
||||
return request<{ data: DashboardChannel[]; nextCursor: string | null }>(
|
||||
`/api/dashboard/channels?${sp}`,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
/**
|
||||
* Generic hook for fetching a single item by ID.
|
||||
* Automatically refetches when guildId or entityId changes.
|
||||
*/
|
||||
export function useItemDetail<T>(
|
||||
fetchFn: (guildId: string, entityId: string) => Promise<T>,
|
||||
guildId: string,
|
||||
entityId: string | null,
|
||||
entityName = "item",
|
||||
) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchFnRef = useRef(fetchFn);
|
||||
fetchFnRef.current = fetchFn;
|
||||
const guildIdRef = useRef(guildId);
|
||||
guildIdRef.current = guildId;
|
||||
const fetchIdRef = useRef(0);
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
if (!entityId) return;
|
||||
const id = ++fetchIdRef.current;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await fetchFnRef.current(guildIdRef.current, entityId);
|
||||
if (id !== fetchIdRef.current) return;
|
||||
if (!result) {
|
||||
setError(`${entityName} not found`);
|
||||
return;
|
||||
}
|
||||
setData(result);
|
||||
} catch (e) {
|
||||
if (id !== fetchIdRef.current) return;
|
||||
const msg =
|
||||
e instanceof Error ? e.message : `Failed to load ${entityName}`;
|
||||
setError(msg);
|
||||
} finally {
|
||||
if (id === fetchIdRef.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [entityId, entityName]);
|
||||
|
||||
useEffect(() => {
|
||||
fetch().catch(() => undefined);
|
||||
}, [fetch]);
|
||||
|
||||
const refetch = useCallback(() => {
|
||||
fetch().catch(() => undefined);
|
||||
}, [fetch]);
|
||||
|
||||
return { data, loading, error, refetch };
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
export interface PaginatedResult<T> {
|
||||
data: T[];
|
||||
nextCursor: string | null;
|
||||
}
|
||||
|
||||
export interface UsePaginatedListParams {
|
||||
limit: number;
|
||||
search?: string;
|
||||
cursor?: string;
|
||||
guildId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic hook for fetching a paginated list with cursor-based pagination,
|
||||
* search support, and automatic refetch when search/guildId changes.
|
||||
*/
|
||||
export function usePaginatedList<T>(
|
||||
fetchFn: (params: UsePaginatedListParams) => Promise<PaginatedResult<T>>,
|
||||
guildId = "",
|
||||
initialSearch = "",
|
||||
) {
|
||||
const [data, setData] = useState<T[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [nextCursor, setNextCursor] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState(initialSearch);
|
||||
|
||||
// Stable refs so fetch() can be a stable callback that reads latest values
|
||||
const fetchFnRef = useRef(fetchFn);
|
||||
fetchFnRef.current = fetchFn;
|
||||
const guildIdRef = useRef(guildId);
|
||||
guildIdRef.current = guildId;
|
||||
const searchRef = useRef(search);
|
||||
searchRef.current = search;
|
||||
const fetchIdRef = useRef(0);
|
||||
|
||||
const fetch = useCallback(async (cursor?: string) => {
|
||||
const id = ++fetchIdRef.current;
|
||||
|
||||
if (cursor) {
|
||||
setLoadingMore(true);
|
||||
} else {
|
||||
setLoading(true);
|
||||
setData([]);
|
||||
}
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await fetchFnRef.current({
|
||||
limit: 20,
|
||||
search: searchRef.current || undefined,
|
||||
cursor,
|
||||
guildId: guildIdRef.current || undefined,
|
||||
});
|
||||
if (id !== fetchIdRef.current) return;
|
||||
|
||||
if (cursor) {
|
||||
setData((prev) => [...prev, ...result.data]);
|
||||
} else {
|
||||
setData(result.data);
|
||||
}
|
||||
setNextCursor(result.nextCursor);
|
||||
} catch (e) {
|
||||
if (id !== fetchIdRef.current) return;
|
||||
const msg = e instanceof Error ? e.message : "Failed to load data";
|
||||
setError(msg);
|
||||
} finally {
|
||||
if (id === fetchIdRef.current) {
|
||||
setLoading(false);
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Re-fetch on mount, search change, or guildId change
|
||||
useEffect(() => {
|
||||
fetch().catch(() => undefined);
|
||||
}, [search, guildId, fetch]);
|
||||
|
||||
const loadMore = useCallback(() => {
|
||||
if (nextCursor && !loading && !loadingMore) {
|
||||
fetch(nextCursor).catch(() => undefined);
|
||||
}
|
||||
}, [nextCursor, loading, loadingMore, fetch]);
|
||||
|
||||
const refetch = useCallback(() => {
|
||||
fetch().catch(() => undefined);
|
||||
}, [fetch]);
|
||||
|
||||
return {
|
||||
data,
|
||||
loading,
|
||||
loadingMore,
|
||||
error,
|
||||
nextCursor,
|
||||
search,
|
||||
setSearch,
|
||||
hasMore: !!nextCursor,
|
||||
loadMore,
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
@@ -15,10 +15,17 @@ interface MobileTabBarProps {
|
||||
|
||||
export function MobileTabBar({ activeTab, onTabChange }: MobileTabBarProps) {
|
||||
return (
|
||||
<nav className="fixed bottom-0 left-0 right-0 z-50 flex border-t border-border bg-card shadow-lg md:hidden">
|
||||
<nav
|
||||
aria-label="Main navigation"
|
||||
role="tablist"
|
||||
className="fixed bottom-0 left-0 right-0 z-50 flex border-t border-border bg-card shadow-lg md:hidden"
|
||||
>
|
||||
{tabs.map(({ id, label, Icon }) => (
|
||||
<button
|
||||
key={id}
|
||||
role="tab"
|
||||
aria-selected={activeTab === id}
|
||||
aria-controls={`tabpanel-${id}`}
|
||||
type="button"
|
||||
onClick={() => onTabChange(id)}
|
||||
className={cn(
|
||||
@@ -29,7 +36,10 @@ export function MobileTabBar({ activeTab, onTabChange }: MobileTabBarProps) {
|
||||
<Icon className="h-5 w-5" />
|
||||
<span className="text-[10px]">{label}</span>
|
||||
{activeTab === id && (
|
||||
<span className="h-0.5 w-6 rounded-full bg-primary mx-auto mt-0.5" />
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="h-0.5 w-6 rounded-full bg-primary mx-auto mt-0.5"
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -7,15 +7,19 @@ type BadgeVariant =
|
||||
| "destructive"
|
||||
| "outline"
|
||||
| "success"
|
||||
| "warning";
|
||||
| "warning"
|
||||
| "info";
|
||||
|
||||
const variants: Record<BadgeVariant, string> = {
|
||||
default: "border-transparent bg-primary text-primary-foreground",
|
||||
secondary: "border-transparent bg-muted text-muted-foreground",
|
||||
destructive: "border-transparent bg-destructive/15 text-destructive",
|
||||
outline: "border-border text-foreground",
|
||||
success: "border-transparent bg-emerald-100 text-emerald-700",
|
||||
warning: "border-transparent bg-amber-100 text-amber-700",
|
||||
success:
|
||||
"border-transparent bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",
|
||||
warning:
|
||||
"border-transparent bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300",
|
||||
info: "border-transparent bg-blue-100 text-blue-700 dark:bg-blue-950 dark:text-blue-300",
|
||||
};
|
||||
|
||||
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
@@ -29,6 +33,7 @@ export function Badge({
|
||||
}: BadgeProps) {
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors",
|
||||
variants[variant],
|
||||
|
||||
@@ -39,17 +39,20 @@ export function Button({
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
disabled,
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
return (
|
||||
<Comp
|
||||
aria-disabled={disabled || undefined}
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.97] disabled:pointer-events-none disabled:opacity-50",
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium motion-safe:transition-all motion-safe:duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 active:scale-[0.97] disabled:pointer-events-none disabled:opacity-50",
|
||||
variants[variant],
|
||||
sizes[size],
|
||||
className,
|
||||
)}
|
||||
disabled={!asChild ? disabled : undefined}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ export function Card({
|
||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
role="region"
|
||||
className={cn(
|
||||
"rounded-xl border border-border bg-card text-card-foreground shadow-sm hover:shadow-md transition-shadow",
|
||||
className,
|
||||
|
||||
@@ -11,8 +11,17 @@ export {
|
||||
CardTitle,
|
||||
} from "./card";
|
||||
export { Input } from "./input";
|
||||
export type {
|
||||
ProfileDetailMessage,
|
||||
ProfileDetailStats,
|
||||
} from "./profile-detail";
|
||||
export { ProfileDetail } from "./profile-detail";
|
||||
export { ScrollArea } from "./scroll-area";
|
||||
export { Select } from "./select";
|
||||
export { Skeleton } from "./skeleton";
|
||||
export type { StatusType } from "./status-badge";
|
||||
export { StatusBadge } from "./status-badge";
|
||||
export type { SummaryItem } from "./summary-list";
|
||||
export { SummaryList } from "./summary-list";
|
||||
export { Tabs, TabsContent, TabsList, TabsTrigger } from "./tabs";
|
||||
export { ToastProvider, useToast } from "./toast";
|
||||
|
||||
@@ -2,14 +2,19 @@ import type * as React from "react";
|
||||
import { cn } from "../lib/utils";
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
errorId?: string;
|
||||
}
|
||||
|
||||
export function Input({ className, type, ...props }: InputProps) {
|
||||
export function Input({ className, type, errorId, ...props }: InputProps) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
aria-describedby={errorId}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
props["aria-invalid"] === "true" &&
|
||||
"border-destructive ring-destructive/30",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { ArrowLeft, RefreshCw } from "lucide-react";
|
||||
import { type ReactNode } from "react";
|
||||
import { cn } from "../lib/utils";
|
||||
import { Card, CardContent } from "./card";
|
||||
import { Skeleton } from "./skeleton";
|
||||
import { StatusBadge, type StatusType } from "./status-badge";
|
||||
|
||||
export interface ProfileDetailStats {
|
||||
totalLabel: string;
|
||||
totalValue: number;
|
||||
cleanLabel: string;
|
||||
cleanValue: number;
|
||||
flaggedLabel: string;
|
||||
flaggedValue: number;
|
||||
}
|
||||
|
||||
export interface ProfileDetailMessage {
|
||||
id: string;
|
||||
content: string | null;
|
||||
created_at: string | null;
|
||||
ai_status: string | null;
|
||||
}
|
||||
|
||||
interface ProfileDetailProps {
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
onRetry: () => void;
|
||||
onBack: () => void;
|
||||
icon: ReactNode;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
summaryLabel: string;
|
||||
summaryText?: string;
|
||||
lastAnalyzedLabel?: string;
|
||||
stats: ProfileDetailStats;
|
||||
messages: ProfileDetailMessage[];
|
||||
messagesTitle?: string;
|
||||
messagesEmptyText?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function DetailSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Skeleton className="h-6 w-24" />
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Skeleton className="h-16 w-16 rounded-full" />
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-6 w-48" />
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-4">
|
||||
<Skeleton className="h-4 w-16 mb-2" />
|
||||
<Skeleton className="h-8 w-12" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProfileDetail({
|
||||
loading,
|
||||
error,
|
||||
onRetry,
|
||||
onBack,
|
||||
icon,
|
||||
title,
|
||||
subtitle,
|
||||
summaryLabel,
|
||||
summaryText,
|
||||
lastAnalyzedLabel,
|
||||
stats,
|
||||
messages,
|
||||
messagesTitle = "Recent Messages",
|
||||
messagesEmptyText = "No messages found",
|
||||
className,
|
||||
}: ProfileDetailProps) {
|
||||
if (loading) return <DetailSkeleton />;
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 py-20 text-muted-foreground">
|
||||
<p className="text-sm">{error}</p>
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="inline-flex items-center gap-1.5 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" /> Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("space-y-6", className)}>
|
||||
{/* Back button */}
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" /> Back
|
||||
</button>
|
||||
|
||||
{/* Header */}
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted text-muted-foreground">
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-xl font-semibold truncate">{title}</h2>
|
||||
{subtitle && (
|
||||
<p className="text-sm text-muted-foreground">{subtitle}</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{summaryLabel}: {summaryText ?? "N/A"}
|
||||
</p>
|
||||
{lastAnalyzedLabel && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{lastAnalyzedLabel}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
{stats.totalLabel}
|
||||
</p>
|
||||
<p className="text-2xl font-bold tabular-nums">
|
||||
{stats.totalValue}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
{stats.cleanLabel}
|
||||
</p>
|
||||
<p className="text-2xl font-bold tabular-nums text-emerald-600">
|
||||
{stats.cleanValue}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wide">
|
||||
{stats.flaggedLabel}
|
||||
</p>
|
||||
<p className="text-2xl font-bold tabular-nums text-red-600">
|
||||
{stats.flaggedValue}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Recent Messages */}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-muted-foreground mb-3">
|
||||
{messagesTitle}
|
||||
</h3>
|
||||
{messages.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-8 text-center">
|
||||
{messagesEmptyText}
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{messages.map((msg) => (
|
||||
<Card key={msg.id}>
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<p className="text-sm line-clamp-2 flex-1">
|
||||
{msg.content ?? "(no content)"}
|
||||
</p>
|
||||
<StatusBadge status={msg.ai_status} />
|
||||
</div>
|
||||
{msg.created_at && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{new Date(msg.created_at).toLocaleString()}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -22,11 +22,17 @@ export function Select({
|
||||
<select
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
props["aria-invalid"] === "true" &&
|
||||
"border-destructive ring-destructive/30",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{placeholder && <option value="">{placeholder}</option>}
|
||||
{placeholder && (
|
||||
<option value="" disabled hidden>
|
||||
{placeholder}
|
||||
</option>
|
||||
)}
|
||||
{options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
|
||||
@@ -7,6 +7,8 @@ export function Skeleton({
|
||||
}: HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
role="presentation"
|
||||
className={cn("rounded-lg bg-muted animate-shimmer", className)}
|
||||
{...props}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { cn } from "../lib/utils";
|
||||
|
||||
export type StatusType =
|
||||
| "flagged"
|
||||
| "clean"
|
||||
| "warn"
|
||||
| "pending"
|
||||
| "processing"
|
||||
| "error"
|
||||
| "deleted"
|
||||
| "none";
|
||||
|
||||
const statusStyles: Record<StatusType, string> = {
|
||||
flagged:
|
||||
"bg-red-100 text-red-700 border-red-200 dark:bg-red-950 dark:text-red-300 dark:border-red-800",
|
||||
clean:
|
||||
"bg-emerald-100 text-emerald-700 border-emerald-200 dark:bg-emerald-950 dark:text-emerald-300 dark:border-emerald-800",
|
||||
warn: "bg-amber-100 text-amber-700 border-amber-200 dark:bg-amber-950 dark:text-amber-300 dark:border-amber-800",
|
||||
pending: "bg-muted text-muted-foreground border-border",
|
||||
processing:
|
||||
"bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-950 dark:text-blue-300 dark:border-blue-800",
|
||||
error:
|
||||
"bg-red-100 text-red-700 border-red-200 dark:bg-red-950 dark:text-red-300 dark:border-red-800",
|
||||
deleted:
|
||||
"bg-gray-100 text-gray-500 border-gray-200 dark:bg-gray-900 dark:text-gray-400 dark:border-gray-800 line-through",
|
||||
none: "bg-muted text-muted-foreground border-border",
|
||||
};
|
||||
|
||||
interface StatusBadgeProps {
|
||||
status: StatusType | string | null;
|
||||
className?: string;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export function StatusBadge({ status, className, children }: StatusBadgeProps) {
|
||||
const key = (status?.toLowerCase() ?? "none") as StatusType;
|
||||
const style = statusStyles[key] ?? statusStyles.none;
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium",
|
||||
style,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
{children ? " " : null}
|
||||
{status ?? "unknown"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { ChevronRight, Loader2, RefreshCw, Search } from "lucide-react";
|
||||
import { type ReactNode } from "react";
|
||||
import { cn } from "../lib/utils";
|
||||
import { Card, CardContent } from "./card";
|
||||
import { Input } from "./input";
|
||||
import { Skeleton } from "./skeleton";
|
||||
|
||||
export interface SummaryItem {
|
||||
id: string;
|
||||
label: string;
|
||||
subtitle?: string;
|
||||
summaryText: string;
|
||||
summaryValue?: number;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
interface SummaryListProps<T extends SummaryItem> {
|
||||
items: T[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
searchValue: string;
|
||||
onSearchChange: (value: string) => void;
|
||||
onRetry: () => void;
|
||||
hasMore: boolean;
|
||||
onLoadMore: () => void;
|
||||
loadingMore: boolean;
|
||||
renderIcon: (item: T) => ReactNode;
|
||||
emptyMessage?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SummaryList<T extends SummaryItem>({
|
||||
items,
|
||||
loading,
|
||||
error,
|
||||
searchValue,
|
||||
onSearchChange,
|
||||
onRetry,
|
||||
hasMore,
|
||||
onLoadMore,
|
||||
loadingMore,
|
||||
renderIcon,
|
||||
emptyMessage = "No items found",
|
||||
className,
|
||||
}: SummaryListProps<T>) {
|
||||
return (
|
||||
<div className={cn("space-y-4", className)}>
|
||||
{/* Search */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search..."
|
||||
value={searchValue}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
className="pl-9 rounded-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="flex flex-col items-center gap-4 py-20 text-muted-foreground">
|
||||
<p className="text-sm">{error}</p>
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="inline-flex items-center gap-1.5 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" /> Retry
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Loading skeleton — only on initial load */}
|
||||
{loading && items.length === 0 && !error && (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-2 flex-1">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-3 w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty */}
|
||||
{!loading && !error && items.length === 0 && (
|
||||
<div className="flex flex-col items-center gap-4 py-20 text-muted-foreground">
|
||||
<p className="text-sm">{emptyMessage}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Items */}
|
||||
{!error && items.length > 0 && (
|
||||
<>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={item.onClick}
|
||||
className="text-left w-full"
|
||||
aria-label={item.label}
|
||||
>
|
||||
<Card className="hover:bg-accent/50 transition-colors cursor-pointer h-full">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="mt-0.5 shrink-0 text-muted-foreground">
|
||||
{renderIcon(item)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="font-medium text-sm truncate">
|
||||
{item.label}
|
||||
</h3>
|
||||
{item.subtitle && (
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{item.subtitle}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{item.summaryText}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground/50 shrink-0 mt-1" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Load More */}
|
||||
{hasMore && (
|
||||
<div className="flex justify-center pt-2">
|
||||
<button
|
||||
onClick={onLoadMore}
|
||||
disabled={loadingMore}
|
||||
className="inline-flex items-center gap-2 rounded-xl border border-border px-6 py-2 text-sm font-medium hover:bg-accent transition-colors disabled:opacity-50"
|
||||
>
|
||||
{loadingMore && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
Load More
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
type ReactNode,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { cn } from "../lib/utils";
|
||||
@@ -35,21 +37,40 @@ const ToastContext = createContext<ToastContextType>({
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(
|
||||
new Map(),
|
||||
);
|
||||
|
||||
const removeToast = useCallback((id: string) => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
const timer = timersRef.current.get(id);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
timersRef.current.delete(id);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const addToast = useCallback(
|
||||
(message: string, type: Toast["type"] = "info") => {
|
||||
const id = `toast-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
||||
setToasts((prev) => [...prev, { id, message, type }]);
|
||||
setTimeout(
|
||||
() => setToasts((prev) => prev.filter((t) => t.id !== id)),
|
||||
4000,
|
||||
);
|
||||
const timer = setTimeout(() => {
|
||||
removeToast(id);
|
||||
}, 4000);
|
||||
timersRef.current.set(id, timer);
|
||||
},
|
||||
[],
|
||||
[removeToast],
|
||||
);
|
||||
|
||||
const removeToast = useCallback((id: string) => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
// Cleanup all timers on unmount
|
||||
useEffect(() => {
|
||||
const current = timersRef.current;
|
||||
return () => {
|
||||
for (const timer of current.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
current.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
@@ -84,19 +105,33 @@ function ToastContainer() {
|
||||
if (toasts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2">
|
||||
<div
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
className="fixed bottom-4 right-4 z-50 flex flex-col gap-2"
|
||||
>
|
||||
{toasts.map((toast) => (
|
||||
<div
|
||||
key={toast.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className={cn(
|
||||
"group flex items-center gap-2.5 rounded-lg border border-border px-4 py-3 text-sm shadow-md cursor-pointer transition-all hover:scale-[1.02] border-l-4",
|
||||
"group flex items-center gap-2.5 rounded-lg border border-border px-4 py-3 text-sm shadow-md cursor-pointer transition-all hover:scale-[1.02] border-l-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
typeStyles[toast.type],
|
||||
)}
|
||||
onClick={() => removeToast(toast.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === "Escape") {
|
||||
removeToast(toast.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="flex-shrink-0">{typeIcons[toast.type]}</span>
|
||||
<span className="flex-1">{toast.message}</span>
|
||||
<X className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
|
||||
<X
|
||||
aria-label="Close notification"
|
||||
className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground md:opacity-0 md:group-hover:opacity-100 transition-opacity"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,30 +1,64 @@
|
||||
// ─── Typed event map for WebSocket events ────────────────────────────────────
|
||||
//
|
||||
// Types correspond to the data field sent by the backend's broadcastEvent().
|
||||
// The backend unwraps the DiscordGatewayEvent envelope and forwards only
|
||||
// the inner `data` field to frontend WebSocket clients.
|
||||
|
||||
import type {
|
||||
AnalysisQueueStatus,
|
||||
AttachmentRecord,
|
||||
MessageRecord,
|
||||
VoiceRecordingUploadData,
|
||||
} from "@bete/shared";
|
||||
|
||||
export interface ActiveSpeakerData {
|
||||
userId: string;
|
||||
username: string;
|
||||
avatar: string;
|
||||
speaking: boolean;
|
||||
}
|
||||
|
||||
export interface WsEventMap {
|
||||
message_created: { data: unknown };
|
||||
message_updated: { data: unknown };
|
||||
message_deleted: { data: { id: string } };
|
||||
message_analyzed: { data: unknown };
|
||||
attachment_uploaded: { data: unknown };
|
||||
message_created: { data: MessageRecord };
|
||||
message_updated: { data: MessageRecord & { edited_content?: string | null } };
|
||||
message_deleted: {
|
||||
data: { id: string; channel_id?: string; deleted_at: number };
|
||||
};
|
||||
message_analyzed: { data: MessageRecord };
|
||||
attachment_created: { data: AttachmentRecord };
|
||||
attachment_uploaded: { data: AttachmentRecord };
|
||||
voice_recording_started: { data: Record<string, unknown> };
|
||||
voice_recording_stopped: {
|
||||
data: {
|
||||
guild_id: string;
|
||||
session_id: string;
|
||||
duration_ms: number;
|
||||
participants: number;
|
||||
segment_count: number;
|
||||
status: string;
|
||||
stopped_at: number;
|
||||
};
|
||||
};
|
||||
voice_recording_uploaded: { data: VoiceRecordingUploadData };
|
||||
voice_pcm_data: {
|
||||
data: { userId: string; pcm: string; metadata?: Record<string, unknown> };
|
||||
};
|
||||
voice_analyzed: { data: Record<string, unknown> };
|
||||
voice_active_user: { data: ActiveSpeakerData };
|
||||
user_state: { users: unknown[] };
|
||||
ui_state: { state: unknown };
|
||||
media_state: { state: unknown };
|
||||
voice_recording_uploaded: { data: unknown };
|
||||
voice_recording_started: { data: unknown };
|
||||
voice_recording_stopped: { data: unknown };
|
||||
voice_pcm_data: { data: unknown };
|
||||
voice_active_user: { data: unknown };
|
||||
attachment_created: { data: unknown };
|
||||
analysis_queue_status: { data: unknown };
|
||||
reaction_added: { data: unknown };
|
||||
reaction_removed: { data: unknown };
|
||||
thread_created: { data: unknown };
|
||||
thread_deleted: { data: unknown };
|
||||
thread_updated: { data: unknown };
|
||||
channel_topic_updated: { data: unknown };
|
||||
presence_updated: { data: unknown };
|
||||
guild_member_added: { data: unknown };
|
||||
guild_member_removed: { data: unknown };
|
||||
ui_state: { state: Record<string, unknown> };
|
||||
media_state: { state: Record<string, unknown> };
|
||||
analysis_queue_status: { data: AnalysisQueueStatus };
|
||||
reaction_added: { data: Record<string, unknown> };
|
||||
reaction_removed: { data: Record<string, unknown> };
|
||||
thread_created: { data: Record<string, unknown> };
|
||||
thread_deleted: { data: Record<string, unknown> };
|
||||
thread_updated: { data: Record<string, unknown> };
|
||||
channel_topic_updated: { data: Record<string, unknown> };
|
||||
presence_updated: { data: Record<string, unknown> };
|
||||
guild_member_added: { data: Record<string, unknown> };
|
||||
guild_member_removed: { data: Record<string, unknown> };
|
||||
heartbeat: { data?: { timestamp: number } };
|
||||
}
|
||||
|
||||
export type WsEventType = keyof WsEventMap;
|
||||
@@ -34,7 +68,7 @@ export function parseWsMessage(
|
||||
): { type: WsEventType; payload: Record<string, unknown> } | null {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed.type) return null;
|
||||
if (!parsed.type || typeof parsed.type !== "string") return null;
|
||||
const { type, ...rest } = parsed;
|
||||
return { type: type as WsEventType, payload: rest };
|
||||
} catch {
|
||||
|
||||
@@ -8,6 +8,19 @@ export type WsStatus = "connecting" | "connected" | "disconnected" | "error";
|
||||
|
||||
export type BinaryHandler = (data: ArrayBuffer) => void;
|
||||
|
||||
const RECONNECT_BASE_MS = 1000;
|
||||
const RECONNECT_MAX_MS = 30000;
|
||||
const MAX_RECONNECT_ATTEMPTS = 20;
|
||||
|
||||
function computeBackoff(attempt: number): number {
|
||||
const delay = Math.min(
|
||||
RECONNECT_BASE_MS * Math.pow(2, attempt),
|
||||
RECONNECT_MAX_MS,
|
||||
);
|
||||
// Full jitter: random between 50% and 100% of delay
|
||||
return delay * (0.5 + Math.random() * 0.5);
|
||||
}
|
||||
|
||||
export interface WsHandlers {
|
||||
onBinary?: BinaryHandler;
|
||||
onMessageCreated?: (data: unknown) => void;
|
||||
@@ -24,6 +37,16 @@ export interface WsHandlers {
|
||||
onVoiceRecordingUploaded?: (data: unknown) => void;
|
||||
onVoicePcmData?: (data: unknown) => void;
|
||||
onVoiceActiveUser?: (data: unknown) => void;
|
||||
onReactionAdded?: (data: unknown) => void;
|
||||
onReactionRemoved?: (data: unknown) => void;
|
||||
onThreadCreated?: (data: unknown) => void;
|
||||
onThreadDeleted?: (data: unknown) => void;
|
||||
onThreadUpdated?: (data: unknown) => void;
|
||||
onChannelTopicUpdated?: (data: unknown) => void;
|
||||
onPresenceUpdated?: (data: unknown) => void;
|
||||
onGuildMemberAdded?: (data: unknown) => void;
|
||||
onGuildMemberRemoved?: (data: unknown) => void;
|
||||
onVoiceAnalyzed?: (data: unknown) => void;
|
||||
}
|
||||
|
||||
let _wsInstance: WebSocket | null = null;
|
||||
@@ -61,8 +84,19 @@ function doConnect(): WebSocket {
|
||||
logger.info("Disconnected", { code: event.code, reason: event.reason });
|
||||
if (!_closed && _listeners.size > 0) {
|
||||
_reconnectAttempts++;
|
||||
logger.warn("Reconnecting", { attempt: _reconnectAttempts });
|
||||
_reconnectTimer = setTimeout(() => doReconnect(), 2500);
|
||||
if (_reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
|
||||
logger.error("Max reconnect attempts reached, giving up", {
|
||||
attempts: _reconnectAttempts,
|
||||
});
|
||||
dispatchStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
const delay = computeBackoff(_reconnectAttempts);
|
||||
logger.warn("Reconnecting", {
|
||||
attempt: _reconnectAttempts,
|
||||
delayMs: Math.round(delay),
|
||||
});
|
||||
_reconnectTimer = setTimeout(() => doReconnect(), delay);
|
||||
}
|
||||
});
|
||||
ws.addEventListener("message", (event) => {
|
||||
@@ -76,19 +110,22 @@ function doConnect(): WebSocket {
|
||||
for (const h of _listeners) {
|
||||
switch (msg.type) {
|
||||
case "message_created":
|
||||
h.onMessageCreated?.(msg.data);
|
||||
if (msg.data !== undefined) h.onMessageCreated?.(msg.data);
|
||||
break;
|
||||
case "message_updated":
|
||||
h.onMessageUpdated?.(msg.data);
|
||||
if (msg.data !== undefined) h.onMessageUpdated?.(msg.data);
|
||||
break;
|
||||
case "message_deleted":
|
||||
h.onMessageDeleted?.(msg.data);
|
||||
if (msg.data !== undefined) h.onMessageDeleted?.(msg.data);
|
||||
break;
|
||||
case "message_analyzed":
|
||||
h.onMessageAnalyzed?.(msg.data);
|
||||
if (msg.data !== undefined) h.onMessageAnalyzed?.(msg.data);
|
||||
break;
|
||||
case "attachment_created":
|
||||
if (msg.data !== undefined) h.onAttachmentCreated?.(msg.data);
|
||||
break;
|
||||
case "attachment_uploaded":
|
||||
h.onAttachmentUploaded?.(msg.data);
|
||||
if (msg.data !== undefined) h.onAttachmentUploaded?.(msg.data);
|
||||
break;
|
||||
case "user_state":
|
||||
h.onUserState?.((msg.users as unknown[]) || []);
|
||||
@@ -99,26 +136,53 @@ function doConnect(): WebSocket {
|
||||
case "media_state":
|
||||
h.onMediaState?.(msg.state);
|
||||
break;
|
||||
case "voice_recording_uploaded":
|
||||
h.onVoiceRecordingUploaded?.(msg.data);
|
||||
break;
|
||||
case "voice_recording_started":
|
||||
h.onVoiceRecordingStarted?.(msg.data);
|
||||
if (msg.data !== undefined) h.onVoiceRecordingStarted?.(msg.data);
|
||||
break;
|
||||
case "voice_recording_stopped":
|
||||
h.onVoiceRecordingStopped?.(msg.data);
|
||||
if (msg.data !== undefined) h.onVoiceRecordingStopped?.(msg.data);
|
||||
break;
|
||||
case "voice_recording_uploaded":
|
||||
if (msg.data !== undefined) h.onVoiceRecordingUploaded?.(msg.data);
|
||||
break;
|
||||
case "voice_pcm_data":
|
||||
h.onVoicePcmData?.(msg.data);
|
||||
if (msg.data !== undefined) h.onVoicePcmData?.(msg.data);
|
||||
break;
|
||||
case "voice_active_user":
|
||||
h.onVoiceActiveUser?.(msg.data);
|
||||
if (msg.data !== undefined) h.onVoiceActiveUser?.(msg.data);
|
||||
break;
|
||||
case "attachment_created":
|
||||
h.onAttachmentCreated?.(msg.data);
|
||||
case "voice_analyzed":
|
||||
if (msg.data !== undefined) h.onVoiceAnalyzed?.(msg.data);
|
||||
break;
|
||||
case "reaction_added":
|
||||
if (msg.data !== undefined) h.onReactionAdded?.(msg.data);
|
||||
break;
|
||||
case "reaction_removed":
|
||||
if (msg.data !== undefined) h.onReactionRemoved?.(msg.data);
|
||||
break;
|
||||
case "thread_created":
|
||||
if (msg.data !== undefined) h.onThreadCreated?.(msg.data);
|
||||
break;
|
||||
case "thread_deleted":
|
||||
if (msg.data !== undefined) h.onThreadDeleted?.(msg.data);
|
||||
break;
|
||||
case "thread_updated":
|
||||
if (msg.data !== undefined) h.onThreadUpdated?.(msg.data);
|
||||
break;
|
||||
case "channel_topic_updated":
|
||||
if (msg.data !== undefined) h.onChannelTopicUpdated?.(msg.data);
|
||||
break;
|
||||
case "presence_updated":
|
||||
if (msg.data !== undefined) h.onPresenceUpdated?.(msg.data);
|
||||
break;
|
||||
case "guild_member_added":
|
||||
if (msg.data !== undefined) h.onGuildMemberAdded?.(msg.data);
|
||||
break;
|
||||
case "guild_member_removed":
|
||||
if (msg.data !== undefined) h.onGuildMemberRemoved?.(msg.data);
|
||||
break;
|
||||
case "analysis_queue_status":
|
||||
// analysis_queue_status is monitoring-only — no UI action needed
|
||||
// monitoring-only — no UI action needed
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -178,6 +242,18 @@ export function useDashboardSocket(handlers: WsHandlers) {
|
||||
handlersRef.current.onVoiceRecordingUploaded?.(d),
|
||||
onVoicePcmData: (d) => handlersRef.current.onVoicePcmData?.(d),
|
||||
onVoiceActiveUser: (d) => handlersRef.current.onVoiceActiveUser?.(d),
|
||||
onReactionAdded: (d) => handlersRef.current.onReactionAdded?.(d),
|
||||
onReactionRemoved: (d) => handlersRef.current.onReactionRemoved?.(d),
|
||||
onThreadCreated: (d) => handlersRef.current.onThreadCreated?.(d),
|
||||
onThreadDeleted: (d) => handlersRef.current.onThreadDeleted?.(d),
|
||||
onThreadUpdated: (d) => handlersRef.current.onThreadUpdated?.(d),
|
||||
onChannelTopicUpdated: (d) =>
|
||||
handlersRef.current.onChannelTopicUpdated?.(d),
|
||||
onPresenceUpdated: (d) => handlersRef.current.onPresenceUpdated?.(d),
|
||||
onGuildMemberAdded: (d) => handlersRef.current.onGuildMemberAdded?.(d),
|
||||
onGuildMemberRemoved: (d) =>
|
||||
handlersRef.current.onGuildMemberRemoved?.(d),
|
||||
onVoiceAnalyzed: (d) => handlersRef.current.onVoiceAnalyzed?.(d),
|
||||
};
|
||||
|
||||
_listeners.add(wrapper);
|
||||
@@ -207,5 +283,3 @@ export function useDashboardSocket(handlers: WsHandlers) {
|
||||
|
||||
return { status, send, socketRef: { current: _wsInstance } };
|
||||
}
|
||||
|
||||
// Alias for backward compatibility
|
||||
|
||||
@@ -28,17 +28,12 @@ export default {
|
||||
sm: "calc(var(--radius) - 4px)",
|
||||
},
|
||||
animation: {
|
||||
shimmer: "shimmer 2s linear infinite",
|
||||
"bar-pulse": "bar-pulse 0.4s ease-in-out infinite",
|
||||
"fade-in-up": "fadeInUp 0.5s ease-out",
|
||||
"fade-in": "fadeIn 0.3s ease-out",
|
||||
"glow-pulse": "glowPulse 3s ease-in-out infinite",
|
||||
},
|
||||
keyframes: {
|
||||
shimmer: {
|
||||
"0%": { backgroundPosition: "-200% 0" },
|
||||
"100%": { backgroundPosition: "200% 0" },
|
||||
},
|
||||
"bar-pulse": {
|
||||
"0%, 100%": { transform: "scaleY(0.8)" },
|
||||
"50%": { transform: "scaleY(1.2)" },
|
||||
|
||||
Reference in New Issue
Block a user