veza/apps/web/src/features/chat/pages/ChatPage.tsx

80 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-12-13 02:34:34 +00:00
import React, { useEffect } from 'react';
import { ChatSidebar } from '../components/ChatSidebar';
import { ChatRoom } from '../components/ChatRoom';
import { ChatInput } from '../components/ChatInput';
import { useChatStore } from '../store/chatStore';
import { useAuthStore } from '@/stores/auth';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/services/api/client';
import { useChat } from '../hooks/useChat';
import { Loader2 } from 'lucide-react';
// This page needs to fetch the WS token first
export const ChatPage: React.FC = () => {
2025-12-13 02:34:34 +00:00
const { user, isAuthenticated } = useAuthStore();
const userId = user?.id; // Derived
const { setWsToken, currentConversationId, wsStatus } = useChatStore();
2025-12-13 02:34:34 +00:00
const { connect } = useChat();
// Fetch WS Token
2025-12-13 02:34:34 +00:00
const {
data: wsTokenResponse,
isLoading: isTokenLoading,
error: tokenError,
} = useQuery({
queryKey: ['chatWsToken', userId],
queryFn: async () => {
if (!isAuthenticated || !userId) return null;
const response = await apiClient.post('/chat/token', {});
return response.data;
},
enabled: isAuthenticated && !!userId && wsStatus === 'disconnected', // Only fetch if authenticated and not connected
refetchOnWindowFocus: false,
retry: false,
});
2025-12-13 02:34:34 +00:00
useEffect(() => {
if (wsTokenResponse?.token && wsTokenResponse?.ws_url) {
setWsToken(wsTokenResponse.token, wsTokenResponse.ws_url);
connect(); // Attempt to connect once token is received
}
}, [wsTokenResponse, setWsToken, connect]);
if (!isAuthenticated) {
return (
<div className="flex flex-col items-center justify-center h-full text-gray-500">
Vous devez être connecté pour utiliser le chat.
</div>
);
}
if (isTokenLoading || wsStatus === 'connecting') {
return (
<div className="flex flex-col items-center justify-center h-full">
<Loader2 className="animate-spin text-blue-500" size={32} />
<p className="mt-4 text-gray-600">Chargement du chat...</p>
</div>
);
}
if (tokenError) {
return (
<div className="flex flex-col items-center justify-center h-full text-red-500">
2025-12-13 02:34:34 +00:00
Erreur:{' '}
{(tokenError as any).message ||
'Impossible de récupérer le token du chat'}
</div>
);
}
return (
<div className="flex h-full max-h-screen bg-gray-50">
<ChatSidebar />
<div className="flex-1 flex flex-col">
<ChatRoom conversationId={currentConversationId || ''} />
<ChatInput />
</div>
</div>
);
2025-12-13 02:34:34 +00:00
};