From 3cda949fa215d9ba852d0ca15fb80552e6b0bc57 Mon Sep 17 00:00:00 2001 From: Jagger <634750802@qq.com> Date: Wed, 22 Jan 2025 09:41:05 +0800 Subject: [PATCH] feat(frontend): support js new chat api in widget (#601) --- frontend/app/src/components/chat/chat-hooks.tsx | 6 ++++-- frontend/packages/widget-react/src/Widget.tsx | 15 +++++++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/frontend/app/src/components/chat/chat-hooks.tsx b/frontend/app/src/components/chat/chat-hooks.tsx index e4f126c6..fb1fd433 100644 --- a/frontend/app/src/components/chat/chat-hooks.tsx +++ b/frontend/app/src/components/chat/chat-hooks.tsx @@ -6,7 +6,7 @@ import type { AppChatStreamState, StackVMState } from '@/components/chat/chat-st import { useGtagFn } from '@/components/gtag-provider'; import { useBootstrapStatus } from '@/components/system/BootstrapStatusProvider'; import { useLatestRef } from '@/components/use-latest-ref'; -import { createContext, type ReactNode, useContext, useEffect, useState } from 'react'; +import { createContext, type ReactNode, type Ref, useContext, useEffect, useImperativeHandle, useState } from 'react'; export interface ChatsProviderValues { chats: Map; @@ -30,7 +30,7 @@ const ChatsContext = createContext({ const ChatControllerContext = createContext(null); -export function ChatsProvider ({ onChatCreated, children }: { children: ReactNode, onChatCreated?: (id: string, chat: Chat, controller: ChatController) => void }) { +export function ChatsProvider ({ newChatRef, onChatCreated, children }: { children: ReactNode,newChatRef?: Ref, onChatCreated?: (id: string, chat: Chat, controller: ChatController) => void }) { const bootstrapStatusRef = useLatestRef(useBootstrapStatus()); const [chats, setChats] = useState(() => new Map); @@ -56,6 +56,8 @@ export function ChatsProvider ({ onChatCreated, children }: { children: ReactNod }); }; + useImperativeHandle(newChatRef, () => newChat); + return ( (({ container, trig } }, [trigger]); + const newChatRef = useRef(undefined); + useImperativeHandle(ref, () => ({ get open () { return openRef.current; @@ -125,6 +127,12 @@ export const Widget = forwardRef(({ container, trig setDark(d); }, get initialized (): true { return true; }, + newChat (content: string) { + newChatRef.current?.(undefined, [], { + content, + chat_engine: chatEngine, + }); + }, }), []); return ( @@ -132,6 +140,7 @@ export const Widget = forwardRef(({ container, trig { window.dispatchEvent(new CustomEvent('tidbainewchat', { detail: { id }, @@ -171,9 +180,7 @@ export const Widget = forwardRef(({ container, trig Ask AI - - . - +