1 import React, { useEffect, useMemo, useRef } from "react"
2 import clsx from "clsx"
3 import {
4 ArrowUpCircleSolid,
5 LightBulb,
6 LightBulbSolid,
7 StopCircleSolid,
8 } from "@medusajs/icons"
9 import { useAiAssistant } from "@/providers/AiAssistant"
10 import { useAnalytics } from "@/providers/Analytics"
11 import { useIsBrowser } from "@/providers/BrowserProvider"
12 import { useChat, useDeepThinking } from "@kapaai/react-sdk"
13 import { useAiAssistantChatNavigation } from "../../../../hooks/use-ai-assistant-chat-navigation"
14 import { Tooltip } from "../../../Tooltip"
15 import { DocsTrackingEvents } from "../../../../constants"
16
17 type AiAssistantChatWindowInputProps = {
18 chatWindowRef: React.RefObject<HTMLDivElement | null>
19 }
20
21 export const AiAssistantChatWindowInput = ({
22 chatWindowRef,
23 }: AiAssistantChatWindowInputProps) => {
24 const { chatOpened, inputRef, loading, setChatOpened, isCaptchaLoaded } =
25 useAiAssistant()
26 const { submitQuery, conversation, stopGeneration } = useChat()
27 const { track } = useAnalytics()
28 const { active, toggle } = useDeepThinking()
29 const { isBrowser } = useIsBrowser()
30 const { searchQuery, searchQueryType } = useMemo(() => {
31 if (!isBrowser) {
32 return {}
33 }
34 const searchParams = new URLSearchParams(location.search)
35
36 return {
37 searchQuery: searchParams.get("query"),
38 searchQueryType: searchParams.get("queryType"),
39 }
40 }, [isBrowser])
41 const [question, setQuestion] = React.useState("")
42 const formRef = useRef<HTMLFormElement | null>(null)
43
44 const onSubmit = (
45 e?: React.FormEvent<HTMLFormElement>,
46 overrideQuestion?: string
47 ) => {
48 e?.preventDefault()
49 if (loading) {
50 // stop the generation
51 stopGeneration()
52 return
53 }
54
55 submitQuery(overrideQuestion || question)
56 if (!conversation.length) {
57 track({
58 event: {
59 event: DocsTrackingEvents.AI_ASSISTANT_START_CHAT,
60 },
61 })
62 }
63 setQuestion("")
64 }
65
66 const handleKeyboardDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
67 if (e.key === "ArrowUp" && !question) {
68 const lastQuestion = conversation.getLatest()?.question
69 if (lastQuestion) {
70 setQuestion(lastQuestion)
71 }
72 return
73 }
74 if (e.key !== "Enter") {
75 return
76 }
77 if (e.shiftKey) {
78 const { selectionStart, selectionEnd } = e.currentTarget
79 setQuestion(
80 (prev) =>
81 `${prev.substring(0, selectionStart)}\n${prev.substring(selectionEnd)}`
82 )
83 setTimeout(() => {
84 if (inputRef.current) {
85 inputRef.current.selectionStart = inputRef.current.selectionEnd =
86 selectionStart + 1
87 }
88 }, 0)
89 } else {
90 onSubmit()
91 }
92 }
93
94 const adjustTextareaHeight = () => {
95 if (!inputRef.current) {
96 return
97 }
98 if (!question.length) {
99 inputRef.current.style.height = "auto"
100 return
101 }
102 inputRef.current.style.height = `${inputRef.current.scrollHeight}px`
103 }
104
105 useEffect(() => {
106 adjustTextareaHeight()
107 if (chatOpened) {
108 inputRef.current?.focus()
109 }
110 }, [question])
111
112 const handleTouch = (e: React.TouchEvent<HTMLTextAreaElement>) => {
113 e.preventDefault()
114 inputRef.current?.focus({
115 preventScroll: true,
116 })
117 }
118
119 useEffect(() => {
120 if (!chatOpened || !inputRef.current) {
121 return
122 }
123
124 const isCursorAtEnd =
125 inputRef.current.selectionStart === inputRef.current.value.length
126
127 if (isCursorAtEnd) {
128 inputRef.current.scrollTop = inputRef.current.scrollHeight
129 }
130 }, [chatOpened, inputRef.current])
131
132 useAiAssistantChatNavigation({
133 getChatWindowElm: () => chatWindowRef.current as HTMLElement | null,
134 getInputElm: () => inputRef.current as HTMLTextAreaElement | null,
135 focusInput: () =>
136 inputRef.current?.focus({
137 preventScroll: true,
138 }),
139 question,
140 })
141
142 useEffect(() => {
143 if (!searchQuery || !isCaptchaLoaded) {
144 return
145 }
146
147 setQuestion(searchQuery)
148 setChatOpened(true)
149 if (searchQueryType !== "submit") {
150 return
151 }
152 onSubmit(undefined, searchQuery)
153 }, [searchQuery, searchQueryType, isCaptchaLoaded])
154
155 return (
156 <div
157 className={clsx(
158 "px-docs_1 py-docs_0.75 border-t border-medusa-border-base"
159 )}
160 >
161 <form
162 className="flex flex-col gap-docs_0.5"
163 onSubmit={onSubmit}
164 ref={formRef}
165 >
166 <textarea
167 className={clsx(
168 "appearance-none text-base md:text-small placeholder:text-medusa-fg-muted",
169 "text-medusa-fg-base max-h-[210px] overflow-auto resize-none bg-transparent",
170 "focus:outline-none focus:ring-0 disabled:cursor-not-allowed max-h-[210px]",
171 "disabled:!bg-transparent disabled:text-medusa-fg-disabled disabled:placeholder:text-medusa-fg-disabled"
172 )}
173 value={question}
174 onChange={(e) => setQuestion(e.target.value)}
175 onKeyDown={handleKeyboardDown}
176 onTouchStart={handleTouch}
177 onTouchMove={handleTouch}
178 onTouchEnd={handleTouch}
179 ref={inputRef as React.RefObject<HTMLTextAreaElement | null>}
180 placeholder="Ask me a question about Medusa..."
181 disabled={loading}
182 />
183 <div className="flex items-center justify-end gap-docs_1">
184 <Tooltip
185 tooltipChildren={
186 <span>
187 Get better answers for complex questions.
188 <br />
189 Results may take up to 1 minute.
190 </span>
191 }
192 >
193 <button
194 onClick={toggle}
195 disabled={loading}
196 className={clsx(
197 "txt-compact-xsmall-plus appearance-none transition-colors flex items-center gap-docs_0.25 px-docs_0.5 py-docs_0.25 rounded-docs_sm",
198 !active &&
199 "bg-transparent hover:bg-medusa-button-transparent-hover text-medusa-fg-muted hover:text-medusa-fg-subtle",
200 active &&
201 "bg-medusa-tag-orange-bg hover:bg-medusa-tag-orange-bg-hover text-medusa-tag-orange-text",
202 loading && "cursor-not-allowed opacity-50"
203 )}
204 type="button"
205 >
206 {!active && <LightBulb />}
207 {active && (
208 <LightBulbSolid className="text-medusa-tag-orange-icon" />
209 )}
210 Deep Thinking
211 </button>
212 </Tooltip>
213 <button
214 className={clsx(
215 "appearance-none p-0 text-medusa-fg-base disabled:text-medusa-fg-disabled",
216 "transition-colors"
217 )}
218 disabled={!isCaptchaLoaded || (!question && !loading)}
219 type="submit"
220 >
221 {loading ? <StopCircleSolid /> : <ArrowUpCircleSolid />}
222 </button>
223 </div>
224 </form>
225 </div>
226 )
227 }