feat(frontend): rebuild chatbot UI to match backend — wider panel, guild context, Indonesian

- Chatbot bubble: 220px → 320px wide, 440px tall; proper header with
  drag handle; quick-prompt row when chat is closed
- ChatPanel: show ALL history (not last 8), Indonesian placeholder/empty
  state/error copy (backend speaks Indonesian), timestamps (id-ID),
  clear-history button, typing indicator bubbles, Enter-to-send
- Send active guildId as context so backend answers reference the real
  server (serverInsights path in chatbot.service)
- GuildId sync from layout → ChatbotProvider via ChatbotGuildSync
- chatbotApi.send(message, guildId) → POST /api/chat {message, context}
  matching BE zod schema (guildId optional)
This commit is contained in:
asepharyana
2026-08-03 06:04:25 +07:00
parent 03d59f0738
commit 2b815e156c
5 changed files with 152 additions and 86 deletions
@@ -14,10 +14,19 @@ import { MiniPlayer } from "@/components/media/mini-player";
import { MediaPlayerProvider } from "@/lib/hooks/use-media-player"; import { MediaPlayerProvider } from "@/lib/hooks/use-media-player";
import { useWebSocket, WsProvider } from "@/lib/ws/context"; import { useWebSocket, WsProvider } from "@/lib/ws/context";
function ChatbotGuildSync({ guildId }: { guildId: string }) {
const { setGuildId } = useChatbot();
useEffect(() => {
setGuildId(guildId);
}, [guildId, setGuildId]);
return null;
}
function ChatbotExpressionSync() { function ChatbotExpressionSync() {
const ws = useWebSocket(); const ws = useWebSocket();
const { setExpression } = useChatbot(); const { setExpression } = useChatbot();
useEffect(() => { useEffect(() => {
const unsub1 = ws.on("message_created", (data: any) => { const unsub1 = ws.on("message_created", (data: any) => {
if (data.ai_status === "flagged" || data.ai_status === "warn") { if (data.ai_status === "flagged" || data.ai_status === "warn") {
@@ -58,6 +67,7 @@ export default function DashboardLayout({
<WsProvider> <WsProvider>
<MediaPlayerProvider> <MediaPlayerProvider>
<ChatbotProvider> <ChatbotProvider>
<ChatbotGuildSync guildId={guildId} />
<ChatbotExpressionSync /> <ChatbotExpressionSync />
<div className="min-h-screen bg-canvas"> <div className="min-h-screen bg-canvas">
<TopNav /> <TopNav />
@@ -1,6 +1,6 @@
"use client"; "use client";
import { Send } from "lucide-react"; import { Eraser, Send } from "lucide-react";
import { useEffect, useRef } from "react"; import { useEffect, useRef } from "react";
import { useChatbot } from "./chatbot-context"; import { useChatbot } from "./chatbot-context";
@@ -8,8 +8,17 @@ interface ChatPanelProps {
inputRef?: React.RefObject<HTMLInputElement | null>; inputRef?: React.RefObject<HTMLInputElement | null>;
} }
function formatTime(ts: string): string {
const d = new Date(ts);
if (Number.isNaN(d.getTime())) return "";
return d.toLocaleTimeString("id-ID", {
hour: "2-digit",
minute: "2-digit",
});
}
export function ChatPanel({ inputRef: externalInputRef }: ChatPanelProps) { export function ChatPanel({ inputRef: externalInputRef }: ChatPanelProps) {
const { messages, sendMessage, isTyping } = useChatbot(); const { messages, sendMessage, clearMessages, isTyping } = useChatbot();
const listRef = useRef<HTMLDivElement>(null); const listRef = useRef<HTMLDivElement>(null);
const internalInputRef = useRef<HTMLInputElement>(null); const internalInputRef = useRef<HTMLInputElement>(null);
const inputRef = externalInputRef ?? internalInputRef; const inputRef = externalInputRef ?? internalInputRef;
@@ -20,12 +29,12 @@ export function ChatPanel({ inputRef: externalInputRef }: ChatPanelProps) {
if (listRef.current) { if (listRef.current) {
listRef.current.scrollTop = listRef.current.scrollHeight; listRef.current.scrollTop = listRef.current.scrollHeight;
} }
}, [messages]); }, [messages, isTyping]);
const handleSubmit = (e: React.FormEvent) => { const handleSubmit = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
const input = inputRef.current; const input = inputRef.current;
if (!input || !input.value.trim()) return; if (!input || !input.value.trim() || isTyping) return;
sendMessage(input.value); sendMessage(input.value);
input.value = ""; input.value = "";
}; };
@@ -33,44 +42,54 @@ export function ChatPanel({ inputRef: externalInputRef }: ChatPanelProps) {
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
{/* Chat messages */} {/* Chat messages */}
<div ref={listRef} className="flex-1 overflow-y-auto px-2 py-1 space-y-1"> <div
{messages.length === 0 && ( ref={listRef}
<div className="flex items-center justify-center h-full"> className="flex-1 overflow-y-auto px-2 py-1.5 space-y-1.5"
<p className="text-[10px] text-text-secondary/40"> >
Ask chatbot anything {messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full gap-1 px-3 text-center">
<p className="text-[10px] text-text-secondary/50">
Halo! 👋 Aku tau soal server ini pesan, flag, dan aktivitas.
</p>
<p className="text-[10px] text-text-secondary/30">
Coba tanya: "Gimana suasana server hari ini?"
</p> </p>
</div> </div>
)} ) : (
{messages.slice(-8).map((msg, i) => ( messages.map((msg, i) => (
<div <div
key={`${msg.timestamp}-${i}`} key={`${msg.timestamp}-${i}`}
className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`} className={`flex flex-col ${msg.role === "user" ? "items-end" : "items-start"}`}
>
<span
className={`text-[10px] px-2 py-1 rounded-lg max-w-[85%] leading-relaxed ${
msg.role === "user"
? "bg-primary/20 text-text-primary"
: "glass text-text-secondary"
}`}
> >
{msg.content} <div
</span> className={`text-[11px] px-2.5 py-1.5 rounded-xl max-w-[85%] leading-relaxed whitespace-pre-wrap break-words ${
</div> msg.role === "user"
))} ? "bg-primary/20 text-text-primary rounded-br-sm"
: "glass text-text-secondary rounded-bl-sm"
}`}
>
{msg.content}
</div>
<span className="mt-0.5 px-1 text-[9px] text-text-secondary/30">
{formatTime(msg.timestamp)}
</span>
</div>
))
)}
{isTyping && ( {isTyping && (
<div className="flex justify-start"> <div className="flex justify-start">
<div className="glass rounded-lg px-2 py-1"> <div className="glass rounded-xl rounded-bl-sm px-2.5 py-2">
<span className="inline-flex gap-0.5"> <span className="inline-flex gap-1">
<span <span
className="size-1 rounded-full bg-text-secondary animate-bounce" className="size-1.5 rounded-full bg-text-secondary animate-bounce"
style={{ animationDelay: "0ms" }} style={{ animationDelay: "0ms" }}
/> />
<span <span
className="size-1 rounded-full bg-text-secondary animate-bounce" className="size-1.5 rounded-full bg-text-secondary animate-bounce"
style={{ animationDelay: "150ms" }} style={{ animationDelay: "150ms" }}
/> />
<span <span
className="size-1 rounded-full bg-text-secondary animate-bounce" className="size-1.5 rounded-full bg-text-secondary animate-bounce"
style={{ animationDelay: "300ms" }} style={{ animationDelay: "300ms" }}
/> />
</span> </span>
@@ -82,20 +101,32 @@ export function ChatPanel({ inputRef: externalInputRef }: ChatPanelProps) {
{/* Input bar */} {/* Input bar */}
<form <form
onSubmit={handleSubmit} onSubmit={handleSubmit}
className="flex items-center gap-1 px-2 py-1.5 border-t border-glass-border shrink-0" className="flex items-center gap-1.5 px-2 py-1.5 border-t border-glass-border shrink-0"
> >
<input <input
ref={inputRef} ref={inputRef}
type="text" type="text"
placeholder="Ask chatbot..." placeholder="Tanya chatbot"
className="flex-1 bg-transparent text-[10px] text-text-primary placeholder-text-secondary/30 outline-none" className="flex-1 bg-transparent text-[11px] text-text-primary placeholder-text-secondary/30 outline-none"
disabled={isTyping} disabled={isTyping}
/> />
{messages.length > 0 && (
<button
type="button"
onClick={() => void clearMessages()}
className="size-6 flex items-center justify-center rounded hover:bg-glass-bg transition-colors disabled:opacity-40"
disabled={isTyping}
aria-label="Hapus riwayat chat"
title="Hapus riwayat"
>
<Eraser className="size-3 text-text-secondary/50 hover:text-destructive" />
</button>
)}
<button <button
type="submit" type="submit"
className="size-5 flex items-center justify-center disabled:opacity-40" className="size-6 flex items-center justify-center rounded bg-primary/15 hover:bg-primary/25 transition-colors disabled:opacity-40"
disabled={isTyping} disabled={isTyping}
aria-label="Send message" aria-label="Kirim pesan"
> >
<Send className="size-3 text-primary" /> <Send className="size-3 text-primary" />
</button> </button>
@@ -1,6 +1,6 @@
"use client"; "use client";
import { Bot, MessageCircle, Minimize2 } from "lucide-react"; import { Bot, MessageCircle, Minimize2, PanelLeft } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { ChatPanel } from "./chat-panel"; import { ChatPanel } from "./chat-panel";
import { ChatbotCanvas } from "./chatbot-canvas"; import { ChatbotCanvas } from "./chatbot-canvas";
@@ -34,7 +34,6 @@ export function ChatbotContainer() {
// Focus input when chat opens // Focus input when chat opens
useEffect(() => { useEffect(() => {
if (chatOpen) { if (chatOpen) {
// Small delay for the animation
const id = setTimeout(() => inputRef.current?.focus(), 150); const id = setTimeout(() => inputRef.current?.focus(), 150);
return () => clearTimeout(id); return () => clearTimeout(id);
} }
@@ -52,9 +51,9 @@ export function ChatbotContainer() {
{/* Main chatbot bubble */} {/* Main chatbot bubble */}
<div <div
className={`glass-intense rounded-2xl overflow-hidden transition-all duration-200 ${ className={`glass-intense rounded-2xl overflow-hidden transition-all duration-200 ${
minimized ? "w-14 h-14 cursor-pointer" : "w-[220px]" minimized ? "w-14 h-14 cursor-pointer" : "w-[320px]"
}`} }`}
style={{ height: minimized ? 56 : 320 }} style={{ height: minimized ? 56 : 440 }}
> >
{minimized ? ( {minimized ? (
<button <button
@@ -71,32 +70,30 @@ export function ChatbotContainer() {
{/* Drag handle + controls */} {/* Drag handle + controls */}
{/* biome-ignore lint/a11y/noStaticElementInteractions: drag handle — mouse-only gesture, keyboard users use the buttons in this header */} {/* biome-ignore lint/a11y/noStaticElementInteractions: drag handle — mouse-only gesture, keyboard users use the buttons in this header */}
<div <div
className="flex items-center justify-between px-3 py-1.5 border-b border-glass-border cursor-grab active:cursor-grabbing" className="flex items-center justify-between px-3 py-2 border-b border-glass-border cursor-grab active:cursor-grabbing"
onMouseDown={handleMouseDown} onMouseDown={handleMouseDown}
> >
<span className="text-[10px] font-semibold text-text-secondary tracking-wide uppercase"> <span className="flex items-center gap-1.5 text-[10px] font-semibold text-text-secondary tracking-wide uppercase">
<Bot className="size-3.5 text-primary" />
Chatbot Chatbot
</span> </span>
<div className="flex items-center gap-1"> <div className="flex items-center gap-0.5">
<button <button
type="button" type="button"
onClick={() => setChatOpen(!chatOpen)} onClick={() => setChatOpen(!chatOpen)}
className="size-5 flex items-center justify-center rounded hover:bg-glass-bg transition-colors" className="size-6 flex items-center justify-center rounded hover:bg-glass-bg transition-colors"
aria-label={chatOpen ? "Close chat" : "Open chat"} aria-label={chatOpen ? "Sembunyikan chat" : "Buka chat"}
title={chatOpen ? "Sembunyikan chat" : "Buka chat"}
> >
<MessageCircle className="size-3 text-text-secondary/60 hover:text-text-primary" /> <PanelLeft className="size-3.5 text-text-secondary/60 hover:text-text-primary" />
</button> </button>
<button <button
type="button" type="button"
onClick={() => setMinimized(true)} onClick={() => setMinimized(true)}
className="size-5 flex items-center justify-center rounded hover:bg-glass-bg transition-colors" className="size-6 flex items-center justify-center rounded hover:bg-glass-bg transition-colors"
aria-label="Minimize chatbot" aria-label="Kecilkan chatbot"
> >
{minimized ? ( <Minimize2 className="size-3.5 text-text-secondary/60 hover:text-text-primary" />
<Bot className="size-3 text-text-secondary/60 hover:text-text-primary" />
) : (
<Minimize2 className="size-3 text-text-secondary/60 hover:text-text-primary" />
)}
</button> </button>
</div> </div>
</div> </div>
@@ -109,11 +106,23 @@ export function ChatbotContainer() {
{/* Chat panel (expandable) */} {/* Chat panel (expandable) */}
<div <div
className={`transition-all duration-200 overflow-hidden ${ className={`transition-all duration-200 overflow-hidden ${
chatOpen ? "h-[130px]" : "h-0" chatOpen ? "h-[248px]" : "h-0"
}`} }`}
> >
<ChatPanel inputRef={inputRef} /> <ChatPanel inputRef={inputRef} />
</div> </div>
{/* Quick prompt row when chat is closed */}
{!chatOpen && (
<button
type="button"
onClick={() => setChatOpen(true)}
className="mx-3 mb-2 flex items-center gap-2 rounded-lg border border-glass-border px-2.5 py-1.5 text-[10px] text-text-secondary/60 transition-colors hover:bg-glass-bg hover:text-text-primary"
>
<MessageCircle className="size-3 shrink-0 text-primary/60" />
Tanya soal server, pesan, atau statistik
</button>
)}
</> </>
)} )}
</div> </div>
@@ -51,6 +51,10 @@ interface ChatbotContextValue {
sendMessage: (content: string) => Promise<void>; sendMessage: (content: string) => Promise<void>;
clearMessages: () => Promise<void>; clearMessages: () => Promise<void>;
isTyping: boolean; isTyping: boolean;
/** Active guild context sent to the backend so answers reference the server */
guildId: string;
setGuildId: (g: string) => void;
} }
const ChatbotContext = createContext<ChatbotContextValue | null>(null); const ChatbotContext = createContext<ChatbotContextValue | null>(null);
@@ -61,6 +65,7 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
const [chatOpen, setChatOpen] = useState(false); const [chatOpen, setChatOpen] = useState(false);
const [messages, setMessages] = useState<ChatbotMessage[]>([]); const [messages, setMessages] = useState<ChatbotMessage[]>([]);
const [isTyping, setIsTyping] = useState(false); const [isTyping, setIsTyping] = useState(false);
const [guildId, setGuildId] = useState("");
const historyFetched = useRef(false); const historyFetched = useRef(false);
// Derived legacy state // Derived legacy state
@@ -104,39 +109,45 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
}); });
}, []); }, []);
const sendMessage = useCallback(async (content: string) => { const sendMessage = useCallback(
if (!content.trim()) return; async (content: string) => {
if (!content.trim()) return;
const userMsg: ChatbotMessage = { const userMsg: ChatbotMessage = {
role: "user", role: "user",
content: content.trim(), content: content.trim(),
timestamp: new Date().toISOString(),
};
setMessages((prev) => [...prev, userMsg]);
setExpression("listening");
setIsTyping(true);
try {
const res = await chatbotApi.send(content.trim());
const botMsg: ChatbotMessage = {
role: "assistant",
content: res.response,
timestamp: res.timestamp ?? new Date().toISOString(),
};
setMessages((prev) => [...prev, botMsg]);
setExpression("happy");
} catch {
const errorMsg: ChatbotMessage = {
role: "assistant",
content: "Sorry, I couldn't process that request. Please try again.",
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
}; };
setMessages((prev) => [...prev, errorMsg]); setMessages((prev) => [...prev, userMsg]);
setExpression("sad"); setExpression("listening");
} finally { setIsTyping(true);
setIsTyping(false);
} try {
}, []); // Send active guild as context so the backend can answer with
// real server insights (serverInsights path in chatbot.service).
const res = await chatbotApi.send(content.trim(), guildId);
const botMsg: ChatbotMessage = {
role: "assistant",
content: res.response,
timestamp: res.timestamp ?? new Date().toISOString(),
};
setMessages((prev) => [...prev, botMsg]);
setExpression("happy");
} catch {
const errorMsg: ChatbotMessage = {
role: "assistant",
content:
"Maaf, aku lagi gagal nyambung ke server. Coba tanya lagi ya 🙏",
timestamp: new Date().toISOString(),
};
setMessages((prev) => [...prev, errorMsg]);
setExpression("sad");
} finally {
setIsTyping(false);
}
},
[guildId],
);
const clearMessages = useCallback(async () => { const clearMessages = useCallback(async () => {
try { try {
@@ -163,6 +174,8 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
sendMessage, sendMessage,
clearMessages, clearMessages,
isTyping, isTyping,
guildId,
setGuildId,
}} }}
> >
{children} {children}
+5 -2
View File
@@ -2,8 +2,11 @@ import type { ChatbotHistoryRow, ChatbotResponse } from "@/lib/types";
import { api } from "./client"; import { api } from "./client";
export const chatbotApi = { export const chatbotApi = {
send: (message: string) => send: (message: string, guildId?: string) =>
api.post<ChatbotResponse>("/api/chat", { message }), api.post<ChatbotResponse>("/api/chat", {
message,
context: guildId ? { guildId } : undefined,
}),
getHistory: () => getHistory: () =>
api.get<{ history: ChatbotHistoryRow[]; total: number }>( api.get<{ history: ChatbotHistoryRow[]; total: number }>(