refactor(fe): replace TanStack Query with SWR + UI/data cleanup
Build & Deploy (Nix) / build-and-deploy (backend) (push) Successful in 2m56s
Build & Deploy (Nix) / build-and-deploy (discord-gateway) (push) Successful in 3m42s
Build & Deploy (Nix) / build-and-deploy (proxy) (push) Successful in 3m59s

Rombak data layer frontend:
- Hapus @tanstack/react-query (package.json, lockfile, provider di
  dashboard layout) — ganti SWR 2.4.2 + SWRConfig (revalidateOnFocus
  false, deduping 10s, no retry on 404)
- Semua hooks data ditulis ulang ke useSWR; useAction() helper baru
  pengganti useMutation dengan surface kompatibel (mutate/mutateAsync/
  isPending/error)
- useMessages + useMessagesHasMore share satu SWR key — probe cursor
  yang tadinya dobel fetch API sekarang deduped
- WS sync (messages/media/recordings) pindah dari queryClient ke
  SWR mutate dengan filter key + revalidate:false
- useMessageSearch() dipakai search-panel & search-overlay; search
  overlay backdrop div -> button (fix a11y lint)

Rapikan UI + isi data:
- Tab stats recordings: placeholder 'coming soon' diganti stat asli
  (total, ukuran, speaker unik, top speakers)
- Empty states konsisten via EmptyState (images/review/recordings),
  EmptyState terima className
- biome check --write: 0 error, 8 warning pre-existing
- Verifikasi: tsc --noEmit PASS, next build PASS (11 halaman static),
  API live dicek — semua endpoint dashboard/messages/guilds/config/
  voice/media/recordings/review balikin data
This commit is contained in:
asepharyana
2026-08-01 09:19:39 +07:00
parent 1f91f99de3
commit 01c18b2060
26 changed files with 5145 additions and 329 deletions
+1 -1
View File
@@ -12,7 +12,6 @@
"dependencies": { "dependencies": {
"@base-ui/react": "^1.6.0", "@base-ui/react": "^1.6.0",
"@shadcn/react": "^0.2.1", "@shadcn/react": "^0.2.1",
"@tanstack/react-query": "^5.101.4",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
@@ -29,6 +28,7 @@
"recharts": "3.8.0", "recharts": "3.8.0",
"shadcn": "^4.15.0", "shadcn": "^4.15.0",
"sonner": "^2.0.7", "sonner": "^2.0.7",
"swr": "^2.4.2",
"tailwind-merge": "^3.6.0", "tailwind-merge": "^3.6.0",
"tw-animate-css": "^1.4.0" "tw-animate-css": "^1.4.0"
}, },
+4536
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
allowBuilds:
sharp: set this to true or false
# pnpm 11 requires build-script approvals here (the legacy `pnpm` field in
# package.json is ignored). Only packages that genuinely need a postinstall
# build are listed; everything else installs with scripts skipped.
onlyBuiltDependencies:
- sharp
@@ -24,7 +24,7 @@ type DashboardTab = "stats" | "live" | "users" | "channels";
export default function DashboardPage() { export default function DashboardPage() {
const [tab, setTab] = useState<DashboardTab>("stats"); const [tab, setTab] = useState<DashboardTab>("stats");
const { data: stats, isLoading, error, refetch } = useStats(); const { data: stats, isLoading, error, mutate: refetch } = useStats();
const { data: review = [] } = useReview(); const { data: review = [] } = useReview();
const modQueueItems: ModQueueItem[] = review.slice(0, 10).map((msg) => ({ const modQueueItems: ModQueueItem[] = review.slice(0, 10).map((msg) => ({
@@ -1,25 +1,18 @@
"use client"; "use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Suspense, useEffect, useState } from "react"; import { Suspense, useEffect, useState } from "react";
import { TopNav } from "@/components/layout/top-nav"; import { SWRConfig } from "swr";
import { MobileNav } from "@/components/layout/mobile-nav";
import { WsProvider, useWebSocket } from "@/lib/ws/context";
import { ChatbotProvider, useChatbot } from "@/components/chatbot/chatbot-context";
import { ChatbotContainer } from "@/components/chatbot/chatbot-container"; import { ChatbotContainer } from "@/components/chatbot/chatbot-container";
import {
ChatbotProvider,
useChatbot,
} from "@/components/chatbot/chatbot-context";
import { HiddenSidebar } from "@/components/layout/hidden-sidebar";
import { MobileNav } from "@/components/layout/mobile-nav";
import { TopNav } from "@/components/layout/top-nav";
import { MiniPlayer } from "@/components/media/mini-player"; import { MiniPlayer } from "@/components/media/mini-player";
import { MediaPlayerProvider } from "@/lib/hooks/use-media-player"; import { MediaPlayerProvider } from "@/lib/hooks/use-media-player";
import { HiddenSidebar } from "@/components/layout/hidden-sidebar"; import { useWebSocket, WsProvider } from "@/lib/ws/context";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 10_000,
retry: 1,
refetchOnWindowFocus: false,
},
},
});
function ChatbotExpressionSync() { function ChatbotExpressionSync() {
const ws = useWebSocket(); const ws = useWebSocket();
@@ -54,14 +47,24 @@ export default function DashboardLayout({
const [guildId, setGuildId] = useState(""); const [guildId, setGuildId] = useState("");
return ( return (
<QueryClientProvider client={queryClient}> <SWRConfig
value={{
revalidateOnFocus: false,
dedupingInterval: 10_000,
shouldRetryOnError: (err) =>
(err as { statusCode?: number })?.statusCode !== 404,
}}
>
<WsProvider> <WsProvider>
<MediaPlayerProvider> <MediaPlayerProvider>
<ChatbotProvider> <ChatbotProvider>
<ChatbotExpressionSync /> <ChatbotExpressionSync />
<div className="min-h-screen bg-canvas"> <div className="min-h-screen bg-canvas">
<TopNav /> <TopNav />
<HiddenSidebar guildId={guildId} onGuildChange={(g) => setGuildId(g ?? "")} /> <HiddenSidebar
guildId={guildId}
onGuildChange={(g) => setGuildId(g ?? "")}
/>
{/* Sub-nav space — filled per-page */} {/* Sub-nav space — filled per-page */}
<div className="pt-11"> <div className="pt-11">
@@ -85,6 +88,6 @@ export default function DashboardLayout({
</ChatbotProvider> </ChatbotProvider>
</MediaPlayerProvider> </MediaPlayerProvider>
</WsProvider> </WsProvider>
</QueryClientProvider> </SWRConfig>
); );
} }
@@ -1,17 +1,17 @@
"use client"; "use client";
import { useCallback, useEffect, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Flag, Image, Loader2, RefreshCw, Search } from "lucide-react"; import { Flag, Image, Loader2, RefreshCw, Search } from "lucide-react";
import { MessageList } from "@/components/messages/message-list"; import { useRouter, useSearchParams } from "next/navigation";
import { MessageDetailView } from "@/components/messages/message-detail-view"; import { useCallback, useEffect, useState } from "react";
import { SearchOverlay } from "@/components/messages/search-overlay";
import { extractFirstImage } from "@/components/messages/message-card";
import { renderMessageContent } from "@/lib/format";
import { SubNav } from "@/components/layout/sub-nav";
import { ErrorState, LoadingSkeleton } from "@/components/shared";
import { GlassCard } from "@/components/glass/card"; import { GlassCard } from "@/components/glass/card";
import { GlassPanel } from "@/components/glass/panel"; import { GlassPanel } from "@/components/glass/panel";
import { SubNav } from "@/components/layout/sub-nav";
import { extractFirstImage } from "@/components/messages/message-card";
import { MessageDetailView } from "@/components/messages/message-detail-view";
import { MessageList } from "@/components/messages/message-list";
import { SearchOverlay } from "@/components/messages/search-overlay";
import { EmptyState, ErrorState, LoadingSkeleton } from "@/components/shared";
import { GuildSelector } from "@/components/shared/guild-selector";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Select, Select,
@@ -32,10 +32,10 @@ import {
useReview, useReview,
useTextChannels, useTextChannels,
} from "@/hooks"; } from "@/hooks";
import { renderMessageContent } from "@/lib/format";
import type { MessageRecord } from "@/lib/types"; import type { MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context"; import { useWebSocket } from "@/lib/ws/context";
import { GuildSelector } from "@/components/shared/guild-selector";
type MessagesTab = "all" | "images" | "review"; type MessagesTab = "all" | "images" | "review";
@@ -185,10 +185,7 @@ export default function MessagesPage() {
<div className="flex gap-4"> <div className="flex gap-4">
{/* Left pane */} {/* Left pane */}
<div <div
className={cn( className={cn("space-y-2", detailId ? "w-1/2 lg:w-2/5" : "w-full")}
"space-y-2",
detailId ? "w-1/2 lg:w-2/5" : "w-full",
)}
> >
{tab === "all" && ( {tab === "all" && (
<MessageList <MessageList
@@ -205,10 +202,7 @@ export default function MessagesPage() {
<ImageGrid items={images ?? []} onSelect={setDetailId} /> <ImageGrid items={images ?? []} onSelect={setDetailId} />
)} )}
{tab === "review" && ( {tab === "review" && (
<ReviewList <ReviewList items={reviews ?? []} onSelect={setDetailId} />
items={reviews ?? []}
onSelect={setDetailId}
/>
)} )}
</div> </div>
@@ -216,7 +210,10 @@ export default function MessagesPage() {
{detailId && ( {detailId && (
<div className="sticky top-16 hidden w-1/2 self-start md:block lg:w-3/5"> <div className="sticky top-16 hidden w-1/2 self-start md:block lg:w-3/5">
{detailLoading ? ( {detailLoading ? (
<GlassPanel dense className="flex items-center justify-center py-12"> <GlassPanel
dense
className="flex items-center justify-center py-12"
>
<Loader2 className="size-5 animate-spin text-text-secondary/60" /> <Loader2 className="size-5 animate-spin text-text-secondary/60" />
</GlassPanel> </GlassPanel>
) : detailMessage ? ( ) : detailMessage ? (
@@ -288,9 +285,12 @@ function ImageGrid({
); );
})} })}
{items.length === 0 && ( {items.length === 0 && (
<div className="col-span-3 py-12 text-center text-xs text-text-secondary/40"> <EmptyState
No images icon={Image}
</div> title="No images"
description="Messages with image attachments will show up here."
className="col-span-3"
/>
)} )}
</div> </div>
); );
@@ -325,9 +325,11 @@ function ReviewList({
</GlassCard> </GlassCard>
))} ))}
{items.length === 0 && ( {items.length === 0 && (
<div className="py-12 text-center text-xs text-text-secondary/40"> <EmptyState
No flagged messages icon={Flag}
</div> title="No flagged messages"
description="Messages flagged by AI moderation will appear here for review."
/>
)} )}
</div> </div>
); );
@@ -1,18 +1,26 @@
"use client"; "use client";
import { useState } from "react"; import { Clock, Database, Mic, Users } from "lucide-react";
import { useMemo, useState } from "react";
import { StatCard } from "@/components/dashboard/stat-card";
import { SubNav } from "@/components/layout/sub-nav"; import { SubNav } from "@/components/layout/sub-nav";
import { RecordingCard } from "@/components/recordings/recording-card"; import { RecordingCard } from "@/components/recordings/recording-card";
import { RecordingPlayer } from "@/components/recordings/recording-player"; import { RecordingPlayer } from "@/components/recordings/recording-player";
import { ErrorState, LoadingSkeleton } from "@/components/shared"; import { EmptyState, ErrorState, LoadingSkeleton } from "@/components/shared";
import { useRecordings, useRecordingsWsSync } from "@/hooks"; import { useRecordings, useRecordingsWsSync } from "@/hooks";
import { formatBytes } from "@/lib/format";
import type { VoiceRecording } from "@/lib/types"; import type { VoiceRecording } from "@/lib/types";
import { useWebSocket } from "@/lib/ws/context"; import { useWebSocket } from "@/lib/ws/context";
type RecordingsTab = "library" | "stats"; type RecordingsTab = "library" | "stats";
export default function RecordingsPage() { export default function RecordingsPage() {
const { data: recordings, isLoading, error, refetch } = useRecordings(); const {
data: recordings,
isLoading,
error,
mutate: refetch,
} = useRecordings();
const [playingId, setPlayingId] = useState<string | null>(null); const [playingId, setPlayingId] = useState<string | null>(null);
const [tab, setTab] = useState<RecordingsTab>("library"); const [tab, setTab] = useState<RecordingsTab>("library");
const ws = useWebSocket(); const ws = useWebSocket();
@@ -25,6 +33,31 @@ export default function RecordingsPage() {
? recordings.find((r: VoiceRecording) => r.id === playingId) ? recordings.find((r: VoiceRecording) => r.id === playingId)
: null; : null;
const stats = useMemo(() => {
const list = recordings ?? [];
const totalSize = list.reduce((sum, r) => sum + (r.size_bytes ?? 0), 0);
const byUser = new Map<
string,
{ name: string; count: number; size: number }
>();
for (const rec of list) {
const key = rec.user_id ?? rec.username;
const cur = byUser.get(key) ?? { name: rec.username, count: 0, size: 0 };
cur.count += 1;
cur.size += rec.size_bytes ?? 0;
byUser.set(key, cur);
}
const topUsers = [...byUser.values()]
.sort((a, b) => b.count - a.count)
.slice(0, 8);
return {
total: list.length,
totalSize,
uniqueUsers: byUser.size,
topUsers,
};
}, [recordings]);
return ( return (
<div className="space-y-4 animate-fade-in-up"> <div className="space-y-4 animate-fade-in-up">
<SubNav <SubNav
@@ -51,18 +84,72 @@ export default function RecordingsPage() {
/> />
))} ))}
{(recordings ?? []).length === 0 && ( {(recordings ?? []).length === 0 && (
<div className="py-12 text-center text-sm text-text-secondary/40"> <EmptyState
No recordings yet icon={Mic}
</div> title="No recordings yet"
description="Voice recordings will appear here once members speak in a monitored voice channel."
/>
)} )}
</div> </div>
))} ))}
{tab === "stats" && ( {tab === "stats" &&
<div className="py-12 text-center text-sm text-text-secondary/40"> (isLoading ? (
Recording stats coming soon <LoadingSkeleton count={4} height="h-28" columns={3} />
</div> ) : stats.total === 0 ? (
)} <EmptyState
icon={Clock}
title="No recording stats yet"
description="Recordings are captured from monitored voice channels."
/>
) : (
<div className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<StatCard
label="Total Recordings"
value={stats.total}
icon={Mic}
/>
<StatCard
label="Total Size"
value={stats.totalSize}
icon={Database}
formatter={(v) => formatBytes(v)}
/>
<StatCard
label="Unique Speakers"
value={stats.uniqueUsers}
icon={Users}
/>
</div>
{stats.topUsers.length > 0 && (
<div className="space-y-1.5">
<p className="text-xs text-text-secondary font-medium uppercase tracking-wide">
Top Speakers
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{stats.topUsers.map((u) => (
<div
key={u.name}
className="flex items-center gap-3 rounded-lg border border-border/40 bg-card/40 px-3 py-2"
>
<span className="flex size-7 items-center justify-center rounded-md bg-primary/10 font-mono text-xs text-primary">
{u.count}
</span>
<span className="flex-1 min-w-0 truncate text-sm text-text-primary">
{u.name}
</span>
<span className="text-[10px] font-mono text-text-secondary/50">
{formatBytes(u.size)}
</span>
</div>
))}
</div>
</div>
)}
</div>
))}
<RecordingPlayer <RecordingPlayer
url={currentTrack?.download_url ?? undefined} url={currentTrack?.download_url ?? undefined}
@@ -7,8 +7,8 @@ import { GlassDivider } from "@/components/glass/divider";
import { SubNav } from "@/components/layout/sub-nav"; import { SubNav } from "@/components/layout/sub-nav";
import { LoadingSkeleton } from "@/components/shared"; import { LoadingSkeleton } from "@/components/shared";
import { useConfig } from "@/hooks"; import { useConfig } from "@/hooks";
import { useWebSocket } from "@/lib/ws/context";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
type SettingsTab = "connection" | "appearance" | "config" | "about"; type SettingsTab = "connection" | "appearance" | "config" | "about";
@@ -32,7 +32,8 @@ export default function SettingsPage() {
}; };
const statusDot = { const statusDot = {
connected: "bg-emerald-500 shadow-[0_0_8px] shadow-emerald-500/60 animate-pulse", connected:
"bg-emerald-500 shadow-[0_0_8px] shadow-emerald-500/60 animate-pulse",
connecting: "bg-accent-amber animate-pulse", connecting: "bg-accent-amber animate-pulse",
disconnected: "bg-destructive", disconnected: "bg-destructive",
error: "bg-destructive", error: "bg-destructive",
@@ -49,9 +50,21 @@ export default function SettingsPage() {
<div className="space-y-4 animate-fade-in-up max-w-2xl"> <div className="space-y-4 animate-fade-in-up max-w-2xl">
<SubNav <SubNav
tabs={[ tabs={[
{ id: "connection", label: "Connection", icon: <Wifi className="size-3" /> }, {
{ id: "appearance", label: "Appearance", icon: <Sun className="size-3" /> }, id: "connection",
{ id: "config", label: "Config", icon: <Server className="size-3" /> }, label: "Connection",
icon: <Wifi className="size-3" />,
},
{
id: "appearance",
label: "Appearance",
icon: <Sun className="size-3" />,
},
{
id: "config",
label: "Config",
icon: <Server className="size-3" />,
},
{ id: "about", label: "About", icon: <Shield className="size-3" /> }, { id: "about", label: "About", icon: <Shield className="size-3" /> },
]} ]}
activeTab={tab} activeTab={tab}
@@ -62,11 +75,15 @@ export default function SettingsPage() {
<GlassCard variant="base"> <GlassCard variant="base">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<span className="text-sm font-semibold text-text-primary">WebSocket</span> <span className="text-sm font-semibold text-text-primary">
WebSocket
</span>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className={cn("size-2 rounded-full", statusDot)} /> <span className={cn("size-2 rounded-full", statusDot)} />
<span className="text-xs font-mono text-text-secondary">{statusLabel}</span> <span className="text-xs font-mono text-text-secondary">
{statusLabel}
</span>
</div> </div>
</div> </div>
</GlassCard> </GlassCard>
@@ -76,8 +93,14 @@ export default function SettingsPage() {
<GlassCard variant="base"> <GlassCard variant="base">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{theme === "dark" ? <Moon className="size-4 text-primary" /> : <Sun className="size-4 text-primary" />} {theme === "dark" ? (
<span className="text-sm font-semibold text-text-primary">Theme</span> <Moon className="size-4 text-primary" />
) : (
<Sun className="size-4 text-primary" />
)}
<span className="text-sm font-semibold text-text-primary">
Theme
</span>
</div> </div>
<button <button
type="button" type="button"
@@ -97,18 +120,37 @@ export default function SettingsPage() {
<LoadingSkeleton count={6} height="h-6" /> <LoadingSkeleton count={6} height="h-6" />
) : config ? ( ) : config ? (
<> <>
<ConfigRow label="Monitor Guild" value={config.monitorGuildId || "Not configured"} /> <ConfigRow
label="Monitor Guild"
value={config.monitorGuildId || "Not configured"}
/>
<GlassDivider /> <GlassDivider />
<ConfigRow label="Voice Guild" value={config.voiceGuildId || "Not configured"} /> <ConfigRow
label="Voice Guild"
value={config.voiceGuildId || "Not configured"}
/>
<GlassDivider /> <GlassDivider />
<ConfigRow label="Voice Channel" value={config.voiceChannelId || "Not configured"} /> <ConfigRow
label="Voice Channel"
value={config.voiceChannelId || "Not configured"}
/>
<GlassDivider /> <GlassDivider />
<ConfigRow label="AI Analysis" value={config.aiAnalysisEnabled ? "Enabled" : "Disabled"} /> <ConfigRow
label="AI Analysis"
value={config.aiAnalysisEnabled ? "Enabled" : "Disabled"}
/>
<GlassDivider /> <GlassDivider />
<ConfigRow label="Auto-Delete Flagged" value={config.autoDeleteFlaggedEnabled ? "Enabled" : "Disabled"} /> <ConfigRow
label="Auto-Delete Flagged"
value={
config.autoDeleteFlaggedEnabled ? "Enabled" : "Disabled"
}
/>
</> </>
) : ( ) : (
<p className="text-xs text-text-secondary/60">Unable to load config.</p> <p className="text-xs text-text-secondary/60">
Unable to load config.
</p>
)} )}
</div> </div>
</GlassCard> </GlassCard>
@@ -117,9 +159,12 @@ export default function SettingsPage() {
{tab === "about" && ( {tab === "about" && (
<GlassCard variant="base"> <GlassCard variant="base">
<div className="space-y-2"> <div className="space-y-2">
<h2 className="text-base font-bold text-primary">Discord Automod</h2> <h2 className="text-base font-bold text-primary">
Discord Automod
</h2>
<p className="text-xs text-text-secondary/80 leading-relaxed"> <p className="text-xs text-text-secondary/80 leading-relaxed">
AI-powered message moderation, voice recording, and real-time monitoring for Discord communities. AI-powered message moderation, voice recording, and real-time
monitoring for Discord communities.
</p> </p>
<div className="text-[10px] font-mono text-text-secondary/40 mt-4"> <div className="text-[10px] font-mono text-text-secondary/40 mt-4">
v0.1.0 v0.1.0
@@ -135,7 +180,9 @@ function ConfigRow({ label, value }: { label: string; value: string }) {
return ( return (
<div className="flex items-center justify-between py-0.5"> <div className="flex items-center justify-between py-0.5">
<span className="text-xs text-text-secondary">{label}</span> <span className="text-xs text-text-secondary">{label}</span>
<span className="text-[11px] font-mono text-text-primary/80 max-w-[240px] truncate text-right">{value}</span> <span className="text-[11px] font-mono text-text-primary/80 max-w-[240px] truncate text-right">
{value}
</span>
</div> </div>
); );
} }
@@ -1,12 +1,11 @@
"use client"; "use client";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { VoiceConnectionCard } from "@/components/voice/connection-card";
import { SpeakerWaveform } from "@/components/voice/speaker-waveform";
import { MicControl } from "@/components/voice/mic-control";
import { VoiceActivityTimeline } from "@/components/voice/activity-timeline";
import { SubNav } from "@/components/layout/sub-nav"; import { SubNav } from "@/components/layout/sub-nav";
import { useWebSocket } from "@/lib/ws/context"; import { VoiceActivityTimeline } from "@/components/voice/activity-timeline";
import { VoiceConnectionCard } from "@/components/voice/connection-card";
import { MicControl } from "@/components/voice/mic-control";
import { SpeakerWaveform } from "@/components/voice/speaker-waveform";
import { import {
useGuilds, useGuilds,
useMicTransmit, useMicTransmit,
@@ -16,6 +15,7 @@ import {
useVoiceDisconnect, useVoiceDisconnect,
useVoiceStatus, useVoiceStatus,
} from "@/hooks"; } from "@/hooks";
import { useWebSocket } from "@/lib/ws/context";
type VoiceTab = "connection" | "activity"; type VoiceTab = "connection" | "activity";
@@ -83,7 +83,12 @@ export default function VoicePage() {
selectedChannel={selectedChannel} selectedChannel={selectedChannel}
onGuildChange={handleGuildChange} onGuildChange={handleGuildChange}
onChannelChange={(v) => setSelectedChannel(v ?? "")} onChannelChange={(v) => setSelectedChannel(v ?? "")}
onConnect={() => connectMut.mutate({ guildId: selectedGuild, channelId: selectedChannel })} onConnect={() =>
connectMut.mutate({
guildId: selectedGuild,
channelId: selectedChannel,
})
}
onDisconnect={() => disconnectMut.mutate(undefined)} onDisconnect={() => disconnectMut.mutate(undefined)}
connecting={connectMut.isPending} connecting={connectMut.isPending}
/> />
@@ -1,6 +1,5 @@
"use client"; "use client";
import { useQuery } from "@tanstack/react-query";
import { Loader2, RefreshCw, Search, Sparkles } from "lucide-react"; import { Loader2, RefreshCw, Search, Sparkles } from "lucide-react";
import { useCallback, useState } from "react"; import { useCallback, useState } from "react";
@@ -11,8 +10,7 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress"; import { Progress } from "@/components/ui/progress";
import { useReanalyze } from "@/hooks"; import { useMessageSearch, useReanalyze } from "@/hooks";
import { messagesApi } from "@/lib/api";
import { renderMessageContent, safeParseJsonArray } from "@/lib/format"; import { renderMessageContent, safeParseJsonArray } from "@/lib/format";
import type { MessageRecord } from "@/lib/types"; import type { MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -22,14 +20,10 @@ export function SearchPanel() {
const [enabled, setEnabled] = useState(false); const [enabled, setEnabled] = useState(false);
const reanalyzeMut = useReanalyze(); const reanalyzeMut = useReanalyze();
const { data: results, isFetching } = useQuery<MessageRecord[]>({ const { data: results, isValidating: isFetching } = useMessageSearch(
queryKey: ["analysis-search", query], query,
queryFn: async () => {
const result = await messagesApi.search(query, 50);
return result.results;
},
enabled, enabled,
}); );
const handleSearch = useCallback(() => { const handleSearch = useCallback(() => {
if (!query.trim()) return; if (!query.trim()) return;
@@ -100,7 +94,9 @@ export function SearchPanel() {
</Badge> </Badge>
)} )}
</div> </div>
<p className="text-sm leading-relaxed">{renderMessageContent(msg.content, msg.metadata)}</p> <p className="text-sm leading-relaxed">
{renderMessageContent(msg.content, msg.metadata)}
</p>
{msg.ai_moderation_flags && {msg.ai_moderation_flags &&
msg.ai_moderation_flags !== "[]" && ( msg.ai_moderation_flags !== "[]" && (
<div className="flex flex-wrap gap-1"> <div className="flex flex-wrap gap-1">
@@ -20,7 +20,7 @@ export function ChannelsSection({ guildId }: { guildId?: string }) {
data: channels = [], data: channels = [],
isLoading, isLoading,
error, error,
refetch, mutate: refetch,
} = useChannels(guildId ?? "", search); } = useChannels(guildId ?? "", search);
const { data: detail } = useChannelDetail(selectedId); const { data: detail } = useChannelDetail(selectedId);
@@ -124,7 +124,9 @@ export function ChannelsSection({ guildId }: { guildId?: string }) {
className="rounded-lg border border-border/40 bg-card/40 px-3 py-2" 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"> <p className="text-xs leading-relaxed text-text-secondary line-clamp-2">
{msg.username}: {renderMessageContent(msg.content, msg.metadata) || "(no text content)"} {msg.username}:{" "}
{renderMessageContent(msg.content, msg.metadata) ||
"(no text content)"}
</p> </p>
<p className="mt-1 text-[10px] font-mono text-text-secondary/40"> <p className="mt-1 text-[10px] font-mono text-text-secondary/40">
{new Date(msg.created_at).toLocaleString()} {new Date(msg.created_at).toLocaleString()}
@@ -1,9 +1,9 @@
"use client"; "use client";
import { type LucideIcon } from "lucide-react"; import type { LucideIcon } from "lucide-react";
import { Area, AreaChart, ResponsiveContainer } from "recharts";
import { GlassCard } from "@/components/glass/card"; import { GlassCard } from "@/components/glass/card";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Area, AreaChart, ResponsiveContainer } from "recharts";
interface StatCardProps { interface StatCardProps {
label: string; label: string;
@@ -43,7 +43,10 @@ export function StatCard({
<Icon className="size-4" /> <Icon className="size-4" />
</div> </div>
</div> </div>
<div className="text-2xl font-mono font-semibold tracking-tight" style={{ color: accentColor }}> <div
className="text-2xl font-mono font-semibold tracking-tight"
style={{ color: accentColor }}
>
{formatter(numValue)} {formatter(numValue)}
</div> </div>
<div className="text-[11px] text-text-secondary font-medium mt-0.5 tracking-wide uppercase"> <div className="text-[11px] text-text-secondary font-medium mt-0.5 tracking-wide uppercase">
@@ -56,7 +59,13 @@ export function StatCard({
<ResponsiveContainer width="100%" height="100%"> <ResponsiveContainer width="100%" height="100%">
<AreaChart data={sparklineData}> <AreaChart data={sparklineData}>
<defs> <defs>
<linearGradient id={`spark-grad-${label}`} x1="0" y1="0" x2="0" y2="1"> <linearGradient
id={`spark-grad-${label}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop offset="0%" stopColor={accentColor} stopOpacity={0.5} /> <stop offset="0%" stopColor={accentColor} stopOpacity={0.5} />
<stop offset="100%" stopColor={accentColor} stopOpacity={0} /> <stop offset="100%" stopColor={accentColor} stopOpacity={0} />
</linearGradient> </linearGradient>
@@ -1,7 +1,14 @@
"use client"; "use client";
import {
Bar,
BarChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { GlassCard } from "@/components/glass/card"; import { GlassCard } from "@/components/glass/card";
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
interface TopChannelsChartProps { interface TopChannelsChartProps {
data?: { name: string; count: number }[]; data?: { name: string; count: number }[];
@@ -11,13 +18,27 @@ export function TopChannelsChart({ data = [] }: TopChannelsChartProps) {
return ( return (
<GlassCard variant="base"> <GlassCard variant="base">
<div className="flex items-center gap-2 mb-3"> <div className="flex items-center gap-2 mb-3">
<span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">Top Channels</span> <span className="text-xs font-semibold tracking-wide uppercase text-text-secondary">
Top Channels
</span>
</div> </div>
<div className="h-48"> <div className="h-48">
<ResponsiveContainer width="100%" height="100%"> <ResponsiveContainer width="100%" height="100%">
<BarChart data={data} layout="vertical"> <BarChart data={data} layout="vertical">
<XAxis type="number" axisLine={false} tickLine={false} tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }} /> <XAxis
<YAxis type="category" dataKey="name" axisLine={false} tickLine={false} tick={{ fill: "oklch(0.55 0.02 245)", fontSize: 10 }} width={80} /> 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 <Tooltip
contentStyle={{ contentStyle={{
background: "oklch(0.11 0.02 245 / 0.9)", background: "oklch(0.11 0.02 245 / 0.9)",
@@ -27,7 +48,11 @@ export function TopChannelsChart({ data = [] }: TopChannelsChartProps) {
color: "oklch(0.93 0.01 245)", color: "oklch(0.93 0.01 245)",
}} }}
/> />
<Bar dataKey="count" fill="var(--color-primary)" radius={[0, 4, 4, 0]} /> <Bar
dataKey="count"
fill="var(--color-primary)"
radius={[0, 4, 4, 0]}
/>
</BarChart> </BarChart>
</ResponsiveContainer> </ResponsiveContainer>
</div> </div>
@@ -17,7 +17,12 @@ export function UsersSection() {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [selectedId, setSelectedId] = useState<string | null>(null); const [selectedId, setSelectedId] = useState<string | null>(null);
const { data: users = [], isLoading, error, refetch } = useUsers(search); const {
data: users = [],
isLoading,
error,
mutate: refetch,
} = useUsers(search);
const { data: detail } = useUserDetail(selectedId); const { data: detail } = useUserDetail(selectedId);
const handleSearch = useCallback((v: string) => { const handleSearch = useCallback((v: string) => {
@@ -135,7 +140,8 @@ export function UsersSection() {
className="rounded-lg border border-border/40 bg-card/40 px-3 py-2" 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"> <p className="text-xs leading-relaxed text-text-secondary line-clamp-2">
{renderMessageContent(msg.content, msg.metadata) || "(no text content)"} {renderMessageContent(msg.content, msg.metadata) ||
"(no text content)"}
</p> </p>
<p className="mt-1 text-[10px] font-mono text-text-secondary/40"> <p className="mt-1 text-[10px] font-mono text-text-secondary/40">
{msg.channel_id?.slice(0, 8)} ·{" "} {msg.channel_id?.slice(0, 8)} ·{" "}
@@ -2,8 +2,7 @@
import { Search, X } from "lucide-react"; import { Search, X } from "lucide-react";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query"; import { useMessageSearch } from "@/hooks";
import { messagesApi } from "@/lib/api";
import { getMessageChannelLabel, renderMessageContent } from "@/lib/format"; import { getMessageChannelLabel, renderMessageContent } from "@/lib/format";
import type { MessageRecord } from "@/lib/types"; import type { MessageRecord } from "@/lib/types";
@@ -17,14 +16,7 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const { data: results } = useQuery<MessageRecord[]>({ const { data: results } = useMessageSearch(query, true);
queryKey: ["messages-search", query],
queryFn: async () => {
const res = await messagesApi.search(query, 20);
return res.results;
},
enabled: query.length >= 2,
});
useEffect(() => { useEffect(() => {
if (open) { if (open) {
@@ -50,7 +42,12 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
return ( return (
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]"> <div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]">
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} /> <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"> <div className="relative w-full max-w-lg glass-intense rounded-[var(--radius-card)] overflow-hidden shadow-2xl">
{/* Input */} {/* Input */}
<div className="flex items-center gap-3 px-4 py-3 border-b border-glass-border"> <div className="flex items-center gap-3 px-4 py-3 border-b border-glass-border">
@@ -63,7 +60,11 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
placeholder="Search messages..." placeholder="Search messages..."
className="flex-1 bg-transparent text-sm text-text-primary placeholder-text-secondary/40 outline-none" className="flex-1 bg-transparent text-sm text-text-primary placeholder-text-secondary/40 outline-none"
/> />
<button type="button" onClick={onClose} className="size-6 flex items-center justify-center rounded hover:bg-glass-bg"> <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" /> <X className="size-3.5 text-text-secondary/60" />
</button> </button>
</div> </div>
@@ -72,21 +73,32 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
<div className="max-h-80 overflow-y-auto p-2 space-y-1"> <div className="max-h-80 overflow-y-auto p-2 space-y-1">
{!results || results.length === 0 ? ( {!results || results.length === 0 ? (
<div className="py-8 text-center text-xs text-text-secondary/40"> <div className="py-8 text-center text-xs text-text-secondary/40">
{query.length < 2 ? "Type at least 2 characters" : "No results found"} {query.length < 2
? "Type at least 2 characters"
: "No results found"}
</div> </div>
) : ( ) : (
results.map((msg) => ( results.map((msg) => (
<button <button
key={msg.id} key={msg.id}
type="button" type="button"
onClick={() => { onSelect(msg.id); onClose(); }} onClick={() => {
onSelect(msg.id);
onClose();
}}
className="w-full text-left px-3 py-2 rounded-lg hover:bg-glass-bg transition-colors" 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"> <div className="flex items-center gap-2 text-xs">
<span className="font-medium text-text-primary">{msg.username}</span> <span className="font-medium text-text-primary">
<span className="text-text-secondary/40">{getMessageChannelLabel(msg)}</span> {msg.username}
</span>
<span className="text-text-secondary/40">
{getMessageChannelLabel(msg)}
</span>
</div> </div>
<p className="text-xs text-text-secondary/80 line-clamp-1 mt-0.5">{renderMessageContent(msg.content, msg.metadata)}</p> <p className="text-xs text-text-secondary/80 line-clamp-1 mt-0.5">
{renderMessageContent(msg.content, msg.metadata)}
</p>
</button> </button>
)) ))
)} )}
@@ -3,20 +3,26 @@
import type { LucideIcon } from "lucide-react"; import type { LucideIcon } from "lucide-react";
import { Inbox } from "lucide-react"; import { Inbox } from "lucide-react";
import { GlassPanel } from "@/components/glass/panel"; import { GlassPanel } from "@/components/glass/panel";
import { cn } from "@/lib/utils";
interface EmptyStateProps { interface EmptyStateProps {
icon?: LucideIcon; icon?: LucideIcon;
title?: string; title?: string;
description?: string; description?: string;
className?: string;
} }
export function EmptyState({ export function EmptyState({
icon: Icon = Inbox, icon: Icon = Inbox,
title = "No data yet", title = "No data yet",
description = "Nothing to display here yet.", description = "Nothing to display here yet.",
className,
}: EmptyStateProps) { }: EmptyStateProps) {
return ( return (
<GlassPanel dense className="flex flex-col items-center gap-2 py-12"> <GlassPanel
dense
className={cn("flex flex-col items-center gap-2 py-12", className)}
>
<Icon className="size-8 text-text-secondary/20" /> <Icon className="size-8 text-text-secondary/20" />
<p className="text-sm text-text-secondary/60">{title}</p> <p className="text-sm text-text-secondary/60">{title}</p>
<p className="text-xs text-text-secondary/40">{description}</p> <p className="text-xs text-text-secondary/40">{description}</p>
@@ -33,7 +33,7 @@ export function GuildSelector({
onChange, onChange,
autoHide = true, autoHide = true,
}: GuildSelectorProps) { }: GuildSelectorProps) {
const { data: guilds = [], isLoading, error, refetch } = useGuilds(); const { data: guilds = [], isLoading, error, mutate: refetch } = useGuilds();
const { data: config } = useConfig(); const { data: config } = useConfig();
const initDone = useRef(false); const initDone = useRef(false);
+1
View File
@@ -19,6 +19,7 @@ export {
useImages, useImages,
useLoadMore, useLoadMore,
useMessageDetail, useMessageDetail,
useMessageSearch,
useMessages, useMessages,
useMessagesHasMore, useMessagesHasMore,
useMessagesWsSync, useMessagesWsSync,
+55
View File
@@ -0,0 +1,55 @@
import { useCallback, useRef, useState } from "react";
export interface UseActionState {
isPending: boolean;
error: Error | null;
}
/**
* A lightweight mutation hook with a TanStack-compatible surface
* ({ mutate, mutateAsync, isPending, error }) built on plain state —
* the SWR replacement for useMutation. Fire-and-forget via `mutate`,
* await the result via `mutateAsync`.
*
* `onSuccess` receives (data, args) and may perform SWR cache updates
* (e.g. `mutate(key, data, { revalidate: false })`).
*/
export function useAction<TArgs = void, TResult = unknown>(
fn: (args: TArgs) => Promise<TResult>,
options?: {
onSuccess?: (data: TResult, args: TArgs) => void | Promise<void>;
},
) {
const [state, setState] = useState<UseActionState>({
isPending: false,
error: null,
});
const fnRef = useRef(fn);
fnRef.current = fn;
const onSuccessRef = useRef(options?.onSuccess);
onSuccessRef.current = options?.onSuccess;
const run = useCallback(async (args?: TArgs): Promise<TResult> => {
setState({ isPending: true, error: null });
try {
const data = await fnRef.current(args as TArgs);
await onSuccessRef.current?.(data, args as TArgs);
setState({ isPending: false, error: null });
return data;
} catch (err) {
setState({ isPending: false, error: err as Error });
throw err;
}
}, []);
return {
mutate: (args?: TArgs) => {
void run(args);
},
mutateAsync: run,
isPending: state.isPending,
error: state.error,
reset: () => setState({ isPending: false, error: null }),
};
}
+3 -5
View File
@@ -1,4 +1,4 @@
import { useQuery } from "@tanstack/react-query"; import useSWR from "swr";
import { configApi } from "@/lib/api"; import { configApi } from "@/lib/api";
import type { AppConfig } from "@/lib/types"; import type { AppConfig } from "@/lib/types";
@@ -7,9 +7,7 @@ import type { AppConfig } from "@/lib/types";
* Fetch the app configuration from the backend. * Fetch the app configuration from the backend.
*/ */
export function useConfig() { export function useConfig() {
return useQuery<AppConfig>({ return useSWR<AppConfig>(["config"], () => configApi.get(), {
queryKey: ["config"], dedupingInterval: 120_000,
queryFn: () => configApi.get(),
staleTime: 120_000,
}); });
} }
+36 -25
View File
@@ -1,4 +1,4 @@
import { useQuery } from "@tanstack/react-query"; import useSWR from "swr";
import { dashboardApi } from "@/lib/api"; import { dashboardApi } from "@/lib/api";
import type { import type {
@@ -8,40 +8,51 @@ import type {
} from "@/lib/types"; } from "@/lib/types";
export function useStats() { export function useStats() {
return useQuery<DashboardStats>({ return useSWR<DashboardStats>(["dashboard-stats"], () =>
queryKey: ["dashboard-stats"], dashboardApi.getStats(),
queryFn: () => dashboardApi.getStats(), );
});
} }
export function useUsers(search?: string) { export function useUsers(search?: string) {
return useQuery({ return useSWR(
queryKey: ["dashboard-users", search ?? ""], ["dashboard-users", search ?? ""],
queryFn: () => dashboardApi.listUsers(20, undefined, search), async () => {
select: (data) => data.data, const res = await dashboardApi.listUsers(20, undefined, search);
}); return res.data;
},
{
keepPreviousData: true,
},
);
} }
export function useChannels(guildId?: string, search?: string) { export function useChannels(guildId?: string, search?: string) {
return useQuery({ return useSWR(
queryKey: ["dashboard-channels", guildId ?? "__all__", search ?? ""], ["dashboard-channels", guildId ?? "__all__", search ?? ""],
queryFn: () => dashboardApi.listChannels(20, search, guildId || undefined), async () => {
select: (data) => data.data, const res = await dashboardApi.listChannels(
}); 20,
search,
guildId || undefined,
);
return res.data;
},
{
keepPreviousData: true,
},
);
} }
export function useUserDetail(userId: string | null) { export function useUserDetail(userId: string | null) {
return useQuery<DashboardUserDetail>({ return useSWR<DashboardUserDetail>(
queryKey: ["dashboard-user", userId], userId ? ["dashboard-user", userId] : null,
queryFn: () => dashboardApi.getUserDetail(userId!), () => dashboardApi.getUserDetail(userId!),
enabled: !!userId, );
});
} }
export function useChannelDetail(channelId: string | null) { export function useChannelDetail(channelId: string | null) {
return useQuery<DashboardChannelDetail>({ return useSWR<DashboardChannelDetail>(
queryKey: ["dashboard-channel", channelId], channelId ? ["dashboard-channel", channelId] : null,
queryFn: () => dashboardApi.getChannelDetail(channelId!), () => dashboardApi.getChannelDetail(channelId!),
enabled: !!channelId, );
});
} }
+3 -5
View File
@@ -1,4 +1,4 @@
import { useQuery } from "@tanstack/react-query"; import useSWR from "swr";
import { voiceApi } from "@/lib/api"; import { voiceApi } from "@/lib/api";
import type { Guild } from "@/lib/types"; import type { Guild } from "@/lib/types";
@@ -7,9 +7,7 @@ import type { Guild } from "@/lib/types";
* Fetch the list of available Discord guilds. * Fetch the list of available Discord guilds.
*/ */
export function useGuilds() { export function useGuilds() {
return useQuery<Guild[]>({ return useSWR<Guild[]>(["guilds"], () => voiceApi.getGuilds(), {
queryKey: ["guilds"], dedupingInterval: 60_000,
queryFn: () => voiceApi.getGuilds(),
staleTime: 60_000,
}); });
} }
+23 -30
View File
@@ -1,58 +1,51 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react"; import { useEffect } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { mediaApi } from "@/lib/api"; import { mediaApi } from "@/lib/api";
import type { MediaState } from "@/lib/types"; import type { MediaState } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook"; import type { WsHook } from "@/lib/ws-hook";
const MEDIA_KEY = ["media-state"] as const;
export function useMediaState() { export function useMediaState() {
return useQuery<MediaState>({ return useSWR<MediaState>(MEDIA_KEY, () => mediaApi.getStatus(), {
queryKey: ["media-state"], refreshInterval: 10_000,
queryFn: () => mediaApi.getStatus(), shouldRetryOnError: false,
retry: false, });
refetchInterval: 10_000, }
function useMediaAction<TArgs>(fn: (args: TArgs) => Promise<MediaState>) {
const { mutate } = useSWRConfig();
return useAction(fn, {
onSuccess: (data) => {
void mutate(MEDIA_KEY, data, { revalidate: false });
},
}); });
} }
export function useMediaQueue() { export function useMediaQueue() {
const qc = useQueryClient(); return useMediaAction((url: string) => mediaApi.queue(url, "music"));
return useMutation({
mutationFn: (url: string) => mediaApi.queue(url, "music"),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
} }
export function useMediaSkip() { export function useMediaSkip() {
const qc = useQueryClient(); return useMediaAction(() => mediaApi.skip());
return useMutation({
mutationFn: () => mediaApi.skip(),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
} }
export function useMediaStop() { export function useMediaStop() {
const qc = useQueryClient(); return useMediaAction(() => mediaApi.stop());
return useMutation({
mutationFn: () => mediaApi.stop(),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
} }
export function useMediaVolume() { export function useMediaVolume() {
const qc = useQueryClient(); return useMediaAction((volume: number) => mediaApi.volume(volume));
return useMutation({
mutationFn: (volume: number) => mediaApi.volume(volume),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
} }
/** Subscribe to WS media_state events to keep cache fresh */ /** Subscribe to WS media_state events to keep cache fresh */
export function useMediaWsSync(ws: WsHook) { export function useMediaWsSync(ws: WsHook) {
const qc = useQueryClient(); const { mutate } = useSWRConfig();
useEffect(() => { useEffect(() => {
const unsub = ws.on("media_state", (data) => { const unsub = ws.on("media_state", (data) => {
qc.setQueryData(["media-state"], data as MediaState); void mutate(MEDIA_KEY, data as MediaState, { revalidate: false });
}); });
return unsub; return unsub;
}, [ws, qc]); }, [ws, mutate]);
} }
+110 -91
View File
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react"; import { useEffect } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { messagesApi, voiceApi } from "@/lib/api"; import { messagesApi, voiceApi } from "@/lib/api";
import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types"; import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook"; import type { WsHook } from "@/lib/ws-hook";
@@ -14,44 +14,48 @@ const msgKeys = {
review: (channelId?: string) => review: (channelId?: string) =>
["messages-review", channelId ?? "__all__"] as const, ["messages-review", channelId ?? "__all__"] as const,
detail: (id: string) => ["message-detail", id] as const, detail: (id: string) => ["message-detail", id] as const,
search: (query: string) => ["messages-search", query] as const,
}; };
type MessagePage = { data: MessageRecord[]; nextCursor: string | null };
/**
* Single source of truth for the paginated message list. Both useMessages and
* useMessagesHasMore derive from this one SWR key, so the cursor probe no
* longer triggers a duplicate API call.
*/
function useMessagesPage(guildId: string, channelId?: string) {
const key = guildId ? msgKeys.list(guildId, channelId) : null;
return useSWR<MessagePage>(key, () =>
messagesApi.list(guildId, 50, channelId || undefined),
);
}
// ── Messages list (paginated, cursor-based) ────── // ── Messages list (paginated, cursor-based) ──────
export function useMessages(guildId: string, channelId?: string) { export function useMessages(guildId: string, channelId?: string) {
return useQuery<MessageRecord[]>({ const page = useMessagesPage(guildId, channelId);
queryKey: msgKeys.list(guildId, channelId), return {
queryFn: async () => { ...page,
const result = await messagesApi.list( data: page.data?.data,
guildId, refetch: () => page.mutate(),
50, };
channelId || undefined,
);
return result.data;
},
enabled: !!guildId,
});
} }
export function useMessagesHasMore(guildId: string, channelId?: string) { export function useMessagesHasMore(guildId: string, channelId?: string) {
return useQuery({ const page = useMessagesPage(guildId, channelId);
queryKey: [...msgKeys.list(guildId, channelId), "cursor"], return {
queryFn: async () => { data: {
const result = await messagesApi.list( cursor: page.data?.nextCursor ?? null,
guildId, hasMore: page.data ? page.data.nextCursor !== null : undefined,
50,
channelId || undefined,
);
return { cursor: result.nextCursor, hasMore: result.nextCursor !== null };
}, },
enabled: !!guildId, };
});
} }
export function useLoadMore() { export function useLoadMore() {
const qc = useQueryClient(); const { mutate } = useSWRConfig();
return useMutation({ return useAction(
mutationFn: async ({ async ({
guildId, guildId,
channelId, channelId,
cursor, cursor,
@@ -66,76 +70,73 @@ export function useLoadMore() {
channelId || undefined, channelId || undefined,
cursor, cursor,
); );
return { data: result.data, cursor: result.nextCursor }; const key = msgKeys.list(guildId, channelId);
}, await mutate(
onSuccess: (data, vars) => { key,
const key = msgKeys.list(vars.guildId, vars.channelId); (old: MessagePage | undefined): MessagePage | undefined =>
qc.setQueryData<MessageRecord[]>(key, (old) => old
old ? [...old, ...data.data] : data.data, ? {
data: [...old.data, ...result.data],
nextCursor: result.nextCursor,
}
: result,
{ revalidate: false },
); );
qc.setQueryData([...key, "cursor"], { return result;
cursor: data.cursor,
hasMore: data.cursor !== null,
});
}, },
}); );
} }
// ── Channels list ──────────────────────────────── // ── Channels list ────────────────────────────────
export function useTextChannels(guildId: string) { export function useTextChannels(guildId: string) {
return useQuery<Channel[]>({ return useSWR<Channel[]>(guildId ? ["text-channels", guildId] : null, () =>
queryKey: ["text-channels", guildId], voiceApi.getTextChannels(guildId),
queryFn: () => voiceApi.getTextChannels(guildId), );
enabled: !!guildId,
});
} }
// ── Images ─────────────────────────────────────── // ── Images ───────────────────────────────────────
export function useImages(guildId: string) { export function useImages(guildId: string) {
return useQuery<MessageRecord[]>({ return useSWR<MessageRecord[]>(
queryKey: msgKeys.images(guildId), guildId ? msgKeys.images(guildId) : null,
queryFn: async () => { async () => {
const result = await messagesApi.getImages(guildId, 50); const result = await messagesApi.getImages(guildId, 50);
return result.data; return result.data;
}, },
enabled: !!guildId, );
});
} }
// ── Review ─────────────────────────────────────── // ── Review ───────────────────────────────────────
export function useReview(channelId?: string) { export function useReview(channelId?: string) {
return useQuery<MessageRecord[]>({ return useSWR<MessageRecord[]>(
queryKey: msgKeys.review(channelId), msgKeys.review(channelId),
queryFn: async () => { async () => {
const result = await messagesApi.getReview(50, channelId || undefined); const result = await messagesApi.getReview(50, channelId || undefined);
return result.results; return result.results;
}, },
}); {
refreshInterval: 15_000,
},
);
} }
// ── Detail ─────────────────────────────────────── // ── Detail ───────────────────────────────────────
export function useMessageDetail(id: string | null) { export function useMessageDetail(id: string | null) {
const detail = useQuery<MessageRecord>({ const detail = useSWR<MessageRecord>(id ? msgKeys.detail(id) : null, () =>
queryKey: msgKeys.detail(id ?? ""), messagesApi.getDetail(id!),
queryFn: () => messagesApi.getDetail(id!), );
enabled: !!id, const attachments = useSWR<AttachmentRecord[]>(
}); id && detail.data?.channel_id
const attachments = useQuery<AttachmentRecord[]>({ ? [...msgKeys.detail(id), "attachments"]
queryKey: [...msgKeys.detail(id ?? ""), "attachments"], : null,
queryFn: async () => { async () => {
if (!id) return []; const res = await messagesApi.getAttachments(detail.data!.channel_id, 10);
const res = await messagesApi.getAttachments(
detail.data?.channel_id ?? "",
10,
);
return res.data; return res.data;
}, },
enabled: !!id && !!detail.data?.channel_id, );
});
return { return {
message: detail.data ?? null, message: detail.data ?? null,
attachments: attachments.data ?? [], attachments: attachments.data ?? [],
@@ -147,52 +148,70 @@ export function useMessageDetail(id: string | null) {
// ── Mutations ──────────────────────────────────── // ── Mutations ────────────────────────────────────
export function useReanalyze() { export function useReanalyze() {
const _qc = useQueryClient(); return useAction((id: string) => messagesApi.reanalyze(id));
return useMutation({
mutationFn: (id: string) => messagesApi.reanalyze(id),
});
} }
export function useReanalyzeBatch() { export function useReanalyzeBatch() {
return useMutation({ return useAction((guildId: string) => messagesApi.reanalyzeBatch(guildId));
mutationFn: (guildId: string) => messagesApi.reanalyzeBatch(guildId), }
});
// ── Search ───────────────────────────────────────
export function useMessageSearch(query: string, enabled: boolean) {
return useSWR<MessageRecord[]>(
enabled && query.trim().length >= 2 ? msgKeys.search(query) : null,
async () => {
const res = await messagesApi.search(query, 50);
return res.results;
},
);
} }
// ── WS sync helpers ────────────────────────────── // ── WS sync helpers ──────────────────────────────
export function useMessagesWsSync(ws: WsHook, guildId: string) { export function useMessagesWsSync(ws: WsHook, guildId: string) {
const qc = useQueryClient(); const { mutate } = useSWRConfig();
useEffect(() => { useEffect(() => {
if (!guildId) return; if (!guildId) return;
const key = msgKeys.list(guildId); // Patch every message-list key for this guild (all channels + "__all__")
const unsub1 = ws.on("message_created", (data) => { const patchLists = (
qc.setQueryData<MessageRecord[]>(key, (old) => updater: (old: MessagePage | undefined) => MessagePage | undefined,
old ? [data as MessageRecord, ...old] : [data as MessageRecord], ) => {
void mutate(
(key) =>
Array.isArray(key) && key[0] === "messages" && key[1] === guildId,
updater,
{ revalidate: false },
); );
};
const unsub1 = ws.on("message_created", (data) => {
const msg = data as MessageRecord;
patchLists((old) => (old ? { ...old, data: [msg, ...old.data] } : old));
}); });
const unsub2 = ws.on("message_updated", (data) => { const unsub2 = ws.on("message_updated", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) => const msg = data as MessageRecord;
patchLists((old) =>
old old
? old.map((m) => ? { ...old, data: old.data.map((m) => (m.id === msg.id ? msg : m)) }
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
)
: old, : old,
); );
void mutate(msgKeys.detail(msg.id), msg, { revalidate: false });
}); });
const unsub3 = ws.on("message_deleted", (data) => { const unsub3 = ws.on("message_deleted", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) => const { id } = data as { id: string };
old ? old.filter((m) => m.id !== (data as { id: string }).id) : old, patchLists((old) =>
old ? { ...old, data: old.data.filter((m) => m.id !== id) } : old,
); );
}); });
const unsub4 = ws.on("message_analyzed", (data) => { const unsub4 = ws.on("message_analyzed", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) => const msg = data as MessageRecord;
patchLists((old) =>
old old
? old.map((m) => ? { ...old, data: old.data.map((m) => (m.id === msg.id ? msg : m)) }
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
)
: old, : old,
); );
void mutate(msgKeys.detail(msg.id), msg, { revalidate: false });
}); });
return () => { return () => {
unsub1(); unsub1();
@@ -200,5 +219,5 @@ export function useMessagesWsSync(ws: WsHook, guildId: string) {
unsub3(); unsub3();
unsub4(); unsub4();
}; };
}, [ws, guildId, qc]); }, [ws, guildId, mutate]);
} }
+18 -16
View File
@@ -1,37 +1,39 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react"; import { useEffect } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { recordingsApi } from "@/lib/api"; import { recordingsApi } from "@/lib/api";
import type { VoiceRecording } from "@/lib/types"; import type { VoiceRecording } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook"; import type { WsHook } from "@/lib/ws-hook";
const RECORDINGS_KEY = ["recordings"] as const;
export function useRecordings() { export function useRecordings() {
return useQuery<VoiceRecording[]>({ return useSWR<VoiceRecording[]>(RECORDINGS_KEY, async () => {
queryKey: ["recordings"], const res = await recordingsApi.list(50);
queryFn: async () => { return res.items;
const res = await recordingsApi.list(50);
return res.items;
},
}); });
} }
export function useDeleteRecording() { export function useDeleteRecording() {
const qc = useQueryClient(); const { mutate } = useSWRConfig();
return useMutation({ return useAction((id: string) => recordingsApi.delete(id), {
mutationFn: (id: string) => recordingsApi.delete(id), onSuccess: () => {
onSuccess: () => qc.invalidateQueries({ queryKey: ["recordings"] }), void mutate(RECORDINGS_KEY);
},
}); });
} }
export function useRecordingsWsSync(ws: WsHook) { export function useRecordingsWsSync(ws: WsHook) {
const qc = useQueryClient(); const { mutate } = useSWRConfig();
useEffect(() => { useEffect(() => {
const unsub = ws.on("voice_recording_uploaded", (data) => { const unsub = ws.on("voice_recording_uploaded", (data) => {
const rec = data as VoiceRecording; const rec = data as VoiceRecording;
qc.setQueryData<VoiceRecording[]>(["recordings"], (old) => void mutate(
old ? [rec, ...old] : [rec], RECORDINGS_KEY,
(old: VoiceRecording[] | undefined) => (old ? [rec, ...old] : [rec]),
{ revalidate: false },
); );
}); });
return unsub; return unsub;
}, [ws, qc]); }, [ws, mutate]);
} }
+29 -33
View File
@@ -1,24 +1,22 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useState } from "react"; import { useCallback, useState } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { voiceApi } from "@/lib/api"; import { voiceApi } from "@/lib/api";
import type { ActiveSpeaker, Channel, VoiceStatus } from "@/lib/types"; import type { ActiveSpeaker, Channel, VoiceStatus } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook"; import type { WsHook } from "@/lib/ws-hook";
const STATUS_KEY = ["voice-status"] as const;
export function useVoiceStatus() { export function useVoiceStatus() {
return useQuery<VoiceStatus>({ return useSWR<VoiceStatus>(STATUS_KEY, () => voiceApi.getStatus(), {
queryKey: ["voice-status"], shouldRetryOnError: false,
queryFn: () => voiceApi.getStatus(),
retry: false,
}); });
} }
export function useVoiceChannels(guildId: string) { export function useVoiceChannels(guildId: string) {
return useQuery<Channel[]>({ return useSWR<Channel[]>(guildId ? ["voice-channels", guildId] : null, () =>
queryKey: ["voice-channels", guildId], voiceApi.getVoiceChannels(guildId),
queryFn: () => voiceApi.getVoiceChannels(guildId), );
enabled: !!guildId,
});
} }
export function useSpeakers() { export function useSpeakers() {
@@ -46,33 +44,31 @@ export function useSpeakers() {
return { speakers, subscribe }; return { speakers, subscribe };
} }
function useStatusInvalidator() {
const { mutate } = useSWRConfig();
return () => {
void mutate(STATUS_KEY);
};
}
export function useVoiceConnect() { export function useVoiceConnect() {
const qc = useQueryClient(); const invalidate = useStatusInvalidator();
return useMutation({ return useAction(
mutationFn: ({ ({ guildId, channelId }: { guildId: string; channelId: string }) =>
guildId, voiceApi.connect(guildId, channelId),
channelId, { onSuccess: invalidate },
}: { );
guildId: string;
channelId: string;
}) => voiceApi.connect(guildId, channelId),
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
});
} }
export function useVoiceDisconnect() { export function useVoiceDisconnect() {
const qc = useQueryClient(); const invalidate = useStatusInvalidator();
return useMutation({ return useAction(() => voiceApi.disconnect(), { onSuccess: invalidate });
mutationFn: () => voiceApi.disconnect(),
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
});
} }
export function useMicTransmit() { export function useMicTransmit() {
return useMutation({ return useAction((active: boolean) =>
mutationFn: (active: boolean) => voiceApi.sendCommand(
voiceApi.sendCommand( active ? "voice:transmit:start" : "voice:transmit:stop",
active ? "voice:transmit:start" : "voice:transmit:stop", ),
), );
});
} }