chat-input.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import type { FC } from 'react'
  2. import {
  3. memo,
  4. useRef,
  5. useState,
  6. } from 'react'
  7. import { useContext } from 'use-context-selector'
  8. import Recorder from 'js-audio-recorder'
  9. import { useTranslation } from 'react-i18next'
  10. import Textarea from 'rc-textarea'
  11. import type {
  12. EnableType,
  13. OnSend,
  14. VisionConfig,
  15. } from '../types'
  16. import { TransferMethod } from '../types'
  17. import { useChatWithHistoryContext } from '../chat-with-history/context'
  18. import type { Theme } from '../embedded-chatbot/theme/theme-context'
  19. import { CssTransform } from '../embedded-chatbot/theme/utils'
  20. import TooltipPlus from '@/app/components/base/tooltip-plus'
  21. import { ToastContext } from '@/app/components/base/toast'
  22. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  23. import VoiceInput from '@/app/components/base/voice-input'
  24. import { Microphone01 } from '@/app/components/base/icons/src/vender/line/mediaAndDevices'
  25. import { Microphone01 as Microphone01Solid } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
  26. import { XCircle } from '@/app/components/base/icons/src/vender/solid/general'
  27. import { Send03 } from '@/app/components/base/icons/src/vender/solid/communication'
  28. import ChatImageUploader from '@/app/components/base/image-uploader/chat-image-uploader'
  29. import ImageList from '@/app/components/base/image-uploader/image-list'
  30. import {
  31. useClipboardUploader,
  32. useDraggableUploader,
  33. useImageFiles,
  34. } from '@/app/components/base/image-uploader/hooks'
  35. type ChatInputProps = {
  36. visionConfig?: VisionConfig
  37. speechToTextConfig?: EnableType
  38. onSend?: OnSend
  39. theme?: Theme | null
  40. }
  41. const ChatInput: FC<ChatInputProps> = ({
  42. visionConfig,
  43. speechToTextConfig,
  44. onSend,
  45. theme,
  46. }) => {
  47. const { appData } = useChatWithHistoryContext()
  48. const { t } = useTranslation()
  49. const { notify } = useContext(ToastContext)
  50. const [voiceInputShow, setVoiceInputShow] = useState(false)
  51. const textAreaRef = useRef<HTMLTextAreaElement>(null)
  52. const {
  53. files,
  54. onUpload,
  55. onRemove,
  56. onReUpload,
  57. onImageLinkLoadError,
  58. onImageLinkLoadSuccess,
  59. onClear,
  60. } = useImageFiles()
  61. const { onPaste } = useClipboardUploader({ onUpload, visionConfig, files })
  62. const { onDragEnter, onDragLeave, onDragOver, onDrop, isDragActive } = useDraggableUploader<HTMLTextAreaElement>({ onUpload, files, visionConfig })
  63. const isUseInputMethod = useRef(false)
  64. const [query, setQuery] = useState('')
  65. const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
  66. const value = e.target.value
  67. setQuery(value)
  68. }
  69. const handleSend = () => {
  70. if (onSend) {
  71. if (files.find(item => item.type === TransferMethod.local_file && !item.fileId)) {
  72. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  73. return
  74. }
  75. if (!query || !query.trim()) {
  76. notify({ type: 'info', message: t('appAnnotation.errorMessage.queryRequired') })
  77. return
  78. }
  79. onSend(query, files.filter(file => file.progress !== -1).map(fileItem => ({
  80. type: 'image',
  81. transfer_method: fileItem.type,
  82. url: fileItem.url,
  83. upload_file_id: fileItem.fileId,
  84. })))
  85. setQuery('')
  86. onClear()
  87. }
  88. }
  89. const handleKeyUp = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  90. if (e.key === 'Enter') {
  91. e.preventDefault()
  92. // prevent send message when using input method enter
  93. if (!e.shiftKey && !isUseInputMethod.current)
  94. handleSend()
  95. }
  96. }
  97. const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  98. isUseInputMethod.current = e.nativeEvent.isComposing
  99. if (e.key === 'Enter' && !e.shiftKey) {
  100. setQuery(query.replace(/\n$/, ''))
  101. e.preventDefault()
  102. }
  103. }
  104. const logError = (message: string) => {
  105. notify({ type: 'error', message })
  106. }
  107. const handleVoiceInputShow = () => {
  108. (Recorder as any).getPermission().then(() => {
  109. setVoiceInputShow(true)
  110. }, () => {
  111. logError(t('common.voiceInput.notAllow'))
  112. })
  113. }
  114. const [isActiveIconFocused, setActiveIconFocused] = useState(false)
  115. const media = useBreakpoints()
  116. const isMobile = media === MediaType.mobile
  117. const sendIconThemeStyle = theme
  118. ? {
  119. color: (isActiveIconFocused || query || (query.trim() !== '')) ? theme.primaryColor : '#d1d5db',
  120. }
  121. : {}
  122. const sendBtn = (
  123. <div
  124. className='group flex items-center justify-center w-8 h-8 rounded-lg hover:bg-[#EBF5FF] cursor-pointer'
  125. onMouseEnter={() => setActiveIconFocused(true)}
  126. onMouseLeave={() => setActiveIconFocused(false)}
  127. onClick={handleSend}
  128. style={isActiveIconFocused ? CssTransform(theme?.chatBubbleColorStyle ?? '') : {}}
  129. >
  130. <Send03
  131. style={sendIconThemeStyle}
  132. className={`
  133. w-5 h-5 text-gray-300 group-hover:text-primary-600
  134. ${!!query.trim() && 'text-primary-600'}
  135. `}
  136. />
  137. </div>
  138. )
  139. return (
  140. <>
  141. <div className='relative'>
  142. <div
  143. className={`
  144. p-[5.5px] max-h-[150px] bg-white border-[1.5px] border-gray-200 rounded-xl overflow-y-auto
  145. ${isDragActive && 'border-primary-600'} mb-2
  146. `}
  147. >
  148. {
  149. visionConfig?.enabled && (
  150. <>
  151. <div className='absolute bottom-2 left-2 flex items-center'>
  152. <ChatImageUploader
  153. settings={visionConfig}
  154. onUpload={onUpload}
  155. disabled={files.length >= visionConfig.number_limits}
  156. />
  157. <div className='mx-1 w-[1px] h-4 bg-black/5' />
  158. </div>
  159. <div className='pl-[52px]'>
  160. <ImageList
  161. list={files}
  162. onRemove={onRemove}
  163. onReUpload={onReUpload}
  164. onImageLinkLoadSuccess={onImageLinkLoadSuccess}
  165. onImageLinkLoadError={onImageLinkLoadError}
  166. />
  167. </div>
  168. </>
  169. )
  170. }
  171. <Textarea
  172. ref={textAreaRef}
  173. className={`
  174. block w-full px-2 pr-[118px] py-[7px] leading-5 max-h-none text-sm text-gray-700 outline-none appearance-none resize-none
  175. ${visionConfig?.enabled && 'pl-12'}
  176. `}
  177. value={query}
  178. onChange={handleContentChange}
  179. onKeyUp={handleKeyUp}
  180. onKeyDown={handleKeyDown}
  181. onPaste={onPaste}
  182. onDragEnter={onDragEnter}
  183. onDragLeave={onDragLeave}
  184. onDragOver={onDragOver}
  185. onDrop={onDrop}
  186. autoSize
  187. />
  188. <div className='absolute bottom-[7px] right-2 flex items-center h-8'>
  189. <div className='flex items-center px-1 h-5 rounded-md bg-gray-100 text-xs font-medium text-gray-500'>
  190. {query.trim().length}
  191. </div>
  192. {
  193. query
  194. ? (
  195. <div className='flex justify-center items-center ml-2 w-8 h-8 cursor-pointer hover:bg-gray-100 rounded-lg' onClick={() => setQuery('')}>
  196. <XCircle className='w-4 h-4 text-[#98A2B3]' />
  197. </div>
  198. )
  199. : speechToTextConfig?.enabled
  200. ? (
  201. <div
  202. className='group flex justify-center items-center ml-2 w-8 h-8 hover:bg-primary-50 rounded-lg cursor-pointer'
  203. onClick={handleVoiceInputShow}
  204. >
  205. <Microphone01 className='block w-4 h-4 text-gray-500 group-hover:hidden' />
  206. <Microphone01Solid className='hidden w-4 h-4 text-primary-600 group-hover:block' />
  207. </div>
  208. )
  209. : null
  210. }
  211. <div className='mx-2 w-[1px] h-4 bg-black opacity-5' />
  212. {isMobile
  213. ? sendBtn
  214. : (
  215. <TooltipPlus
  216. popupContent={
  217. <div>
  218. <div>{t('common.operation.send')} Enter</div>
  219. <div>{t('common.operation.lineBreak')} Shift Enter</div>
  220. </div>
  221. }
  222. >
  223. {sendBtn}
  224. </TooltipPlus>
  225. )}
  226. </div>
  227. {
  228. voiceInputShow && (
  229. <VoiceInput
  230. onCancel={() => setVoiceInputShow(false)}
  231. onConverted={(text) => {
  232. setQuery(text)
  233. textAreaRef.current?.focus()
  234. }}
  235. />
  236. )
  237. }
  238. </div>
  239. </div>
  240. {appData?.site?.custom_disclaimer && <div className='text-xs text-gray-500 mt-1 text-center'>
  241. {appData.site.custom_disclaimer}
  242. </div>}
  243. </>
  244. )
  245. }
  246. export default memo(ChatInput)