feat(chat-window): add ability to use `q` query param

This commit is contained in:
ItzCrazyKns 2024-05-11 12:09:39 +05:30
parent 7a28be9e1a
commit 3ef39c69a7
No known key found for this signature in database
GPG Key ID: 8162927C7CCE3065
2 changed files with 27 additions and 6 deletions

View File

@ -6,6 +6,7 @@ import Navbar from './Navbar';
import Chat from './Chat';
import EmptyChat from './EmptyChat';
import { toast } from 'sonner';
import { useSearchParams } from 'next/navigation';
export type Message = {
id: string;
@ -15,7 +16,7 @@ export type Message = {
sources?: Document[];
};
const useSocket = (url: string) => {
const useSocket = (url: string, setIsReady: (ready: boolean) => void) => {
const [ws, setWs] = useState<WebSocket | null>(null);
useEffect(() => {
@ -101,9 +102,17 @@ const useSocket = (url: string) => {
ws.onopen = () => {
console.log('[DEBUG] open');
setWs(ws);
};
const stateCheckInterval = setInterval(() => {
if (ws.readyState === 1) {
setIsReady(true);
clearInterval(stateCheckInterval);
}
}, 100);
setWs(ws);
ws.onmessage = (e) => {
const parsedData = JSON.parse(e.data);
if (parsedData.type === 'error') {
@ -122,13 +131,18 @@ const useSocket = (url: string) => {
ws?.close();
console.log('[DEBUG] closed');
};
}, [ws, url]);
}, [ws, url, setIsReady]);
return ws;
};
const ChatWindow = () => {
const ws = useSocket(process.env.NEXT_PUBLIC_WS_URL!);
const searchParams = useSearchParams();
const initialMessage = searchParams.get('q');
const [isReady, setIsReady] = useState(false);
const ws = useSocket(process.env.NEXT_PUBLIC_WS_URL!, setIsReady);
const [chatHistory, setChatHistory] = useState<[string, string][]>([]);
const [messages, setMessages] = useState<Message[]>([]);
const [loading, setLoading] = useState(false);
@ -250,7 +264,14 @@ const ChatWindow = () => {
sendMessage(message.content);
};
return ws ? (
useEffect(() => {
if (isReady && initialMessage) {
sendMessage(initialMessage);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isReady, initialMessage]);
return isReady ? (
<div>
{messages.length > 0 ? (
<>

View File

@ -1,7 +1,7 @@
import { ArrowRight } from 'lucide-react';
import { useState } from 'react';
import TextareaAutosize from 'react-textarea-autosize';
import { Attach, CopilotToggle, Focus } from './MessageInputActions';
import { CopilotToggle, Focus } from './MessageInputActions';
const EmptyChatMessageInput = ({
sendMessage,