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": {
"@base-ui/react": "^1.6.0",
"@shadcn/react": "^0.2.1",
"@tanstack/react-query": "^5.101.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@@ -29,6 +28,7 @@
"recharts": "3.8.0",
"shadcn": "^4.15.0",
"sonner": "^2.0.7",
"swr": "^2.4.2",
"tailwind-merge": "^3.6.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() {
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 modQueueItems: ModQueueItem[] = review.slice(0, 10).map((msg) => ({
@@ -1,25 +1,18 @@
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Suspense, useEffect, useState } from "react";
import { TopNav } from "@/components/layout/top-nav";
import { MobileNav } from "@/components/layout/mobile-nav";
import { WsProvider, useWebSocket } from "@/lib/ws/context";
import { ChatbotProvider, useChatbot } from "@/components/chatbot/chatbot-context";
import { SWRConfig } from "swr";
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 { MediaPlayerProvider } from "@/lib/hooks/use-media-player";
import { HiddenSidebar } from "@/components/layout/hidden-sidebar";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 10_000,
retry: 1,
refetchOnWindowFocus: false,
},
},
});
import { useWebSocket, WsProvider } from "@/lib/ws/context";
function ChatbotExpressionSync() {
const ws = useWebSocket();
@@ -54,14 +47,24 @@ export default function DashboardLayout({
const [guildId, setGuildId] = useState("");
return (
<QueryClientProvider client={queryClient}>
<SWRConfig
value={{
revalidateOnFocus: false,
dedupingInterval: 10_000,
shouldRetryOnError: (err) =>
(err as { statusCode?: number })?.statusCode !== 404,
}}
>
<WsProvider>
<MediaPlayerProvider>
<ChatbotProvider>
<ChatbotExpressionSync />
<div className="min-h-screen bg-canvas">
<TopNav />
<HiddenSidebar guildId={guildId} onGuildChange={(g) => setGuildId(g ?? "")} />
<HiddenSidebar
guildId={guildId}
onGuildChange={(g) => setGuildId(g ?? "")}
/>
{/* Sub-nav space — filled per-page */}
<div className="pt-11">
@@ -85,6 +88,6 @@ export default function DashboardLayout({
</ChatbotProvider>
</MediaPlayerProvider>
</WsProvider>
</QueryClientProvider>
</SWRConfig>
);
}
@@ -1,17 +1,17 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Flag, Image, Loader2, RefreshCw, Search } from "lucide-react";
import { MessageList } from "@/components/messages/message-list";
import { MessageDetailView } from "@/components/messages/message-detail-view";
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 { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { GlassCard } from "@/components/glass/card";
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 {
Select,
@@ -32,10 +32,10 @@ import {
useReview,
useTextChannels,
} from "@/hooks";
import { renderMessageContent } from "@/lib/format";
import type { MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
import { GuildSelector } from "@/components/shared/guild-selector";
type MessagesTab = "all" | "images" | "review";
@@ -185,10 +185,7 @@ export default function MessagesPage() {
<div className="flex gap-4">
{/* Left pane */}
<div
className={cn(
"space-y-2",
detailId ? "w-1/2 lg:w-2/5" : "w-full",
)}
className={cn("space-y-2", detailId ? "w-1/2 lg:w-2/5" : "w-full")}
>
{tab === "all" && (
<MessageList
@@ -205,10 +202,7 @@ export default function MessagesPage() {
<ImageGrid items={images ?? []} onSelect={setDetailId} />
)}
{tab === "review" && (
<ReviewList
items={reviews ?? []}
onSelect={setDetailId}
/>
<ReviewList items={reviews ?? []} onSelect={setDetailId} />
)}
</div>
@@ -216,7 +210,10 @@ export default function MessagesPage() {
{detailId && (
<div className="sticky top-16 hidden w-1/2 self-start md:block lg:w-3/5">
{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" />
</GlassPanel>
) : detailMessage ? (
@@ -288,9 +285,12 @@ function ImageGrid({
);
})}
{items.length === 0 && (
<div className="col-span-3 py-12 text-center text-xs text-text-secondary/40">
No images
</div>
<EmptyState
icon={Image}
title="No images"
description="Messages with image attachments will show up here."
className="col-span-3"
/>
)}
</div>
);
@@ -325,9 +325,11 @@ function ReviewList({
</GlassCard>
))}
{items.length === 0 && (
<div className="py-12 text-center text-xs text-text-secondary/40">
No flagged messages
</div>
<EmptyState
icon={Flag}
title="No flagged messages"
description="Messages flagged by AI moderation will appear here for review."
/>
)}
</div>
);
@@ -1,18 +1,26 @@
"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 { RecordingCard } from "@/components/recordings/recording-card";
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 { formatBytes } from "@/lib/format";
import type { VoiceRecording } from "@/lib/types";
import { useWebSocket } from "@/lib/ws/context";
type RecordingsTab = "library" | "stats";
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 [tab, setTab] = useState<RecordingsTab>("library");
const ws = useWebSocket();
@@ -25,6 +33,31 @@ export default function RecordingsPage() {
? recordings.find((r: VoiceRecording) => r.id === playingId)
: 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 (
<div className="space-y-4 animate-fade-in-up">
<SubNav
@@ -51,18 +84,72 @@ export default function RecordingsPage() {
/>
))}
{(recordings ?? []).length === 0 && (
<div className="py-12 text-center text-sm text-text-secondary/40">
No recordings yet
</div>
<EmptyState
icon={Mic}
title="No recordings yet"
description="Voice recordings will appear here once members speak in a monitored voice channel."
/>
)}
</div>
))}
{tab === "stats" && (
<div className="py-12 text-center text-sm text-text-secondary/40">
Recording stats coming soon
</div>
)}
{tab === "stats" &&
(isLoading ? (
<LoadingSkeleton count={4} height="h-28" columns={3} />
) : 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
url={currentTrack?.download_url ?? undefined}
@@ -7,8 +7,8 @@ import { GlassDivider } from "@/components/glass/divider";
import { SubNav } from "@/components/layout/sub-nav";
import { LoadingSkeleton } from "@/components/shared";
import { useConfig } from "@/hooks";
import { useWebSocket } from "@/lib/ws/context";
import { cn } from "@/lib/utils";
import { useWebSocket } from "@/lib/ws/context";
type SettingsTab = "connection" | "appearance" | "config" | "about";
@@ -32,7 +32,8 @@ export default function SettingsPage() {
};
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",
disconnected: "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">
<SubNav
tabs={[
{ id: "connection", 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: "connection",
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" /> },
]}
activeTab={tab}
@@ -62,11 +75,15 @@ export default function SettingsPage() {
<GlassCard variant="base">
<div className="flex items-center justify-between">
<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 className="flex items-center gap-2">
<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>
</GlassCard>
@@ -76,8 +93,14 @@ export default function SettingsPage() {
<GlassCard variant="base">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{theme === "dark" ? <Moon className="size-4 text-primary" /> : <Sun className="size-4 text-primary" />}
<span className="text-sm font-semibold text-text-primary">Theme</span>
{theme === "dark" ? (
<Moon className="size-4 text-primary" />
) : (
<Sun className="size-4 text-primary" />
)}
<span className="text-sm font-semibold text-text-primary">
Theme
</span>
</div>
<button
type="button"
@@ -97,18 +120,37 @@ export default function SettingsPage() {
<LoadingSkeleton count={6} height="h-6" />
) : config ? (
<>
<ConfigRow label="Monitor Guild" value={config.monitorGuildId || "Not configured"} />
<ConfigRow
label="Monitor Guild"
value={config.monitorGuildId || "Not configured"}
/>
<GlassDivider />
<ConfigRow label="Voice Guild" value={config.voiceGuildId || "Not configured"} />
<ConfigRow
label="Voice Guild"
value={config.voiceGuildId || "Not configured"}
/>
<GlassDivider />
<ConfigRow label="Voice Channel" value={config.voiceChannelId || "Not configured"} />
<ConfigRow
label="Voice Channel"
value={config.voiceChannelId || "Not configured"}
/>
<GlassDivider />
<ConfigRow label="AI Analysis" value={config.aiAnalysisEnabled ? "Enabled" : "Disabled"} />
<ConfigRow
label="AI Analysis"
value={config.aiAnalysisEnabled ? "Enabled" : "Disabled"}
/>
<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>
</GlassCard>
@@ -117,9 +159,12 @@ export default function SettingsPage() {
{tab === "about" && (
<GlassCard variant="base">
<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">
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>
<div className="text-[10px] font-mono text-text-secondary/40 mt-4">
v0.1.0
@@ -135,7 +180,9 @@ function ConfigRow({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-center justify-between py-0.5">
<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>
);
}
@@ -1,12 +1,11 @@
"use client";
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 { 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 {
useGuilds,
useMicTransmit,
@@ -16,6 +15,7 @@ import {
useVoiceDisconnect,
useVoiceStatus,
} from "@/hooks";
import { useWebSocket } from "@/lib/ws/context";
type VoiceTab = "connection" | "activity";
@@ -83,7 +83,12 @@ export default function VoicePage() {
selectedChannel={selectedChannel}
onGuildChange={handleGuildChange}
onChannelChange={(v) => setSelectedChannel(v ?? "")}
onConnect={() => connectMut.mutate({ guildId: selectedGuild, channelId: selectedChannel })}
onConnect={() =>
connectMut.mutate({
guildId: selectedGuild,
channelId: selectedChannel,
})
}
onDisconnect={() => disconnectMut.mutate(undefined)}
connecting={connectMut.isPending}
/>
@@ -1,6 +1,5 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { Loader2, RefreshCw, Search, Sparkles } from "lucide-react";
import { useCallback, useState } from "react";
@@ -11,8 +10,7 @@ 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 { useReanalyze } from "@/hooks";
import { messagesApi } from "@/lib/api";
import { useMessageSearch, useReanalyze } from "@/hooks";
import { renderMessageContent, safeParseJsonArray } from "@/lib/format";
import type { MessageRecord } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -22,14 +20,10 @@ export function SearchPanel() {
const [enabled, setEnabled] = useState(false);
const reanalyzeMut = useReanalyze();
const { data: results, isFetching } = useQuery<MessageRecord[]>({
queryKey: ["analysis-search", query],
queryFn: async () => {
const result = await messagesApi.search(query, 50);
return result.results;
},
const { data: results, isValidating: isFetching } = useMessageSearch(
query,
enabled,
});
);
const handleSearch = useCallback(() => {
if (!query.trim()) return;
@@ -100,7 +94,9 @@ export function SearchPanel() {
</Badge>
)}
</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 !== "[]" && (
<div className="flex flex-wrap gap-1">
@@ -20,7 +20,7 @@ export function ChannelsSection({ guildId }: { guildId?: string }) {
data: channels = [],
isLoading,
error,
refetch,
mutate: refetch,
} = useChannels(guildId ?? "", search);
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"
>
<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 className="mt-1 text-[10px] font-mono text-text-secondary/40">
{new Date(msg.created_at).toLocaleString()}
@@ -1,9 +1,9 @@
"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 { cn } from "@/lib/utils";
import { Area, AreaChart, ResponsiveContainer } from "recharts";
interface StatCardProps {
label: string;
@@ -43,7 +43,10 @@ export function StatCard({
<Icon className="size-4" />
</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)}
</div>
<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%">
<AreaChart data={sparklineData}>
<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="100%" stopColor={accentColor} stopOpacity={0} />
</linearGradient>
@@ -1,7 +1,14 @@
"use client";
import {
Bar,
BarChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { GlassCard } from "@/components/glass/card";
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
interface TopChannelsChartProps {
data?: { name: string; count: number }[];
@@ -11,13 +18,27 @@ export function TopChannelsChart({ data = [] }: TopChannelsChartProps) {
return (
<GlassCard variant="base">
<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 className="h-48">
<ResponsiveContainer width="100%" height="100%">
<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} />
<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)",
@@ -27,7 +48,11 @@ export function TopChannelsChart({ data = [] }: TopChannelsChartProps) {
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>
</ResponsiveContainer>
</div>
@@ -17,7 +17,12 @@ export function UsersSection() {
const [search, setSearch] = useState("");
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 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"
>
<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 className="mt-1 text-[10px] font-mono text-text-secondary/40">
{msg.channel_id?.slice(0, 8)} ·{" "}
@@ -2,8 +2,7 @@
import { Search, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { messagesApi } from "@/lib/api";
import { useMessageSearch } from "@/hooks";
import { getMessageChannelLabel, renderMessageContent } from "@/lib/format";
import type { MessageRecord } from "@/lib/types";
@@ -17,14 +16,7 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
const [query, setQuery] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const { data: results } = useQuery<MessageRecord[]>({
queryKey: ["messages-search", query],
queryFn: async () => {
const res = await messagesApi.search(query, 20);
return res.results;
},
enabled: query.length >= 2,
});
const { data: results } = useMessageSearch(query, true);
useEffect(() => {
if (open) {
@@ -50,7 +42,12 @@ export function SearchOverlay({ open, onClose, onSelect }: SearchOverlayProps) {
return (
<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">
{/* Input */}
<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..."
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" />
</button>
</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">
{!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"}
{query.length < 2
? "Type at least 2 characters"
: "No results found"}
</div>
) : (
results.map((msg) => (
<button
key={msg.id}
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"
>
<div className="flex items-center gap-2 text-xs">
<span className="font-medium text-text-primary">{msg.username}</span>
<span className="text-text-secondary/40">{getMessageChannelLabel(msg)}</span>
<span className="font-medium text-text-primary">
{msg.username}
</span>
<span className="text-text-secondary/40">
{getMessageChannelLabel(msg)}
</span>
</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>
))
)}
@@ -3,20 +3,26 @@
import type { LucideIcon } from "lucide-react";
import { Inbox } from "lucide-react";
import { GlassPanel } from "@/components/glass/panel";
import { cn } from "@/lib/utils";
interface EmptyStateProps {
icon?: LucideIcon;
title?: string;
description?: string;
className?: string;
}
export function EmptyState({
icon: Icon = Inbox,
title = "No data yet",
description = "Nothing to display here yet.",
className,
}: EmptyStateProps) {
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" />
<p className="text-sm text-text-secondary/60">{title}</p>
<p className="text-xs text-text-secondary/40">{description}</p>
@@ -33,7 +33,7 @@ export function GuildSelector({
onChange,
autoHide = true,
}: GuildSelectorProps) {
const { data: guilds = [], isLoading, error, refetch } = useGuilds();
const { data: guilds = [], isLoading, error, mutate: refetch } = useGuilds();
const { data: config } = useConfig();
const initDone = useRef(false);
+1
View File
@@ -19,6 +19,7 @@ export {
useImages,
useLoadMore,
useMessageDetail,
useMessageSearch,
useMessages,
useMessagesHasMore,
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 type { AppConfig } from "@/lib/types";
@@ -7,9 +7,7 @@ import type { AppConfig } from "@/lib/types";
* Fetch the app configuration from the backend.
*/
export function useConfig() {
return useQuery<AppConfig>({
queryKey: ["config"],
queryFn: () => configApi.get(),
staleTime: 120_000,
return useSWR<AppConfig>(["config"], () => configApi.get(), {
dedupingInterval: 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 type {
@@ -8,40 +8,51 @@ import type {
} from "@/lib/types";
export function useStats() {
return useQuery<DashboardStats>({
queryKey: ["dashboard-stats"],
queryFn: () => dashboardApi.getStats(),
});
return useSWR<DashboardStats>(["dashboard-stats"], () =>
dashboardApi.getStats(),
);
}
export function useUsers(search?: string) {
return useQuery({
queryKey: ["dashboard-users", search ?? ""],
queryFn: () => dashboardApi.listUsers(20, undefined, search),
select: (data) => data.data,
});
return useSWR(
["dashboard-users", search ?? ""],
async () => {
const res = await dashboardApi.listUsers(20, undefined, search);
return res.data;
},
{
keepPreviousData: true,
},
);
}
export function useChannels(guildId?: string, search?: string) {
return useQuery({
queryKey: ["dashboard-channels", guildId ?? "__all__", search ?? ""],
queryFn: () => dashboardApi.listChannels(20, search, guildId || undefined),
select: (data) => data.data,
});
return useSWR(
["dashboard-channels", guildId ?? "__all__", search ?? ""],
async () => {
const res = await dashboardApi.listChannels(
20,
search,
guildId || undefined,
);
return res.data;
},
{
keepPreviousData: true,
},
);
}
export function useUserDetail(userId: string | null) {
return useQuery<DashboardUserDetail>({
queryKey: ["dashboard-user", userId],
queryFn: () => dashboardApi.getUserDetail(userId!),
enabled: !!userId,
});
return useSWR<DashboardUserDetail>(
userId ? ["dashboard-user", userId] : null,
() => dashboardApi.getUserDetail(userId!),
);
}
export function useChannelDetail(channelId: string | null) {
return useQuery<DashboardChannelDetail>({
queryKey: ["dashboard-channel", channelId],
queryFn: () => dashboardApi.getChannelDetail(channelId!),
enabled: !!channelId,
});
return useSWR<DashboardChannelDetail>(
channelId ? ["dashboard-channel", channelId] : null,
() => dashboardApi.getChannelDetail(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 type { Guild } from "@/lib/types";
@@ -7,9 +7,7 @@ import type { Guild } from "@/lib/types";
* Fetch the list of available Discord guilds.
*/
export function useGuilds() {
return useQuery<Guild[]>({
queryKey: ["guilds"],
queryFn: () => voiceApi.getGuilds(),
staleTime: 60_000,
return useSWR<Guild[]>(["guilds"], () => voiceApi.getGuilds(), {
dedupingInterval: 60_000,
});
}
+23 -30
View File
@@ -1,58 +1,51 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { mediaApi } from "@/lib/api";
import type { MediaState } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
const MEDIA_KEY = ["media-state"] as const;
export function useMediaState() {
return useQuery<MediaState>({
queryKey: ["media-state"],
queryFn: () => mediaApi.getStatus(),
retry: false,
refetchInterval: 10_000,
return useSWR<MediaState>(MEDIA_KEY, () => mediaApi.getStatus(), {
refreshInterval: 10_000,
shouldRetryOnError: false,
});
}
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() {
const qc = useQueryClient();
return useMutation({
mutationFn: (url: string) => mediaApi.queue(url, "music"),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
return useMediaAction((url: string) => mediaApi.queue(url, "music"));
}
export function useMediaSkip() {
const qc = useQueryClient();
return useMutation({
mutationFn: () => mediaApi.skip(),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
return useMediaAction(() => mediaApi.skip());
}
export function useMediaStop() {
const qc = useQueryClient();
return useMutation({
mutationFn: () => mediaApi.stop(),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
return useMediaAction(() => mediaApi.stop());
}
export function useMediaVolume() {
const qc = useQueryClient();
return useMutation({
mutationFn: (volume: number) => mediaApi.volume(volume),
onSuccess: (data) => qc.setQueryData(["media-state"], data),
});
return useMediaAction((volume: number) => mediaApi.volume(volume));
}
/** Subscribe to WS media_state events to keep cache fresh */
export function useMediaWsSync(ws: WsHook) {
const qc = useQueryClient();
const { mutate } = useSWRConfig();
useEffect(() => {
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;
}, [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 useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { messagesApi, voiceApi } from "@/lib/api";
import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
@@ -14,44 +14,48 @@ const msgKeys = {
review: (channelId?: string) =>
["messages-review", channelId ?? "__all__"] 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) ──────
export function useMessages(guildId: string, channelId?: string) {
return useQuery<MessageRecord[]>({
queryKey: msgKeys.list(guildId, channelId),
queryFn: async () => {
const result = await messagesApi.list(
guildId,
50,
channelId || undefined,
);
return result.data;
},
enabled: !!guildId,
});
const page = useMessagesPage(guildId, channelId);
return {
...page,
data: page.data?.data,
refetch: () => page.mutate(),
};
}
export function useMessagesHasMore(guildId: string, channelId?: string) {
return useQuery({
queryKey: [...msgKeys.list(guildId, channelId), "cursor"],
queryFn: async () => {
const result = await messagesApi.list(
guildId,
50,
channelId || undefined,
);
return { cursor: result.nextCursor, hasMore: result.nextCursor !== null };
const page = useMessagesPage(guildId, channelId);
return {
data: {
cursor: page.data?.nextCursor ?? null,
hasMore: page.data ? page.data.nextCursor !== null : undefined,
},
enabled: !!guildId,
});
};
}
export function useLoadMore() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({
const { mutate } = useSWRConfig();
return useAction(
async ({
guildId,
channelId,
cursor,
@@ -66,76 +70,73 @@ export function useLoadMore() {
channelId || undefined,
cursor,
);
return { data: result.data, cursor: result.nextCursor };
},
onSuccess: (data, vars) => {
const key = msgKeys.list(vars.guildId, vars.channelId);
qc.setQueryData<MessageRecord[]>(key, (old) =>
old ? [...old, ...data.data] : data.data,
const key = msgKeys.list(guildId, channelId);
await mutate(
key,
(old: MessagePage | undefined): MessagePage | undefined =>
old
? {
data: [...old.data, ...result.data],
nextCursor: result.nextCursor,
}
: result,
{ revalidate: false },
);
qc.setQueryData([...key, "cursor"], {
cursor: data.cursor,
hasMore: data.cursor !== null,
});
return result;
},
});
);
}
// ── Channels list ────────────────────────────────
export function useTextChannels(guildId: string) {
return useQuery<Channel[]>({
queryKey: ["text-channels", guildId],
queryFn: () => voiceApi.getTextChannels(guildId),
enabled: !!guildId,
});
return useSWR<Channel[]>(guildId ? ["text-channels", guildId] : null, () =>
voiceApi.getTextChannels(guildId),
);
}
// ── Images ───────────────────────────────────────
export function useImages(guildId: string) {
return useQuery<MessageRecord[]>({
queryKey: msgKeys.images(guildId),
queryFn: async () => {
return useSWR<MessageRecord[]>(
guildId ? msgKeys.images(guildId) : null,
async () => {
const result = await messagesApi.getImages(guildId, 50);
return result.data;
},
enabled: !!guildId,
});
);
}
// ── Review ───────────────────────────────────────
export function useReview(channelId?: string) {
return useQuery<MessageRecord[]>({
queryKey: msgKeys.review(channelId),
queryFn: async () => {
return useSWR<MessageRecord[]>(
msgKeys.review(channelId),
async () => {
const result = await messagesApi.getReview(50, channelId || undefined);
return result.results;
},
});
{
refreshInterval: 15_000,
},
);
}
// ── Detail ───────────────────────────────────────
export function useMessageDetail(id: string | null) {
const detail = useQuery<MessageRecord>({
queryKey: msgKeys.detail(id ?? ""),
queryFn: () => messagesApi.getDetail(id!),
enabled: !!id,
});
const attachments = useQuery<AttachmentRecord[]>({
queryKey: [...msgKeys.detail(id ?? ""), "attachments"],
queryFn: async () => {
if (!id) return [];
const res = await messagesApi.getAttachments(
detail.data?.channel_id ?? "",
10,
);
const detail = useSWR<MessageRecord>(id ? msgKeys.detail(id) : null, () =>
messagesApi.getDetail(id!),
);
const attachments = useSWR<AttachmentRecord[]>(
id && detail.data?.channel_id
? [...msgKeys.detail(id), "attachments"]
: null,
async () => {
const res = await messagesApi.getAttachments(detail.data!.channel_id, 10);
return res.data;
},
enabled: !!id && !!detail.data?.channel_id,
});
);
return {
message: detail.data ?? null,
attachments: attachments.data ?? [],
@@ -147,52 +148,70 @@ export function useMessageDetail(id: string | null) {
// ── Mutations ────────────────────────────────────
export function useReanalyze() {
const _qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => messagesApi.reanalyze(id),
});
return useAction((id: string) => messagesApi.reanalyze(id));
}
export function useReanalyzeBatch() {
return useMutation({
mutationFn: (guildId: string) => messagesApi.reanalyzeBatch(guildId),
});
return useAction((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 ──────────────────────────────
export function useMessagesWsSync(ws: WsHook, guildId: string) {
const qc = useQueryClient();
const { mutate } = useSWRConfig();
useEffect(() => {
if (!guildId) return;
const key = msgKeys.list(guildId);
const unsub1 = ws.on("message_created", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) =>
old ? [data as MessageRecord, ...old] : [data as MessageRecord],
// Patch every message-list key for this guild (all channels + "__all__")
const patchLists = (
updater: (old: MessagePage | undefined) => MessagePage | undefined,
) => {
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) => {
qc.setQueryData<MessageRecord[]>(key, (old) =>
const msg = data as MessageRecord;
patchLists((old) =>
old
? old.map((m) =>
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
)
? { ...old, data: old.data.map((m) => (m.id === msg.id ? msg : m)) }
: old,
);
void mutate(msgKeys.detail(msg.id), msg, { revalidate: false });
});
const unsub3 = ws.on("message_deleted", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) =>
old ? old.filter((m) => m.id !== (data as { id: string }).id) : old,
const { id } = data as { id: string };
patchLists((old) =>
old ? { ...old, data: old.data.filter((m) => m.id !== id) } : old,
);
});
const unsub4 = ws.on("message_analyzed", (data) => {
qc.setQueryData<MessageRecord[]>(key, (old) =>
const msg = data as MessageRecord;
patchLists((old) =>
old
? old.map((m) =>
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
)
? { ...old, data: old.data.map((m) => (m.id === msg.id ? msg : m)) }
: old,
);
void mutate(msgKeys.detail(msg.id), msg, { revalidate: false });
});
return () => {
unsub1();
@@ -200,5 +219,5 @@ export function useMessagesWsSync(ws: WsHook, guildId: string) {
unsub3();
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 useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { recordingsApi } from "@/lib/api";
import type { VoiceRecording } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
const RECORDINGS_KEY = ["recordings"] as const;
export function useRecordings() {
return useQuery<VoiceRecording[]>({
queryKey: ["recordings"],
queryFn: async () => {
const res = await recordingsApi.list(50);
return res.items;
},
return useSWR<VoiceRecording[]>(RECORDINGS_KEY, async () => {
const res = await recordingsApi.list(50);
return res.items;
});
}
export function useDeleteRecording() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => recordingsApi.delete(id),
onSuccess: () => qc.invalidateQueries({ queryKey: ["recordings"] }),
const { mutate } = useSWRConfig();
return useAction((id: string) => recordingsApi.delete(id), {
onSuccess: () => {
void mutate(RECORDINGS_KEY);
},
});
}
export function useRecordingsWsSync(ws: WsHook) {
const qc = useQueryClient();
const { mutate } = useSWRConfig();
useEffect(() => {
const unsub = ws.on("voice_recording_uploaded", (data) => {
const rec = data as VoiceRecording;
qc.setQueryData<VoiceRecording[]>(["recordings"], (old) =>
old ? [rec, ...old] : [rec],
void mutate(
RECORDINGS_KEY,
(old: VoiceRecording[] | undefined) => (old ? [rec, ...old] : [rec]),
{ revalidate: false },
);
});
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 useSWR, { useSWRConfig } from "swr";
import { useAction } from "@/hooks/use-action";
import { voiceApi } from "@/lib/api";
import type { ActiveSpeaker, Channel, VoiceStatus } from "@/lib/types";
import type { WsHook } from "@/lib/ws-hook";
const STATUS_KEY = ["voice-status"] as const;
export function useVoiceStatus() {
return useQuery<VoiceStatus>({
queryKey: ["voice-status"],
queryFn: () => voiceApi.getStatus(),
retry: false,
return useSWR<VoiceStatus>(STATUS_KEY, () => voiceApi.getStatus(), {
shouldRetryOnError: false,
});
}
export function useVoiceChannels(guildId: string) {
return useQuery<Channel[]>({
queryKey: ["voice-channels", guildId],
queryFn: () => voiceApi.getVoiceChannels(guildId),
enabled: !!guildId,
});
return useSWR<Channel[]>(guildId ? ["voice-channels", guildId] : null, () =>
voiceApi.getVoiceChannels(guildId),
);
}
export function useSpeakers() {
@@ -46,33 +44,31 @@ export function useSpeakers() {
return { speakers, subscribe };
}
function useStatusInvalidator() {
const { mutate } = useSWRConfig();
return () => {
void mutate(STATUS_KEY);
};
}
export function useVoiceConnect() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({
guildId,
channelId,
}: {
guildId: string;
channelId: string;
}) => voiceApi.connect(guildId, channelId),
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
});
const invalidate = useStatusInvalidator();
return useAction(
({ guildId, channelId }: { guildId: string; channelId: string }) =>
voiceApi.connect(guildId, channelId),
{ onSuccess: invalidate },
);
}
export function useVoiceDisconnect() {
const qc = useQueryClient();
return useMutation({
mutationFn: () => voiceApi.disconnect(),
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
});
const invalidate = useStatusInvalidator();
return useAction(() => voiceApi.disconnect(), { onSuccess: invalidate });
}
export function useMicTransmit() {
return useMutation({
mutationFn: (active: boolean) =>
voiceApi.sendCommand(
active ? "voice:transmit:start" : "voice:transmit:stop",
),
});
return useAction((active: boolean) =>
voiceApi.sendCommand(
active ? "voice:transmit:start" : "voice:transmit:stop",
),
);
}