This commit is contained in:
2026-06-30 10:43:11 +07:00
parent d9c8e3930b
commit 6e284e66fa
10 changed files with 247 additions and 51 deletions

View File

@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { apiChat, type ChatConversation, type ChatMessage, type ChatStudent } from '../api';
import { useAuth } from '../auth/AuthContext';
import { onStaffChatMessage, playChatSound } from '../hooks/useStaffChatSocket';
export function ChatWidget() {
const { staff } = useAuth();
@@ -14,12 +15,13 @@ export function ChatWidget() {
const [draft, setDraft] = useState('');
const [sending, setSending] = useState(false);
const [pickerOpen, setPickerOpen] = useState(false);
const [toast, setToast] = useState<{ title: string; body: string } | null>(null);
const listRef = useRef<HTMLDivElement>(null);
const activeRef = useRef<ChatStudent | null>(null);
const openRef = useRef(false);
useEffect(() => {
activeRef.current = active;
}, [active]);
useEffect(() => { activeRef.current = active; }, [active]);
useEffect(() => { openRef.current = open; }, [open]);
const scrollBottom = () => {
requestAnimationFrame(() => {
@@ -32,6 +34,7 @@ export function ChatWidget() {
const loadConversations = useCallback(async () => {
const res = await apiChat.listConversations();
setConversations(res.data);
return res.data;
}, []);
const loadMessages = useCallback(async (studentRkId: number) => {
@@ -46,6 +49,46 @@ export function ChatWidget() {
setStudents(res.data);
}, []);
const showToast = (title: string, body: string) => {
setToast({ title, body });
setTimeout(() => setToast(null), 4500);
};
const handleIncoming = useCallback((msg: ChatMessage) => {
const studentId = Number(msg.studentRkId);
const current = activeRef.current;
void loadConversations();
if (msg.senderRole === 'student') {
playChatSound();
const preview = msg.body?.slice(0, 80) || 'Tin nhắn mới';
if (!openRef.current || !current || Number(current.studentRkId) !== studentId) {
showToast('Sinh viên nhắn tin', preview);
}
}
if (current && Number(current.studentRkId) === studentId) {
setMessages((prev) => {
if (prev.some((m) => m.id === msg.id)) return prev;
return [...prev, msg];
});
scrollBottom();
}
}, [loadConversations]);
useEffect(() => {
const off = onStaffChatMessage(handleIncoming);
return () => { off(); };
}, [handleIncoming]);
useEffect(() => {
if (!staff?.id) return;
loadConversations().catch(console.error);
const t = setInterval(() => loadConversations().catch(console.error), 5000);
return () => clearInterval(t);
}, [staff?.id, loadConversations]);
const pickStudent = async (s: ChatStudent) => {
setActive(s);
setPickerOpen(false);
@@ -69,32 +112,6 @@ export function ChatWidget() {
searchStudents('').catch(console.error);
}, [open, staff?.id, loadConversations, searchStudents]);
useEffect(() => {
if (!staff?.id) return;
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.hostname}:8080/ws?role=teacher&staffId=${staff.id}`;
const ws = new WebSocket(wsUrl);
ws.onmessage = (ev) => {
try {
const payload = JSON.parse(ev.data);
if (payload.event !== 'chat:message') return;
const msg = payload.data as ChatMessage;
loadConversations().catch(console.error);
const current = activeRef.current;
if (current && msg.studentRkId === current.studentRkId) {
setMessages((prev) => {
if (prev.some((m) => m.id === msg.id)) return prev;
return [...prev, msg];
});
scrollBottom();
}
} catch {
/* ignore */
}
};
return () => ws.close();
}, [staff?.id, loadConversations]);
const send = async () => {
if (!active || !draft.trim()) return;
setSending(true);
@@ -113,6 +130,12 @@ export function ChatWidget() {
const dock = (
<div className="chat-dock">
{toast && (
<div className="chat-toast" role="status">
<strong>{toast.title}</strong>
<span>{toast.body}</span>
</div>
)}
{!open ? (
<button type="button" className="chat-fab" onClick={() => setOpen(true)} title="Tin nhắn">
💬