Refactor voice page and hooks to use React Query for data fetching
Deploy to VPS / deploy (push) Successful in 2m57s
Deploy to VPS / deploy (push) Successful in 2m57s
- Updated VoicePage component to utilize useVoiceConnect, useVoiceDisconnect, and useMicTransmit mutations. - Replaced local state management with React Query's useQuery for voice status, guilds, and channels. - Removed custom useAsync hook and replaced it with useQuery in useConfig, useStats, useUsers, useChannels, and useMessages hooks. - Simplified useRecordings and useSpeakers hooks to leverage React Query for data fetching and mutations. - Removed deprecated use-async hook and related code. - Enhanced error handling and loading states across various hooks.
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
export { useAsync } from "./use-async";
|
||||
export { useConfig } from "./use-config";
|
||||
export {
|
||||
useChannelDetail,
|
||||
@@ -8,15 +7,37 @@ export {
|
||||
useUsers,
|
||||
} from "./use-dashboard";
|
||||
export { useGuilds } from "./use-guilds";
|
||||
export { useMediaState, useMediaWsSubscription } from "./use-media";
|
||||
export {
|
||||
useMediaQueue,
|
||||
useMediaSkip,
|
||||
useMediaState,
|
||||
useMediaStop,
|
||||
useMediaVolume,
|
||||
useMediaWsSync,
|
||||
} from "./use-media";
|
||||
export {
|
||||
useImages,
|
||||
useLoadMore,
|
||||
useMessageDetail,
|
||||
useMessages,
|
||||
useMessageWsSubscription,
|
||||
useMessagesHasMore,
|
||||
useMessagesWsSync,
|
||||
useReanalyze,
|
||||
useReanalyzeBatch,
|
||||
useReview,
|
||||
useSearch,
|
||||
useTextChannels,
|
||||
} from "./use-messages";
|
||||
export { useRecordings, useRecordingsWsSubscription } from "./use-recordings";
|
||||
export { useSpeakers, useVoiceChannels, useVoiceStatus } from "./use-voice";
|
||||
export {
|
||||
useDeleteRecording,
|
||||
useRecordings,
|
||||
useRecordingsWsSync,
|
||||
} from "./use-recordings";
|
||||
export {
|
||||
useMicTransmit,
|
||||
useSpeakers,
|
||||
useVoiceChannels,
|
||||
useVoiceConnect,
|
||||
useVoiceDisconnect,
|
||||
useVoiceStatus,
|
||||
} from "./use-voice";
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
interface UseAsyncState<T> {
|
||||
data: T | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
type UseAsyncReturn<T> = UseAsyncState<T> & { refetch: () => void };
|
||||
|
||||
/**
|
||||
* Generic async data-fetching hook.
|
||||
*
|
||||
* - Cancels requests on unmount
|
||||
* - Provides loading / error / data states
|
||||
* - Returns a refetch trigger
|
||||
*/
|
||||
export function useAsync<T>(
|
||||
fetcher: () => Promise<T>,
|
||||
deps: unknown[] = [],
|
||||
): UseAsyncReturn<T> {
|
||||
const [state, setState] = useState<UseAsyncState<T>>({
|
||||
data: null,
|
||||
loading: true,
|
||||
error: null,
|
||||
});
|
||||
const cancelledRef = useRef(false);
|
||||
|
||||
const execute = useCallback(() => {
|
||||
cancelledRef.current = false;
|
||||
setState((prev) => ({ ...prev, loading: true, error: null }));
|
||||
fetcher()
|
||||
.then((data) => {
|
||||
if (!cancelledRef.current) {
|
||||
setState({ data, loading: false, error: null });
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelledRef.current) {
|
||||
setState({
|
||||
data: null,
|
||||
loading: false,
|
||||
error: err instanceof Error ? err.message : "An error occurred",
|
||||
});
|
||||
}
|
||||
});
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: deps is intentionally dynamic
|
||||
}, deps);
|
||||
|
||||
useEffect(() => {
|
||||
execute();
|
||||
return () => {
|
||||
cancelledRef.current = true;
|
||||
};
|
||||
}, [execute]);
|
||||
|
||||
return { ...state, refetch: execute };
|
||||
}
|
||||
@@ -1,21 +1,15 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { configApi } from "@/lib/api";
|
||||
import type { AppConfig } from "@/lib/types";
|
||||
import { useAsync } from "./use-async";
|
||||
|
||||
interface UseConfigReturn {
|
||||
config: AppConfig | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the app configuration from the backend.
|
||||
*/
|
||||
export function useConfig(): UseConfigReturn {
|
||||
const { data, loading, error, refetch } = useAsync<AppConfig>(
|
||||
() => configApi.get(),
|
||||
[],
|
||||
);
|
||||
return { config: data, loading, error, refetch };
|
||||
export function useConfig() {
|
||||
return useQuery<AppConfig>({
|
||||
queryKey: ["config"],
|
||||
queryFn: () => configApi.get(),
|
||||
staleTime: 120_000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,173 +1,48 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { dashboardApi } from "@/lib/api";
|
||||
import type {
|
||||
DashboardChannel,
|
||||
DashboardChannelDetail,
|
||||
DashboardStats,
|
||||
DashboardUser,
|
||||
DashboardUserDetail,
|
||||
} from "@/lib/types";
|
||||
|
||||
// ── Stats ───────────────────────────────────────
|
||||
|
||||
interface UseStatsReturn {
|
||||
stats: DashboardStats | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refetch: () => void;
|
||||
export function useStats() {
|
||||
return useQuery<DashboardStats>({
|
||||
queryKey: ["dashboard-stats"],
|
||||
queryFn: () => dashboardApi.getStats(),
|
||||
});
|
||||
}
|
||||
|
||||
export function useStats(): UseStatsReturn {
|
||||
const [stats, setStats] = useState<DashboardStats | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await dashboardApi.getStats();
|
||||
setStats(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to load stats");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetch();
|
||||
}, [fetch]);
|
||||
|
||||
return { stats, loading, error, refetch: fetch };
|
||||
export function useUsers(search?: string) {
|
||||
return useQuery({
|
||||
queryKey: ["dashboard-users", search ?? ""],
|
||||
queryFn: () => dashboardApi.listUsers(20, undefined, search),
|
||||
select: (data) => data.data,
|
||||
});
|
||||
}
|
||||
|
||||
// ── Users ───────────────────────────────────────
|
||||
|
||||
interface UseUsersReturn {
|
||||
users: DashboardUser[];
|
||||
loading: boolean;
|
||||
search: string;
|
||||
setSearch: (q: string) => void;
|
||||
refetch: () => void;
|
||||
export function useChannels(guildId: string, search?: string) {
|
||||
return useQuery({
|
||||
queryKey: ["dashboard-channels", guildId, search ?? ""],
|
||||
queryFn: () => dashboardApi.listChannels(20, search, guildId || undefined),
|
||||
select: (data) => data.data,
|
||||
enabled: !!guildId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUsers(): UseUsersReturn {
|
||||
const [users, setUsers] = useState<DashboardUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const fetch = useCallback(async (q?: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await dashboardApi.listUsers(20, undefined, q);
|
||||
setUsers(result.data);
|
||||
} catch (err) {
|
||||
console.error("useUsers:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchWithSearch = useCallback(() => {
|
||||
fetch(search || undefined);
|
||||
}, [fetch, search]);
|
||||
|
||||
return {
|
||||
users,
|
||||
loading,
|
||||
search,
|
||||
setSearch,
|
||||
refetch: fetchWithSearch,
|
||||
};
|
||||
export function useUserDetail(userId: string | null) {
|
||||
return useQuery<DashboardUserDetail>({
|
||||
queryKey: ["dashboard-user", userId],
|
||||
queryFn: () => dashboardApi.getUserDetail(userId!),
|
||||
enabled: !!userId,
|
||||
});
|
||||
}
|
||||
|
||||
// ── Channels ────────────────────────────────────
|
||||
|
||||
interface UseChannelsReturn {
|
||||
channels: DashboardChannel[];
|
||||
loading: boolean;
|
||||
search: string;
|
||||
setSearch: (q: string) => void;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
export function useChannels(guildId: string): UseChannelsReturn {
|
||||
const [channels, setChannels] = useState<DashboardChannel[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const fetch = useCallback(
|
||||
async (q?: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await dashboardApi.listChannels(
|
||||
20,
|
||||
q,
|
||||
guildId || undefined,
|
||||
);
|
||||
setChannels(result.data);
|
||||
} catch (err) {
|
||||
console.error("useChannels:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[guildId],
|
||||
);
|
||||
|
||||
const fetchWithSearch = useCallback(() => {
|
||||
fetch(search || undefined);
|
||||
}, [fetch, search]);
|
||||
|
||||
return {
|
||||
channels,
|
||||
loading,
|
||||
search,
|
||||
setSearch,
|
||||
refetch: fetchWithSearch,
|
||||
};
|
||||
}
|
||||
|
||||
// ── User Detail ─────────────────────────────────
|
||||
|
||||
export function useUserDetail() {
|
||||
const [user, setUser] = useState<DashboardUserDetail | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetch = useCallback(async (userId: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const detail = await dashboardApi.getUserDetail(userId);
|
||||
setUser(detail);
|
||||
} catch (err) {
|
||||
console.error("useUserDetail:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return { user, loading, fetch };
|
||||
}
|
||||
|
||||
// ── Channel Detail ──────────────────────────────
|
||||
|
||||
export function useChannelDetail() {
|
||||
const [channel, setChannel] = useState<DashboardChannelDetail | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetch = useCallback(async (channelId: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const detail = await dashboardApi.getChannelDetail(channelId);
|
||||
setChannel(detail);
|
||||
} catch (err) {
|
||||
console.error("useChannelDetail:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return { channel, loading, fetch };
|
||||
export function useChannelDetail(channelId: string | null) {
|
||||
return useQuery<DashboardChannelDetail>({
|
||||
queryKey: ["dashboard-channel", channelId],
|
||||
queryFn: () => dashboardApi.getChannelDetail(channelId!),
|
||||
enabled: !!channelId,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,38 +1,15 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { voiceApi } from "@/lib/api";
|
||||
import type { Guild } from "@/lib/types";
|
||||
|
||||
interface UseGuildsReturn {
|
||||
guilds: Guild[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the list of available Discord guilds.
|
||||
*/
|
||||
export function useGuilds(): UseGuildsReturn {
|
||||
const [guilds, setGuilds] = useState<Guild[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchGuilds = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
voiceApi
|
||||
.getGuilds()
|
||||
.then(setGuilds)
|
||||
.catch((err: unknown) =>
|
||||
setError(err instanceof Error ? err.message : "Failed to load guilds"),
|
||||
)
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchGuilds();
|
||||
}, [fetchGuilds]);
|
||||
|
||||
return { guilds, loading, error, refetch: fetchGuilds };
|
||||
export function useGuilds() {
|
||||
return useQuery<Guild[]>({
|
||||
queryKey: ["guilds"],
|
||||
queryFn: () => voiceApi.getGuilds(),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { voiceApi } from "@/lib/api";
|
||||
import type { MediaState } from "@/lib/types";
|
||||
@@ -11,74 +11,60 @@ type WsHook = {
|
||||
) => () => void;
|
||||
};
|
||||
|
||||
interface UseMediaStateReturn {
|
||||
mediaState: MediaState | null;
|
||||
refresh: () => void;
|
||||
queue: (url: string) => void;
|
||||
skip: () => void;
|
||||
stop: () => void;
|
||||
setVolume: (value: number | readonly number[]) => void;
|
||||
export function useMediaState() {
|
||||
return useQuery<MediaState>({
|
||||
queryKey: ["media-state"],
|
||||
queryFn: () => voiceApi.getMediaStatus(),
|
||||
retry: false,
|
||||
refetchInterval: 10_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useMediaState(): UseMediaStateReturn {
|
||||
const [mediaState, setMediaState] = useState<MediaState | null>(null);
|
||||
export function useMediaQueue() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (url: string) => voiceApi.mediaQueue(url, "music"),
|
||||
onSuccess: (data) => qc.setQueryData(["media-state"], data),
|
||||
});
|
||||
}
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const state = await voiceApi.getMediaStatus();
|
||||
setMediaState(state);
|
||||
} catch (err) {
|
||||
console.error("useMediaState/refresh:", err);
|
||||
}
|
||||
}, []);
|
||||
export function useMediaSkip() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () => voiceApi.mediaSkip(),
|
||||
onSuccess: (data) => qc.setQueryData(["media-state"], data),
|
||||
});
|
||||
}
|
||||
|
||||
const queue = useCallback(async (url: string) => {
|
||||
try {
|
||||
const state = await voiceApi.mediaQueue(url, "music");
|
||||
setMediaState(state);
|
||||
} catch (err) {
|
||||
console.error("useMediaState/queue:", err);
|
||||
}
|
||||
}, []);
|
||||
export function useMediaStop() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () => voiceApi.mediaStop(),
|
||||
onSuccess: (data) => qc.setQueryData(["media-state"], data),
|
||||
});
|
||||
}
|
||||
|
||||
const skip = useCallback(async () => {
|
||||
try {
|
||||
const state = await voiceApi.mediaSkip();
|
||||
setMediaState(state);
|
||||
} catch (err) {
|
||||
console.error("useMediaState/skip:", err);
|
||||
}
|
||||
}, []);
|
||||
export function useMediaVolume() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (volume: number) => voiceApi.mediaVolume(volume),
|
||||
onSuccess: (data) => qc.setQueryData(["media-state"], data),
|
||||
});
|
||||
}
|
||||
|
||||
const stop = useCallback(async () => {
|
||||
try {
|
||||
const state = await voiceApi.mediaStop();
|
||||
setMediaState(state);
|
||||
} catch (err) {
|
||||
console.error("useMediaState/stop:", err);
|
||||
}
|
||||
}, []);
|
||||
/** Subscribe to WS media_state events to keep cache fresh */
|
||||
export function useMediaWsSync(ws: WsHook) {
|
||||
const qc = useQueryClient();
|
||||
useEffectFn(ws, qc);
|
||||
}
|
||||
|
||||
const setVolume = useCallback(async (value: number | readonly number[]) => {
|
||||
const vol = Array.isArray(value) ? value[0] : value;
|
||||
try {
|
||||
const state = await voiceApi.mediaVolume(vol);
|
||||
setMediaState(state);
|
||||
} catch (err) {
|
||||
console.error("useMediaState/setVolume:", err);
|
||||
}
|
||||
}, []);
|
||||
import { useEffect } from "react";
|
||||
|
||||
function useEffectFn(ws: WsHook, qc: ReturnType<typeof useQueryClient>) {
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return { mediaState, refresh, queue, skip, stop, setVolume };
|
||||
}
|
||||
|
||||
export function useMediaWsSubscription(
|
||||
ws: WsHook,
|
||||
onState: (state: MediaState) => void,
|
||||
) {
|
||||
return ws.on("media_state", (data) => onState(data as MediaState));
|
||||
const unsub = ws.on("media_state", (data) => {
|
||||
qc.setQueryData(["media-state"], data as MediaState);
|
||||
});
|
||||
return unsub;
|
||||
}, [ws, qc]);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect } from "react";
|
||||
|
||||
import { messagesApi, voiceApi } from "@/lib/api";
|
||||
import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types";
|
||||
@@ -11,262 +12,210 @@ type WsHook = {
|
||||
) => () => void;
|
||||
};
|
||||
|
||||
// ── Messages list ───────────────────────────────
|
||||
// ── Query keys factory ───────────────────────────
|
||||
|
||||
interface UseMessagesReturn {
|
||||
messages: MessageRecord[];
|
||||
loading: boolean;
|
||||
loadingMore: boolean;
|
||||
error: string | null;
|
||||
hasMore: boolean;
|
||||
refetch: () => void;
|
||||
loadMore: () => void;
|
||||
prepend: (msg: MessageRecord) => void;
|
||||
update: (msg: MessageRecord) => void;
|
||||
remove: (id: string) => void;
|
||||
}
|
||||
const msgKeys = {
|
||||
list: (guildId: string, channelId?: string) =>
|
||||
["messages", guildId, channelId ?? "__all__"] as const,
|
||||
images: (guildId: string) => ["messages-images", guildId] as const,
|
||||
review: (channelId?: string) =>
|
||||
["messages-review", channelId ?? "__all__"] as const,
|
||||
detail: (id: string) => ["message-detail", id] as const,
|
||||
};
|
||||
|
||||
export function useMessages(
|
||||
guildId: string,
|
||||
channelId?: string,
|
||||
): UseMessagesReturn {
|
||||
const [messages, setMessages] = useState<MessageRecord[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [cursor, setCursor] = useState<string | null>(null);
|
||||
const [hasMore, setHasMore] = useState(true);
|
||||
// ── Messages list (paginated, cursor-based) ──────
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
if (!guildId) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
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,
|
||||
);
|
||||
setMessages(result.data);
|
||||
setCursor(result.nextCursor);
|
||||
setHasMore(result.nextCursor !== null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to load messages");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [guildId, channelId]);
|
||||
return result.data;
|
||||
},
|
||||
enabled: !!guildId,
|
||||
});
|
||||
}
|
||||
|
||||
const loadMore = useCallback(async () => {
|
||||
if (!cursor || loadingMore) return;
|
||||
setLoadingMore(true);
|
||||
try {
|
||||
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 };
|
||||
},
|
||||
enabled: !!guildId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useLoadMore() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
guildId,
|
||||
channelId,
|
||||
cursor,
|
||||
}: {
|
||||
guildId: string;
|
||||
channelId?: string;
|
||||
cursor: string;
|
||||
}) => {
|
||||
const result = await messagesApi.list(
|
||||
guildId,
|
||||
50,
|
||||
channelId || undefined,
|
||||
cursor,
|
||||
);
|
||||
setMessages((prev) => [...prev, ...result.data]);
|
||||
setCursor(result.nextCursor);
|
||||
setHasMore(result.nextCursor !== null);
|
||||
} catch (err) {
|
||||
console.error("useMessages/loadMore:", err);
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}, [cursor, loadingMore, guildId, channelId]);
|
||||
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,
|
||||
);
|
||||
qc.setQueryData([...key, "cursor"], {
|
||||
cursor: data.cursor,
|
||||
hasMore: data.cursor !== null,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Auto-fetch when guildId/channelId changes
|
||||
useEffect(() => {
|
||||
fetch();
|
||||
}, [fetch]);
|
||||
// ── Channels list ────────────────────────────────
|
||||
|
||||
const prepend = useCallback((msg: MessageRecord) => {
|
||||
setMessages((prev) => [msg, ...prev]);
|
||||
}, []);
|
||||
export function useTextChannels(guildId: string) {
|
||||
return useQuery<Channel[]>({
|
||||
queryKey: ["text-channels", guildId],
|
||||
queryFn: () => voiceApi.getTextChannels(guildId),
|
||||
enabled: !!guildId,
|
||||
});
|
||||
}
|
||||
|
||||
const update = useCallback((msg: MessageRecord) => {
|
||||
setMessages((prev) => prev.map((m) => (m.id === msg.id ? msg : m)));
|
||||
}, []);
|
||||
// ── Search ───────────────────────────────────────
|
||||
|
||||
const remove = useCallback((id: string) => {
|
||||
setMessages((prev) => prev.filter((m) => m.id !== id));
|
||||
}, []);
|
||||
export function useSearch() {
|
||||
return useQuery<MessageRecord[]>({
|
||||
queryKey: ["messages-search"],
|
||||
queryFn: () => Promise.resolve([]),
|
||||
enabled: false,
|
||||
});
|
||||
}
|
||||
|
||||
// ── Images ───────────────────────────────────────
|
||||
|
||||
export function useImages(guildId: string) {
|
||||
return useQuery<MessageRecord[]>({
|
||||
queryKey: msgKeys.images(guildId),
|
||||
queryFn: 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 () => {
|
||||
const result = await messagesApi.getReview(50, channelId || undefined);
|
||||
return result.results;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ── 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,
|
||||
);
|
||||
return res.data;
|
||||
},
|
||||
enabled: !!id && !!detail.data?.channel_id,
|
||||
});
|
||||
return {
|
||||
messages,
|
||||
loading,
|
||||
loadingMore,
|
||||
error,
|
||||
hasMore,
|
||||
refetch: fetch,
|
||||
loadMore,
|
||||
prepend,
|
||||
update,
|
||||
remove,
|
||||
message: detail.data ?? null,
|
||||
attachments: attachments.data ?? [],
|
||||
loading: detail.isLoading || attachments.isLoading,
|
||||
error: detail.error,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Channels list ───────────────────────────────
|
||||
// ── Mutations ────────────────────────────────────
|
||||
|
||||
interface UseTextChannelsReturn {
|
||||
channels: Channel[];
|
||||
loading: boolean;
|
||||
export function useReanalyze() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => messagesApi.reanalyze(id),
|
||||
});
|
||||
}
|
||||
|
||||
export function useTextChannels(guildId: string): UseTextChannelsReturn {
|
||||
const [channels, setChannels] = useState<Channel[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
export function useReanalyzeBatch() {
|
||||
return useMutation({
|
||||
mutationFn: (guildId: string) => messagesApi.reanalyzeBatch(guildId),
|
||||
});
|
||||
}
|
||||
|
||||
// ── WS sync helpers ──────────────────────────────
|
||||
|
||||
export function useMessagesWsSync(ws: WsHook, guildId: string) {
|
||||
const qc = useQueryClient();
|
||||
useEffect(() => {
|
||||
if (!guildId) return;
|
||||
voiceApi
|
||||
.getTextChannels(guildId)
|
||||
.then(setChannels)
|
||||
.catch((err) => console.error("useTextChannels:", err))
|
||||
.finally(() => setLoading(false));
|
||||
}, [guildId]);
|
||||
|
||||
return { channels, loading };
|
||||
}
|
||||
|
||||
// ── Search ──────────────────────────────────────
|
||||
|
||||
interface UseSearchReturn {
|
||||
results: MessageRecord[] | null;
|
||||
searching: boolean;
|
||||
search: (query: string) => void;
|
||||
}
|
||||
|
||||
export function useSearch(): UseSearchReturn {
|
||||
const [results, setResults] = useState<MessageRecord[] | null>(null);
|
||||
const [searching, setSearching] = useState(false);
|
||||
|
||||
const search = useCallback(async (query: string) => {
|
||||
if (!query.trim()) {
|
||||
setResults(null);
|
||||
return;
|
||||
}
|
||||
setSearching(true);
|
||||
try {
|
||||
const result = await messagesApi.search(query, 50);
|
||||
setResults(result.results);
|
||||
} catch (err) {
|
||||
console.error("useSearch:", err);
|
||||
setResults([]);
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return { results, searching, search };
|
||||
}
|
||||
|
||||
// ── Images ──────────────────────────────────────
|
||||
|
||||
export function useImages(guildId: string) {
|
||||
const [images, setImages] = useState<MessageRecord[]>([]);
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
if (!guildId) return;
|
||||
try {
|
||||
const result = await messagesApi.getImages(guildId, 50);
|
||||
setImages(result.data);
|
||||
} catch (err) {
|
||||
console.error("useImages:", err);
|
||||
}
|
||||
}, [guildId]);
|
||||
|
||||
return { images, refetch: fetch };
|
||||
}
|
||||
|
||||
// ── Review ──────────────────────────────────────
|
||||
|
||||
export function useReview(channelId?: string) {
|
||||
const [reviews, setReviews] = useState<MessageRecord[]>([]);
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
try {
|
||||
const result = await messagesApi.getReview(50, channelId || undefined);
|
||||
setReviews(result.results);
|
||||
} catch (err) {
|
||||
console.error("useReview:", err);
|
||||
}
|
||||
}, [channelId]);
|
||||
|
||||
return { reviews, refetch: fetch };
|
||||
}
|
||||
|
||||
// ── Detail ──────────────────────────────────────
|
||||
|
||||
interface UseMessageDetailReturn {
|
||||
message: MessageRecord | null;
|
||||
attachments: AttachmentRecord[];
|
||||
loading: boolean;
|
||||
open: (id: string) => void;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export function useMessageDetail(): UseMessageDetailReturn {
|
||||
const [message, setMessage] = useState<MessageRecord | null>(null);
|
||||
const [attachments, setAttachments] = useState<AttachmentRecord[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const open = useCallback(async (id: string) => {
|
||||
setLoading(true);
|
||||
setAttachments([]);
|
||||
try {
|
||||
const detail = await messagesApi.getDetail(id);
|
||||
setMessage(detail);
|
||||
if (detail.channel_id && id) {
|
||||
messagesApi
|
||||
.getAttachments(detail.channel_id, 10)
|
||||
.then((res) => setAttachments(res.data))
|
||||
.catch((err) => console.error("useMessageDetail/attachments:", err));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("useMessageDetail:", err);
|
||||
setMessage(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const close = useCallback(() => setMessage(null), []);
|
||||
|
||||
return { message, attachments, loading, open, close };
|
||||
}
|
||||
|
||||
// ── WS Subscription helper ──────────────────────
|
||||
|
||||
export function useMessageWsSubscription(
|
||||
ws: WsHook | undefined,
|
||||
guildId: string,
|
||||
onCreated: (msg: MessageRecord) => void,
|
||||
onUpdated: (msg: MessageRecord) => void,
|
||||
onDeleted: (id: string) => void,
|
||||
onAnalyzed: (msg: MessageRecord) => void,
|
||||
) {
|
||||
useEffect(() => {
|
||||
if (!ws || !guildId) return;
|
||||
const unsub1 = ws.on("message_created", (data) =>
|
||||
onCreated(data as MessageRecord),
|
||||
);
|
||||
const unsub2 = ws.on("message_updated", (data) =>
|
||||
onUpdated(data as MessageRecord),
|
||||
);
|
||||
const unsub3 = ws.on("message_deleted", (data) =>
|
||||
onDeleted(data as unknown as string),
|
||||
);
|
||||
const unsub4 = ws.on("message_analyzed", (data) =>
|
||||
onAnalyzed(data as MessageRecord),
|
||||
);
|
||||
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],
|
||||
);
|
||||
});
|
||||
const unsub2 = ws.on("message_updated", (data) => {
|
||||
qc.setQueryData<MessageRecord[]>(key, (old) =>
|
||||
old
|
||||
? old.map((m) =>
|
||||
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
|
||||
)
|
||||
: old,
|
||||
);
|
||||
});
|
||||
const unsub3 = ws.on("message_deleted", (data) => {
|
||||
qc.setQueryData<MessageRecord[]>(key, (old) =>
|
||||
old ? old.filter((m) => m.id !== (data as unknown as string)) : old,
|
||||
);
|
||||
});
|
||||
const unsub4 = ws.on("message_analyzed", (data) => {
|
||||
qc.setQueryData<MessageRecord[]>(key, (old) =>
|
||||
old
|
||||
? old.map((m) =>
|
||||
m.id === (data as MessageRecord).id ? (data as MessageRecord) : m,
|
||||
)
|
||||
: old,
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
unsub1();
|
||||
unsub2();
|
||||
unsub3();
|
||||
unsub4();
|
||||
};
|
||||
}, [ws, guildId, onCreated, onUpdated, onDeleted, onAnalyzed]);
|
||||
}, [ws, guildId, qc]);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { recordingsApi } from "@/lib/api";
|
||||
import type { VoiceRecording } from "@/lib/types";
|
||||
@@ -11,55 +12,33 @@ type WsHook = {
|
||||
) => () => void;
|
||||
};
|
||||
|
||||
interface UseRecordingsReturn {
|
||||
recordings: VoiceRecording[];
|
||||
loading: boolean;
|
||||
refresh: () => void;
|
||||
remove: (id: string) => void;
|
||||
prepend: (rec: VoiceRecording) => void;
|
||||
export function useRecordings() {
|
||||
return useQuery<VoiceRecording[]>({
|
||||
queryKey: ["recordings"],
|
||||
queryFn: async () => {
|
||||
const res = await recordingsApi.list(50);
|
||||
return res.items;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useRecordings(): UseRecordingsReturn {
|
||||
const [recordings, setRecordings] = useState<VoiceRecording[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await recordingsApi.list(50);
|
||||
setRecordings(result.items);
|
||||
} catch (err) {
|
||||
console.error("useRecordings/refresh:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
export function useDeleteRecording() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => recordingsApi.delete(id),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["recordings"] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useRecordingsWsSync(ws: WsHook) {
|
||||
const qc = useQueryClient();
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const remove = useCallback(async (id: string) => {
|
||||
try {
|
||||
await recordingsApi.delete(id);
|
||||
setRecordings((prev) => prev.filter((r) => r.id !== id));
|
||||
} catch (err) {
|
||||
console.error("useRecordings/remove:", err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const prepend = useCallback((rec: VoiceRecording) => {
|
||||
setRecordings((prev) => [rec, ...prev]);
|
||||
}, []);
|
||||
|
||||
return { recordings, loading, refresh, remove, prepend };
|
||||
}
|
||||
|
||||
export function useRecordingsWsSubscription(
|
||||
ws: WsHook,
|
||||
onUploaded: (rec: VoiceRecording) => void,
|
||||
) {
|
||||
return ws.on("voice_recording_uploaded", (data) =>
|
||||
onUploaded(data as VoiceRecording),
|
||||
);
|
||||
const unsub = ws.on("voice_recording_uploaded", (data) => {
|
||||
const rec = data as VoiceRecording;
|
||||
qc.setQueryData<VoiceRecording[]>(["recordings"], (old) =>
|
||||
old ? [rec, ...old] : [rec],
|
||||
);
|
||||
});
|
||||
return unsub;
|
||||
}, [ws, qc]);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { voiceApi } from "@/lib/api";
|
||||
@@ -11,37 +12,15 @@ type WsHook = {
|
||||
) => () => void;
|
||||
};
|
||||
|
||||
interface UseVoiceStatusReturn {
|
||||
voiceStatus: VoiceStatus | null;
|
||||
refresh: () => void;
|
||||
export function useVoiceStatus() {
|
||||
return useQuery<VoiceStatus>({
|
||||
queryKey: ["voice-status"],
|
||||
queryFn: () => voiceApi.getStatus(),
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useVoiceStatus(): UseVoiceStatusReturn {
|
||||
const [voiceStatus, setVoiceStatus] = useState<VoiceStatus | null>(null);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const status = await voiceApi.getStatus();
|
||||
setVoiceStatus(status);
|
||||
} catch (err) {
|
||||
console.error("useVoiceStatus:", err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return { voiceStatus, refresh };
|
||||
}
|
||||
|
||||
interface UseVoiceChannelsReturn {
|
||||
channels: Array<{ id: string; name: string }>;
|
||||
loading: boolean;
|
||||
fetch: (guildId: string) => void;
|
||||
}
|
||||
|
||||
export function useVoiceChannels(): UseVoiceChannelsReturn {
|
||||
export function useVoiceChannels() {
|
||||
const [channels, setChannels] = useState<Array<{ id: string; name: string }>>(
|
||||
[],
|
||||
);
|
||||
@@ -63,12 +42,7 @@ export function useVoiceChannels(): UseVoiceChannelsReturn {
|
||||
return { channels, loading, fetch };
|
||||
}
|
||||
|
||||
interface UseSpeakersReturn {
|
||||
speakers: ActiveSpeaker[];
|
||||
subscribe: (ws: WsHook) => () => void;
|
||||
}
|
||||
|
||||
export function useSpeakers(): UseSpeakersReturn {
|
||||
export function useSpeakers() {
|
||||
const [speakers, setSpeakers] = useState<ActiveSpeaker[]>([]);
|
||||
|
||||
const subscribe = useCallback((ws: WsHook) => {
|
||||
@@ -92,3 +66,34 @@ export function useSpeakers(): UseSpeakersReturn {
|
||||
|
||||
return { speakers, subscribe };
|
||||
}
|
||||
|
||||
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"] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useVoiceDisconnect() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () => voiceApi.disconnect(),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-status"] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useMicTransmit() {
|
||||
return useMutation({
|
||||
mutationFn: (active: boolean) =>
|
||||
voiceApi.sendCommand(
|
||||
active ? "voice:transmit:start" : "voice:transmit:stop",
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user