From 3ef39c69a76eb67278aba6af2132e69da461cbe7 Mon Sep 17 00:00:00 2001 From: ItzCrazyKns Date: Sat, 11 May 2024 12:09:39 +0530 Subject: [PATCH] feat(chat-window): add ability to use `q` query param --- ui/components/ChatWindow.tsx | 31 +++++++++++++++++++++---- ui/components/EmptyChatMessageInput.tsx | 2 +- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/ui/components/ChatWindow.tsx b/ui/components/ChatWindow.tsx index 6f58757..1cc6ae0 100644 --- a/ui/components/ChatWindow.tsx +++ b/ui/components/ChatWindow.tsx @@ -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(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([]); 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 ? (
{messages.length > 0 ? ( <> diff --git a/ui/components/EmptyChatMessageInput.tsx b/ui/components/EmptyChatMessageInput.tsx index 2e3ab53..4932803 100644 --- a/ui/components/EmptyChatMessageInput.tsx +++ b/ui/components/EmptyChatMessageInput.tsx @@ -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,