feat: add app header, sidebar, and mobile navigation components
Deploy to VPS / deploy (push) Failing after 1m45s

- Implemented AppHeader component with theme toggle and connection status.
- Created AppSidebar component for navigation with connection status indicator.
- Added MobileNav component for mobile navigation with responsive design.
- Introduced shared components: DetailStat, EmptyState, ErrorState, LoadingSkeleton, and StatCard for consistent UI.
- Developed hooks for async data fetching: useAsync, useConfig, useDashboard, useGuilds, useMedia, useMessages, useRecordings, and useVoice.
- Added chatbot API functions for sending messages and managing chat history.
This commit is contained in:
asepharyana
2026-07-26 16:14:32 +07:00
parent 726ea8fca5
commit d5a547eb25
35 changed files with 2385 additions and 1733 deletions
+22
View File
@@ -0,0 +1,22 @@
export { useAsync } from "./use-async";
export { useConfig } from "./use-config";
export {
useChannelDetail,
useChannels,
useStats,
useUserDetail,
useUsers,
} from "./use-dashboard";
export { useGuilds } from "./use-guilds";
export { useMediaState, useMediaWsSubscription } from "./use-media";
export {
useImages,
useMessageDetail,
useMessages,
useMessageWsSubscription,
useReview,
useSearch,
useTextChannels,
} from "./use-messages";
export { useRecordings, useRecordingsWsSubscription } from "./use-recordings";
export { useSpeakers, useVoiceChannels, useVoiceStatus } from "./use-voice";
+58
View File
@@ -0,0 +1,58 @@
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 };
}
+21
View File
@@ -0,0 +1,21 @@
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 };
}
@@ -0,0 +1,169 @@
import { useCallback, useState } from "react";
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(): 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);
}
}, []);
return { stats, loading, error, refetch: fetch };
}
// ── Users ───────────────────────────────────────
interface UseUsersReturn {
users: DashboardUser[];
loading: boolean;
search: string;
setSearch: (q: string) => void;
refetch: () => void;
}
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 {
// silently fail
} finally {
setLoading(false);
}
}, []);
const fetchWithSearch = useCallback(() => {
fetch(search || undefined);
}, [fetch, search]);
return {
users,
loading,
search,
setSearch,
refetch: fetchWithSearch,
};
}
// ── 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 {
// silently fail
} 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 {
// ignore
} 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 {
// ignore
} finally {
setLoading(false);
}
}, []);
return { channel, loading, fetch };
}
+38
View File
@@ -0,0 +1,38 @@
import { useCallback, useEffect, useState } from "react";
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 };
}
+80
View File
@@ -0,0 +1,80 @@
import { useCallback, useState } from "react";
import { voiceApi } from "@/lib/api";
import type { MediaState } from "@/lib/types";
import type { WsEventType } from "@/lib/ws/types";
type WsHook = {
on: <E extends WsEventType>(
eventType: E,
handler: (data: unknown) => void,
) => () => 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(): UseMediaStateReturn {
const [mediaState, setMediaState] = useState<MediaState | null>(null);
const refresh = useCallback(async () => {
try {
const state = await voiceApi.getMediaStatus();
setMediaState(state);
} catch {
// ignore
}
}, []);
const queue = useCallback(async (url: string) => {
try {
const state = await voiceApi.mediaQueue(url, "music");
setMediaState(state);
} catch {
// ignore
}
}, []);
const skip = useCallback(async () => {
try {
const state = await voiceApi.mediaSkip();
setMediaState(state);
} catch {
// ignore
}
}, []);
const stop = useCallback(async () => {
try {
const state = await voiceApi.mediaStop();
setMediaState(state);
} catch {
// ignore
}
}, []);
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 {
// ignore
}
}, []);
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));
}
+265
View File
@@ -0,0 +1,265 @@
import { useCallback, useEffect, useState } from "react";
import { messagesApi, voiceApi } from "@/lib/api";
import type { AttachmentRecord, Channel, MessageRecord } from "@/lib/types";
import type { WsEventType } from "@/lib/ws/types";
type WsHook = {
on: <E extends WsEventType>(
eventType: E,
handler: (data: unknown) => void,
) => () => void;
};
// ── Messages list ───────────────────────────────
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;
}
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);
const fetch = useCallback(async () => {
if (!guildId) return;
setLoading(true);
setError(null);
try {
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]);
const loadMore = useCallback(async () => {
if (!cursor || loadingMore) return;
setLoadingMore(true);
try {
const result = await messagesApi.list(
guildId,
50,
channelId || undefined,
cursor,
);
setMessages((prev) => [...prev, ...result.data]);
setCursor(result.nextCursor);
setHasMore(result.nextCursor !== null);
} catch {
// ignore
} finally {
setLoadingMore(false);
}
}, [cursor, loadingMore, guildId, channelId]);
const prepend = useCallback((msg: MessageRecord) => {
setMessages((prev) => [msg, ...prev]);
}, []);
const update = useCallback((msg: MessageRecord) => {
setMessages((prev) => prev.map((m) => (m.id === msg.id ? msg : m)));
}, []);
const remove = useCallback((id: string) => {
setMessages((prev) => prev.filter((m) => m.id !== id));
}, []);
return {
messages,
loading,
loadingMore,
error,
hasMore,
refetch: fetch,
loadMore,
prepend,
update,
remove,
};
}
// ── Channels list ───────────────────────────────
interface UseTextChannelsReturn {
channels: Channel[];
loading: boolean;
}
export function useTextChannels(guildId: string): UseTextChannelsReturn {
const [channels, setChannels] = useState<Channel[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!guildId) return;
voiceApi
.getTextChannels(guildId)
.then(setChannels)
.catch(() => {})
.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 {
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 {
// silently fail
}
}, [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 {
// silently fail
}
}, [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(() => {});
}
} catch {
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),
);
return () => {
unsub1();
unsub2();
unsub3();
unsub4();
};
}, [ws, guildId, onCreated, onUpdated, onDeleted, onAnalyzed]);
}
@@ -0,0 +1,61 @@
import { useCallback, useState } from "react";
import { recordingsApi } from "@/lib/api";
import type { VoiceRecording } from "@/lib/types";
import type { WsEventType } from "@/lib/ws/types";
type WsHook = {
on: <E extends WsEventType>(
eventType: E,
handler: (data: unknown) => void,
) => () => void;
};
interface UseRecordingsReturn {
recordings: VoiceRecording[];
loading: boolean;
refresh: () => void;
remove: (id: string) => void;
prepend: (rec: VoiceRecording) => void;
}
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 {
// ignore
} finally {
setLoading(false);
}
}, []);
const remove = useCallback(async (id: string) => {
try {
await recordingsApi.delete(id);
setRecordings((prev) => prev.filter((r) => r.id !== id));
} catch {
// ignore
}
}, []);
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),
);
}
+89
View File
@@ -0,0 +1,89 @@
import { useCallback, useState } from "react";
import { voiceApi } from "@/lib/api";
import type { ActiveSpeaker, VoiceStatus } from "@/lib/types";
import type { WsEventType } from "@/lib/ws/types";
type WsHook = {
on: <E extends WsEventType>(
eventType: E,
handler: (data: unknown) => void,
) => () => void;
};
interface UseVoiceStatusReturn {
voiceStatus: VoiceStatus | null;
refresh: () => void;
}
export function useVoiceStatus(): UseVoiceStatusReturn {
const [voiceStatus, setVoiceStatus] = useState<VoiceStatus | null>(null);
const refresh = useCallback(async () => {
try {
const status = await voiceApi.getStatus();
setVoiceStatus(status);
} catch {
// ignore
}
}, []);
return { voiceStatus, refresh };
}
interface UseVoiceChannelsReturn {
channels: Array<{ id: string; name: string }>;
loading: boolean;
fetch: (guildId: string) => void;
}
export function useVoiceChannels(): UseVoiceChannelsReturn {
const [channels, setChannels] = useState<Array<{ id: string; name: string }>>(
[],
);
const [loading, setLoading] = useState(false);
const fetch = useCallback(async (guildId: string) => {
setLoading(true);
try {
const ch = await voiceApi.getVoiceChannels(guildId);
setChannels(ch);
} catch {
setChannels([]);
} finally {
setLoading(false);
}
}, []);
return { channels, loading, fetch };
}
interface UseSpeakersReturn {
speakers: ActiveSpeaker[];
subscribe: (ws: WsHook) => () => void;
}
export function useSpeakers(): UseSpeakersReturn {
const [speakers, setSpeakers] = useState<ActiveSpeaker[]>([]);
const subscribe = useCallback((ws: WsHook) => {
const unsub = ws.on("voice_active_user", (data) => {
const speaker = data as ActiveSpeaker;
setSpeakers((prev) => {
const idx = prev.findIndex((s) => s.userId === speaker.userId);
if (idx >= 0) {
const next = [...prev];
next[idx] = speaker;
return next;
}
return [...prev, speaker];
});
});
return () => {
unsub();
setSpeakers([]);
};
}, []);
return { speakers, subscribe };
}