index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
  4. import { useContext } from 'use-context-selector'
  5. import cn from 'classnames'
  6. import Recorder from 'js-audio-recorder'
  7. import { useTranslation } from 'react-i18next'
  8. import s from './style.module.css'
  9. import type { DisplayScene, FeedbackFunc, IChatItem, SubmitAnnotationFunc } from './type'
  10. import { TryToAskIcon, stopIcon } from './icon-component'
  11. import Answer from './answer'
  12. import Question from './question'
  13. import Tooltip from '@/app/components/base/tooltip'
  14. import { ToastContext } from '@/app/components/base/toast'
  15. import AutoHeightTextarea from '@/app/components/base/auto-height-textarea'
  16. import Button from '@/app/components/base/button'
  17. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  18. import VoiceInput from '@/app/components/base/voice-input'
  19. import { Microphone01 } from '@/app/components/base/icons/src/vender/line/mediaAndDevices'
  20. import { Microphone01 as Microphone01Solid } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
  21. import { XCircle } from '@/app/components/base/icons/src/vender/solid/general'
  22. import type { DataSet } from '@/models/datasets'
  23. export type IChatProps = {
  24. configElem?: React.ReactNode
  25. chatList: IChatItem[]
  26. controlChatUpdateAllConversation?: number
  27. /**
  28. * Whether to display the editing area and rating status
  29. */
  30. feedbackDisabled?: boolean
  31. /**
  32. * Whether to display the input area
  33. */
  34. isHideFeedbackEdit?: boolean
  35. isHideSendInput?: boolean
  36. onFeedback?: FeedbackFunc
  37. onSubmitAnnotation?: SubmitAnnotationFunc
  38. checkCanSend?: () => boolean
  39. onSend?: (message: string) => void
  40. displayScene?: DisplayScene
  41. useCurrentUserAvatar?: boolean
  42. isResponsing?: boolean
  43. canStopResponsing?: boolean
  44. abortResponsing?: () => void
  45. controlClearQuery?: number
  46. controlFocus?: number
  47. isShowSuggestion?: boolean
  48. suggestionList?: string[]
  49. isShowSpeechToText?: boolean
  50. isShowCitation?: boolean
  51. answerIconClassName?: string
  52. isShowConfigElem?: boolean
  53. dataSets?: DataSet[]
  54. isShowCitationHitInfo?: boolean
  55. }
  56. const Chat: FC<IChatProps> = ({
  57. configElem,
  58. chatList,
  59. feedbackDisabled = false,
  60. isHideFeedbackEdit = false,
  61. isHideSendInput = false,
  62. onFeedback,
  63. onSubmitAnnotation,
  64. checkCanSend,
  65. onSend = () => { },
  66. displayScene,
  67. useCurrentUserAvatar,
  68. isResponsing,
  69. canStopResponsing,
  70. abortResponsing,
  71. controlClearQuery,
  72. controlFocus,
  73. isShowSuggestion,
  74. suggestionList,
  75. isShowSpeechToText,
  76. isShowCitation,
  77. answerIconClassName,
  78. isShowConfigElem,
  79. dataSets,
  80. isShowCitationHitInfo,
  81. }) => {
  82. const { t } = useTranslation()
  83. const { notify } = useContext(ToastContext)
  84. const isUseInputMethod = useRef(false)
  85. const [query, setQuery] = React.useState('')
  86. const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
  87. const value = e.target.value
  88. setQuery(value)
  89. }
  90. const logError = (message: string) => {
  91. notify({ type: 'error', message, duration: 3000 })
  92. }
  93. const valid = () => {
  94. if (!query || query.trim() === '') {
  95. logError('Message cannot be empty')
  96. return false
  97. }
  98. return true
  99. }
  100. useEffect(() => {
  101. if (controlClearQuery)
  102. setQuery('')
  103. }, [controlClearQuery])
  104. const handleSend = () => {
  105. if (!valid() || (checkCanSend && !checkCanSend()))
  106. return
  107. onSend(query)
  108. if (!isResponsing)
  109. setQuery('')
  110. }
  111. const handleKeyUp = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  112. if (e.code === 'Enter') {
  113. e.preventDefault()
  114. // prevent send message when using input method enter
  115. if (!e.shiftKey && !isUseInputMethod.current)
  116. handleSend()
  117. }
  118. }
  119. const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  120. isUseInputMethod.current = e.nativeEvent.isComposing
  121. if (e.code === 'Enter' && !e.shiftKey) {
  122. setQuery(query.replace(/\n$/, ''))
  123. e.preventDefault()
  124. }
  125. }
  126. const media = useBreakpoints()
  127. const isMobile = media === MediaType.mobile
  128. const sendBtn = <div className={cn(!(!query || query.trim() === '') && s.sendBtnActive, `${s.sendBtn} w-8 h-8 cursor-pointer rounded-md`)} onClick={handleSend}></div>
  129. const suggestionListRef = useRef<HTMLDivElement>(null)
  130. const [hasScrollbar, setHasScrollbar] = useState(false)
  131. useLayoutEffect(() => {
  132. if (suggestionListRef.current) {
  133. const listDom = suggestionListRef.current
  134. const hasScrollbar = listDom.scrollWidth > listDom.clientWidth
  135. setHasScrollbar(hasScrollbar)
  136. }
  137. }, [suggestionList])
  138. const [voiceInputShow, setVoiceInputShow] = useState(false)
  139. const handleVoiceInputShow = () => {
  140. (Recorder as any).getPermission().then(() => {
  141. setVoiceInputShow(true)
  142. }, () => {
  143. logError(t('common.voiceInput.notAllow'))
  144. })
  145. }
  146. return (
  147. <div className={cn('px-3.5', 'h-full')}>
  148. {isShowConfigElem && (configElem || null)}
  149. {/* Chat List */}
  150. <div className={cn((isShowConfigElem && configElem) ? 'h-0' : 'h-full', 'space-y-[30px]')}>
  151. {chatList.map((item) => {
  152. if (item.isAnswer) {
  153. const isLast = item.id === chatList[chatList.length - 1].id
  154. const thoughts = item.agent_thoughts?.filter(item => item.thought !== '[DONE]')
  155. const citation = item.citation
  156. const isThinking = !item.content && item.agent_thoughts && item.agent_thoughts?.length > 0 && !item.agent_thoughts.some(item => item.thought === '[DONE]')
  157. return <Answer
  158. key={item.id}
  159. item={item}
  160. feedbackDisabled={feedbackDisabled}
  161. isHideFeedbackEdit={isHideFeedbackEdit}
  162. onFeedback={onFeedback}
  163. onSubmitAnnotation={onSubmitAnnotation}
  164. displayScene={displayScene ?? 'web'}
  165. isResponsing={isResponsing && isLast}
  166. answerIconClassName={answerIconClassName}
  167. thoughts={thoughts}
  168. citation={citation}
  169. isThinking={isThinking}
  170. dataSets={dataSets}
  171. isShowCitation={isShowCitation}
  172. isShowCitationHitInfo={isShowCitationHitInfo}
  173. />
  174. }
  175. return <Question key={item.id} id={item.id} content={item.content} more={item.more} useCurrentUserAvatar={useCurrentUserAvatar} />
  176. })}
  177. </div>
  178. {
  179. !isHideSendInput && (
  180. <div className={cn(!feedbackDisabled && '!left-3.5 !right-3.5', 'absolute z-10 bottom-0 left-0 right-0')}>
  181. {/* Thinking is sync and can not be stopped */}
  182. {(isResponsing && canStopResponsing && !!chatList[chatList.length - 1]?.content) && (
  183. <div className='flex justify-center mb-4'>
  184. <Button className='flex items-center space-x-1 bg-white' onClick={() => abortResponsing?.()}>
  185. {stopIcon}
  186. <span className='text-xs text-gray-500 font-normal'>{t('appDebug.operation.stopResponding')}</span>
  187. </Button>
  188. </div>
  189. )}
  190. {
  191. isShowSuggestion && (
  192. <div className='pt-2'>
  193. <div className='flex items-center justify-center mb-2.5'>
  194. <div className='grow h-[1px]'
  195. style={{
  196. background: 'linear-gradient(270deg, #F3F4F6 0%, rgba(243, 244, 246, 0) 100%)',
  197. }}></div>
  198. <div className='shrink-0 flex items-center px-3 space-x-1'>
  199. {TryToAskIcon}
  200. <span className='text-xs text-gray-500 font-medium'>{t('appDebug.feature.suggestedQuestionsAfterAnswer.tryToAsk')}</span>
  201. </div>
  202. <div className='grow h-[1px]'
  203. style={{
  204. background: 'linear-gradient(270deg, rgba(243, 244, 246, 0) 0%, #F3F4F6 100%)',
  205. }}></div>
  206. </div>
  207. {/* has scrollbar would hide part of first item */}
  208. <div ref={suggestionListRef} className={cn(!hasScrollbar && 'justify-center', 'flex overflow-x-auto pb-2')}>
  209. {suggestionList?.map((item, index) => (
  210. <div key={item} className='shrink-0 flex justify-center mr-2'>
  211. <Button
  212. key={index}
  213. onClick={() => setQuery(item)}
  214. >
  215. <span className='text-primary-600 text-xs font-medium'>{item}</span>
  216. </Button>
  217. </div>
  218. ))}
  219. </div>
  220. </div>)
  221. }
  222. <div className="relative">
  223. <AutoHeightTextarea
  224. value={query}
  225. onChange={handleContentChange}
  226. onKeyUp={handleKeyUp}
  227. onKeyDown={handleKeyDown}
  228. minHeight={48}
  229. autoFocus
  230. controlFocus={controlFocus}
  231. className={`${cn(s.textArea)} resize-none block w-full pl-3 bg-gray-50 border border-gray-200 rounded-md focus:outline-none sm:text-sm text-gray-700`}
  232. />
  233. <div className="absolute top-0 right-2 flex items-center h-[48px]">
  234. <div className={`${s.count} mr-4 h-5 leading-5 text-sm bg-gray-50 text-gray-500`}>{query.trim().length}</div>
  235. {
  236. query
  237. ? (
  238. <div className='flex justify-center items-center w-8 h-8 cursor-pointer hover:bg-gray-100 rounded-lg' onClick={() => setQuery('')}>
  239. <XCircle className='w-4 h-4 text-[#98A2B3]' />
  240. </div>
  241. )
  242. : isShowSpeechToText
  243. ? (
  244. <div
  245. className='group flex justify-center items-center w-8 h-8 hover:bg-primary-50 rounded-lg cursor-pointer'
  246. onClick={handleVoiceInputShow}
  247. >
  248. <Microphone01 className='block w-4 h-4 text-gray-500 group-hover:hidden' />
  249. <Microphone01Solid className='hidden w-4 h-4 text-primary-600 group-hover:block' />
  250. </div>
  251. )
  252. : null
  253. }
  254. <div className='mx-2 w-[1px] h-4 bg-black opacity-5' />
  255. {isMobile
  256. ? sendBtn
  257. : (
  258. <Tooltip
  259. selector='send-tip'
  260. htmlContent={
  261. <div>
  262. <div>{t('common.operation.send')} Enter</div>
  263. <div>{t('common.operation.lineBreak')} Shift Enter</div>
  264. </div>
  265. }
  266. >
  267. {sendBtn}
  268. </Tooltip>
  269. )}
  270. </div>
  271. {
  272. voiceInputShow && (
  273. <VoiceInput
  274. onCancel={() => setVoiceInputShow(false)}
  275. onConverted={text => setQuery(text)}
  276. />
  277. )
  278. }
  279. </div>
  280. </div>
  281. )
  282. }
  283. </div>
  284. )
  285. }
  286. export default React.memo(Chat)