index.tsx 11 KB

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