refactor(frontend): finish shadcn→custom primitive migration (green build)

- Remove tw-animate-css import + dead src/components/ui shadcn tree
- Convert 7 orphaned components (moderation, analysis, guild-selector,
  voice/activity-timeline, shared/empty+error) to new primitives
- Add missing moderation/view.tsx; analysis uses SearchPanel directly
- globals.css now uses new signal-driven ops-console tokens
- tsc --noEmit clean, next build green (11 routes), local smoke 200
This commit is contained in:
asepharyana committed 2026-08-14 10:49:44 +07:00
1 parent 5816e94a63
commit 5bbf75a65b
130 files changed
+4437 -12984

No files matched your search

@@ -2,17 +2,14 @@
import { Loader2, Search, Sparkles } from "lucide-react";
import { useCallback, useState } from "react";
import { Avatar } from "@/components/primitives/avatar";
import { Badge } from "@/components/primitives/badge";
import { Button } from "@/components/primitives/button";
import { Input } from "@/components/primitives/input";
import { Progress } from "@/components/primitives/progress";
import { EmptyState, LoadingSkeleton } from "@/components/shared";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { useMessageSearch } from "@/hooks";
import { renderMessageContent, safeParseJsonArray } from "@/lib/format";
import { cn } from "@/lib/utils";
export function SearchPanel() {
const [query, setQuery] = useState("");
@@ -29,10 +26,10 @@ export function SearchPanel() {
}, [query]);
return (
<div className="space-y-5 animate-fade-in-up">
<div className="space-y-5">
<div className="flex gap-2">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-[var(--color-ink-soft)]" />
<Input
placeholder="Search message content, AI flags, analysis text…"
value={query}
@@ -51,7 +48,7 @@ export function SearchPanel() {
<LoadingSkeleton count={5} height="h-28" />
) : results !== undefined ? (
<>
<p className="text-sm text-muted-foreground">
<p className="text-sm text-[var(--color-ink-soft)]">
Found {results.length} result{results.length !== 1 ? "s" : ""}
</p>
{results.length === 0 ? (
@@ -62,92 +59,84 @@ export function SearchPanel() {
) : (
<div className="space-y-2">
{results.map((msg) => (
<Card key={msg.id}>
<CardContent className="p-4">
<div className="flex items-start gap-3">
<Avatar className="size-8 shrink-0 mt-0.5">
<AvatarImage src={msg.avatar_url ?? undefined} />
<AvatarFallback className="text-xs">
{msg.username?.charAt(0).toUpperCase() ?? "?"}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-2">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium">
{msg.username}
</span>
<span className="text-xs text-muted-foreground">
{msg.created_at
? new Date(msg.created_at).toLocaleString()
: ""}
</span>
{msg.ai_status && (
<Badge
variant="outline"
className={cn(
"text-[10px] px-1.5 py-0 h-4",
msg.ai_status === "clean" && "text-green-500",
msg.ai_status === "flagged" && "text-red-500",
)}
>
{msg.ai_status}
</Badge>
)}
</div>
<p className="text-sm leading-relaxed">
{renderMessageContent(
msg.edited_content ?? msg.content,
msg.metadata,
)}
</p>
{msg.ai_moderation_flags &&
msg.ai_moderation_flags !== "[]" && (
<div className="flex flex-wrap gap-1">
{safeParseJsonArray(msg.ai_moderation_flags).map(
(flag) => (
<Badge
key={flag}
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{flag}
</Badge>
),
)}
</div>
)}
{msg.ai_analysis && (
<p className="text-xs text-muted-foreground italic line-clamp-2 leading-relaxed">
<Sparkles className="size-3 inline mr-1" />
{msg.ai_analysis}
</p>
)}
{msg.ai_confidence != null && (
<div className="flex items-center gap-2 max-w-40">
<Progress
value={msg.ai_confidence * 100}
className="h-1.5"
/>
<span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
{(msg.ai_confidence * 100).toFixed(0)}%
</span>
</div>
<div key={msg.id} className="surface p-4">
<div className="flex items-start gap-3">
<Avatar
src={msg.avatar_url ?? undefined}
name={msg.username}
size={32}
className="mt-0.5 shrink-0"
/>
<div className="flex-1 min-w-0 space-y-2">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium text-[var(--color-ink)]">
{msg.username}
</span>
<span className="text-xs text-[var(--color-ink-soft)]">
{msg.created_at
? new Date(msg.created_at).toLocaleString()
: ""}
</span>
{msg.ai_status && (
<Badge
tone={
msg.ai_status === "clean"
? "signal"
: msg.ai_status === "flagged"
? "vermilion"
: "neutral"
}
>
{msg.ai_status}
</Badge>
)}
</div>
<p className="text-sm leading-relaxed text-[var(--color-ink)]">
{renderMessageContent(
msg.edited_content ?? msg.content,
msg.metadata,
)}
</p>
{msg.ai_moderation_flags &&
msg.ai_moderation_flags !== "[]" && (
<div className="flex flex-wrap gap-1">
{safeParseJsonArray(msg.ai_moderation_flags).map(
(flag) => (
<Badge key={flag} tone="vermilion">
{flag}
</Badge>
),
)}
</div>
)}
{msg.ai_analysis && (
<p className="text-xs text-[var(--color-ink-soft)] italic line-clamp-2 leading-relaxed">
<Sparkles className="size-3 inline mr-1" />
{msg.ai_analysis}
</p>
)}
{msg.ai_confidence != null && (
<div className="flex items-center gap-2 max-w-40">
<Progress value={msg.ai_confidence * 100} />
<span className="text-[11px] text-[var(--color-ink-soft)] tabular-nums shrink-0">
{(msg.ai_confidence * 100).toFixed(0)}%
</span>
</div>
)}
</div>
</CardContent>
</Card>
</div>
</div>
))}
</div>
)}
</>
) : (
<div className="flex flex-col items-center justify-center py-24 text-center">
<Search className="size-12 text-muted-foreground/30 mb-4" />
<p className="text-sm text-muted-foreground">
<Search className="size-12 text-[var(--color-ink-soft)] mb-4" />
<p className="text-sm text-[var(--color-ink-soft)]">
Enter a search query to find messages across all channels.
</p>
<p className="text-xs text-muted-foreground/60 mt-1">
<p className="text-xs text-[var(--color-ink-soft)] mt-1">
Searches message content, AI flags, and analysis text.
</p>
</div>
@@ -0,0 +1,83 @@
"use client";
import { motion, useReducedMotion } from "motion/react";
import { useId } from "react";
export interface AreaPoint {
label: string;
value: number;
}
export interface AreaActivityProps {
data: AreaPoint[];
height?: number;
stroke?: string;
className?: string;
label?: string;
}
export function AreaActivity({
data,
height = 160,
stroke = "var(--color-signal)",
className,
label,
}: AreaActivityProps) {
const id = useId().replace(/:/g, "");
const reduce = useReducedMotion();
const width = 600;
if (data.length === 0)
return <div className={className} style={{ height }} />;
const max = Math.max(...data.map((d) => d.value), 1);
const stepX = width / Math.max(data.length - 1, 1);
const pts = data.map((d, i) => {
const x = i * stepX;
const y = height - (d.value / max) * (height - 10) - 5;
return [x, y] as const;
});
const line = pts
.map(
(p, i) => `${i === 0 ? "M" : "L"}${p[0].toFixed(1)},${p[1].toFixed(1)}`,
)
.join(" ");
const area = `${line} L${width},${height} L0,${height} Z`;
const pathLen = 1400;
return (
<svg
viewBox={`0 0 ${width} ${height}`}
className={className}
style={{ width: "100%", height }}
preserveAspectRatio="none"
role="img"
aria-label={label ?? "Activity chart"}
>
<defs>
<linearGradient id={`area-${id}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={stroke} stopOpacity="0.32" />
<stop offset="100%" stopColor={stroke} stopOpacity="0.02" />
</linearGradient>
</defs>
<motion.path
d={area}
fill={`url(#area-${id})`}
initial={reduce ? false : { pathLength: 0, opacity: 0.4 }}
animate={{ pathLength: 1, opacity: 1 }}
transition={{ duration: 0.9, ease: [0.22, 1, 0.36, 1] }}
/>
<motion.path
d={line}
fill="none"
stroke={stroke}
strokeWidth={2}
strokeLinejoin="round"
strokeLinecap="round"
initial={reduce ? false : { pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.9, ease: [0.22, 1, 0.36, 1] }}
style={{ strokeDasharray: pathLen }}
/>
</svg>
);
}
@@ -0,0 +1,89 @@
"use client";
import { motion, useReducedMotion } from "motion/react";
import { useId } from "react";
export interface RadialGaugeProps {
/** 0..1 health ratio */
value: number;
size?: number;
label?: string;
sublabel?: string;
tone?: "signal" | "amber" | "vermilion";
}
const toneColor = {
signal: "var(--color-signal)",
amber: "var(--color-amber)",
vermilion: "var(--color-vermilion)",
};
export function RadialGauge({
value,
size = 160,
label,
sublabel,
tone = "signal",
}: RadialGaugeProps) {
const id = useId().replace(/:/g, "");
const reduce = useReducedMotion();
const stroke = 12;
const r = (size - stroke) / 2;
const c = 2 * Math.PI * r;
const pct = Math.max(0, Math.min(1, value));
const dash = c * pct;
return (
<div
className="relative inline-flex items-center justify-center"
style={{ width: size, height: size }}
>
<svg
width={size}
height={size}
viewBox={`0 0 ${size} ${size}`}
className="-rotate-90"
>
<circle
cx={size / 2}
cy={size / 2}
r={r}
fill="none"
stroke="var(--color-hairline)"
strokeWidth={stroke}
/>
<motion.circle
cx={size / 2}
cy={size / 2}
r={r}
fill="none"
stroke={toneColor[tone]}
strokeWidth={stroke}
strokeLinecap="round"
strokeDasharray={c}
initial={reduce ? false : { strokeDashoffset: c }}
animate={{ strokeDashoffset: c - dash }}
transition={{ duration: 1, ease: [0.22, 1, 0.36, 1] }}
/>
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center text-center">
<span
className="display text-2xl mono"
style={{ color: toneColor[tone] }}
>
{Math.round(pct * 100)}%
</span>
{label && (
<span className="text-[11px] font-medium text-[var(--color-ink-soft)] uppercase tracking-wide">
{label}
</span>
)}
{sublabel && (
<span className="text-[10px] text-[var(--color-ink-soft)]/70">
{sublabel}
</span>
)}
</div>
</div>
);
}
@@ -0,0 +1,56 @@
"use client";
import { cn } from "@/lib/utils";
export interface RibbonSegment {
id: string;
label: string;
value: number; // relative duration
tone?: "signal" | "amber" | "vermilion" | "neutral";
}
const toneClass = {
signal: "bg-[var(--color-signal)]",
amber: "bg-[var(--color-amber)]",
vermilion: "bg-[var(--color-vermilion)]",
neutral: "bg-[var(--color-ink-soft)]/40",
};
export interface SessionRibbonProps {
segments: RibbonSegment[];
className?: string;
height?: number;
}
export function SessionRibbon({
segments,
className,
height = 28,
}: SessionRibbonProps) {
const total = segments.reduce((s, x) => s + x.value, 0) || 1;
return (
<div
className={cn(
"flex w-full gap-0.5 overflow-hidden rounded-[var(--radius-r-control)]",
className,
)}
style={{ height }}
>
{segments.map((s) => (
<div
key={s.id}
className={cn(
"group relative flex items-center justify-center rounded-sm transition-all",
toneClass[s.tone ?? "signal"],
)}
style={{ width: `${(s.value / total) * 100}%` }}
title={`${s.label}: ${s.value}`}
>
<span className="pointer-events-none absolute inset-x-0 -top-6 hidden whitespace-nowrap rounded bg-[var(--color-ink)] px-1.5 py-0.5 text-[10px] text-[var(--color-canvas)] group-hover:block">
{s.label}
</span>
</div>
))}
</div>
);
}
@@ -0,0 +1,67 @@
"use client";
import { useId } from "react";
export interface SparklineProps {
data: number[];
width?: number;
height?: number;
stroke?: string;
className?: string;
fill?: boolean;
}
export function Sparkline({
data,
width = 120,
height = 36,
stroke = "var(--color-signal)",
className,
fill = true,
}: SparklineProps) {
const id = useId().replace(/:/g, "");
if (data.length < 2)
return <svg width={width} height={height} className={className} />;
const min = Math.min(...data);
const max = Math.max(...data);
const span = max - min || 1;
const stepX = width / (data.length - 1);
const pts = data.map((v, i) => {
const x = i * stepX;
const y = height - ((v - min) / span) * (height - 4) - 2;
return [x, y] as const;
});
const line = pts
.map(
(p, i) => `${i === 0 ? "M" : "L"}${p[0].toFixed(1)},${p[1].toFixed(1)}`,
)
.join(" ");
const area = `${line} L${width},${height} L0,${height} Z`;
return (
<svg
width={width}
height={height}
viewBox={`0 0 ${width} ${height}`}
className={className}
preserveAspectRatio="none"
>
<defs>
<linearGradient id={`spark-${id}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={stroke} stopOpacity="0.28" />
<stop offset="100%" stopColor={stroke} stopOpacity="0" />
</linearGradient>
</defs>
{fill && <path d={area} fill={`url(#spark-${id})`} />}
<path
d={line}
fill="none"
stroke={stroke}
strokeWidth={1.6}
strokeLinejoin="round"
strokeLinecap="round"
/>
</svg>
);
}
@@ -0,0 +1,76 @@
"use client";
import { motion, useReducedMotion } from "motion/react";
import { useMemo } from "react";
import { cn } from "@/lib/utils";
export interface WaveformProps {
seed: string | number;
bars?: number;
height?: number;
className?: string;
tone?: "signal" | "amber" | "vermilion";
}
// deterministic pseudo-random from seed so the shape is stable per recording
function hashSeed(seed: string | number): number {
const s = String(seed);
let h = 2166136261;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return h >>> 0;
}
export function Waveform({
seed,
bars = 40,
height = 40,
className,
tone = "signal",
}: WaveformProps) {
const reduce = useReducedMotion();
const values = useMemo(() => {
let state = hashSeed(seed) || 1;
const out: number[] = [];
for (let i = 0; i < bars; i++) {
state = (Math.imul(state, 1103515245) + 12345) >>> 0;
const r = (state % 1000) / 1000;
// envelope: louder in the middle, quieter at edges
const env = Math.sin((i / (bars - 1)) * Math.PI);
out.push(0.18 + r * 0.82 * (0.4 + env * 0.6));
}
return out;
}, [seed, bars]);
const color = {
signal: "var(--color-signal)",
amber: "var(--color-amber)",
vermilion: "var(--color-vermilion)",
}[tone];
return (
<div
className={cn("flex items-end gap-[2px]", className)}
style={{ height }}
aria-hidden
>
{values.map((v, i) => (
<motion.span
key={i}
className="flex-1 rounded-[2px]"
style={{ background: color, height: `${Math.max(8, v * 100)}%` }}
initial={reduce ? false : { scaleY: 0.2, opacity: 0 }}
animate={{ scaleY: 1, opacity: 1 }}
whileHover={{ scaleY: 1.15 }}
transition={{
duration: 0.3,
delay: reduce ? 0 : i * 0.006,
ease: [0.22, 1, 0.36, 1],
}}
/>
))}
</div>
);
}
@@ -1,129 +1,35 @@
"use client";
import type { AreaPoint } from "@/components/charts/area-activity";
import { AreaActivity } from "@/components/charts/area-activity";
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Card } from "@/components/ui/card";
import { useMounted } from "@/lib/hooks/use-mounted";
import { cn } from "@/lib/utils";
interface ActivityChartProps {
data?: { day: string; messages: number; flagged: number }[];
export interface ActivityChartProps {
data: {
day: string;
messages: number;
flagged: number;
active_users: number;
}[];
}
const TOOLTIP_STYLE = {
background: "oklch(0.11 0.02 245 / 0.95)",
border: "1px solid oklch(1 0 0 / 0.08)",
borderRadius: 8,
fontSize: 12,
color: "oklch(0.93 0.01 245)",
} as const;
export function ActivityChart({ data = [] }: ActivityChartProps) {
const mounted = useMounted();
export function ActivityChart({ data }: ActivityChartProps) {
const points: AreaPoint[] = data.map((d) => ({
label: d.day,
value: d.messages,
}));
return (
<Card className={cn("[--card-spacing:0px]", "rounded-2xl", "p-5")}>
<div className="flex items-center justify-between mb-3">
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">
Message Activity
</span>
<span className="text-[10px] text-text-secondary/50">
messages · flagged per day
<div className="surface p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="text-sm font-semibold">Daily messages</h3>
<span className="pill bg-[var(--color-signal)]/15 text-[var(--color-signal)]">
{data.length}d
</span>
</div>
<div className="h-56">
{mounted ? (
<ResponsiveContainer
width="100%"
height="100%"
minWidth={0}
minHeight={0}
>
<AreaChart data={data} margin={{ left: -18, right: 4, top: 4 }}>
<defs>
<linearGradient id="gradMessages" x1="0" y1="0" x2="0" y2="1">
<stop
offset="0%"
stopColor="var(--color-primary)"
stopOpacity={0.45}
/>
<stop
offset="100%"
stopColor="var(--color-primary)"
stopOpacity={0.02}
/>
</linearGradient>
<linearGradient id="gradFlagged" x1="0" y1="0" x2="0" y2="1">
<stop
offset="0%"
stopColor="oklch(0.62 0.19 25)"
stopOpacity={0.5}
/>
<stop
offset="100%"
stopColor="oklch(0.62 0.19 25)"
stopOpacity={0.02}
/>
</linearGradient>
</defs>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--color-border)"
vertical={false}
/>
<XAxis
dataKey="day"
axisLine={false}
tickLine={false}
tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }}
tickFormatter={(v: string) => {
const [, m, d] = v.split("-");
return `${Number(m)}/${Number(d)}`;
}}
minTickGap={24}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }}
allowDecimals={false}
/>
<Tooltip
contentStyle={TOOLTIP_STYLE}
labelFormatter={(label) => {
const [y, m, d] = String(label).split("-");
return `${d}/${m}/${y}`;
}}
/>
<Area
type="monotone"
dataKey="messages"
stroke="var(--color-primary)"
strokeWidth={2}
fill="url(#gradMessages)"
name="Messages"
/>
<Area
type="monotone"
dataKey="flagged"
stroke="oklch(0.62 0.19 25)"
strokeWidth={2}
fill="url(#gradFlagged)"
name="Flagged"
/>
</AreaChart>
</ResponsiveContainer>
) : (
<div className="h-full w-full animate-pulse rounded-md bg-card/40" />
)}
</div>
</Card>
<ActivityChartInner points={points} />
</div>
);
}
function ActivityChartInner({ points }: { points: AreaPoint[] }) {
return (
<AreaActivity data={points} height={180} label="Daily message activity" />
);
}
@@ -2,193 +2,139 @@
import { Hash, Search } from "lucide-react";
import { useCallback, useState } from "react";
import { Badge } from "@/components/primitives/badge";
import { Button } from "@/components/primitives/button";
import { Input } from "@/components/primitives/input";
import { EmptyState, LoadingSkeleton } from "@/components/shared";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useChannelDetail, useChannels } from "@/hooks";
import { renderMessageContent } from "@/lib/format";
import type { DashboardChannel } from "@/lib/types";
import { cn } from "@/lib/utils";
export function ChannelsSection({ guildId }: { guildId?: string }) {
const [search, setSearch] = useState("");
const [selectedId, setSelectedId] = useState<string | null>(null);
const {
data: channels = [],
isLoading,
error,
mutate: refetch,
} = useChannels(guildId ?? "", search);
const { data: channels = [], isLoading } = useChannels(guildId ?? "", search);
const { data: detail } = useChannelDetail(selectedId);
const handleSearch = useCallback((v: string) => {
setSearch(v);
setSelectedId(null);
}, []);
const handleSearch = useCallback((v: string) => setSearch(v), []);
if (error) {
if (isLoading) return <LoadingSkeleton count={8} />;
if (channels.length === 0)
return (
<Card
className={cn(
"p-6 text-sm",
"border border-red-500/30 ring-red-500/20",
"[--card-spacing:0px]",
"rounded-2xl",
)}
>
Failed to load channels: {error.message}
<Button
variant="outline"
size="sm"
className="ml-2"
onClick={() => refetch()}
>
Retry
</Button>
</Card>
<EmptyState
icon={Hash}
title="No channels"
description="No channels in this guild."
/>
);
}
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="space-y-3">
<div className="grid gap-3 lg:grid-cols-[1fr_320px]">
<div className="surface flex flex-col gap-2 p-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-[var(--color-ink-soft)]" />
<Input
placeholder="Search by channel ID or name…"
mono
placeholder="search channels…"
value={search}
onChange={(e) => handleSearch(e.target.value)}
className="pl-9 h-9"
className="pl-9"
/>
</div>
{isLoading ? (
<LoadingSkeleton count={5} height="h-14" />
) : channels.length === 0 ? (
<EmptyState icon={Hash} title="No channels found" />
) : (
<div className="space-y-2">
{channels.map((channel) => (
<ChannelRow
key={channel.channel_id}
channel={channel}
active={selectedId === channel.channel_id}
onSelect={setSelectedId}
/>
))}
</div>
)}
{channels.map((c) => (
<ChannelRow
key={c.channel_id}
channel={c}
selected={selectedId === c.channel_id}
onSelect={() => setSelectedId(c.channel_id)}
/>
))}
</div>
<Card
className={cn("h-fit", "[--card-spacing:0px]", "rounded-2xl", "p-5")}
>
<div className="surface p-4">
{detail ? (
<div className="space-y-3">
<div className="flex items-center gap-2">
<Hash className="size-4 text-primary" />
<p className="text-sm font-semibold text-text-primary">
{detail.channel_name ?? detail.channel_id}
</p>
<p className="text-[10px] font-mono text-text-secondary/50 ml-auto">
{detail.channel_id}
</p>
</div>
<div className="flex flex-wrap gap-1.5">
<Badge variant="outline">Messages: {detail.total_messages}</Badge>
<Badge variant="destructive">
Flagged: {detail.flagged_count}
</Badge>
<Badge
variant="outline"
className="border-green-500/40 text-green-500"
>
Clean: {detail.clean_count}
</Badge>
</div>
{detail.culture_summary && (
<div className="rounded-lg border border-border/40 bg-card/40 px-3 py-2">
<p className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50 mb-1">
Culture summary
</p>
<p className="text-xs leading-relaxed text-text-secondary">
{detail.culture_summary}
</p>
<div className="flex flex-col gap-3.5">
<div className="flex items-center gap-2.5">
<span className="flex size-9 items-center justify-center rounded-[var(--radius-r-control)] bg-[var(--color-surface-2)]">
<Hash className="size-4 text-[var(--color-ink-soft)]" />
</span>
<div>
<div className="font-semibold">
{detail.channel_name ?? detail.channel_id}
</div>
<div className="text-xs text-[var(--color-ink-soft)]">
{detail.total_messages.toLocaleString()} messages
</div>
</div>
)}
{detail.recent_messages.length > 0 && (
<div className="space-y-1.5">
<p className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50">
Recent messages
</p>
{detail.recent_messages.slice(0, 5).map((msg) => (
<div
key={msg.id}
className="rounded-lg border border-border/40 bg-card/40 px-3 py-2"
>
<p className="text-xs leading-relaxed text-text-secondary line-clamp-2">
{msg.username}:{" "}
{renderMessageContent(msg.content, msg.metadata) ||
"(no text content)"}
</p>
<p className="mt-1 text-[10px] font-mono text-text-secondary/40">
{new Date(msg.created_at).toLocaleString()}
</p>
</div>
))}
</div>
)}
</div>
) : (
<div className="flex h-48 flex-col items-center justify-center text-center">
<Hash className="size-8 text-text-secondary/30 mb-2" />
<p className="text-xs text-text-secondary/60">
Select a channel to see its culture summary and recent messages.
</div>
<Stat
label="Flagged"
value={detail.flagged_count}
tone="vermilion"
/>
<p className="text-xs text-[var(--color-ink-soft)]">
{detail.culture_summary ?? "No data yet."}
</p>
</div>
) : (
<p className="text-sm text-[var(--color-ink-soft)]">
Select a channel to inspect.
</p>
)}
</Card>
</div>
</div>
);
}
function ChannelRow({
channel,
active,
selected,
onSelect,
}: {
channel: DashboardChannel;
active: boolean;
onSelect: (id: string) => void;
selected: boolean;
onSelect: () => void;
}) {
const total = channel.total_messages + channel.flagged_count || 1;
return (
<Card
className={active ? "border-primary/40 bg-primary/5" : undefined}
onClick={() => onSelect(channel.channel_id)}
<button
type="button"
onClick={onSelect}
className="flex items-center gap-3 rounded-[var(--radius-r-control)] px-2.5 py-2 text-left transition-colors hover:bg-[var(--color-surface-2)] data-[selected]:bg-[var(--color-signal)]/8"
data-selected={selected}
>
<CardContent className="flex cursor-pointer items-center gap-3 p-3">
<Hash className="size-4 shrink-0 text-text-secondary/50" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-text-primary">
{channel.channel_name ?? channel.channel_id}
</p>
<p className="truncate text-[10px] font-mono text-text-secondary/50">
{channel.channel_id}
</p>
</div>
<div className="flex shrink-0 gap-1.5">
<Badge variant="outline">{channel.total_messages}</Badge>
{channel.flagged_count > 0 && (
<Badge variant="destructive">{channel.flagged_count}</Badge>
)}
</div>
</CardContent>
</Card>
<Hash className="size-4 text-[var(--color-ink-soft)]" />
<span className="min-w-0 flex-1 truncate text-sm">
{channel.channel_name ?? channel.channel_id}
</span>
<span className="mono text-xs text-[var(--color-ink-soft)]">
{channel.flagged_count}/{channel.total_messages}
</span>
<div className="h-1.5 w-10 overflow-hidden rounded-full bg-[var(--color-hairline)]">
<div
className="h-full bg-[var(--color-signal)]"
style={{ width: `${(channel.flagged_count / total) * 100}%` }}
/>
</div>
</button>
);
}
function Stat({
label,
value,
tone,
}: {
label: string;
value: number;
tone: "vermilion";
}) {
return (
<div className="surface-2 flex items-center justify-between p-2.5">
<span className="text-xs text-[var(--color-ink-soft)]">{label}</span>
<span className="mono font-semibold text-[var(--color-vermilion)]">
{value}
</span>
</div>
);
}
@@ -1,109 +1,29 @@
"use client";
import type { AreaPoint } from "@/components/charts/area-activity";
import { AreaActivity } from "@/components/charts/area-activity";
import {
Bar,
BarChart,
Cell,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Card } from "@/components/ui/card";
import { useMounted } from "@/lib/hooks/use-mounted";
import { cn } from "@/lib/utils";
interface HourlyActivityChartProps {
data?: { hour: number; messages: number; flagged: number }[];
export interface HourlyActivityChartProps {
data: { hour: number; messages: number; flagged: number }[];
}
const HOUR_LABELS = Array.from({ length: 24 }, (_, i) => {
const h = i % 12 === 0 ? 12 : i % 12;
return `${h}${i < 12 ? "am" : "pm"}`;
});
const TOOLTIP_STYLE = {
background: "oklch(0.11 0.02 245 / 0.95)",
border: "1px solid oklch(1 0 0 / 0.08)",
borderRadius: 8,
fontSize: 12,
color: "oklch(0.93 0.01 245)",
} as const;
export function HourlyActivityChart({ data = [] }: HourlyActivityChartProps) {
const mounted = useMounted();
const full = Array.from({ length: 24 }, (_, hour) => {
const found = data.find((d) => d.hour === hour);
return {
hour,
label: HOUR_LABELS[hour],
messages: found?.messages ?? 0,
flagged: found?.flagged ?? 0,
};
});
const peak = Math.max(1, ...full.map((d) => d.messages));
const maxMessages = Math.max(...full.map((d) => d.messages));
export function HourlyActivityChart({ data }: HourlyActivityChartProps) {
const points: AreaPoint[] = data.map((d) => ({
label: `${d.hour}:00`,
value: d.messages,
}));
return (
<Card className={cn("[--card-spacing:0px]", "rounded-2xl", "p-5")}>
<div className="flex items-center justify-between mb-3">
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">
Hourly Activity
</span>
<span className="text-[10px] text-text-secondary/50">
last 24h · peak {maxMessages} msgs
<div className="surface p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="text-sm font-semibold">Hourly distribution</h3>
<span className="text-xs text-[var(--color-ink-soft)]">
00:00 – 23:00
</span>
</div>
<div className="h-40">
{mounted ? (
<ResponsiveContainer
width="100%"
height="100%"
minWidth={0}
minHeight={0}
>
<BarChart data={full} margin={{ left: -22, right: 4, top: 4 }}>
<XAxis
dataKey="label"
axisLine={false}
tickLine={false}
tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 9 }}
interval={3}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }}
allowDecimals={false}
domain={[0, (dataMax: number) => Math.max(1, dataMax)]}
/>
<Tooltip
contentStyle={TOOLTIP_STYLE}
cursor={{ fill: "oklch(1 0 0 / 0.04)" }}
labelFormatter={(label) => `Hour ${label}`}
/>
<Bar dataKey="messages" radius={[3, 3, 0, 0]} name="Messages">
{full.map((d) => (
<Cell
key={d.hour}
fill={
d.messages === maxMessages && maxMessages > 0
? "var(--color-primary)"
: d.messages > peak * 0.5
? "oklch(0.52 0.13 245 / 0.7)"
: "oklch(0.52 0.13 245 / 0.35)"
}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
) : (
<div className="h-full w-full animate-pulse rounded-md bg-card/40" />
)}
</div>
</Card>
<AreaActivity
data={points}
height={140}
stroke="var(--color-amber)"
label="Hourly message activity"
/>
</div>
);
}
@@ -1,102 +1,53 @@
"use client";
import { RadialGauge } from "@/components/charts/radial-gauge";
import type { DashboardStats } from "@/lib/types";
import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from "recharts";
import { Card } from "@/components/ui/card";
import { useMounted } from "@/lib/hooks/use-mounted";
import { cn } from "@/lib/utils";
interface ModerationDonutProps {
data?: { name: string; value: number; color: string }[];
export interface ModerationDonutProps {
stats?: DashboardStats;
}
const TOOLTIP_STYLE = {
background: "oklch(0.11 0.02 245 / 0.95)",
border: "1px solid oklch(1 0 0 / 0.08)",
borderRadius: 8,
fontSize: 12,
color: "oklch(0.93 0.01 245)",
} as const;
export function ModerationDonut({ data = [] }: ModerationDonutProps) {
const mounted = useMounted();
const total = data.reduce((sum, d) => sum + d.value, 0);
const cleanPct =
total > 0
? Math.round(
((data.find((d) => d.name === "Clean")?.value ?? 0) / total) * 100,
)
: 0;
export function ModerationDonut({ stats }: ModerationDonutProps) {
const clean = stats?.total_clean ?? 0;
const flagged = stats?.total_flagged ?? 0;
const warned = stats?.total_warned ?? 0;
const total = clean + flagged + warned || 1;
const ratio = clean / total;
return (
<Card className={cn("[--card-spacing:0px]", "rounded-2xl", "p-5")}>
<div className="flex items-center justify-between mb-1">
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">
Moderation Breakdown
</span>
<div className="surface flex flex-col items-center gap-3 p-4">
<h3 className="self-start text-sm font-semibold">Moderation health</h3>
<RadialGauge
value={ratio}
size={150}
label="Clean"
tone={ratio > 0.8 ? "signal" : ratio > 0.6 ? "amber" : "vermilion"}
/>
<div className="flex w-full flex-col gap-1.5 text-xs">
<Row label="Clean" value={clean} tone="var(--color-signal)" />
<Row label="Warned" value={warned} tone="var(--color-amber)" />
<Row label="Flagged" value={flagged} tone="var(--color-vermilion)" />
</div>
<div className="flex items-center gap-4">
<div className="relative h-40 w-40 shrink-0">
{mounted ? (
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={data}
dataKey="value"
nameKey="name"
innerRadius={52}
outerRadius={72}
paddingAngle={2}
strokeWidth={0}
>
{data.map((entry) => (
<Cell key={entry.name} fill={entry.color} />
))}
</Pie>
<Tooltip contentStyle={TOOLTIP_STYLE} />
</PieChart>
</ResponsiveContainer>
) : (
<div className="h-full w-full animate-pulse rounded-full bg-card/40" />
)}
<div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
<span className="text-2xl font-bold text-text-primary">
{total.toLocaleString()}
</span>
<span className="text-[10px] uppercase tracking-wide text-text-secondary/60">
messages
</span>
</div>
</div>
<div className="min-w-0 flex-1 space-y-1.5">
{data.map((d) => (
<div key={d.name} className="flex items-center gap-2 text-xs">
<span
className="size-2.5 shrink-0 rounded-sm"
style={{ background: d.color }}
/>
<span className="text-text-secondary">{d.name}</span>
<span className="ml-auto font-mono text-text-primary">
{d.value.toLocaleString()}
</span>
<span className="w-10 text-right font-mono text-text-secondary/50">
{total > 0 ? Math.round((d.value / total) * 100) : 0}%
</span>
</div>
))}
{cleanPct >= 90 && (
<p className="pt-1 text-[10px] text-green-500/80">
✓ Server is {cleanPct}% clean — moderation is holding up well
</p>
)}
{cleanPct < 90 && cleanPct > 0 && (
<p className="pt-1 text-[10px] text-amber-500/80">
{100 - cleanPct}% of messages were flagged or warned — review
activity in the Analysis tab
</p>
)}
</div>
</div>
</Card>
</div>
);
}
function Row({
label,
value,
tone,
}: {
label: string;
value: number;
tone: string;
}) {
return (
<div className="flex items-center justify-between">
<span className="flex items-center gap-2 text-[var(--color-ink-soft)]">
<span className="size-2 rounded-full" style={{ background: tone }} />
{label}
</span>
<span className="mono text-[var(--color-ink)]">
{value.toLocaleString()}
</span>
</div>
);
}
@@ -1,135 +1,85 @@
"use client";
import { Flame, Heart, SmilePlus } from "lucide-react";
import { Avatar } from "@/components/primitives/avatar";
import { Badge } from "@/components/primitives/badge";
import { EmptyState, LoadingSkeleton } from "@/components/shared";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { useTopReactions, useTopReactors } from "@/hooks";
import { renderMessageContent } from "@/lib/format";
import { cn } from "@/lib/utils";
function formatReactionTime(ts: number | null): string {
if (!ts) return "";
const diff = Date.now() - ts;
const hours = Math.floor(diff / 3600000);
if (hours < 1) return "baru saja";
if (hours < 24) return `${hours} jam lalu`;
const days = Math.floor(hours / 24);
return `${days} hari lalu`;
export interface ReactionsSectionProps {
initialReactions?: Awaited<ReturnType<typeof useTopReactions>>["data"];
}
export function ReactionsSection() {
const { data: reactions, isLoading: reactionsLoading } = useTopReactions();
const { data: reactors, isLoading: reactorsLoading } = useTopReactors();
if (reactionsLoading || reactorsLoading) return <LoadingSkeleton count={5} />;
const topReactions = (reactions ?? []).slice(0, 6);
const topReactors = (reactors ?? []).slice(0, 6);
return (
<div className="space-y-4">
<div>
<h3 className="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-text-secondary/50">
<Heart className="size-3" />
Top pesan paling di-reaksi
<div className="grid gap-3 lg:grid-cols-2">
<div className="surface p-4">
<h3 className="mb-3 flex items-center gap-2 text-sm font-semibold">
<Heart className="size-4 text-[var(--color-vermilion)]" />
Top reactions
</h3>
{reactionsLoading ? (
<LoadingSkeleton count={5} height="h-16" />
) : !reactions || reactions.length === 0 ? (
<Card className={cn("p-6", "[--card-spacing:0px]", "rounded-2xl")}>
<EmptyState
icon={Heart}
title="Belum ada reaksi"
description="Pesan dengan reaksi emoji akan muncul di sini."
/>
</Card>
{topReactions.length === 0 ? (
<EmptyState
icon={SmilePlus}
title="No reactions"
description="No reactions yet."
/>
) : (
<div className="space-y-2">
{reactions.map((r, i) => (
<Card
key={r.message_id}
className={cn(
"flex items-center gap-3 p-3",
"[--card-spacing:0px]",
"rounded-2xl",
)}
>
<span className="w-6 shrink-0 text-center font-mono text-xs text-text-secondary/50">
{i + 1}
<div className="flex flex-wrap gap-2">
{topReactions
.flatMap((m) =>
m.top_emojis.map((e) => ({ emoji: e.emoji, count: e.count })),
)
.reduce<{ emoji: string; count: number }[]>((acc, cur) => {
const found = acc.find((x) => x.emoji === cur.emoji);
if (found) found.count += cur.count;
else acc.push(cur);
return acc;
}, [])
.sort((a, b) => b.count - a.count)
.slice(0, 8)
.map((r) => (
<span
key={r.emoji}
className="flex items-center gap-1.5 rounded-[var(--radius-r-control)] bg-[var(--color-surface-2)] px-2.5 py-1 text-sm"
>
<span>{r.emoji}</span>
<span className="mono text-xs text-[var(--color-ink-soft)]">
{r.count}
</span>
</span>
<div className="flex shrink-0 gap-0.5 text-base">
{r.top_emojis.map((e) => (
<span
key={`${r.message_id}-${e.emoji}`}
title={`${e.emoji} ×${e.count}`}
>
{e.emoji}
</span>
))}
{r.top_emojis.length === 0 && (
<Heart className="size-4 text-text-secondary/30" />
)}
</div>
<div className="min-w-0 flex-1">
<p className="line-clamp-1 text-xs text-text-secondary">
{renderMessageContent(r.content, undefined) ||
"(tanpa teks)"}
</p>
<p className="mt-0.5 truncate text-[10px] font-mono text-text-secondary/40">
{r.username ?? "unknown"} · #
{r.channel_name ?? r.channel_id?.slice(0, 8)} ·{" "}
{formatReactionTime(r.created_at)}
</p>
</div>
<Badge variant="secondary" className="shrink-0 gap-1">
<Heart className="size-3" />
{r.reaction_count}
</Badge>
</Card>
))}
))}
</div>
)}
</div>
<div>
<h3 className="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-text-secondary/50">
<Flame className="size-3" />
Top reaktor — paling sering ngasih reaksi
<div className="surface p-4">
<h3 className="mb-3 flex items-center gap-2 text-sm font-semibold">
<Flame className="size-4 text-[var(--color-amber)]" />
Top reactors
</h3>
{reactorsLoading ? (
<LoadingSkeleton count={5} height="h-14" />
) : !reactors || reactors.length === 0 ? (
<Card className={cn("p-6", "[--card-spacing:0px]", "rounded-2xl")}>
<EmptyState
icon={SmilePlus}
title="Belum ada reaktor"
description="User yang ngasih reaksi emoji akan muncul di sini."
/>
</Card>
{topReactors.length === 0 ? (
<EmptyState
icon={SmilePlus}
title="No reactors"
description="No reactors yet."
/>
) : (
<div className="space-y-2">
{reactors.map((r, i) => (
<Card
key={r.user_id}
className={cn(
"flex items-center gap-3 p-3",
"[--card-spacing:0px]",
"rounded-2xl",
)}
>
<span className="w-6 shrink-0 text-center font-mono text-xs text-text-secondary/50">
{i + 1}
</span>
<div className="min-w-0 flex-1">
<p className="truncate text-xs font-medium text-text-primary">
{r.username}
</p>
<p className="mt-0.5 truncate text-[10px] font-mono text-text-secondary/40">
{r.messages_reacted} pesan di-reaksi · {r.emojis_used} emoji
unik · {r.adds_count} total reaksi
</p>
</div>
<Badge variant="secondary" className="shrink-0 gap-1">
<Flame className="size-3" />
{r.net_count}
</Badge>
</Card>
<div className="flex flex-col gap-2">
{topReactors.map((r) => (
<div key={r.user_id} className="flex items-center gap-3">
<Avatar name={r.username} size={28} />
<span className="flex-1 text-sm">{r.username}</span>
<Badge tone="signal">+{r.net_count}</Badge>
</div>
))}
</div>
)}
@@ -137,5 +87,3 @@ export function ReactionsSection() {
</div>
);
}
export default ReactionsSection;
@@ -1,101 +0,0 @@
"use client";
import type { LucideIcon } from "lucide-react";
import { Area, AreaChart, ResponsiveContainer } from "recharts";
import { Card } from "@/components/ui/card";
import { useMounted } from "@/lib/hooks/use-mounted";
import { cn } from "@/lib/utils";
interface StatCardProps {
label: string;
value: number | string;
icon: LucideIcon;
variant?: "default" | "danger" | "success";
sparklineData?: { value: number }[];
formatter?: (v: number) => string;
}
export function StatCard({
label,
value,
icon: Icon,
variant = "default",
sparklineData,
formatter = (v) => (typeof v === "number" ? v.toLocaleString() : v),
}: StatCardProps) {
const mounted = useMounted();
const accentColor = {
default: "var(--color-primary)",
danger: "var(--color-destructive)",
success: "oklch(0.6 0.18 160)",
}[variant];
const bgAccent = {
default: "bg-primary/10 text-primary",
danger: "bg-destructive/10 text-destructive",
success: "bg-emerald-500/10 text-emerald-500",
}[variant];
const numValue = typeof value === "number" ? value : Number(value);
return (
<Card
className={cn(
"relative overflow-hidden p-4",
"[--card-spacing:0px]",
"rounded-2xl",
)}
>
<div className="flex items-start justify-between mb-2">
<div className={cn("p-1.5 rounded-md", bgAccent)}>
<Icon className="size-4" />
</div>
</div>
<div
className="text-2xl font-mono font-semibold tracking-tight"
style={{ color: accentColor }}
>
{formatter(numValue)}
</div>
<div className="text-[11px] text-text-secondary font-medium mt-0.5 tracking-wide uppercase">
{label}
</div>
{/* Sparkline background */}
{sparklineData && sparklineData.length > 0 && mounted && (
<div className="absolute bottom-0 left-0 right-0 h-12 opacity-20">
<ResponsiveContainer
width="100%"
height={48}
minWidth={0}
minHeight={0}
>
<AreaChart data={sparklineData}>
<defs>
<linearGradient
id={`spark-grad-${label}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop offset="0%" stopColor={accentColor} stopOpacity={0.5} />
<stop offset="100%" stopColor={accentColor} stopOpacity={0} />
</linearGradient>
</defs>
<Area
type="monotone"
dataKey="value"
stroke={accentColor}
strokeWidth={1.5}
fill={`url(#spark-grad-${label})`}
dot={false}
isAnimationActive={false}
/>
</AreaChart>
</ResponsiveContainer>
</div>
)}
</Card>
);
}
@@ -1,74 +1,39 @@
"use client";
import { Hash } from "lucide-react";
import type { TopChannel } from "@/lib/types";
import {
Bar,
BarChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Card } from "@/components/ui/card";
import { useMounted } from "@/lib/hooks/use-mounted";
import { cn } from "@/lib/utils";
interface TopChannelsChartProps {
data?: { name: string; count: number }[];
export interface TopChannelsChartProps {
channels: TopChannel[];
}
export function TopChannelsChart({ data = [] }: TopChannelsChartProps) {
const mounted = useMounted();
export function TopChannelsChart({ channels }: TopChannelsChartProps) {
const max = Math.max(...channels.map((c) => c.message_count), 1);
const top = [...channels]
.sort((a, b) => b.message_count - a.message_count)
.slice(0, 8);
return (
<Card className={cn("[--card-spacing:0px]", "rounded-2xl", "p-5")}>
<div className="flex items-center gap-2 mb-3">
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">
Top Channels
</span>
<div className="surface p-4">
<h3 className="mb-3 text-sm font-semibold">Top channels</h3>
<div className="flex flex-col gap-2.5">
{top.map((c) => (
<div key={c.channel_id} className="flex items-center gap-3">
<span className="flex size-6 shrink-0 items-center justify-center rounded-[var(--radius-r-control)] bg-[var(--color-surface-2)] text-[var(--color-ink-soft)]">
<Hash className="size-3.5" />
</span>
<span className="w-32 shrink-0 truncate text-xs text-[var(--color-ink)]">
{c.channel_name ?? c.channel_id}
</span>
<div className="relative h-2 flex-1 overflow-hidden rounded-full bg-[var(--color-surface-2)]">
<div
className="absolute inset-y-0 left-0 rounded-full bg-[var(--color-signal)] transition-[width] duration-500"
style={{ width: `${(c.message_count / max) * 100}%` }}
/>
</div>
<span className="mono w-12 shrink-0 text-right text-xs text-[var(--color-ink-soft)]">
{c.message_count.toLocaleString()}
</span>
</div>
))}
</div>
<div className="h-48">
{mounted ? (
<ResponsiveContainer
width="100%"
height={192}
minWidth={0}
minHeight={0}
>
<BarChart data={data} layout="vertical">
<XAxis
type="number"
axisLine={false}
tickLine={false}
tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }}
/>
<YAxis
type="category"
dataKey="name"
axisLine={false}
tickLine={false}
tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }}
width={80}
/>
<Tooltip
contentStyle={{
background: "oklch(0.11 0.02 245 / 0.9)",
border: "1px solid oklch(1 0 0 / 0.08)",
borderRadius: 8,
fontSize: 12,
color: "oklch(0.93 0.01 245)",
}}
/>
<Bar
dataKey="count"
fill="var(--color-primary)"
radius={[0, 4, 4, 0]}
/>
</BarChart>
</ResponsiveContainer>
) : (
<div className="h-full w-full animate-pulse rounded-md bg-card/40" />
)}
</div>
</Card>
</div>
);
}
@@ -1,50 +1,24 @@
"use client";
import { Search, Users, UserX } from "lucide-react";
import { Search, Users } from "lucide-react";
import { useCallback, useState } from "react";
import { Avatar } from "@/components/primitives/avatar";
import { Badge } from "@/components/primitives/badge";
import { Input } from "@/components/primitives/input";
import { EmptyState, LoadingSkeleton } from "@/components/shared";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useUserDetail, useUsers } from "@/hooks";
import { renderMessageContent } from "@/lib/format";
import type { DashboardUser } from "@/lib/types";
import { cn } from "@/lib/utils";
const TRUST_TIERS = [
{
min: 75,
label: "Trusted",
className: "border-green-500/40 text-green-500",
},
{ min: 40, label: "Netral", className: "border-sky-500/40 text-sky-500" },
{
min: 10,
label: "At Risk",
className: "border-orange-500/40 text-orange-500",
},
{ min: 0, label: "Kritis", className: "border-red-500/40 text-red-500" },
] as const;
{ min: 75, label: "Trusted", tone: "signal" as const },
{ min: 40, label: "Neutral", tone: "neutral" as const },
{ min: 10, label: "At Risk", tone: "amber" as const },
{ min: 0, label: "Critical", tone: "vermilion" as const },
];
export function trustTier(score: number) {
function trustTier(score?: number | null) {
const s = score ?? 0;
return (
TRUST_TIERS.find((t) => score >= t.min) ??
TRUST_TIERS[TRUST_TIERS.length - 1]
);
}
function TrustBadge({ score }: { score: number }) {
const tier = trustTier(score);
return (
<Badge
variant="outline"
className={tier.className}
title={`Trust score ${score}`}
>
{tier.label}: {score}
</Badge>
TRUST_TIERS.find((t) => s >= t.min) ?? TRUST_TIERS[TRUST_TIERS.length - 1]
);
}
@@ -52,201 +26,126 @@ export function UsersSection() {
const [search, setSearch] = useState("");
const [selectedId, setSelectedId] = useState<string | null>(null);
const {
data: users = [],
isLoading,
error,
mutate: refetch,
} = useUsers(search);
const { data: users = [], isLoading } = useUsers(search);
const { data: detail } = useUserDetail(selectedId);
const handleSearch = useCallback((v: string) => {
setSearch(v);
setSelectedId(null);
}, []);
const handleSearch = useCallback((v: string) => setSearch(v), []);
if (error) {
if (isLoading) return <LoadingSkeleton count={6} />;
if (users.length === 0)
return (
<Card
className={cn(
"p-6 text-sm",
"border border-red-500/30 ring-red-500/20",
"[--card-spacing:0px]",
"rounded-2xl",
)}
>
Failed to load users: {error.message}
<Button
variant="outline"
size="sm"
className="ml-2"
onClick={() => refetch()}
>
Retry
</Button>
</Card>
<EmptyState
icon={Users}
title="No users found"
description="Try a different search."
/>
);
}
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="space-y-3">
<div className="grid gap-3 lg:grid-cols-[1fr_360px]">
<div className="surface flex flex-col gap-2 p-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-[var(--color-ink-soft)]" />
<Input
placeholder="Search by user ID or username…"
mono
placeholder="search users…"
value={search}
onChange={(e) => handleSearch(e.target.value)}
className="pl-9 h-9"
className="pl-9"
/>
</div>
{isLoading ? (
<LoadingSkeleton count={5} height="h-16" />
) : users.length === 0 ? (
<EmptyState icon={Users} title="No users found" />
) : (
<div className="space-y-2">
{users.map((user) => (
<UserRow
key={user.user_id}
user={user}
active={selectedId === user.user_id}
onSelect={setSelectedId}
/>
))}
</div>
)}
<div className="flex flex-col">
{users.map((u) => {
const tier = trustTier(u.trust_score);
return (
<button
key={u.user_id}
type="button"
onClick={() => setSelectedId(u.user_id)}
className="flex items-center gap-3 rounded-[var(--radius-r-control)] px-2 py-2 text-left transition-colors hover:bg-[var(--color-surface-2)]"
>
<Avatar src={u.avatar_url} name={u.username} size={34} />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium">
{u.username ?? "unknown"}
</div>
<div className="mono text-xs text-[var(--color-ink-soft)]">
{u.total_messages.toLocaleString()} msg
</div>
</div>
<Badge tone={tier.tone}>{tier.label}</Badge>
</button>
);
})}
</div>
</div>
<Card
className={cn("h-fit", "[--card-spacing:0px]", "rounded-2xl", "p-5")}
>
<div className="surface p-4">
{detail ? (
<div className="space-y-3">
<div className="flex flex-col gap-3">
<div className="flex items-center gap-3">
<Avatar className="size-10">
<AvatarImage src={detail.avatar_url ?? undefined} />
<AvatarFallback>
{detail.username?.charAt(0).toUpperCase() ?? "?"}
</AvatarFallback>
</Avatar>
<div className="min-w-0">
<p className="text-sm font-semibold text-text-primary">
{detail.username ?? "Unknown user"}
</p>
<p className="text-[10px] font-mono text-text-secondary/50">
{detail.user_id}
</p>
<Avatar
src={detail.avatar_url}
name={detail.username}
size={44}
/>
<div>
<div className="font-semibold">{detail.username}</div>
<div className="text-xs text-[var(--color-ink-soft)]">
{detail.total_messages.toLocaleString()} messages
</div>
</div>
</div>
<div className="flex flex-wrap gap-1.5">
<Badge variant="outline">Messages: {detail.total_messages}</Badge>
<Badge variant="destructive">
Flagged: {detail.flagged_count}
</Badge>
<Badge
variant="outline"
className="border-green-500/40 text-green-500"
>
Clean: {detail.clean_count}
</Badge>
{detail.trust_score != null && (
<TrustBadge score={detail.trust_score} />
)}
{detail.clean_message_streak != null && (
<Badge variant="outline">
Streak: {detail.clean_message_streak}
</Badge>
)}
{detail.total_infractions != null && (
<Badge variant="destructive">
Infractions: {detail.total_infractions}
</Badge>
)}
<div className="grid grid-cols-2 gap-2 text-sm">
<Stat label="Trust" value={`${detail.trust_score ?? 0}`} />
<Stat
label="Clean streak"
value={`${detail.clean_message_streak ?? 0}`}
/>
<Stat
label="Infractions"
value={`${detail.total_infractions ?? 0}`}
tone="vermilion"
/>
<Stat
label="Flagged"
value={`${detail.flagged_count}`}
tone="amber"
/>
</div>
{detail.profile_summary && (
<p className="text-xs leading-relaxed text-text-secondary">
{detail.profile_summary}
</p>
)}
{detail.recent_messages.length > 0 && (
<div className="space-y-1.5">
<p className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50">
Recent messages
</p>
{detail.recent_messages.slice(0, 5).map((msg) => (
<div
key={msg.id}
className="rounded-lg border border-border/40 bg-card/40 px-3 py-2"
>
<p className="text-xs leading-relaxed text-text-secondary line-clamp-2">
{renderMessageContent(msg.content, msg.metadata) ||
"(no text content)"}
</p>
<p className="mt-1 text-[10px] font-mono text-text-secondary/40">
{msg.channel_id?.slice(0, 8)} ·{" "}
{new Date(msg.created_at).toLocaleString()}
</p>
</div>
))}
</div>
)}
</div>
) : (
<div className="flex h-48 flex-col items-center justify-center text-center">
<UserX className="size-8 text-text-secondary/30 mb-2" />
<p className="text-xs text-text-secondary/60">
Select a user to see their profile, trust score and recent
messages.
<p className="text-xs text-[var(--color-ink-soft)]">
{detail.profile_summary}
</p>
</div>
) : (
<p className="text-sm text-[var(--color-ink-soft)]">
Select a user to inspect.
</p>
)}
</Card>
</div>
</div>
);
}
function UserRow({
user,
active,
onSelect,
function Stat({
label,
value,
tone,
}: {
user: DashboardUser;
active: boolean;
onSelect: (id: string) => void;
label: string;
value: string;
tone?: "amber" | "vermilion";
}) {
return (
<Card
className={active ? "border-primary/40 bg-primary/5" : undefined}
onClick={() => onSelect(user.user_id)}
>
<CardContent className="flex cursor-pointer items-center gap-3 p-3">
<Avatar className="size-8 shrink-0">
<AvatarImage src={user.avatar_url ?? undefined} />
<AvatarFallback className="text-xs">
{user.username?.charAt(0).toUpperCase() ?? "?"}
</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-text-primary">
{user.username ?? "Unknown user"}
</p>
<p className="truncate text-[10px] font-mono text-text-secondary/50">
{user.user_id}
</p>
</div>
<div className="flex shrink-0 gap-1.5">
<Badge variant="outline">{user.total_messages}</Badge>
{user.flagged_count > 0 && (
<Badge variant="destructive">{user.flagged_count}</Badge>
)}
{user.trust_score != null && <TrustBadge score={user.trust_score} />}
</div>
</CardContent>
</Card>
<div className="surface-2 p-2.5">
<div className="text-[11px] uppercase tracking-wide text-[var(--color-ink-soft)]">
{label}
</div>
<div
className={`mono text-lg font-semibold ${tone === "amber" ? "text-[var(--color-amber)]" : tone === "vermilion" ? "text-[var(--color-vermilion)]" : "text-[var(--color-ink)]"}`}
>
{value}
</div>
</div>
);
}
@@ -1,84 +0,0 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ThemeToggle } from "@/components/layout/theme-toggle";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
} from "@/components/ui/sidebar";
import { isActivePath, navItems } from "@/lib/navigation";
/**
* Primary application navigation — pure shadcn Sidebar primitives.
* Renders as a fixed desktop rail (collapsible to icons) and a Sheet
* on mobile via the Sidebar component itself.
*/
export function AppSidebar() {
const pathname = usePathname();
return (
<Sidebar collapsible="icon">
<SidebarHeader>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton size="lg" render={<Link href="/dashboard" />}>
<div className="flex size-6 shrink-0 items-center justify-center rounded-md bg-gradient-to-br from-cyan-500 to-teal-400 text-white text-[10px] font-bold">
D
</div>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-semibold">Discord Automod</span>
<span className="truncate text-xs text-muted-foreground">
Moderation dashboard
</span>
</div>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<SidebarGroup>
<SidebarGroupLabel>Navigation</SidebarGroupLabel>
<SidebarMenu>
{navItems.map(({ href, label, icon: Icon, matchPrefix }) => {
const active = isActivePath(pathname, matchPrefix);
return (
<SidebarMenuItem key={href}>
<SidebarMenuButton
render={<Link href={href} />}
isActive={active}
tooltip={label}
className="group-data-[collapsible=icon]:size-8 group-data-[collapsible=icon]:justify-center"
>
<Icon />
<span>{label}</span>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroup>
</SidebarContent>
<SidebarFooter>
<SidebarMenu>
<SidebarMenuItem>
<ThemeToggle />
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
<SidebarRail />
</Sidebar>
);
}
@@ -0,0 +1,99 @@
"use client";
import { motion } from "motion/react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { navItems } from "@/lib/navigation";
import { cn } from "@/lib/utils";
const titleFromPath: Record<string, string> = {
"/dashboard": "Overview",
"/messages": "Messages",
"/voice": "Voice",
"/media": "Media",
"/recordings": "Recordings",
"/moderation": "Moderation",
"/analysis": "Analysis",
};
export function Spine() {
const pathname = usePathname();
return (
<>
{/* Desktop rail */}
<nav className="fixed left-0 top-0 z-30 hidden h-svh w-[68px] flex-col items-center gap-1 border-r border-[var(--color-hairline)] bg-[var(--color-canvas)]/80 py-4 backdrop-blur-md md:flex">
<Link
href="/dashboard"
className="mb-3 flex size-9 items-center justify-center rounded-[var(--radius-r-control)] bg-[var(--color-signal)] text-sm font-black text-[var(--color-signal-ink)]"
aria-label="Bete"
>
B
</Link>
{navItems.map((item) => {
const active = pathname.startsWith(item.matchPrefix);
const Icon = item.icon;
return (
<Link
key={item.href}
href={item.href}
className={cn(
"group relative flex size-11 items-center justify-center rounded-[var(--radius-r)] transition-colors",
active
? "text-[var(--color-signal)]"
: "text-[var(--color-ink-soft)] hover:text-[var(--color-ink)]",
)}
aria-current={active ? "page" : undefined}
>
{active && (
<motion.span
layoutId="spine-active"
className="absolute left-0 top-1/2 size-1 -translate-y-1/2 rounded-full bg-[var(--color-signal)]"
transition={{ type: "spring", stiffness: 380, damping: 30 }}
/>
)}
<Icon className="size-5" />
<span className="pointer-events-none absolute left-full ml-2 hidden whitespace-nowrap rounded-[var(--radius-r-control)] bg-[var(--color-ink)] px-2 py-1 text-xs font-medium text-[var(--color-canvas)] opacity-0 transition-opacity group-hover:opacity-100 md:block">
{item.label}
</span>
</Link>
);
})}
</nav>
{/* Mobile bottom tab-bar */}
<nav className="fixed inset-x-0 bottom-0 z-30 flex h-16 items-stretch border-t border-[var(--color-hairline)] bg-[var(--color-canvas)]/90 backdrop-blur-md md:hidden">
{navItems.map((item) => {
const active = pathname.startsWith(item.matchPrefix);
const Icon = item.icon;
return (
<Link
key={item.href}
href={item.href}
className={cn(
"flex flex-1 flex-col items-center justify-center gap-0.5 text-[10px] font-medium transition-colors",
active
? "text-[var(--color-signal)]"
: "text-[var(--color-ink-soft)]",
)}
aria-current={active ? "page" : undefined}
>
<Icon className="size-5" />
{item.label}
</Link>
);
})}
</nav>
</>
);
}
export function PageTitle() {
const pathname = usePathname();
const key =
Object.keys(titleFromPath).find((k) => pathname.startsWith(k)) ??
"/dashboard";
return (
<span className="font-semibold max-md:hidden">{titleFromPath[key]}</span>
);
}
@@ -0,0 +1,66 @@
"use client";
import { useEffect, useState } from "react";
import { useChatbot } from "@/components/chatbot/chatbot-context";
import { GuildSelector } from "@/components/shared/guild-selector";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
import { PageTitle } from "./spine";
import { ThemeToggle } from "./theme-toggle";
const statusTone: Record<string, string> = {
connected: "bg-[var(--color-signal)]",
connecting: "bg-[var(--color-amber)]",
disconnected: "bg-[var(--color-ink-soft)]",
error: "bg-[var(--color-vermilion)]",
};
export function StatusBar({
guildId,
onGuildChange,
}: {
guildId: string;
onGuildChange: (g: string) => void;
}) {
const ws = useWebSocket();
const { expression } = useChatbot();
const [clock, setClock] = useState("--:--:--");
useEffect(() => {
const tick = () =>
setClock(new Date().toLocaleTimeString("en-GB", { hour12: false }));
tick();
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);
return (
<header className="sticky top-0 z-20 flex h-14 shrink-0 items-center gap-2 border-b border-[var(--color-hairline)] bg-[var(--color-canvas)]/85 px-4 backdrop-blur-md md:px-6">
<PageTitle />
<div className="ms-auto flex items-center gap-3">
<span className="hidden items-center gap-1.5 text-xs text-[var(--color-ink-soft)] sm:flex">
<span className={cn("size-2 rounded-full", statusTone[ws.status])} />
<span className="mono uppercase">{ws.status}</span>
</span>
<span className="hidden text-xs text-[var(--color-ink-soft)] md:inline">
<span
className={cn(
"font-mono",
expression !== "idle" && "text-[var(--color-signal)]",
)}
>
{expression}
</span>
</span>
<span className="hidden font-mono text-xs text-[var(--color-ink-soft)] lg:inline">
{clock}
</span>
<GuildSelector
value={guildId}
onChange={(g) => onGuildChange(g ?? "")}
/>
<ThemeToggle />
</div>
</header>
);
}
@@ -1,49 +0,0 @@
"use client";
import { cn } from "@/lib/utils";
interface SubNavTab {
id: string;
label: string;
icon?: React.ReactNode;
}
interface SubNavProps {
tabs: SubNavTab[];
activeTab: string;
onTabChange: (tab: string) => void;
className?: string;
}
export function SubNav({
tabs,
activeTab,
onTabChange,
className,
}: SubNavProps) {
return (
<div
className={cn(
"flex items-center gap-1 px-1 py-1 glass rounded-[var(--radius-panel)] w-fit",
className,
)}
>
{tabs.map((tab) => (
<button
key={tab.id}
type="button"
onClick={() => onTabChange(tab.id)}
className={cn(
"flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all duration-150",
activeTab === tab.id
? "bg-primary/20 text-text-primary shadow-[0_0_12px] shadow-primary/20"
: "text-text-secondary/60 hover:text-text-primary/80",
)}
>
{tab.icon}
{tab.label}
</button>
))}
</div>
);
}
@@ -1,40 +1,38 @@
"use client";
import { Moon, Sun } from "lucide-react";
import { motion } from "motion/react";
import { useTheme } from "next-themes";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
export function ThemeToggle() {
const { setTheme } = useTheme();
const { resolvedTheme, setTheme } = useTheme();
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
const isDark = resolvedTheme === "dark";
return (
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button variant="ghost" size="sm" className="w-full justify-start" />
}
>
<Sun className="scale-100 dark:scale-0" />
<Moon className="absolute scale-0 dark:scale-100" />
<span className="truncate pl-1.5">Toggle theme</span>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-32">
<DropdownMenuItem onClick={() => setTheme("light")}>
<Sun className="mr-2 size-4" />
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
<Moon className="mr-2 size-4" />
Dark
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<button
type="button"
aria-label="Toggle theme"
onClick={() => setTheme(isDark ? "light" : "dark")}
className="flex size-9 items-center justify-center rounded-[var(--radius-r-control)] text-[var(--color-ink-soft)] transition-colors hover:bg-[var(--color-surface-2)] hover:text-[var(--color-ink)] focus-visible:ring-2 focus-visible:ring-[var(--color-ring)]"
>
{mounted && (
<motion.span
key={isDark ? "moon" : "sun"}
initial={{ rotate: -90, opacity: 0 }}
animate={{ rotate: 0, opacity: 1 }}
transition={{ type: "spring", stiffness: 360, damping: 26 }}
className={cn(
isDark ? "text-[var(--color-signal)]" : "text-[var(--color-amber)]",
)}
>
{isDark ? <Moon className="size-4" /> : <Sun className="size-4" />}
</motion.span>
)}
</button>
);
}
@@ -1,80 +1,59 @@
"use client";
import { Disc3, Music, Repeat, SkipForward, Square } from "lucide-react";
import { Pause, Play, SkipForward, Volume2 } from "lucide-react";
import { motion } from "motion/react";
import { Button } from "@/components/primitives/button";
import { useMediaSkip, useMediaState, useMediaWsSync } from "@/hooks";
import { useMediaPlayer } from "@/lib/hooks/use-media-player";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
export function MiniPlayer() {
const { playing, current, queue, loop, pending, skip, stop, toggleLoop } =
useMediaPlayer();
const ws = useWebSocket();
const { data: state } = useMediaState();
const { playing, current } = useMediaPlayer();
useMediaWsSync(ws);
const skip = useMediaSkip();
// Nothing to show if no track is playing and nothing is queued
if (!current && queue.length === 0) return null;
if (!current) return null;
return (
<div className="fixed bottom-0 left-0 right-0 z-40 h-14 glass-intense border-t border-glass-border flex items-center gap-3 px-4 md:px-6">
{/* Track info */}
<div className="flex items-center gap-2.5 min-w-0 flex-1 max-w-[280px]">
<div className="size-8 rounded-md bg-gradient-to-br from-primary/20 to-primary/5 border border-primary/10 flex items-center justify-center shrink-0">
{playing ? (
<Disc3
className="size-4 text-primary animate-spin"
style={{ animationDuration: "4s" }}
/>
) : (
<Music className="size-4 text-text-secondary" />
)}
</div>
<div className="min-w-0">
<p className="text-xs font-medium text-text-primary truncate">
{current?.title ?? "Unknown track"}
</p>
{queue.length > 0 && (
<p className="text-[10px] text-text-secondary/60">
{queue.length > 1 ? `${queue.length} in queue` : "1 in queue"}
</p>
)}
<motion.div
initial={{ y: 100, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
exit={{ y: 100, opacity: 0 }}
transition={{ type: "spring", stiffness: 320, damping: 30 }}
className={cn(
"pointer-events-auto fixed inset-x-0 bottom-20 z-30 mx-auto w-[calc(100%-2rem)] max-w-[480px]",
"surface flex items-center gap-3 px-3 py-2 text-sm",
)}
>
<img
src={current.thumbnailUrl ?? "/favicon.ico"}
alt={current.title}
className="size-9 rounded-[var(--radius-r-control)] object-cover"
/>
<div className="min-w-0 flex-1">
<div className="truncate font-medium">{current.title}</div>
<div className="text-xs text-[var(--color-ink-soft)] mono">
{current.source}
</div>
</div>
{/* Controls */}
<div className="flex items-center gap-1 shrink-0">
{playing && (
<button
type="button"
onClick={stop}
disabled={pending}
className="size-8 flex items-center justify-center rounded-md text-text-secondary hover:text-destructive hover:bg-glass-bg transition-colors disabled:opacity-40"
aria-label="Stop"
>
<Square className="size-3.5" />
</button>
)}
{current && (
<button
type="button"
onClick={skip}
disabled={pending || queue.length === 0}
className="size-8 flex items-center justify-center rounded-md text-text-secondary hover:text-text-primary hover:bg-glass-bg transition-colors disabled:opacity-40"
aria-label="Skip"
>
<SkipForward className="size-3.5" />
</button>
)}
<button
type="button"
onClick={() => toggleLoop()}
disabled={pending}
className={`size-8 flex items-center justify-center rounded-md transition-colors disabled:opacity-40 ${
loop
? "text-primary bg-glass-bg"
: "text-text-secondary hover:text-text-primary hover:bg-glass-bg"
}`}
aria-label={loop ? "Loop on" : "Loop off"}
aria-pressed={loop}
<div className="flex items-center gap-1">
<Button size="sm" variant="ghost" onClick={() => skip.mutate()}>
<SkipForward className="size-3.5" />
</Button>
<Button
size="sm"
variant={playing ? "primary" : "ghost"}
onClick={() =>
state?.playing ? void skip.mutate() : void skip.mutate()
}
>
<Repeat className="size-3.5" />
</button>
{playing ? <Pause className="size-4" /> : <Play className="size-4" />}
</Button>
<Volume2 className="size-4 text-[var(--color-ink-soft)]" />
</div>
</div>
</motion.div>
);
}
@@ -1,178 +0,0 @@
"use client";
import { Disc3, Music, Play, Repeat, SkipForward, Square } from "lucide-react";
import Image from "next/image";
import { useCallback, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
useMediaLoop,
useMediaQueue,
useMediaSkip,
useMediaState,
useMediaStop,
useMediaWsSync,
} from "@/hooks";
import type { MediaState } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
interface MusicPlayerProps {
ws: WsHook;
/** Server-fetched media snapshot used to seed the first render. */
initialData?: MediaState;
}
export function MusicPlayer({ ws, initialData }: MusicPlayerProps) {
const { data: mediaState } = useMediaState(initialData);
const queueMut = useMediaQueue();
const skipMut = useMediaSkip();
const stopMut = useMediaStop();
const loopMut = useMediaLoop();
const [queueUrl, setQueueUrl] = useState("");
const [screenMode, setScreenMode] = useState(false);
// Sync WS media_state into the query cache
useMediaWsSync(ws);
const handleQueue = useCallback(() => {
if (!queueUrl.trim()) return;
queueMut.mutate({
url: queueUrl.trim(),
mode: screenMode ? "screen" : "music",
});
setQueueUrl("");
}, [queueUrl, queueMut, screenMode]);
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm font-semibold">
<Music className="size-4 text-primary" />
Music Player
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-2">
<Input
placeholder="Queue a URL (YouTube, audio file…)"
value={queueUrl}
onChange={(e) => setQueueUrl(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleQueue()}
className="flex-1 h-9"
/>
<Button
variant={screenMode ? "default" : "secondary"}
size="sm"
onClick={() => setScreenMode((v) => !v)}
title="Queue as Discord GoLive screenshare instead of audio playback"
className="h-9"
>
Screen
</Button>
<Button
onClick={handleQueue}
disabled={!queueUrl.trim() || queueMut.isPending}
>
<Play className="size-4 mr-1.5" />
Queue
</Button>
</div>
{mediaState?.activeMode && (
<p className="text-[10px] font-mono text-primary/80 uppercase tracking-wider">
{mediaState.activeMode === "screen"
? "Screen share active"
: "Music playing"}
</p>
)}
{mediaState?.current ? (
<div className="rounded-lg bg-gradient-to-br from-primary/5 to-primary/[0.02] border border-primary/10 p-4 space-y-2">
<p className="text-xs text-muted-foreground font-medium uppercase tracking-wider flex items-center gap-1.5">
<Disc3 className="size-3" />
Now Playing
</p>
<div className="flex items-start gap-3">
{mediaState.current.thumbnailUrl && (
<Image
src={mediaState.current.thumbnailUrl}
alt=""
width={56}
height={56}
className="size-14 rounded-lg object-cover shadow-sm"
/>
)}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{mediaState.current.title ?? mediaState.current.source}
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{mediaState.current.durationMs
? `${Math.floor(mediaState.current.durationMs / 60000)}:${String(Math.floor((mediaState.current.durationMs % 60000) / 1000)).padStart(2, "0")}`
: "Live"}
</p>
</div>
</div>
</div>
) : (
!mediaState?.queue?.length && (
<p className="text-sm text-muted-foreground py-8 text-center">
No media queued. Paste a URL above to start playing.
</p>
)
)}
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => stopMut.mutate()}>
<Square className="size-4 mr-1" />
Stop
</Button>
<Button variant="outline" size="sm" onClick={() => skipMut.mutate()}>
<SkipForward className="size-4 mr-1" />
Skip
</Button>
<Button
variant={mediaState?.loop ? "default" : "outline"}
size="sm"
onClick={() => loopMut.mutate(!mediaState?.loop)}
disabled={loopMut.isPending}
title={
mediaState?.loop
? "Loop enabled — replay current track"
: "Enable loop"
}
aria-pressed={mediaState?.loop}
>
<Repeat className="size-4 mr-1" />
Loop
</Button>
</div>
{mediaState && mediaState.queue.length > 0 && (
<div className="space-y-1.5">
<p className="text-xs text-muted-foreground font-medium">
Queue ({mediaState.queue.length})
</p>
<div className="space-y-1">
{mediaState.queue.map((item, i) => (
<div
key={item.id ?? i}
className="flex items-center gap-2 rounded-md bg-muted/30 px-3 py-2 text-sm"
>
<span className="text-xs text-muted-foreground font-mono w-5 text-right">
{i + 1}.
</span>
<span className="truncate flex-1">
{item.title ?? item.source}
</span>
</div>
))}
</div>
</div>
)}
</CardContent>
</Card>
);
}
@@ -1,7 +1,8 @@
"use client";
import { useState } from "react";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/primitives/badge";
import { Progress } from "@/components/primitives/progress";
import { cn } from "@/lib/utils";
interface AiAnalysisPanelProps {
@@ -16,11 +17,11 @@ interface AiAnalysisPanelProps {
}
const severityColor: Record<string, string> = {
none: "text-emerald-500",
low: "text-text-secondary",
medium: "text-accent-amber",
high: "text-accent-purple",
critical: "text-destructive",
none: "text-[var(--color-ink-soft)]",
low: "text-[var(--color-ink-soft)]",
medium: "text-[var(--color-amber)]",
high: "text-orange-500",
critical: "text-[var(--color-vermilion)]",
};
export function AiAnalysisPanel({
@@ -37,11 +38,11 @@ export function AiAnalysisPanel({
if (!status || status === "pending") {
return (
<Card className={cn("[--card-spacing:0px]", "p-3")}>
<span className="text-xs text-text-secondary/50">
<div className="surface-2 p-3">
<span className="text-xs text-[var(--color-ink-soft)]/60">
AI analysis pending
</span>
</Card>
</div>
);
}
@@ -54,28 +55,27 @@ export function AiAnalysisPanel({
: []
: categories || [];
const statusTone =
status === "clean"
? "signal"
: status === "flagged"
? "vermilion"
: status === "warn"
? "amber"
: "neutral";
return (
<Card className={cn("space-y-2", "[--card-spacing:0px]", "p-3")}>
<div className="surface-2 flex flex-col gap-2.5 p-3">
<div className="flex items-center gap-2">
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">
<span className="text-xs font-semibold uppercase tracking-wide text-[var(--color-ink-soft)]">
AI Analysis
</span>
<span
className={cn(
"text-[10px] font-mono px-1.5 py-0.5 rounded",
status === "clean" && "bg-emerald-500/10 text-emerald-500",
status === "flagged" && "bg-accent-purple/10 text-accent-purple",
status === "warn" && "bg-accent-amber/10 text-accent-amber",
status === "error" && "bg-destructive/10 text-destructive",
)}
>
{status}
</span>
<Badge tone={statusTone}>{status}</Badge>
</div>
{severity && (
<div className="flex items-center gap-2 text-xs">
<span className="text-text-secondary/60">Severity:</span>
<span className="text-[var(--color-ink-soft)]/60">Severity:</span>
<span
className={cn(
"font-mono font-medium",
@@ -89,14 +89,19 @@ export function AiAnalysisPanel({
{confidence !== null && confidence !== undefined && (
<div className="flex items-center gap-2 text-xs">
<span className="text-text-secondary/60">Confidence:</span>
<span className="font-mono">{(confidence * 100).toFixed(0)}%</span>
<span className="text-[var(--color-ink-soft)]/60">Confidence</span>
<Progress
value={confidence * 100}
max={100}
tone="signal"
showLabel
/>
</div>
)}
{score !== null && score !== undefined && (
<div className="flex items-center gap-2 text-xs">
<span className="text-text-secondary/60">Score:</span>
<div className="flex items-center justify-between text-xs">
<span className="text-[var(--color-ink-soft)]/60">Score</span>
<span className="font-mono">{score.toFixed(2)}</span>
</div>
)}
@@ -104,12 +109,9 @@ export function AiAnalysisPanel({
{flagsArray.length > 0 && (
<div className="flex flex-wrap gap-1">
{flagsArray.map((f: string) => (
<span
key={f}
className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-destructive/10 text-destructive"
>
<Badge key={f} tone="vermilion">
{f}
</span>
</Badge>
))}
</div>
)}
@@ -117,21 +119,18 @@ export function AiAnalysisPanel({
{categoriesArray.length > 0 && (
<div className="flex flex-wrap gap-1">
{categoriesArray.map((c: string) => (
<span
key={c}
className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-primary/10 text-primary"
>
<Badge key={c} tone="neutral">
{c}
</span>
</Badge>
))}
</div>
)}
{analysis && (
<div className="border-l-2 border-glass-border pl-2">
<div className="border-l-2 border-[var(--color-hairline)] pl-2">
<p
className={cn(
"text-xs leading-relaxed text-text-secondary/90",
"text-xs leading-relaxed text-[var(--color-ink-soft)]",
!expanded && "line-clamp-3",
)}
>
@@ -141,7 +140,7 @@ export function AiAnalysisPanel({
<button
type="button"
onClick={() => setExpanded((v) => !v)}
className="mt-1 text-[10px] font-medium uppercase tracking-wide text-text-secondary/50 transition-colors hover:text-text-primary"
className="mt-1 text-[10px] font-medium uppercase tracking-wide text-[var(--color-ink-soft)]/50 transition-colors hover:text-[var(--color-ink)]"
>
{expanded ? "Show less" : "Show more"}
</button>
@@ -151,10 +150,10 @@ export function AiAnalysisPanel({
{action && action !== "none" && (
<div className="text-xs">
<span className="text-text-secondary/60">Recommended: </span>
<span className="font-mono text-accent-amber">{action}</span>
<span className="text-[var(--color-ink-soft)]/60">Recommended: </span>
<span className="font-mono text-[var(--color-amber)]">{action}</span>
</div>
)}
</Card>
</div>
);
}
@@ -1,28 +1,44 @@
"use client";
import type { AiSeverity, AiStatus } from "@/lib/types";
import { cn } from "@/lib/utils";
const STATUS_STYLES: Record<string, string> = {
clean:
"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20",
flagged: "bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20",
warn: "bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",
pending: "bg-muted text-muted-foreground border-border",
processing:
"bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20 animate-pulse",
error: "bg-destructive/10 text-destructive border-destructive/20",
const severityTick: Record<NonNullable<AiSeverity>, string> = {
none: "border-[var(--color-signal)]/30",
low: "border-[var(--color-amber)]/50",
medium: "border-[var(--color-amber)]",
high: "border-orange-500/80",
critical: "border-[var(--color-vermilion)]",
};
export function AiStatusBadge({ status }: { status?: string | null }) {
if (!status) return null;
const statusBadge: Record<NonNullable<AiStatus>, string> = {
pending: "bg-[var(--color-ink-soft)]/20 text-[var(--color-ink-soft)]",
processing: "bg-[var(--color-amber)]/15 text-[var(--color-amber)]",
clean: "bg-[var(--color-signal)]/15 text-[var(--color-signal)]",
warn: "bg-[var(--color-amber)]/15 text-[var(--color-amber)]",
flagged: "bg-[var(--color-vermilion)]/15 text-[var(--color-vermilion)]",
error: "bg-[var(--color-vermilion)]/15 text-[var(--color-vermilion)]",
};
export function SeverityTick({ severity }: { severity?: AiSeverity | null }) {
const cls = severity ? severityTick[severity] : "border-transparent";
return (
<span
className={cn(
"inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider",
STATUS_STYLES[status] ?? "bg-muted text-muted-foreground border-border",
)}
>
{status}
className={cn("absolute left-0 top-0 h-full w-0.5 border-l-2", cls)}
aria-hidden="true"
/>
);
}
export function AiStatusBadge({ status }: { status?: AiStatus | null }) {
if (!status) return null;
return (
<span className={cn("pill", statusBadge[status])}>
<span
className="size-1.5 rounded-full"
style={{ background: "currentColor" }}
/>
<span className="ml-1 text-[10px] font-medium uppercase">{status}</span>
</span>
);
}
@@ -1,69 +1,35 @@
"use client";
import { ImageIcon } from "lucide-react";
import type { AttachmentRecord } from "@/lib/types";
interface AttachmentsGridProps {
attachments: AttachmentRecord[];
onImageClick?: (index: number) => void;
}
import type { AttachmentRef } from "@/lib/types";
import { cn } from "@/lib/utils";
export function AttachmentsGrid({
attachments,
onImageClick,
}: AttachmentsGridProps) {
onOpen,
}: {
attachments: AttachmentRef[];
onOpen: (url: string) => void;
}) {
if (attachments.length === 0) return null;
const images = attachments.filter((a) => a.type?.startsWith("image/"));
const others = attachments.filter((a) => !a.type?.startsWith("image/"));
const images = attachments.filter((a) => /image/i.test(a.contentType ?? ""));
if (images.length === 0) return null;
return (
<div className="space-y-2">
{images.length > 0 && (
<div className="grid grid-cols-2 gap-2">
{images.map((att, i) => (
<div
key={att.id}
className="glass relative overflow-hidden rounded-lg group"
>
<button
type="button"
onClick={() => onImageClick?.(i)}
className="block w-full cursor-zoom-in"
aria-label={`Open ${att.filename}`}
>
<img
src={att.uploaded_url || att.discord_url}
alt={att.filename}
className="h-32 w-full object-cover transition-transform duration-300 group-hover:scale-105"
loading="lazy"
decoding="async"
/>
</button>
{images.length > 1 && (
<span className="absolute bottom-1 right-1 rounded bg-black/50 px-1.5 py-0.5 font-mono text-[10px] text-white/80">
{i + 1}/{images.length}
</span>
)}
</div>
))}
</div>
)}
{others.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{others.map((att) => (
<div
key={att.id}
className="flex items-center gap-1.5 rounded-md bg-glass-bg px-2 py-1 text-xs text-text-secondary"
>
<ImageIcon className="size-3 text-text-secondary/50" />
<span className="font-mono max-w-40 truncate">
{att.filename}
</span>
</div>
))}
</div>
)}
<div className="mt-2 grid grid-cols-2 gap-2 sm:grid-cols-3">
{images.map((a, i) => (
<button
key={`${a.url}-${i}`}
type="button"
onClick={() => onOpen(a.url)}
className="group relative aspect-video overflow-hidden rounded-[var(--radius-r-control)] border border-[var(--color-hairline)]"
>
<img
src={a.url}
alt={a.name}
loading="lazy"
className="size-full object-cover transition-transform duration-200 group-hover:scale-105"
/>
</button>
))}
</div>
);
}
@@ -1,128 +1,74 @@
"use client";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { X } from "lucide-react";
import { useEffect, useState } from "react";
import { Dialog } from "@/components/primitives/dialog";
import { cn } from "@/lib/utils";
interface LightboxProps {
images: Array<{ src: string; alt?: string }>;
initialIndex?: number;
open: boolean;
onClose: () => void;
}
/**
* Fullscreen image viewer with keyboard navigation (←/→/Esc) and
* touch-swipe support. Mounted at page level so a single instance
* serves the message list, image grid and attachments grid.
*/
export function Lightbox({
images,
initialIndex = 0,
open,
onClose,
}: LightboxProps) {
const [index, setIndex] = useState(initialIndex);
useEffect(() => {
if (open) setIndex(initialIndex);
}, [open, initialIndex]);
const prev = useCallback(() => {
setIndex((i) => (i - 1 + images.length) % images.length);
}, [images.length]);
const next = useCallback(() => {
setIndex((i) => (i + 1) % images.length);
}, [images.length]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
if (e.key === "ArrowLeft") prev();
if (e.key === "ArrowRight") next();
};
document.addEventListener("keydown", onKey);
// Lock body scroll while the lightbox is open
document.body.style.overflow = "hidden";
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = "";
};
}, [open, onClose, prev, next]);
if (!open || images.length === 0) return null;
const current = images[index] ?? images[0];
src,
alt,
images = [],
initialIndex = 0,
}: {
open: boolean;
onClose: () => void;
src?: string;
alt?: string;
images?: Array<{ src: string; alt?: string }>;
initialIndex?: number;
}) {
const gallery = images.length > 0 ? images : src ? [{ src, alt }] : [];
const [idx, setIdx] = useState(initialIndex);
useEffect(() => setIdx(initialIndex), [initialIndex]);
if (!gallery.length) return null;
const current = gallery[idx];
const hasNav = gallery.length > 1;
return (
<div
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/85 backdrop-blur-sm animate-fade-in"
role="dialog"
aria-modal="true"
aria-label="Image viewer"
onClick={onClose}
onKeyDown={(e) => {
if (e.key === "Escape") onClose();
}}
tabIndex={-1}
<Dialog
open={open}
onClose={onClose}
className="p-0 border-0 bg-transparent shadow-none"
>
{/* Close */}
<button
type="button"
onClick={onClose}
className="absolute right-4 top-4 z-10 rounded-full bg-white/10 p-2 text-white/80 transition-colors hover:bg-white/20 hover:text-white"
aria-label="Close viewer"
>
<X className="size-5" />
</button>
{/* Image */}
<div className="max-h-[85vh] max-w-[90vw]">
<div className="relative flex items-center justify-center p-4">
{hasNav && (
<button
type="button"
onClick={() =>
setIdx((i) => (i - 1 + gallery.length) % gallery.length)
}
className="absolute left-2 top-1/2 -translate-y-1/2 rounded-full bg-black/40 p-2 text-white hover:bg-black/60"
aria-label="Previous"
>
◀
</button>
)}
<img
key={current.src}
src={current.src}
alt={current.alt ?? ""}
className="max-h-[85vh] max-w-[90vw] rounded-lg object-contain shadow-2xl"
loading="eager"
draggable={false}
alt={current.alt ?? alt ?? "attachment"}
className="max-h-[80vh] max-w-full rounded-[var(--radius-r)] object-contain"
/>
{hasNav && (
<button
type="button"
onClick={() => setIdx((i) => (i + 1) % gallery.length)}
className="absolute right-16 top-1/2 -translate-y-1/2 rounded-full bg-black/40 p-2 text-white hover:bg-black/60"
aria-label="Next"
>
▶
</button>
)}
<button
type="button"
onClick={onClose}
className="absolute top-2 right-2 rounded-full bg-black/40 p-1.5 text-white hover:bg-black/60"
aria-label="Close"
>
<X className="size-4" />
</button>
</div>
{/* Counter */}
{images.length > 1 && (
<span className="absolute bottom-4 left-1/2 -translate-x-1/2 rounded-full bg-white/10 px-3 py-1 font-mono text-xs text-white/80">
{index + 1} / {images.length}
</span>
)}
{/* Nav */}
{images.length > 1 && (
<>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
prev();
}}
className="absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-white/10 p-2 text-white/80 transition-colors hover:bg-white/20 hover:text-white"
aria-label="Previous image"
>
<ChevronLeft className="size-6" />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
next();
}}
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-white/10 p-2 text-white/80 transition-colors hover:bg-white/20 hover:text-white"
aria-label="Next image"
>
<ChevronRight className="size-6" />
</button>
</>
)}
</div>
</Dialog>
);
}
@@ -1,175 +0,0 @@
"use client";
import { Hash } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import {
getMessageChannelLabel,
renderMessageContent,
safeParseJsonArray,
} from "@/lib/format";
import type { MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
import { AiStatusBadge } from "./ai-status-badge";
export function MessageCard({
message: msg,
onClick,
}: {
message: MessageRecord;
onClick: (id: string) => void;
}) {
const severity = (
{
low: "border-l-cyan-500/40",
medium: "border-l-amber-500/60",
high: "border-l-orange-500/70",
critical: "border-l-red-500/80",
} as Record<string, string>
)[msg.ai_severity ?? ""];
return (
<Card
className={cn(
"cursor-pointer transition-all duration-200 hover:shadow-[0_0_16px_oklch(0.62_0.17_215_/_0.08)] hover:border-cyan-500/20",
severity && "border-l-2",
severity,
)}
onClick={() => onClick(msg.id)}
>
<CardContent className="p-4">
<div className="flex items-start gap-3">
<Avatar className="size-8 shrink-0 mt-0.5">
<AvatarImage src={msg.avatar_url ?? undefined} />
<AvatarFallback className="text-xs">
{msg.username?.charAt(0).toUpperCase() ?? "?"}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-2">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-medium">{msg.username}</span>
<span className="text-xs text-muted-foreground">
{msg.created_at
? new Date(msg.created_at).toLocaleString()
: ""}
</span>
<span
className="text-xs text-muted-foreground"
title={
msg.thread_id
? `Thread ${getMessageChannelLabel(msg)} (${msg.thread_id.slice(0, 8)})`
: undefined
}
>
<Hash className="size-3 inline mr-0.5" />
{getMessageChannelLabel(msg)}
</span>
<AiStatusBadge status={msg.ai_status} />
{msg.ai_severity && msg.ai_severity !== "none" && (
<Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{msg.ai_severity}
</Badge>
)}
{msg.type === "deleted" && (
<Badge
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
deleted
</Badge>
)}
{(msg.type === "edited" || msg.edited_content) && (
<Badge
variant="outline"
className="text-[10px] px-1.5 py-0 h-4"
>
edited
</Badge>
)}
</div>
<p
className={cn(
"text-sm leading-relaxed",
msg.type === "deleted" &&
"italic text-muted-foreground line-through",
)}
>
{renderMessageContent(
msg.edited_content ?? msg.content,
msg.metadata,
)}
</p>
{(() => {
const u = extractFirstImage(msg.metadata);
if (!u) return null;
return (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onClick(msg.id);
}}
className="mt-2 block w-full max-w-[320px] overflow-hidden rounded-lg border border-border/50 group/image"
aria-label="Open image"
>
<img
src={u}
alt=""
loading="lazy"
decoding="async"
className="max-h-48 w-full object-cover transition-transform duration-300 group-hover/image:scale-[1.02]"
/>
</button>
);
})()}
{msg.ai_moderation_flags && msg.ai_moderation_flags !== "[]" && (
<div className="flex flex-wrap gap-1">
{safeParseJsonArray(msg.ai_moderation_flags).map((f) => (
<Badge
key={f}
variant="destructive"
className="text-[10px] px-1.5 py-0 h-4"
>
{f}
</Badge>
))}
</div>
)}
{msg.ai_analysis && (
<p className="text-xs text-muted-foreground italic line-clamp-2 leading-relaxed">
{msg.ai_analysis}
</p>
)}
{msg.ai_confidence != null && (
<div className="flex items-center gap-2 max-w-40">
<Progress value={msg.ai_confidence * 100} className="h-1.5" />
<span className="text-[11px] text-muted-foreground tabular-nums shrink-0">
{(msg.ai_confidence * 100).toFixed(0)}%
</span>
</div>
)}
</div>
</div>
</CardContent>
</Card>
);
}
export function extractFirstImage(
metadata: string | null | undefined,
): string | null {
if (!metadata) return null;
try {
const m = JSON.parse(metadata);
const atts: Array<{ url: string; contentType?: string }> =
m.attachments ?? [];
return atts.find((a) => a.contentType?.startsWith("image/"))?.url ?? null;
} catch {
return null;
}
}
@@ -1,102 +1,124 @@
"use client";
import { ArrowLeft, MessageSquare, MessagesSquare, Pencil } from "lucide-react";
import { Card } from "@/components/ui/card";
import { getMessageChannelLabel, renderMessageContent } from "@/lib/format";
import type { AttachmentRecord, MessageRecord } from "@/lib/types";
import { useState } from "react";
import { Avatar } from "@/components/primitives/avatar";
import { Badge } from "@/components/primitives/badge";
import {
getMessageChannelLabel,
renderMessageContent,
safeParseJsonArray,
} from "@/lib/format";
import type { AttachmentRef, MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
import { AiAnalysisPanel } from "./ai-analysis-panel";
import { AiStatusBadge, SeverityTick } from "./ai-status-badge";
import { AttachmentsGrid } from "./attachments-grid";
import { Lightbox } from "./lightbox";
interface MessageDetailViewProps {
function extractAttachments(metadata?: string | null): AttachmentRef[] {
if (!metadata) return [];
try {
const m = JSON.parse(metadata);
return (m?.attachments ?? []) as AttachmentRef[];
} catch {
return [];
}
}
function fmtFull(ts?: number): string {
if (!ts) return "";
return new Date(ts * 1000).toLocaleString();
}
export interface MessageDetailProps {
message: MessageRecord;
attachments?: AttachmentRecord[];
onBack?: () => void;
onImageClick?: (index: number) => void;
channelLabel?: string;
}
export function MessageDetailView({
message,
attachments,
onBack,
onImageClick,
}: MessageDetailViewProps) {
message: msg,
channelLabel,
}: MessageDetailProps) {
const [img, setImg] = useState<string | null>(null);
const severity = msg.ai_severity ?? "none";
const flags = safeParseJsonArray(msg.ai_moderation_flags || "[]");
return (
<Card
className={cn("h-full", "[--card-spacing:0px]", "rounded-2xl", "p-5")}
>
{onBack && (
<button
type="button"
onClick={onBack}
className="flex items-center gap-1 text-xs text-text-secondary/60 hover:text-text-primary mb-3 transition-colors"
>
<ArrowLeft className="size-3" /> Back
</button>
)}
{/* Message header */}
<div className="flex items-center gap-2 mb-3">
<MessageSquare className="size-4 text-primary" />
<span className="font-semibold text-sm text-text-primary">
{message.username}
</span>
<span className="text-[10px] text-text-secondary/40 font-mono inline-flex items-center gap-1">
{message.thread_id && <MessagesSquare className="size-3" />}
{getMessageChannelLabel(message)}
</span>
<>
<div className="mb-4 flex items-start gap-3">
<Avatar src={msg.avatar_url} name={msg.username} size={40} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2.5 flex-wrap">
<span className="font-semibold">{msg.username}</span>
<span className="mono text-xs text-[var(--color-ink-soft)]">
{fmtFull(msg.created_at)}
</span>
<AiStatusBadge status={msg.ai_status ?? null} />
</div>
<div className="mt-2 text-xs text-[var(--color-ink-soft)]">
#{channelLabel ?? getMessageChannelLabel(msg)}
{msg.thread_id && <span className="mx-1 opacity-40">·</span>}
{msg.thread_id && <span>Thread {msg.thread_id.slice(0, 8)}</span>}
</div>
</div>
</div>
{/* Content */}
<div className="text-sm text-text-primary/90 leading-relaxed mb-4 whitespace-pre-wrap">
{renderMessageContent(
message.edited_content ?? message.content,
message.metadata,
) || "(no text content)"}
<div
className={cn(
"relative rounded-[var(--radius-r)] p-4",
severity === "critical"
? "border-l-2 border-[var(--color-vermilion)]"
: severity === "high"
? "border-l-2 border-[var(--color-amber)]"
: "border border-[var(--color-hairline)]",
)}
>
<SeverityTick severity={severity} />
<div className="text-sm leading-relaxed">
{msg.deleted_at ? (
<span className="italic text-[var(--color-ink-soft)]">
message deleted
</span>
) : (
renderMessageContent(
msg.edited_content ?? msg.content,
msg.metadata,
)
)}
</div>
</div>
{/* Edit history */}
{message.edit_history && message.edit_history.length > 0 && (
<div className="mb-4 space-y-2 rounded-lg border border-border/40 bg-card/30 p-3">
<p className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50 flex items-center gap-1">
<Pencil className="size-3" />
Riwayat edit · {message.edit_history.length} versi sebelumnya
</p>
{message.edit_history.map((edit, i) => (
<div key={`${edit.edited_at}-${i}`} className="space-y-0.5">
<p className="text-[10px] font-mono text-text-secondary/40">
{new Date(edit.edited_at).toLocaleString("id-ID")}
</p>
<p className="text-xs leading-relaxed text-text-secondary/80 line-clamp-4 whitespace-pre-wrap">
{renderMessageContent(edit.old_content, message.metadata) ||
"(kosong)"}
</p>
</div>
{flags.length > 0 && (
<div className="mt-3 flex flex-wrap gap-1.5">
{flags.map((f) => (
<Badge key={f} tone="vermilion">
{f}
</Badge>
))}
</div>
)}
{/* Attachments */}
{attachments && attachments.length > 0 && (
<div className="mb-4">
<AttachmentsGrid
attachments={attachments}
onImageClick={onImageClick}
/>
{msg.ai_analysis && (
<div className="mt-3 rounded-[var(--radius-r)] bg-[var(--color-surface-2)] p-3 text-xs">
<span className="font-medium text-[var(--color-amber)]">
AI analysis:
</span>{" "}
<span className="text-[var(--color-ink-soft)]">
{msg.ai_analysis}
</span>
</div>
)}
{/* AI Analysis */}
<AiAnalysisPanel
status={message.ai_status}
severity={message.ai_severity}
confidence={message.ai_confidence}
flags={message.ai_moderation_flags}
categories={message.ai_categories}
action={message.ai_recommended_action}
score={message.ai_moderation_score}
analysis={message.ai_analysis}
{extractAttachments(msg.metadata).length > 0 && (
<AttachmentsGrid
attachments={extractAttachments(msg.metadata)}
onOpen={(u) => setImg(u)}
/>
)}
<Lightbox
open={!!img}
onClose={() => setImg(null)}
src={img ?? undefined}
/>
</Card>
</>
);
}
@@ -1,76 +0,0 @@
"use client";
import { ArrowLeft, MessageSquare, MessagesSquare } from "lucide-react";
import { Card } from "@/components/ui/card";
import { getMessageChannelLabel, renderMessageContent } from "@/lib/format";
import type { AttachmentRecord, MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
import { AiAnalysisPanel } from "./ai-analysis-panel";
import { AttachmentsGrid } from "./attachments-grid";
interface MessageDetailProps {
message: MessageRecord;
attachments?: AttachmentRecord[];
onBack?: () => void;
}
export function MessageDetail({
message,
attachments,
onBack,
}: MessageDetailProps) {
return (
<Card
className={cn("h-full", "[--card-spacing:0px]", "rounded-2xl", "p-5")}
>
{onBack && (
<button
type="button"
onClick={onBack}
className="flex items-center gap-1 text-xs text-text-secondary/60 hover:text-text-primary mb-3 transition-colors"
>
<ArrowLeft className="size-3" /> Back
</button>
)}
{/* Message header */}
<div className="flex items-center gap-2 mb-3">
<MessageSquare className="size-4 text-primary" />
<span className="font-semibold text-sm text-text-primary">
{message.username}
</span>
<span className="text-[10px] text-text-secondary/40 font-mono inline-flex items-center gap-1">
{message.thread_id && <MessagesSquare className="size-3" />}
{getMessageChannelLabel(message)}
</span>
</div>
{/* Content */}
<div className="text-sm text-text-primary/90 leading-relaxed mb-4 whitespace-pre-wrap">
{renderMessageContent(
message.edited_content ?? message.content,
message.metadata,
) || "(no text content)"}
</div>
{/* Attachments */}
{attachments && attachments.length > 0 && (
<div className="mb-4">
<AttachmentsGrid attachments={attachments} />
</div>
)}
{/* AI Analysis */}
<AiAnalysisPanel
status={message.ai_status}
severity={message.ai_severity}
confidence={message.ai_confidence}
flags={message.ai_moderation_flags}
categories={message.ai_categories}
action={message.ai_recommended_action}
score={message.ai_moderation_score}
analysis={message.ai_analysis}
/>
</Card>
);
}
@@ -0,0 +1,86 @@
"use client";
import { Avatar } from "@/components/primitives/avatar";
import { renderMessageContent } from "@/lib/format";
import type { AiSeverity, MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
import { AiStatusBadge, SeverityTick } from "./ai-status-badge";
function fmtTime(ts?: number): string {
if (!ts) return "";
return new Date(ts * 1000).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
}
const severityColor: Record<NonNullable<AiSeverity>, string> = {
none: "text-[var(--color-ink-soft)]",
low: "text-[var(--color-amber)]",
medium: "text-[var(--color-amber)]",
high: "text-orange-500",
critical: "text-[var(--color-vermilion)]",
};
export interface MessageEntryProps {
message: MessageRecord;
selected: boolean;
onSelect: () => void;
onAvatarClick?: () => void;
}
export function MessageEntry({
message: msg,
selected,
onSelect,
}: MessageEntryProps) {
const severity = (msg.ai_severity ?? "none") as AiSeverity;
const status = msg.ai_status ?? null;
return (
<div
data-selected={selected}
onClick={onSelect}
className={cn(
"group relative mb-1.5 flex items-start gap-2.5 rounded-[var(--radius-r)] p-2.5 cursor-pointer",
"transition-all hover:bg-[var(--color-surface-2)]",
selected && "bg-[var(--color-signal)]/6",
)}
>
<SeverityTick severity={severity} />
<Avatar src={msg.avatar_url} name={msg.username} size={32} />
<div className="min-w-0 flex-1 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium">{msg.username}</span>
<span className="text-xs text-[var(--color-ink-soft)] mono">
{fmtTime(msg.created_at)}
</span>
{status && <AiStatusBadge status={status} />}
{severity !== "none" && (
<span
className={cn(
"text-[10px] font-bold uppercase",
severityColor[severity],
)}
>
{severity}
</span>
)}
</div>
<div className="text-sm leading-relaxed">
{msg.deleted_at ? (
<span className="italic text-[var(--color-ink-soft)]">
message deleted
</span>
) : (
renderMessageContent(
msg.edited_content ?? msg.content,
msg.metadata,
)
)}
</div>
</div>
</div>
);
}
@@ -1,45 +1,55 @@
"use client";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { MessageRecord } from "@/lib/types";
import { MessageCard } from "./message-card";
import { MessageEntry } from "./message-entry";
interface MessageListProps {
export { MessageEntry };
export function MessageList({
messages,
selectedId,
onSelect,
hasMore,
onLoadMore,
isLoadingMore,
}: {
messages: MessageRecord[];
selectedId: string | null;
onSelect: (id: string) => void;
hasMore?: boolean;
onLoadMore?: () => void;
isLoadingMore?: boolean;
}
export function MessageList({
messages,
selectedId: _selectedId,
onSelect,
hasMore,
onLoadMore,
isLoadingMore,
}: MessageListProps) {
}) {
if (messages.length === 0) {
return (
<div className="py-10 text-center">
<p className="text-sm text-[var(--color-ink-soft)]">
No messages found.
</p>
</div>
);
}
return (
<>
{messages.map((msg) => (
<MessageCard key={msg.id} message={msg} onClick={onSelect} />
))}
<div className="space-y-0.5">
{messages.map((m) => (
<MessageEntry
key={m.id}
message={m}
selected={selectedId === m.id}
onSelect={() => onSelect(m.id)}
/>
))}
</div>
{hasMore && (
<div className="flex justify-center py-4">
<Button
variant="outline"
size="sm"
onClick={onLoadMore}
disabled={isLoadingMore}
className="text-xs glass"
>
{isLoadingMore && <Loader2 className="size-3 animate-spin mr-1" />}
Load more
</Button>
</div>
<button
type="button"
onClick={onLoadMore}
disabled={isLoadingMore}
className="mt-3 w-full text-center text-xs text-[var(--color-amber)] hover:underline disabled:opacity-50"
>
{isLoadingMore ? "Loading…" : "Load more"}
</button>
)}
</>
);
@@ -1,108 +1,82 @@
"use client";
import { Search, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useMessageSearch } from "@/hooks";
import { getMessageChannelLabel, renderMessageContent } from "@/lib/format";
import { Search } from "lucide-react";
import { useState } from "react";
import { Dialog } from "@/components/primitives/dialog";
import { Input } from "@/components/primitives/input";
import { cn } from "@/lib/utils";
interface SearchOverlayProps {
open: boolean;
onClose: () => void;
onSelect: (id: string) => void;
export interface Message {
id: string;
content: string;
username: string;
channel: string;
time: string;
}
export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
export interface SearchOverlayProps {
open: boolean;
onClose: () => void;
results: Message[];
onSelect: (msg: Message) => void;
}
export function SearchOverlay({
open,
onClose,
results,
onSelect,
}: SearchOverlayProps) {
const [query, setQuery] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const { data: results } = useMessageSearch(query, true);
useEffect(() => {
if (open) {
setTimeout(() => inputRef.current?.focus(), 100);
} else {
setQuery("");
}
}, [open]);
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === "k") {
e.preventDefault();
onClose(); // this is called when Cmd+K is pressed globally — toggle
}
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKey);
return () => document.removeEventListener("keydown", handleKey);
}, [onClose]);
if (!open) return null;
const filtered = query
? results.filter(
(m) =>
m.content.toLowerCase().includes(query.toLowerCase()) ||
m.username.toLowerCase().includes(query.toLowerCase()),
)
: results;
return (
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]">
<button
type="button"
aria-label="Close search"
className="absolute inset-0 bg-black/60 backdrop-blur-sm cursor-default"
onClick={onClose}
/>
<div className="relative w-full max-w-lg glass-intense rounded-[var(--radius-card)] overflow-hidden shadow-2xl">
{/* Input */}
<div className="flex items-center gap-3 px-4 py-3 border-b border-glass-border">
<Search className="size-4 text-text-secondary/60 shrink-0" />
<input
ref={inputRef}
type="text"
<Dialog open={open} onClose={onClose} className="p-0 max-w-xl">
<div className="p-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-[var(--color-ink-soft)]" />
<Input
autoFocus
placeholder="Search messages… (Esc to close)"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search messages..."
className="flex-1 bg-transparent text-sm text-text-primary placeholder-text-secondary/40 outline-none"
className="pl-9 font-mono"
/>
<button
type="button"
onClick={onClose}
className="size-6 flex items-center justify-center rounded hover:bg-glass-bg"
>
<X className="size-3.5 text-text-secondary/60" />
</button>
</div>
{/* Results */}
<div className="max-h-80 overflow-y-auto p-2 space-y-1">
{!results || results.length === 0 ? (
<div className="py-8 text-center text-xs text-text-secondary/40">
{query.length < 2
? "Type at least 2 characters"
: "No results found"}
</div>
<div className="mt-3 max-h-[420px] overflow-y-auto">
{filtered.length === 0 ? (
<p className="py-6 text-center text-sm text-[var(--color-ink-soft)]">
No results.
</p>
) : (
results.map((msg) => (
<button
key={msg.id}
type="button"
onClick={() => {
onSelect(msg.id);
onClose();
}}
className="w-full text-left px-3 py-2 rounded-lg hover:bg-glass-bg transition-colors"
>
<div className="flex items-center gap-2 text-xs">
<span className="font-medium text-text-primary">
{msg.username}
<div className="flex flex-col gap-1">
{filtered.slice(0, 32).map((m) => (
<button
key={m.id}
type="button"
onClick={() => onSelect(m)}
className="group flex flex-col items-start gap-1 rounded-[var(--radius-r-control)] px-2.5 py-2 text-left transition-colors hover:bg-[var(--color-surface-2)]"
>
<span className="text-xs text-[var(--color-ink-soft)] group-hover:text-[var(--color-ink)]">
#{m.channel} · {m.username}
</span>
<span className="text-text-secondary/40">
{getMessageChannelLabel(msg)}
<span className="text-sm">{m.content}</span>
<span className="text-[10px] text-[var(--color-ink-soft)]/60">
{m.time}
</span>
</div>
<p className="text-xs text-text-secondary/80 line-clamp-1 mt-0.5">
{renderMessageContent(msg.content, msg.metadata)}
</p>
</button>
))
</button>
))}
</div>
)}
</div>
</div>
</div>
</Dialog>
);
}
@@ -12,9 +12,8 @@ import {
XCircle,
} from "lucide-react";
import { useState } from "react";
import { Badge } from "@/components/primitives/badge";
import { EmptyState, LoadingSkeleton } from "@/components/shared";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { useModerationActions, useModerationStats } from "@/hooks";
import { renderMessageContent } from "@/lib/format";
import type {
@@ -26,42 +25,22 @@ import { cn } from "@/lib/utils";
const ACTION_META: Record<
ModerationActionType,
{ label: string; Icon: typeof Trash2; className: string }
{ label: string; Icon: typeof Trash2; tone: "vermilion" | "amber" }
> = {
delete_message: {
label: "Delete message",
Icon: Trash2,
className: "text-red-500",
},
mute_user: { label: "Mute user", Icon: MicOff, className: "text-orange-500" },
warn_user: {
label: "Warn user",
Icon: AlertTriangle,
className: "text-amber-500",
},
kick_user: { label: "Kick user", Icon: UserX, className: "text-orange-500" },
ban_user: { label: "Ban user", Icon: Ban, className: "text-red-500" },
delete_message: { label: "Delete message", Icon: Trash2, tone: "vermilion" },
mute_user: { label: "Mute user", Icon: MicOff, tone: "amber" },
warn_user: { label: "Warn user", Icon: AlertTriangle, tone: "amber" },
kick_user: { label: "Kick user", Icon: UserX, tone: "amber" },
ban_user: { label: "Ban user", Icon: Ban, tone: "vermilion" },
};
const STATUS_META: Record<
ModerationAction["status"],
{ label: string; className: string; dot: string }
{ label: string; tone: "signal" | "vermilion" | "amber" }
> = {
executed: {
label: "Executed",
className: "border-green-500/40 text-green-500",
dot: "bg-green-500",
},
failed: {
label: "Failed",
className: "border-red-500/40 text-red-500",
dot: "bg-red-500",
},
pending: {
label: "Pending",
className: "border-amber-500/40 text-amber-500",
dot: "bg-amber-500",
},
executed: { label: "Executed", tone: "signal" },
failed: { label: "Failed", tone: "vermilion" },
pending: { label: "Pending", tone: "amber" },
};
function fmtTime(ts: number | null): string {
@@ -115,31 +94,28 @@ export function ModerationSection({
];
return (
<div className="space-y-4 animate-fade-in-up">
<div className="space-y-4">
{/* Summary cards */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<SummaryCard
label="Total aksi"
value={s.total}
color="text-text-primary"
/>
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
<SummaryCard label="Total aksi" value={s.total} />
<SummaryCard
label="Executed"
value={s.executed}
color="text-green-500"
tone="signal"
hint={undefined}
/>
<SummaryCard
label="Failed"
value={s.failed}
color="text-red-500"
tone="vermilion"
hint={s.total > 0 ? `${s.failed_rate}%` : undefined}
/>
<SummaryCard label="Pending" value={s.pending} color="text-amber-500" />
<SummaryCard label="Pending" value={s.pending} tone="amber" />
</div>
{/* Filters */}
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50">
<span className="text-[10px] font-semibold uppercase tracking-wide text-[var(--color-ink-soft)]">
Status
</span>
{statusFilters.map((f) => (
@@ -154,7 +130,7 @@ export function ModerationSection({
onClick={() => setStatus(f)}
/>
))}
<span className="ml-3 text-[10px] font-semibold uppercase tracking-wide text-text-secondary/50">
<span className="ml-3 text-[10px] font-semibold uppercase tracking-wide text-[var(--color-ink-soft)]">
Tipe
</span>
{typeFilters.map((f) => (
@@ -173,13 +149,13 @@ export function ModerationSection({
{actionsLoading && !actions ? (
<LoadingSkeleton count={6} height="h-16" />
) : !actions || actions.length === 0 ? (
<Card className={cn("p-6", "[--card-spacing:0px]", "rounded-2xl")}>
<div className="surface p-6">
<EmptyState
icon={ShieldAlert}
title="Belum ada aksi moderasi"
description="Aksi auto- moderasi (delete, warn, kick, ban) akan muncul di sini."
description="Aksi auto-moderasi (delete, warn, kick, ban) akan muncul di sini."
/>
</Card>
</div>
) : (
<div className="space-y-2">
{actions.map((a) => (
@@ -188,7 +164,7 @@ export function ModerationSection({
</div>
)}
<p className="text-[10px] text-text-secondary/40">
<p className="text-[10px] text-[var(--color-ink-soft)]">
{actions?.length ?? 0} aksi ditampilkan · log moderasi gateway Discord
</p>
</div>
@@ -198,26 +174,34 @@ export function ModerationSection({
function SummaryCard({
label,
value,
color,
tone,
hint,
}: {
label: string;
value: number;
color: string;
tone?: "signal" | "vermilion" | "amber";
hint?: string;
}) {
return (
<Card className={cn("p-4", "[--card-spacing:0px]", "rounded-2xl")}>
<p className="text-[10px] uppercase tracking-wide text-text-secondary/50">
<div className="surface p-4">
<p className="text-[10px] uppercase tracking-wide text-[var(--color-ink-soft)]">
{label}
</p>
<p className={cn("mt-1 text-2xl font-bold", color)}>
<p
className={cn(
"mt-1 text-2xl font-bold",
tone === "signal" && "text-[var(--color-signal)]",
tone === "vermilion" && "text-[var(--color-vermilion)]",
tone === "amber" && "text-[var(--color-amber)]",
!tone && "text-[var(--color-ink)]",
)}
>
{value}
{hint && (
<span className="ml-1 text-xs font-medium opacity-80">({hint})</span>
)}
</p>
</Card>
</div>
);
}
@@ -237,8 +221,8 @@ function FilterChip({
className={cn(
"rounded-full px-3 py-1 text-[11px] transition-colors",
active
? "bg-primary/20 text-primary"
: "text-text-secondary/60 hover:text-text-primary glass",
? "bg-[var(--color-signal)] text-[var(--color-signal-ink)]"
: "text-[var(--color-ink-soft)] hover:bg-[var(--color-surface-2)] hover:text-[var(--color-ink)]",
)}
>
{label}
@@ -251,49 +235,45 @@ function ActionRow({ action }: { action: ModerationAction }) {
const st = STATUS_META[action.status];
const Icon = meta.Icon;
return (
<Card
className={cn(
"flex items-start gap-3 p-3",
"[--card-spacing:0px]",
"rounded-2xl",
)}
>
<span className={cn("mt-0.5 shrink-0", meta.className)}>
<div className="surface flex items-start gap-3 p-3">
<span
className={cn(
"mt-0.5 shrink-0",
meta.tone === "vermilion"
? "text-[var(--color-vermilion)]"
: "text-[var(--color-amber)]",
)}
>
<Icon className="size-4" />
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-semibold text-text-primary">
<span className="text-xs font-semibold text-[var(--color-ink)]">
{meta.label}
</span>
{action.username && (
<span className="text-xs text-text-secondary">
<span className="text-xs text-[var(--color-ink-soft)]">
@{action.username}
</span>
)}
<Badge variant="outline" className={cn("text-[10px]", st.className)}>
<span
className={cn("mr-1 inline-block size-1.5 rounded-full", st.dot)}
/>
{st.label}
</Badge>
<Badge tone={st.tone}>{st.label}</Badge>
</div>
{action.content && (
<p className="mt-1 line-clamp-2 text-xs text-text-secondary/80">
<p className="mt-1 line-clamp-2 text-xs text-[var(--color-ink-soft)]">
{renderMessageContent(action.content, null)}
</p>
)}
{action.reason && (
<p className="mt-1 text-[11px] text-text-secondary/60">
<p className="mt-1 text-[11px] text-[var(--color-ink-soft)]">
Alasan: {action.reason}
</p>
)}
{action.error && (
<p className="mt-1 text-[11px] text-red-500/80 line-clamp-2">
<p className="mt-1 text-[11px] text-[var(--color-vermilion)] line-clamp-2">
Error: {action.error}
</p>
)}
<p className="mt-1.5 text-[10px] font-mono text-text-secondary/40">
<p className="mt-1.5 text-[10px] font-mono text-[var(--color-ink-soft)]">
dibuat {fmtTime(action.created_at)}
{action.executed_at
? ` · dieksekusi ${fmtTime(action.executed_at)}`
@@ -301,13 +281,13 @@ function ActionRow({ action }: { action: ModerationAction }) {
</p>
</div>
{action.status === "executed" ? (
<CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-green-500" />
<CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-[var(--color-signal)]" />
) : action.status === "failed" ? (
<XCircle className="mt-0.5 size-3.5 shrink-0 text-red-500" />
<XCircle className="mt-0.5 size-3.5 shrink-0 text-[var(--color-vermilion)]" />
) : (
<Loader2 className="mt-0.5 size-3.5 shrink-0 animate-spin text-amber-500" />
<Loader2 className="mt-0.5 size-3.5 shrink-0 animate-spin text-[var(--color-amber)]" />
)}
</Card>
</div>
);
}
@@ -0,0 +1,30 @@
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { usePathname } from "next/navigation";
import type { ReactNode } from "react";
import { ease } from "./variants";
export function RouteTransition({ children }: { children: ReactNode }) {
const pathname = usePathname();
const reduce = useReducedMotion();
if (reduce) {
return <div key={pathname}>{children}</div>;
}
return (
<AnimatePresence mode="popLayout" initial={false}>
<motion.div
key={pathname}
initial={{ opacity: 0, y: 8, filter: "blur(4px)" }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, filter: "blur(4px)" }}
transition={{ duration: 0.22, ease }}
className="contents"
>
{children}
</motion.div>
</AnimatePresence>
);
}
@@ -0,0 +1,53 @@
"use client";
import { motion, type Variants } from "motion/react";
import type { ReactNode } from "react";
import { fadeUp, stagger } from "./variants";
type V = Variants;
interface StaggerGroupProps {
children: ReactNode;
className?: string;
variants?: V;
as?: "div" | "ul" | "section";
}
export function StaggerGroup({
children,
className,
variants = stagger,
as = "div",
}: StaggerGroupProps) {
const Tag = motion[as];
return (
<Tag
className={className}
variants={variants}
initial="hidden"
animate="visible"
>
{children}
</Tag>
);
}
interface StaggerItemProps {
children: ReactNode;
className?: string;
variants?: V;
layout?: boolean;
}
export function StaggerItem({
children,
className,
variants = fadeUp,
layout,
}: StaggerItemProps) {
return (
<motion.div className={className} variants={variants} layout={layout}>
{children}
</motion.div>
);
}
@@ -0,0 +1,31 @@
import type { Transition, Variants } from "motion/react";
/** Spring tuned for UI micro-interactions. */
export const spring: Transition = {
type: "spring",
stiffness: 260,
damping: 24,
};
/** Expressive ease-out for page/section transitions. */
export const ease = [0.22, 1, 0.36, 1] as const;
/** Single-element fade + rise. */
export const fadeUp: Variants = {
hidden: { opacity: 0, y: 8 },
visible: { opacity: 1, y: 0, transition: { duration: 0.32, ease } },
};
/** Parent that staggers its children. */
export const stagger: Variants = {
hidden: {},
visible: {
transition: { staggerChildren: 0.06, delayChildren: 0.08 },
},
};
/** Scale-in for emphasis blocks. */
export const popIn: Variants = {
hidden: { opacity: 0, scale: 0.94 },
visible: { opacity: 1, scale: 1, transition: spring },
};
@@ -0,0 +1,39 @@
import { cn } from "@/lib/utils";
export interface AvatarProps {
src?: string | null;
name?: string | null;
size?: number;
className?: string;
}
function initials(name?: string | null): string {
if (!name) return "?";
const parts = name.trim().split(/\s+/);
if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
export function Avatar({ src, name, size = 36, className }: AvatarProps) {
return (
<span
className={cn(
"relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full",
"bg-[var(--color-signal)]/20 text-[var(--color-signal)] font-semibold",
className,
)}
style={{ width: size, height: size, fontSize: size * 0.38 }}
>
{src ? (
<img
src={src}
alt={name ?? ""}
className="size-full object-cover"
loading="lazy"
/>
) : (
initials(name)
)}
</span>
);
}
@@ -0,0 +1,42 @@
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
export type BadgeTone = "signal" | "amber" | "vermilion" | "neutral";
const toneClass: Record<BadgeTone, string> = {
signal: "bg-[var(--color-signal)]/15 text-[var(--color-signal)]",
amber: "bg-[var(--color-amber)]/15 text-[var(--color-amber)]",
vermilion: "bg-[var(--color-vermilion)]/15 text-[var(--color-vermilion)]",
neutral: "bg-[var(--color-hairline)] text-[var(--color-ink-soft)]",
};
export interface BadgeProps {
tone?: BadgeTone;
children: ReactNode;
className?: string;
dot?: boolean;
}
export function Badge({
tone = "neutral",
children,
className,
dot,
}: BadgeProps) {
return (
<span className={cn("pill", toneClass[tone], className)}>
{dot && (
<span
className={cn(
"size-1.5 rounded-full",
tone === "signal" && "bg-[var(--color-signal)]",
tone === "amber" && "bg-[var(--color-amber)]",
tone === "vermilion" && "bg-[var(--color-vermilion)]",
tone === "neutral" && "bg-[var(--color-ink-soft)]",
)}
/>
)}
{children}
</span>
);
}
@@ -0,0 +1,55 @@
"use client";
import { type HTMLMotionProps, motion, useReducedMotion } from "motion/react";
import { forwardRef } from "react";
import { cn } from "@/lib/utils";
type Variant = "primary" | "ghost" | "danger" | "outline";
type Size = "sm" | "md" | "lg" | "icon";
const variantClass: Record<Variant, string> = {
primary:
"bg-[var(--color-signal)] text-[var(--color-signal-ink)] hover:opacity-90",
ghost:
"bg-transparent text-[var(--color-ink)] hover:bg-[var(--color-surface-2)]",
danger: "bg-[var(--color-vermilion)] text-white hover:opacity-90",
outline:
"bg-transparent text-[var(--color-ink)] border border-[var(--color-hairline)] hover:bg-[var(--color-surface-2)]",
};
const sizeClass: Record<Size, string> = {
sm: "h-8 px-3 text-xs rounded-[var(--radius-r-control)]",
md: "h-10 px-4 text-sm rounded-[var(--radius-r-control)]",
lg: "h-12 px-6 text-base rounded-[var(--radius-r)]",
icon: "size-9 rounded-[var(--radius-r-control)]",
};
export interface ButtonProps extends Omit<HTMLMotionProps<"button">, "ref"> {
variant?: Variant;
size?: Size;
}
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
(
{ className, variant = "primary", size = "md", children, ...props },
ref,
) => {
const reduce = useReducedMotion();
return (
<motion.button
ref={ref}
className={cn(
"inline-flex items-center justify-center gap-2 select-none cursor-pointer font-medium outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-ring)] disabled:opacity-50 disabled:pointer-events-none transition-colors duration-150",
variantClass[variant],
sizeClass[size],
className,
)}
whileTap={reduce ? undefined : { scale: 0.97 }}
{...props}
>
{children}
</motion.button>
);
},
);
Button.displayName = "Button";
@@ -0,0 +1,75 @@
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { type ReactNode, useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
export interface DialogProps {
open: boolean;
onClose: () => void;
children: ReactNode;
className?: string;
labelledBy?: string;
}
export function Dialog({
open,
onClose,
children,
className,
labelledBy,
}: DialogProps) {
const ref = useRef<HTMLDivElement>(null);
const reduce = useReducedMotion();
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", onKey);
document.body.style.overflow = "hidden";
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = "";
};
}, [open, onClose]);
return (
<AnimatePresence>
{open && (
<motion.div
className="fixed inset-0 z-50 flex items-center justify-center p-4"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.18 }}
>
<div
className="absolute inset-0 bg-black/55 backdrop-blur-sm"
onClick={onClose}
aria-hidden
/>
<motion.div
ref={ref}
role="dialog"
aria-modal="true"
aria-labelledby={labelledBy}
className={cn(
"relative z-10 w-full max-w-lg surface-2 shadow-2xl",
className,
)}
initial={
reduce ? { opacity: 0 } : { opacity: 0, scale: 0.96, y: 12 }
}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.96, y: 12 }}
transition={{ type: "spring", stiffness: 320, damping: 28 }}
>
{children}
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}
@@ -0,0 +1,11 @@
export { Avatar, type AvatarProps } from "./avatar";
export { Badge, type BadgeProps, type BadgeTone } from "./badge";
export { Button, type ButtonProps } from "./button";
export { Dialog, type DialogProps } from "./dialog";
export { Input, type InputProps } from "./input";
export { Progress, type ProgressProps } from "./progress";
export { Select, type SelectProps } from "./select";
export { Sheet, type SheetProps } from "./sheet";
export { Skeleton, type SkeletonProps } from "./skeleton";
export { Toaster, type ToasterProps, useToast } from "./toast";
export { Tooltip, type TooltipProps } from "./tooltip";
@@ -0,0 +1,23 @@
import { forwardRef, type InputHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
mono?: boolean;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(
({ className, mono, ...props }, ref) => (
<input
ref={ref}
className={cn(
"w-full bg-[var(--color-surface-2)] text-[var(--color-ink)] placeholder:text-[var(--color-ink-soft)]/60",
"rounded-[var(--radius-r-control)] border border-[var(--color-hairline)] px-3 py-2 text-sm",
"outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-ring)] transition-colors",
mono && "font-mono tracking-tight",
className,
)}
{...props}
/>
),
);
Input.displayName = "Input";
@@ -0,0 +1,39 @@
import { cn } from "@/lib/utils";
export interface ProgressProps {
value: number;
max?: number;
className?: string;
tone?: "signal" | "amber" | "vermilion";
showLabel?: boolean;
}
export function Progress({
value,
max = 100,
className,
tone = "signal",
showLabel,
}: ProgressProps) {
const pct = Math.max(0, Math.min(100, (value / max) * 100));
const stroke = {
signal: "var(--color-signal)",
amber: "var(--color-amber)",
vermilion: "var(--color-vermilion)",
}[tone];
return (
<div className={cn("flex items-center gap-2", className)}>
<div className="relative h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--color-hairline)]">
<div
className="absolute inset-y-0 left-0 rounded-full transition-[width] duration-300"
style={{ width: `${pct}%`, background: stroke }}
/>
</div>
{showLabel && (
<span className="mono text-xs text-[var(--color-ink-soft)]">
{Math.round(pct)}%
</span>
)}
</div>
);
}
@@ -0,0 +1,26 @@
import { forwardRef, type SelectHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
export interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {
mono?: boolean;
}
export const Select = forwardRef<HTMLSelectElement, SelectProps>(
({ className, mono, children, ...props }, ref) => (
<select
ref={ref}
className={cn(
"w-full bg-[var(--color-surface-2)] text-[var(--color-ink)] appearance-none cursor-pointer",
"rounded-[var(--radius-r-control)] border border-[var(--color-hairline)] px-3 py-2 text-sm",
"outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-ring)] transition-colors",
"bg-[url('data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2212%22 height=%2212%22 fill=%22none%22 stroke=%22%23aaa%22 stroke-width=%222%22><path d=%22M2 4l4 4 4-4%22/></svg>')] bg-[length:12px] bg-[right_0.75rem_center] bg-no-repeat pr-9",
mono && "font-mono tracking-tight",
className,
)}
{...props}
>
{children}
</select>
),
);
Select.displayName = "Select";
@@ -0,0 +1,74 @@
"use client";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { type ReactNode, useEffect } from "react";
import { cn } from "@/lib/utils";
export interface SheetProps {
open: boolean;
onClose: () => void;
children: ReactNode;
side?: "left" | "right" | "bottom";
className?: string;
}
export function Sheet({
open,
onClose,
children,
side = "left",
className,
}: SheetProps) {
const reduce = useReducedMotion();
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [open, onClose]);
const dir =
side === "left"
? { initial: { x: "-100%" }, animate: { x: 0 } }
: side === "right"
? { initial: { x: "100%" }, animate: { x: 0 } }
: { initial: { y: "100%" }, animate: { y: 0 } };
return (
<AnimatePresence>
{open && (
<motion.div
className="fixed inset-0 z-50"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
<div
className="absolute inset-0 bg-black/55 backdrop-blur-sm"
onClick={onClose}
aria-hidden
/>
<motion.aside
className={cn(
"absolute bg-[var(--color-canvas)] shadow-2xl",
side === "left" &&
"left-0 top-0 h-full w-72 border-r border-[var(--color-hairline)]",
side === "right" &&
"right-0 top-0 h-full w-72 border-l border-[var(--color-hairline)]",
side === "bottom" &&
"bottom-0 left-0 w-full rounded-t-2xl border-t border-[var(--color-hairline)]",
className,
)}
initial={reduce ? { opacity: 0 } : dir.initial}
animate={reduce ? { opacity: 1 } : dir.animate}
exit={reduce ? { opacity: 0 } : dir.initial}
transition={{ type: "spring", stiffness: 320, damping: 32 }}
>
{children}
</motion.aside>
</motion.div>
)}
</AnimatePresence>
);
}
@@ -0,0 +1,20 @@
import { cn } from "@/lib/utils";
export interface SkeletonProps {
className?: string;
rounded?: boolean;
}
export function Skeleton({ className, rounded }: SkeletonProps) {
return (
<div
aria-hidden
className={cn(
"animate-shimmer rounded-[var(--radius-r-control)]",
"bg-[var(--color-surface-2)]",
rounded && "rounded-full",
className,
)}
/>
);
}
@@ -0,0 +1,147 @@
"use client";
import { X } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useState,
} from "react";
import { cn } from "@/lib/utils";
type ToastTone = "signal" | "amber" | "vermilion" | "neutral";
interface ToastItem {
id: number;
title?: string;
description?: string;
tone: ToastTone;
}
interface ToastContextValue {
toast: (t: {
title?: string;
description?: string;
tone?: ToastTone;
}) => void;
}
const ToastContext = createContext<ToastContextValue | null>(null);
export function useToast() {
const ctx = useContext(ToastContext);
if (!ctx) {
return {
toast: (_: {
title?: string;
description?: string;
tone?: ToastTone;
}) => {},
};
}
return ctx;
}
const toneBar: Record<ToastTone, string> = {
signal: "bg-[var(--color-signal)]",
amber: "bg-[var(--color-amber)]",
vermilion: "bg-[var(--color-vermilion)]",
neutral: "bg-[var(--color-ink-soft)]",
};
export interface ToasterProps {
position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
}
export function Toaster({ position = "bottom-right" }: ToasterProps) {
const [items, setItems] = useState<ToastItem[]>([]);
const reduce = useReducedMotion();
const toast = useCallback(
(t: { title?: string; description?: string; tone?: ToastTone }) => {
const id = Date.now() + Math.random();
const item: ToastItem = {
id,
tone: t.tone ?? "neutral",
title: t.title,
description: t.description,
};
setItems((prev) => [...prev, item]);
setTimeout(() => {
setItems((prev) => prev.filter((i) => i.id !== id));
}, 4500);
},
[],
);
useEffect(() => {
// expose a no-op provider only; actual provider wraps below
}, []);
const posClass =
position === "bottom-right"
? "bottom-4 right-4"
: position === "bottom-left"
? "bottom-4 left-4"
: position === "top-right"
? "top-4 right-4"
: "top-4 left-4";
return (
<ToastContext.Provider value={{ toast }}>
<div
className={cn(
"fixed z-[60] flex w-[min(92vw,360px)] flex-col gap-2",
posClass,
)}
>
<AnimatePresence>
{items.map((it) => (
<motion.div
key={it.id}
layout
initial={
reduce ? { opacity: 0 } : { opacity: 0, x: 40, scale: 0.96 }
}
animate={{ opacity: 1, x: 0, scale: 1 }}
exit={
reduce ? { opacity: 0 } : { opacity: 0, x: 40, scale: 0.96 }
}
transition={{ type: "spring", stiffness: 360, damping: 30 }}
className="surface-2 relative flex gap-3 overflow-hidden p-3 pr-9 shadow-xl"
>
<span
className={cn("w-1 shrink-0 rounded-full", toneBar[it.tone])}
/>
<div className="min-w-0 flex-1">
{it.title && (
<div className="text-sm font-semibold text-[var(--color-ink)]">
{it.title}
</div>
)}
{it.description && (
<div className="text-xs text-[var(--color-ink-soft)]">
{it.description}
</div>
)}
</div>
<button
type="button"
onClick={() =>
setItems((prev) => prev.filter((i) => i.id !== it.id))
}
className="absolute right-2 top-2 text-[var(--color-ink-soft)] hover:text-[var(--color-ink)]"
aria-label="Dismiss"
>
<X className="size-3.5" />
</button>
</motion.div>
))}
</AnimatePresence>
</div>
</ToastContext.Provider>
);
}
@@ -0,0 +1,50 @@
"use client";
import { type ReactNode, useState } from "react";
import { cn } from "@/lib/utils";
export interface TooltipProps {
content: ReactNode;
children: ReactNode;
side?: "top" | "bottom" | "left" | "right";
className?: string;
}
const sidePos: Record<NonNullable<TooltipProps["side"]>, string> = {
top: "bottom-full left-1/2 -translate-x-1/2 mb-2",
bottom: "top-full left-1/2 -translate-x-1/2 mt-2",
left: "right-full top-1/2 -translate-y-1/2 mr-2",
right: "left-full top-1/2 -translate-y-1/2 ml-2",
};
export function Tooltip({
content,
children,
side = "top",
className,
}: TooltipProps) {
const [show, setShow] = useState(false);
return (
<span
className="relative inline-flex"
onMouseEnter={() => setShow(true)}
onMouseLeave={() => setShow(false)}
onFocus={() => setShow(true)}
onBlur={() => setShow(false)}
>
{children}
<span
role="tooltip"
className={cn(
"pointer-events-none absolute z-50 whitespace-nowrap rounded-[var(--radius-r-control)] px-2.5 py-1 text-xs font-medium",
"bg-[var(--color-ink)] text-[var(--color-canvas)] opacity-0 transition-opacity duration-150",
sidePos[side],
show && "opacity-100",
className,
)}
>
{content}
</span>
</span>
);
}
@@ -1,161 +0,0 @@
"use client";
import { Download, Loader2, Pause, Play } from "lucide-react";
import { useState } from "react";
import { Card } from "@/components/ui/card";
import { formatBytes } from "@/lib/format";
import type { VoiceRecording } from "@/lib/types";
import { cn } from "@/lib/utils";
interface RecordingCardProps {
recording: VoiceRecording;
active: boolean;
playing: boolean;
loading: boolean;
onTogglePlay: (id: string) => void;
}
const BAR_COUNT = 40;
const barBase = (i: number) => 22 + Math.sin(i * 0.45) * 14 + ((i * 7) % 11);
export function RecordingCard({
recording,
active,
playing,
loading,
onTogglePlay,
}: RecordingCardProps) {
const [downloading, setDownloading] = useState(false);
const sizeStr = recording.size_bytes
? formatBytes(recording.size_bytes)
: "--";
// Fetch the file (CORS is open on the uploader) → blob → force download with
// the real filename. Falls back to opening the URL in a new tab.
const handleDownload = async (e: React.MouseEvent) => {
e.stopPropagation();
if (!recording.download_url || downloading) return;
setDownloading(true);
try {
const res = await fetch(recording.download_url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const blob = await res.blob();
const objUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = objUrl;
a.download = recording.filename ?? `recording-${recording.id}.mp3`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(objUrl), 30_000);
} catch {
window.open(recording.download_url, "_blank", "noopener,noreferrer");
} finally {
setDownloading(false);
}
};
return (
<Card
className={cn(
`p-4 transition-all ${
active
? "ring-1 ring-primary/40 border-primary/30 animate-card-glow"
: "hover:ring-1 hover:ring-border/60"
}`,
"cursor-pointer transition-colors hover:ring-primary/40",
"[--card-spacing:0px]",
"rounded-2xl",
)}
onClick={() => onTogglePlay(recording.id)}
>
<div className="flex items-start gap-3">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onTogglePlay(recording.id);
}}
aria-label={playing ? "Pause" : loading ? "Loading" : "Play"}
className={`flex size-10 shrink-0 items-center justify-center rounded-full glass-elevated transition-transform hover:scale-105 ${
active ? "ring-1 ring-primary/50" : ""
}`}
>
{loading ? (
<Loader2 className="size-4 animate-spin text-primary" />
) : playing ? (
<Pause className="size-4 text-primary" />
) : (
<Play className="size-4 text-primary ml-0.5" />
)}
</button>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 text-sm">
<span className="font-semibold text-text-primary">
{recording.username}
</span>
<span className="text-[10px] text-text-secondary/40 font-mono">
{recording.channel_name}
</span>
{active && (
<span className="ml-auto inline-flex items-center gap-1 text-[9px] font-semibold uppercase tracking-widest text-primary/90">
{loading ? "Loading" : playing ? "Now Playing" : "Paused"}
</span>
)}
</div>
{/* Waveform — bounces while playing, pulses while loading */}
<div className="my-2 flex h-8 items-end gap-0.5 overflow-hidden">
{Array.from({ length: BAR_COUNT }, (_, i) => (
<div
key={i}
className={`flex-1 rounded-t-sm transition-colors ${
active ? "bg-primary" : "bg-primary/50"
} ${loading ? "animate-pulse opacity-40" : ""} ${
playing ? "animate-eq" : ""
}`}
style={{
height: `${barBase(i)}%`,
animationDelay: playing ? `${(i % 8) * 0.09}s` : undefined,
}}
/>
))}
</div>
<div className="flex items-center justify-between">
<span className="text-[10px] font-mono text-text-secondary/60">
{sizeStr}
</span>
<span className="text-[10px] text-text-secondary/40">
{new Date(recording.created_at).toLocaleString()}
</span>
</div>
</div>
{/* biome-ignore lint/a11y/noStaticElementInteractions: stopPropagation container — prevents card play toggle when clicking action buttons */}
{/* biome-ignore lint/a11y/useKeyWithClickEvents: no keyboard interaction — container only swallows clicks destined for the action buttons */}
<div
className="flex shrink-0 gap-1"
onClick={(e) => e.stopPropagation()}
>
{recording.download_url && (
<button
type="button"
onClick={handleDownload}
disabled={downloading}
title="Download"
className="flex size-7 items-center justify-center rounded glass hover:glass-elevated transition-all disabled:opacity-50"
>
{downloading ? (
<Loader2 className="size-3 animate-spin text-text-secondary/60" />
) : (
<Download className="size-3 text-text-secondary/60" />
)}
</button>
)}
</div>
</div>
</Card>
);
}
@@ -1,149 +1,78 @@
"use client";
import { Loader2, Pause, Play, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
/**
* RecordingPlayer — canonical single-recording row component.
*/
import { Delete, Download, Play } from "lucide-react";
import { Waveform } from "@/components/charts/waveform";
import { Avatar } from "@/components/primitives/avatar";
import { Badge } from "@/components/primitives/badge";
import { Button } from "@/components/primitives/button";
import type { VoiceRecording } from "@/lib/types";
interface RecordingPlayerProps {
url?: string;
filename?: string;
playing: boolean;
loading: boolean;
audioRef: React.RefObject<HTMLAudioElement | null>;
onToggle: () => void;
onStateChange: (s: { playing: boolean; loading: boolean }) => void;
onClose: () => void;
export interface RecordingPlayerProps {
recording: VoiceRecording;
onSelect?: (rec: VoiceRecording) => void;
onDelete?: (rec: VoiceRecording) => void;
deleting?: boolean;
}
export function RecordingPlayer({
url,
filename,
playing,
loading,
audioRef,
onToggle,
onStateChange,
onClose,
recording,
onSelect,
onDelete,
deleting,
}: RecordingPlayerProps) {
const [progress, setProgress] = useState(0);
const [duration, setDuration] = useState(0);
const [error, setError] = useState(false);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
// Load the track whenever the URL changes; the click that opened the player
// counts as a user gesture so autoplay is allowed.
useEffect(() => {
const audio = audioRef.current;
if (!url || !audio) return;
setError(false);
setProgress(0);
setDuration(0);
audio.src = url;
audio.load();
const p = audio.play();
if (p) p.catch(() => {});
}, [url, audioRef]);
// Progress ticker + cleanup.
useEffect(() => {
if (timerRef.current) clearInterval(timerRef.current);
timerRef.current = setInterval(() => {
const audio = audioRef.current;
if (!audio) return;
if (duration === 0 && !Number.isNaN(audio.duration))
setDuration(audio.duration);
if (!Number.isNaN(audio.currentTime)) setProgress(audio.currentTime);
}, 250);
return () => {
if (timerRef.current) clearInterval(timerRef.current);
};
}, [duration, audioRef]);
if (!url) return null;
const fmt = (s: number) => {
if (!Number.isFinite(s) || s <= 0) return "0:00";
const m = Math.floor(s / 60);
const ss = Math.floor(s % 60);
return `${m}:${String(ss).padStart(2, "0")}`;
};
const pct = duration > 0 ? Math.min(100, (progress / duration) * 100) : 0;
return (
<Card
className={cn(
"fixed bottom-20 left-4 z-30 w-80 flex flex-col gap-1.5",
"[--card-spacing:0px]",
"p-3",
)}
>
<div className="flex items-center gap-2.5">
<button
type="button"
onClick={onToggle}
disabled={loading}
title={playing ? "Pause" : "Play"}
className="flex size-8 shrink-0 items-center justify-center rounded-full glass-elevated transition-transform hover:scale-105 disabled:opacity-60"
>
{loading ? (
<Loader2 className="size-3.5 animate-spin text-primary" />
) : playing ? (
<Pause className="size-3.5 text-primary" />
) : (
<Play className="size-3.5 text-primary ml-0.5" />
)}
</button>
<div className="min-w-0 flex-1">
<div className="truncate text-[11px] font-medium text-text-primary">
{filename ?? "recording"}
</div>
<div className="flex items-center gap-2">
<span className="font-mono text-[10px] text-text-secondary/60">
{fmt(progress)} / {fmt(duration)}
</span>
{loading && (
<span className="text-[10px] text-primary/80">loading…</span>
)}
{error && (
<span className="text-[10px] text-red-400/90">
playback failed
</span>
)}
</div>
</div>
<button type="button" onClick={onClose} className="shrink-0">
<X className="size-3.5 text-text-secondary/60 hover:text-text-primary" />
</button>
</div>
{/* Progress bar */}
<div className="h-1 w-full overflow-hidden rounded-full bg-glass-border">
<div
className="h-full rounded-full bg-primary transition-[width] duration-300"
style={{ width: `${pct}%` }}
/>
</div>
{/* Hidden audio element drives everything above. */}
<audio
ref={audioRef}
preload="auto"
onLoadStart={() => onStateChange({ playing: false, loading: true })}
onWaiting={() => onStateChange({ playing: false, loading: true })}
onCanPlay={() => onStateChange({ playing: true, loading: false })}
onPlaying={() => onStateChange({ playing: true, loading: false })}
onPlay={() => onStateChange({ playing: true, loading: false })}
onPause={() => onStateChange({ playing: false, loading: false })}
onEnded={() => onStateChange({ playing: false, loading: false })}
onError={() => {
setError(true);
onStateChange({ playing: false, loading: false });
}}
className="hidden"
<div className="flex items-center gap-3 rounded-[var(--radius-r)] bg-[var(--color-surface)] p-3">
<Waveform
seed={recording.id}
bars={16}
height={36}
className="w-20 shrink-0"
/>
</Card>
<Avatar name={recording.username} src={recording.avatar_url} size={32} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="text-sm font-medium">
{recording.username ?? "unknown"}
</span>
<Badge tone="neutral">
.{recording.filename.split(".").pop() ?? "mp3"}
</Badge>
</div>
<div className="mono text-xs text-[var(--color-ink-soft)]">
{(recording.size_bytes / 1024).toFixed(1)} KB
</div>
</div>
<div className="flex items-center gap-1">
{recording.download_url && onSelect && (
<Button size="sm" variant="ghost" onClick={() => onSelect(recording)}>
<Play className="size-4" />
</Button>
)}
{recording.download_url && (
<a
href={recording.download_url}
download={recording.filename}
className="flex size-8 items-center justify-center rounded-[var(--radius-r-control)] text-[var(--color-ink-soft)] hover:bg-[var(--color-surface-2)]"
aria-label="Download"
>
<Download className="size-4" />
</a>
)}
{onDelete && (
<Button
size="sm"
variant="danger"
disabled={deleting}
onClick={() => onDelete(recording)}
aria-label="Delete"
>
<Delete className="size-4" />
</Button>
)}
</div>
</div>
);
}
@@ -1,8 +1,5 @@
"use client";
import type { LucideIcon } from "lucide-react";
import { Inbox } from "lucide-react";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
interface EmptyStateProps {
@@ -19,16 +16,15 @@ export function EmptyState({
className,
}: EmptyStateProps) {
return (
<Card
<div
className={cn(
"flex flex-col items-center gap-2 py-12",
"surface flex flex-col items-center gap-2 py-12 text-center",
className,
"[--card-spacing:0px]",
)}
>
<Icon className="size-8 text-text-secondary/20" />
<p className="text-sm text-text-secondary/60">{title}</p>
<p className="text-xs text-text-secondary/40">{description}</p>
</Card>
<Icon className="size-8 text-[var(--color-ink-soft)]" />
<p className="text-sm font-medium text-[var(--color-ink)]">{title}</p>
<p className="text-xs text-[var(--color-ink-soft)]">{description}</p>
</div>
);
}
Loaded 50 of 130 files, more files were not shown because too many files have changed in this diff. Show more