Raw
1 "use client"
2
3 import { KapaProvider, useChat, useDeepThinking } from "@kapaai/react-sdk"
4 import React, {
5 createContext,
6 useCallback,
7 useContext,
8 useEffect,
9 useMemo,
10 useRef,
11 useState,
12 } from "react"
13 import type { Source } from "@kapaai/react-sdk"
14 import useResizeObserver from "@react-hook/resize-observer"
15 import { AiAssistantSearchWindow } from "../../components/AiAssistant/SearchWindow"
16 import { useIsBrowser } from "../BrowserProvider"
17
18 export type AiAssistantChatType = "default" | "popover"
19
20 export type AiAssistantSuggestionType = {
21 title: string
22 items: string[]
23 }
24
25 const defaultSuggestions: AiAssistantSuggestionType[] = [
26 {
27 title: "FAQ",
28 items: [
29 "What is Medusa?",
30 "How can I create a module?",
31 "How can I create a data model?",
32 "How do I create a workflow?",
33 "How can I extend a data model in the Product Module?",
34 ],
35 },
36 {
37 title: "Recipes",
38 items: [
39 "How do I build a marketplace with Medusa?",
40 "How do I build digital products with Medusa?",
41 "How do I build subscription-based purchases with Medusa?",
42 "What other recipes are available in the Medusa documentation?",
43 ],
44 },
45 ]
46
47 export type AiAssistantContextType = {
48 chatOpened: boolean
49 setChatOpened: React.Dispatch<React.SetStateAction<boolean>>
50 chatType: AiAssistantChatType
51 inputRef: React.RefObject<HTMLInputElement | HTMLTextAreaElement | null>
52 contentRef: React.RefObject<HTMLDivElement | null>
53 loading: boolean
54 isCaptchaLoaded: boolean
55 submitQuery: (q: string) => void
56 deepThinkingEnabled: boolean
57 toggleDeepThinking: () => void
58 suggestions: AiAssistantSuggestionType[]
59 hideAiToolsMessage?: boolean
60 }
61
62 export type AiAssistantThreadItem = {
63 type: "question" | "answer" | "error"
64 content: string
65 question_id?: string | null
66 sources?: Source[]
67 isGenerationAborted?: boolean
68 }
69
70 const AiAssistantContext = createContext<AiAssistantContextType | null>(null)
71
72 export type AiAssistantProviderProps = {
73 children?: React.ReactNode
74 integrationId: string
75 groupIds?: string[]
76 chatType?: AiAssistantChatType
77 type?: "search" | "chat"
78 suggestions?: AiAssistantSuggestionType[]
79 hideAiToolsMessage?: boolean
80 }
81
82 type AiAssistantInnerProviderProps = Omit<
83 AiAssistantProviderProps,
84 "integrationId"
85 > & {
86 preventAutoScroll: boolean
87 setPreventAutoScroll: React.Dispatch<React.SetStateAction<boolean>>
88 setOnCompleteAction: React.Dispatch<React.SetStateAction<() => void>>
89 }
90
91 const AiAssistantInnerProvider = ({
92 children,
93 chatType = "default",
94 preventAutoScroll,
95 setPreventAutoScroll,
96 setOnCompleteAction,
97 type,
98 suggestions = defaultSuggestions,
99 hideAiToolsMessage = false,
100 }: AiAssistantInnerProviderProps) => {
101 const [isCaptchaLoaded, setIsCaptchaLoaded] = useState(false)
102 const [chatOpened, setChatOpened] = useState(false)
103 const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>(null)
104 const contentRef = useRef<HTMLDivElement>(null)
105 const { isGeneratingAnswer, isPreparingAnswer, submitQuery } = useChat()
106 const { active: deepThinkingEnabled, toggle: toggleDeepThinking } =
107 useDeepThinking()
108 const loading = useMemo(
109 () => isGeneratingAnswer || isPreparingAnswer,
110 [isGeneratingAnswer, isPreparingAnswer]
111 )
112 const { isBrowser } = useIsBrowser()
113
114 const scrollToBottom = () => {
115 if (preventAutoScroll) {
116 return
117 }
118 const parent = contentRef.current?.parentElement as HTMLElement
119
120 if (!parent) {
121 return
122 }
123
124 parent.scrollTop = parent.scrollHeight
125 }
126
127 useResizeObserver(contentRef as React.RefObject<HTMLDivElement>, () => {
128 if (!loading) {
129 return
130 }
131
132 scrollToBottom()
133 })
134
135 const handleUserScroll = useCallback(() => {
136 if (!loading || preventAutoScroll) {
137 return
138 }
139
140 setPreventAutoScroll(true)
141 }, [loading, preventAutoScroll])
142
143 useEffect(() => {
144 if (!contentRef.current?.parentElement) {
145 return
146 }
147
148 contentRef.current.parentElement.addEventListener(
149 "wheel",
150 handleUserScroll,
151 {
152 passive: true,
153 }
154 )
155 contentRef.current.parentElement.addEventListener(
156 "touchmove",
157 handleUserScroll,
158 {
159 passive: true,
160 }
161 )
162
163 return () => {
164 contentRef.current?.parentElement?.removeEventListener(
165 "wheel",
166 handleUserScroll
167 )
168 contentRef.current?.parentElement?.removeEventListener(
169 "touchmove",
170 handleUserScroll
171 )
172 }
173 }, [contentRef.current, handleUserScroll])
174
175 useEffect(() => {
176 setOnCompleteAction(() => {
177 scrollToBottom()
178 if (chatOpened) {
179 inputRef.current?.focus({
180 preventScroll: true,
181 })
182 }
183 })
184 }, [scrollToBottom])
185
186 /**
187 * This effect is required to avoid recaptcha messing up
188 * the page layout.
189 */
190 useEffect(() => {
191 if (!isBrowser) {
192 return
193 }
194
195 const recaptchaElm = document.querySelector(".grecaptcha-badge")
196 recaptchaElm?.parentElement?.classList.add("absolute")
197 const maxRetry = 10
198 let retries = 0
199 const interval = setInterval(() => {
200 if (window.grecaptcha) {
201 setIsCaptchaLoaded(true)
202 clearInterval(interval)
203 return
204 }
205 retries++
206 if (retries > maxRetry) {
207 clearInterval(interval)
208 }
209 }, 1000)
210
211 return () => {
212 clearInterval(interval)
213 }
214 }, [isBrowser])
215
216 return (
217 <AiAssistantContext.Provider
218 value={{
219 chatOpened,
220 setChatOpened,
221 chatType,
222 inputRef,
223 contentRef,
224 loading,
225 isCaptchaLoaded,
226 submitQuery,
227 deepThinkingEnabled,
228 toggleDeepThinking,
229 suggestions,
230 hideAiToolsMessage,
231 }}
232 >
233 {children}
234 {type === "search" && <AiAssistantSearchWindow />}
235 </AiAssistantContext.Provider>
236 )
237 }
238
239 export const AiAssistantProvider = ({
240 integrationId,
241 groupIds,
242 ...props
243 }: AiAssistantProviderProps) => {
244 const [preventAutoScroll, setPreventAutoScroll] = useState(false)
245 const [onCompleteAction, setOnCompleteAction] = useState<() => void>(
246 () => () => {}
247 )
248
249 return (
250 <KapaProvider
251 integrationId={integrationId}
252 sourceGroupIDsInclude={groupIds}
253 callbacks={{
254 askAI: {
255 onAnswerGenerationCompleted: () => {
256 onCompleteAction?.()
257 },
258 onQuerySubmit: () => setPreventAutoScroll(false),
259 },
260 }}
261 userTrackingMode="cookie"
262 >
263 <AiAssistantInnerProvider
264 {...props}
265 preventAutoScroll={preventAutoScroll}
266 setPreventAutoScroll={setPreventAutoScroll}
267 setOnCompleteAction={setOnCompleteAction}
268 />
269 </KapaProvider>
270 )
271 }
272
273 export const useAiAssistant = () => {
274 const context = useContext(AiAssistantContext)
275
276 if (!context) {
277 throw new Error("useAiAssistant must be used within a AiAssistantProvider")
278 }
279
280 return context
281 }